diff --git a/.config/cargo_spellcheck.dic b/.config/cargo_spellcheck.dic index b232f7a22c4..bae78ab2200 100644 --- a/.config/cargo_spellcheck.dic +++ b/.config/cargo_spellcheck.dic @@ -15,6 +15,7 @@ KECCAK L1 L2 Polkadot +PolkaVM PSP22 RPC SHA @@ -42,6 +43,7 @@ defragmentation delegatee delegator deploy +deployer dereferencing deserialize/S deserialization @@ -77,6 +79,7 @@ tuple type_info unordered untyped +upgradeable v1 v2 v3 diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 018a56649b1..8b4d287c09d 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -3,7 +3,7 @@ updates: - package-ecosystem: "cargo" directory: "/" schedule: - interval: "daily" + interval: "weekly" # ignore Substrate pallets major updates. # automated Substrate releases cause dependabot PR spam, so these must be updated manually when required. ignore: diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index db4afe40717..1cf085b7a98 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,14 +1,13 @@ ## Summary Closes #_ - [ ] y/n | Does it introduce breaking changes? -- [ ] y/n | Is it dependent on the specific version of `cargo-contract` or `pallet-contracts`? +- [ ] y/n | Is it dependent on a specific version of `cargo-contract` or `pallet-revive`? ## Description ## Checklist before requesting a review -- [ ] My code follows the style guidelines of this project - [ ] I have added an entry to `CHANGELOG.md` - [ ] I have commented on my code, particularly in hard-to-understand areas - [ ] I have added tests that prove my fix is effective or that my feature works diff --git a/.github/riscv64emac-unknown-none-polkavm.json b/.github/riscv64emac-unknown-none-polkavm.json new file mode 100644 index 00000000000..7e9c482ca08 --- /dev/null +++ b/.github/riscv64emac-unknown-none-polkavm.json @@ -0,0 +1,26 @@ +{ + "arch": "riscv64", + "cpu": "generic-rv64", + "crt-objects-fallback": "false", + "data-layout": "e-m:e-p:64:64-i64:64-i128:128-n32:64-S64", + "eh-frame-header": false, + "emit-debug-gdb-scripts": false, + "features": "+e,+m,+a,+c,+auipc-addi-fusion,+ld-add-fusion,+lui-addi-fusion,+xtheadcondmov", + "linker": "rust-lld", + "linker-flavor": "ld.lld", + "llvm-abiname": "lp64e", + "llvm-target": "riscv64", + "max-atomic-width": 64, + "panic-strategy": "abort", + "relocation-model": "pie", + "target-pointer-width": "64", + "singlethread": true, + "pre-link-args": { + "ld": [ + "--emit-relocs", + "--unique", + "--relocatable" + ] + }, + "env": "polkavm" +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 56b15f24412..32fc4dc439f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,11 +26,12 @@ on: - 'FILE_HEADER' env: + # Image can be edited at https://github.com/use-ink/docker-images IMAGE: useink/ci CARGO_TARGET_DIR: /ci-cache/${{ github.repository }}/targets/${{ github.ref_name }}/${{ github.job }} CARGO_INCREMENTAL: 0 PURELY_STD_CRATES: ink/codegen metadata engine e2e e2e/macro ink/ir - ALSO_WASM_CRATES: env storage storage/traits allocator prelude primitives ink ink/macro + ALSO_RISCV_CRATES: env storage storage/traits allocator prelude primitives ink ink/macro # TODO `cargo clippy --all-targets --all-features` for this crate # currently fails on `stable`, but succeeds on `nightly`. This is due to # this fix not yet in stable: https://github.com/rust-lang/rust-clippy/issues/8895. @@ -40,8 +41,10 @@ env: # RISC-V does not have a standard library in contrast to Wasm. Compiling against # this target also makes sure that we don't pull in `std` by accident (through dependencies). # RISC-V is a modular architecture. We might switch to a different flavor with more features - # later. For example, `riscv32imc-unknown-none-elf`. - RISCV_TARGET: riscv32ema-unknown-none-elf + # later. For example, `riscv64imc-unknown-none-elf`. + RISCV_TARGET: .github/riscv64emac-unknown-none-polkavm.json + # Clippy doesn't support JSON files for `--target`, hence we use another RISC-V target. + CLIPPY_TARGET: riscv64imac-unknown-none-elf concurrency: # Cancel in-progress jobs triggered only on pull_requests @@ -73,7 +76,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Rust Info uses: ./.github/rust-info @@ -95,7 +98,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Rust Info uses: ./.github/rust-info @@ -126,7 +129,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Cache uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 @@ -138,16 +141,17 @@ jobs: - name: Run Clippy run: | - ALL_CRATES="${PURELY_STD_CRATES} ${ALSO_WASM_CRATES}" + ALL_CRATES="${PURELY_STD_CRATES} ${ALSO_RISCV_CRATES}" for crate in ${ALL_CRATES}; do cargo clippy --all-targets --all-features --manifest-path ./crates/${crate}/Cargo.toml \ -- -D warnings -A ${CLIPPY_ALLOWED}; done - - name: Run Clippy for WASM Crates + - name: Run Clippy for RISC-V Crates run: | - for crate in ${ALSO_WASM_CRATES}; do - cargo clippy --no-default-features --manifest-path ./crates/${crate}/Cargo.toml --target wasm32-unknown-unknown \ + for crate in ${ALSO_RISCV_CRATES}; do + cargo clippy --no-default-features --manifest-path ./crates/${crate}/Cargo.toml \ + --target ${CLIPPY_TARGET} \ -- -D warnings -A ${CLIPPY_ALLOWED}; done @@ -162,12 +166,12 @@ jobs: strategy: fail-fast: false matrix: - type: [STD, WASM] + type: [STD, RISCV] steps: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Cache uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 @@ -183,11 +187,12 @@ jobs: scripts/for_all_contracts_exec.sh --path integration-tests -- cargo clippy --all-targets \ --manifest-path {} -- -D warnings -A $CLIPPY_ALLOWED - - name: Run Clippy for WASM Examples - if: ${{ matrix.type == 'WASM' }} + - name: Run Clippy for RISC-V Examples + if: ${{ matrix.type == 'RISCV' }} run: | scripts/for_all_contracts_exec.sh --path integration-tests -- cargo clippy --no-default-features \ - --target wasm32-unknown-unknown --manifest-path {} -- -D warnings -A $CLIPPY_ALLOWED + --target ${CLIPPY_TARGET} \ + --manifest-path {} -- -D warnings -A $CLIPPY_ALLOWED check: runs-on: ubuntu-latest @@ -200,12 +205,12 @@ jobs: strategy: fail-fast: false matrix: - type: [STD, WASM, RISCV] + type: [STD, RISCV] steps: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Cache uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 @@ -218,27 +223,19 @@ jobs: - name: Check if: ${{ matrix.type == 'STD' }} run: | - ALL_CRATES="${PURELY_STD_CRATES} ${ALSO_WASM_CRATES}" + ALL_CRATES="${PURELY_STD_CRATES} ${ALSO_RISCV_CRATES}" for crate in ${ALL_CRATES}; do cargo check --all-features --manifest-path ./crates/${crate}/Cargo.toml; done - - name: Check WASM - if: ${{ matrix.type == 'WASM' }} - run: | - for crate in ${ALSO_WASM_CRATES}; do - cargo check --no-default-features --target wasm32-unknown-unknown \ - --manifest-path ./crates/${crate}/Cargo.toml; - done - - name: Check RISCV - if: ${{ matrix.type == 'RISCV-disabled' }} + if: ${{ matrix.type == 'RISCV' }} env: RUSTC_BOOTSTRAP: 1 - RUSTUP_TOOLCHAIN: rve-nightly run: | - for crate in ${ALSO_WASM_CRATES}; do - cargo check --no-default-features --target $RISCV_TARGET -Zbuild-std="core,alloc" \ + for crate in ${ALSO_RISCV_CRATES}; do + # remove `nightly` once new stable is released, currently there is an ICE in stable + cargo +nightly check --no-default-features --target $RISCV_TARGET -Zbuild-std="core,alloc" \ --manifest-path ./crates/${crate}/Cargo.toml; done @@ -254,7 +251,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Cache uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 @@ -269,13 +266,9 @@ jobs: cd linting/ # we are using a toolchain file in this directory # add required components for CI - rustup component add rustfmt clippy - rustup component add rust-src rustc-dev llvm-tools-preview cargo check --verbose cargo +nightly fmt --all -- --check cargo clippy -- -D warnings; - # Needed until https://github.com/mozilla/sccache/issues/1000 is fixed. - unset RUSTC_WRAPPER cargo test --all-features ### workspace @@ -291,12 +284,12 @@ jobs: strategy: fail-fast: false matrix: - type: [STD, WASM] + type: [STD, RISCV] steps: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Cache uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 @@ -306,20 +299,28 @@ jobs: - name: Rust Info uses: ./.github/rust-info - - name: Build + - name: Build for STD if: ${{ matrix.type == 'STD' }} run: | - ALL_CRATES="${PURELY_STD_CRATES} ${ALSO_WASM_CRATES}" + ALL_CRATES="${PURELY_STD_CRATES} ${ALSO_RISCV_CRATES}" for crate in ${ALL_CRATES}; do cargo build --all-features --release --manifest-path ./crates/${crate}/Cargo.toml; done - - name: Build WASM - if: ${{ matrix.type == 'WASM' }} + - name: Build for RISC-V + if: ${{ matrix.type == 'RISCV' }} + #env: + #RUSTC_BOOTSTRAP: 1 + #CARGO_ENCODED_RUSTFLAGS: "--cfg\x1fsubstrate_runtime" + #RUSTFLAGS: "--cfg substrate_runtime" run: | - for crate in ${ALSO_WASM_CRATES}; do - cargo build --no-default-features --release --target wasm32-unknown-unknown \ - --manifest-path ./crates/${crate}/Cargo.toml; + for crate in ${ALSO_RISCV_CRATES}; do + echo ${crate}; + RUSTFLAGS="--cfg substrate_runtime" cargo +nightly build \ + --no-default-features --release \ + --target $CLIPPY_TARGET \ + --manifest-path ./crates/${crate}/Cargo.toml \ + -Zbuild-std="core,alloc"; done test: @@ -338,7 +339,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Cache uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 @@ -360,8 +361,8 @@ jobs: # at the same time, hence we use this workaround. QUICKCHECK_TESTS: 0 run: | - cargo nextest run --all-features --no-fail-fast --workspace --locked - cargo test --all-features --no-fail-fast --workspace --doc --locked + cargo +nightly nextest run --all-features --no-fail-fast --workspace --locked + cargo +nightly test --all-features --no-fail-fast --workspace --doc --locked - name: Test Linting if: ${{ matrix.workspace == 'linting' }} @@ -388,7 +389,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Cache uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 @@ -483,18 +484,10 @@ jobs: matrix: partition: [1, 2, 3, 4, 5, 6] steps: - # We go out of storage on runners - - name: Clean runner - run: | - sudo rm -rf /usr/share/dotnet - sudo rm -rf /opt/ghc - sudo rm -rf "/usr/local/share/boost" - sudo rm -rf "$AGENT_TOOLSDIRECTORY" - - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Cache uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 @@ -502,18 +495,53 @@ jobs: cache-directories: ${{ env.CARGO_TARGET_DIR }} - name: Test Examples - env: - # Fix linking of `linkme`: https://github.com/dtolnay/linkme/issues/49 - RUSTFLAGS: -Clink-arg=-z -Clink-arg=nostart-stop-gc uses: docker://useink/ci + env: + #RUSTFLAGS: -Clinker-plugin-lto -Clink-arg=-zstack-size=4096 + # Fix for linking of `linkme` for `cargo test`: https://github.com/dtolnay/linkme/issues/49 + RUSTFLAGS: -Clink-arg=-z -Clink-arg=nostart-stop-gc with: # run all tests with --all-features, which will run the e2e-tests feature if present - args: /bin/bash -c "scripts/for_all_contracts_exec.sh --path integration-tests --ignore public/static-buffer --partition ${{ matrix.partition }}/6 -- cargo test \ - --all-features --manifest-path {}" + args: + /bin/bash -c "scripts/for_all_contracts_exec.sh --path integration-tests --ignore public/static-buffer --ignore public/mapping --partition ${{ matrix.partition }}/6 -- \ + cargo +nightly test --all-features --all --manifest-path {}" + + examples-test-mapping: + runs-on: ubuntu-latest + needs: [set-image] + defaults: + run: + shell: bash + container: + image: ${{ needs.set-image.outputs.IMAGE }} + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 1 + + - name: Cache + uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 + with: + cache-directories: ${{ env.CARGO_TARGET_DIR }} + + - name: Rust Info + uses: ./.github/rust-info + + - name: Test Mapping Example + env: + # Fix for linking of `linkme` for `cargo test`: https://github.com/dtolnay/linkme/issues/49 + RUSTFLAGS: -Clink-arg=-z -Clink-arg=nostart-stop-gc + # needed for `mapping::e2e_tests::fallible_storage_methods_work` + INK_STATIC_BUFFER_SIZE: 256 + run: + rustup install nightly-2025-01-07; + rustup component add rust-src --toolchain nightly-2025-01-07; + cargo +nightly-2024-11-28 test --all-features --all --manifest-path integration-tests/public/mapping/Cargo.toml examples-custom-test: runs-on: ubuntu-latest - needs: [set-image, clippy] + needs: [set-image, clippy, clippy-examples] defaults: run: shell: bash @@ -523,7 +551,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Cache uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 @@ -538,23 +566,27 @@ jobs: # Fix linking of `linkme`: https://github.com/dtolnay/linkme/issues/49 RUSTFLAGS: -Clink-arg=-z -Clink-arg=nostart-stop-gc run: | - # run the static buffer test with a custom buffer size + # run the static buffer test with a custom buffer size. + # the readme + test comments explain why `32`, in short because the tests write + # content into the buffer and want to provoke an exhaustion of the buffer. cargo clean --manifest-path integration-tests/public/static-buffer/Cargo.toml - INK_STATIC_BUFFER_SIZE=30 cargo test --manifest-path integration-tests/public/static-buffer/Cargo.toml --all-features + INK_STATIC_BUFFER_SIZE=32 cargo +nightly test --manifest-path integration-tests/public/static-buffer/Cargo.toml --all-features - name: Run E2E test with on-chain contract + # todo disabled until `cargo-contract` supports mapping the account + if: false env: # Fix linking of `linkme`: https://github.com/dtolnay/linkme/issues/49 RUSTFLAGS: -Clink-arg=-z -Clink-arg=nostart-stop-gc run: | # run flipper E2E test with on-chain contract - substrate-contracts-node -lruntime::contracts=debug 2>&1 & - cargo contract build --release --manifest-path integration-tests/public/flipper/Cargo.toml - export CONTRACT_ADDR_HEX=$(cargo contract instantiate \ + substrate-contracts-node -lruntime::revive=debug 2>&1 & + cargo +nightly contract build --release --manifest-path integration-tests/public/flipper/Cargo.toml + export CONTRACT_ADDR_HEX=$(cargo +nightly contract instantiate \ --manifest-path integration-tests/public/flipper/Cargo.toml \ --suri //Alice --args true -x -y --output-json | \ jq -r .contract | xargs subkey inspect | grep -o "0x.*" | head -n1) - CONTRACTS_NODE_URL=ws://127.0.0.1:9944 cargo test \ + CONTRACTS_NODE_URL=ws://127.0.0.1:9944 cargo +nightly test \ --features e2e-tests \ --manifest-path integration-tests/public/flipper/Cargo.toml \ e2e_test_deployed_contract \ @@ -571,20 +603,13 @@ jobs: strategy: fail-fast: false matrix: - type: [WASM, RISCV] + type: [RISCV] partition: [1, 2, 3, 4] - exclude: - - type: RISCV - partition: 2 - - type: RISCV - partition: 3 - - type: RISCV - partition: 4 steps: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Cache uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 @@ -594,37 +619,18 @@ jobs: - name: Rust Info uses: ./.github/rust-info - - name: Build Contract WASM Examples - if: ${{ matrix.type == 'WASM' }} - run: | - rustup component add rust-src --toolchain stable - cargo contract -V - # Build all examples - scripts/for_all_contracts_exec.sh --path integration-tests --partition ${{ matrix.partition }}/4 -- cargo contract build --release --manifest-path {} - if [ ${{ matrix.partition }} -eq 4 ]; then - # Build the different features for the conditional compilation example - pushd ./integration-tests/public/conditional-compilation - cargo contract build --release --features "foo" - cargo contract build --release --features "bar" - cargo contract build --release --features "foo, bar" - popd - fi - - name: Build Contract RISCV Examples - if: ${{ matrix.type == 'RISCV-disabled' }} + if: ${{ matrix.type == 'RISCV' }} env: RUSTC_BOOTSTRAP: 1 - RUSTUP_TOOLCHAIN: rve-nightly run: | - rustup component add rust-src --toolchain stable - cargo contract -V # We skip some examples for those reasons: # This uses dlmalloc which is only supported on select targets. # - custom_allocator # Pulls in sp-std which needlessly requires atomic pointers (TODO: Fix sp-std and enable this example) # - call-runtime scripts/for_all_contracts_exec.sh --path integration-tests --ignore public/custom-allocator --ignore public/call-runtime --ignore public/contract-xcm \ - -- cargo build --manifest-path {} --no-default-features --target $RISCV_TARGET -Zbuild-std="core,alloc" + -- cargo +nightly build --manifest-path {} --no-default-features --target $RISCV_TARGET -Zbuild-std="core,alloc" examples-docs: runs-on: ubuntu-latest @@ -638,7 +644,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Cache uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 @@ -662,7 +668,7 @@ jobs: # measurements measurements: - needs: [examples-docs, examples-contract-build, examples-test, examples-custom-test] + needs: [examples-docs, examples-contract-build, examples-test, examples-custom-test, examples-test-mapping] uses: ./.github/workflows/measurements.yml # fuzz @@ -685,7 +691,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 100 + fetch-depth: 1 - name: Cache uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 @@ -702,7 +708,7 @@ jobs: run: | # We fuzz-test only crates which possess the `ink-fuzz-tests` feature all_tests_passed=0 - ALL_CRATES="${PURELY_STD_CRATES} ${ALSO_WASM_CRATES}" + ALL_CRATES="${PURELY_STD_CRATES} ${ALSO_RISCV_CRATES}" for crate in ${ALL_CRATES}; do if grep "ink-fuzz-tests =" ./crates/${crate}/Cargo.toml; then diff --git a/.github/workflows/examples.yml b/.github/workflows/examples.yml index 0e0193c31c0..5bead1f801b 100644 --- a/.github/workflows/examples.yml +++ b/.github/workflows/examples.yml @@ -76,7 +76,7 @@ jobs: if: matrix.os == 'windows-latest' run: | cargo install contracts-node --git https://github.com/paritytech/substrate-contracts-node.git --force --locked && \ - substrate-contracts-node -lruntime::contracts=debug 2>&1 | tee /tmp/contracts-node.log & + substrate-contracts-node -lruntime::revive=debug 2>&1 | tee /tmp/contracts-node.log & - name: Rust Cache uses: Swatinem/rust-cache@82a92a6e8fbeee089604da2575dc567ae9ddeaab # v2.7.5 diff --git a/.github/workflows/measurements.yml b/.github/workflows/measurements.yml index a579f335010..7301346ce79 100644 --- a/.github/workflows/measurements.yml +++ b/.github/workflows/measurements.yml @@ -55,7 +55,7 @@ jobs: ${SCRIPTS_DIR}/for_all_contracts_exec.sh --path integration-tests --quiet -- ${SCRIPTS_DIR}/contract_size.sh {} > ${CONTRACT_SIZES} sed -ie 's/^integration-tests\/\(public\/\|internal\/\)\?//' ${CONTRACT_SIZES} - CARGO_CONTRACT_VERSION=$(cargo-contract --version | egrep --only-matching "cargo-contract.* .*-x86" | sed -s 's/-x86//') + CARGO_CONTRACT_VERSION=$(cargo contract --version | egrep --only-matching "cargo-contract.* .*-x86" | sed -s 's/-x86//') echo "CARGO_CONTRACT_VERSION=\"${CARGO_CONTRACT_VERSION}\"" > ${MEASUREMENTS_DIR}/context.out echo "PR_NUMBER=\"${PR_NUMBER}\"" >> ${MEASUREMENTS_DIR}/context.out diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index a57b217bc43..c5e134a39f2 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -3,9 +3,9 @@ name: continuous-integration/publish-docs -on: +on: workflow_run: - workflows: + workflows: - continuous-integration types: - completed diff --git a/.rustfmt.toml b/.rustfmt.toml index 2843071a0d6..90456fa14ec 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -8,7 +8,7 @@ wrap_comments = true # changed format_code_in_doc_comments = true # changed doc_comment_code_block_width = 100 # changed comment_width = 90 # changed -normalize_comments = true # changed +#normalize_comments = true # changed # todo uncomment normalize_doc_attributes = false format_strings = false format_macro_matchers = false diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index ad7958e1437..10afd22c130 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -23,7 +23,7 @@ ink! is composed of a number of crates that are all found in the Serves two roles: * Exposes environmental functions, like information about the caller of a contract call or e.g. self-terminating the contract. - * Provides the connection to the [`pallet-contracts`](https://github.com/paritytech/substrate/tree/master/frame/contracts), + * Provides the connection to the [`pallet-revive`](https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/revive), so anything that calls into the underlying execution engine of the smart contract. This includes getting and setting a smart contracts storage, as well as the mentioned environmental functions. @@ -45,7 +45,7 @@ ink! is composed of a number of crates that are all found in the mocking specified conditions. * [`e2e`](https://github.com/use-ink/ink/tree/master/crates/e2e): An end-to-end testing framework for ink! contracts. It requires a Substrate node - which includes `pallet-contracts` running in the background. The crate provides a + which includes `pallet-revive` running in the background. The crate provides a macro which can be used to write an idiomatic Rust test that will in the background create transactions, submit it to the Substrate chain and return the state changes, gas costs, etc. @@ -58,7 +58,7 @@ are only relevant off-chain. ink! contracts are compiled for a WebAssembly (Wasm) target architecture, i.e. they are executed in a Wasm sandbox execution environment on the blockchain itself ‒ hence a `no_std` environment. -More specifically they are executed by the [`pallet-contracts`](https://github.com/paritytech/substrate/tree/master/frame/contracts), +More specifically they are executed by the [`pallet-revive`](https://github.com/paritytech/substrate/tree/master/frame/contracts), a module of the Substrate blockchain framework. This module takes ink! smart contracts and runs them in a sandbox environment. @@ -123,38 +123,38 @@ One advantage is that users don't deal with an ever-changing nightly compiler. It's easier for us to support. If you build a contract without `cargo-contract` you will have to set this env variable too or use nightly. -## Interaction with `pallet-contracts` +## Interaction with `pallet-revive` The Wasm blob to which an ink! contract is compiled is executed in -an execution environment named [`pallet-contracts`](https://github.com/paritytech/substrate/commits/master/frame/contracts) +an execution environment named [`pallet-revive`](https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/revive) on-chain. -This `pallet-contracts` is the smart contracts module of +This `pallet-revive` is the smart contracts module of [the Substrate blockchain framework](http://substrate.io/). The relationship is as depicted in this diagram: -pallet-contracts Interaction +pallet-revive Interaction ### Communication with the pallet -ink! uses a static buffer for interacting with `pallet-contracts`, i.e. +ink! uses a static buffer for interacting with `pallet-revive`, i.e. to move data between the pallet and a smart contract. The advantage of a static buffer is that no gas-expensive heap allocations are necessary, all allocations are done using simple pointer arithmetic. The implementation of this static buffer is found in [`ink_env/src/engine/on_chain/buffer.rs`](https://github.com/use-ink/ink/blob/master/crates/env/src/engine/on_chain/buffer.rs). -The methods for communicating with the pallet are found in [`ink_env/src/engine/on_chain/impls`](https://github.com/use-ink/ink/tree/master/crates/env/src/engine/on_chain/impls). +The methods for communicating with the pallet are found in [`ink_env/src/engine/on_chain/pallet_revive.rs`](https://github.com/use-ink/ink/blob/master/crates/env/src/engine/on_chain/pallet_revive.rs). If you look at the implementations you'll see a common pattern of * SCALE-encoding values on the ink! side in order to pass them as a slice - of bytes to the `pallet-contracts`. -* SCALE-decoding values that come from the `pallet-contracts` side in order + of bytes to the `pallet-revive`. +* SCALE-decoding values that come from the `pallet-revive` side in order to convert them into the proper types on the ink! side, making them available for contract developers. ### The pallet API Signatures of host API functions are defined in -[`pallet-contracts-uapi`](https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/contracts/uapi/src/host/wasm32.rs). +[`pallet-revive-uapi`](https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/revive/uapi/src/host/riscv64.rs). You'll see that we import different versions of API functions, something like the following excerpt: @@ -178,7 +178,7 @@ extern "C" { } ``` -Smart contracts are immutable, thus the `pallet-contracts` can never change or remove +Smart contracts are immutable, thus the `pallet-revive` can never change or remove old API functions ‒ otherwise smart contracts that are deployed on-chain would break. Hence there is this version mechanism. Functions start out at version `seal0` and for @@ -192,7 +192,7 @@ contract. And we found seals to be a cute animal as well ‒ like squids! ## `Environment` Trait You can use ink! on any blockchain that was built with the [Substrate](https://substrate.io) -framework and includes the [`pallet-contracts`](https://github.com/paritytech/substrate/tree/master/frame/contracts) +framework and includes the [`pallet-revive`](https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/revive) module. Substrate does not define specific types for a blockchain, it uses generic types throughout. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9b8b864faa1..70c35e392f4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,5 +1,7 @@ # Contributing to ink! +TODO review + First of all, thank you for taking your time to contribute to ink! > [I don't want to contribute, I just have some questions! :S](#I-dont-want-to-contribute-I-just-have-some-questions) @@ -81,14 +83,14 @@ Verify the following locally, otherwise the CI will fail: ### Backwards Compatibility -ink! and `pallet-contracts` are projects under active development. As the Contracts API +ink! and `pallet-revive` are projects under active development. As the Contracts API functions evolve to their newer versions we need to introduce them in ink! in a way that keeps the current *MAJOR* ink! versions compatible with older Substrate nodes which may not have these new API function. In order to achieve this, please stick to the following workflow. -Imagine there is a `[seal0] function()` in the Contracts pallet API and our +Imagine there is a `[seal0] function()` in the Revive pallet API and our `ink_env::function()` uses its import under the hood. Then some time later we decide to add a new `[seal1] function()` version to the pallet. In order to introduce it into ink! and still be able to run contracts (which don't use this particular function) on @@ -107,7 +109,6 @@ older nodes, please do the following: You can have a look at the [PR#1284](https://github.com/use-ink/ink/pull/1284/files#diff-e7cc1cdb3856da1293c785de863703d5961c324aa2018decb0166ea1eb0631e8R191) for a reference of how the described way could be implemented. - ## Issues and Pull Requests Please always respect our [code of conduct](CODE_OF_CONDUCT.md) when writing issues and pull requests or taking part in any kind of discussion. diff --git a/Cargo.lock b/Cargo.lock index fc2f10e4948..910ba0b7454 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -33,7 +33,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" dependencies = [ - "crypto-common", + "crypto-common 0.1.6", "generic-array", ] @@ -131,9 +131,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.94" +version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1fd03a028ef38ba2276dce7e33fcd6369c158a1bca17946c4b1b701891c1ff7" +checksum = "34ac096ce696dc2fcabef30516bb13c0a68a11d30131d3df6f04711467681b04" [[package]] name = "approx" @@ -155,7 +155,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -173,9 +173,21 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb00293ba84f51ce3bd026bd0de55899c4e68f0a39a5728cebae3a73ffdc0a4f" dependencies = [ - "ark-ec", - "ark-ff", - "ark-std", + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-std 0.4.0", +] + +[[package]] +name = "ark-bls12-377-ext" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c7021f180a0cbea0380eba97c2af3c57074cdaffe0eef7e840e1c9f2841e55" +dependencies = [ + "ark-bls12-377", + "ark-ec 0.4.2", + "ark-models-ext", + "ark-std 0.4.0", ] [[package]] @@ -184,10 +196,49 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c775f0d12169cba7aae4caeb547bb6a50781c7449a8aa53793827c9ec4abf488" dependencies = [ - "ark-ec", - "ark-ff", - "ark-serialize", - "ark-std", + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", +] + +[[package]] +name = "ark-bls12-381-ext" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1dc4b3d08f19e8ec06e949712f95b8361e43f1391d94f65e4234df03480631c" +dependencies = [ + "ark-bls12-381", + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-models-ext", + "ark-serialize 0.4.2", + "ark-std 0.4.0", +] + +[[package]] +name = "ark-bw6-761" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e0605daf0cc5aa2034b78d008aaf159f56901d92a52ee4f6ecdfdac4f426700" +dependencies = [ + "ark-bls12-377", + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-std 0.4.0", +] + +[[package]] +name = "ark-bw6-761-ext" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccee5fba47266f460067588ee1bf070a9c760bf2050c1c509982c5719aadb4f2" +dependencies = [ + "ark-bw6-761", + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-models-ext", + "ark-std 0.4.0", ] [[package]] @@ -196,34 +247,126 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "defd9a439d56ac24968cca0571f598a61bc8c55f71d50a89cda591cb750670ba" dependencies = [ - "ark-ff", - "ark-poly", - "ark-serialize", - "ark-std", + "ark-ff 0.4.2", + "ark-poly 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", "derivative", "hashbrown 0.13.2", "itertools 0.10.5", "num-traits", + "rayon", + "zeroize", +] + +[[package]] +name = "ark-ec" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d68f2d516162846c1238e755a7c4d131b892b70cc70c471a8e3ca3ed818fce" +dependencies = [ + "ahash", + "ark-ff 0.5.0", + "ark-poly 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "educe", + "fnv", + "hashbrown 0.15.2", + "itertools 0.13.0", + "num-bigint", + "num-integer", + "num-traits", "zeroize", ] +[[package]] +name = "ark-ed-on-bls12-377" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b10d901b9ac4b38f9c32beacedfadcdd64e46f8d7f8e88c1ae1060022cf6f6c6" +dependencies = [ + "ark-bls12-377", + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-std 0.4.0", +] + +[[package]] +name = "ark-ed-on-bls12-377-ext" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "524a4fb7540df2e1a8c2e67a83ba1d1e6c3947f4f9342cc2359fc2e789ad731d" +dependencies = [ + "ark-ec 0.4.2", + "ark-ed-on-bls12-377", + "ark-ff 0.4.2", + "ark-models-ext", + "ark-std 0.4.0", +] + +[[package]] +name = "ark-ed-on-bls12-381-bandersnatch" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9cde0f2aa063a2a5c28d39b47761aa102bda7c13c84fc118a61b87c7b2f785c" +dependencies = [ + "ark-bls12-381", + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-std 0.4.0", +] + +[[package]] +name = "ark-ed-on-bls12-381-bandersnatch-ext" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d15185f1acb49a07ff8cbe5f11a1adc5a93b19e211e325d826ae98e98e124346" +dependencies = [ + "ark-ec 0.4.2", + "ark-ed-on-bls12-381-bandersnatch", + "ark-ff 0.4.2", + "ark-models-ext", + "ark-std 0.4.0", +] + [[package]] name = "ark-ff" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec847af850f44ad29048935519032c33da8aa03340876d351dfab5660d2966ba" dependencies = [ - "ark-ff-asm", - "ark-ff-macros", - "ark-serialize", - "ark-std", + "ark-ff-asm 0.4.2", + "ark-ff-macros 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", "derivative", "digest 0.10.7", "itertools 0.10.5", "num-bigint", "num-traits", "paste", - "rustc_version 0.4.1", + "rustc_version", + "zeroize", +] + +[[package]] +name = "ark-ff" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a177aba0ed1e0fbb62aa9f6d0502e9b46dad8c2eab04c14258a1212d2557ea70" +dependencies = [ + "ark-ff-asm 0.5.0", + "ark-ff-macros 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "arrayvec 0.7.6", + "digest 0.10.7", + "educe", + "itertools 0.13.0", + "num-bigint", + "num-traits", + "paste", "zeroize", ] @@ -237,6 +380,16 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "ark-ff-asm" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62945a2f7e6de02a31fe400aa489f0e0f5b2502e69f95f853adb82a96c7a6b60" +dependencies = [ + "quote", + "syn 2.0.93", +] + [[package]] name = "ark-ff-macros" version = "0.4.2" @@ -250,27 +403,110 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "ark-ff-macros" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09be120733ee33f7693ceaa202ca41accd5653b779563608f1234f78ae07c4b3" +dependencies = [ + "num-bigint", + "num-traits", + "proc-macro2", + "quote", + "syn 2.0.93", +] + +[[package]] +name = "ark-models-ext" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e9eab5d4b5ff2f228b763d38442adc9b084b0a465409b059fac5c2308835ec2" +dependencies = [ + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "derivative", +] + [[package]] name = "ark-poly" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d320bfc44ee185d899ccbadfa8bc31aab923ce1558716e1997a1e74057fe86bf" dependencies = [ - "ark-ff", - "ark-serialize", - "ark-std", + "ark-ff 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", "derivative", "hashbrown 0.13.2", ] +[[package]] +name = "ark-poly" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "579305839da207f02b89cd1679e50e67b4331e2f9294a57693e5051b7703fe27" +dependencies = [ + "ahash", + "ark-ff 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "educe", + "fnv", + "hashbrown 0.15.2", +] + +[[package]] +name = "ark-scale" +version = "0.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f69c00b3b529be29528a6f2fd5fa7b1790f8bed81b9cdca17e326538545a179" +dependencies = [ + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "parity-scale-codec", + "scale-info", +] + +[[package]] +name = "ark-secret-scalar" +version = "0.0.2" +source = "git+https://github.com/w3f/ring-vrf?rev=0fef826#0fef8266d851932ad25d6b41bc4b34d834d1e11d" +dependencies = [ + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "ark-transcript", + "digest 0.10.7", + "getrandom_or_panic", + "zeroize", +] + [[package]] name = "ark-serialize" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" dependencies = [ - "ark-serialize-derive", - "ark-std", + "ark-serialize-derive 0.4.2", + "ark-std 0.4.0", + "digest 0.10.7", + "num-bigint", +] + +[[package]] +name = "ark-serialize" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f4d068aaf107ebcd7dfb52bc748f8030e0fc930ac8e360146ca54c1203088f7" +dependencies = [ + "ark-serialize-derive 0.5.0", + "ark-std 0.5.0", + "arrayvec 0.7.6", "digest 0.10.7", "num-bigint", ] @@ -286,16 +522,51 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "ark-serialize-derive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "213888f660fddcca0d257e88e54ac05bca01885f258ccdf695bafd77031bb69d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.93", +] + [[package]] name = "ark-std" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" +dependencies = [ + "num-traits", + "rand", + "rayon", +] + +[[package]] +name = "ark-std" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "246a225cc6131e9ee4f24619af0f19d67761fff15d7ccc22e42b80846e69449a" dependencies = [ "num-traits", "rand", ] +[[package]] +name = "ark-transcript" +version = "0.0.2" +source = "git+https://github.com/w3f/ring-vrf?rev=0fef826#0fef8266d851932ad25d6b41bc4b34d834d1e11d" +dependencies = [ + "ark-ff 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "digest 0.10.7", + "rand_core", + "sha3 0.10.8", +] + [[package]] name = "array-bytes" version = "6.2.3" @@ -457,7 +728,7 @@ checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -493,6 +764,27 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "bandersnatch_vrfs" +version = "0.0.4" +source = "git+https://github.com/w3f/ring-vrf?rev=0fef826#0fef8266d851932ad25d6b41bc4b34d834d1e11d" +dependencies = [ + "ark-bls12-381", + "ark-ec 0.4.2", + "ark-ed-on-bls12-381-bandersnatch", + "ark-ff 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "dleq_vrf", + "rand_chacha", + "rand_core", + "ring 0.1.0", + "sha2 0.10.8", + "sp-ark-bls12-381", + "sp-ark-ed-on-bls12-381-bandersnatch", + "zeroize", +] + [[package]] name = "base16ct" version = "0.2.0" @@ -523,6 +815,32 @@ version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" +[[package]] +name = "binary-merkle-tree" +version = "13.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" +dependencies = [ + "hash-db", + "log", + "parity-scale-codec", +] + +[[package]] +name = "bip32" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa13fae8b6255872fd86f7faf4b41168661d7d78609f7bfe6771b85c6739a15b" +dependencies = [ + "bs58", + "hmac 0.12.1", + "k256", + "rand_core", + "ripemd", + "sha2 0.10.8", + "subtle", + "zeroize", +] + [[package]] name = "bip39" version = "2.1.0" @@ -639,6 +957,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.11.0-rc.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fd016a0ddc7cb13661bf5576073ce07330a693f8608a1320b4e20561cc12cdc" +dependencies = [ + "hybrid-array", +] + [[package]] name = "blocking" version = "1.6.1" @@ -677,7 +1004,7 @@ dependencies = [ "serde_json", "serde_repr", "serde_urlencoded", - "thiserror 2.0.4", + "thiserror 2.0.9", "tokio", "tokio-util", "tower-service", @@ -714,6 +1041,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" dependencies = [ + "sha2 0.10.8", "tinyvec", ] @@ -731,9 +1059,9 @@ checksum = "c3ac9f8b63eca6fd385229b3675f6cc0dc5c8a5c8a54a59d4f52ffd670d87b0c" [[package]] name = "bytemuck" -version = "1.20.0" +version = "1.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b37c88a63ffd85d15b406896cc343916d7cf57838a847b3a6f2ca5d39a5695a" +checksum = "ef657dfab802224e671f5818e9a4935f9b1957ed18e58292690cc39e7a4092a3" [[package]] name = "byteorder" @@ -773,20 +1101,18 @@ checksum = "8769706aad5d996120af43197bf46ef6ad0fda35216b4505f926a365a232d924" dependencies = [ "camino", "cargo-platform", - "semver 1.0.23", + "semver", "serde", "serde_json", - "thiserror 2.0.4", + "thiserror 2.0.9", ] [[package]] name = "cc" -version = "1.2.2" +version = "1.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f34d93e62b03caf570cccc334cbc6c2fceca82f39211051345108adcba3eebdc" +checksum = "8d6dbb628b8f8555f86d0323c2eb39e3ec81901f4b83e091db8a6a76d316a333" dependencies = [ - "jobserver", - "libc", "shlex", ] @@ -824,9 +1150,9 @@ dependencies = [ [[package]] name = "chrono" -version = "0.4.38" +version = "0.4.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" +checksum = "7e36cc9d416881d2e24f9a963be5fb1cd90966419ac844274161d10488b3e825" dependencies = [ "android-tzdata", "iana-time-zone", @@ -841,16 +1167,16 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common", + "crypto-common 0.1.6", "inout", "zeroize", ] [[package]] name = "clap" -version = "4.5.22" +version = "4.5.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69371e34337c4c984bbe322360c2547210bf632eb2814bbe78a6e87a2935bd2b" +checksum = "3135e7ec2ef7b10c6ed8950f0f792ed96ee093fa088608f1c76e569722700c84" dependencies = [ "clap_builder", "clap_derive", @@ -858,9 +1184,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.22" +version = "4.5.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e24c1b4099818523236a8ca881d2b45db98dadfb4625cf6608c12069fcbbde1" +checksum = "30582fc632330df2bd26877bde0c1f4470d57c582bbc070376afcd04d8cb4838" dependencies = [ "anstream", "anstyle", @@ -874,27 +1200,17 @@ version = "4.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab" dependencies = [ - "heck 0.5.0", + "heck", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "clap_lex" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afb84c814227b90d6895e01398aee0d8033c00e7466aca416fb6a8e0eb19d8a7" - -[[package]] -name = "codespan-reporting" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" -dependencies = [ - "termcolor", - "unicode-width 0.1.14", -] +checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" [[package]] name = "colorchoice" @@ -904,12 +1220,12 @@ checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" [[package]] name = "colored" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbf2150cce219b664a8a70df7a1f933836724b503f8a413af9365b4dcc4d90b8" +checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c" dependencies = [ "lazy_static", - "windows-sys 0.48.0", + "windows-sys 0.59.0", ] [[package]] @@ -922,6 +1238,22 @@ dependencies = [ "memchr", ] +[[package]] +name = "common" +version = "0.1.0" +source = "git+https://github.com/w3f/ring-proof?rev=665f5f5#665f5f51af5734c7b6d90b985dd6861d4c5b4752" +dependencies = [ + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-poly 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "fflonk", + "getrandom_or_panic", + "merlin", + "rand_chacha", +] + [[package]] name = "common-path" version = "1.0.0" @@ -943,6 +1275,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.0-rc.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ff6be19477a1bd5441f382916a89bc2a0b2c35db6d41e0f6e8538bf6d6463f" + [[package]] name = "const-random" version = "0.1.18" @@ -1004,8 +1342,7 @@ checksum = "cd7e35aee659887cbfb97aaf227ac12cad1a9d7c71e55ff3376839ed4e282d08" [[package]] name = "contract-build" version = "5.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "857769855bf40d230e41baf6575cc44bd5e6869f69f88f45f6791da793f49a0c" +source = "git+https://github.com/use-ink/cargo-contract?branch=cmichi-remove-wasm-default-to-revive#934ecf915acb87be521402cfbdb685020f9655ce" dependencies = [ "anyhow", "blake2", @@ -1016,16 +1353,18 @@ dependencies = [ "contract-metadata", "crossterm", "duct", - "heck 0.5.0", + "heck", "hex", - "impl-serde 0.5.0", + "impl-serde", "parity-scale-codec", + "polkavm-linker", "regex", - "rustc_version 0.4.1", - "semver 1.0.23", + "rustc_version", + "semver", "serde", "serde_json", - "strum 0.26.3", + "sha3 0.11.0-pre.4", + "strum", "tempfile", "term_size", "tokio", @@ -1035,9 +1374,7 @@ dependencies = [ "url", "uzers", "walkdir", - "wasm-encoder 0.220.0", - "wasm-opt", - "wasmparser 0.220.0", + "wasmparser", "which", "zip", ] @@ -1045,12 +1382,11 @@ dependencies = [ [[package]] name = "contract-metadata" version = "5.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "733a6624ea05dd71050641c3cd9baff7a1445032a0082f0e55c800c078716424" +source = "git+https://github.com/use-ink/cargo-contract?branch=cmichi-remove-wasm-default-to-revive#934ecf915acb87be521402cfbdb685020f9655ce" dependencies = [ "anyhow", - "impl-serde 0.5.0", - "semver 1.0.23", + "impl-serde", + "semver", "serde", "serde_json", "url", @@ -1096,20 +1432,39 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-deque" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-queue" -version = "0.3.11" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df0346b5d5e76ac2fe4e327c5fd1118d6be7c51dfb18f9b7922923f287471e35" +checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.20" +version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "crossterm" @@ -1165,6 +1520,17 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.0-rc.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0b8ce8218c97789f16356e7896b3714f26c2ee1079b79c0b7ae7064bb9089fa" +dependencies = [ + "getrandom", + "hybrid-array", + "rand_core", +] + [[package]] name = "crypto-mac" version = "0.8.0" @@ -1201,7 +1567,7 @@ dependencies = [ "curve25519-dalek-derive", "digest 0.10.7", "fiat-crypto", - "rustc_version 0.4.1", + "rustc_version", "subtle", "zeroize", ] @@ -1214,66 +1580,7 @@ checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", -] - -[[package]] -name = "cxx" -version = "1.0.133" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05e1ec88093d2abd9cf1b09ffd979136b8e922bf31cad966a8fe0d73233112ef" -dependencies = [ - "cc", - "cxxbridge-cmd", - "cxxbridge-flags", - "cxxbridge-macro", - "foldhash", - "link-cplusplus", -] - -[[package]] -name = "cxx-build" -version = "1.0.133" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9afa390d956ee7ccb41aeed7ed7856ab3ffb4fc587e7216be7e0f83e949b4e6c" -dependencies = [ - "cc", - "codespan-reporting", - "proc-macro2", - "quote", - "scratch", - "syn 2.0.90", -] - -[[package]] -name = "cxxbridge-cmd" -version = "1.0.133" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c23bfff654d6227cbc83de8e059d2f8678ede5fc3a6c5a35d5c379983cc61e6" -dependencies = [ - "clap", - "codespan-reporting", - "proc-macro2", - "quote", - "syn 2.0.90", -] - -[[package]] -name = "cxxbridge-flags" -version = "1.0.133" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c01b36e22051bc6928a78583f1621abaaf7621561c2ada1b00f7878fbe2caa" - -[[package]] -name = "cxxbridge-macro" -version = "1.0.133" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6e14013136fac689345d17b9a6df55977251f11d333c0a571e8d963b55e1f95" -dependencies = [ - "proc-macro2", - "quote", - "rustversion", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -1297,7 +1604,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -1308,7 +1615,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -1317,7 +1624,7 @@ version = "0.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f55bf8e7b65898637379c1b74eb1551107c8294ed26d855ceb9fd1a09cfc9bc0" dependencies = [ - "const-oid", + "const-oid 0.9.6", "zeroize", ] @@ -1350,7 +1657,7 @@ checksum = "d65d7ce8132b7c0e54497a4d9a55a1c2a0912a0d786cf894472ba818fba45762" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -1361,7 +1668,7 @@ checksum = "62d671cc41a825ebabc75757b62d3d168c577f9149b2d49ece1dad1f72119d25" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -1372,7 +1679,7 @@ checksum = "30542c1ad912e0e3d22a1935c290e12e8a29d704a420177a31faad4a601a0800" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -1384,8 +1691,8 @@ dependencies = [ "convert_case", "proc-macro2", "quote", - "rustc_version 0.4.1", - "syn 2.0.90", + "rustc_version", + "syn 2.0.93", ] [[package]] @@ -1405,7 +1712,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", "unicode-xid", ] @@ -1431,11 +1738,43 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", - "const-oid", - "crypto-common", + "const-oid 0.9.6", + "crypto-common 0.1.6", "subtle", ] +[[package]] +name = "digest" +version = "0.11.0-pre.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf2e3d6615d99707295a9673e889bf363a04b2a466bd320c65a72536f7577379" +dependencies = [ + "block-buffer 0.11.0-rc.3", + "const-oid 0.10.0-rc.3", + "crypto-common 0.2.0-rc.1", +] + +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.48.0", +] + [[package]] name = "displaydoc" version = "0.2.5" @@ -1444,7 +1783,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -1453,6 +1792,22 @@ version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59f8e79d1fbf76bdfbde321e902714bf6c49df88a7dda6fc682fc2979226962d" +[[package]] +name = "dleq_vrf" +version = "0.0.2" +source = "git+https://github.com/w3f/ring-vrf?rev=0fef826#0fef8266d851932ad25d6b41bc4b34d834d1e11d" +dependencies = [ + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-scale", + "ark-secret-scalar", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "ark-transcript", + "arrayvec 0.7.6", + "zeroize", +] + [[package]] name = "docify" version = "0.2.9" @@ -1474,7 +1829,7 @@ dependencies = [ "proc-macro2", "quote", "regex", - "syn 2.0.90", + "syn 2.0.93", "termcolor", "toml", "walkdir", @@ -1579,6 +1934,18 @@ dependencies = [ "zeroize", ] +[[package]] +name = "educe" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7bc049e1bd8cdeb31b68bbd586a9464ecf9f3944af3958a7a9d0f8b9799417" +dependencies = [ + "enum-ordinalize", + "proc-macro2", + "quote", + "syn 2.0.93", +] + [[package]] name = "either" version = "1.13.0" @@ -1605,6 +1972,32 @@ dependencies = [ "zeroize", ] +[[package]] +name = "enum-ordinalize" +version = "4.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fea0dcfa4e54eeb516fe454635a95753ddd39acda650ce703031c6973e315dd5" +dependencies = [ + "enum-ordinalize-derive", +] + +[[package]] +name = "enum-ordinalize-derive" +version = "4.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d28318a75d4aead5c4db25382e8ef717932d0346600cacae6357eb5941bc5ff" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.93", +] + +[[package]] +name = "env_home" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" + [[package]] name = "env_logger" version = "0.8.4" @@ -1637,6 +2030,37 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "ethbloom" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c321610643004cf908ec0f5f2aa0d8f1f8e14b540562a2887a1111ff1ecbf7b" +dependencies = [ + "crunchy", + "fixed-hash", + "impl-codec", + "impl-rlp", + "impl-serde", + "scale-info", + "tiny-keccak", +] + +[[package]] +name = "ethereum-types" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ab15ed80916029f878e0267c3a9f92b67df55e79af370bf66199059ae2b4ee3" +dependencies = [ + "ethbloom", + "fixed-hash", + "impl-codec", + "impl-rlp", + "impl-serde", + "primitive-types", + "scale-info", + "uint", +] + [[package]] name = "event-listener" version = "5.3.1" @@ -1670,14 +2094,20 @@ dependencies = [ "prettyplease", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + [[package]] name = "fastrand" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "486f806e73c5707928240ddc295403b1b93c96a02038563881c4a2fd84b81ac4" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "ff" @@ -1689,6 +2119,19 @@ dependencies = [ "subtle", ] +[[package]] +name = "fflonk" +version = "0.1.1" +source = "git+https://github.com/w3f/fflonk#eda051ea3b80042e844a3ebd17c2f60536e6ee3f" +dependencies = [ + "ark-ec 0.5.0", + "ark-ff 0.5.0", + "ark-poly 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "merlin", +] + [[package]] name = "fiat-crypto" version = "0.2.9" @@ -1725,9 +2168,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "foldhash" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f81ec6369c545a7d40e4589b5597581fa1c441fe1cce96dd1de43159910a36a2" +checksum = "a0d2fde1f7b3d48b8395d5f2de76c18a528bd6a9cdde438df747bfcba3e05d6f" [[package]] name = "form_urlencoded" @@ -1740,9 +2183,8 @@ dependencies = [ [[package]] name = "frame-benchmarking" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a01bdd47c2d541b38bd892da647d1e972c9d85b4ecd7094ad64f7600175da54d" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-support", "frame-support-procedural", @@ -1758,8 +2200,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-runtime-interface", - "sp-storage", + "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "static_assertions", ] @@ -1774,26 +2216,24 @@ dependencies = [ "scale-decode", "scale-info", "scale-type-resolver", - "sp-crypto-hashing", + "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "frame-election-provider-solution-type" -version = "14.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8156f209055d352994ecd49e19658c6b469d7c6de923bd79868957d0dcfb6f71" +version = "13.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "frame-election-provider-support" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c36f5116192c63d39f1b4556fa30ac7db5a6a52575fa241b045f7dfa82ecc2be" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-election-provider-solution-type", "frame-support", @@ -1808,9 +2248,9 @@ dependencies = [ [[package]] name = "frame-metadata" -version = "16.0.0" +version = "17.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87cf1549fba25a6fcac22785b61698317d958e96cac72a59102ea45b9ae64692" +checksum = "701bac17e9b55e0f95067c428ebcb46496587f08e8cf4ccc0fe5903bea10dbb8" dependencies = [ "cfg-if", "parity-scale-codec", @@ -1820,9 +2260,9 @@ dependencies = [ [[package]] name = "frame-metadata" -version = "17.0.0" +version = "18.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "701bac17e9b55e0f95067c428ebcb46496587f08e8cf4ccc0fe5903bea10dbb8" +checksum = "daaf440c68eb2c3d88e5760fe8c7af3f9fee9181fab6c2f2c4e7cc48dcc40bb8" dependencies = [ "cfg-if", "parity-scale-codec", @@ -1832,16 +2272,16 @@ dependencies = [ [[package]] name = "frame-support" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e44af69fa61bc5005ffe0339e198957e77f0f255704a9bee720da18a733e3dc" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "aquamarine", "array-bytes", + "binary-merkle-tree", "bitflags 1.3.2", "docify", "environmental", - "frame-metadata 16.0.0", + "frame-metadata 18.0.0", "frame-support-procedural", "impl-trait-for-tuples", "k256", @@ -1857,7 +2297,7 @@ dependencies = [ "sp-arithmetic", "sp-core", "sp-crypto-hashing-proc-macro", - "sp-debug-derive", + "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "sp-genesis-builder", "sp-inherents", "sp-io", @@ -1865,8 +2305,9 @@ dependencies = [ "sp-runtime", "sp-staking", "sp-state-machine", - "sp-std", - "sp-tracing", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-trie", "sp-weights", "static_assertions", "tt-call", @@ -1874,13 +2315,13 @@ dependencies = [ [[package]] name = "frame-support-procedural" -version = "30.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e8f9b6bc1517a6fcbf0b2377e5c8c6d39f5bb7862b191a59a9992081d63972d" +version = "23.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "Inflector", "cfg-expr", "derive-syn-parse", + "docify", "expander", "frame-support-procedural-tools", "itertools 0.11.0", @@ -1888,39 +2329,36 @@ dependencies = [ "proc-macro-warning", "proc-macro2", "quote", - "sp-crypto-hashing", - "syn 2.0.90", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "syn 2.0.93", ] [[package]] name = "frame-support-procedural-tools" -version = "13.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bead15a320be1764cdd50458c4cfacb23e0cee65f64f500f8e34136a94c7eeca" +version = "10.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-support-procedural-tools-derive", "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "frame-support-procedural-tools-derive" -version = "12.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed971c6435503a099bdac99fe4c5bea08981709e5b5a0a8535a1856f48561191" +version = "11.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "frame-system" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3c7fa02f8c305496d2ae52edaecdb9d165f11afa965e05686d7d7dd1ce93611" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "cfg-if", "docify", @@ -1932,7 +2370,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", "sp-version", "sp-weights", ] @@ -2022,7 +2459,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -2098,12 +2535,16 @@ name = "gimli" version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" +dependencies = [ + "fallible-iterator", + "stable_deref_trait", +] [[package]] name = "glob" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" +checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" [[package]] name = "group" @@ -2168,12 +2609,6 @@ dependencies = [ "foldhash", ] -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - [[package]] name = "heck" version = "0.5.0" @@ -2249,15 +2684,6 @@ dependencies = [ "hmac 0.8.1", ] -[[package]] -name = "home" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" -dependencies = [ - "windows-sys 0.52.0", -] - [[package]] name = "http" version = "1.2.0" @@ -2304,11 +2730,20 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2d35805454dc9f8662a98d6d61886ffe26bd465f5960e0e55345c70d5c0d2a9" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" -version = "1.5.1" +version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97818827ef4f364230e16705d4706e2897df2bb60617d6ca15d598025a3c481f" +checksum = "256fb8d4bd6413123cc9d91832d78325c48ff41677595be797d90f42969beae0" dependencies = [ "bytes", "futures-channel", @@ -2511,7 +2946,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -2543,29 +2978,31 @@ dependencies = [ [[package]] name = "impl-codec" -version = "0.6.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba6a270039626615617f3f36d15fc827041df3b78c439da2cadfa47455a77f2f" +checksum = "b67aa010c1e3da95bf151bd8b4c059b2ed7e75387cdb969b4f8f2723a43f9941" dependencies = [ "parity-scale-codec", ] [[package]] -name = "impl-codec" -version = "0.7.0" +name = "impl-num-traits" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67aa010c1e3da95bf151bd8b4c059b2ed7e75387cdb969b4f8f2723a43f9941" +checksum = "803d15461ab0dcc56706adf266158acbc44ccf719bf7d0af30705f58b90a4b8c" dependencies = [ - "parity-scale-codec", + "integer-sqrt", + "num-traits", + "uint", ] [[package]] -name = "impl-serde" +name = "impl-rlp" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc88fc67028ae3db0c853baa36269d398d5f45b6982f95549ff5def78c935cd" +checksum = "54ed8ad1f3877f7e775b8cbf30ed1bd3209a95401817f19a0eb4402d13f8cf90" dependencies = [ - "serde", + "rlp", ] [[package]] @@ -2585,7 +3022,7 @@ checksum = "a0eb5a3343abf848c0984fe4604b2b105da9539376e24fc0a3b0007411ae4fd9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -2647,10 +3084,9 @@ dependencies = [ "ink_prelude", "ink_primitives", "ink_storage", - "pallet-contracts-uapi", "pallet-revive-uapi", "parity-scale-codec", - "polkavm-derive 0.17.1", + "polkavm-derive", "scale-info", "sp-io", "staging-xcm", @@ -2673,18 +3109,18 @@ dependencies = [ "blake2", "derive_more 1.0.0", "either", - "heck 0.5.0", - "impl-serde 0.5.0", + "heck", + "impl-serde", "ink_ir", "ink_primitives", "itertools 0.13.0", "parity-scale-codec", - "polkavm-derive 0.17.1", + "polkavm-derive", "proc-macro2", "quote", "serde", "serde_json", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -2695,15 +3131,16 @@ dependencies = [ "contract-build", "frame-support", "funty", - "impl-serde 0.5.0", + "impl-serde", "ink", "ink_e2e_macro", "ink_env", "ink_primitives", "ink_sandbox", + "itertools 0.13.0", "jsonrpsee", - "pallet-contracts", - "pallet-contracts-mock-network", + "pallet-revive", + "pallet-revive-mock-network", "parity-scale-codec", "regex", "scale-info", @@ -2716,11 +3153,10 @@ dependencies = [ "subxt", "subxt-metadata", "subxt-signer", - "thiserror 2.0.4", + "thiserror 2.0.9", "tokio", "tracing", "tracing-subscriber", - "wasm-instrument", "which", ] @@ -2736,7 +3172,7 @@ dependencies = [ "proc-macro2", "quote", "serde_json", - "syn 2.0.90", + "syn 2.0.93", "temp-env", "tracing-subscriber", ] @@ -2748,12 +3184,11 @@ dependencies = [ "blake2", "derive_more 1.0.0", "ink_primitives", - "pallet-contracts-uapi", "pallet-revive-uapi", "parity-scale-codec", "secp256k1 0.30.0", "sha2 0.10.8", - "sha3", + "sha3 0.10.8", ] [[package]] @@ -2767,24 +3202,23 @@ dependencies = [ "ink", "ink_allocator", "ink_engine", + "ink_macro", "ink_prelude", "ink_primitives", "ink_storage_traits", "num-traits", - "pallet-contracts-uapi", "pallet-revive-uapi", "parity-scale-codec", - "paste", - "polkavm-derive 0.17.1", - "rlibc", + "polkavm-derive", "scale-decode", "scale-encode", "scale-info", "schnorrkel", "secp256k1 0.30.0", "sha2 0.10.8", - "sha3", + "sha3 0.10.8", "sp-io", + "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "staging-xcm", "static_assertions", ] @@ -2795,12 +3229,12 @@ version = "5.1.0" dependencies = [ "blake2", "either", - "impl-serde 0.5.0", + "impl-serde", "ink_prelude", "itertools 0.13.0", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -2819,7 +3253,7 @@ dependencies = [ "proc-macro2", "quote", "scale-info", - "syn 2.0.90", + "syn 2.0.93", "synstructure", ] @@ -2828,7 +3262,7 @@ name = "ink_metadata" version = "5.1.0" dependencies = [ "derive_more 1.0.0", - "impl-serde 0.5.0", + "impl-serde", "ink_prelude", "ink_primitives", "linkme", @@ -2858,9 +3292,11 @@ dependencies = [ "ink_prelude", "num-traits", "parity-scale-codec", + "primitive-types", "scale-decode", "scale-encode", "scale-info", + "serde", "xxhash-rust", ] @@ -2868,19 +3304,20 @@ dependencies = [ name = "ink_sandbox" version = "5.1.0" dependencies = [ - "frame-metadata 16.0.0", + "frame-metadata 18.0.0", "frame-support", "frame-system", + "ink_primitives", "pallet-balances", - "pallet-contracts", + "pallet-revive", "pallet-timestamp", "parity-scale-codec", "paste", "scale-info", + "sha3 0.10.8", "sp-core", - "sp-externalities", + "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "sp-io", - "wat", ] [[package]] @@ -2897,7 +3334,6 @@ dependencies = [ "ink_primitives", "ink_storage_traits", "itertools 0.13.0", - "pallet-contracts-uapi", "pallet-revive-uapi", "parity-scale-codec", "quickcheck", @@ -2994,20 +3430,11 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" -[[package]] -name = "jobserver" -version = "0.1.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0" -dependencies = [ - "libc", -] - [[package]] name = "js-sys" -version = "0.3.74" +version = "0.3.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a865e038f7f6ed956f788f0d7d60c541fff74c7bd74272c5d4cf15c63743e705" +checksum = "6717b6b5b077764fb5966237269cb3c64edddde4b14ce42647430a78ced9e7b7" dependencies = [ "once_cell", "wasm-bindgen", @@ -3059,7 +3486,7 @@ dependencies = [ "futures-util", "jsonrpsee-types", "pin-project", - "rustc-hash", + "rustc-hash 2.1.0", "serde", "serde_json", "thiserror 1.0.69", @@ -3116,13 +3543,22 @@ dependencies = [ "cpufeatures", ] +[[package]] +name = "keccak" +version = "0.2.0-pre.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7cdd4f0dc5807b9a2b25dd48a3f58e862606fe7bd47f41ecde36e97422d7e90" +dependencies = [ + "cpufeatures", +] + [[package]] name = "keccak-hash" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e1b8590eb6148af2ea2d75f38e7d29f5ca970d5a4df456b3ef19b8b415d0264" dependencies = [ - "primitive-types 0.13.1", + "primitive-types", "tiny-keccak", ] @@ -3132,17 +3568,11 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" -[[package]] -name = "leb128" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67" - [[package]] name = "libc" -version = "0.2.167" +version = "0.2.169" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09d6582e104315a817dff97f75133544b2e094ee22447d2acf4a74e189ba06fc" +checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" [[package]] name = "libm" @@ -3150,6 +3580,16 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa" +[[package]] +name = "libredox" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" +dependencies = [ + "bitflags 2.6.0", + "libc", +] + [[package]] name = "libsecp256k1" version = "0.7.1" @@ -3198,15 +3638,6 @@ dependencies = [ "libsecp256k1-core", ] -[[package]] -name = "link-cplusplus" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d240c6f7e1ba3a28b0249f774e6a9dd0175054b52dfbb61b16eb8505c3785c9" -dependencies = [ - "cc", -] - [[package]] name = "linkme" version = "0.3.31" @@ -3224,7 +3655,7 @@ checksum = "edbe595006d355eaf9ae11db92707d4338cd2384d16866131cc1afdbdd35d8d9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -3282,7 +3713,7 @@ dependencies = [ "macro_magic_core", "macro_magic_macros", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -3296,7 +3727,7 @@ dependencies = [ "macro_magic_core_macros", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -3307,7 +3738,7 @@ checksum = "b02abfe41815b5bd98dbd4260173db2c116dda171dc0fe7838cb206333b83308" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -3318,7 +3749,7 @@ checksum = "73ea28ee64b88876bf45277ed9a5817c1817df061a74f2b988971a12570e5869" dependencies = [ "macro_magic_core", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -3362,7 +3793,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "58c38e2799fc0978b65dfff8023ec7843e2330bb462f19198840b34b6582397d" dependencies = [ "byteorder", - "keccak", + "keccak 0.1.5", "rand_core", "zeroize", ] @@ -3375,9 +3806,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.8.0" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" +checksum = "4ffbe83022cedc1d264172192511ae958937694cd57ce297164951b8b3568394" dependencies = [ "adler2", ] @@ -3480,7 +3911,7 @@ checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -3534,9 +3965,9 @@ dependencies = [ [[package]] name = "object" -version = "0.36.5" +version = "0.36.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedf0a2d09c573ed1d8d85b30c119153926a2b36dce0ab28322c09a117a4683e" +checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" dependencies = [ "memchr", ] @@ -3559,6 +3990,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "os_pipe" version = "1.2.1" @@ -3577,9 +4014,8 @@ checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" [[package]] name = "pallet-asset-conversion" -version = "20.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33f0078659ae95efe6a1bf138ab5250bc41ab98f22ff3651d0208684f08ae797" +version = "10.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-benchmarking", "frame-support", @@ -3596,9 +4032,8 @@ dependencies = [ [[package]] name = "pallet-assets" -version = "40.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f45f4eb6027fc34c4650e0ed6a7e57ed3335cc364be74b4531f714237676bcee" +version = "29.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-benchmarking", "frame-support", @@ -3613,9 +4048,8 @@ dependencies = [ [[package]] name = "pallet-authority-discovery" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffb0208f0538d58dcb78ce1ff5e6e8641c5f37b23b20b05587e51da30ab13541" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-support", "frame-system", @@ -3629,9 +4063,8 @@ dependencies = [ [[package]] name = "pallet-authorship" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625d47577cabbe1318ccec5d612e2379002d1b6af1ab6edcef3243c66ec246df" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-support", "frame-system", @@ -3643,9 +4076,8 @@ dependencies = [ [[package]] name = "pallet-babe" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee096c0def13832475b340d00121025e0225de29604d44bc6dfcaa294c995b4" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-benchmarking", "frame-support", @@ -3667,9 +4099,8 @@ dependencies = [ [[package]] name = "pallet-balances" -version = "39.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c6945b078919acb14d126490e4b0973a688568b30142476ca69c6df2bed27ad" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "docify", "frame-benchmarking", @@ -3683,9 +4114,8 @@ dependencies = [ [[package]] name = "pallet-broker" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3043c90106d88cb93fcf0d9b6d19418f11f44cc2b11873414aec3b46044a24ea" +version = "0.6.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "bitvec", "frame-benchmarking", @@ -3701,180 +4131,143 @@ dependencies = [ ] [[package]] -name = "pallet-contracts" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5df77077745d891c822b4275f273f336077a97e69e62a30134776aa721c96fee" +name = "pallet-message-queue" +version = "31.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ - "bitflags 1.3.2", "environmental", "frame-benchmarking", "frame-support", "frame-system", - "impl-trait-for-tuples", "log", - "pallet-balances", - "pallet-contracts-proc-macro", - "pallet-contracts-uapi", "parity-scale-codec", - "paste", - "rand", "scale-info", - "serde", - "smallvec", - "sp-api", + "sp-arithmetic", "sp-core", "sp-io", "sp-runtime", - "sp-std", - "staging-xcm", - "staging-xcm-builder", - "wasm-instrument", - "wasmi", + "sp-weights", ] [[package]] -name = "pallet-contracts-mock-network" -version = "14.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "309666537ed001c61a99f59fa7b98680f4a6e4e361ed3bc64f7b0237da3e3e06" +name = "pallet-mmr" +version = "27.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ + "frame-benchmarking", "frame-support", "frame-system", - "pallet-assets", - "pallet-balances", - "pallet-contracts", - "pallet-contracts-proc-macro", - "pallet-contracts-uapi", - "pallet-insecure-randomness-collective-flip", - "pallet-message-queue", - "pallet-proxy", - "pallet-timestamp", - "pallet-utility", - "pallet-xcm", + "log", "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-parachains", "scale-info", - "sp-api", "sp-core", "sp-io", - "sp-keystore", - "sp-runtime", - "sp-tracing", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "xcm-simulator", -] - -[[package]] -name = "pallet-contracts-proc-macro" -version = "23.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94226cbd48516b7c310eb5dae8d50798c1ce73a7421dc0977c55b7fc2237a283" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.90", -] - -[[package]] -name = "pallet-contracts-uapi" -version = "12.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16f74b000590c33fadea48585d3ae3f4b7867e99f0a524c444d5779f36b9a1b6" -dependencies = [ - "bitflags 1.3.2", - "parity-scale-codec", - "paste", - "polkavm-derive 0.9.1", - "scale-info", -] - -[[package]] -name = "pallet-insecure-randomness-collective-flip" -version = "26.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dce7ad80675d78bd38a7a66ecbbf2d218dd32955e97f8e301d0afe6c87b0f251" -dependencies = [ - "frame-support", - "frame-system", - "parity-scale-codec", - "safe-mix", - "scale-info", + "sp-mmr-primitives", "sp-runtime", ] [[package]] -name = "pallet-message-queue" -version = "41.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "983f7d1be18e9a089a3e23670918f5085705b4403acd3fdde31878d57b76a1a8" +name = "pallet-revive" +version = "0.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ + "derive_more 0.99.18", "environmental", + "ethereum-types", "frame-benchmarking", "frame-support", "frame-system", + "hex", + "impl-trait-for-tuples", "log", + "pallet-revive-fixtures", + "pallet-revive-proc-macro", + "pallet-revive-uapi", + "pallet-transaction-payment", "parity-scale-codec", + "paste", + "polkavm", + "rlp", "scale-info", + "serde", + "sp-api", "sp-arithmetic", "sp-core", "sp-io", "sp-runtime", - "sp-weights", + "staging-xcm", + "staging-xcm-builder", + "subxt-signer", ] [[package]] -name = "pallet-mmr" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6932dfb85f77a57c2d1fdc28a7b3a59ffe23efd8d5bb02dc3039d91347e4a3b" +name = "pallet-revive-fixtures" +version = "0.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" +dependencies = [ + "anyhow", + "polkavm-linker", + "sp-core", + "sp-io", + "toml", +] + +[[package]] +name = "pallet-revive-mock-network" +version = "0.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ - "frame-benchmarking", "frame-support", "frame-system", - "log", + "pallet-assets", + "pallet-balances", + "pallet-message-queue", + "pallet-revive", + "pallet-revive-uapi", + "pallet-timestamp", + "pallet-xcm", "parity-scale-codec", + "polkadot-parachain-primitives", + "polkadot-primitives", + "polkadot-runtime-parachains", "scale-info", "sp-core", "sp-io", - "sp-mmr-primitives", "sp-runtime", + "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "staging-xcm", + "staging-xcm-builder", + "staging-xcm-executor", + "xcm-simulator", ] [[package]] -name = "pallet-proxy" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d39df395f0dbcf07dafe842916adea3266a87ce36ed87b5132184b6bcd746393" +name = "pallet-revive-proc-macro" +version = "0.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "parity-scale-codec", - "scale-info", - "sp-io", - "sp-runtime", + "proc-macro2", + "quote", + "syn 2.0.93", ] [[package]] name = "pallet-revive-uapi" version = "0.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk?tag=polkadot-stable2412-rc2#a86fb861573b31fb35db97d6ffe3eb4ff4a80359" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "bitflags 1.3.2", + "pallet-revive-proc-macro", + "parity-scale-codec", "paste", - "polkavm-derive 0.14.0", + "polkavm-derive", + "scale-info", ] [[package]] name = "pallet-session" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8474b62b6b7622f891e83d922a589e2ad5be5471f5ca47d45831a797dba0b3f4" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-support", "frame-system", @@ -3894,9 +4287,8 @@ dependencies = [ [[package]] name = "pallet-staking" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c870d123f4f053b56af808a4beae1ffc4309a696e829796c26837936c926db3b" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-benchmarking", "frame-election-provider-support", @@ -3916,9 +4308,8 @@ dependencies = [ [[package]] name = "pallet-timestamp" -version = "37.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9ba9b71bbfd33ae672f23ba7efaeed2755fdac37b8f946cb7474fc37841b7e1" +version = "27.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "docify", "frame-benchmarking", @@ -3930,37 +4321,21 @@ dependencies = [ "sp-inherents", "sp-io", "sp-runtime", - "sp-storage", + "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "sp-timestamp", ] [[package]] name = "pallet-transaction-payment" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b1aa3498107a30237f941b0f02180db3b79012c3488878ff01a4ac3e8ee04e" -dependencies = [ - "frame-support", - "frame-system", - "parity-scale-codec", - "scale-info", - "serde", - "sp-core", - "sp-io", - "sp-runtime", -] - -[[package]] -name = "pallet-utility" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fdcade6efc0b66fc7fc4138964802c02d0ffb7380d894e26b9dd5073727d2b3" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-benchmarking", "frame-support", "frame-system", "parity-scale-codec", "scale-info", + "serde", "sp-core", "sp-io", "sp-runtime", @@ -3968,9 +4343,8 @@ dependencies = [ [[package]] name = "pallet-vesting" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "807df2ef13ab6bf940879352c3013bfa00b670458b4c125c2f60e5753f68e3d5" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-benchmarking", "frame-support", @@ -3983,15 +4357,13 @@ dependencies = [ [[package]] name = "pallet-xcm" -version = "17.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "989676964dbda5f5275650fbdcd3894fe7fac626d113abf89d572b4952adcc36" +version = "7.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "bounded-collections", "frame-benchmarking", "frame-support", "frame-system", - "log", "pallet-balances", "parity-scale-codec", "scale-info", @@ -4132,7 +4504,7 @@ checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -4180,9 +4552,8 @@ dependencies = [ [[package]] name = "polkadot-core-primitives" -version = "15.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2900d3b857e34c480101618a950c3a4fbcddc8c0d50573d48553376185908b8" +version = "7.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "parity-scale-codec", "scale-info", @@ -4192,9 +4563,8 @@ dependencies = [ [[package]] name = "polkadot-parachain-primitives" -version = "14.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52b5648a2e8ce1f9a0f8c41c38def670cefd91932cd793468e1a5b0b0b4e4af1" +version = "6.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "bounded-collections", "derive_more 0.99.18", @@ -4209,9 +4579,8 @@ dependencies = [ [[package]] name = "polkadot-primitives" -version = "16.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bb20b75d33212150242d39890d7ededab55f1084160c337f15d0eb8ca8c3ad4" +version = "7.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "bitvec", "hex-literal", @@ -4232,26 +4601,26 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-staking", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "thiserror 1.0.69", ] [[package]] name = "polkadot-runtime-metrics" -version = "17.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c306f1ace7644a24de860479f92cf8d6467393bb0c9b0777c57e2d42c9d452a" +version = "7.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "bs58", "frame-benchmarking", "parity-scale-codec", "polkadot-primitives", - "sp-tracing", + "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", ] [[package]] name = "polkadot-runtime-parachains" -version = "17.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd58e3a17e5df678f5737b018cbfec603af2c93bec56bbb9f8fb8b2b017b54b1" +version = "7.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "bitflags 1.3.2", "bitvec", @@ -4291,7 +4660,7 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "staging-xcm", "staging-xcm-executor", ] @@ -4302,119 +4671,93 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eb819108697967452fa6d8d96ab4c0d48cbaa423b3156499dcb24f1cf95d6775" dependencies = [ - "sp-crypto-hashing", -] - -[[package]] -name = "polkavm-common" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d9428a5cfcc85c5d7b9fc4b6a18c4b802d0173d768182a51cc7751640f08b92" - -[[package]] -name = "polkavm-common" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "711952a783e9c5ad407cdacb1ed147f36d37c5d43417c1091d86456d2999417b" - -[[package]] -name = "polkavm-common" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f0dbafef4ab6ceecb4982ac3b550df430ef4f9fdbf07c108b7d4f91a0682fce" - -[[package]] -name = "polkavm-derive" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae8c4bea6f3e11cd89bb18bcdddac10bd9a24015399bd1c485ad68a985a19606" -dependencies = [ - "polkavm-derive-impl-macro 0.9.0", + "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "polkavm-derive" -version = "0.14.0" +name = "polkavm" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4832a0aebf6cefc988bb7b2d74ea8c86c983164672e2fc96300f356a1babfc1" +checksum = "dd044ab1d3b11567ab6b98ca71259a992b4034220d5972988a0e96518e5d343d" dependencies = [ - "polkavm-derive-impl-macro 0.14.0", + "libc", + "log", + "polkavm-assembler", + "polkavm-common", + "polkavm-linux-raw", ] [[package]] -name = "polkavm-derive" -version = "0.17.1" +name = "polkavm-assembler" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "206caf322dfc02144510ad8360ff2051e5072f0874dcab3b410f78cdd52d0ebb" +checksum = "eaad38dc420bfed79e6f731471c973ce5ff5e47ab403e63cf40358fef8a6368f" dependencies = [ - "polkavm-derive-impl-macro 0.17.0", + "log", ] [[package]] -name = "polkavm-derive-impl" -version = "0.9.0" +name = "polkavm-common" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c4fdfc49717fb9a196e74a5d28e0bc764eb394a2c803eb11133a31ac996c60c" +checksum = "31ff33982a807d8567645d4784b9b5d7ab87bcb494f534a57cadd9012688e102" dependencies = [ - "polkavm-common 0.9.0", - "proc-macro2", - "quote", - "syn 2.0.90", + "log", + "polkavm-assembler", ] [[package]] -name = "polkavm-derive-impl" -version = "0.14.0" +name = "polkavm-derive" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e339fc7c11310fe5adf711d9342278ac44a75c9784947937cce12bd4f30842f2" +checksum = "c2eb703f3b6404c13228402e98a5eae063fd16b8f58afe334073ec105ee4117e" dependencies = [ - "polkavm-common 0.14.0", - "proc-macro2", - "quote", - "syn 2.0.90", + "polkavm-derive-impl-macro", ] [[package]] name = "polkavm-derive-impl" -version = "0.17.0" +version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42565aed4adbc4034612d0b17dea8db3681fb1bd1aed040d6edc5455a9f478a1" +checksum = "2f2116a92e6e96220a398930f4c8a6cda1264206f3e2034fc9982bfd93f261f7" dependencies = [ - "polkavm-common 0.17.0", + "polkavm-common", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "polkavm-derive-impl-macro" -version = "0.9.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ba81f7b5faac81e528eb6158a6f3c9e0bb1008e0ffa19653bc8dea925ecb429" +checksum = "48c16669ddc7433e34c1007d31080b80901e3e8e523cb9d4b441c3910cf9294b" dependencies = [ - "polkavm-derive-impl 0.9.0", - "syn 2.0.90", + "polkavm-derive-impl", + "syn 2.0.93", ] [[package]] -name = "polkavm-derive-impl-macro" -version = "0.14.0" +name = "polkavm-linker" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b569754b15060d03000c09e3bf11509d527f60b75d79b4c30c3625b5071d9702" +checksum = "e9bfe793b094d9ea5c99b7c43ba46e277b0f8f48f4bbfdbabf8d3ebf701a4bd3" dependencies = [ - "polkavm-derive-impl 0.14.0", - "syn 2.0.90", + "dirs", + "gimli", + "hashbrown 0.14.5", + "log", + "object", + "polkavm-common", + "regalloc2", + "rustc-demangle", ] [[package]] -name = "polkavm-derive-impl-macro" -version = "0.17.0" +name = "polkavm-linux-raw" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86d9838e95241b0bce4fe269cdd4af96464160505840ed5a8ac8536119ba19e2" -dependencies = [ - "polkavm-derive-impl 0.17.0", - "syn 2.0.90", -] +checksum = "23eff02c070c70f31878a3d915e88a914ecf3e153741e2fb572dde28cce20fde" [[package]] name = "polling" @@ -4474,20 +4817,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64d1ec885c64d0457d564db4ec299b2dae3f9c02808b8ad9c3a089c591b18033" dependencies = [ "proc-macro2", - "syn 2.0.90", -] - -[[package]] -name = "primitive-types" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b34d9fd68ae0b74a41b21c03c2f62847aa0ffea044eee893b4c140b37e244e2" -dependencies = [ - "fixed-hash", - "impl-codec 0.6.0", - "impl-serde 0.4.0", - "scale-info", - "uint 0.9.5", + "syn 2.0.93", ] [[package]] @@ -4497,10 +4827,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d15600a7d856470b7d278b3fe0e311fe28c2526348549f8ef2ff7db3299c87f5" dependencies = [ "fixed-hash", - "impl-codec 0.7.0", - "impl-serde 0.5.0", + "impl-codec", + "impl-num-traits", + "impl-rlp", + "impl-serde", "scale-info", - "uint 0.10.0", + "uint", ] [[package]] @@ -4555,7 +4887,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -4566,7 +4898,7 @@ checksum = "834da187cfe638ae8abb0203f0b33e5ccdb02a28e7199f2f47b3e2754f50edca" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -4602,9 +4934,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.37" +version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" dependencies = [ "proc-macro2", ] @@ -4651,15 +4983,46 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" +[[package]] +name = "rayon" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + [[package]] name = "redox_syscall" -version = "0.5.7" +version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" +checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" dependencies = [ "bitflags 2.6.0", ] +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom", + "libredox", + "thiserror 1.0.69", +] + [[package]] name = "ref-cast" version = "1.0.23" @@ -4677,7 +5040,20 @@ checksum = "bcc303e793d3734489387d205e9b186fac9c6cfacedd98cbb2e8a5943595f3e6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", +] + +[[package]] +name = "regalloc2" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad156d539c879b7a24a363a2016d77961786e71f48f2e2fc8302a92abd2429a6" +dependencies = [ + "hashbrown 0.13.2", + "log", + "rustc-hash 1.1.0", + "slice-group-by", + "smallvec", ] [[package]] @@ -4734,6 +5110,23 @@ dependencies = [ "subtle", ] +[[package]] +name = "ring" +version = "0.1.0" +source = "git+https://github.com/w3f/ring-proof?rev=665f5f5#665f5f51af5734c7b6d90b985dd6861d4c5b4752" +dependencies = [ + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-poly 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "arrayvec 0.7.6", + "blake2", + "common", + "fflonk", + "merlin", +] + [[package]] name = "ring" version = "0.17.8" @@ -4750,10 +5143,23 @@ dependencies = [ ] [[package]] -name = "rlibc" -version = "1.0.0" +name = "ripemd" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc874b127765f014d792f16763a81245ab80500e2ad921ed4ee9e82481ee08fe" +checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "rlp" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa24e92bb2a83198bb76d661a71df9f7076b8c420b8696e4d3d97d50d94479e3" +dependencies = [ + "bytes", + "rustc-hex", +] [[package]] name = "rustc-demangle" @@ -4761,6 +5167,12 @@ version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + [[package]] name = "rustc-hash" version = "2.1.0" @@ -4773,46 +5185,37 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e75f6a532d0fd9f7f13144f392b6ad56a32696bfcd9c78f797f16bbb6f072d6" -[[package]] -name = "rustc_version" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -dependencies = [ - "semver 0.9.0", -] - [[package]] name = "rustc_version" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" dependencies = [ - "semver 1.0.23", + "semver", ] [[package]] name = "rustix" -version = "0.38.41" +version = "0.38.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7f649912bc1495e167a6edee79151c84b1bad49748cb4f1f1167f459f6224f6" +checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85" dependencies = [ "bitflags 2.6.0", "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] name = "rustls" -version = "0.23.19" +version = "0.23.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "934b404430bb06b3fae2cba809eb45a1ab1aecd64491213d7c3301b88393f8d1" +checksum = "5065c3f250cbd332cd894be57c40fa52387247659b14a2d6041d121547903b1b" dependencies = [ "log", "once_cell", - "ring", + "ring 0.17.8", "rustls-pki-types", "rustls-webpki", "subtle", @@ -4843,9 +5246,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.10.0" +version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16f1201b3c9a7ee8039bcadc17b7e605e2945b27eee7631788c1bd2b0643674b" +checksum = "d2bf47e6ff922db3825eb750c4e2ff784c6ff8fb9e13046ef6a1d1c5401b0b37" [[package]] name = "rustls-platform-verifier" @@ -4880,16 +5283,16 @@ version = "0.102.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" dependencies = [ - "ring", + "ring 0.17.8", "rustls-pki-types", "untrusted", ] [[package]] name = "rustversion" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e819f2bc632f285be6d7cd36e25940d45b2391dd6d9b939e79de557f7014248" +checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4" [[package]] name = "ruzstd" @@ -4907,20 +5310,11 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" -[[package]] -name = "safe-mix" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d3d055a2582e6b00ed7a31c1524040aa391092bf636328350813f3a0605215c" -dependencies = [ - "rustc_version 0.2.3", -] - [[package]] name = "safe_arch" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3460605018fdc9612bce72735cba0d27efbcd9904780d44c7e3a9948f96148a" +checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323" dependencies = [ "bytemuck", ] @@ -4963,7 +5357,7 @@ checksum = "f8ae9cc099ae85ff28820210732b00f019546f36f33225f509fe25d5816864a0" dependencies = [ "derive_more 1.0.0", "parity-scale-codec", - "primitive-types 0.13.1", + "primitive-types", "scale-bits", "scale-decode-derive", "scale-type-resolver", @@ -4979,7 +5373,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -4990,7 +5384,7 @@ checksum = "5f9271284d05d0749c40771c46180ce89905fd95aa72a2a2fddb4b7c0aa424db" dependencies = [ "derive_more 1.0.0", "parity-scale-codec", - "primitive-types 0.13.1", + "primitive-types", "scale-bits", "scale-encode-derive", "scale-type-resolver", @@ -5007,7 +5401,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -5034,7 +5428,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -5056,7 +5450,7 @@ dependencies = [ "proc-macro2", "quote", "scale-info", - "syn 2.0.90", + "syn 2.0.93", "thiserror 1.0.69", ] @@ -5110,7 +5504,7 @@ dependencies = [ "proc-macro2", "quote", "serde_derive_internals", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -5149,12 +5543,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" -[[package]] -name = "scratch" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3cf7c11c38cb994f3d40e8a8cde3bbd1f72a435e4c49e85d6553d8312306152" - [[package]] name = "scrypt" version = "0.11.0" @@ -5254,9 +5642,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.12.1" +version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa39c7303dc58b5543c94d22c1766b0d31f2ee58306363ea622b10bbc075eaa2" +checksum = "1863fd3768cd83c56a7f60faa4dc0d403f1b6df0a38c3c25f44b7894e45370d5" dependencies = [ "core-foundation-sys", "libc", @@ -5264,33 +5652,18 @@ dependencies = [ [[package]] name = "semver" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -dependencies = [ - "semver-parser", -] - -[[package]] -name = "semver" -version = "1.0.23" +version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" +checksum = "3cb6eb87a131f756572d7fb904f6e7b68633f09cca868c5df1c4b8d1a694bbba" dependencies = [ "serde", ] -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" - [[package]] name = "serde" -version = "1.0.215" +version = "1.0.217" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" +checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70" dependencies = [ "serde_derive", ] @@ -5306,13 +5679,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.215" +version = "1.0.217" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" +checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -5323,14 +5696,14 @@ checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "serde_json" -version = "1.0.133" +version = "1.0.134" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" +checksum = "d00f4175c42ee48b15416f6193a959ba3a0d67fc699a0db9ad12df9f83991c7d" dependencies = [ "itoa", "memchr", @@ -5346,7 +5719,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -5372,9 +5745,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.11.0" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e28bdad6db2b8340e449f7108f020b3b092e8583a9e3fb82713e1d4e71fe817" +checksum = "d6b6f7f2fcb69f747921f79f3926bd1e203fce4fef62c268dd3abfb6d86029aa" dependencies = [ "base64 0.22.1", "chrono", @@ -5439,7 +5812,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60" dependencies = [ "digest 0.10.7", - "keccak", + "keccak 0.1.5", +] + +[[package]] +name = "sha3" +version = "0.11.0-pre.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e485881f388c2818d709796dc883c1ffcadde9d1f0e054f3a5c14974185261a6" +dependencies = [ + "digest 0.11.0-pre.9", + "keccak 0.2.0-pre.0", ] [[package]] @@ -5541,6 +5924,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "slice-group-by" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "826167069c09b99d56f31e9ae5c99049e932a98c9dc2dac47645b08dbbf76ba7" + [[package]] name = "smallvec" version = "1.13.2" @@ -5607,7 +5996,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.10.8", - "sha3", + "sha3 0.10.8", "siphasher", "slab", "smallvec", @@ -5681,9 +6070,8 @@ dependencies = [ [[package]] name = "sp-api" -version = "34.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbce492e0482134128b7729ea36f5ef1a9f9b4de2d48ff8dde7b5e464e28ce75" +version = "26.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "docify", "hash-db", @@ -5692,10 +6080,10 @@ dependencies = [ "scale-info", "sp-api-proc-macro", "sp-core", - "sp-externalities", + "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "sp-metadata-ir", "sp-runtime", - "sp-runtime-interface", + "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "sp-state-machine", "sp-trie", "sp-version", @@ -5704,9 +6092,8 @@ dependencies = [ [[package]] name = "sp-api-proc-macro" -version = "20.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9aadf9e97e694f0e343978aa632938c5de309cbcc8afed4136cb71596737278" +version = "15.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "Inflector", "blake2", @@ -5714,14 +6101,13 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "sp-application-crypto" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8133012faa5f75b2f0b1619d9f720c1424ac477152c143e5f7dbde2fe1a958" +version = "30.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "parity-scale-codec", "scale-info", @@ -5732,9 +6118,8 @@ dependencies = [ [[package]] name = "sp-arithmetic" -version = "26.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46d0d0a4c591c421d3231ddd5e27d828618c24456d51445d21a1f79fcee97c23" +version = "23.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "docify", "integer-sqrt", @@ -5742,15 +6127,31 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-std", "static_assertions", ] +[[package]] +name = "sp-ark-bls12-381" +version = "0.4.2" +source = "git+https://github.com/paritytech/arkworks-substrate#caa2eed74beb885dd07c7db5f916f2281dad818f" +dependencies = [ + "ark-bls12-381-ext", + "sp-crypto-ec-utils", +] + +[[package]] +name = "sp-ark-ed-on-bls12-381-bandersnatch" +version = "0.4.2" +source = "git+https://github.com/paritytech/arkworks-substrate#caa2eed74beb885dd07c7db5f916f2281dad818f" +dependencies = [ + "ark-ed-on-bls12-381-bandersnatch-ext", + "sp-crypto-ec-utils", +] + [[package]] name = "sp-authority-discovery" -version = "34.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "519c33af0e25ba2dd2eb3790dc404d634b6e4ce0801bcc8fa3574e07c365e734" +version = "26.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "parity-scale-codec", "scale-info", @@ -5761,9 +6162,8 @@ dependencies = [ [[package]] name = "sp-consensus-babe" -version = "0.40.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36ee95e17ee8dcd14db7d584b899a426565ca9abe5a266ab82277977fc547f86" +version = "0.32.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "async-trait", "parity-scale-codec", @@ -5780,9 +6180,8 @@ dependencies = [ [[package]] name = "sp-consensus-slots" -version = "0.40.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbafb7ed44f51c22fa277fb39b33dc601fa426133a8e2b53f3f46b10f07fba43" +version = "0.32.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "parity-scale-codec", "scale-info", @@ -5792,11 +6191,11 @@ dependencies = [ [[package]] name = "sp-core" -version = "34.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c961a5e33fb2962fa775c044ceba43df9c6f917e2c35d63bfe23738468fa76a7" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "array-bytes", + "bandersnatch_vrfs", "bitflags 1.3.2", "blake2", "bounded-collections", @@ -5806,7 +6205,7 @@ dependencies = [ "futures", "hash-db", "hash256-std-hasher", - "impl-serde 0.4.0", + "impl-serde", "itertools 0.11.0", "k256", "libsecp256k1", @@ -5816,19 +6215,19 @@ dependencies = [ "parity-scale-codec", "parking_lot", "paste", - "primitive-types 0.12.2", + "primitive-types", "rand", "scale-info", "schnorrkel", "secp256k1 0.28.2", "secrecy 0.8.0", "serde", - "sp-crypto-hashing", - "sp-debug-derive", - "sp-externalities", - "sp-runtime-interface", - "sp-std", - "sp-storage", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "ss58-registry", "substrate-bip39", "thiserror 1.0.69", @@ -5837,6 +6236,26 @@ dependencies = [ "zeroize", ] +[[package]] +name = "sp-crypto-ec-utils" +version = "0.10.0" +source = "git+https://github.com/paritytech/polkadot-sdk#e051f3edd3d6a0699a9261c8f8985d2e8e95c276" +dependencies = [ + "ark-bls12-377", + "ark-bls12-377-ext", + "ark-bls12-381", + "ark-bls12-381-ext", + "ark-bw6-761", + "ark-bw6-761-ext", + "ark-ec 0.4.2", + "ark-ed-on-bls12-377", + "ark-ed-on-bls12-377-ext", + "ark-ed-on-bls12-381-bandersnatch", + "ark-ed-on-bls12-381-bandersnatch-ext", + "ark-scale", + "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk)", +] + [[package]] name = "sp-crypto-hashing" version = "0.1.0" @@ -5847,48 +6266,77 @@ dependencies = [ "byteorder", "digest 0.10.7", "sha2 0.10.8", - "sha3", + "sha3 0.10.8", + "twox-hash", +] + +[[package]] +name = "sp-crypto-hashing" +version = "0.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" +dependencies = [ + "blake2b_simd", + "byteorder", + "digest 0.10.7", + "sha2 0.10.8", + "sha3 0.10.8", "twox-hash", ] [[package]] name = "sp-crypto-hashing-proc-macro" version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b85d0f1f1e44bd8617eb2a48203ee854981229e3e79e6f468c7175d5fd37489b" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "quote", - "sp-crypto-hashing", - "syn 2.0.90", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "syn 2.0.93", ] [[package]] name = "sp-debug-derive" version = "14.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48d09fa0a5f7299fb81ee25ae3853d26200f7a348148aed6de76be905c007dbe" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.93", +] + +[[package]] +name = "sp-debug-derive" +version = "14.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#e051f3edd3d6a0699a9261c8f8985d2e8e95c276" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "sp-externalities" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a904407d61cb94228c71b55a9d3708e9d6558991f9e83bd42bd91df37a159d30" +version = "0.25.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" +dependencies = [ + "environmental", + "parity-scale-codec", + "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", +] + +[[package]] +name = "sp-externalities" +version = "0.25.0" +source = "git+https://github.com/paritytech/polkadot-sdk#e051f3edd3d6a0699a9261c8f8985d2e8e95c276" dependencies = [ "environmental", "parity-scale-codec", - "sp-storage", + "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk)", ] [[package]] name = "sp-genesis-builder" -version = "0.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a646ed222fd86d5680faa4a8967980eb32f644cae6c8523e1c689a6deda3e8" +version = "0.8.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "parity-scale-codec", "scale-info", @@ -5899,9 +6347,8 @@ dependencies = [ [[package]] name = "sp-inherents" -version = "34.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afffbddc380d99a90c459ba1554bbbc01d62e892de9f1485af6940b89c4c0d57" +version = "26.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "async-trait", "impl-trait-for-tuples", @@ -5913,9 +6360,8 @@ dependencies = [ [[package]] name = "sp-io" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ef7eb561bb4839cc8424ce58c5ea236cbcca83f26fcc0426d8decfe8aa97d4" +version = "30.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "bytes", "docify", @@ -5923,16 +6369,16 @@ dependencies = [ "libsecp256k1", "log", "parity-scale-codec", - "polkavm-derive 0.9.1", + "polkavm-derive", "rustversion", "secp256k1 0.28.2", "sp-core", - "sp-crypto-hashing", - "sp-externalities", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "sp-keystore", - "sp-runtime-interface", + "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "sp-state-machine", - "sp-tracing", + "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "sp-trie", "tracing", "tracing-core", @@ -5940,43 +6386,39 @@ dependencies = [ [[package]] name = "sp-keyring" -version = "39.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c0e20624277f578b27f44ecfbe2ebc2e908488511ee2c900c5281599f700ab3" +version = "31.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "sp-core", "sp-runtime", - "strum 0.26.3", + "strum", ] [[package]] name = "sp-keystore" -version = "0.40.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0248b4d784cb4a01472276928977121fa39d977a5bb24793b6b15e64b046df42" +version = "0.34.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "parity-scale-codec", "parking_lot", "sp-core", - "sp-externalities", + "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", ] [[package]] name = "sp-metadata-ir" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a616fa51350b35326682a472ee8e6ba742fdacb18babac38ecd46b3e05ead869" +version = "0.6.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ - "frame-metadata 16.0.0", + "frame-metadata 18.0.0", "parity-scale-codec", "scale-info", ] [[package]] name = "sp-mmr-primitives" -version = "34.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a12dd76e368f1e48144a84b4735218b712f84b3f976970e2f25a29b30440e10" +version = "26.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "log", "parity-scale-codec", @@ -5985,16 +6427,15 @@ dependencies = [ "serde", "sp-api", "sp-core", - "sp-debug-derive", + "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "sp-runtime", "thiserror 1.0.69", ] [[package]] name = "sp-npos-elections" -version = "34.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af922f112c7c1ed199eabe14f12a82ceb75e1adf0804870eccfbcf3399492847" +version = "26.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "parity-scale-codec", "scale-info", @@ -6007,20 +6448,18 @@ dependencies = [ [[package]] name = "sp-panic-handler" version = "13.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8f5a17a0a11de029a8b811cb6e8b32ce7e02183cc04a3e965c383246798c416" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "backtrace", - "lazy_static", "regex", ] [[package]] name = "sp-runtime" -version = "39.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "658f23be7c79a85581029676a73265c107c5469157e3444c8c640fdbaa8bfed0" +version = "31.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ + "binary-merkle-tree", "docify", "either", "hash256-std-hasher", @@ -6037,50 +6476,81 @@ dependencies = [ "sp-arithmetic", "sp-core", "sp-io", - "sp-std", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-trie", "sp-weights", "tracing", + "tuplex", ] [[package]] name = "sp-runtime-interface" -version = "28.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985eb981f40c689c6a0012c937b68ed58dabb4341d06f2dfe4dfd5ed72fa4017" +version = "24.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" +dependencies = [ + "bytes", + "impl-trait-for-tuples", + "parity-scale-codec", + "polkavm-derive", + "primitive-types", + "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-runtime-interface-proc-macro 17.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", + "static_assertions", +] + +[[package]] +name = "sp-runtime-interface" +version = "24.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#e051f3edd3d6a0699a9261c8f8985d2e8e95c276" dependencies = [ "bytes", "impl-trait-for-tuples", "parity-scale-codec", - "polkavm-derive 0.9.1", - "primitive-types 0.12.2", - "sp-externalities", - "sp-runtime-interface-proc-macro", - "sp-std", - "sp-storage", - "sp-tracing", - "sp-wasm-interface", + "polkavm-derive", + "primitive-types", + "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-runtime-interface-proc-macro 17.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk)", "static_assertions", ] [[package]] name = "sp-runtime-interface-proc-macro" -version = "18.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0195f32c628fee3ce1dfbbf2e7e52a30ea85f3589da9fe62a8b816d70fc06294" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" +dependencies = [ + "Inflector", + "expander", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.93", +] + +[[package]] +name = "sp-runtime-interface-proc-macro" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#e051f3edd3d6a0699a9261c8f8985d2e8e95c276" dependencies = [ "Inflector", "expander", "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "sp-session" -version = "36.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00a3a307fedc423fb8cd2a7726a3bbb99014f1b4b52f26153993e2aae3338fe6" +version = "27.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "parity-scale-codec", "scale-info", @@ -6093,9 +6563,8 @@ dependencies = [ [[package]] name = "sp-staking" -version = "36.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a73eedb4b85f4cd420d31764827546aa22f82ce1646d0fd258993d051de7a90" +version = "26.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", @@ -6107,9 +6576,8 @@ dependencies = [ [[package]] name = "sp-state-machine" -version = "0.43.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "930104d6ae882626e8880d9b1578da9300655d337a3ffb45e130c608b6c89660" +version = "0.35.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "hash-db", "log", @@ -6118,7 +6586,7 @@ dependencies = [ "rand", "smallvec", "sp-core", - "sp-externalities", + "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "sp-panic-handler", "sp-trie", "thiserror 1.0.69", @@ -6129,27 +6597,41 @@ dependencies = [ [[package]] name = "sp-std" version = "14.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f8ee986414b0a9ad741776762f4083cd3a5128449b982a3919c4df36874834" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" + +[[package]] +name = "sp-std" +version = "14.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#e051f3edd3d6a0699a9261c8f8985d2e8e95c276" [[package]] name = "sp-storage" -version = "21.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99c82989b3a4979a7e1ad848aad9f5d0b4388f1f454cc131766526601ab9e8f8" +version = "19.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" +dependencies = [ + "impl-serde", + "parity-scale-codec", + "ref-cast", + "serde", + "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", +] + +[[package]] +name = "sp-storage" +version = "19.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#e051f3edd3d6a0699a9261c8f8985d2e8e95c276" dependencies = [ - "impl-serde 0.4.0", + "impl-serde", "parity-scale-codec", "ref-cast", "serde", - "sp-debug-derive", + "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk)", ] [[package]] name = "sp-timestamp" -version = "34.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72a1cb4df653d62ccc0dbce1db45d1c9443ec60247ee9576962d24da4c9c6f07" +version = "26.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "async-trait", "parity-scale-codec", @@ -6160,9 +6642,19 @@ dependencies = [ [[package]] name = "sp-tracing" -version = "17.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf641a1d17268c8fcfdb8e0fa51a79c2d4222f4cfda5f3944dbdbc384dced8d5" +version = "16.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" +dependencies = [ + "parity-scale-codec", + "tracing", + "tracing-core", + "tracing-subscriber", +] + +[[package]] +name = "sp-tracing" +version = "16.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#e051f3edd3d6a0699a9261c8f8985d2e8e95c276" dependencies = [ "parity-scale-codec", "tracing", @@ -6172,13 +6664,11 @@ dependencies = [ [[package]] name = "sp-trie" -version = "37.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6282aef9f4b6ecd95a67a45bcdb67a71f4a4155c09a53c10add4ffe823db18cd" +version = "29.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "ahash", "hash-db", - "lazy_static", "memory-db", "nohash-hasher", "parity-scale-codec", @@ -6187,7 +6677,7 @@ dependencies = [ "scale-info", "schnellru", "sp-core", - "sp-externalities", + "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "thiserror 1.0.69", "tracing", "trie-db", @@ -6196,39 +6686,48 @@ dependencies = [ [[package]] name = "sp-version" -version = "37.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d521a405707b5be561367cd3d442ff67588993de24062ce3adefcf8437ee9fe1" +version = "29.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ - "impl-serde 0.4.0", + "impl-serde", "parity-scale-codec", "parity-wasm", "scale-info", "serde", "sp-crypto-hashing-proc-macro", "sp-runtime", - "sp-std", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "sp-version-proc-macro", "thiserror 1.0.69", ] [[package]] name = "sp-version-proc-macro" -version = "14.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aee8f6730641a65fcf0c8f9b1e448af4b3bb083d08058b47528188bccc7b7a7" +version = "13.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "parity-scale-codec", + "proc-macro-warning", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "sp-wasm-interface" -version = "21.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b066baa6d57951600b14ffe1243f54c47f9c23dd89c262e17ca00ae8dca58be9" +version = "20.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" +dependencies = [ + "anyhow", + "impl-trait-for-tuples", + "log", + "parity-scale-codec", +] + +[[package]] +name = "sp-wasm-interface" +version = "20.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#e051f3edd3d6a0699a9261c8f8985d2e8e95c276" dependencies = [ "anyhow", "impl-trait-for-tuples", @@ -6238,9 +6737,8 @@ dependencies = [ [[package]] name = "sp-weights" -version = "31.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93cdaf72a1dad537bbb130ba4d47307ebe5170405280ed1aa31fa712718a400e" +version = "27.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "bounded-collections", "parity-scale-codec", @@ -6248,7 +6746,7 @@ dependencies = [ "serde", "smallvec", "sp-arithmetic", - "sp-debug-derive", + "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", ] [[package]] @@ -6290,14 +6788,15 @@ checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" [[package]] name = "staging-xcm" -version = "14.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96bee7cd999e9cdf10f8db72342070d456e21e82a0f5962ff3b87edbd5f2b20e" +version = "7.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "array-bytes", "bounded-collections", "derivative", "environmental", + "frame-support", + "hex-literal", "impl-trait-for-tuples", "log", "parity-scale-codec", @@ -6310,9 +6809,8 @@ dependencies = [ [[package]] name = "staging-xcm-builder" -version = "17.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3746adbbae27b1e6763f0cca622e15482ebcb94835a9e078c212dd7be896e35" +version = "7.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-support", "frame-system", @@ -6333,9 +6831,8 @@ dependencies = [ [[package]] name = "staging-xcm-executor" -version = "17.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79dd0c5332a5318e58f0300b20768b71cf9427c906f94a743c9dc7c3ee9e7fa9" +version = "7.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "environmental", "frame-benchmarking", @@ -6366,7 +6863,6 @@ checksum = "1c6a0d765f5807e98a091107bae0a56ea3799f66a5de47b2c84c94a39c09974e" dependencies = [ "cfg-if", "hashbrown 0.14.5", - "serde", ] [[package]] @@ -6375,32 +6871,13 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" -[[package]] -name = "strum" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f" - [[package]] name = "strum" version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" dependencies = [ - "strum_macros 0.26.4", -] - -[[package]] -name = "strum_macros" -version = "0.24.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e385be0d24f186b4ce2f9982191e7101bb737312ad61c1f2f984f34bcf85d59" -dependencies = [ - "heck 0.4.1", - "proc-macro2", - "quote", - "rustversion", - "syn 1.0.109", + "strum_macros", ] [[package]] @@ -6409,18 +6886,17 @@ version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" dependencies = [ - "heck 0.5.0", + "heck", "proc-macro2", "quote", "rustversion", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "substrate-bip39" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca58ffd742f693dc13d69bdbb2e642ae239e0053f6aab3b104252892f856700a" +version = "0.4.7" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "hmac 0.12.1", "pbkdf2", @@ -6447,11 +6923,11 @@ dependencies = [ "frame-metadata 17.0.0", "futures", "hex", - "impl-serde 0.5.0", + "impl-serde", "jsonrpsee", "parity-scale-codec", "polkadot-sdk", - "primitive-types 0.13.1", + "primitive-types", "scale-bits", "scale-decode", "scale-encode", @@ -6478,14 +6954,14 @@ version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3cfcfb7d9589f3df0ac87c4988661cf3fb370761fcb19f2fd33104cc59daf22a" dependencies = [ - "heck 0.5.0", + "heck", "parity-scale-codec", "proc-macro2", "quote", "scale-info", "scale-typegen", "subxt-metadata", - "syn 2.0.90", + "syn 2.0.93", "thiserror 1.0.69", ] @@ -6502,11 +6978,11 @@ dependencies = [ "frame-metadata 17.0.0", "hashbrown 0.14.5", "hex", - "impl-serde 0.5.0", + "impl-serde", "keccak-hash", "parity-scale-codec", "polkadot-sdk", - "primitive-types 0.13.1", + "primitive-types", "scale-bits", "scale-decode", "scale-encode", @@ -6548,7 +7024,7 @@ dependencies = [ "scale-typegen", "subxt-codegen", "subxt-utils-fetchmetadata", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -6572,11 +7048,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e7a336d6a1f86f126100a4a717be58352de4c8214300c4f7807f974494efdb9" dependencies = [ "base64 0.22.1", + "bip32", "bip39", "cfg-if", "crypto_secretbox", "hex", "hmac 0.12.1", + "keccak-hash", "parity-scale-codec", "pbkdf2", "polkadot-sdk", @@ -6616,9 +7094,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.90" +version = "2.0.93" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31" +checksum = "9c786062daee0d6db1132800e623df74274a0a87322d8e183338e01b3d98d058" dependencies = [ "proc-macro2", "quote", @@ -6633,7 +7111,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -6700,11 +7178,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.4" +version = "2.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f49a1853cf82743e3b7950f77e0f4d622ca36cf4317cba00c767838bac8d490" +checksum = "f072643fd0190df67a8bab670c20ef5d8737177d6ac6b2e9a236cb096206b2cc" dependencies = [ - "thiserror-impl 2.0.4", + "thiserror-impl 2.0.9", ] [[package]] @@ -6715,18 +7193,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "thiserror-impl" -version = "2.0.4" +version = "2.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8381894bb3efe0c4acac3ded651301ceee58a15d47c2e34885ed1908ad667061" +checksum = "7b50fa271071aae2e6ee85f842e2e28ba8cd2c5fb67f11fcb1fd70b276f9e7d4" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -6791,9 +7269,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.8.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938" +checksum = "022db8904dfa342efe721985167e9fcd16c29b226db4397ed752a761cfce81e8" dependencies = [ "tinyvec_macros", ] @@ -6828,25 +7306,24 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "tokio-rustls" -version = "0.26.0" +version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" +checksum = "5f6d0975eaace0cf0fcadee4e4aaa5da15b5c079146f2cffb67c113be122bf37" dependencies = [ "rustls", - "rustls-pki-types", "tokio", ] [[package]] name = "tokio-stream" -version = "0.1.16" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f4e6ce100d0eb49a2734f8c0812bcd324cf357d21810932c5df6b96ef2b86f1" +checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047" dependencies = [ "futures-core", "pin-project-lite", @@ -6927,7 +7404,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -7019,6 +7496,12 @@ version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4f195fd851901624eee5a58c4bb2b4f06399148fcd0ed336e6f1cb60a9881df" +[[package]] +name = "tuplex" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "676ac81d5454c4dcf37955d34fa8626ede3490f744b86ca14a7b90168d2a08aa" + [[package]] name = "twox-hash" version = "1.6.3" @@ -7037,18 +7520,6 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" -[[package]] -name = "uint" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76f64bba2c53b04fcab63c01a7d7427eadc821e3bc48c34dc9ba29c501164b52" -dependencies = [ - "byteorder", - "crunchy", - "hex", - "static_assertions", -] - [[package]] name = "uint" version = "0.10.0" @@ -7076,18 +7547,6 @@ dependencies = [ "tinyvec", ] -[[package]] -name = "unicode-width" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" - -[[package]] -name = "unicode-width" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" - [[package]] name = "unicode-xid" version = "0.2.6" @@ -7100,7 +7559,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" dependencies = [ - "crypto-common", + "crypto-common 0.1.6", "subtle", ] @@ -7170,10 +7629,10 @@ checksum = "70a3028804c8bbae2a97a15b71ffc0e308c4b01a520994aafa77d56e94e19024" dependencies = [ "ark-bls12-377", "ark-bls12-381", - "ark-ec", - "ark-ff", - "ark-serialize", - "ark-serialize-derive", + "ark-ec 0.4.2", + "ark-ff 0.4.2", + "ark-serialize 0.4.2", + "ark-serialize-derive 0.4.2", "arrayref", "constcat", "digest 0.10.7", @@ -7181,7 +7640,7 @@ dependencies = [ "rand_chacha", "rand_core", "sha2 0.10.8", - "sha3", + "sha3 0.10.8", "thiserror 1.0.69", "zeroize", ] @@ -7213,9 +7672,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.97" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d15e63b4482863c109d70a7b8706c1e364eb6ea449b201a76c5b89cedcec2d5c" +checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396" dependencies = [ "cfg-if", "once_cell", @@ -7224,24 +7683,23 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.97" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d36ef12e3aaca16ddd3f67922bc63e48e953f126de60bd33ccc0101ef9998cd" +checksum = "5f89bb38646b4f81674e8f5c3fb81b562be1fd936d84320f3264486418519c79" dependencies = [ "bumpalo", "log", - "once_cell", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.47" +version = "0.4.49" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dfaf8f50e5f293737ee323940c7d8b08a66a95a419223d9f41610ca08b0833d" +checksum = "38176d9b44ea84e9184eff0bc34cc167ed044f816accfe5922e54d84cf48eca2" dependencies = [ "cfg-if", "js-sys", @@ -7252,9 +7710,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.97" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "705440e08b42d3e4b36de7d66c944be628d579796b8090bfa3471478a2260051" +checksum = "2cc6181fd9a7492eef6fef1f33961e3695e4579b9872a6f7c83aee556666d4fe" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -7262,91 +7720,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.97" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98c9ae5a76e46f4deecd0f0255cc223cfa18dc9b261213b8aa0c7b36f61b3f1d" +checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.97" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ee99da9c5ba11bd675621338ef6fa52296b76b83305e9b6e5c77d4c286d6d49" - -[[package]] -name = "wasm-encoder" -version = "0.220.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebf48234b389415b226a4daef6562933d38c7b28a8b8f64c5c4130dad1561ab7" -dependencies = [ - "leb128", - "wasmparser 0.220.0", -] - -[[package]] -name = "wasm-encoder" -version = "0.221.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c17a3bd88f2155da63a1f2fcb8a56377a24f0b6dfed12733bb5f544e86f690c5" -dependencies = [ - "leb128", - "wasmparser 0.221.2", -] - -[[package]] -name = "wasm-instrument" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a47ecb37b9734d1085eaa5ae1a81e60801fd8c28d4cabdd8aedb982021918bc" -dependencies = [ - "parity-wasm", -] - -[[package]] -name = "wasm-opt" -version = "0.116.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fd87a4c135535ffed86123b6fb0f0a5a0bc89e50416c942c5f0662c645f679c" -dependencies = [ - "anyhow", - "libc", - "strum 0.24.1", - "strum_macros 0.24.3", - "tempfile", - "thiserror 1.0.69", - "wasm-opt-cxx-sys", - "wasm-opt-sys", -] - -[[package]] -name = "wasm-opt-cxx-sys" -version = "0.116.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c57b28207aa724318fcec6575fe74803c23f6f266fce10cbc9f3f116762f12e" -dependencies = [ - "anyhow", - "cxx", - "cxx-build", - "wasm-opt-sys", -] - -[[package]] -name = "wasm-opt-sys" -version = "0.116.0" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a1cce564dc768dacbdb718fc29df2dba80bd21cb47d8f77ae7e3d95ceb98cbe" -dependencies = [ - "anyhow", - "cc", - "cxx", - "cxx-build", -] +checksum = "943aab3fdaaa029a6e0271b35ea10b72b943135afe9bffca82384098ad0e06a6" [[package]] name = "wasmi" @@ -7398,21 +7787,10 @@ dependencies = [ "bitflags 2.6.0", "hashbrown 0.14.5", "indexmap 2.7.0", - "semver 1.0.23", + "semver", "serde", ] -[[package]] -name = "wasmparser" -version = "0.221.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9845c470a2e10b61dd42c385839cdd6496363ed63b5c9e420b5488b77bd22083" -dependencies = [ - "bitflags 2.6.0", - "indexmap 2.7.0", - "semver 1.0.23", -] - [[package]] name = "wasmparser-nostd" version = "0.100.2" @@ -7422,33 +7800,11 @@ dependencies = [ "indexmap-nostd", ] -[[package]] -name = "wast" -version = "221.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcc4470b9de917ba199157d1f0ae104f2ae362be728c43e68c571c7715bd629e" -dependencies = [ - "bumpalo", - "leb128", - "memchr", - "unicode-width 0.2.0", - "wasm-encoder 0.221.2", -] - -[[package]] -name = "wat" -version = "1.221.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1f3c6d82af47286494c6caea1d332037f5cbeeac82bbf5ef59cb8c201c466e" -dependencies = [ - "wast", -] - [[package]] name = "web-sys" -version = "0.3.74" +version = "0.3.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a98bc3c33f0fe7e59ad7cd041b89034fa82a7c2d4365ca538dda6cdaf513863c" +checksum = "04dd7223427d52553d3702c004d3b2fe07c148165faa56313cb00211e31c12bc" dependencies = [ "js-sys", "wasm-bindgen", @@ -7475,12 +7831,12 @@ dependencies = [ [[package]] name = "which" -version = "7.0.0" +version = "7.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9cad3279ade7346b96e38731a641d7343dd6a53d55083dd54eadfa5a1b38c6b" +checksum = "fb4a9e33648339dc1642b0e36e21b3385e6148e289226f657c809dee59df5028" dependencies = [ "either", - "home", + "env_home", "rustix", "winsafe", ] @@ -7733,21 +8089,19 @@ dependencies = [ [[package]] name = "xcm-procedural" -version = "10.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87fb4f14094d65c500a59bcf540cf42b99ee82c706edd6226a92e769ad60563e" +version = "7.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "Inflector", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "xcm-runtime-apis" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69d4473a5d157e4d437d9ebcb1b99f9693a64983877ee57d97005f0167869935" +version = "0.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-support", "parity-scale-codec", @@ -7760,9 +8114,8 @@ dependencies = [ [[package]] name = "xcm-simulator" -version = "17.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "058e21bfc3e1180bbd83cad3690d0e63f34f43ab309e338afe988160aa776fcf" +version = "7.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067#645878a27115db52e5d63115699b4bbb89034067" dependencies = [ "frame-support", "frame-system", @@ -7775,7 +8128,7 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?rev=645878a27115db52e5d63115699b4bbb89034067)", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -7783,9 +8136,9 @@ dependencies = [ [[package]] name = "xxhash-rust" -version = "0.8.12" +version = "0.8.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a5cbf750400958819fb6178eaa83bee5cd9c29a26a40cc241df8c70fdd46984" +checksum = "d7d48f1b18be023c95e7b75f481cac649d74be7c507ff4a407c55cfb957f7934" [[package]] name = "yansi" @@ -7819,7 +8172,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", "synstructure", ] @@ -7841,7 +8194,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -7861,7 +8214,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", "synstructure", ] @@ -7882,7 +8235,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] @@ -7904,14 +8257,14 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.93", ] [[package]] name = "zip" -version = "2.2.1" +version = "2.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99d52293fc86ea7cf13971b3bb81eb21683636e7ae24c729cdaf1b7c4157a352" +checksum = "ae9c1ea7b3a5e1f4b922ff856a129881167511563dc219869afe3787fc0c1a45" dependencies = [ "arbitrary", "crc32fast", @@ -7919,5 +8272,5 @@ dependencies = [ "displaydoc", "indexmap 2.7.0", "memchr", - "thiserror 2.0.4", + "thiserror 2.0.9", ] diff --git a/Cargo.toml b/Cargo.toml index 4b7cff9ff97..c3858c16d79 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ authors = ["Use Ink "] categories = ["no-std", "embedded"] edition = "2021" homepage = "https://use.ink" -keywords = ["wasm", "ink", "webassembly", "blockchain", "edsl"] +keywords = ["polkavm", "ink", "riscv", "blockchain", "edsl"] license = "Apache-2.0" repository = "https://github.com/use-ink/ink" version = "5.1.0" @@ -38,7 +38,7 @@ array-init = { version = "2.0", default-features = false } blake2 = { version = "0.10" } cargo_metadata = { version = "0.19.0" } cfg-if = { version = "1.0" } -contract-build = { version = "5.0.1" } +contract-build = { git = "https://github.com/use-ink/cargo-contract", branch = "cmichi-remove-wasm-default-to-revive" } darling = { version = "0.20.10" } derive_more = { version = "1.0.0", default-features = false } either = { version = "1.13", default-features = false } @@ -55,7 +55,6 @@ proc-macro2 = { version = "1" } quickcheck = { version = "1" } quickcheck_macros = { version = "1" } quote = { version = "1" } -rlibc = { version = "1" } scale = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } scale-decode = { version = "0.14.0", default-features = false } scale-encode = { version = "0.8.0", default-features = false } @@ -77,34 +76,30 @@ tokio = { version = "1.41.1" } tracing = { version = "0.1.41" } tracing-subscriber = { version = "0.3.19" } trybuild = { version = "1.0.101" } -wasm-instrument = { version = "0.4.0" } which = { version = "7.0.0" } xxhash-rust = { version = "0.8" } const_env = { version = "0.1"} -wat = { version = "1.221.2" } # Substrate dependencies -frame-metadata = { version = "16.0.0" } -frame-system = { version = "38.0.0", default-features = false } -frame-support = { version = "38.0.0", default-features = false } -pallet-contracts = { version = "38.0.0", default-features = false } -pallet-balances = { version = "39.0.0", default-features = false } -pallet-timestamp = { version = "37.0.0", default-features = false } -pallet-contracts-uapi = { version = "12.0.0", default-features = false } -pallet-revive-uapi = { git = "https://github.com/paritytech/polkadot-sdk", tag = "polkadot-stable2412-rc2", default-features = false } -# TODO include mock-network for revive -pallet-contracts-mock-network = { version = "14.0.0", default-features = false } -sp-externalities = { version = "0.29.0", default-features = false } -sp-io = { version = "38.0.0", default-features = false } -sp-runtime-interface = { version = "28.0.0" } -sp-core = { version = "34.0.0", default-features = false } -sp-keyring = { version = "39.0.0", default-features = false } -sp-runtime = { version = "39.0.2", default-features = false } -sp-weights = { version = "31.0.0", default-features = false } -xcm = { package = "staging-xcm", version = "14.2.0", default-features = false } +frame-metadata = { version = "18.0.0", default-features = false } +frame-system = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +frame-support = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +pallet-revive = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +pallet-revive-uapi = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false, features = ["unstable-hostfn"] } +pallet-revive-mock-network = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +sp-externalities = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +sp-io = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +sp-runtime-interface = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false, features = ["disable_target_static_assertions"] } +sp-core = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +sp-keyring = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +sp-weights = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +xcm = { package = "staging-xcm", git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } # PolkaVM dependencies -polkavm-derive = { version = "0.17.1", default-features = false } +polkavm-derive = { version = "0.18.0", default-features = false } # Local dependencies ink = { version = "=5.1.0", path = "crates/ink", default-features = false } diff --git a/crates/allocator/src/bump.rs b/crates/allocator/src/bump.rs index 56aef9c1ae6..16bde75f03d 100644 --- a/crates/allocator/src/bump.rs +++ b/crates/allocator/src/bump.rs @@ -24,12 +24,14 @@ use core::alloc::{ }; /// A page in Wasm is `64KiB` +/// todo: remove +#[allow(dead_code)] const PAGE_SIZE: usize = 64 * 1024; static mut INNER: Option = None; -#[cfg(target_arch = "riscv32")] -static mut RISCV_HEAP: [u8; 1024 * 1024] = [0; 1024 * 1024]; +#[cfg(target_arch = "riscv64")] +static mut RISCV_HEAP: [u8; 1024 * 10] = [0; 1024 * 10]; /// A bump allocator suitable for use in a Wasm environment. pub struct BumpAllocator; @@ -53,6 +55,7 @@ unsafe impl GlobalAlloc for BumpAllocator { #[inline] unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + // todo // A new page in Wasm is guaranteed to already be zero initialized, so we can just // use our regular `alloc` call here and save a bit of work. // @@ -97,6 +100,7 @@ impl InnerAlloc { /// /// This implementation is only meant to be used for testing, since we cannot (easily) /// test the `wasm32` implementation. + #[allow(dead_code)] fn request_pages(&mut self, _pages: usize) -> Option { Some(self.upper_limit) } @@ -109,62 +113,33 @@ impl InnerAlloc { 0 } + #[allow(dead_code)] fn request_pages(&mut self, _pages: usize) -> Option { unreachable!( "This branch is only used to keep the compiler happy when building tests, and should never actually be called outside of a test run." ) } - } else if #[cfg(target_arch = "wasm32")] { - fn heap_start() -> usize { - extern "C" { - static __heap_base: usize; - } - // # SAFETY - // - // The `__heap_base` symbol is defined by the wasm linker and is guaranteed - // to point to the start of the heap. - let heap_start = unsafe { &__heap_base as *const usize as usize }; - // if the symbol isn't found it will resolve to 0 - // for that to happen the rust compiler or linker need to break or change - assert_ne!(heap_start, 0, "Can't find `__heap_base` symbol."); - heap_start - } - - fn heap_end() -> usize { - // Cannot overflow on this architecture - core::arch::wasm32::memory_size(0) * PAGE_SIZE - } - - /// Request a `pages` number of pages of Wasm memory. Each page is `64KiB` in size. - /// - /// Returns `None` if a page is not available. - fn request_pages(&mut self, pages: usize) -> Option { - let prev_page = core::arch::wasm32::memory_grow(0, pages); - if prev_page == usize::MAX { - return None; - } - - // Cannot overflow on this architecture - Some(prev_page * PAGE_SIZE) - } - } else if #[cfg(target_arch = "riscv32")] { + } else if #[cfg(target_arch = "riscv64")] { fn heap_start() -> usize { + #[allow(static_mut_refs)] unsafe { RISCV_HEAP.as_mut_ptr() as usize } } + #[allow(static_mut_refs)] fn heap_end() -> usize { Self::heap_start() + unsafe { RISCV_HEAP.len() } } + #[allow(dead_code)] fn request_pages(&mut self, _pages: usize) -> Option { // On riscv the memory can't be grown - None + core::panic!("no request possible"); } } else { - core::compile_error!("ink! only supports wasm32 and riscv32"); + core::compile_error!("ink! only supports riscv64"); } } @@ -181,15 +156,7 @@ impl InnerAlloc { let alloc_end = alloc_start.checked_add(aligned_size)?; if alloc_end > self.upper_limit { - let required_pages = required_pages(aligned_size)?; - let page_start = self.request_pages(required_pages)?; - - self.upper_limit = required_pages - .checked_mul(PAGE_SIZE) - .and_then(|pages| page_start.checked_add(pages))?; - self.next = page_start.checked_add(aligned_size)?; - - Some(page_start) + panic!("exhausted heap limit"); } else { self.next = alloc_end; Some(alloc_start) @@ -205,6 +172,7 @@ impl InnerAlloc { /// - the binary with the inverse of the align creates a bitmask that is used to zero /// out bits, ensuring alignment according to type requirements and ensures that the /// next allocated pointer address is of the power of 2. + #[allow(clippy::arithmetic_side_effects)] // todo fn align_ptr(&self, layout: &Layout) -> usize { (self.next + layout.align() - 1) & !(layout.align() - 1) } @@ -216,12 +184,13 @@ impl InnerAlloc { /// `size = PAGE_SIZE / 2` this function will indicate that one page is required to /// satisfy the allocation. #[inline] -fn required_pages(size: usize) -> Option { - size.checked_add(PAGE_SIZE - 1) - .and_then(|num| num.checked_div(PAGE_SIZE)) +#[allow(dead_code)] +fn required_pages(_size: usize) -> Option { + core::panic!("required_pages"); } -#[cfg(test)] +// todo +#[cfg(all(test, target_os = "dragonfly"))] mod tests { use super::*; use std::mem::size_of; @@ -357,7 +326,8 @@ mod tests { } } -#[cfg(all(test, feature = "ink-fuzz-tests"))] +// todo +#[cfg(all(test, feature = "ink-fuzz-tests", target_os = "dragonfly"))] mod fuzz_tests { use super::*; use quickcheck::{ diff --git a/crates/allocator/src/lib.rs b/crates/allocator/src/lib.rs index 10835e5476a..8371e485fef 100644 --- a/crates/allocator/src/lib.rs +++ b/crates/allocator/src/lib.rs @@ -28,8 +28,15 @@ #[global_allocator] static mut ALLOC: bump::BumpAllocator = bump::BumpAllocator {}; -mod bump; +#[cfg(not(any(feature = "std", feature = "no-allocator")))] +pub mod bump; -#[cfg(all(test, feature = "std", feature = "ink-fuzz-tests",))] +// todo +#[cfg(all( + test, + feature = "std", + feature = "ink-fuzz-tests", + target_os = "dragonfly" +))] #[macro_use(quickcheck)] extern crate quickcheck_macros; diff --git a/crates/e2e/Cargo.toml b/crates/e2e/Cargo.toml index fac65b83791..23393a16d7d 100644 --- a/crates/e2e/Cargo.toml +++ b/crates/e2e/Cargo.toml @@ -19,11 +19,12 @@ ink_e2e_macro = { workspace = true, default-features = true } ink = { workspace = true, default-features = true } ink_env = { workspace = true, default-features = true } ink_primitives = { workspace = true, default-features = true } +ink_sandbox = { version = "=5.1.0", path = "./sandbox", optional = true } cargo_metadata = { workspace = true } contract-build = { workspace = true } -ink_sandbox = { version = "=5.1.0", path = "./sandbox", optional = true } -pallet-contracts-mock-network = { workspace = true, optional = true } +pallet-revive = { workspace = true } +pallet-revive-mock-network = { workspace = true, optional = true } funty = { workspace = true } impl-serde = { workspace = true } jsonrpsee = { workspace = true, features = ["ws-client"] } @@ -37,17 +38,16 @@ subxt = { workspace = true } subxt-metadata = { workspace = true, optional = true } subxt-signer = { workspace = true, features = ["subxt", "sr25519"] } thiserror = { workspace = true } -wasm-instrument = { workspace = true } which = { workspace = true } # Substrate frame-support = { workspace = true } -pallet-contracts = { workspace = true } sp-core = { workspace = true } sp-keyring = { workspace = true } sp-runtime = { workspace = true } sp-weights = { workspace = true } regex = "1.11.1" +itertools = "0.13.0" [dev-dependencies] # Required for the doctest of `MessageBuilder::call` @@ -58,7 +58,7 @@ default = [ "std" ] std = [ "impl-serde/std", "ink_e2e_macro/std", - "pallet-contracts/std", + "pallet-revive/std", "scale-info/std", "scale/std", "serde/std", @@ -69,16 +69,12 @@ std = [ "ink_e2e_macro/std", "ink_sandbox/std", "frame-support/std", - "pallet-contracts-mock-network?/std", + "pallet-revive-mock-network?/std", ] sandbox = [ "dep:ink_sandbox", "subxt-metadata", - "pallet-contracts-mock-network", + "pallet-revive-mock-network", "ink_e2e_macro/sandbox", ] -revive = [ - "ink/revive", - "ink_env/revive" -] diff --git a/crates/e2e/macro/Cargo.toml b/crates/e2e/macro/Cargo.toml index d9e5a03f2c1..f3a164f153b 100644 --- a/crates/e2e/macro/Cargo.toml +++ b/crates/e2e/macro/Cargo.toml @@ -20,6 +20,7 @@ proc-macro = true [dependencies] darling = { workspace = true } +# todo check greyed out deps ink_ir = { workspace = true, default-features = true } derive_more = { workspace = true, features = ["from"] } tracing-subscriber = { workspace = true, features = ["env-filter"] } diff --git a/crates/e2e/macro/src/codegen.rs b/crates/e2e/macro/src/codegen.rs index df59283007e..abe02f4b486 100644 --- a/crates/e2e/macro/src/codegen.rs +++ b/crates/e2e/macro/src/codegen.rs @@ -150,6 +150,6 @@ fn build_full_client( fn build_runtime_client(contracts: TokenStream2, runtime: syn::Path) -> TokenStream2 { quote! { let contracts = #contracts; - let mut client = ::ink_e2e::SandboxClient::<_, _, #runtime>::new(contracts); + let mut client = ::ink_e2e::SandboxClient::<_, #runtime>::new(contracts); } } diff --git a/crates/e2e/macro/src/lib.rs b/crates/e2e/macro/src/lib.rs index b15a0a92089..1fe40731baa 100644 --- a/crates/e2e/macro/src/lib.rs +++ b/crates/e2e/macro/src/lib.rs @@ -29,7 +29,7 @@ use syn::Result; /// /// The system requirements are: /// -/// - A Substrate node with `pallet-contracts` installed on the local system. You can e.g. +/// - A Substrate node with `pallet-revive` installed on the local system. You can e.g. /// use [`substrate-contracts-node`](https://github.com/paritytech/substrate-contracts-node) /// and install it on your PATH, or provide a path to an executable using the /// `CONTRACTS_NODE` environment variable. @@ -67,7 +67,7 @@ use syn::Result; /// ``` /// /// In this configuration the test will not run against a node that is running in the -/// background, but against an in-process slimmed down `pallet-contracts` execution +/// background, but against an in-process slimmed down `pallet-revive` execution /// environment. /// /// Please see [the page on testing with DRink!](https://use.ink/basics/contract-testing/drink) diff --git a/crates/e2e/sandbox/Cargo.toml b/crates/e2e/sandbox/Cargo.toml index 4d347500932..b2331493fc1 100644 --- a/crates/e2e/sandbox/Cargo.toml +++ b/crates/e2e/sandbox/Cargo.toml @@ -10,20 +10,21 @@ documentation = "https://docs.rs/ink_sandbox" homepage.workspace = true [dependencies] +sha3 = "0.10.8" frame-metadata = { workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } pallet-balances = { workspace = true } -pallet-contracts = { workspace = true } +pallet-revive = { workspace = true } pallet-timestamp = { workspace = true } scale = { workspace = true } sp-core = { workspace = true } sp-externalities = { workspace = true } sp-io = { workspace = true } +ink_primitives = { workspace = true } paste = { workspace = true } scale-info = { workspace = true } -wat = { workspace = true } [features] default = [ @@ -33,8 +34,10 @@ default = [ std = [ "frame-support/std", "frame-system/std", + "frame-metadata/std", + "ink_primitives/std", "pallet-balances/std", - "pallet-contracts/std", + "pallet-revive/std", "pallet-timestamp/std", "scale/std", "scale-info/std", diff --git a/crates/e2e/sandbox/src/api.rs b/crates/e2e/sandbox/src/api.rs index 01fe8d48367..190d9ad8f87 100644 --- a/crates/e2e/sandbox/src/api.rs +++ b/crates/e2e/sandbox/src/api.rs @@ -1,12 +1,12 @@ pub mod balance_api; -pub mod contracts_api; +pub mod revive_api; pub mod system_api; pub mod timestamp_api; pub mod prelude { pub use super::{ balance_api::BalanceAPI, - contracts_api::ContractAPI, + revive_api::ContractAPI, system_api::SystemAPI, timestamp_api::TimestampAPI, }; diff --git a/crates/e2e/sandbox/src/api/balance_api.rs b/crates/e2e/sandbox/src/api/balance_api.rs index 70fb0e7ba8a..48fae332c79 100644 --- a/crates/e2e/sandbox/src/api/balance_api.rs +++ b/crates/e2e/sandbox/src/api/balance_api.rs @@ -31,10 +31,10 @@ where /// /// # Arguments /// - /// * `address` - The address of the account to query. + /// * `account` - The account id of the account to query. fn free_balance( &mut self, - address: &AccountIdFor, + account_id: &AccountIdFor, ) -> BalanceOf; } @@ -55,9 +55,11 @@ where fn free_balance( &mut self, - address: &AccountIdFor, + account_id: &AccountIdFor, ) -> BalanceOf { - self.execute_with(|| pallet_balances::Pallet::::free_balance(address)) + self.execute_with(|| { + pallet_balances::Pallet::::free_balance(account_id) + }) } } diff --git a/crates/e2e/sandbox/src/api/contracts_api.rs b/crates/e2e/sandbox/src/api/revive_api.rs similarity index 54% rename from crates/e2e/sandbox/src/api/contracts_api.rs rename to crates/e2e/sandbox/src/api/revive_api.rs index c02c5c27f14..7c3e3554810 100644 --- a/crates/e2e/sandbox/src/api/contracts_api.rs +++ b/crates/e2e/sandbox/src/api/revive_api.rs @@ -1,33 +1,57 @@ use crate::{ AccountIdFor, ContractExecResultFor, - ContractInstantiateResultFor, - EventRecordOf, + ContractResultInstantiate, Sandbox, + H256, }; use frame_support::{ - traits::fungible::Inspect, + pallet_prelude::DispatchError, + sp_runtime::traits::Bounded, + traits::{ + fungible::Inspect, + Time, + }, weights::Weight, }; -use frame_system::Config as SysConfig; -use pallet_contracts::{ +use frame_system::pallet_prelude::OriginFor; +use ink_primitives::DepositLimit; +use pallet_revive::{ Code, CodeUploadResult, CollectEvents, - ContractInstantiateResult, DebugInfo, - Determinism, }; -use scale::Decode as _; +use sp_core::{ + H160, + U256, +}; use std::ops::Not; type BalanceOf = - <::Currency as Inspect>>::Balance; + <::Currency as Inspect>>::Balance; + +type MomentOf = <::Time as Time>::Moment; /// Contract API used to interact with the contracts pallet. pub trait ContractAPI { /// The runtime contract config. - type T: pallet_contracts::Config; + type T: pallet_revive::Config; + + /// Interface for `bare_instantiate` contract call with a simultaneous upload. + /// + /// # Arguments + /// + /// * `contract_bytes` - The contract code. + /// * `value` - The number of tokens to be transferred to the contract. + /// * `data` - The input data to be passed to the contract (including constructor + /// name). + /// * `salt` - The salt to be used for contract address derivation. + /// * `origin` - The sender of the contract call. + /// * `gas_limit` - The gas limit for the contract call. + /// * `storage_deposit_limit` - The storage deposit limit for the contract call. + #[allow(clippy::type_complexity, clippy::too_many_arguments)] + fn map_account(&mut self, account: OriginFor) -> Result<(), DispatchError>; /// Interface for `bare_instantiate` contract call with a simultaneous upload. /// @@ -47,15 +71,11 @@ pub trait ContractAPI { contract_bytes: Vec, value: BalanceOf, data: Vec, - salt: Vec, - origin: AccountIdFor, + salt: Option<[u8; 32]>, + origin: OriginFor, gas_limit: Weight, - storage_deposit_limit: Option>, - ) -> ContractInstantiateResult< - AccountIdFor, - BalanceOf, - EventRecordOf, - >; + storage_deposit_limit: DepositLimit>, + ) -> ContractResultInstantiate; /// Interface for `bare_instantiate` contract call for a previously uploaded contract. /// @@ -72,18 +92,14 @@ pub trait ContractAPI { #[allow(clippy::type_complexity, clippy::too_many_arguments)] fn instantiate_contract( &mut self, - code_hash: Vec, + code_hash: H256, value: BalanceOf, data: Vec, - salt: Vec, - origin: AccountIdFor, + salt: Option<[u8; 32]>, + origin: OriginFor, gas_limit: Weight, - storage_deposit_limit: Option>, - ) -> ContractInstantiateResult< - AccountIdFor, - BalanceOf, - EventRecordOf, - >; + storage_deposit_limit: DepositLimit>, + ) -> ContractResultInstantiate; /// Interface for `bare_upload_code` contract call. /// @@ -95,10 +111,9 @@ pub trait ContractAPI { fn upload_contract( &mut self, contract_bytes: Vec, - origin: AccountIdFor, - storage_deposit_limit: Option>, - determinism: Determinism, - ) -> CodeUploadResult<::Hash, BalanceOf>; + origin: OriginFor, + storage_deposit_limit: BalanceOf, + ) -> CodeUploadResult>; /// Interface for `bare_call` contract call. /// @@ -113,35 +128,49 @@ pub trait ContractAPI { #[allow(clippy::type_complexity, clippy::too_many_arguments)] fn call_contract( &mut self, - address: AccountIdFor, + address: H160, value: BalanceOf, data: Vec, - origin: AccountIdFor, + origin: OriginFor, gas_limit: Weight, - storage_deposit_limit: Option>, - determinism: Determinism, + storage_deposit_limit: DepositLimit>, ) -> ContractExecResultFor; } impl ContractAPI for T where T: Sandbox, - T::Runtime: pallet_contracts::Config, + T::Runtime: pallet_revive::Config, + + BalanceOf: Into + TryFrom + Bounded, + MomentOf: Into, + + // todo + <::Runtime as frame_system::Config>::Hash: + frame_support::traits::IsType, { type T = T::Runtime; + fn map_account( + &mut self, + account_id: OriginFor, + ) -> Result<(), DispatchError> { + self.execute_with(|| pallet_revive::Pallet::::map_account(account_id)) + } + fn deploy_contract( &mut self, contract_bytes: Vec, value: BalanceOf, data: Vec, - salt: Vec, - origin: AccountIdFor, + salt: Option<[u8; 32]>, + origin: OriginFor, gas_limit: Weight, - storage_deposit_limit: Option>, - ) -> ContractInstantiateResultFor { + storage_deposit_limit: DepositLimit>, + ) -> ContractResultInstantiate { + let storage_deposit_limit = storage_deposit_limit_fn(storage_deposit_limit); self.execute_with(|| { - pallet_contracts::Pallet::::bare_instantiate( + pallet_revive::Pallet::::bare_instantiate( origin, value, gas_limit, @@ -157,33 +186,26 @@ where fn instantiate_contract( &mut self, - code_hash: Vec, + code_hash: H256, value: BalanceOf, data: Vec, - salt: Vec, - origin: AccountIdFor, + salt: Option<[u8; 32]>, + origin: OriginFor, gas_limit: Weight, - storage_deposit_limit: Option>, - ) -> ContractInstantiateResult< - AccountIdFor, - BalanceOf, - EventRecordOf, - > { - let mut code_hash = &code_hash[..]; + storage_deposit_limit: DepositLimit>, + ) -> ContractResultInstantiate { + let storage_deposit_limit = storage_deposit_limit_fn(storage_deposit_limit); self.execute_with(|| { - pallet_contracts::Pallet::::bare_instantiate( + pallet_revive::Pallet::::bare_instantiate( origin, value, gas_limit, storage_deposit_limit, - Code::Existing( - ::Hash::decode(&mut code_hash) - .expect("Invalid code hash"), - ), + Code::Existing(code_hash), data, salt, DebugInfo::UnsafeDebug, - CollectEvents::UnsafeCollect, + CollectEvents::Skip, ) }) } @@ -191,33 +213,30 @@ where fn upload_contract( &mut self, contract_bytes: Vec, - origin: AccountIdFor, - storage_deposit_limit: Option>, - determinism: Determinism, - ) -> CodeUploadResult<::Hash, BalanceOf> - { + origin: OriginFor, + storage_deposit_limit: BalanceOf, + ) -> CodeUploadResult> { self.execute_with(|| { - pallet_contracts::Pallet::::bare_upload_code( + pallet_revive::Pallet::::bare_upload_code( origin, contract_bytes, storage_deposit_limit, - determinism, ) }) } fn call_contract( &mut self, - address: AccountIdFor, + address: H160, value: BalanceOf, data: Vec, - origin: AccountIdFor, + origin: OriginFor, gas_limit: Weight, - storage_deposit_limit: Option>, - determinism: Determinism, + storage_deposit_limit: DepositLimit>, ) -> ContractExecResultFor { + let storage_deposit_limit = storage_deposit_limit_fn(storage_deposit_limit); self.execute_with(|| { - pallet_contracts::Pallet::::bare_call( + pallet_revive::Pallet::::bare_call( origin, address, value, @@ -226,12 +245,21 @@ where data, DebugInfo::UnsafeDebug, CollectEvents::UnsafeCollect, - determinism, ) }) } } +/// todo +fn storage_deposit_limit_fn( + limit: DepositLimit, +) -> pallet_revive::DepositLimit { + match limit { + DepositLimit::Unchecked => pallet_revive::DepositLimit::Unchecked, + DepositLimit::Balance(v) => pallet_revive::DepositLimit::Balance(v), + } +} + /// Converts bytes to a '\n'-split string, ignoring empty lines. pub fn decode_debug_buffer(buffer: &[u8]) -> Vec { let decoded = buffer.iter().map(|b| *b as char).collect::(); @@ -250,34 +278,35 @@ mod tests { RuntimeEventOf, RuntimeOf, }; - use frame_support::sp_runtime::traits::Hash; - use pallet_contracts::Origin; + + const STORAGE_DEPOSIT_LIMIT: DepositLimit = DepositLimit::Unchecked; fn compile_module(contract_name: &str) -> Vec { let path = [ std::env::var("CARGO_MANIFEST_DIR").as_deref().unwrap(), "/test-resources/", contract_name, - ".wat", + ".polkavm", ] .concat(); - wat::parse_file(path).expect("Failed to parse wat file") + std::fs::read(std::path::Path::new(&path)).unwrap() } #[test] fn can_upload_code() { let mut sandbox = DefaultSandbox::default(); let wasm_binary = compile_module("dummy"); - let hash = < as frame_system::Config>::Hashing>::hash( - &wasm_binary, - ); - let result = sandbox.upload_contract( - wasm_binary, - DefaultSandbox::default_actor(), - None, - Determinism::Enforced, - ); + use sha3::{ + Digest, + Keccak256, + }; + let hash = Keccak256::digest(wasm_binary.as_slice()); + let hash = H256::from_slice(hash.as_slice()); + + let origin = + DefaultSandbox::convert_account_to_origin(DefaultSandbox::default_actor()); + let result = sandbox.upload_contract(wasm_binary, origin, 100000000000000); assert!(result.is_ok()); assert_eq!(hash, result.unwrap().code_hash); @@ -291,14 +320,17 @@ mod tests { let events_before = sandbox.events(); assert!(events_before.is_empty()); + let origin = + DefaultSandbox::convert_account_to_origin(DefaultSandbox::default_actor()); + sandbox.map_account(origin.clone()).expect("cannot map"); let result = sandbox.deploy_contract( wasm_binary, 0, vec![], - vec![], - DefaultSandbox::default_actor(), - DefaultSandbox::default_gas_limit(), None, + origin, + DefaultSandbox::default_gas_limit(), + DepositLimit::Balance(100000000000000), ); assert!(result.result.is_ok()); assert!(!result.result.unwrap().result.did_revert()); @@ -308,50 +340,50 @@ mod tests { let instantiation_event = events[event_count - 2].clone(); assert!(matches!( instantiation_event.event, - RuntimeEventOf::::Contracts(pallet_contracts::Event::< + RuntimeEventOf::::Revive(pallet_revive::Event::< RuntimeOf, >::Instantiated { .. }) )); let deposit_event = events[event_count - 1].clone(); assert!(matches!( deposit_event.event, - RuntimeEventOf::::Contracts( - pallet_contracts::Event::>::StorageDepositTransferredAndHeld { .. } - ) + RuntimeEventOf::::Revive(pallet_revive::Event::< + RuntimeOf, + >::StorageDepositTransferredAndHeld { .. }) )); } #[test] fn can_call_contract() { let mut sandbox = DefaultSandbox::default(); - let actor = DefaultSandbox::default_actor(); + let _actor = DefaultSandbox::default_actor(); let wasm_binary = compile_module("dummy"); + let origin = + DefaultSandbox::convert_account_to_origin(DefaultSandbox::default_actor()); + sandbox.map_account(origin.clone()).expect("unable to map"); let result = sandbox.deploy_contract( wasm_binary, 0, vec![], - vec![], - actor.clone(), - DefaultSandbox::default_gas_limit(), None, + origin.clone(), + DefaultSandbox::default_gas_limit(), + STORAGE_DEPOSIT_LIMIT, ); + assert!(!result.result.clone().unwrap().result.did_revert()); - let contract_address = result - .result - .expect("Contract should be deployed") - .account_id; + let contract_address = result.result.expect("Contract should be deployed").addr; sandbox.reset_events(); let result = sandbox.call_contract( - contract_address.clone(), + contract_address, 0, vec![], - actor.clone(), + origin.clone(), DefaultSandbox::default_gas_limit(), - None, - Determinism::Enforced, + STORAGE_DEPOSIT_LIMIT, ); assert!(result.result.is_ok()); assert!(!result.result.unwrap().did_revert()); @@ -361,22 +393,31 @@ mod tests { assert_eq!( events[0].event, - RuntimeEventOf::::Contracts(pallet_contracts::Event::< + RuntimeEventOf::::Revive(pallet_revive::Event::< RuntimeOf, >::ContractEmitted { - contract: contract_address.clone(), - data: vec![0, 0, 0, 0], + contract: contract_address, + topics: vec![H256::from([42u8; 32])], + data: vec![1, 2, 3, 4], }) ); - assert_eq!( - events[1].event, - RuntimeEventOf::::Contracts(pallet_contracts::Event::< - RuntimeOf, - >::Called { - contract: contract_address, - caller: Origin::Signed(actor), - }), - ); + // TODO Wait for `pallet_revive::exec::Origin` re-export. + // let account_id = DefaultSandbox::default_actor(); + // let caller = origin.clone(); + // let caller = pallet_revive::exec::Origin::from_runtime_origin(caller).unwrap(); + // let origin = + // DefaultSandbox::convert_account_to_origin(DefaultSandbox::default_actor()); + // let foo = pallet_revive::Origin::>::from(origin); + // assert_eq!( + // events[1].event, + // RuntimeEventOf::::Revive(pallet_revive::Event::< + // RuntimeOf, + // >::Called { + // contract: contract_address, + // caller: frame_system::EnsureSigned::try_origin(actor).unwrap(), + // caller, + // }), + // ); } } diff --git a/crates/e2e/sandbox/src/lib.rs b/crates/e2e/sandbox/src/lib.rs index 01ba7b48b79..99e8c7f4984 100644 --- a/crates/e2e/sandbox/src/lib.rs +++ b/crates/e2e/sandbox/src/lib.rs @@ -10,16 +10,20 @@ use frame_support::{ traits::fungible::Inspect, }; use frame_system::{ - pallet_prelude::BlockNumberFor, + pallet_prelude::{ + BlockNumberFor, + OriginFor, + }, EventRecord, }; pub use macros::{ BlockBuilder, DefaultSandbox, }; -use pallet_contracts::{ - ContractExecResult, - ContractInstantiateResult, +use pallet_revive::{ + ContractResult, + ExecReturnValue, + InstantiateReturnValue, }; /// Export pallets that are used in [`crate::create_sandbox`] pub use { @@ -33,7 +37,7 @@ pub use { }, frame_system, pallet_balances, - pallet_contracts, + pallet_revive, pallet_timestamp, paste, sp_core::crypto::Ss58Codec, @@ -58,7 +62,7 @@ pub type StorageRoot = H256; /// Alias for the balance type. type BalanceOf = - <::Currency as Inspect>>::Balance; + <::Currency as Inspect>>::Balance; /// Alias for the account ID type. pub type AccountIdFor = ::AccountId; @@ -73,15 +77,21 @@ pub type EventRecordOf = EventRecord< >; /// Alias for the contract instantiate result. -pub type ContractInstantiateResultFor = ContractInstantiateResult< - AccountIdFor, - BalanceOf, - EventRecordOf, ->; +pub type ContractInstantiateResultFor = + ContractResult, BalanceOf, EventRecordOf>; + +pub type ContractResultFor = + ContractResult, EventRecordOf>; + +pub type ContractResultInstantiate = + ContractResult, EventRecordOf>; /// Alias for the contract exec result. pub type ContractExecResultFor = - ContractExecResult, EventRecordOf>; + ContractResult, EventRecordOf>; + +/// Alias for the `map_acocunt` result. +pub type MapAccountResultFor = Result<(), DispatchError>; /// Alias for the runtime of a sandbox. pub type RuntimeOf = ::Runtime; @@ -121,7 +131,7 @@ pub trait Sandbox { fn default_actor() -> AccountIdFor; fn default_gas_limit() -> Weight { - Weight::from_parts(100_000_000_000, 3 * 1024 * 1024) + Weight::from_parts(100_000_000_000_000, 6 * 1024 * 1024) } /// Metadata of the runtime. diff --git a/crates/e2e/sandbox/src/macros.rs b/crates/e2e/sandbox/src/macros.rs index 0b251b9b99b..5b722e833ba 100644 --- a/crates/e2e/sandbox/src/macros.rs +++ b/crates/e2e/sandbox/src/macros.rs @@ -19,7 +19,7 @@ pub struct BlockBuilder(std::marker::PhantomData); impl< T: pallet_balances::Config + pallet_timestamp::Config - + pallet_contracts::Config, + + pallet_revive::Config, > BlockBuilder { /// Create a new externalities with the given balances. @@ -55,7 +55,7 @@ impl< .as_secs(), ); pallet_timestamp::Pallet::::on_initialize(height); - pallet_contracts::Pallet::::on_initialize(height); + pallet_revive::Pallet::::on_initialize(height); frame_system::Pallet::::note_finished_initialize(); } @@ -63,7 +63,7 @@ impl< pub fn finalize_block( height: frame_system::pallet_prelude::BlockNumberFor, ) -> ::Hash { - pallet_contracts::Pallet::::on_finalize(height); + pallet_revive::Pallet::::on_finalize(height); pallet_timestamp::Pallet::::on_finalize(height); pallet_balances::Pallet::::on_finalize(height); frame_system::Pallet::::finalize().hash() @@ -107,11 +107,10 @@ mod construct_runtime { derive_impl, parameter_types, sp_runtime::{ - testing::H256, traits::Convert, AccountId32, Perbill, }, - traits::{ConstBool, ConstU128, ConstU32, ConstU64, Currency, Randomness}, + traits::{ConstBool, ConstU128, ConstU32, ConstU64, Currency}, weights::Weight, }; @@ -123,7 +122,7 @@ mod construct_runtime { System: $crate::frame_system, Balances: $crate::pallet_balances, Timestamp: $crate::pallet_timestamp, - Contracts: $crate::pallet_contracts, + Revive: $crate::pallet_revive, $( $pallet_name: $pallet, )* @@ -154,6 +153,7 @@ mod construct_runtime { type MaxFreezes = (); type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; + type DoneSlashHandler = (); } // Configure pallet timestamp @@ -164,14 +164,7 @@ mod construct_runtime { type WeightInfo = (); } - // Configure pallet contracts - pub enum SandboxRandomness {} - impl Randomness for SandboxRandomness { - fn random(_subject: &[u8]) -> (H256, u32) { - unreachable!("No randomness") - } - } - + // Configure pallet revive type BalanceOf = >::Balance; impl Convert for $runtime { fn convert(w: Weight) -> BalanceOf { @@ -180,46 +173,36 @@ mod construct_runtime { } parameter_types! { - pub SandboxSchedule: $crate::pallet_contracts::Schedule<$runtime> = { - <$crate::pallet_contracts::Schedule<$runtime>>::default() - }; + // TODO can we delete some? pub DeletionWeightLimit: Weight = Weight::zero(); pub DefaultDepositLimit: BalanceOf = 10_000_000; pub CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0); pub MaxDelegateDependencies: u32 = 32; } - impl $crate::pallet_contracts::Config for $runtime { + impl $crate::pallet_revive::Config for $runtime { + type AddressMapper = $crate::pallet_revive::AccountId32Mapper; + type ChainId = ConstU64<0>; // TODO + type NativeToEthRatio = ConstU32<1>; type Time = Timestamp; - type Randomness = SandboxRandomness; type Currency = Balances; type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type CallFilter = (); + type DepositPerItem = ConstU128<1>; + type DepositPerByte = ConstU128<1>; type WeightPrice = Self; type WeightInfo = (); type ChainExtension = $chain_extension; - type Schedule = SandboxSchedule; - type CallStack = [$crate::pallet_contracts::Frame; 5]; - type DepositPerByte = ConstU128<1>; - type DepositPerItem = ConstU128<1>; - type AddressGenerator = $crate::pallet_contracts::DefaultAddressGenerator; - type MaxCodeLen = ConstU32<{ 123 * 1024 }>; - type MaxStorageKeyLen = ConstU32<128>; - type MaxTransientStorageSize = ConstU32<{ 1024 * 1024 }>; - type UnsafeUnstableInterface = ConstBool; - type UploadOrigin = $crate::frame_system::EnsureSigned; - type InstantiateOrigin = $crate::frame_system::EnsureSigned; - type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>; - type Migrations = (); - type DefaultDepositLimit = DefaultDepositLimit; - type Debug = $debug; + type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>; + type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>; + type UnsafeUnstableInterface = ConstBool; type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; - type MaxDelegateDependencies = MaxDelegateDependencies; type RuntimeHoldReason = RuntimeHoldReason; - type Environment = (); + type Debug = $debug; type Xcm = (); - type ApiVersion = (); + type UploadOrigin = $crate::frame_system::EnsureSigned; + type InstantiateOrigin = $crate::frame_system::EnsureSigned; } // Implement `crate::Sandbox` trait @@ -320,7 +303,7 @@ mod construct_runtime { // Export runtime type itself, pallets and useful types from the auxiliary module pub use construct_runtime::{ - $sandbox, $runtime, Balances, Contracts, PalletInfo, RuntimeCall, RuntimeEvent, RuntimeHoldReason, + $sandbox, $runtime, Balances, Revive, PalletInfo, RuntimeCall, RuntimeEvent, RuntimeHoldReason, RuntimeOrigin, System, Timestamp, }; }; diff --git a/crates/e2e/sandbox/test-resources/dummy.polkavm b/crates/e2e/sandbox/test-resources/dummy.polkavm new file mode 100644 index 00000000000..34c003082a4 Binary files /dev/null and b/crates/e2e/sandbox/test-resources/dummy.polkavm differ diff --git a/crates/e2e/sandbox/test-resources/dummy.wat b/crates/e2e/sandbox/test-resources/dummy.wat deleted file mode 100644 index 23eff87ad51..00000000000 --- a/crates/e2e/sandbox/test-resources/dummy.wat +++ /dev/null @@ -1,25 +0,0 @@ -;; Dummy contract emitting a dummy event. -(module - (import "seal0" "seal_deposit_event" (func $seal_deposit_event (param i32 i32 i32 i32))) - (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) - (import "env" "memory" (memory 1 1)) - - (func (export "deploy")) - - (func (export "call") - ;; emit dummy event - (call $seal_deposit_event - (i32.const 0) ;; The topics buffer - (i32.const 0) ;; The topics buffer's length - (i32.const 8) ;; The data buffer - (i32.const 4) ;; The data buffer's length - ) - - ;; exit with success - (call $seal_return - (i32.const 0) ;; flags - (i32.const 0) ;; returned value - (i32.const 4) ;; length of returned value - ) - ) -) diff --git a/crates/e2e/src/backend.rs b/crates/e2e/src/backend.rs index 760a44dff0c..82746b9360a 100644 --- a/crates/e2e/src/backend.rs +++ b/crates/e2e/src/backend.rs @@ -12,7 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::Keypair; +use super::{ + InstantiateDryRunResult, + Keypair, + H256, +}; use crate::{ backend_calls::{ InstantiateBuilder, @@ -20,10 +24,7 @@ use crate::{ UploadBuilder, }, builders::CreateBuilderPartial, - contract_results::{ - BareInstantiationResult, - InstantiateDryRunResult, - }, + contract_results::BareInstantiationResult, CallBuilder, CallBuilderFinal, CallDryRunResult, @@ -33,6 +34,7 @@ use ink_env::{ DefaultEnvironment, Environment, }; +use ink_primitives::DepositLimit; use jsonrpsee::core::async_trait; use scale::{ Decode, @@ -175,7 +177,7 @@ pub trait ContractsBackend { fn remove_code<'a>( &'a mut self, caller: &'a Keypair, - code_hash: E::Hash, + code_hash: H256, ) -> RemoveCodeBuilder<'a, E, Self> where Self: Sized + BuilderClient, @@ -230,7 +232,7 @@ pub trait BuilderClient: ContractsBackend { message: &CallBuilderFinal, value: E::Balance, gas_limit: Weight, - storage_deposit_limit: Option, + storage_deposit_limit: DepositLimit, ) -> Result where CallBuilderFinal: Clone; @@ -244,7 +246,7 @@ pub trait BuilderClient: ContractsBackend { caller: &Keypair, message: &CallBuilderFinal, value: E::Balance, - storage_deposit_limit: Option, + storage_deposit_limit: DepositLimit, ) -> Result, Self::Error> where CallBuilderFinal: Clone; @@ -260,14 +262,14 @@ pub trait BuilderClient: ContractsBackend { &mut self, contract_name: &str, caller: &Keypair, - storage_deposit_limit: Option, + storage_deposit_limit: E::Balance, ) -> Result, Self::Error>; /// Removes the code of the contract at `code_hash`. async fn bare_remove_code( &mut self, caller: &Keypair, - code_hash: E::Hash, + code_hash: crate::H256, ) -> Result; /// Bare instantiate call. This function does not perform a dry-run, @@ -290,8 +292,8 @@ pub trait BuilderClient: ContractsBackend { constructor: &mut CreateBuilderPartial, value: E::Balance, gas_limit: Weight, - storage_deposit_limit: Option, - ) -> Result, Self::Error>; + storage_deposit_limit: DepositLimit, + ) -> Result, Self::Error>; /// Dry run contract instantiation. async fn bare_instantiate_dry_run< @@ -304,6 +306,12 @@ pub trait BuilderClient: ContractsBackend { caller: &Keypair, constructor: &mut CreateBuilderPartial, value: E::Balance, - storage_deposit_limit: Option, + storage_deposit_limit: DepositLimit, ) -> Result, Self::Error>; + + /// todo + async fn map_account(&mut self, caller: &Keypair) -> Result<(), Self::Error>; + + /// todo + async fn map_account_dry_run(&mut self, caller: &Keypair) -> Result<(), Self::Error>; } diff --git a/crates/e2e/src/backend_calls.rs b/crates/e2e/src/backend_calls.rs index aedba9683bb..2a7774683ae 100644 --- a/crates/e2e/src/backend_calls.rs +++ b/crates/e2e/src/backend_calls.rs @@ -12,13 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -use ink_env::Environment; -use scale::{ - Decode, - Encode, +use super::{ + balance_to_deposit_limit, + InstantiateDryRunResult, + Keypair, }; -use sp_weights::Weight; - use crate::{ backend::BuilderClient, builders::CreateBuilderPartial, @@ -26,12 +24,18 @@ use crate::{ CallDryRunResult, CallResult, ContractsBackend, - InstantiateDryRunResult, InstantiationResult, UploadResult, + H256, }; - -use super::Keypair; +use ink_env::Environment; +use ink_primitives::DepositLimit; +use scale::{ + Decode, + Encode, +}; +use sp_weights::Weight; +use std::marker::PhantomData; /// Allows to build an end-to-end call using a builder pattern. pub struct CallBuilder<'a, E, Args, RetType, B> @@ -48,7 +52,7 @@ where value: E::Balance, extra_gas_portion: Option, gas_limit: Option, - storage_deposit_limit: Option, + storage_deposit_limit: E::Balance, } impl<'a, E, Args, RetType, B> CallBuilder<'a, E, Args, RetType, B> @@ -75,7 +79,7 @@ where value: 0u32.into(), extra_gas_portion: None, gas_limit: None, - storage_deposit_limit: None, + storage_deposit_limit: 0u32.into(), } } @@ -107,7 +111,7 @@ where /// # Notes /// /// Overwrites any values specified for `extra_gas_portion`. - /// The gas estimate fro dry-run will be ignored. + /// The gas estimate from the dry-run will be ignored. pub fn gas_limit(&mut self, limit: Weight) -> &mut Self { if limit == Weight::from_parts(0, 0) { self.gas_limit = None @@ -122,11 +126,7 @@ where &mut self, storage_deposit_limit: E::Balance, ) -> &mut Self { - if storage_deposit_limit == 0u32.into() { - self.storage_deposit_limit = None - } else { - self.storage_deposit_limit = Some(storage_deposit_limit) - } + self.storage_deposit_limit = storage_deposit_limit; self } @@ -140,12 +140,15 @@ where where CallBuilderFinal: Clone, { + // todo must be added to remove as well + let _map = B::map_account(self.client, self.caller).await; // todo will fail if instantiation happened before + let dry_run = B::bare_call_dry_run( self.client, self.caller, self.message, self.value, - self.storage_deposit_limit, + balance_to_deposit_limit::(self.storage_deposit_limit), ) .await?; @@ -164,7 +167,8 @@ where self.message, self.value, gas_limit, - self.storage_deposit_limit, + // todo: the `bare_call` converts this value back, this is unnecessary work + DepositLimit::Balance(dry_run.exec_result.storage_deposit.charge_or_zero()), ) .await?; @@ -184,7 +188,7 @@ where self.caller, self.message, self.value, - self.storage_deposit_limit, + balance_to_deposit_limit::(self.storage_deposit_limit), ) .await } @@ -206,7 +210,7 @@ where value: E::Balance, extra_gas_portion: Option, gas_limit: Option, - storage_deposit_limit: Option, + storage_deposit_limit: DepositLimit, } impl<'a, E, Contract, Args, R, B> InstantiateBuilder<'a, E, Contract, Args, R, B> @@ -235,7 +239,7 @@ where value: 0u32.into(), extra_gas_portion: None, gas_limit: None, - storage_deposit_limit: None, + storage_deposit_limit: DepositLimit::Unchecked, } } @@ -280,13 +284,9 @@ where /// Specify the max amount of funds that can be charged for storage. pub fn storage_deposit_limit( &mut self, - storage_deposit_limit: E::Balance, + storage_deposit_limit: DepositLimit, ) -> &mut Self { - if storage_deposit_limit == 0u32.into() { - self.storage_deposit_limit = None - } else { - self.storage_deposit_limit = Some(storage_deposit_limit) - } + self.storage_deposit_limit = storage_deposit_limit; self } @@ -297,13 +297,16 @@ where pub async fn submit( &mut self, ) -> Result, B::Error> { + // we have to make sure the account was mapped + let _map = B::map_account(self.client, self.caller).await; // todo will fail if instantiation happened before + let dry_run = B::bare_instantiate_dry_run( self.client, self.contract_name, self.caller, self.constructor, self.value, - self.storage_deposit_limit, + self.storage_deposit_limit.clone(), ) .await?; @@ -323,12 +326,14 @@ where self.constructor, self.value, gas_limit, - self.storage_deposit_limit, + balance_to_deposit_limit::( + dry_run.contract_result.storage_deposit.charge_or_zero(), + ), ) .await?; Ok(InstantiationResult { - account_id: instantiate_result.account_id, + addr: instantiate_result.addr, dry_run, events: instantiate_result.events, }) @@ -342,7 +347,7 @@ where self.caller, self.constructor, self.value, - self.storage_deposit_limit, + self.storage_deposit_limit.clone(), ) .await } @@ -357,7 +362,7 @@ where client: &'a mut B, contract_name: &'a str, caller: &'a Keypair, - storage_deposit_limit: Option, + storage_deposit_limit: E::Balance, } impl<'a, E, B> UploadBuilder<'a, E, B> @@ -371,7 +376,7 @@ where client, contract_name, caller, - storage_deposit_limit: None, + storage_deposit_limit: 0u32.into(), } } @@ -380,11 +385,7 @@ where &mut self, storage_deposit_limit: E::Balance, ) -> &mut Self { - if storage_deposit_limit == 0u32.into() { - self.storage_deposit_limit = None - } else { - self.storage_deposit_limit = Some(storage_deposit_limit) - } + self.storage_deposit_limit = storage_deposit_limit; self } @@ -408,7 +409,8 @@ where { client: &'a mut B, caller: &'a Keypair, - code_hash: E::Hash, + code_hash: crate::H256, + _phantom: PhantomData E>, } impl<'a, E, B> RemoveCodeBuilder<'a, E, B> @@ -417,11 +419,12 @@ where B: BuilderClient, { /// Initialize a remove code builder with essential values. - pub fn new(client: &'a mut B, caller: &'a Keypair, code_hash: E::Hash) -> Self { + pub fn new(client: &'a mut B, caller: &'a Keypair, code_hash: H256) -> Self { Self { client, caller, code_hash, + _phantom: Default::default(), } } diff --git a/crates/e2e/src/builders.rs b/crates/e2e/src/builders.rs index 93453c32d4c..24df0a63f54 100644 --- a/crates/e2e/src/builders.rs +++ b/crates/e2e/src/builders.rs @@ -12,12 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. +use crate::H256; use ink_env::{ call::{ utils::{ ReturnType, Set, - Unset, }, CreateBuilder, ExecutionInput, @@ -32,11 +32,8 @@ use scale::Encode; pub type CreateBuilderPartial = CreateBuilder< E, ContractRef, - Unset<::Hash>, - Set>, - Unset<::Balance>, + Set, Set>, - Unset, Set>, >; @@ -50,8 +47,8 @@ where // set all the other properties to default values, we only require the `exec_input`. builder .endowment(0u32.into()) - .code_hash(ink_primitives::Clear::CLEAR_HASH) - .salt_bytes(Vec::new()) + .code_hash(H256::zero()) + .salt_bytes(None) .params() .exec_input() .encode() diff --git a/crates/e2e/src/client_utils.rs b/crates/e2e/src/client_utils.rs index 69b9901fcd9..4ee60916eae 100644 --- a/crates/e2e/src/client_utils.rs +++ b/crates/e2e/src/client_utils.rs @@ -19,16 +19,19 @@ use std::{ }; /// Generate a unique salt based on the system time. -pub fn salt() -> Vec { +pub fn salt() -> Option<[u8; 32]> { use funty::Fundamental as _; - std::time::SystemTime::now() + let mut arr = [0u8; 32]; + let t: [u8; 16] = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_else(|err| panic!("unable to get unix time: {err}")) .as_millis() .as_u128() - .to_le_bytes() - .to_vec() + .to_le_bytes(); + arr[..16].copy_from_slice(t.as_slice()); + arr[16..].copy_from_slice(t.as_slice()); + Some(arr) } /// A registry of contracts that can be loaded. diff --git a/crates/e2e/src/contract_build.rs b/crates/e2e/src/contract_build.rs index c65357fd9e5..813279d9658 100644 --- a/crates/e2e/src/contract_build.rs +++ b/crates/e2e/src/contract_build.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use crate::log_info; use contract_build::{ BuildArtifacts, BuildMode, @@ -22,11 +23,11 @@ use contract_build::{ Network, OptimizationPasses, OutputType, - Target, UnstableFlags, Verbosity, DEFAULT_MAX_MEMORY_PAGES, }; +use itertools::Itertools; use std::{ collections::{ hash_map::Entry, @@ -68,7 +69,11 @@ impl ContractProject { package .features .iter() - .any(|(feat, _)| feat == "ink-as-dependency") + .any(|(feat, _)| { + feat == "ink-as-dependency" + && !package.name.eq("ink") + && !package.name.eq("ink_env") + }) .then(|| package.manifest_path.clone().into_std_path_buf()) } @@ -83,6 +88,7 @@ impl ContractProject { .find(|package| &package.id == root_package_id) }) .and_then(maybe_contract_package); + log_info(&format!("found root package: {:?}", root_package)); let contract_dependencies: Vec = metadata .packages @@ -90,6 +96,10 @@ impl ContractProject { .filter_map(maybe_contract_package) .collect(); + log_info(&format!( + "found those contract dependencies: {:?}", + contract_dependencies + )); Self { root_package, contract_dependencies, @@ -109,7 +119,7 @@ impl ContractProject { .map(PathBuf::from) .collect(); all_manifests.append(&mut additional_contracts); - all_manifests + all_manifests.into_iter().unique().collect() } fn root_with_contract_dependencies(&self) -> Vec { @@ -129,7 +139,7 @@ fn build_contracts(contract_manifests: &[PathBuf]) -> Vec { .lock() .unwrap(); - let mut wasm_paths = Vec::new(); + let mut blob_paths = Vec::new(); for manifest in contract_manifests { let wasm_path = match contract_build_jobs.entry(manifest.clone()) { Entry::Occupied(entry) => entry.get().clone(), @@ -139,13 +149,13 @@ fn build_contracts(contract_manifests: &[PathBuf]) -> Vec { wasm_path } }; - wasm_paths.push(wasm_path); + blob_paths.push(wasm_path); } - wasm_paths + blob_paths } /// Builds the contract at `manifest_path`, returns the path to the contract -/// Wasm build artifact. +/// PolkaVM build artifact. fn build_contract(path_to_cargo_toml: &Path) -> PathBuf { let manifest_path = ManifestPath::new(path_to_cargo_toml).unwrap_or_else(|err| { panic!( @@ -165,8 +175,8 @@ fn build_contract(path_to_cargo_toml: &Path) -> PathBuf { keep_debug_symbols: false, extra_lints: false, output_type: OutputType::HumanReadable, + // todo remove skip_wasm_validation: false, - target: Target::Wasm, max_memory_pages: DEFAULT_MAX_MEMORY_PAGES, image: ImageVariant::Default, }; @@ -175,7 +185,7 @@ fn build_contract(path_to_cargo_toml: &Path) -> PathBuf { Ok(build_result) => { build_result .dest_wasm - .expect("Wasm code artifact not generated") + .expect("PolkaVM code artifact not generated") .canonicalize() .expect("Invalid dest bundle path") } diff --git a/crates/e2e/src/contract_results.rs b/crates/e2e/src/contract_results.rs index 2c19473a270..e9b6209f8ca 100644 --- a/crates/e2e/src/contract_results.rs +++ b/crates/e2e/src/contract_results.rs @@ -12,21 +12,30 @@ // See the License for the specific language governing permissions and // limitations under the License. +use frame_support::pallet_prelude::{ + Decode, + Encode, +}; use ink::codegen::ContractCallBuilder; use ink_env::{ - call::FromAccountId, + call::FromAddr, Environment, }; use ink_primitives::{ ConstructorResult, MessageResult, + H256, }; -use pallet_contracts::{ +use pallet_revive::{ + evm::H160, CodeUploadResult, - ContractExecResult, - ContractInstantiateResult, ExecReturnValue, InstantiateReturnValue, + StorageDeposit, +}; +use sp_runtime::{ + DispatchError, + Weight, }; use std::{ fmt, @@ -34,38 +43,89 @@ use std::{ marker::PhantomData, }; +/// Alias for the contract instantiate result. +pub type ContractInstantiateResultForBar = + ContractResult::Balance>; + +/// Result type of a `bare_call`, `bare_instantiate`, `ReviveApi::call`, and +/// `ReviveApi::instantiate`. +/// +/// It contains the execution result together with some auxiliary information. +/// +/// # Note +/// +/// It has been extended to include `events` at the end of the struct while not bumping +/// the `ReviveApi` version. Therefore when SCALE decoding a `ContractResult` its +/// trailing data should be ignored to avoid any potential compatibility issues. +#[derive(Debug, Clone, Eq, PartialEq, Encode, Decode)] +pub struct ContractResult { + /// How much weight was consumed during execution. + pub gas_consumed: Weight, + /// How much weight is required as gas limit in order to execute this call. + /// + /// This value should be used to determine the weight limit for on-chain execution. + /// + /// # Note + /// + /// This can only different from [`Self::gas_consumed`] when weight pre-charging + /// is used. Currently, only `seal_call_runtime` makes use of pre-charging. + /// Additionally, any `seal_call` or `seal_instantiate` makes use of pre-charging + /// when a non-zero `gas_limit` argument is supplied. + pub gas_required: Weight, + /// How much balance was paid by the origin into the contract's deposit account in + /// order to pay for storage. + /// + /// The storage deposit is never actually charged from the origin in case of + /// [`Self::result`] is `Err`. This is because on error all storage changes are + /// rolled back including the payment of the deposit. + pub storage_deposit: StorageDeposit, + /// An optional debug message. This message is only filled when explicitly requested + /// by the code that calls into the contract. Otherwise it is empty. + /// + /// The contained bytes are valid UTF-8. This is not declared as `String` because + /// this type is not allowed within the runtime. + /// + /// Clients should not make any assumptions about the format of the buffer. + /// They should just display it as-is. It is **not** only a collection of log lines + /// provided by a contract but a formatted buffer with different sections. + /// + /// # Note + /// + /// The debug message is never generated during on-chain execution. It is reserved + /// for RPC calls. + pub debug_message: Vec, + /// The execution result of the Wasm code. + pub result: Result, +} + +/// Alias for the contract exec result. +pub type ContractExecResultFor = + ContractResult::Balance>; + /// Result of a contract instantiation using bare call. -pub struct BareInstantiationResult { - /// The account id at which the contract was instantiated. - pub account_id: E::AccountId, +pub struct BareInstantiationResult { + /// The address at which the contract was instantiated. + pub addr: H160, /// Events that happened with the contract instantiation. pub events: EventLog, } -impl BareInstantiationResult { +impl BareInstantiationResult { /// Returns the account id at which the contract was instantiated. - pub fn call(&self) -> ::Type - where - Contract: ContractCallBuilder, - Contract::Type: FromAccountId, - { - <::Type as FromAccountId>::from_account_id( - self.account_id.clone(), - ) + pub fn call(&self) -> H160 { + self.addr } } /// We implement a custom `Debug` here, as to avoid requiring the trait bound `Debug` for /// `E`. -impl Debug for BareInstantiationResult +impl Debug for BareInstantiationResult where - E::AccountId: Debug, - E::Balance: Debug, EventLog: Debug, { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { f.debug_struct("InstantiationResult") - .field("account_id", &self.account_id) + .field("addr", &self.addr) .field("events", &self.events) .finish() } @@ -74,7 +134,7 @@ where /// Result of a contract instantiation. pub struct InstantiationResult { /// The account id at which the contract was instantiated. - pub account_id: E::AccountId, + pub addr: H160, /// The result of the dry run, contains debug messages /// if there were any. pub dry_run: InstantiateDryRunResult, @@ -87,11 +147,9 @@ impl InstantiationResult { pub fn call_builder(&self) -> ::Type where Contract: ContractCallBuilder, - Contract::Type: FromAccountId, + Contract::Type: FromAddr, { - <::Type as FromAccountId>::from_account_id( - self.account_id.clone(), - ) + <::Type as FromAddr>::from_addr(self.addr) } } @@ -101,11 +159,12 @@ impl Debug for InstantiationResult where E::AccountId: Debug, E::Balance: Debug, + E::EventRecord: Debug, EventLog: Debug, { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { f.debug_struct("InstantiationResult") - .field("account_id", &self.account_id) + .field("addr", &self.addr) .field("dry_run", &self.dry_run) .field("events", &self.events) .finish() @@ -115,9 +174,9 @@ where /// Result of a contract upload. pub struct UploadResult { /// The hash with which the contract can be instantiated. - pub code_hash: E::Hash, + pub code_hash: H256, /// The result of the dry run, contains debug messages if there were any. - pub dry_run: CodeUploadResult, + pub dry_run: CodeUploadResult, /// Events that happened with the contract instantiation. pub events: EventLog, } @@ -127,7 +186,7 @@ pub struct UploadResult { impl Debug for UploadResult where E::Balance: Debug, - E::Hash: Debug, + H256: Debug, EventLog: Debug, { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { @@ -184,6 +243,7 @@ impl Debug for CallResult where E: Debug, E::Balance: Debug, + E::EventRecord: Debug, V: Debug, EventLog: Debug, { @@ -196,13 +256,26 @@ where } /// Result of the dry run of a contract call. -#[derive(Debug)] pub struct CallDryRunResult { /// The result of the dry run, contains debug messages if there were any. - pub exec_result: ContractExecResult, + pub exec_result: ContractExecResultFor, pub _marker: PhantomData, } +/// We implement a custom `Debug` here, as to avoid requiring the trait bound `Debug` for +/// `E`. +impl Debug for CallDryRunResult +where + E::Balance: Debug, + E::EventRecord: Debug, +{ + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("CallDryRunResult") + .field("exec_result", &self.exec_result) + .finish() + } +} + impl CallDryRunResult { /// Returns true if the dry-run execution resulted in an error. pub fn is_err(&self) -> bool { @@ -262,15 +335,13 @@ impl CallDryRunResult { /// Result of the dry run of a contract call. pub struct InstantiateDryRunResult { /// The result of the dry run, contains debug messages if there were any. - pub contract_result: ContractInstantiateResult, + pub contract_result: ContractInstantiateResultForBar, } -impl From> +impl From> for InstantiateDryRunResult { - fn from( - contract_result: ContractInstantiateResult, - ) -> Self { + fn from(contract_result: ContractInstantiateResultForBar) -> Self { Self { contract_result } } } @@ -284,7 +355,7 @@ impl InstantiateDryRunResult { /// Returns the [`InstantiateReturnValue`] resulting from the dry-run message call. /// /// Panics if the dry-run message call failed to execute. - pub fn instantiate_return_value(&self) -> &InstantiateReturnValue { + pub fn instantiate_return_value(&self) -> &InstantiateReturnValue { self.contract_result .result .as_ref() @@ -314,6 +385,7 @@ where E: Environment, E::AccountId: Debug, E::Balance: Debug, + E::EventRecord: Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("InstantiateDryRunResult") diff --git a/crates/e2e/src/error.rs b/crates/e2e/src/error.rs index f043607f8a5..2b31d23f22d 100644 --- a/crates/e2e/src/error.rs +++ b/crates/e2e/src/error.rs @@ -12,8 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -use pallet_contracts::ContractExecResult; - use std::fmt; /// An error occurred while interacting with the E2E backend. @@ -96,11 +94,3 @@ impl fmt::Display for SandboxErr { write!(f, "SandboxErr: {}", self.msg) } } - -impl From> for SandboxErr { - fn from(_value: ContractExecResult) -> Self { - Self { - msg: "ContractExecResult".to_string(), - } - } -} diff --git a/crates/e2e/src/events.rs b/crates/e2e/src/events.rs index 96c5a605d3b..93819603e03 100644 --- a/crates/e2e/src/events.rs +++ b/crates/e2e/src/events.rs @@ -12,10 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -use ink_env::Environment; +use crate::H256; +use pallet_revive::evm::H160; #[cfg(feature = "std")] use std::fmt::Debug; - use subxt::{ events::StaticEvent, ext::{ @@ -34,18 +34,15 @@ use subxt::{ )] #[decode_as_type(trait_bounds = "", crate_path = "subxt::ext::scale_decode")] #[encode_as_type(crate_path = "subxt::ext::scale_encode")] -pub struct ContractInstantiatedEvent { - /// Account id of the deployer. - pub deployer: E::AccountId, - /// Account id where the contract was instantiated to. - pub contract: E::AccountId, +pub struct ContractInstantiatedEvent { + /// Address of the deployer. + pub deployer: H160, + /// Address where the contract was instantiated to. + pub contract: H160, } -impl StaticEvent for ContractInstantiatedEvent -where - E: Environment, -{ - const PALLET: &'static str = "Contracts"; +impl StaticEvent for ContractInstantiatedEvent { + const PALLET: &'static str = "Revive"; const EVENT: &'static str = "Instantiated"; } @@ -59,16 +56,13 @@ where )] #[decode_as_type(trait_bounds = "", crate_path = "subxt::ext::scale_decode")] #[encode_as_type(crate_path = "subxt::ext::scale_encode")] -pub struct CodeStoredEvent { +pub struct CodeStoredEvent { /// Hash under which the contract code was stored. - pub code_hash: E::Hash, + pub code_hash: H256, } -impl StaticEvent for CodeStoredEvent -where - E: Environment, -{ - const PALLET: &'static str = "Contracts"; +impl StaticEvent for CodeStoredEvent { + const PALLET: &'static str = "Revive"; const EVENT: &'static str = "CodeStored"; } @@ -82,21 +76,19 @@ where #[decode_as_type(trait_bounds = "", crate_path = "subxt::ext::scale_decode")] #[encode_as_type(crate_path = "subxt::ext::scale_encode")] /// A custom event emitted by the contract. -pub struct ContractEmitted { - pub contract: E::AccountId, +pub struct ContractEmitted { + pub contract: H160, pub data: Vec, + pub topics: Vec, } -impl StaticEvent for ContractEmitted -where - E: Environment, -{ - const PALLET: &'static str = "Contracts"; +impl StaticEvent for ContractEmitted { + const PALLET: &'static str = "Revive"; const EVENT: &'static str = "ContractEmitted"; } /// A decoded event with its associated topics. pub struct EventWithTopics { - pub topics: Vec, + pub topics: Vec, pub event: T, } diff --git a/crates/e2e/src/lib.rs b/crates/e2e/src/lib.rs index 61cfada3a84..d6a2daad8ad 100644 --- a/crates/e2e/src/lib.rs +++ b/crates/e2e/src/lib.rs @@ -35,6 +35,7 @@ mod xts; pub use crate::contract_build::build_root_and_contract_dependencies; pub use backend::{ + BuilderClient, ChainBackend, ContractsBackend, E2EBackend, @@ -60,8 +61,7 @@ pub use sandbox_client::{ preset, Client as SandboxClient, }; -pub use sp_core::H256; -pub use sp_keyring::AccountKeyring; +pub use sp_keyring::Sr25519Keyring; pub use subxt::{ self, backend::rpc::RpcClient, @@ -87,19 +87,21 @@ pub use ink_sandbox::DefaultSandbox; use ink::codegen::ContractCallBuilder; use ink_env::{ - call::FromAccountId, + call::FromAddr, ContractEnv, Environment, }; -use pallet_contracts::{ - ContractExecResult, - ContractInstantiateResult, +use ink_primitives::{ + AccountId, + DepositLimit, + H160, + H256, }; use std::{ cell::RefCell, sync::Once, }; -use xts::ContractsApi; +use xts::ReviveApi; pub use subxt::PolkadotConfig; @@ -132,22 +134,46 @@ pub fn log_error(msg: &str) { } /// Get an ink! [`ink_primitives::AccountId`] for a given keyring account. -pub fn account_id(account: AccountKeyring) -> ink_primitives::AccountId { +pub fn account_id(account: Sr25519Keyring) -> ink_primitives::AccountId { ink_primitives::AccountId::try_from(account.to_account_id().as_ref()) .expect("account keyring has a valid account id") } -/// Creates a call builder builder for `Contract`, based on an account id. +/// Returns the [`ink::H160`] for a given keyring account. +/// +/// # Developer Note +/// +/// We take the `AccountId` and return only the first twenty bytes, this +/// is what `pallet-revive` does as well. +pub fn address(account: Sr25519Keyring) -> H160 { + let account_id = account_id(account); + H160::from_slice(&>::as_ref(&account_id)[..20]) +} + +/// Creates a call builder for `Contract`, based on an account id. pub fn create_call_builder( - acc_id: <::Env as Environment>::AccountId, + acc_id: H160, ) -> ::Type where ::Env: Environment, Contract: ContractCallBuilder, Contract: ContractEnv, - Contract::Type: FromAccountId<::Env>, + Contract::Type: FromAddr, { - <::Type as FromAccountId< - ::Env, - >>::from_account_id(acc_id) + <::Type as FromAddr>::from_addr(acc_id) +} + +fn balance_to_deposit_limit( + b: ::Balance, +) -> DepositLimit<::Balance> { + DepositLimit::Balance(b) +} + +fn deposit_limit_to_balance( + l: DepositLimit<::Balance>, +) -> ::Balance { + match l { + DepositLimit::Balance(l) => l, + DepositLimit::Unchecked => panic!("oh no"), + } } diff --git a/crates/e2e/src/node_proc.rs b/crates/e2e/src/node_proc.rs index ed707953248..b39c8572bdb 100644 --- a/crates/e2e/src/node_proc.rs +++ b/crates/e2e/src/node_proc.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use sp_keyring::AccountKeyring; +use sp_keyring::Sr25519Keyring; use std::{ ffi::{ OsStr, @@ -113,7 +113,7 @@ where /// Construct a test node process. pub struct TestNodeProcessBuilder { node_path: OsString, - authority: Option, + authority: Option, marker: std::marker::PhantomData, } @@ -133,7 +133,7 @@ where } /// Set the authority development account for a node in validator mode e.g. --alice. - pub fn with_authority(&mut self, account: AccountKeyring) -> &mut Self { + pub fn with_authority(&mut self, account: Sr25519Keyring) -> &mut Self { self.authority = Some(account); self } @@ -146,7 +146,8 @@ where .stdout(process::Stdio::piped()) .stderr(process::Stdio::piped()) .arg("--port=0") - .arg("--rpc-port=0"); + .arg("--rpc-port=0") + .arg("-lruntime::revive=debug"); if let Some(authority) = self.authority { let authority = format!("{authority:?}"); diff --git a/crates/e2e/src/sandbox_client.rs b/crates/e2e/src/sandbox_client.rs index e6f12032b0f..7fe005ea875 100644 --- a/crates/e2e/src/sandbox_client.rs +++ b/crates/e2e/src/sandbox_client.rs @@ -22,7 +22,11 @@ use crate::{ salt, ContractsRegistry, }, - contract_results::BareInstantiationResult, + contract_results::{ + BareInstantiationResult, + ContractExecResultFor, + ContractResult, + }, error::SandboxErr, log_error, CallBuilderFinal, @@ -32,26 +36,35 @@ use crate::{ E2EBackend, InstantiateDryRunResult, UploadResult, + H256, }; - -use frame_support::traits::fungible::Inspect; +use frame_support::{ + dispatch::RawOrigin, + pallet_prelude::DispatchError, + traits::{ + fungible::Inspect, + IsType, + }, +}; +use ink_env::Environment; +use ink_primitives::DepositLimit; use ink_sandbox::{ api::prelude::*, + frame_system, + frame_system::pallet_prelude::OriginFor, pallet_balances, - pallet_contracts, + pallet_revive, AccountIdFor, RuntimeCall, Sandbox, Weight, }; -use pallet_contracts::ContractResult; - -use ink_env::Environment; use jsonrpsee::core::async_trait; -use pallet_contracts::{ +use pallet_revive::{ + evm::U256, CodeUploadReturnValue, - ContractInstantiateResult, InstantiateReturnValue, + MomentOf, }; use scale::{ Decode, @@ -61,6 +74,7 @@ use sp_core::{ sr25519::Pair, Pair as _, }; +use sp_runtime::traits::Bounded; use std::{ marker::PhantomData, path::PathBuf, @@ -73,22 +87,22 @@ use subxt_signer::sr25519::Keypair; type BalanceOf = ::Balance; type ContractsBalanceOf = - <::Currency as Inspect>>::Balance; + <::Currency as Inspect>>::Balance; -pub struct Client { +pub struct Client { sandbox: S, contracts: ContractsRegistry, - _phantom: PhantomData<(AccountId, Hash)>, + _phantom: PhantomData, } // While it is not necessary true that `Client` is `Send`, it will not be used in a way // that would violate this bound. In particular, all `Client` instances will be operating // synchronously. -unsafe impl Send for Client {} -impl Client +unsafe impl Send for Client {} +impl Client where S: Default, - S::Runtime: pallet_balances::Config + pallet_contracts::Config, + S::Runtime: pallet_balances::Config + pallet_revive::Config, AccountIdFor: From<[u8; 32]>, BalanceOf: From, { @@ -127,8 +141,7 @@ where } #[async_trait] -impl + Send, Hash, S: Sandbox> ChainBackend - for Client +impl + Send, S: Sandbox> ChainBackend for Client where S::Runtime: pallet_balances::Config, AccountIdFor: From<[u8; 32]>, @@ -208,18 +221,21 @@ where #[async_trait] impl< AccountId: Clone + Send + Sync + From<[u8; 32]> + AsRef<[u8; 32]>, - Hash: Copy + Send + From<[u8; 32]>, S: Sandbox, - E: Environment< - AccountId = AccountId, - Balance = ContractsBalanceOf, - Hash = Hash, - > + 'static, - > BuilderClient for Client + E: Environment> + + 'static, + > BuilderClient for Client where - S::Runtime: pallet_balances::Config + pallet_contracts::Config, + S::Runtime: pallet_balances::Config + pallet_revive::Config, AccountIdFor: From<[u8; 32]> + AsRef<[u8; 32]>, ContractsBalanceOf: Send + Sync, + + ContractsBalanceOf: Into + TryFrom + Bounded, + MomentOf: Into, + + // todo + <::Runtime as frame_system::Config>::Hash: + frame_support::traits::IsType, { async fn bare_instantiate( &mut self, @@ -228,8 +244,11 @@ where constructor: &mut CreateBuilderPartial, value: E::Balance, gas_limit: Weight, - storage_deposit_limit: Option, - ) -> Result, Self::Error> { + storage_deposit_limit: DepositLimit, + ) -> Result, Self::Error> { + let _ = + as BuilderClient>::map_account(self, caller).await; + let code = self.contracts.load_code(contract_name); let data = constructor_exec_input(constructor.clone()); @@ -238,22 +257,21 @@ where value, data, salt(), - keypair_to_account(caller), + caller_to_origin::(caller), gas_limit, storage_deposit_limit, ); - let account_id_raw = match &result.result { + let addr_raw = match &result.result { Err(err) => { log_error(&format!("Instantiation failed: {err:?}")); return Err(SandboxErr::new(format!("bare_instantiate: {err:?}"))); } - Ok(res) => *res.account_id.as_ref(), + Ok(res) => res.addr, }; - let account_id = AccountId::from(account_id_raw); Ok(BareInstantiationResult { - account_id: account_id.clone(), + addr: addr_raw, events: (), // todo: https://github.com/Cardinal-Cryptography/drink/issues/32 }) } @@ -264,8 +282,13 @@ where caller: &Keypair, constructor: &mut CreateBuilderPartial, value: E::Balance, - storage_deposit_limit: Option, + storage_deposit_limit: DepositLimit, ) -> Result, Self::Error> { + // todo has to be: let _ = as + // BuilderClient>::map_account_dry_run(self, &caller).await; + let _ = + as BuilderClient>::map_account(self, caller).await; + let code = self.contracts.load_code(contract_name); let data = constructor_exec_input(constructor.clone()); let result = self.sandbox.dry_run(|sandbox| { @@ -274,21 +297,20 @@ where value, data, salt(), - keypair_to_account(caller), + caller_to_origin::(caller), S::default_gas_limit(), storage_deposit_limit, ) }); - let account_id_raw = match &result.result { + let addr_id_raw = match &result.result { Err(err) => { panic!("Instantiate dry-run failed: {err:?}!") } - Ok(res) => *res.account_id.as_ref(), + Ok(res) => res.addr, }; - let account_id = AccountId::from(account_id_raw); - let result = ContractInstantiateResult { + let result = ContractResult:: { gas_consumed: result.gas_consumed, gas_required: result.gas_required, storage_deposit: result.storage_deposit, @@ -296,10 +318,9 @@ where result: result.result.map(|r| { InstantiateReturnValue { result: r.result, - account_id, + addr: addr_id_raw, // todo } }), - events: None, }; Ok(result.into()) } @@ -308,15 +329,14 @@ where &mut self, contract_name: &str, caller: &Keypair, - storage_deposit_limit: Option, + storage_deposit_limit: E::Balance, ) -> Result, Self::Error> { let code = self.contracts.load_code(contract_name); let result = match self.sandbox.upload_contract( code, - keypair_to_account(caller), + caller_to_origin::(caller), storage_deposit_limit, - pallet_contracts::Determinism::Enforced, ) { Ok(result) => result, Err(err) => { @@ -325,16 +345,10 @@ where } }; - let code_hash_raw: [u8; 32] = result - .code_hash - .as_ref() - .try_into() - .expect("Invalid code hash"); - let code_hash = Hash::from(code_hash_raw); Ok(UploadResult { - code_hash, + code_hash: result.code_hash, dry_run: Ok(CodeUploadReturnValue { - code_hash, + code_hash: result.code_hash, deposit: result.deposit, }), events: (), @@ -344,7 +358,7 @@ where async fn bare_remove_code( &mut self, _caller: &Keypair, - _code_hash: E::Hash, + _code_hash: H256, ) -> Result { unimplemented!("sandbox does not yet support remove_code") } @@ -355,24 +369,26 @@ where message: &CallBuilderFinal, value: E::Balance, gas_limit: Weight, - storage_deposit_limit: Option, + storage_deposit_limit: DepositLimit, ) -> Result where CallBuilderFinal: Clone, { - let account_id = message.clone().params().callee().clone(); + let _ = + as BuilderClient>::map_account(self, caller).await; + + // todo rename any account_id coming back from callee + let addr = *message.clone().params().callee(); let exec_input = Encode::encode(message.clone().params().exec_input()); - let account_id = (*account_id.as_ref()).into(); self.sandbox .call_contract( - account_id, + addr, value, exec_input, - keypair_to_account(caller), + caller_to_origin::(caller), gas_limit, storage_deposit_limit, - pallet_contracts::Determinism::Enforced, ) .result .map_err(|err| SandboxErr::new(format!("bare_call: {err:?}")))?; @@ -385,54 +401,93 @@ where caller: &Keypair, message: &CallBuilderFinal, value: E::Balance, - storage_deposit_limit: Option, + storage_deposit_limit: DepositLimit, ) -> Result, Self::Error> where CallBuilderFinal: Clone, { - let account_id = message.clone().params().callee().clone(); + // todo there's side effects here + let _ = + as BuilderClient>::map_account(self, caller).await; + + let addr = *message.clone().params().callee(); let exec_input = Encode::encode(message.clone().params().exec_input()); - let account_id = (*account_id.as_ref()).into(); let result = self.sandbox.dry_run(|sandbox| { sandbox.call_contract( - account_id, + addr, value, exec_input, - keypair_to_account(caller), + caller_to_origin::(caller), S::default_gas_limit(), storage_deposit_limit, - pallet_contracts::Determinism::Enforced, ) }); + if result.result.is_err() { + let res = result.result.clone().unwrap_err(); + if let DispatchError::Module(m) = res { + let msg = m.message; + if msg.is_some() { + let s = msg.unwrap(); + if s.contains("AccountUnmapped") { + panic!("something is wrong, we mapped the account before") + } + } + } + } + // todo error when `AccountUnmapped` Ok(CallDryRunResult { - exec_result: ContractResult { + exec_result: ContractExecResultFor:: { gas_consumed: result.gas_consumed, gas_required: result.gas_required, storage_deposit: result.storage_deposit, debug_message: result.debug_message, result: result.result, - events: None, }, _marker: Default::default(), }) } + + async fn map_account_dry_run(&mut self, caller: &Keypair) -> Result<(), Self::Error> { + let caller = keypair_to_account(caller); + let origin = RawOrigin::Signed(caller); + let origin = OriginFor::::from(origin); + + self.sandbox + .dry_run(|sandbox| sandbox.map_account(origin)) + .map_err(|err| { + SandboxErr::new(format!("map_account_dry_run: execution error {:?}", err)) + }) + } + + async fn map_account(&mut self, caller: &Keypair) -> Result<(), Self::Error> { + let caller = keypair_to_account(caller); + let origin = RawOrigin::Signed(caller); + let origin = OriginFor::::from(origin); + + self.sandbox.map_account(origin).map_err(|err| { + SandboxErr::new(format!("map_account: execution error {:?}", err)) + }) + } } impl< AccountId: Clone + Send + Sync + From<[u8; 32]> + AsRef<[u8; 32]>, - Hash: Copy + Send + From<[u8; 32]>, Config: Sandbox, E: Environment< AccountId = AccountId, Balance = ContractsBalanceOf, - Hash = Hash, > + 'static, - > E2EBackend for Client + > E2EBackend for Client where - Config::Runtime: pallet_balances::Config + pallet_contracts::Config, + Config::Runtime: pallet_balances::Config + pallet_revive::Config, AccountIdFor: From<[u8; 32]> + AsRef<[u8; 32]>, ContractsBalanceOf: Send + Sync, + ContractsBalanceOf: Into + TryFrom + Bounded, + MomentOf: Into, + + // todo + ::Hash: IsType, { } @@ -440,19 +495,26 @@ fn keypair_to_account>(keypair: &Keypair) -> AccountId AccountId::from(keypair.public_key().0) } +fn caller_to_origin(caller: &Keypair) -> OriginFor +where + S: Sandbox, + S::Runtime: pallet_balances::Config + pallet_revive::Config, + AccountIdFor: From<[u8; 32]> + AsRef<[u8; 32]>, +{ + let caller = keypair_to_account(caller); + let origin = RawOrigin::Signed(caller); + OriginFor::::from(origin) +} + #[async_trait] impl< AccountId: Clone + Send + Sync + From<[u8; 32]> + AsRef<[u8; 32]>, - Hash: Copy + From<[u8; 32]>, S: Sandbox, - E: Environment< - AccountId = AccountId, - Balance = ContractsBalanceOf, - Hash = Hash, - > + 'static, - > ContractsBackend for Client + E: Environment> + + 'static, + > ContractsBackend for Client where - S::Runtime: pallet_balances::Config + pallet_contracts::Config, + S::Runtime: pallet_balances::Config + pallet_revive::Config, AccountIdFor: From<[u8; 32]> + AsRef<[u8; 32]>, { type Error = SandboxErr; @@ -471,7 +533,7 @@ pub mod preset { Sandbox, Snapshot, }; - pub use pallet_contracts_mock_network::*; + pub use pallet_revive_mock_network::*; use sp_runtime::traits::Dispatchable; /// A [`ink_sandbox::Sandbox`] that can be used to test contracts diff --git a/crates/e2e/src/subxt_client.rs b/crates/e2e/src/subxt_client.rs index ba70d5e3129..7415734fc58 100644 --- a/crates/e2e/src/subxt_client.rs +++ b/crates/e2e/src/subxt_client.rs @@ -17,6 +17,7 @@ use super::{ constructor_exec_input, CreateBuilderPartial, }, + deposit_limit_to_balance, events::{ CodeStoredEvent, ContractInstantiatedEvent, @@ -25,9 +26,10 @@ use super::{ log_error, log_info, sr25519, - ContractsApi, InstantiateDryRunResult, Keypair, + ReviveApi, + H256, }; use crate::{ backend::BuilderClient, @@ -49,8 +51,8 @@ use ink_env::{ }, Environment, }; +use ink_primitives::DepositLimit; use jsonrpsee::core::async_trait; -use pallet_contracts::ContractResult; use scale::{ Decode, Encode, @@ -66,6 +68,7 @@ use crate::{ salt, ContractsRegistry, }, + contract_results::ContractResult, error::DryRunError, events, ContractsBackend, @@ -92,7 +95,7 @@ pub type Error = crate::error::Error; /// Represents an initialized contract message builder. pub type CallBuilderFinal = ink_env::call::CallBuilder< E, - Set>, + Set, Set>, Set>, >; @@ -106,7 +109,7 @@ where C: subxt::Config, E: Environment, { - api: ContractsApi, + api: ReviveApi, contracts: ContractsRegistry, } @@ -122,8 +125,9 @@ where E: Environment, E::AccountId: Debug, + E::EventRecord: Debug, E::Balance: Debug + scale::HasCompact + serde::Serialize, - E::Hash: Debug + scale::Encode, + H256: Debug + scale::Encode, { /// Creates a new [`Client`] instance using a `subxt` client. pub async fn new>( @@ -131,7 +135,7 @@ where contracts: impl IntoIterator, ) -> Result { Ok(Self { - api: ContractsApi::new(client).await?, + api: ReviveApi::new(client).await?, contracts: ContractsRegistry::new(contracts), }) } @@ -144,8 +148,8 @@ where data: Vec, value: E::Balance, gas_limit: Weight, - storage_deposit_limit: Option, - ) -> Result>, Error> { + storage_deposit_limit: E::Balance, + ) -> Result>, Error> { let salt = salt(); let tx_events = self @@ -161,14 +165,14 @@ where ) .await; - let mut account_id = None; + let mut addr = None; for evt in tx_events.iter() { let evt = evt.unwrap_or_else(|err| { panic!("unable to unwrap event: {err:?}"); }); if let Some(instantiated) = evt - .as_event::>() + .as_event::() .unwrap_or_else(|err| { panic!("event conversion to `Instantiated` failed: {err:?}"); }) @@ -177,7 +181,7 @@ where "contract was instantiated at {:?}", instantiated.contract )); - account_id = Some(instantiated.contract); + addr = Some(instantiated.contract); // We can't `break` here, we need to assign the account id from the // last `ContractInstantiatedEvent`, in case the contract instantiates @@ -193,12 +197,12 @@ where return Err(Error::InstantiateExtrinsic(dispatch_error)) } } - let account_id = account_id.expect("cannot extract `account_id` from events"); + let addr = addr.expect("cannot extract `account_id` from events"); Ok(BareInstantiationResult { // The `account_id` must exist at this point. If the instantiation fails // the dry-run must already return that. - account_id, + addr, events: tx_events, }) } @@ -208,9 +212,12 @@ where &mut self, signer: &Keypair, code: Vec, - storage_deposit_limit: Option, + _storage_deposit_limit: E::Balance, ) -> Result>, Error> { - // dry run the instantiate to calculate the gas limit + // todo + let storage_deposit_limit: E::Balance = unsafe { + core::mem::transmute_copy::::Balance>(&u128::MAX) + }; let dry_run = self .api .upload_dry_run(signer, code.clone(), storage_deposit_limit) @@ -230,7 +237,7 @@ where }); if let Some(uploaded) = - evt.as_event::>().unwrap_or_else(|err| { + evt.as_event::().unwrap_or_else(|err| { panic!("event conversion to `Uploaded` failed: {err:?}"); }) { @@ -251,7 +258,8 @@ where } } - // The `pallet-contracts` behavior is that if the code was already stored on the + // todo still up to date? + // The `pallet-revive` behavior is that if the code was already stored on the // chain we won't get an event with the hash, but the extrinsic will still // succeed. We then don't error (`cargo-contract` would), but instead // return the hash from the dry-run. @@ -272,20 +280,14 @@ where }) } + /// todo check if comment still holds /// Transforms a [`ContractResult`] from a dry run into a [`Result`] type, containing /// details of the [`DispatchError`] if the dry run failed. #[allow(clippy::type_complexity)] fn contract_result_to_result( &self, - contract_result: ContractResult< - Result, - E::Balance, - (), - >, - ) -> Result< - ContractResult, E::Balance, ()>, - DryRunError, - > { + contract_result: ContractResult, + ) -> Result, DryRunError> { if let Err(error) = contract_result.result { let debug_message = String::from_utf8(contract_result.debug_message.clone()) .expect("invalid utf8 debug message"); @@ -339,6 +341,7 @@ where + TryFrom + scale::HasCompact + serde::Serialize, + E::EventRecord: Debug, { type AccountId = E::AccountId; type Balance = E::Balance; @@ -472,9 +475,10 @@ where E: Environment, E::AccountId: Debug + Send + Sync, + E::EventRecord: Debug, E::Balance: Clone + Debug + Send + Sync + From + scale::HasCompact + serde::Serialize, - E::Hash: Debug + Send + Sync + scale::Encode, + H256: Debug + Send + Sync + scale::Encode, { async fn bare_instantiate( &mut self, @@ -483,14 +487,15 @@ where constructor: &mut CreateBuilderPartial, value: E::Balance, gas_limit: Weight, - storage_deposit_limit: Option, - ) -> Result, Self::Error> { + storage_deposit_limit: DepositLimit, + ) -> Result, Self::Error> { let code = self.contracts.load_code(contract_name); let data = constructor_exec_input(constructor.clone()); + let storage_deposit_limit = deposit_limit_to_balance::(storage_deposit_limit); let ret = self .exec_instantiate(caller, code, data, value, gas_limit, storage_deposit_limit) .await?; - log_info(&format!("instantiated contract at {:?}", ret.account_id)); + log_info(&format!("instantiated contract at {:?}", ret.addr)); Ok(ret) } @@ -504,8 +509,12 @@ where caller: &Keypair, constructor: &mut CreateBuilderPartial, value: E::Balance, - storage_deposit_limit: Option, + storage_deposit_limit: DepositLimit, ) -> Result, Self::Error> { + // todo beware side effect! this is wrong, we have to batch up the `map_account` + // into the RPC dry run instead + let _ = self.map_account(caller).await; + let code = self.contracts.load_code(contract_name); let data = constructor_exec_input(constructor.clone()); @@ -521,6 +530,11 @@ where ) .await; + log_info(&format!("instantiate dry run: {:?}", &result.result)); + log_info(&format!( + "instantiate dry run debug message: {}", + String::from_utf8_lossy(&result.debug_message) + )); let result = self .contract_result_to_result(result) .map_err(Error::InstantiateDryRun)?; @@ -532,7 +546,7 @@ where &mut self, contract_name: &str, caller: &Keypair, - storage_deposit_limit: Option, + storage_deposit_limit: E::Balance, ) -> Result, Self::Error> { let code = self.contracts.load_code(contract_name); let ret = self @@ -545,7 +559,7 @@ where async fn bare_remove_code( &mut self, caller: &Keypair, - code_hash: E::Hash, + code_hash: H256, ) -> Result { let tx_events = self.api.remove_code(caller, code_hash).await; @@ -572,22 +586,22 @@ where message: &CallBuilderFinal, value: E::Balance, gas_limit: Weight, - storage_deposit_limit: Option, + storage_deposit_limit: DepositLimit, ) -> Result where CallBuilderFinal: Clone, { - let account_id = message.clone().params().callee().clone(); + let addr = *message.clone().params().callee(); let exec_input = Encode::encode(message.clone().params().exec_input()); log_info(&format!("call: {:02X?}", exec_input)); let tx_events = self .api .call( - subxt::utils::MultiAddress::Id(account_id.clone()), + addr, value, gas_limit.into(), - storage_deposit_limit, + deposit_limit_to_balance::(storage_deposit_limit), exec_input, caller, ) @@ -611,17 +625,22 @@ where Ok(tx_events) } + // todo is not really a `bare_call` async fn bare_call_dry_run( &mut self, caller: &Keypair, message: &CallBuilderFinal, value: E::Balance, - storage_deposit_limit: Option, + storage_deposit_limit: DepositLimit, ) -> Result, Self::Error> where CallBuilderFinal: Clone, { - let dest = message.clone().params().callee().clone(); + // todo beware side effect! this is wrong, we have to batch up the `map_account` + // into the RPC dry run instead + let _ = self.map_account(caller).await; + + let dest = *message.clone().params().callee(); let exec_input = Encode::encode(message.clone().params().exec_input()); let exec_result = self @@ -631,7 +650,7 @@ where dest, exec_input, value, - storage_deposit_limit, + deposit_limit_to_balance::(storage_deposit_limit), ) .await; log_info(&format!("call dry run: {:?}", &exec_result.result)); @@ -649,6 +668,49 @@ where _marker: Default::default(), }) } + + async fn map_account(&mut self, caller: &Keypair) -> Result<(), Self::Error> { + let tx_events = self.api.map_account(caller).await; + + for evt in tx_events.iter() { + let evt = evt.unwrap_or_else(|err| { + panic!("unable to unwrap event: {err:?}"); + }); + + if is_extrinsic_failed_event(&evt) { + let metadata = self.api.client.metadata(); + let dispatch_error = + DispatchError::decode_from(evt.field_bytes(), metadata) + .map_err(|e| Error::Decoding(e.to_string()))?; + log_error(&format!("extrinsic for call failed: {dispatch_error}")); + return Err(Error::CallExtrinsic(dispatch_error)) + } + } + + // todo: Ok(tx_events) + Ok(()) + } + + async fn map_account_dry_run(&mut self, caller: &Keypair) -> Result<(), Self::Error> { + let tx_events = self.api.map_account(caller).await; + + for evt in tx_events.iter() { + let evt = evt.unwrap_or_else(|err| { + panic!("unable to unwrap event: {err:?}"); + }); + + if is_extrinsic_failed_event(&evt) { + let metadata = self.api.client.metadata(); + let dispatch_error = + DispatchError::decode_from(evt.field_bytes(), metadata) + .map_err(|e| Error::Decoding(e.to_string()))?; + log_error(&format!("extrinsic for call failed: {dispatch_error}")); + return Err(Error::CallExtrinsic(dispatch_error)) + } + } + + Ok(()) + } } impl ContractsBackend for Client @@ -670,7 +732,7 @@ where E::AccountId: Debug + Send + Sync, E::Balance: Clone + Debug + Send + Sync + From + scale::HasCompact + serde::Serialize, - E::Hash: Debug + Send + scale::Encode, + H256: Debug + Send + scale::Encode, { type Error = Error; type EventLog = ExtrinsicEvents; @@ -695,9 +757,10 @@ where E: Environment, E::AccountId: Debug + Send + Sync, + E::EventRecord: Debug, E::Balance: Clone + Debug + Send + Sync + From + scale::HasCompact + serde::Serialize, - E::Hash: Debug + Send + Sync + scale::Encode, + H256: Debug + Send + Sync + scale::Encode, { } @@ -742,17 +805,20 @@ impl CallResult> { /// Returns all the `ContractEmitted` events emitted by the contract. pub fn contract_emitted_events( &self, - ) -> Result>>, subxt::Error> + ) -> Result>, subxt::Error> where C::Hash: Into, { let mut events_with_topics = Vec::new(); for event in self.events.iter() { let event = event?; - if let Some(decoded_event) = event.as_event::>()? { + if let Some(decoded_event) = event.as_event::()? { + let topics = decoded_event.topics.clone(); let event_with_topics = EventWithTopics { event: decoded_event, - topics: event.topics().iter().cloned().map(Into::into).collect(), + //topics: event.topics().iter().cloned().map(Into::into).collect(), + //topics: topics.iter().map(|v| H256::from_slice(&v[..])).collect(), + topics, }; events_with_topics.push(event_with_topics); } diff --git a/crates/e2e/src/xts.rs b/crates/e2e/src/xts.rs index ef63d036dd0..067955a135a 100644 --- a/crates/e2e/src/xts.rs +++ b/crates/e2e/src/xts.rs @@ -15,14 +15,20 @@ use super::{ log_info, sr25519, - ContractExecResult, - ContractInstantiateResult, Keypair, }; use ink_env::Environment; +use crate::contract_results::{ + ContractExecResultFor, + ContractInstantiateResultForBar, +}; use core::marker::PhantomData; -use pallet_contracts::CodeUploadResult; +use ink_primitives::DepositLimit; +use pallet_revive::{ + evm::H160, + CodeUploadResult, +}; use sp_core::H256; use subxt::{ backend::{ @@ -40,7 +46,6 @@ use subxt::{ Signer, TxStatus, }, - utils::MultiAddress, OnlineClient, }; @@ -84,32 +89,39 @@ impl From for sp_weights::Weight { } } -/// A raw call to `pallet-contracts`'s `instantiate_with_code`. +/// A raw call to `pallet-revive`'s `instantiate_with_code`. #[derive(Debug, scale::Encode, scale::Decode, scale_encode::EncodeAsType)] #[encode_as_type(trait_bounds = "", crate_path = "subxt::ext::scale_encode")] pub struct InstantiateWithCode { #[codec(compact)] value: E::Balance, gas_limit: Weight, - storage_deposit_limit: Option, + #[codec(compact)] + storage_deposit_limit: E::Balance, code: Vec, data: Vec, - salt: Vec, + salt: Option<[u8; 32]>, } -/// A raw call to `pallet-contracts`'s `call`. +/// A raw call to `pallet-revive`'s `call`. #[derive(Debug, scale::Decode, scale::Encode, scale_encode::EncodeAsType)] #[encode_as_type(trait_bounds = "", crate_path = "subxt::ext::scale_encode")] pub struct Call { - dest: MultiAddress, + dest: H160, #[codec(compact)] value: E::Balance, gas_limit: Weight, - storage_deposit_limit: Option, + #[codec(compact)] + storage_deposit_limit: E::Balance, data: Vec, } -/// A raw call to `pallet-contracts`'s `call`. +/// A raw call to `pallet-revive`'s `map_account`. +#[derive(Debug, scale::Decode, scale::Encode, scale_encode::EncodeAsType)] +#[encode_as_type(trait_bounds = "", crate_path = "subxt::ext::scale_encode")] +pub struct MapAccount {} + +/// A raw call to `pallet-revive`'s `call`. #[derive(Debug, scale::Decode, scale::Encode, scale_encode::EncodeAsType)] #[encode_as_type(trait_bounds = "", crate_path = "subxt::ext::scale_encode")] pub struct Transfer { @@ -118,68 +130,40 @@ pub struct Transfer { value: E::Balance, } -#[derive( - Debug, - Clone, - Copy, - PartialEq, - Eq, - serde::Serialize, - scale::Decode, - scale::Encode, - scale_encode::EncodeAsType, -)] -#[encode_as_type(crate_path = "subxt::ext::scale_encode")] -pub enum Determinism { - /// The execution should be deterministic and hence no indeterministic instructions - /// are allowed. - /// - /// Dispatchables always use this mode in order to make on-chain execution - /// deterministic. - Enforced, - /// Allow calling or uploading an indeterministic code. - /// - /// This is only possible when calling into `pallet-contracts` directly via - /// [`crate::Pallet::bare_call`]. - /// - /// # Note - /// - /// **Never** use this mode for on-chain execution. - Relaxed, -} - -/// A raw call to `pallet-contracts`'s `remove_code`. +/// A raw call to `pallet-revive`'s `remove_code`. #[derive(Debug, scale::Encode, scale::Decode, scale_encode::EncodeAsType)] #[encode_as_type(trait_bounds = "", crate_path = "subxt::ext::scale_encode")] -pub struct RemoveCode { - code_hash: E::Hash, +pub struct RemoveCode { + code_hash: H256, } -/// A raw call to `pallet-contracts`'s `upload`. +/// A raw call to `pallet-revive`'s `upload_code`. #[derive(Debug, scale::Encode, scale::Decode, scale_encode::EncodeAsType)] #[encode_as_type(trait_bounds = "", crate_path = "subxt::ext::scale_encode")] pub struct UploadCode { code: Vec, - storage_deposit_limit: Option, - determinism: Determinism, + #[codec(compact)] + storage_deposit_limit: E::Balance, } /// A struct that encodes RPC parameters required to instantiate a new smart contract. -#[derive(serde::Serialize, scale::Encode)] -#[serde(rename_all = "camelCase")] +#[derive(scale::Encode)] +// todo: #[derive(serde::Serialize, scale::Encode)] +// todo: #[serde(rename_all = "camelCase")] struct RpcInstantiateRequest { origin: C::AccountId, value: E::Balance, gas_limit: Option, - storage_deposit_limit: Option, + storage_deposit_limit: DepositLimit, code: Code, data: Vec, - salt: Vec, + salt: Option<[u8; 32]>, } /// A struct that encodes RPC parameters required to upload a new smart contract. -#[derive(serde::Serialize, scale::Encode)] -#[serde(rename_all = "camelCase")] +#[derive(scale::Encode)] +// todo: #[derive(serde::Serialize, scale::Encode)] +// todo: #[serde(rename_all = "camelCase")] struct RpcCodeUploadRequest where E::Balance: serde::Serialize, @@ -187,20 +171,18 @@ where origin: C::AccountId, code: Vec, storage_deposit_limit: Option, - determinism: Determinism, } /// A struct that encodes RPC parameters required for a call to a smart contract. -/// -/// Copied from [`pallet-contracts-rpc`]. -#[derive(serde::Serialize, scale::Encode)] -#[serde(rename_all = "camelCase")] +#[derive(scale::Encode)] +// todo: #[derive(serde::Serialize, scale::Encode)] +// todo: #[serde(rename_all = "camelCase")] struct RpcCallRequest { origin: C::AccountId, - dest: E::AccountId, + dest: H160, value: E::Balance, gas_limit: Option, - storage_deposit_limit: Option, + storage_deposit_limit: DepositLimit, input_data: Vec, } @@ -215,14 +197,14 @@ enum Code { Existing(H256), } -/// Provides functions for interacting with the `pallet-contracts` API. -pub struct ContractsApi { +/// Provides functions for interacting with the `pallet-revive` API. +pub struct ReviveApi { pub rpc: LegacyRpcMethods, pub client: OnlineClient, _phantom: PhantomData (C, E)>, } -impl ContractsApi +impl ReviveApi where C: subxt::Config, C::AccountId: From + serde::de::DeserializeOwned + scale::Codec, @@ -234,7 +216,7 @@ where E: Environment, E::Balance: scale::HasCompact + serde::Serialize, { - /// Creates a new [`ContractsApi`] instance. + /// Creates a new [`ReviveApi`] instance. pub async fn new(rpc: RpcClient) -> Result { let client = OnlineClient::::from_rpc_client(rpc.clone()).await?; let rpc = LegacyRpcMethods::::new(rpc); @@ -274,12 +256,13 @@ where pub async fn instantiate_with_code_dry_run( &self, value: E::Balance, - storage_deposit_limit: Option, + storage_deposit_limit: DepositLimit, code: Vec, data: Vec, - salt: Vec, + salt: Option<[u8; 32]>, signer: &Keypair, - ) -> ContractInstantiateResult { + ) -> ContractInstantiateResultForBar { + // todo map_account beforehand? let code = Code::Upload(code); let call_request = RpcInstantiateRequest:: { origin: Signer::::account_id(signer), @@ -290,14 +273,14 @@ where data, salt, }; - let func = "ContractsApi_instantiate"; + let func = "ReviveApi_instantiate"; let params = scale::Encode::encode(&call_request); let bytes = self .rpc .state_call(func, Some(¶ms), None) .await .unwrap_or_else(|err| { - panic!("error on ws request `contracts_instantiate`: {err:?}"); + panic!("error on ws request `revive_instantiate`: {err:?}"); }); scale::Decode::decode(&mut bytes.as_ref()).unwrap_or_else(|err| { panic!("decoding ContractInstantiateResult failed: {err}") @@ -412,19 +395,19 @@ where &self, value: E::Balance, gas_limit: Weight, - storage_deposit_limit: Option, + storage_deposit_limit: E::Balance, code: Vec, data: Vec, - salt: Vec, + salt: Option<[u8; 32]>, signer: &Keypair, ) -> ExtrinsicEvents { let call = subxt::tx::DefaultPayload::new( - "Contracts", + "Revive", "instantiate_with_code", InstantiateWithCode:: { value, gas_limit, - storage_deposit_limit, + storage_deposit_limit, // todo code, data, salt, @@ -440,15 +423,16 @@ where &self, signer: &Keypair, code: Vec, - storage_deposit_limit: Option, - ) -> CodeUploadResult { + // todo + _storage_deposit_limit: E::Balance, + ) -> CodeUploadResult { let call_request = RpcCodeUploadRequest:: { origin: Signer::::account_id(signer), code, - storage_deposit_limit, - determinism: Determinism::Enforced, + //storage_deposit_limit, + storage_deposit_limit: None, }; - let func = "ContractsApi_upload_code"; + let func = "ReviveApi_upload_code"; let params = scale::Encode::encode(&call_request); let bytes = self .rpc @@ -469,15 +453,15 @@ where &self, signer: &Keypair, code: Vec, - storage_deposit_limit: Option, + storage_deposit_limit: E::Balance, ) -> ExtrinsicEvents { let call = subxt::tx::DefaultPayload::new( - "Contracts", + "Revive", "upload_code", UploadCode:: { code, storage_deposit_limit, - determinism: Determinism::Enforced, + //storage_deposit_limit: None }, ) .unvalidated(); @@ -492,12 +476,12 @@ where pub async fn remove_code( &self, signer: &Keypair, - code_hash: E::Hash, + code_hash: H256, ) -> ExtrinsicEvents { let call = subxt::tx::DefaultPayload::new( - "Contracts", + "Revive", "remove_code", - RemoveCode:: { code_hash }, + RemoveCode { code_hash }, ) .unvalidated(); @@ -508,20 +492,20 @@ where pub async fn call_dry_run( &self, origin: C::AccountId, - dest: E::AccountId, + dest: H160, input_data: Vec, value: E::Balance, - storage_deposit_limit: Option, - ) -> ContractExecResult { + _storage_deposit_limit: E::Balance, // todo + ) -> ContractExecResultFor { let call_request = RpcCallRequest:: { origin, dest, value, gas_limit: None, - storage_deposit_limit, + storage_deposit_limit: DepositLimit::Unchecked, input_data, }; - let func = "ContractsApi_call"; + let func = "ReviveApi_call"; let params = scale::Encode::encode(&call_request); let bytes = self .rpc @@ -540,15 +524,15 @@ where /// contains all events that are associated with this transaction. pub async fn call( &self, - contract: MultiAddress, + contract: H160, value: E::Balance, gas_limit: Weight, - storage_deposit_limit: Option, + storage_deposit_limit: E::Balance, data: Vec, signer: &Keypair, ) -> ExtrinsicEvents { let call = subxt::tx::DefaultPayload::new( - "Contracts", + "Revive", "call", Call:: { dest: contract, @@ -563,6 +547,18 @@ where self.submit_extrinsic(&call, signer).await } + /// todo + /// Submits an extrinsic to call a contract with the given parameters. + /// + /// Returns when the transaction is included in a block. The return value + /// contains all events that are associated with this transaction. + pub async fn map_account(&self, signer: &Keypair) -> ExtrinsicEvents { + let call = subxt::tx::DefaultPayload::new("Revive", "map_account", MapAccount {}) + .unvalidated(); + + self.submit_extrinsic(&call, signer).await + } + /// Submit an extrinsic `call_name` for the `pallet_name`. /// The `call_data` is a `Vec` that holds /// a representation of some value. diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 5afd2e36dc4..ae46dedd530 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -17,7 +17,6 @@ include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE"] [dependencies] ink_primitives = { workspace = true } scale = { workspace = true } -pallet-contracts-uapi = { workspace = true } pallet-revive-uapi = { workspace = true } derive_more = { workspace = true, features = ["from", "display"] } @@ -36,4 +35,3 @@ std = [ "secp256k1", "derive_more/std" ] -revive = [] diff --git a/crates/engine/src/database.rs b/crates/engine/src/database.rs index 1ae633b687f..b53c1b0bb2d 100644 --- a/crates/engine/src/database.rs +++ b/crates/engine/src/database.rs @@ -12,7 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::types::Balance; +use crate::types::{ + Balance, + H160, +}; +use ink_primitives::{ + AccountId, + H256, + U256, +}; use scale::KeyedVec; use std::collections::HashMap; @@ -22,9 +30,21 @@ const CONTRACT_PREFIX: &[u8] = b"contract:"; const MSG_HANDLER_OF: &[u8] = b"message-handler:"; const CODE_HASH_OF: &[u8] = b"code-hash:"; -/// Returns the database key under which to find the balance for account `who`. -pub fn balance_of_key(who: &[u8]) -> [u8; 32] { - let keyed = who.to_vec().to_keyed_vec(BALANCE_OF); +/// Returns the database key under which to find the balance for contract `who`. +pub fn balance_of_key(who: &H160) -> [u8; 32] { + let keyed = who.0.to_vec().to_keyed_vec(BALANCE_OF); + let mut hashed_key: [u8; 32] = [0; 32]; + super::hashing::blake2b_256(&keyed[..], &mut hashed_key); + hashed_key +} + +/// Returns the database key under which to find the storage for contract `who`. +pub fn storage_of_contract_key(who: &H160, key: &[u8]) -> [u8; 32] { + let keyed = who + .as_bytes() + .to_vec() + .to_keyed_vec(key) + .to_keyed_vec(STORAGE_OF); let mut hashed_key: [u8; 32] = [0; 32]; super::hashing::blake2b_256(&keyed[..], &mut hashed_key); hashed_key @@ -48,24 +68,17 @@ pub fn message_handler_of_contract_key(key: &[u8]) -> [u8; 32] { hashed_key } -pub fn code_hash_of_key(key: &Vec) -> [u8; 32] { +pub fn code_hash_for_addr(addr: &H160) -> [u8; 32] { + let key = addr.0; let keyed = key.to_keyed_vec(CODE_HASH_OF); let mut hashed_key: [u8; 32] = [0; 32]; super::hashing::blake2b_256(&keyed[..], &mut hashed_key); hashed_key } -/// Returns the database key under which to find the balance for account `who`. -pub fn storage_of_contract_key(who: &[u8], key: &[u8]) -> [u8; 32] { - let keyed = who.to_vec().to_keyed_vec(key).to_keyed_vec(STORAGE_OF); - let mut hashed_key: [u8; 32] = [0; 32]; - super::hashing::blake2b_256(&keyed[..], &mut hashed_key); - hashed_key -} - /// The chain database. /// -/// Everything is stored in here: accounts, balances, contract storage, etc.. +/// Everything is stored in here: contracts, balances, contract storage, etc. /// Just like in Substrate a prefix hash is computed for every contract. #[derive(Default)] pub struct Database { @@ -94,33 +107,29 @@ impl Database { } /// Returns a reference to the value corresponding to the key. - pub fn get_from_contract_storage( - &self, - account_id: &[u8], - key: &[u8], - ) -> Option<&Vec> { - let hashed_key = storage_of_contract_key(account_id, key); + pub fn get_from_contract_storage(&self, addr: &H160, key: &[u8]) -> Option<&Vec> { + let hashed_key = storage_of_contract_key(addr, key); self.hmap.get(hashed_key.as_slice()) } - /// Inserts `value` into the contract storage of `account_id` at storage key `key`. + /// Inserts `value` into the contract storage of `addr` at storage key `key`. pub fn insert_into_contract_storage( &mut self, - account_id: &[u8], + addr: &H160, key: &[u8], value: Vec, ) -> Option> { - let hashed_key = storage_of_contract_key(account_id, key); + let hashed_key = storage_of_contract_key(addr, key); self.hmap.insert(hashed_key.to_vec(), value) } - /// Removes the value at the contract storage of `account_id` at storage key `key`. + /// Removes the value at the contract storage of `addr` at storage key `key`. pub fn remove_contract_storage( &mut self, - account_id: &[u8], + addr: &H160, key: &[u8], ) -> Option> { - let hashed_key = storage_of_contract_key(account_id, key); + let hashed_key = storage_of_contract_key(addr, key); self.hmap.remove(hashed_key.as_slice()) } @@ -140,25 +149,34 @@ impl Database { self.hmap.clear(); } - /// Returns the balance of `account_id`, if available. - pub fn get_balance(&self, account_id: &[u8]) -> Option { - let hashed_key = balance_of_key(account_id); + /// Returns the balance of the contract at `addr`, if available. + pub fn get_acc_balance(&self, _addr: &AccountId) -> Option { + todo!() + } + + /// Sets the balance of `addr` to `new_balance`. + pub fn set_acc_balance(&mut self, _addr: &AccountId, _new_balance: Balance) { + todo!() + } + + pub fn get_balance(&self, addr: &H160) -> Option { + let hashed_key = balance_of_key(addr); self.get(&hashed_key).map(|encoded_balance| { scale::Decode::decode(&mut &encoded_balance[..]) .expect("unable to decode balance from database") }) } - /// Sets the balance of `account_id` to `new_balance`. - pub fn set_balance(&mut self, account_id: &[u8], new_balance: Balance) { - let hashed_key = balance_of_key(account_id); + /// Sets the balance of `addr` to `new_balance`. + pub fn set_balance(&mut self, addr: &H160, new_balance: U256) { + let hashed_key = balance_of_key(addr); let encoded_balance = scale::Encode::encode(&new_balance); self.hmap .entry(hashed_key.to_vec()) .and_modify(|v| *v = encoded_balance.clone()) .or_insert(encoded_balance); } - + pub fn set_contract_message_handler(&mut self, handler: MessageHandler) -> [u8; 32] { let key = contract_key(handler); let hashed_key = message_handler_of_contract_key(&key); @@ -169,28 +187,32 @@ impl Database { key } - pub fn get_contract_message_handler(&mut self, key: &[u8]) -> MessageHandler { - let hashed_key = message_handler_of_contract_key(key); + /// Returns the message handler for a code hash. + pub fn get_contract_message_handler(&mut self, code_hash: &H256) -> MessageHandler { + let hashed_key = message_handler_of_contract_key(&code_hash.0); *self.fmap.get(hashed_key.as_slice()).unwrap() } - pub fn set_code_hash(&mut self, account: &Vec, code_hash: &[u8]) { - let hashed_key = code_hash_of_key(account); + pub fn set_code_hash(&mut self, addr: &H160, code_hash: &H256) { + let hashed_key = code_hash_for_addr(addr); self.hmap .entry(hashed_key.to_vec()) - .and_modify(|x| *x = code_hash.to_vec()) - .or_insert(code_hash.to_vec()); + .and_modify(|x| *x = code_hash.as_bytes().to_vec()) + .or_insert(code_hash.as_bytes().to_vec()); } - pub fn get_code_hash(&self, account: &Vec) -> Option> { - let hashed_key = code_hash_of_key(account); - self.get(&hashed_key).cloned() + pub fn get_code_hash(&self, addr: &H160) -> Option { + let hashed_key = code_hash_for_addr(addr); + self.get(&hashed_key) + .cloned() + .map(|v| H256::from_slice(v.as_slice())) } } #[cfg(test)] mod tests { use super::Database; + use crate::types::H160; #[test] fn basic_operations() { @@ -217,7 +239,7 @@ mod tests { #[test] fn contract_storage() { - let account_id = vec![1; 32]; + let addr = H160::from([1; 20]); let mut storage = Database::new(); let key1 = vec![42]; let key2 = vec![43]; @@ -226,37 +248,25 @@ mod tests { let val3 = vec![46]; assert_eq!(storage.len(), 0); - assert_eq!(storage.get_from_contract_storage(&account_id, &key1), None); + assert_eq!(storage.get_from_contract_storage(&addr, &key1), None); assert_eq!( - storage.insert_into_contract_storage(&account_id, &key1, val1.clone()), + storage.insert_into_contract_storage(&addr, &key1, val1.clone()), None ); + assert_eq!(storage.get_from_contract_storage(&addr, &key1), Some(&val1)); assert_eq!( - storage.get_from_contract_storage(&account_id, &key1), - Some(&val1) - ); - assert_eq!( - storage.insert_into_contract_storage(&account_id, &key1, val2.clone()), + storage.insert_into_contract_storage(&addr, &key1, val2.clone()), Some(val1) ); + assert_eq!(storage.get_from_contract_storage(&addr, &key1), Some(&val2)); assert_eq!( - storage.get_from_contract_storage(&account_id, &key1), - Some(&val2) - ); - assert_eq!( - storage.insert_into_contract_storage(&account_id, &key2, val3.clone()), + storage.insert_into_contract_storage(&addr, &key2, val3.clone()), None ); assert_eq!(storage.len(), 2); - assert_eq!( - storage.remove_contract_storage(&account_id, &key2), - Some(val3) - ); + assert_eq!(storage.remove_contract_storage(&addr, &key2), Some(val3)); assert_eq!(storage.len(), 1); - assert_eq!( - storage.remove_contract_storage(&account_id, &key1), - Some(val2) - ); + assert_eq!(storage.remove_contract_storage(&addr, &key1), Some(val2)); assert_eq!(storage.len(), 0); } } diff --git a/crates/engine/src/exec_context.rs b/crates/engine/src/exec_context.rs index 4ee6daa50fe..2074c8fc783 100644 --- a/crates/engine/src/exec_context.rs +++ b/crates/engine/src/exec_context.rs @@ -13,11 +13,11 @@ // limitations under the License. use super::types::{ - AccountId, - Balance, BlockNumber, BlockTimestamp, + H160, }; +use ink_primitives::U256; /// The context of a contract execution. #[cfg_attr(test, derive(Debug, PartialEq, Eq))] @@ -25,26 +25,27 @@ use super::types::{ pub struct ExecContext { /// The caller of the contract execution. Might be user or another contract. /// + /// TODO check next comment /// We don't know the specifics of the `AccountId` ‒ like how many bytes or what /// type of default `AccountId` makes sense ‒ they are left to be initialized /// by the crate which uses the `engine`. Methods which require a caller might /// panic when it has not been set. - pub caller: Option, + pub caller: H160, /// The callee of the contract execution. Might be user or another contract. /// /// We don't know the specifics of the `AccountId` ‒ like how many bytes or what /// type of default `AccountId` makes sense ‒ they are left to be initialized /// by the crate which uses the `engine`. Methods which require a callee might /// panic when it has not been set. - pub callee: Option, + pub callee: Option, /// The value transferred to the contract as part of the call. - pub value_transferred: Balance, + pub value_transferred: U256, /// The current block number. pub block_number: BlockNumber, /// The current block timestamp. pub block_timestamp: BlockTimestamp, /// Known contract accounts - pub contracts: Vec>, + pub contracts: Vec, } impl ExecContext { @@ -54,12 +55,8 @@ impl ExecContext { } /// Returns the callee. - pub fn callee(&self) -> Vec { - self.callee - .as_ref() - .expect("no callee has been set") - .as_bytes() - .into() + pub fn callee(&self) -> H160 { + self.callee.expect("no callee has been set") } /// Resets the execution context @@ -80,19 +77,17 @@ impl ExecContext { #[cfg(test)] mod tests { - use super::{ - AccountId, - ExecContext, - }; + use super::ExecContext; + use crate::types::H160; #[test] fn basic_operations() { let mut exec_cont = ExecContext::new(); - exec_cont.callee = Some(AccountId::from_bytes(&[13])); - exec_cont.caller = Some(AccountId::from_bytes(&[14])); - exec_cont.value_transferred = 15; - assert_eq!(exec_cont.callee(), vec![13]); + exec_cont.callee = Some(H160::from([13; 20])); + exec_cont.caller = H160::from([14; 20]); + exec_cont.value_transferred = 15.into(); + assert_eq!(exec_cont.callee(), H160::from([13; 20])); exec_cont.reset(); diff --git a/crates/engine/src/ext.rs b/crates/engine/src/ext.rs index 976f891dffc..550e850459b 100644 --- a/crates/engine/src/ext.rs +++ b/crates/engine/src/ext.rs @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Provides the same interface as Substrate's FRAME `contract` module. +//! Provides the same interface as Substrate's FRAME `revive` module. //! -//! See [the documentation for the `contract` module](https://docs.rs/crate/pallet-contracts) +//! See [the documentation for the `revive` module](https://docs.rs/crate/pallet-revive) //! for more information. use crate::{ @@ -26,14 +26,11 @@ use crate::{ EmittedEvent, }, types::{ - AccountId, - Balance, BlockTimestamp, + H160, }, }; -#[cfg(not(feature = "revive"))] -pub use pallet_contracts_uapi::ReturnErrorCode as Error; -#[cfg(feature = "revive")] +use ink_primitives::U256; pub use pallet_revive_uapi::ReturnErrorCode as Error; use scale::Encode; use std::panic::panic_any; @@ -57,10 +54,10 @@ pub struct Engine { /// The chain specification. pub struct ChainSpec { /// The current gas price. - pub gas_price: Balance, + pub gas_price: U256, /// The minimum value an account of the chain must have /// (i.e. the chain's existential deposit). - pub minimum_balance: Balance, + pub minimum_balance: U256, /// The targeted block time. pub block_time: BlockTimestamp, } @@ -75,8 +72,8 @@ pub struct ChainSpec { impl Default for ChainSpec { fn default() -> Self { Self { - gas_price: 100, - minimum_balance: 1000000, + gas_price: 100.into(), + minimum_balance: 42.into(), block_time: 6, } } @@ -103,18 +100,18 @@ impl Default for Engine { impl Engine { /// Transfers value from the contract to the destination account. - pub fn transfer(&mut self, account_id: &[u8], mut value: &[u8]) -> Result<(), Error> { + #[allow(clippy::arithmetic_side_effects)] // todo + pub fn transfer(&mut self, dest: H160, mut value: &[u8]) -> Result<(), Error> { // Note that a transfer of `0` is allowed here let increment = ::decode(&mut value) .map_err(|_| Error::TransferFailed)?; - let dest = account_id.to_vec(); // Note that the destination account does not have to exist - let dest_old_balance = self.get_balance(dest.clone()).unwrap_or_default(); + let dest_old_balance = self.get_balance(dest).unwrap_or_default(); let contract = self.get_callee(); let contract_old_balance = self - .get_balance(contract.clone()) + .get_balance(contract) .map_err(|_| Error::TransferFailed)?; self.database @@ -125,6 +122,7 @@ impl Engine { } /// Deposits an event identified by the supplied topics and data. + #[allow(clippy::arithmetic_side_effects)] // todo pub fn deposit_event(&mut self, topics: &[u8], data: &[u8]) { // The first byte contains the number of topics in the slice let topics_count: scale::Compact = scale::Decode::decode(&mut &topics[0..1]) @@ -155,11 +153,10 @@ impl Engine { /// Returns the size of the previously stored value at the key if any. pub fn set_storage(&mut self, key: &[u8], encoded_value: &[u8]) -> Option { let callee = self.get_callee(); - let account_id = AccountId::from_bytes(&callee[..]); - self.debug_info.inc_writes(account_id.clone()); + self.debug_info.inc_writes(callee); self.debug_info - .record_cell_for_account(account_id, key.to_vec()); + .record_cell_for_account(callee, key.to_vec()); self.database .insert_into_contract_storage(&callee, key, encoded_value.to_vec()) @@ -169,9 +166,8 @@ impl Engine { /// Returns the contract storage bytes at the key if any. pub fn get_storage(&mut self, key: &[u8]) -> Result<&[u8], Error> { let callee = self.get_callee(); - let account_id = AccountId::from_bytes(&callee[..]); - self.debug_info.inc_reads(account_id); + self.debug_info.inc_reads(callee); match self.database.get_from_contract_storage(&callee, key) { Some(val) => Ok(val), None => Err(Error::KeyNotFound), @@ -182,9 +178,8 @@ impl Engine { /// returning previously stored value at the key if any. pub fn take_storage(&mut self, key: &[u8]) -> Result, Error> { let callee = self.get_callee(); - let account_id = AccountId::from_bytes(&callee[..]); - self.debug_info.inc_writes(account_id); + self.debug_info.inc_writes(callee); match self.database.remove_contract_storage(&callee, key) { Some(val) => Ok(val), None => Err(Error::KeyNotFound), @@ -194,9 +189,8 @@ impl Engine { /// Returns the size of the value stored in the contract storage at the key if any. pub fn contains_storage(&mut self, key: &[u8]) -> Option { let callee = self.get_callee(); - let account_id = AccountId::from_bytes(&callee[..]); - self.debug_info.inc_reads(account_id); + self.debug_info.inc_reads(callee); self.database .get_from_contract_storage(&callee, key) .map(|val| val.len() as u32) @@ -206,11 +200,10 @@ impl Engine { /// Returns the size of the previously stored value at the key if any. pub fn clear_storage(&mut self, key: &[u8]) -> Option { let callee = self.get_callee(); - let account_id = AccountId::from_bytes(&callee[..]); - self.debug_info.inc_writes(account_id.clone()); + self.debug_info.inc_writes(callee); let _ = self .debug_info - .remove_cell_for_account(account_id, key.to_vec()); + .remove_cell_for_account(callee, key.to_vec()); self.database .remove_contract_storage(&callee, key) .map(|val| val.len() as u32) @@ -218,10 +211,11 @@ impl Engine { /// Remove the calling account and transfer remaining balance. /// + /// todo is the following comment still correct? /// This function never returns. Either the termination was successful and the /// execution of the destroyed contract is halted. Or it failed during the /// termination which is considered fatal. - pub fn terminate(&mut self, beneficiary: &[u8]) -> ! { + pub fn terminate(&mut self, beneficiary: H160) -> ! { // Send the remaining balance to the beneficiary let contract = self.get_callee(); let all = self @@ -234,19 +228,15 @@ impl Engine { // Encode the result of the termination and panic with it. // This enables testing for the proper result and makes sure this // method returns `Never`. - let res = (all, beneficiary.to_vec()); + let res = (all, beneficiary); panic_any(scale::Encode::encode(&res)); } /// Returns the address of the caller. pub fn caller(&self, output: &mut &mut [u8]) { - let caller = self - .exec_context - .caller - .as_ref() - .expect("no caller has been set") - .as_bytes(); - set_output(output, caller); + let caller = self.exec_context.caller; + let caller = scale::Encode::encode(&caller); + set_output(output, &caller[..]) } /// Returns the balance of the executed contract. @@ -259,7 +249,7 @@ impl Engine { let balance_in_storage = self .database - .get_balance(contract.as_bytes()) + .get_balance(contract) .expect("currently executing contract must exist"); let balance = scale::Encode::encode(&balance_in_storage); set_output(output, &balance[..]) @@ -323,11 +313,6 @@ impl Engine { set_output(output, &block_timestamp[..]) } - #[cfg(not(feature = "revive"))] - pub fn gas_left(&self, _output: &mut &mut [u8]) { - unimplemented!("off-chain environment does not yet support `gas_left`"); - } - /// Returns the minimum balance that is required for creating an account /// (i.e. the chain's existential deposit). pub fn minimum_balance(&self, output: &mut &mut [u8]) { @@ -391,6 +376,7 @@ impl Engine { /// Recovers the compressed ECDSA public key for given `signature` and `message_hash`, /// and stores the result in `output`. + #[allow(clippy::arithmetic_side_effects)] // todo pub fn ecdsa_recover( &mut self, signature: &[u8; 65], diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 367c90dc28d..613b50fe012 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,7 +30,10 @@ mod types; mod tests; pub use chain_extension::ChainExtension; -pub use types::AccountError; +pub use types::{ + AccountError, + // Origin, +}; use derive_more::From; diff --git a/crates/engine/src/test_api.rs b/crates/engine/src/test_api.rs index 460faf774ad..e29afab349e 100644 --- a/crates/engine/src/test_api.rs +++ b/crates/engine/src/test_api.rs @@ -15,14 +15,18 @@ use crate::{ ext::Engine, types::{ - AccountId, Balance, BlockNumber, BlockTimestamp, + H160, }, AccountError, Error, }; +use ink_primitives::{ + AccountId, + U256, +}; use std::collections::HashMap; /// Record for an emitted event. @@ -80,11 +84,11 @@ pub struct DebugInfo { /// Emitted print messages recorder. emitted_debug_messages: RecordedDebugMessages, /// The total number of reads to the storage. - count_reads: HashMap, + count_reads: HashMap, /// The total number of writes to the storage. - count_writes: HashMap, - /// The number of storage cells used by each account id. - cells_per_account: HashMap, bool>>, + count_writes: HashMap, + /// The number of storage cells used by each contract. + cells_per_contract: HashMap, bool>>, } impl Default for DebugInfo { @@ -101,7 +105,7 @@ impl DebugInfo { emitted_debug_messages: RecordedDebugMessages::new(), count_reads: HashMap::new(), count_writes: HashMap::new(), - cells_per_account: HashMap::new(), + cells_per_contract: HashMap::new(), } } @@ -111,21 +115,23 @@ impl DebugInfo { self.count_writes.clear(); self.emitted_events.clear(); self.emitted_debug_messages.clear(); - self.cells_per_account.clear(); + self.cells_per_contract.clear(); } /// Increases the number of storage writes for the supplied account by one. - pub fn inc_writes(&mut self, account_id: AccountId) { + #[allow(clippy::arithmetic_side_effects)] // todo + pub fn inc_writes(&mut self, addr: H160) { self.count_writes - .entry(account_id) + .entry(addr) .and_modify(|v| *v += 1) .or_insert(1); } /// Increases the number of storage reads for the supplied account by one. - pub fn inc_reads(&mut self, account_id: AccountId) { + #[allow(clippy::arithmetic_side_effects)] // todo + pub fn inc_reads(&mut self, addr: H160) { self.count_reads - .entry(account_id) + .entry(addr) .and_modify(|v| *v += 1) .or_insert(1); } @@ -134,9 +140,9 @@ impl DebugInfo { /// /// Calling this function multiple times won't change the fact that only /// one cell is recorded. - pub fn record_cell_for_account(&mut self, account_id: AccountId, key: Vec) { - self.cells_per_account - .entry(account_id) + pub fn record_cell_for_account(&mut self, addr: H160, key: Vec) { + self.cells_per_contract + .entry(addr) .and_modify(|hm| { let _ = hm.insert(key.clone(), true); }) @@ -150,13 +156,9 @@ impl DebugInfo { /// Removes the cell under `key` for the supplied account. /// /// Returns the removed cell, if there was one. - pub fn remove_cell_for_account( - &mut self, - account_id: AccountId, - key: Vec, - ) -> Option { - self.cells_per_account - .get_mut(&account_id) + pub fn remove_cell_for_account(&mut self, addr: H160, key: Vec) -> Option { + self.cells_per_contract + .get_mut(&addr) .map(|hm| hm.remove(&key)) .unwrap_or(None) } @@ -181,10 +183,9 @@ impl Engine { } /// Returns the total number of reads and writes of the contract's storage. - pub fn get_contract_storage_rw(&self, account_id: Vec) -> (usize, usize) { - let account_id = AccountId::from(account_id); - let reads = self.debug_info.count_reads.get(&account_id).unwrap_or(&0); - let writes = self.debug_info.count_writes.get(&account_id).unwrap_or(&0); + pub fn get_contract_storage_rw(&self, addr: H160) -> (usize, usize) { + let reads = self.debug_info.count_reads.get(&addr).unwrap_or(&0); + let writes = self.debug_info.count_writes.get(&addr).unwrap_or(&0); (*reads, *writes) } @@ -199,48 +200,54 @@ impl Engine { } /// Sets a caller for the next call. - pub fn set_caller(&mut self, caller: Vec) { - self.exec_context.caller = Some(caller.into()); + pub fn set_caller(&mut self, caller: H160) { + self.exec_context.caller = caller; } /// Sets a known contract by adding it to a vector of known contracts accounts - pub fn set_contract(&mut self, caller: Vec) { + pub fn set_contract(&mut self, caller: H160) { self.exec_context.contracts.push(caller); } /// Sets the callee for the next call. - pub fn set_callee(&mut self, callee: Vec) { - self.exec_context.callee = Some(callee.into()); + pub fn set_callee(&mut self, callee: H160) { + self.exec_context.callee = Some(callee); } - /// Returns the amount of storage cells used by the account `account_id`. + /// Returns the amount of storage cells used by the contract `addr`. /// - /// Returns `None` if the `account_id` is non-existent. - pub fn count_used_storage_cells(&self, account_id: &[u8]) -> Result { + /// Returns `None` if the contract `addr` is non-existent. + pub fn count_used_storage_cells(&self, addr: &H160) -> Result { let cells = self .debug_info - .cells_per_account - .get(&account_id.to_owned().into()) - .ok_or_else(|| { - Error::Account(AccountError::NoAccountForId(account_id.to_vec())) - })?; + .cells_per_contract + .get(addr) + .ok_or(Error::Account(AccountError::NoContractForId(*addr)))?; Ok(cells.len()) } /// Advances the chain by a single block. pub fn advance_block(&mut self) { - self.exec_context.block_number += 1; - self.exec_context.block_timestamp += self.chain_spec.block_time; + self.exec_context.block_number = self + .exec_context + .block_number + .checked_add(1) + .expect("failed to add"); + self.exec_context.block_timestamp = self + .exec_context + .block_timestamp + .checked_add(self.chain_spec.block_time) + .expect("failed to add"); } /// Returns the callee, i.e. the currently executing contract. - pub fn get_callee(&self) -> Vec { + pub fn get_callee(&self) -> H160 { self.exec_context.callee() } /// Returns boolean value indicating whether the account is a contract - pub fn is_contract(&self, account_id: Vec) -> bool { - self.exec_context.contracts.contains(&account_id) + pub fn is_contract(&self, addr: &H160) -> bool { + self.exec_context.contracts.contains(addr) } /// Returns the contents of the past performed environmental `debug_message` in order. @@ -253,20 +260,32 @@ impl Engine { self.debug_info.emitted_events.clone().into_iter() } - /// Returns the current balance of `account_id`. - pub fn get_balance(&self, account_id: Vec) -> Result { + /// Returns the current balance of `addr`. + pub fn get_acc_balance(&self, addr: AccountId) -> Result { + self.database + .get_acc_balance(&addr) + .ok_or(Error::Account(AccountError::NoAccountForId(addr))) + } + + /// Sets the balance of `addr` to `new_balance`. + pub fn set_acc_balance(&mut self, addr: AccountId, new_balance: Balance) { + self.database.set_acc_balance(&addr, new_balance); + } + + /// Returns the current balance of `addr`. + pub fn get_balance(&self, addr: H160) -> Result { self.database - .get_balance(&account_id) - .ok_or(Error::Account(AccountError::NoAccountForId(account_id))) + .get_balance(&addr) + .ok_or(Error::Account(AccountError::NoContractForId(addr))) } - /// Sets the balance of `account_id` to `new_balance`. - pub fn set_balance(&mut self, account_id: Vec, new_balance: Balance) { - self.database.set_balance(&account_id, new_balance); + /// Sets the balance of `addr` to `new_balance`. + pub fn set_balance(&mut self, addr: H160, new_balance: U256) { + self.database.set_balance(&addr, new_balance); } /// Sets the value transferred from the caller to the callee as part of the call. - pub fn set_value_transferred(&mut self, value: Balance) { + pub fn set_value_transferred(&mut self, value: U256) { self.exec_context.value_transferred = value; } @@ -288,20 +307,20 @@ mod tests { #[test] fn setting_getting_callee() { let mut engine = Engine::new(); - let account_id = vec![1; 32]; - engine.set_callee(account_id.clone()); - assert_eq!(engine.get_callee(), account_id); + let addr = H160::from([1; 20]); + engine.set_callee(addr); + assert_eq!(engine.get_callee(), addr); } #[test] fn count_cells_per_account_must_stay_the_same() { // given let mut engine = Engine::new(); - let account_id = vec![1; 32]; - engine.set_callee(account_id.clone()); + let addr = H160::from([1; 20]); + engine.set_callee(addr); let key: &[u8; 32] = &[0x42; 32]; engine.set_storage(key, &[0x05_u8; 5]); - assert_eq!(engine.count_used_storage_cells(&account_id), Ok(1)); + assert_eq!(engine.count_used_storage_cells(&addr), Ok(1)); // when // we set the storage a second time @@ -309,24 +328,24 @@ mod tests { // then // the amount of storage cells used must have stayed the same - assert_eq!(engine.count_used_storage_cells(&account_id), Ok(1)); + assert_eq!(engine.count_used_storage_cells(&addr), Ok(1)); } #[test] fn count_cells_per_account_must_be_reset() { // given let mut engine = Engine::new(); - let account_id = vec![1; 32]; - engine.set_callee(account_id.clone()); + let addr = H160::from([1; 20]); + engine.set_callee(addr); let key: &[u8; 32] = &[0x42; 32]; engine.set_storage(key, &[0x05_u8; 5]); - assert_eq!(engine.count_used_storage_cells(&account_id), Ok(1)); + assert_eq!(engine.count_used_storage_cells(&addr), Ok(1)); // when engine.clear_storage(key); // then - assert_eq!(engine.count_used_storage_cells(&account_id), Ok(0)); + assert_eq!(engine.count_used_storage_cells(&addr), Ok(0)); } #[test] @@ -336,12 +355,12 @@ mod tests { let key: &[u8; 32] = &[0x42; 32]; // when - engine.set_callee(vec![1; 32]); + engine.set_callee(H160::from([1; 20])); engine.set_storage(key, &[0x05_u8; 5]); engine.set_storage(key, &[0x05_u8; 6]); engine.get_storage(key).unwrap(); - engine.set_callee(vec![2; 32]); + engine.set_callee(H160::from([2; 20])); engine.set_storage(key, &[0x07_u8; 7]); engine.get_storage(key).unwrap(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index afcdb507b04..49e88698bc6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12,10 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::ext::{ - Engine, - Error, +use crate::{ + ext::{ + Engine, + Error, + }, + types::H160, }; +use ink_primitives::U256; use secp256k1::{ ecdsa::RecoverableSignature, Message, @@ -38,7 +42,7 @@ fn get_buffer() -> [u8; 1024] { #[test] fn store_load_clear() { let mut engine = Engine::new(); - engine.set_callee(vec![1; 32]); + engine.set_callee(H160::from([1; 20])); let key: &[u8; 32] = &[0x42; 32]; let res = engine.get_storage(key); assert_eq!(res, Err(Error::KeyNotFound)); @@ -57,17 +61,17 @@ fn store_load_clear() { fn setting_getting_balance() { // given let mut engine = Engine::new(); - let account_id = vec![1; 32]; - let balance = 1337; - engine.set_callee(account_id.clone()); - engine.set_balance(account_id, balance); + let addr = H160::from([1; 20]); + let balance = 1337.into(); + engine.set_callee(addr); + engine.set_balance(addr, balance); // when let mut output = get_buffer(); engine.balance(&mut &mut output[..]); // then - let output = ::decode(&mut &output[..16]) + let output = ::decode(&mut &output[..32]) .unwrap_or_else(|err| panic!("decoding balance failed: {err}")); assert_eq!(output, balance); } @@ -76,48 +80,49 @@ fn setting_getting_balance() { fn setting_getting_caller() { // given let mut engine = Engine::new(); - let account_id = vec![1; 32]; + let caller = H160::from([1u8; 20]); // when - engine.set_caller(account_id.clone()); + engine.set_caller(caller); // then let mut output = get_buffer(); engine.caller(&mut &mut output[..]); - assert_eq!(&output[..account_id.len()], &account_id); + let val = scale::Encode::encode(&caller); + assert!(&output[..val.len()].eq(val.as_slice())); } #[test] fn address() { // given let mut engine = Engine::new(); - let account_id = vec![1; 32]; - engine.set_callee(account_id.clone()); + let addr = H160::from([1; 20]); + engine.set_callee(addr); // when let mut output = get_buffer(); engine.address(&mut &mut output[..]); // then - assert_eq!(&output[..account_id.len()], &account_id); + assert!(&output[..20].eq(addr.as_bytes())); } #[test] fn transfer() { // given let mut engine = Engine::new(); - let alice = vec![1; 32]; - let bob = vec![2; 32]; - engine.set_callee(alice.clone()); - engine.set_balance(alice.clone(), 1337); + let alice = H160::from([1; 20]); + let bob = H160::from([2; 20]); + engine.set_callee(alice); + engine.set_balance(alice, 1337.into()); // when let val = scale::Encode::encode(&337u128); - assert_eq!(engine.transfer(&bob, &val), Ok(())); + assert_eq!(engine.transfer(bob, &val), Ok(())); // then - assert_eq!(engine.get_balance(alice), Ok(1000)); - assert_eq!(engine.get_balance(bob), Ok(337)); + assert_eq!(engine.get_balance(alice), Ok(1000.into())); + assert_eq!(engine.get_balance(bob), Ok(337.into())); } #[test] @@ -166,7 +171,7 @@ fn events() { fn value_transferred() { // given let mut engine = Engine::new(); - let value = 1337; + let value = 1337.into(); engine.set_value_transferred(value); // when @@ -174,7 +179,7 @@ fn value_transferred() { engine.value_transferred(output); // then - let output = ::decode(&mut &output[..16]) + let output = ::decode(&mut &output[..32]) .expect("decoding value transferred failed"); assert_eq!(output, value); } diff --git a/crates/engine/src/types.rs b/crates/engine/src/types.rs index 131db420809..fcc826e0b26 100644 --- a/crates/engine/src/types.rs +++ b/crates/engine/src/types.rs @@ -16,6 +16,8 @@ //! This is a known limitation that we want to address in the future. use derive_more::From; +use ink_primitives::AccountId; +pub use ink_primitives::H160; /// Same type as the `DefaultEnvironment::BlockNumber` type. pub type BlockNumber = u32; @@ -26,23 +28,6 @@ pub type BlockTimestamp = u64; /// Same type as the `DefaultEnvironment::Balance` type. pub type Balance = u128; -/// The Account Id type used by this crate. -#[derive(Debug, From, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[repr(transparent)] -pub struct AccountId(Vec); - -impl AccountId { - /// Creates a new `AccountId` from the given raw bytes. - pub fn from_bytes(bytes: &[u8]) -> Self { - Self(bytes.to_vec()) - } - - /// Returns the `AccountId` as bytes. - pub fn as_bytes(&self) -> &[u8] { - &self.0[..] - } -} - /// Key into the database. /// /// Used to identify contract storage cells for read and write operations. @@ -58,6 +43,7 @@ impl Key { } } +// todo rename the whole thing /// Errors encountered upon interacting with accounts. #[derive(Clone, Debug, From, PartialEq, Eq)] pub enum AccountError { @@ -65,5 +51,30 @@ pub enum AccountError { #[from(ignore)] UnexpectedUserAccount, #[from(ignore)] - NoAccountForId(Vec), + NoAccountForId(AccountId), + NoContractForId(H160), +} + +/// The type of origins supported by `pallet-revive`. +#[derive(Debug, Eq, Default, Clone, scale::Encode, scale::Decode, PartialEq)] +//#[cfg_attr(feature = "std", derive(::scale_info::TypeInfo))] +pub enum Origin { + #[default] + Root, + Signed(Vec), } + +// impl Origin { +// Returns the AccountId of a Signed Origin or an error if the origin is Root. +// pub fn account_id(&self) -> Result { +// match self { +// Origin::Signed(id) => { +// let mut arr = [0u8; 32]; +// arr.copy_from_slice(id.as_slice()); +// Ok(AccountId::from(arr)) +// }, +// Origin::Root => Err(()), +// } +// } +// } +// diff --git a/crates/env/Cargo.toml b/crates/env/Cargo.toml index 588fe646ed0..a0888828b8f 100644 --- a/crates/env/Cargo.toml +++ b/crates/env/Cargo.toml @@ -20,29 +20,25 @@ ink_allocator = { workspace = true } ink_storage_traits = { workspace = true } ink_prelude = { workspace = true } ink_primitives = { workspace = true } -pallet-contracts-uapi = { workspace = true } +ink_macro = { workspace = true } pallet-revive-uapi = { workspace = true } scale = { workspace = true, features = ["max-encoded-len"] } derive_more = { workspace = true, features = ["from", "display"] } num-traits = { workspace = true, features = ["i128"] } cfg-if = { workspace = true } -paste = { workspace = true } static_assertions = { workspace = true } const_env = { workspace = true } xcm = { workspace = true } # We add the `sp-io` here to disable those features -sp-io = { version = "38.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } +sp-io = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } +sp-runtime-interface = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false, features = ["disable_target_static_assertions"] } -[target.'cfg(target_arch = "wasm32")'.dependencies] -rlibc = "1" - -[target.'cfg(target_arch = "riscv32")'.dependencies] +[target.'cfg(target_arch = "riscv64")'.dependencies] polkavm-derive = { workspace = true, default-features = false } -# TODO -[target.'cfg(all(not(target_arch = "wasm32"), not(target_arch = "riscv32")))'.dependencies] +[target.'cfg(not(target_arch = "riscv64"))'.dependencies] ink_engine = { workspace = true, default-features = true, optional = true } # Hashes for the off-chain environment. @@ -77,6 +73,7 @@ std = [ "ink_primitives/std", "ink_storage_traits/std", "ink_engine/std", + "ink_macro/std", "scale/std", "scale-decode", "scale-encode", @@ -84,6 +81,7 @@ std = [ "secp256k1", "schnorrkel", "sp-io/std", + "sp-runtime-interface/std", "num-traits/std", # Enables hashing crates for off-chain environment. "sha2", @@ -93,7 +91,6 @@ std = [ "xcm/std", "derive_more/std" ] -test_instantiate = [] # Enable contract debug messages via `debug_print!` and `debug_println!`. ink-debug = [] @@ -104,6 +101,9 @@ no-allocator = [ "ink_allocator/no-allocator" ] # Disable the ink! provided panic handler. no-panic-handler = [] -revive = [ - "ink_engine/revive" +# For the ui tests, which use this `Cargo.toml` +[lints.rust.unexpected_cfgs] +level = "warn" +check-cfg = [ + 'cfg(feature, values(any()))', ] diff --git a/crates/env/src/api.rs b/crates/env/src/api.rs index 6dbce70786f..0f02e5d7981 100644 --- a/crates/env/src/api.rs +++ b/crates/env/src/api.rs @@ -14,11 +14,6 @@ //! The public raw interface towards the host Wasm engine. -#[cfg(not(feature = "revive"))] -use crate::call::{ - CallV1, - LimitParamsV1, -}; use crate::{ backend::{ EnvBackend, @@ -30,7 +25,7 @@ use crate::{ ConstructorReturnType, CreateParams, DelegateCall, - FromAccountId, + FromAddr, LimitParamsV2, }, engine::{ @@ -48,10 +43,12 @@ use crate::{ }, Result, }; +use ink_primitives::{ + H160, + H256, + U256, +}; use ink_storage_traits::Storable; -#[cfg(not(feature = "revive"))] -use pallet_contracts_uapi::ReturnFlags; -#[cfg(feature = "revive")] use pallet_revive_uapi::ReturnFlags; /// Returns the address of the caller of the executed contract. @@ -59,13 +56,8 @@ use pallet_revive_uapi::ReturnFlags; /// # Errors /// /// If the returned caller cannot be properly decoded. -pub fn caller() -> E::AccountId -where - E: Environment, -{ - ::on_instance(|instance| { - TypedEnvBackend::caller::(instance) - }) +pub fn caller() -> H160 { + ::on_instance(TypedEnvBackend::caller) } /// Returns the transferred value for the contract execution. @@ -73,12 +65,9 @@ where /// # Errors /// /// If the returned value cannot be properly decoded. -pub fn transferred_value() -> E::Balance -where - E: Environment, -{ +pub fn transferred_value() -> U256 { ::on_instance(|instance| { - TypedEnvBackend::transferred_value::(instance) + TypedEnvBackend::transferred_value(instance) }) } @@ -96,21 +85,6 @@ where }) } -/// Returns the amount of gas left for the contract execution. -/// -/// # Errors -/// -/// If the returned value cannot be properly decoded. -#[cfg(not(feature = "revive"))] -pub fn gas_left() -> Gas -where - E: Environment, -{ - ::on_instance(|instance| { - TypedEnvBackend::gas_left::(instance) - }) -} - /// Returns the current block timestamp. /// /// # Errors @@ -143,17 +117,25 @@ where }) } +/// Returns the address of the executed contract. +/// +/// # Errors +/// +/// If the returned value cannot be properly decoded. +pub fn address() -> H160 { + ::on_instance(|instance| { + TypedEnvBackend::address(instance) + }) +} + /// Returns the balance of the executed contract. /// /// # Errors /// /// If the returned value cannot be properly decoded. -pub fn balance() -> E::Balance -where - E: Environment, -{ +pub fn balance() -> U256 { ::on_instance(|instance| { - TypedEnvBackend::balance::(instance) + TypedEnvBackend::balance(instance) }) } @@ -270,38 +252,6 @@ where }) } -/// Invokes a contract message and returns its result. -/// -/// # Note -/// -/// This is a low level way to evaluate another smart contract. -/// Prefer to use the ink! guided and type safe approach to using this. -/// -/// **This will call into the original version of the host function. It is recommended to -/// use [`invoke_contract`] to use the latest version if the target runtime supports it.** -/// -/// # Errors -/// -/// - If the called account does not exist. -/// - If the called account is not a contract. -/// - If arguments passed to the called contract message are invalid. -/// - If the called contract execution has trapped. -/// - If the called contract ran out of gas upon execution. -/// - If the returned value failed to decode properly. -#[cfg(not(feature = "revive"))] -pub fn invoke_contract_v1( - params: &CallParams, Args, R>, -) -> Result> -where - E: Environment, - Args: scale::Encode, - R: scale::Decode, -{ - ::on_instance(|instance| { - TypedEnvBackend::invoke_contract_v1::(instance, params) - }) -} - /// Invokes a contract message and returns its result. /// /// # Note @@ -322,7 +272,7 @@ where /// execution. /// - If the returned value failed to decode properly. pub fn invoke_contract( - params: &CallParams, Args, R>, + params: &CallParams, ) -> Result> where E: Environment, @@ -347,7 +297,7 @@ where /// - If arguments passed to the called code message are invalid. /// - If the called code execution has trapped. pub fn invoke_contract_delegate( - params: &CallParams, Args, R>, + params: &CallParams, ) -> Result> where E: Environment, @@ -364,7 +314,7 @@ where /// # Note /// /// This is a low level way to instantiate another smart contract, calling the latest -/// `instantiate_v2` host function. +/// `instantiate_v2` host function. // todo /// /// Prefer to use methods on a `ContractRef` or the /// [`CreateBuilder`](`crate::call::CreateBuilder`) @@ -378,63 +328,21 @@ where /// - If the instantiation process runs out of gas. /// - If given insufficient endowment. /// - If the returned account ID failed to decode properly. -pub fn instantiate_contract( - params: &CreateParams, Args, Salt, R>, +pub fn instantiate_contract( + params: &CreateParams, ) -> Result< ink_primitives::ConstructorResult<>::Output>, > where E: Environment, - ContractRef: FromAccountId + crate::ContractReverseReference, + ContractRef: FromAddr + crate::ContractReverseReference, ::Type: crate::reflect::ContractConstructorDecoder, Args: scale::Encode, - Salt: AsRef<[u8]>, - R: ConstructorReturnType, -{ - ::on_instance(|instance| { - TypedEnvBackend::instantiate_contract::( - instance, params, - ) - }) -} - -/// Instantiates another contract. -/// -/// # Note -/// -/// This is a low level way to instantiate another smart contract, calling the legacy -/// `instantiate_v1` host function. -/// -/// Prefer to use methods on a `ContractRef` or the -/// [`CreateBuilder`](`crate::call::CreateBuilder`) -/// through [`build_create`](`crate::call::build_create`) instead. -/// -/// # Errors -/// -/// - If the code hash is invalid. -/// - If the arguments passed to the instantiation process are invalid. -/// - If the instantiation process traps. -/// - If the instantiation process runs out of gas. -/// - If given insufficient endowment. -/// - If the returned account ID failed to decode properly. -#[cfg(not(feature = "revive"))] -pub fn instantiate_contract_v1( - params: &CreateParams, -) -> Result< - ink_primitives::ConstructorResult<>::Output>, -> -where - E: Environment, - ContractRef: FromAccountId, - Args: scale::Encode, - Salt: AsRef<[u8]>, R: ConstructorReturnType, { ::on_instance(|instance| { - TypedEnvBackend::instantiate_contract_v1::( - instance, params, - ) + TypedEnvBackend::instantiate_contract::(instance, params) }) } @@ -448,12 +356,9 @@ where /// This function never returns. Either the termination was successful and the /// execution of the destroyed contract is halted. Or it failed during the termination /// which is considered fatal and results in a trap and rollback. -pub fn terminate_contract(beneficiary: E::AccountId) -> ! -where - E: Environment, -{ +pub fn terminate_contract(beneficiary: H160) -> ! { ::on_instance(|instance| { - TypedEnvBackend::terminate_contract::(instance, beneficiary) + TypedEnvBackend::terminate_contract(instance, beneficiary) }) } @@ -469,8 +374,8 @@ where /// /// - If the contract does not have sufficient free funds. /// - If the transfer had brought the sender's total balance below the minimum balance. -/// You need to use [`terminate_contract`] in case this is your intention. -pub fn transfer(destination: E::AccountId, value: E::Balance) -> Result<()> +/// You need to use `terminate_contract` in case this is your intention. +pub fn transfer(destination: H160, value: U256) -> Result<()> where E: Environment, { @@ -516,7 +421,7 @@ where /// # Note /// /// This function stops the execution of the contract immediately. -#[cfg(not(feature = "test_instantiate"))] +#[cfg(not(feature = "std"))] pub fn return_value(return_flags: ReturnFlags, return_value: &R) -> ! where R: scale::Encode, @@ -530,9 +435,9 @@ where /// /// # Note /// -/// When the test_instantiate feature is used, the contract is allowed to +/// When the `std` feature is used, the contract is allowed to /// return normally. This feature should only be used for integration tests. -#[cfg(feature = "test_instantiate")] +#[cfg(feature = "std")] pub fn return_value(return_flags: ReturnFlags, return_value: &R) where R: scale::Encode, @@ -699,12 +604,9 @@ pub fn sr25519_verify( /// # Errors /// /// If the returned value cannot be properly decoded. -pub fn is_contract(account: &E::AccountId) -> bool -where - E: Environment, -{ +pub fn is_contract(account: &H160) -> bool { ::on_instance(|instance| { - TypedEnvBackend::is_contract::(instance, account) + TypedEnvBackend::is_contract(instance, account) }) } @@ -714,12 +616,9 @@ where /// /// - If no code hash was found for the specified account id. /// - If the returned value cannot be properly decoded. -pub fn code_hash(account: &E::AccountId) -> Result -where - E: Environment, -{ +pub fn code_hash(addr: &H160) -> Result { ::on_instance(|instance| { - TypedEnvBackend::code_hash::(instance, account) + TypedEnvBackend::code_hash(instance, addr) }) } @@ -728,12 +627,9 @@ where /// # Errors /// /// If the returned value cannot be properly decoded. -pub fn own_code_hash() -> Result -where - E: Environment, -{ +pub fn own_code_hash() -> Result { ::on_instance(|instance| { - TypedEnvBackend::own_code_hash::(instance) + TypedEnvBackend::own_code_hash(instance) }) } @@ -810,6 +706,7 @@ where /// /// # Errors /// +/// todo: this enum variant no longer exists /// `ReturnCode::CodeNotFound` in case the supplied `code_hash` cannot be found on-chain. /// /// # Storage Compatibility @@ -879,13 +776,11 @@ where /// Please refer to the /// [Open Zeppelin docs](https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#modifying-your-contracts) /// for more details and examples. -pub fn set_code_hash(code_hash: &E::Hash) -> Result<()> +pub fn set_code_hash(code_hash: &H256) -> Result<()> where E: Environment, { - ::on_instance(|instance| { - instance.set_code_hash(code_hash.as_ref()) - }) + ::on_instance(|instance| instance.set_code_hash(code_hash)) } /// Tries to trigger a runtime dispatchable, i.e. an extrinsic from a pallet. @@ -919,7 +814,7 @@ where /// /// This guarantees that the code of the dependency cannot be removed without first /// calling [`unlock_delegate_dependency`]. It charges a fraction of the code -/// deposit, see [`pallet_contracts::Config::CodeHashLockupDepositPercent`](https://docs.rs/pallet-contracts/latest/pallet_contracts/pallet/trait.Config.html#associatedtype.CodeHashLockupDepositPercent) for details. +/// deposit, see [`pallet_contracts::Config::CodeHashLockupDepositPercent`](https://docs.rs/pallet-revive/latest/pallet_revive/pallet/trait.Config.html#associatedtype.CodeHashLockupDepositPercent) for details. /// /// # Errors /// @@ -927,7 +822,7 @@ where /// - If the `code_hash` is the same as the calling contract. /// - If the maximum number of delegate dependencies is reached. /// - If the delegate dependency already exists. -pub fn lock_delegate_dependency(code_hash: &E::Hash) +pub fn lock_delegate_dependency(code_hash: &H256) where E: Environment, { @@ -945,7 +840,7 @@ where /// # Errors /// /// - If the delegate dependency does not exist. -pub fn unlock_delegate_dependency(code_hash: &E::Hash) +pub fn unlock_delegate_dependency(code_hash: &H256) where E: Environment, { @@ -957,11 +852,11 @@ where /// Execute an XCM message locally, using the contract's address as the origin. /// /// For more details consult the -/// [host function documentation](https://paritytech.github.io/substrate/master/pallet_contracts/api_doc/trait.Current.html#tymethod.xcm_execute). +/// [host function documentation](https://paritytech.github.io/polkadot-sdk/master/pallet_contracts/api_doc/trait.Current.html#tymethod.xcm_execute). /// /// # Errors /// -/// - If the message cannot be properly decoded on the `pallet-contracts` side. +/// - If the message cannot be properly decoded on the `pallet-revive` side. /// - If the XCM execution fails because of the runtime's XCM configuration. /// /// # Panics @@ -983,11 +878,11 @@ where /// instance of the `RuntimeCall` enum. /// /// For more details consult -/// [host function documentation](https://paritytech.github.io/substrate/master/pallet_contracts/api_doc/trait.Current.html#tymethod.xcm_send). +/// [host function documentation](https://paritytech.github.io/polkadot-sdk/master/pallet_contracts/api_doc/trait.Current.html#tymethod.xcm_send). /// /// # Errors /// -/// - If the message cannot be properly decoded on the `pallet-contracts` side. +/// - If the message cannot be properly decoded on the `pallet-revive` side. /// /// # Panics /// diff --git a/crates/env/src/backend.rs b/crates/env/src/backend.rs index 3e7af4f8c6d..1f6d811482c 100644 --- a/crates/env/src/backend.rs +++ b/crates/env/src/backend.rs @@ -12,11 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[cfg(not(feature = "revive"))] -use crate::call::{ - CallV1, - LimitParamsV1, -}; use crate::{ call::{ Call, @@ -24,7 +19,7 @@ use crate::{ ConstructorReturnType, CreateParams, DelegateCall, - FromAccountId, + FromAddr, LimitParamsV2, }, event::Event, @@ -32,13 +27,15 @@ use crate::{ CryptoHash, HashOutput, }, - types::Environment, Result, }; +use ink_primitives::{ + types::Environment, + H160, + H256, + U256, +}; use ink_storage_traits::Storable; -#[cfg(not(feature = "revive"))] -pub use pallet_contracts_uapi::ReturnFlags; -#[cfg(feature = "revive")] pub use pallet_revive_uapi::ReturnFlags; /// Environmental contract functionality that does not require `Environment`. @@ -121,7 +118,7 @@ pub trait EnvBackend { /// /// The `flags` parameter can be used to revert the state changes of the /// entire execution if necessary. - #[cfg(not(feature = "test_instantiate"))] + #[cfg(not(feature = "std"))] fn return_value(&mut self, flags: ReturnFlags, return_value: &R) -> ! where R: scale::Encode; @@ -130,12 +127,12 @@ pub trait EnvBackend { /// /// # Note /// - /// When the test_instantiate feature is used, the contract is allowed to + /// When the `std` feature is used, the contract is allowed to /// return normally. This feature should only be used for integration tests. /// /// The `flags` parameter can be used to revert the state changes of the /// entire execution if necessary. - #[cfg(feature = "test_instantiate")] + #[cfg(feature = "std")] fn return_value(&mut self, flags: ReturnFlags, return_value: &R) where R: scale::Encode; @@ -235,7 +232,7 @@ pub trait EnvBackend { /// # Errors /// /// - If the supplied `code_hash` cannot be found on-chain. - fn set_code_hash(&mut self, code_hash: &[u8]) -> Result<()>; + fn set_code_hash(&mut self, code_hash: &H256) -> Result<()>; } /// Environmental contract functionality. @@ -245,14 +242,14 @@ pub trait TypedEnvBackend: EnvBackend { /// # Note /// /// For more details visit: [`caller`][`crate::caller`] - fn caller(&mut self) -> E::AccountId; + fn caller(&mut self) -> H160; /// Returns the transferred value for the contract execution. /// /// # Note /// /// For more details visit: [`transferred_value`][`crate::transferred_value`] - fn transferred_value(&mut self) -> E::Balance; + fn transferred_value(&mut self) -> U256; /// Returns the price for the specified amount of gas. /// @@ -261,14 +258,6 @@ pub trait TypedEnvBackend: EnvBackend { /// For more details visit: [`weight_to_fee`][`crate::weight_to_fee`] fn weight_to_fee(&mut self, gas: u64) -> E::Balance; - /// Returns the amount of gas left for the contract execution. - /// - /// # Note - /// - /// For more details visit: [`gas_left`][`crate::gas_left`] - #[cfg(not(feature = "revive"))] - fn gas_left(&mut self) -> u64; - /// Returns the timestamp of the current block. /// /// # Note @@ -283,12 +272,19 @@ pub trait TypedEnvBackend: EnvBackend { /// For more details visit: [`account_id`][`crate::account_id`] fn account_id(&mut self) -> E::AccountId; + /// Returns the address of the executed contract. + /// + /// # Note + /// + /// For more details visit: [`address`][`crate::address`] + fn address(&mut self) -> H160; + /// Returns the balance of the executed contract. /// /// # Note /// /// For more details visit: [`balance`][`crate::balance`] - fn balance(&mut self) -> E::Balance; + fn balance(&mut self) -> U256; /// Returns the current block number. /// @@ -315,23 +311,6 @@ pub trait TypedEnvBackend: EnvBackend { E: Environment, Evt: Event; - /// Invokes a contract message and returns its result. - /// - /// # Note - /// - /// **This will call into the original `call` host function.** - /// - /// For more details visit: [`invoke_contract`][`crate::invoke_contract_v1`] - #[cfg(not(feature = "revive"))] - fn invoke_contract_v1( - &mut self, - call_data: &CallParams, Args, R>, - ) -> Result> - where - E: Environment, - Args: scale::Encode, - R: scale::Decode; - /// Invokes a contract message and returns its result. /// /// # Note @@ -341,7 +320,7 @@ pub trait TypedEnvBackend: EnvBackend { /// For more details visit: [`invoke_contract`][`crate::invoke_contract`] fn invoke_contract( &mut self, - call_data: &CallParams, Args, R>, + call_data: &CallParams, ) -> Result> where E: Environment, @@ -356,7 +335,7 @@ pub trait TypedEnvBackend: EnvBackend { /// [`invoke_contract_delegate`][`crate::invoke_contract_delegate`] fn invoke_contract_delegate( &mut self, - call_data: &CallParams, Args, R>, + call_data: &CallParams, ) -> Result> where E: Environment, @@ -368,9 +347,9 @@ pub trait TypedEnvBackend: EnvBackend { /// # Note /// /// For more details visit: [`instantiate_contract`][`crate::instantiate_contract`] - fn instantiate_contract( + fn instantiate_contract( &mut self, - params: &CreateParams, Args, Salt, R>, + params: &CreateParams, ) -> Result< ink_primitives::ConstructorResult< >::Output, @@ -378,27 +357,10 @@ pub trait TypedEnvBackend: EnvBackend { > where E: Environment, - ContractRef: FromAccountId + crate::ContractReverseReference, + ContractRef: FromAddr + crate::ContractReverseReference, ::Type: crate::reflect::ContractConstructorDecoder, Args: scale::Encode, - Salt: AsRef<[u8]>, - R: ConstructorReturnType; - - #[cfg(not(feature = "revive"))] - fn instantiate_contract_v1( - &mut self, - params: &CreateParams, - ) -> Result< - ink_primitives::ConstructorResult< - >::Output, - >, - > - where - E: Environment, - ContractRef: FromAccountId, - Args: scale::Encode, - Salt: AsRef<[u8]>, R: ConstructorReturnType; /// Terminates a smart contract. @@ -406,28 +368,24 @@ pub trait TypedEnvBackend: EnvBackend { /// # Note /// /// For more details visit: [`terminate_contract`][`crate::terminate_contract`] - fn terminate_contract(&mut self, beneficiary: E::AccountId) -> ! - where - E: Environment; + fn terminate_contract(&mut self, beneficiary: H160) -> !; /// Transfers value from the contract to the destination account ID. /// /// # Note /// /// For more details visit: [`transfer`][`crate::transfer`] - fn transfer(&mut self, destination: E::AccountId, value: E::Balance) -> Result<()> + fn transfer(&mut self, destination: H160, value: U256) -> Result<()> where E: Environment; - /// Checks whether a specified account belongs to a contract. + /// Checks whether a specified contract lives at `addr`. /// /// # Note /// /// For more details visit: [`is_contract`][`crate::is_contract`] #[allow(clippy::wrong_self_convention)] - fn is_contract(&mut self, account: &E::AccountId) -> bool - where - E: Environment; + fn is_contract(&mut self, account: &H160) -> bool; /// Checks whether the caller of the current contract is the origin of the whole call /// stack. @@ -453,18 +411,14 @@ pub trait TypedEnvBackend: EnvBackend { /// # Note /// /// For more details visit: [`code_hash`][`crate::code_hash`] - fn code_hash(&mut self, account: &E::AccountId) -> Result - where - E: Environment; + fn code_hash(&mut self, account: &H160) -> Result; /// Retrieves the code hash of the currently executing contract. /// /// # Note /// /// For more details visit: [`own_code_hash`][`crate::own_code_hash`] - fn own_code_hash(&mut self) -> Result - where - E: Environment; + fn own_code_hash(&mut self) -> Result; fn call_runtime(&mut self, call: &Call) -> Result<()> where @@ -477,7 +431,7 @@ pub trait TypedEnvBackend: EnvBackend { /// /// For more details visit: /// [`lock_delegate_dependency`][`crate::lock_delegate_dependency`] - fn lock_delegate_dependency(&mut self, code_hash: &E::Hash) + fn lock_delegate_dependency(&mut self, code_hash: &H256) where E: Environment; @@ -487,7 +441,7 @@ pub trait TypedEnvBackend: EnvBackend { /// /// For more details visit: /// [`unlock_delegate_dependency`][`crate::unlock_delegate_dependency`]. - fn unlock_delegate_dependency(&mut self, code_hash: &E::Hash) + fn unlock_delegate_dependency(&mut self, code_hash: &H256) where E: Environment; diff --git a/crates/env/src/call/call_builder/call.rs b/crates/env/src/call/call_builder/call.rs index fafe894ebe9..e60eb0026c5 100644 --- a/crates/env/src/call/call_builder/call.rs +++ b/crates/env/src/call/call_builder/call.rs @@ -12,8 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[cfg(not(feature = "revive"))] -use crate::call::CallV1; use crate::{ call::{ common::{ @@ -32,64 +30,43 @@ use crate::{ }, Error, }; -use num_traits::Zero; -#[cfg(not(feature = "revive"))] -use pallet_contracts_uapi::CallFlags; -#[cfg(feature = "revive")] +use ink_primitives::{ + H160, + U256, +}; use pallet_revive_uapi::CallFlags; -/// The default call type for cross-contract calls, for calling into the latest `call_v2` +/// The default call type for cross-contract calls, for calling into the latest `call` /// host function. This adds the additional weight limit parameter `proof_size_limit` as /// well as `storage_deposit_limit`. #[derive(Clone)] -pub struct Call { - callee: E::AccountId, +pub struct Call { + callee: H160, ref_time_limit: u64, proof_size_limit: u64, - storage_deposit_limit: Option, - transferred_value: E::Balance, + storage_deposit_limit: Option, + transferred_value: U256, call_flags: CallFlags, } -impl Call { +impl Call { /// Returns a clean builder for [`Call`]. - pub fn new(callee: E::AccountId) -> Self { + pub fn new(callee: H160) -> Self { Self { callee, ref_time_limit: Default::default(), proof_size_limit: Default::default(), storage_deposit_limit: None, - transferred_value: E::Balance::zero(), + transferred_value: U256::zero(), call_flags: CallFlags::empty(), } } } -impl CallBuilder>, Args, RetType> +impl CallBuilder, Args, RetType> where E: Environment, { - /// Switch to the original `call` host function API, which only allows the `gas_limit` - /// limit parameter (equivalent to the `ref_time_limit` in the latest `call_v2`). - /// - /// This method instance is used to allow usage of the generated call builder methods - /// for messages which initialize the builder with the new [`Call`] type. - #[cfg(not(feature = "revive"))] - pub fn call_v1(self) -> CallBuilder>, Args, RetType> { - let call_type = self.call_type.value(); - CallBuilder { - call_type: Set(CallV1 { - callee: call_type.callee, - gas_limit: call_type.ref_time_limit, - transferred_value: call_type.transferred_value, - call_flags: call_type.call_flags, - }), - exec_input: self.exec_input, - return_type: self.return_type, - _phantom: Default::default(), - } - } - /// Sets the `ref_time_limit` part of the weight limit for the current cross-contract /// call. /// @@ -134,7 +111,7 @@ where /// The `storage_deposit_limit` specifies the amount of user funds that /// can be charged for creating storage. You can find more info /// [here](https://use.ink/basics/gas). - pub fn storage_deposit_limit(self, storage_deposit_limit: E::Balance) -> Self { + pub fn storage_deposit_limit(self, storage_deposit_limit: U256) -> Self { let call_type = self.call_type.value(); CallBuilder { call_type: Set(Call { @@ -149,7 +126,7 @@ where /// /// This value specifies the amount of user funds that are transferred /// to the other contract with this call. - pub fn transferred_value(self, transferred_value: E::Balance) -> Self { + pub fn transferred_value(self, transferred_value: U256) -> Self { let call_type = self.call_type.value(); CallBuilder { call_type: Set(Call { @@ -176,12 +153,12 @@ where } impl - CallBuilder>, Set>, Set>> + CallBuilder, Set>, Set>> where E: Environment, { /// Finalizes the call builder to call a function. - pub fn params(self) -> CallParams, Args, RetType> { + pub fn params(self) -> CallParams { CallParams { call_type: self.call_type.value(), _return_type: Default::default(), @@ -192,12 +169,12 @@ where } impl - CallBuilder>, Unset>, Unset> + CallBuilder, Unset>, Unset> where E: Environment, { /// Finalizes the call builder to call a function. - pub fn params(self) -> CallParams, EmptyArgumentList, ()> { + pub fn params(self) -> CallParams { CallParams { call_type: self.call_type.value(), _return_type: Default::default(), @@ -210,7 +187,7 @@ where impl CallBuilder< E, - Set>, + Set, Unset>, Unset>, > @@ -240,8 +217,7 @@ where } } -impl - CallBuilder>, Set>, Set>> +impl CallBuilder, Set>, Set>> where E: Environment, Args: scale::Encode, @@ -270,13 +246,13 @@ where } } -impl CallParams, Args, R> +impl CallParams where E: Environment, { - /// Returns the account ID of the called contract instance. + /// Returns the contract address of the called contract instance. #[inline] - pub fn callee(&self) -> &E::AccountId { + pub fn callee(&self) -> &H160 { &self.call_type.callee } @@ -293,14 +269,15 @@ where } /// Returns the chosen storage deposit limit for the called contract execution. + /// todo #[inline] - pub fn storage_deposit_limit(&self) -> Option<&E::Balance> { - self.call_type.storage_deposit_limit.as_ref() + pub fn storage_deposit_limit(&self) -> Option { + self.call_type.storage_deposit_limit } /// Returns the transferred value for the called contract. #[inline] - pub fn transferred_value(&self) -> &E::Balance { + pub fn transferred_value(&self) -> &U256 { &self.call_type.transferred_value } @@ -311,7 +288,7 @@ where } } -impl CallParams, Args, R> +impl CallParams where E: Environment, Args: scale::Encode, diff --git a/crates/env/src/call/call_builder/delegate.rs b/crates/env/src/call/call_builder/delegate.rs index dd4c28d6e76..e59755bf111 100644 --- a/crates/env/src/call/call_builder/delegate.rs +++ b/crates/env/src/call/call_builder/delegate.rs @@ -27,57 +27,66 @@ use crate::{ types::Environment, Error, }; -#[cfg(not(feature = "revive"))] -use pallet_contracts_uapi::CallFlags; -#[cfg(feature = "revive")] +use ink_primitives::H160; use pallet_revive_uapi::CallFlags; /// The `delegatecall` call type. Performs a call with the given code hash. #[derive(Clone)] -pub struct DelegateCall { - code_hash: E::Hash, - call_flags: CallFlags, +pub struct DelegateCall { + // todo comments please + address: H160, + flags: CallFlags, + ref_time_limit: u64, + proof_size_limit: u64, + // todo U256 + deposit_limit: Option<[u8; 32]>, } -impl DelegateCall { +impl DelegateCall { /// Returns a clean builder for [`DelegateCall`] - pub const fn new(code_hash: E::Hash) -> Self { + pub const fn new(address: H160) -> Self { DelegateCall { - code_hash, - call_flags: CallFlags::empty(), + address, + flags: CallFlags::empty(), + ref_time_limit: 0, + proof_size_limit: 0, + deposit_limit: None, } } - /// Sets the `code_hash` to perform a delegate call with. - pub fn code_hash(self, code_hash: E::Hash) -> Self { + /// Sets the `address` to perform a delegate call with. + pub fn address(self, address: H160) -> Self { DelegateCall { - code_hash, - call_flags: CallFlags::empty(), + address, + flags: CallFlags::empty(), + ref_time_limit: 0, + proof_size_limit: 0, + deposit_limit: None, } } } -impl CallBuilder>, Args, RetType> +impl CallBuilder, Args, RetType> where E: Environment, { - /// Sets the `code_hash` to perform a delegate call with. - pub fn code_hash(self, code_hash: E::Hash) -> Self { + /// Sets the `address` to perform a delegate call with. + pub fn address(self, address: H160) -> Self { let call_type = self.call_type.value(); CallBuilder { call_type: Set(DelegateCall { - code_hash, + address, ..call_type }), ..self } } - /// Sets the `code_hash` to perform a delegate call with. + /// Sets the `CallFlags` to perform a delegate call with. pub fn call_flags(self, call_flags: CallFlags) -> Self { CallBuilder { call_type: Set(DelegateCall { - call_flags, + flags: call_flags, ..self.call_type.value() }), exec_input: self.exec_input, @@ -88,17 +97,12 @@ where } impl - CallBuilder< - E, - Set>, - Set>, - Set>, - > + CallBuilder, Set>, Set>> where E: Environment, { /// Finalizes the call builder to call a function. - pub fn params(self) -> CallParams, Args, RetType> { + pub fn params(self) -> CallParams { CallParams { call_type: self.call_type.value(), _return_type: Default::default(), @@ -111,7 +115,7 @@ where impl CallBuilder< E, - Set>, + Set, Unset>, Unset, > @@ -119,7 +123,7 @@ where E: Environment, { /// Finalizes the call builder to call a function. - pub fn params(self) -> CallParams, EmptyArgumentList, ()> { + pub fn params(self) -> CallParams { CallParams { call_type: self.call_type.value(), _return_type: Default::default(), @@ -132,7 +136,7 @@ where impl CallBuilder< E, - Set>, + Set, Unset>, Unset>, > @@ -162,7 +166,7 @@ where } impl - CallBuilder>, Set>, Set>> + CallBuilder, Set>, Set>> where E: Environment, Args: scale::Encode, @@ -193,24 +197,42 @@ where } } -impl CallParams, Args, R> +impl CallParams where E: Environment, { - /// Returns the code hash which we use to perform a delegate call. + /// Returns the call flags. #[inline] - pub fn code_hash(&self) -> &E::Hash { - &self.call_type.code_hash + pub fn call_flags(&self) -> &CallFlags { + &self.call_type.flags } - /// Returns the call flags. + /// Returns the contract address which we use to perform a delegate call. #[inline] - pub fn call_flags(&self) -> &CallFlags { - &self.call_type.call_flags + pub fn address(&self) -> &H160 { + &self.call_type.address + } + + /// Returns the `ref_time_limit` which we use to perform a delegate call. + #[inline] + pub fn ref_time_limit(&self) -> u64 { + self.call_type.ref_time_limit + } + + /// Returns the `proof_size_limit` which we use to perform a delegate call. + #[inline] + pub fn proof_size_limit(&self) -> u64 { + self.call_type.proof_size_limit + } + + /// Returns the `deposit_limit` which we use to perform a delegate call. + #[inline] + pub fn deposit_limit(&self) -> &Option<[u8; 32]> { + &self.call_type.deposit_limit } } -impl CallParams, Args, R> +impl CallParams where E: Environment, Args: scale::Encode, diff --git a/crates/env/src/call/call_builder/mod.rs b/crates/env/src/call/call_builder/mod.rs index c83c9277412..3a237a04a73 100644 --- a/crates/env/src/call/call_builder/mod.rs +++ b/crates/env/src/call/call_builder/mod.rs @@ -13,13 +13,9 @@ // limitations under the License. mod call; -#[cfg(not(feature = "revive"))] -mod call_v1; mod delegate; pub use call::Call; -#[cfg(not(feature = "revive"))] -pub use call_v1::CallV1; pub use delegate::DelegateCall; use crate::{ @@ -36,6 +32,7 @@ use crate::{ types::Environment, }; use core::marker::PhantomData; +use ink_primitives::H160; /// The final parameters to the cross-contract call. #[derive(Debug)] @@ -89,13 +86,15 @@ where /// # DefaultEnvironment, /// # call::{build_call, Selector, ExecutionInput} /// # }; -/// # use ink_env::call::CallV1; -/// # type AccountId = ::AccountId; +/// # use ink_env::call::Call; +/// # use ink_primitives::H160; +/// +/// type AccountId = ::AccountId; /// # type Balance = ::Balance; /// build_call::() -/// .call_v1(AccountId::from([0x42; 32])) -/// .gas_limit(5000) -/// .transferred_value(10) +/// .call(H160::from([0x42; 20])) +/// .ref_time_limit(5000) +/// .transferred_value(ink::U256::from(10)) /// .exec_input( /// ExecutionInput::new(Selector::new([0xDE, 0xAD, 0xBE, 0xEF])) /// .push_arg(42u8) @@ -121,13 +120,13 @@ where /// # use ::ink_env::{ /// # Environment, /// # DefaultEnvironment, -/// # call::{build_call, Selector, ExecutionInput, CallV1}, +/// # call::{build_call, Selector, ExecutionInput, Call}, /// # }; /// # type AccountId = ::AccountId; /// let my_return_value: i32 = build_call::() -/// .call_type(CallV1::new(AccountId::from([0x42; 32]))) -/// .gas_limit(5000) -/// .transferred_value(10) +/// .call_type(Call::new(ink::H160::from([0x42; 20]))) +/// .ref_time_limit(5000) +/// .transferred_value(ink::U256::from(10)) /// .exec_input( /// ExecutionInput::new(Selector::new([0xDE, 0xAD, 0xBE, 0xEF])) /// .push_arg(42u8) @@ -150,10 +149,11 @@ where /// # DefaultEnvironment, /// # call::{build_call, Selector, ExecutionInput, utils::ReturnType, DelegateCall}, /// # }; +/// use ink::H160; /// # use ink_primitives::Clear; /// # type AccountId = ::AccountId; /// let my_return_value: i32 = build_call::() -/// .delegate(::Hash::CLEAR_HASH) +/// .delegate(H160::zero()) /// .exec_input( /// ExecutionInput::new(Selector::new([0xDE, 0xAD, 0xBE, 0xEF])) /// .push_arg(42u8) @@ -185,13 +185,15 @@ where /// # DefaultEnvironment, /// # call::{build_call, Selector, ExecutionInput} /// # }; -/// # use ink_env::call::CallV1; -/// # type AccountId = ::AccountId; +/// # use ink_env::call::Call; +/// # use ink_primitives::H160; +/// +/// type AccountId = ::AccountId; /// # type Balance = ::Balance; /// let call_result = build_call::() -/// .call_v1(AccountId::from([0x42; 32])) -/// .gas_limit(5000) -/// .transferred_value(10) +/// .call(H160::from([0x42; 20])) +/// .ref_time_limit(5000) +/// .transferred_value(ink::U256::from(10)) /// .try_invoke() /// .expect("Got an error from the Contract's pallet."); /// @@ -204,7 +206,7 @@ where #[allow(clippy::type_complexity)] pub fn build_call() -> CallBuilder< E, - Unset>, + Unset, Unset>, Unset>, > @@ -229,16 +231,11 @@ where call_type: CallType, exec_input: Args, return_type: RetType, - _phantom: PhantomData E>, + _phantom: PhantomData E>, // todo possibly remove? } impl From> - for CallBuilder< - E, - Unset>, - Set>, - Set>, - > + for CallBuilder, Set>, Set>> where E: Environment, { @@ -316,27 +313,9 @@ impl CallBuilder, Args, RetType> where E: Environment, { - /// Prepares the `CallBuilder` for a cross-contract [`CallV1`], calling into the - /// original `call` host function. - #[cfg(not(feature = "revive"))] - pub fn call_v1( - self, - callee: E::AccountId, - ) -> CallBuilder>, Args, RetType> { - CallBuilder { - call_type: Set(CallV1::new(callee)), - exec_input: self.exec_input, - return_type: self.return_type, - _phantom: Default::default(), - } - } - /// Prepares the `CallBuilder` for a cross-contract [`Call`] to the latest `call_v2` /// host function. - pub fn call( - self, - callee: E::AccountId, - ) -> CallBuilder>, Args, RetType> { + pub fn call(self, callee: H160) -> CallBuilder, Args, RetType> { CallBuilder { call_type: Set(Call::new(callee)), exec_input: self.exec_input, @@ -348,10 +327,11 @@ where /// Prepares the `CallBuilder` for a cross-contract [`DelegateCall`]. pub fn delegate( self, - code_hash: E::Hash, - ) -> CallBuilder>, Args, RetType> { + address: H160, + ) -> CallBuilder, Args, RetType> { CallBuilder { - call_type: Set(DelegateCall::new(code_hash)), + // todo Generic `Set` can be removed + call_type: Set(DelegateCall::new(address)), exec_input: self.exec_input, return_type: self.return_type, _phantom: Default::default(), diff --git a/crates/env/src/call/create_builder.rs b/crates/env/src/call/create_builder.rs index a154f3b8262..8ea6d76bac3 100644 --- a/crates/env/src/call/create_builder.rs +++ b/crates/env/src/call/create_builder.rs @@ -23,18 +23,20 @@ use crate::{ ExecutionInput, Selector, }, - ContractEnv, types::Environment, + ContractEnv, Error, }; use core::marker::PhantomData; +use ink_primitives::{ + H160, + H256, + U256, +}; pub mod state { //! Type states that tell what state of a instantiation argument has not //! yet been set properly for a valid construction. - - /// Type state for the salt used for contract instantiation. - pub enum Salt {} } /// Contracts that can be constructed from an `AccountId`. @@ -46,13 +48,10 @@ pub mod state { /// /// But it is possible to use `From for T` with [`crate::AccountIdGuard`] /// bound. -pub trait FromAccountId -where - T: Environment, -{ +pub trait FromAddr { /// Creates the contract instance from the account ID of the already instantiated /// contract. - fn from_account_id(account_id: ::AccountId) -> Self; + fn from_addr(addr: H160) -> Self; } /// Represents any type that can be returned from an `ink!` constructor. The following @@ -134,7 +133,7 @@ pub trait ConstructorReturnType { /// type will become the type of the `ContractRef`'s type. impl ConstructorReturnType for C where - C: ContractEnv + FromAccountId<::Env>, + C: ContractEnv + FromAddr, { type Output = C; type Error = (); @@ -148,7 +147,7 @@ where /// of a `ContractRef` inherent becomes the `ContractRef`s type. impl ConstructorReturnType for core::result::Result where - C: ContractEnv + FromAccountId<::Env>, + C: ContractEnv + FromAddr, E: scale::Decode, { const IS_RESULT: bool = true; @@ -165,62 +164,49 @@ where } } -/// Defines the limit params for the legacy `ext::instantiate_v1` host function, -/// consisting of the `gas_limit` which is equivalent to the `ref_time_limit` in the new -/// `ext::instantiate`. -#[derive(Clone, Debug)] -pub struct LimitParamsV1 { - gas_limit: u64, -} - /// Defines the limit params for the new `ext::instantiate` host function. +/// todo: rename #[derive(Clone, Debug)] -pub struct LimitParamsV2 -where - E: Environment, -{ +pub struct LimitParamsV2 { ref_time_limit: u64, proof_size_limit: u64, - storage_deposit_limit: Option, + storage_deposit_limit: Option, } /// Builds up contract instantiations. #[derive(Debug)] -pub struct CreateParams -where - E: Environment, -{ +pub struct CreateParams { /// The code hash of the created contract. - code_hash: E::Hash, + code_hash: H256, /// Parameters for weight and storage limits, differs for versions of the instantiate /// host function. limits: Limits, /// The endowment for the instantiated contract. - endowment: E::Balance, + /// todo: is this correct? or is the value here `U256`? + endowment: U256, /// The input data for the instantiation. exec_input: ExecutionInput, /// The salt for determining the hash for the contract account ID. - salt_bytes: Salt, + salt_bytes: Option<[u8; 32]>, /// The return type of the target contract's constructor method. _return_type: ReturnType, /// The type of the reference to the contract returned from the constructor. - _phantom: PhantomData ContractRef>, + _phantom: PhantomData (E, ContractRef)>, } -impl - CreateParams +impl CreateParams where E: Environment, { /// The code hash of the contract. #[inline] - pub fn code_hash(&self) -> &E::Hash { + pub fn code_hash(&self) -> &H256 { &self.code_hash } /// The endowment for the instantiated contract. #[inline] - pub fn endowment(&self) -> &E::Balance { + pub fn endowment(&self) -> &U256 { &self.endowment } @@ -239,8 +225,7 @@ where } } -impl - CreateParams, Args, Salt, R> +impl CreateParams where E: Environment, { @@ -259,49 +244,34 @@ where /// Gets the `storage_deposit_limit` for the contract instantiation. #[inline] - pub fn storage_deposit_limit(&self) -> Option<&E::Balance> { + pub fn storage_deposit_limit(&self) -> Option<&U256> { self.limits.storage_deposit_limit.as_ref() } } -impl - CreateParams -where - E: Environment, -{ - /// The gas limit for the contract instantiation. - #[inline] - pub fn gas_limit(&self) -> u64 { - self.limits.gas_limit - } -} - -impl - CreateParams +impl CreateParams where E: Environment, - Salt: AsRef<[u8]>, { /// The salt for determining the hash for the contract account ID. #[inline] - pub fn salt_bytes(&self) -> &Salt { + pub fn salt_bytes(&self) -> &Option<[u8; 32]> { &self.salt_bytes } } -impl - CreateParams, Args, Salt, R> +impl CreateParams where E: Environment, - ContractRef: FromAccountId + crate::ContractReverseReference, + ContractRef: FromAddr + crate::ContractReverseReference, ::Type: crate::reflect::ContractConstructorDecoder, ::Type: crate::reflect::ContractMessageDecoder, Args: scale::Encode, - Salt: AsRef<[u8]>, R: ConstructorReturnType, { + /// todo /// Instantiates the contract and returns its account ID back to the caller. /// /// # Panics @@ -341,66 +311,17 @@ where } } -#[cfg(not(feature = "revive"))] -impl - CreateParams -where - E: Environment, - ContractRef: FromAccountId, - Args: scale::Encode, - Salt: AsRef<[u8]>, - R: ConstructorReturnType, -{ - /// Instantiates the contract and returns its account ID back to the caller. - /// - /// # Panics - /// - /// This method panics if it encounters an [`ink::env::Error`][`crate::Error`] or an - /// [`ink::primitives::LangError`][`ink_primitives::LangError`]. If you want to handle - /// those use the [`try_instantiate`][`CreateParams::try_instantiate`] method - /// instead. - #[inline] - pub fn instantiate(&self) -> >::Output { - self.try_instantiate() - .unwrap_or_else(|env_error| { - panic!("Cross-contract instantiation failed with {env_error:?}") - }) - .unwrap_or_else(|lang_error| { - panic!("Received a `LangError` while instantiating: {lang_error:?}") - }) - } - - /// Instantiates the contract and returns its account ID back to the caller. - /// - /// # Note - /// - /// On failure this returns an outer [`ink::env::Error`][`crate::Error`] or inner - /// [`ink::primitives::LangError`][`ink_primitives::LangError`], both of which can be - /// handled by the caller. - #[inline] - pub fn try_instantiate( - &self, - ) -> Result< - ink_primitives::ConstructorResult< - >::Output, - >, - Error, - > { - crate::instantiate_contract_v1(self) - } -} - /// Builds up contract instantiations. #[derive(Clone)] -pub struct CreateBuilder +pub struct CreateBuilder where E: Environment, { - code_hash: CodeHash, + code_hash: H256, limits: Limits, - endowment: Endowment, + endowment: U256, exec_input: Args, - salt: Salt, + salt: Option<[u8; 32]>, return_type: RetType, _phantom: PhantomData (E, ContractRef)>, } @@ -430,7 +351,7 @@ where /// # use ::ink_env::{ /// # Environment, /// # DefaultEnvironment, -/// # call::{build_create, Selector, ExecutionInput, FromAccountId} +/// # call::{build_create, Selector, ExecutionInput, FromAddr} /// # }; /// # type Hash = ::Hash; /// # @@ -449,15 +370,15 @@ where /// # } /// # use contract::MyContractRef; /// let my_contract: MyContractRef = build_create::() -/// .code_hash(Hash::from([0x42; 32])) -/// .endowment(25) +/// .code_hash(ink::H256::from([0x42; 32])) +/// .endowment(25.into()) /// .exec_input( /// ExecutionInput::new(Selector::new(ink::selector_bytes!("my_constructor"))) /// .push_arg(42) /// .push_arg(true) /// .push_arg(&[0x10u8; 32]), /// ) -/// .salt_bytes(&[0xDE, 0xAD, 0xBE, 0xEF]) +/// .salt_bytes(Some([1u8; 32])) /// .returns::() /// .instantiate(); /// ``` @@ -468,7 +389,7 @@ where /// # use ::ink_env::{ /// # Environment, /// # DefaultEnvironment, -/// # call::{build_create, Selector, ExecutionInput, FromAccountId} +/// # call::{build_create, Selector, ExecutionInput, FromAddr} /// # }; /// # type Hash = ::Hash; /// # @@ -493,15 +414,15 @@ where /// # } /// # use contract::{MyContractRef, ConstructorError}; /// let my_contract: MyContractRef = build_create::() -/// .code_hash(Hash::from([0x42; 32])) -/// .endowment(25) +/// .code_hash(ink::H256::from([0x42; 32])) +/// .endowment(25.into()) /// .exec_input( /// ExecutionInput::new(Selector::new(ink::selector_bytes!("my_constructor"))) /// .push_arg(42) /// .push_arg(true) /// .push_arg(&[0x10u8; 32]), /// ) -/// .salt_bytes(&[0xDE, 0xAD, 0xBE, 0xEF]) +/// .salt_bytes(Some([1u8; 32])) /// .returns::>() /// .instantiate() /// .expect("Constructor should have executed successfully."); @@ -510,11 +431,8 @@ where pub fn build_create() -> CreateBuilder< ::Env, ContractRef, - Unset<<::Env as Environment>::Hash>, - Set::Env>>, - Unset<<::Env as Environment>::Balance>, + Set, Unset>, - Unset, Unset>, > where @@ -535,8 +453,8 @@ where } } -impl - CreateBuilder, Limits, Endowment, Args, Salt, RetType> +impl + CreateBuilder where E: Environment, { @@ -544,11 +462,10 @@ where #[inline] pub fn code_hash( self, - code_hash: E::Hash, - ) -> CreateBuilder, Limits, Endowment, Args, Salt, RetType> - { + code_hash: H256, + ) -> CreateBuilder { CreateBuilder { - code_hash: Set(code_hash), + code_hash, limits: self.limits, endowment: self.endowment, exec_input: self.exec_input, @@ -559,76 +476,11 @@ where } } -impl - CreateBuilder< - E, - ContractRef, - CodeHash, - Set, - Endowment, - Args, - Salt, - RetType, - > +impl + CreateBuilder, Args, RetType> where E: Environment, { - /// Sets the maximum allowed gas costs for the contract instantiation. - #[inline] - pub fn gas_limit(self, gas_limit: u64) -> Self { - CreateBuilder { - limits: Set(LimitParamsV1 { gas_limit }), - ..self - } - } -} - -impl - CreateBuilder< - E, - ContractRef, - CodeHash, - Set>, - Endowment, - Args, - Salt, - RetType, - > -where - E: Environment, -{ - /// Switch to the original `instantiate` host function API, which only allows the - /// `gas_limit` limit parameter (equivalent to the `ref_time_limit` in the latest - /// `instantiate_v2`). - /// - /// This method instance is used to allow usage of the generated builder methods - /// for constructors which initialize the builder with the new [`LimitParamsV2`] type. - #[inline] - pub fn instantiate_v1( - self, - ) -> CreateBuilder< - E, - ContractRef, - CodeHash, - Set, - Endowment, - Args, - Salt, - RetType, - > { - CreateBuilder { - code_hash: self.code_hash, - limits: Set(LimitParamsV1 { - gas_limit: self.limits.value().ref_time_limit, - }), - endowment: self.endowment, - exec_input: self.exec_input, - salt: self.salt, - return_type: self.return_type, - _phantom: Default::default(), - } - } - /// Sets the `ref_time_limit` part of the weight limit for the contract instantiation. #[inline] pub fn ref_time_limit(self, ref_time_limit: u64) -> Self { @@ -656,7 +508,7 @@ where /// Sets the `storage_deposit_limit` for the contract instantiation. #[inline] - pub fn storage_deposit_limit(self, storage_deposit_limit: E::Balance) -> Self { + pub fn storage_deposit_limit(self, storage_deposit_limit: U256) -> Self { CreateBuilder { limits: Set(LimitParamsV2 { storage_deposit_limit: Some(storage_deposit_limit), @@ -667,17 +519,8 @@ where } } -impl - CreateBuilder< - E, - ContractRef, - CodeHash, - Limits, - Unset, - Args, - Salt, - RetType, - > +impl + CreateBuilder where E: Environment, { @@ -685,21 +528,12 @@ where #[inline] pub fn endowment( self, - endowment: E::Balance, - ) -> CreateBuilder< - E, - ContractRef, - CodeHash, - Limits, - Set, - Args, - Salt, - RetType, - > { + endowment: U256, + ) -> CreateBuilder { CreateBuilder { code_hash: self.code_hash, limits: self.limits, - endowment: Set(endowment), + endowment, exec_input: self.exec_input, salt: self.salt, return_type: self.return_type, @@ -708,15 +542,12 @@ where } } -impl +impl CreateBuilder< E, ContractRef, - CodeHash, Limits, - Endowment, Unset>, - Salt, RetType, > where @@ -727,16 +558,7 @@ where pub fn exec_input( self, exec_input: ExecutionInput, - ) -> CreateBuilder< - E, - ContractRef, - CodeHash, - Limits, - Endowment, - Set>, - Salt, - RetType, - > { + ) -> CreateBuilder>, RetType> { CreateBuilder { code_hash: self.code_hash, limits: self.limits, @@ -749,61 +571,31 @@ where } } -impl - CreateBuilder< - E, - ContractRef, - CodeHash, - Limits, - Endowment, - Args, - Unset, - RetType, - > +impl + CreateBuilder where E: Environment, { - /// Sets the value transferred upon the execution of the call. + /// Sets the salt used for the execution of the call. #[inline] - pub fn salt_bytes( + pub fn salt_bytes( self, - salt: Salt, - ) -> CreateBuilder< - E, - ContractRef, - CodeHash, - Limits, - Endowment, - Args, - Set, - RetType, - > - where - Salt: AsRef<[u8]>, - { + salt: Option<[u8; 32]>, + ) -> CreateBuilder { CreateBuilder { code_hash: self.code_hash, limits: self.limits, endowment: self.endowment, exec_input: self.exec_input, - salt: Set(salt), + salt, return_type: self.return_type, _phantom: Default::default(), } } } -impl - CreateBuilder< - E, - ContractRef, - CodeHash, - Limits, - Endowment, - Args, - Salt, - Unset>, - > +impl + CreateBuilder>> where E: Environment, { @@ -811,26 +603,17 @@ where /// /// # Note /// - /// Constructors are not able to return arbitrary values. Instead a successful call to - /// a constructor returns the address at which the contract was instantiated. + /// Constructors are not able to return arbitrary values. Instead, a successful call + /// to a constructor returns the address at which the contract was instantiated. /// - /// Therefore this must always be a reference (i.e `ContractRef`) to the contract + /// Therefore this must always be a reference (i.e. `ContractRef`) to the contract /// you're trying to instantiate. #[inline] pub fn returns( self, - ) -> CreateBuilder< - E, - ContractRef, - CodeHash, - Limits, - Endowment, - Args, - Salt, - Set>, - > + ) -> CreateBuilder>> where - ContractRef: FromAccountId, + ContractRef: FromAddr, R: ConstructorReturnType, { CreateBuilder { @@ -845,109 +628,51 @@ where } } -impl +impl CreateBuilder< E, ContractRef, - Set, Set, - Set, Set>, - Set, Set>, > where E: Environment, { - /// Finalizes the create builder, allowing it to instantiate a contract. + /// Finalizes the `CreateBuilder`, allowing it to instantiate a contract. #[inline] - pub fn params(self) -> CreateParams { + pub fn params(self) -> CreateParams { CreateParams { - code_hash: self.code_hash.value(), + code_hash: self.code_hash, limits: self.limits.value(), - endowment: self.endowment.value(), + endowment: self.endowment, exec_input: self.exec_input.value(), - salt_bytes: self.salt.value(), + salt_bytes: self.salt, _return_type: Default::default(), _phantom: Default::default(), } } } -impl +impl CreateBuilder< E, ContractRef, - Set, - Set>, - Set, + Set, Set>, - Set, Set>, > where E: Environment, - ContractRef: FromAccountId + crate::ContractReverseReference, + ContractRef: FromAddr + crate::ContractReverseReference, ::Type: crate::reflect::ContractConstructorDecoder, ::Type: crate::reflect::ContractMessageDecoder, Args: scale::Encode, - Salt: AsRef<[u8]>, - RetType: ConstructorReturnType, -{ - /// Instantiates the contract and returns its account ID back to the caller. - /// - /// # Panics - /// - /// This method panics if it encounters an [`ink::env::Error`][`crate::Error`] or an - /// [`ink::primitives::LangError`][`ink_primitives::LangError`]. If you want to handle - /// those use the [`try_instantiate`][`CreateBuilder::try_instantiate`] method - /// instead. - #[inline] - pub fn instantiate(self) -> >::Output { - self.params().instantiate() - } - - /// Instantiates the contract and returns its account ID back to the caller. - /// - /// # Note - /// - /// On failure this returns an outer [`ink::env::Error`][`crate::Error`] or inner - /// [`ink::primitives::LangError`][`ink_primitives::LangError`], both of which can be - /// handled by the caller. - #[inline] - pub fn try_instantiate( - self, - ) -> Result< - ink_primitives::ConstructorResult< - >::Output, - >, - Error, - > { - self.params().try_instantiate() - } -} - -#[cfg(not(feature = "revive"))] -impl - CreateBuilder< - E, - ContractRef, - Set, - Set, - Set, - Set>, - Set, - Set>, - > -where - E: Environment, - ContractRef: FromAccountId, - Args: scale::Encode, - Salt: AsRef<[u8]>, RetType: ConstructorReturnType, { + /// todo check comment /// Instantiates the contract and returns its account ID back to the caller. /// /// # Panics @@ -961,6 +686,7 @@ where self.params().instantiate() } + /// todo check comment /// Instantiates the contract and returns its account ID back to the caller. /// /// # Note diff --git a/crates/env/src/call/mod.rs b/crates/env/src/call/mod.rs index b3922cb8378..cb28951c255 100644 --- a/crates/env/src/call/mod.rs +++ b/crates/env/src/call/mod.rs @@ -39,11 +39,6 @@ pub mod utils { }; } -#[cfg(not(feature = "revive"))] -pub use self::{ - call_builder::CallV1, - create_builder::LimitParamsV1 -}; pub use self::{ call_builder::{ build_call, @@ -58,7 +53,7 @@ pub use self::{ ConstructorReturnType, CreateBuilder, CreateParams, - FromAccountId, + FromAddr, LimitParamsV2, }, execution::{ diff --git a/crates/env/src/engine/mod.rs b/crates/env/src/engine/mod.rs index cbd2d8457a0..a701e379030 100644 --- a/crates/env/src/engine/mod.rs +++ b/crates/env/src/engine/mod.rs @@ -19,7 +19,7 @@ use crate::{ }, call::{ ConstructorReturnType, - FromAccountId, + FromAddr, }, Error, Result as EnvResult, @@ -29,10 +29,6 @@ use ink_primitives::{ ConstructorResult, LangError, }; - -#[cfg(not(feature = "revive"))] -use pallet_contracts_uapi::ReturnErrorCode; -#[cfg(feature = "revive")] use pallet_revive_uapi::ReturnErrorCode; /// Convert a slice into an array reference. @@ -74,40 +70,37 @@ cfg_if! { // We only use this function when 1) compiling to Wasm 2) compiling for tests. #[cfg_attr(all(feature = "std", not(test)), allow(dead_code))] -pub(crate) fn decode_instantiate_result( +pub(crate) fn decode_instantiate_result( instantiate_result: EnvResult<()>, out_address: &mut I, out_return_value: &mut I, ) -> EnvResult>::Output>> where I: scale::Input, - E: crate::types::Environment, - ContractRef: FromAccountId, + ContractRef: FromAddr, R: ConstructorReturnType, { match instantiate_result { Ok(()) => { - let account_id = scale::Decode::decode(out_address)?; - let contract_ref = - >::from_account_id(account_id); + let addr = scale::Decode::decode(out_address)?; + let contract_ref = ::from_addr(addr); let output = >::ok(contract_ref); Ok(Ok(output)) } Err(Error::ReturnError(ReturnErrorCode::CalleeReverted)) => { - decode_instantiate_err::(out_return_value) + decode_instantiate_err::(out_return_value) } Err(actual_error) => Err(actual_error), } } #[cfg_attr(all(feature = "std", not(test)), allow(dead_code))] -fn decode_instantiate_err( +fn decode_instantiate_err( out_return_value: &mut I, ) -> EnvResult>::Output>> where I: scale::Input, - E: crate::types::Environment, - ContractRef: FromAccountId, + ContractRef: FromAddr, R: ConstructorReturnType, { let constructor_result_variant = out_return_value.read_byte()?; @@ -151,10 +144,8 @@ where #[cfg(test)] mod decode_instantiate_result_tests { use super::*; - use crate::{ - DefaultEnvironment, - Environment, - }; + use crate::DefaultEnvironment; + use ink_primitives::H160; use scale::Encode; // The `Result` type used to represent the programmer defined contract output. @@ -163,18 +154,17 @@ mod decode_instantiate_result_tests { #[derive(scale::Encode, scale::Decode)] struct ContractError(String); - type AccountId = ::AccountId; // The `allow(dead_code)` is for the `AccountId` in the struct. #[allow(dead_code)] - struct TestContractRef(AccountId); + struct TestContractRef(H160); impl crate::ContractEnv for TestContractRef { type Env = DefaultEnvironment; } - impl FromAccountId for TestContractRef { - fn from_account_id(account_id: AccountId) -> Self { - Self(account_id) + impl FromAddr for TestContractRef { + fn from_addr(addr: H160) -> Self { + Self(addr) } } @@ -195,7 +185,6 @@ mod decode_instantiate_result_tests { ) -> EnvResult>> { decode_instantiate_result::< I, - DefaultEnvironment, TestContractRef, Result, >( diff --git a/crates/env/src/engine/off_chain/impls.rs b/crates/env/src/engine/off_chain/impls.rs index f0a66f1196a..a55a3f7ee69 100644 --- a/crates/env/src/engine/off_chain/impls.rs +++ b/crates/env/src/engine/off_chain/impls.rs @@ -13,11 +13,6 @@ // limitations under the License. use super::EnvInstance; -#[cfg(not(feature = "revive"))] -use crate::call::{ - CallV1, - LimitParamsV1, -}; use crate::{ call::{ Call, @@ -25,7 +20,7 @@ use crate::{ ConstructorReturnType, CreateParams, DelegateCall, - FromAccountId, + FromAddr, LimitParamsV2, }, event::{ @@ -40,23 +35,23 @@ use crate::{ Keccak256, Sha2x256, }, + test::callee, Clear, EnvBackend, - types::Environment, Result, TypedEnvBackend, }; use ink_engine::ext::Engine; +use ink_primitives::{ + types::Environment, + H160, + H256, + U256, +}; use ink_storage_traits::{ decode_all, Storable, }; -#[cfg(not(feature = "revive"))] -use pallet_contracts_uapi::{ - ReturnErrorCode, - ReturnFlags, -}; -#[cfg(feature = "revive")] use pallet_revive_uapi::{ ReturnErrorCode, ReturnFlags, @@ -96,41 +91,65 @@ where crate::test::get_return_value() } -fn invoke_contract_impl( +fn invoke_contract_impl( env: &mut EnvInstance, _gas_limit: Option, _call_flags: u32, - _transferred_value: Option<&::Balance>, - callee_account: Option<&::AccountId>, - code_hash: Option<&::Hash>, + _transferred_value: Option<&U256>, + callee_account: H160, input: Vec, ) -> Result> where - E: Environment, R: scale::Decode, { - let mut callee_code_hash = match callee_account { - Some(ca) => env.code_hash::(ca)?, - None => *code_hash.unwrap(), - }; + let callee_code_hash = env.code_hash(&callee_account).unwrap_or_else(|err| { + panic!( + "failed getting code hash for {:?}: {:?}", + callee_account, err + ) + }); let handler = env .engine .database - .get_contract_message_handler(callee_code_hash.as_mut()); + .get_contract_message_handler(&callee_code_hash); let old_callee = env.engine.get_callee(); - let mut restore_callee = false; - if let Some(callee_account) = callee_account { - let encoded_callee = scale::Encode::encode(callee_account); - env.engine.set_callee(encoded_callee); - restore_callee = true; - } + env.engine.set_callee(callee_account); let result = handler(input); - if restore_callee { - env.engine.set_callee(old_callee); - } + env.engine.set_callee(old_callee); + + let result = + as scale::Decode>::decode(&mut &result[..]) + .expect("failed to decode return value"); + + Ok(result) +} + +fn invoke_contract_impl_delegate( + env: &mut EnvInstance, + _gas_limit: Option, + _call_flags: u32, + _transferred_value: Option<&U256>, + callee_account: H160, + input: Vec, +) -> Result> +where + R: scale::Decode, +{ + let callee_code_hash = env.code_hash(&callee_account).unwrap_or_else(|err| { + panic!( + "failed getting code hash for {:?}: {:?}", + callee_account, err + ) + }); + + let handler = env + .engine + .database + .get_contract_message_handler(&callee_code_hash); + let result = handler(input); let result = as scale::Decode>::decode(&mut &result[..]) @@ -198,12 +217,11 @@ where { type Output = Vec; - fn expect(&mut self, _expected_topics: usize) {} - fn push_topic(&mut self, topic_value: &T) where T: scale::Encode, { + // todo let encoded = topic_value.encode(); let len_encoded = encoded.len(); let mut result = ::Hash::CLEAR_HASH; @@ -252,13 +270,13 @@ impl EnvInstance { self.engine.get_storage(&[255_u8; 32]).unwrap().to_vec() } - pub fn upload_code(&mut self) -> ink_primitives::types::Hash + pub fn upload_code(&mut self) -> H256 where ContractRef: crate::ContractReverseReference, ::Type: crate::reflect::ContractMessageDecoder, { - ink_primitives::types::Hash::from( + H256::from( self.engine .database .set_contract_message_handler(execute_contract_call::), @@ -328,15 +346,15 @@ impl EnvBackend for EnvInstance { unimplemented!("the off-chain env does not implement `input`") } - #[cfg(not(feature = "test_instantiate"))] + #[cfg(not(feature = "std"))] fn return_value(&mut self, _flags: ReturnFlags, _return_value: &R) -> ! where R: scale::Encode, { - panic!("enable feature test_instantiate to use return_value()") + panic!("enable feature `std` to use `return_value()`") } - #[cfg(feature = "test_instantiate")] + #[cfg(feature = "std")] fn return_value(&mut self, _flags: ReturnFlags, return_value: &R) where R: scale::Encode, @@ -366,6 +384,7 @@ impl EnvBackend for EnvInstance { ::hash(enc_input, output) } + #[allow(clippy::arithmetic_side_effects)] // todo fn ecdsa_recover( &mut self, signature: &[u8; 65], @@ -473,7 +492,7 @@ impl EnvBackend for EnvInstance { Ok(decoded) } - fn set_code_hash(&mut self, code_hash: &[u8]) -> Result<()> { + fn set_code_hash(&mut self, code_hash: &H256) -> Result<()> { self.engine .database .set_code_hash(&self.engine.get_callee(), code_hash); @@ -482,26 +501,18 @@ impl EnvBackend for EnvInstance { } impl TypedEnvBackend for EnvInstance { - fn caller(&mut self) -> E::AccountId { - self.get_property::(Engine::caller) + fn caller(&mut self) -> H160 { + self.get_property::(Engine::caller) .unwrap_or_else(|error| panic!("could not read `caller` property: {error:?}")) } - fn transferred_value(&mut self) -> E::Balance { - self.get_property::(Engine::value_transferred) + fn transferred_value(&mut self) -> U256 { + self.get_property(Engine::value_transferred) .unwrap_or_else(|error| { panic!("could not read `transferred_value` property: {error:?}") }) } - #[cfg(not(feature = "revive"))] - fn gas_left(&mut self) -> u64 { - self.get_property::(Engine::gas_left) - .unwrap_or_else(|error| { - panic!("could not read `gas_left` property: {error:?}") - }) - } - fn block_timestamp(&mut self) -> E::Timestamp { self.get_property::(Engine::block_timestamp) .unwrap_or_else(|error| { @@ -510,14 +521,22 @@ impl TypedEnvBackend for EnvInstance { } fn account_id(&mut self) -> E::AccountId { + // todo should not use `Engine::account_id` self.get_property::(Engine::address) .unwrap_or_else(|error| { panic!("could not read `account_id` property: {error:?}") }) } - fn balance(&mut self) -> E::Balance { - self.get_property::(Engine::balance) + fn address(&mut self) -> H160 { + self.get_property::(Engine::address) + .unwrap_or_else(|error| { + panic!("could not read `account_id` property: {error:?}") + }) + } + + fn balance(&mut self) -> U256 { + self.get_property::(Engine::balance) .unwrap_or_else(|error| { panic!("could not read `balance` property: {error:?}") }) @@ -548,22 +567,9 @@ impl TypedEnvBackend for EnvInstance { self.engine.deposit_event(&enc_topics[..], enc_data); } - #[cfg(not(feature = "revive"))] - fn invoke_contract_v1( - &mut self, - _params: &CallParams, Args, R>, - ) -> Result> - where - E: Environment, - Args: scale::Encode, - R: scale::Decode, - { - unimplemented!("off-chain environment does not support contract invocation") - } - fn invoke_contract( &mut self, - params: &CallParams, Args, R>, + params: &CallParams, ) -> Result> where E: Environment, @@ -576,45 +582,43 @@ impl TypedEnvBackend for EnvInstance { let callee_account = params.callee(); let input = scale::Encode::encode(input); - invoke_contract_impl::( + invoke_contract_impl::( self, None, call_flags, Some(transferred_value), - Some(callee_account), - None, + *callee_account, // todo possibly return no reference from callee() input, ) } fn invoke_contract_delegate( &mut self, - params: &CallParams, Args, R>, + params: &CallParams, ) -> Result> where E: Environment, Args: scale::Encode, R: scale::Decode, { + let _addr = params.address(); let call_flags = params.call_flags().bits(); let input = params.exec_input(); - let code_hash = params.code_hash(); let input = scale::Encode::encode(input); - invoke_contract_impl::( + invoke_contract_impl_delegate::( self, None, call_flags, None, - None, - Some(code_hash), + *params.address(), input, ) } - fn instantiate_contract( + fn instantiate_contract( &mut self, - params: &CreateParams, Args, Salt, R>, + params: &CreateParams, ) -> Result< ink_primitives::ConstructorResult< >::Output, @@ -622,45 +626,40 @@ impl TypedEnvBackend for EnvInstance { > where E: Environment, - ContractRef: FromAccountId + crate::ContractReverseReference, + ContractRef: FromAddr + crate::ContractReverseReference, ::Type: crate::reflect::ContractConstructorDecoder, Args: scale::Encode, - Salt: AsRef<[u8]>, R: ConstructorReturnType, { let endowment = params.endowment(); - let endowment = scale::Encode::encode(endowment); - let endowment: u128 = scale::Decode::decode(&mut &endowment[..])?; - let salt_bytes = params.salt_bytes(); - let code_hash = params.code_hash(); - let code_hash = scale::Encode::encode(code_hash); let input = params.exec_input(); let input = scale::Encode::encode(input); - // Compute account for instantiated contract. - let account_id_vec = { + // Compute address for instantiated contract. + let addr_id_vec = { let mut account_input = Vec::::new(); - account_input.extend(&b"contract_addr_v1".to_vec()); - if let Some(caller) = &self.engine.exec_context.caller { - scale::Encode::encode_to(&caller.as_bytes(), &mut account_input); - } - account_input.extend(&code_hash); + account_input.extend(&b"contract_addr".to_vec()); + scale::Encode::encode_to( + &self.engine.exec_context.caller.as_bytes(), + &mut account_input, + ); + account_input.extend(&code_hash.0); account_input.extend(&input); - account_input.extend(salt_bytes.as_ref()); + if let Some(salt) = salt_bytes { + account_input.extend(salt); + } let mut account_id = [0_u8; 32]; ink_engine::hashing::blake2b_256(&account_input[..], &mut account_id); account_id.to_vec() }; - - let mut account_id = - ::AccountId::decode(&mut &account_id_vec[..]).unwrap(); + let contract_addr = H160::from_slice(&addr_id_vec[..20]); let old_callee = self.engine.get_callee(); - self.engine.set_callee(account_id_vec.clone()); + self.engine.set_callee(contract_addr); let dispatch = < < @@ -676,59 +675,32 @@ impl TypedEnvBackend for EnvInstance { crate::reflect::ExecuteDispatchable::execute_dispatchable(dispatch) .unwrap_or_else(|e| panic!("Constructor call failed: {:?}", e)); - self.set_code_hash(code_hash.as_slice())?; - self.engine.set_contract(account_id_vec.clone()); + self.set_code_hash(code_hash)?; + self.engine.set_contract(callee()); self.engine .database - .set_balance(account_id.as_mut(), endowment); + // todo passing the types instead of refs would be better + .set_balance(&callee(), *endowment); + // todo why? self.engine.set_callee(old_callee); - Ok(Ok(R::ok( - >::from_account_id(account_id), - ))) + Ok(Ok(R::ok(::from_addr( + contract_addr, + )))) } - #[cfg(not(feature = "revive"))] - fn instantiate_contract_v1( - &mut self, - params: &CreateParams, - ) -> Result< - ink_primitives::ConstructorResult< - >::Output, - >, - > - where - E: Environment, - ContractRef: FromAccountId, - Args: scale::Encode, - Salt: AsRef<[u8]>, - R: ConstructorReturnType, - { - let _code_hash = params.code_hash(); - let _ref_time_limit = params.gas_limit(); - let _endowment = params.endowment(); - let _input = params.exec_input(); - let _salt_bytes = params.salt_bytes(); - unimplemented!("off-chain environment does not support contract instantiation") - } - - fn terminate_contract(&mut self, beneficiary: E::AccountId) -> ! - where - E: Environment, - { - let buffer = scale::Encode::encode(&beneficiary); - self.engine.terminate(&buffer[..]) + fn terminate_contract(&mut self, beneficiary: H160) -> ! { + self.engine.terminate(beneficiary) } - fn transfer(&mut self, destination: E::AccountId, value: E::Balance) -> Result<()> + fn transfer(&mut self, destination: H160, value: U256) -> Result<()> where E: Environment, { - let enc_destination = &scale::Encode::encode(&destination)[..]; let enc_value = &scale::Encode::encode(&value)[..]; self.engine - .transfer(enc_destination, enc_value) + .transfer(destination, enc_value) .map_err(Into::into) } @@ -740,11 +712,8 @@ impl TypedEnvBackend for EnvInstance { }) } - fn is_contract(&mut self, account: &E::AccountId) -> bool - where - E: Environment, - { - self.engine.is_contract(scale::Encode::encode(&account)) + fn is_contract(&mut self, account: &H160) -> bool { + self.engine.is_contract(account) } fn caller_is_origin(&mut self) -> bool @@ -761,32 +730,21 @@ impl TypedEnvBackend for EnvInstance { unimplemented!("off-chain environment does not support `caller_is_root`") } - fn code_hash(&mut self, account: &E::AccountId) -> Result - where - E: Environment, - { - let code_hash = self - .engine - .database - .get_code_hash(&scale::Encode::encode(&account)); + fn code_hash(&mut self, addr: &H160) -> Result { + let code_hash = self.engine.database.get_code_hash(addr); if let Some(code_hash) = code_hash { - let code_hash = - ::Hash::decode(&mut &code_hash[..]).unwrap(); + // todo + let code_hash = H256::decode(&mut &code_hash[..]).unwrap(); Ok(code_hash) } else { Err(ReturnErrorCode::KeyNotFound.into()) } } - fn own_code_hash(&mut self) -> Result - where - E: Environment, - { + fn own_code_hash(&mut self) -> Result { let callee = &self.engine.get_callee(); let code_hash = self.engine.database.get_code_hash(callee); if let Some(code_hash) = code_hash { - let code_hash = - ::Hash::decode(&mut &code_hash[..]).unwrap(); Ok(code_hash) } else { Err(ReturnErrorCode::KeyNotFound.into()) @@ -800,7 +758,7 @@ impl TypedEnvBackend for EnvInstance { unimplemented!("off-chain environment does not support `call_runtime`") } - fn lock_delegate_dependency(&mut self, _code_hash: &E::Hash) + fn lock_delegate_dependency(&mut self, _code_hash: &H256) where E: Environment, { @@ -825,7 +783,7 @@ impl TypedEnvBackend for EnvInstance { unimplemented!("off-chain environment does not support `xcm_send`") } - fn unlock_delegate_dependency(&mut self, _code_hash: &E::Hash) + fn unlock_delegate_dependency(&mut self, _code_hash: &H256) where E: Environment, { diff --git a/crates/env/src/engine/off_chain/mod.rs b/crates/env/src/engine/off_chain/mod.rs index 8c5914f4566..6a8ea5e81ca 100644 --- a/crates/env/src/engine/off_chain/mod.rs +++ b/crates/env/src/engine/off_chain/mod.rs @@ -25,6 +25,10 @@ use crate::Error; use derive_more::From; use ink_engine::ext::Engine; +use ink_primitives::{ + AccountId, + H160, +}; /// The off-chain environment. pub struct EnvInstance { @@ -66,6 +70,7 @@ pub enum OffChainError { UnregisteredChainExtension, } +// todo rename /// Errors encountered upon interacting with the accounts database. #[derive(Debug, From, PartialEq, Eq)] pub enum AccountError { @@ -73,5 +78,6 @@ pub enum AccountError { #[from(ignore)] UnexpectedUserAccount, #[from(ignore)] - NoAccountForId(Vec), + NoAccountForId(AccountId), + NoContractForId(H160), } diff --git a/crates/env/src/engine/off_chain/test_api.rs b/crates/env/src/engine/off_chain/test_api.rs index 238c0c2b727..7829b2afedd 100644 --- a/crates/env/src/engine/off_chain/test_api.rs +++ b/crates/env/src/engine/off_chain/test_api.rs @@ -31,6 +31,11 @@ pub use ink_engine::{ ext::ChainSpec, ChainExtension, }; +use ink_primitives::{ + H160, + H256, + U256, +}; /// Record for an emitted event. #[derive(Clone)] @@ -57,12 +62,9 @@ pub struct EmittedEvent { /// - If the underlying `account` type does not match. /// - If the underlying `new_balance` type does not match. /// - If the `new_balance` is less than the existential minimum. -pub fn set_account_balance(account_id: T::AccountId, new_balance: T::Balance) -where - T: Environment, // Just temporary for the MVP! -{ +pub fn set_account_balance(addr: H160, new_balance: U256) { let min = ChainSpec::default().minimum_balance; - if new_balance < min && new_balance != 0u128 { + if new_balance < min && new_balance != U256::zero() { panic!( "Balance must be at least [{}]. Use 0 as balance to reap the account.", min @@ -70,9 +72,7 @@ where } ::on_instance(|instance| { - instance - .engine - .set_balance(scale::Encode::encode(&account_id), new_balance); + instance.engine.set_balance(addr, new_balance); }) } @@ -88,15 +88,9 @@ where /// /// - If `account` does not exist. /// - If the underlying `account` type does not match. -pub fn get_account_balance(account_id: T::AccountId) -> Result -where - T: Environment, // Just temporary for the MVP! -{ +pub fn get_account_balance(addr: H160) -> Result { ::on_instance(|instance| { - instance - .engine - .get_balance(scale::Encode::encode(&account_id)) - .map_err(Into::into) + instance.engine.get_balance(addr).map_err(Into::into) }) } @@ -144,60 +138,37 @@ where } /// Sets a caller for the next call. -pub fn set_caller(caller: T::AccountId) -where - T: Environment, - ::AccountId: From<[u8; 32]>, -{ +pub fn set_caller(caller: H160) { ::on_instance(|instance| { - instance.engine.set_caller(scale::Encode::encode(&caller)); + instance.engine.set_caller(caller); }) } /// Sets the callee for the next call. -pub fn set_callee(callee: T::AccountId) -where - T: Environment, - ::AccountId: From<[u8; 32]>, -{ +pub fn set_callee(callee: H160) { ::on_instance(|instance| { - instance.engine.set_callee(scale::Encode::encode(&callee)); + instance.engine.set_callee(callee); }) } /// Sets an account as a contract -pub fn set_contract(contract: T::AccountId) -where - T: Environment, - ::AccountId: From<[u8; 32]>, -{ +pub fn set_contract(contract: H160) { ::on_instance(|instance| { - instance - .engine - .set_contract(scale::Encode::encode(&contract)); + instance.engine.set_contract(contract); }) } /// Returns a boolean to indicate whether an account is a contract -pub fn is_contract(contract: T::AccountId) -> bool -where - T: Environment, - ::AccountId: From<[u8; 32]>, -{ +pub fn is_contract(contract: H160) -> bool { ::on_instance(|instance| { - instance - .engine - .is_contract(scale::Encode::encode(&contract)) + instance.engine.is_contract(&contract) }) } /// Gets the currently set callee. /// -/// This is account id of the currently executing contract. -pub fn callee() -> T::AccountId -where - T: Environment, -{ +/// This is the address of the currently executing contract. +pub fn callee() -> H160 { ::on_instance(|instance| { let callee = instance.engine.get_callee(); scale::Decode::decode(&mut &callee[..]) @@ -206,14 +177,9 @@ where } /// Returns the total number of reads and writes of the contract's storage. -pub fn get_contract_storage_rw(account_id: &T::AccountId) -> (usize, usize) -where - T: Environment, -{ +pub fn get_contract_storage_rw(addr: H160) -> (usize, usize) { ::on_instance(|instance| { - instance - .engine - .get_contract_storage_rw(scale::Encode::encode(&account_id)) + instance.engine.get_contract_storage_rw(addr) }) } @@ -221,10 +187,7 @@ where /// /// Please note that the acting accounts should be set with [`set_caller()`] and /// [`set_callee()`] beforehand. -pub fn set_value_transferred(value: T::Balance) -where - T: Environment, // Just temporary for the MVP! -{ +pub fn set_value_transferred(value: U256) { ::on_instance(|instance| { instance.engine.set_value_transferred(value); }) @@ -234,30 +197,16 @@ where /// /// Please note that the acting accounts should be set with [`set_caller()`] and /// [`set_callee()`] beforehand. -pub fn transfer_in(value: T::Balance) -where - T: Environment, // Just temporary for the MVP! -{ +#[allow(clippy::arithmetic_side_effects)] // todo +pub fn transfer_in(value: U256) { ::on_instance(|instance| { - let caller = instance - .engine - .exec_context - .caller - .as_ref() - .expect("no caller has been set") - .as_bytes() - .to_vec(); - - let caller_old_balance = instance - .engine - .get_balance(caller.clone()) - .unwrap_or_default(); + let caller = instance.engine.exec_context.caller; + + let caller_old_balance = instance.engine.get_balance(caller).unwrap_or_default(); let callee = instance.engine.get_callee(); - let contract_old_balance = instance - .engine - .get_balance(callee.clone()) - .unwrap_or_default(); + let contract_old_balance = + instance.engine.get_balance(callee).unwrap_or_default(); instance .engine @@ -269,17 +218,17 @@ where }); } -/// Returns the amount of storage cells used by the account `account_id`. +/// Returns the amount of storage cells used by the contract `addr`. /// -/// Returns `None` if the `account_id` is non-existent. -pub fn count_used_storage_cells(account_id: &T::AccountId) -> Result +/// Returns `None` if the contract at `addr` is non-existent. +pub fn count_used_storage_cells(addr: H160) -> Result where T: Environment, { ::on_instance(|instance| { instance .engine - .count_used_storage_cells(&scale::Encode::encode(&account_id)) + .count_used_storage_cells(&addr) .map_err(Into::into) }) } @@ -309,74 +258,60 @@ where pub fn run_test(f: F) -> Result<()> where T: Environment, - F: FnOnce(DefaultAccounts) -> Result<()>, - ::AccountId: From<[u8; 32]>, + F: FnOnce(DefaultAccounts) -> Result<()>, { - let default_accounts = default_accounts::(); + let default_accounts = default_accounts(); ::on_instance(|instance| { instance.engine.initialize_or_reset(); - let encoded_alice = scale::Encode::encode(&default_accounts.alice); - instance.engine.set_caller(encoded_alice.clone()); - instance.engine.set_callee(encoded_alice.clone()); + let alice = default_accounts.alice; + // instance.engine.set_caller(alice.clone()); // todo + instance.engine.set_callee(alice); // set up the funds for the default accounts - let substantial = 1_000_000; - let some = 1_000; - instance.engine.set_balance(encoded_alice, substantial); + let substantial = 1_000_000.into(); + let some = 1_000.into(); + instance.engine.set_balance(alice, substantial); + instance.engine.set_balance(default_accounts.bob, some); + instance.engine.set_balance(default_accounts.charlie, some); instance .engine - .set_balance(scale::Encode::encode(&default_accounts.bob), some); + .set_balance(default_accounts.django, 0.into()); + instance.engine.set_balance(default_accounts.eve, 0.into()); instance .engine - .set_balance(scale::Encode::encode(&default_accounts.charlie), some); - instance - .engine - .set_balance(scale::Encode::encode(&default_accounts.django), 0); - instance - .engine - .set_balance(scale::Encode::encode(&default_accounts.eve), 0); - instance - .engine - .set_balance(scale::Encode::encode(&default_accounts.frank), 0); + .set_balance(default_accounts.frank, 0.into()); }); f(default_accounts) } /// Returns the default accounts for testing purposes: /// Alice, Bob, Charlie, Django, Eve and Frank. -pub fn default_accounts() -> DefaultAccounts -where - T: Environment, - ::AccountId: From<[u8; 32]>, -{ +pub fn default_accounts() -> DefaultAccounts { DefaultAccounts { - alice: T::AccountId::from([0x01; 32]), - bob: T::AccountId::from([0x02; 32]), - charlie: T::AccountId::from([0x03; 32]), - django: T::AccountId::from([0x04; 32]), - eve: T::AccountId::from([0x05; 32]), - frank: T::AccountId::from([0x06; 32]), + alice: H160::from([0x01; 20]), + bob: H160::from([0x02; 20]), + charlie: H160::from([0x03; 20]), + django: H160::from([0x04; 20]), + eve: H160::from([0x05; 20]), + frank: H160::from([0x06; 20]), } } /// The default accounts. -pub struct DefaultAccounts -where - T: Environment, -{ +pub struct DefaultAccounts { /// The predefined `ALICE` account holding substantial amounts of value. - pub alice: T::AccountId, + pub alice: H160, /// The predefined `BOB` account holding some amounts of value. - pub bob: T::AccountId, + pub bob: H160, /// The predefined `CHARLIE` account holding some amounts of value. - pub charlie: T::AccountId, + pub charlie: H160, /// The predefined `DJANGO` account holding no value. - pub django: T::AccountId, + pub django: H160, /// The predefined `EVE` account holding no value. - pub eve: T::AccountId, + pub eve: H160, /// The predefined `FRANK` account holding no value. - pub frank: T::AccountId, + pub frank: H160, } /// Returns the recorded emitted events in order. @@ -415,8 +350,8 @@ pub fn recorded_events() -> impl Iterator { /// example for a complete usage exemplification. pub fn assert_contract_termination( should_terminate: F, - expected_beneficiary: T::AccountId, - expected_value_transferred_to_beneficiary: T::Balance, + expected_beneficiary: H160, + expected_value_transferred_to_beneficiary: U256, ) where T: Environment, F: FnMut() + UnwindSafe, @@ -428,12 +363,9 @@ pub fn assert_contract_termination( let encoded_input = value_any .downcast_ref::>() .expect("panic object can not be cast"); - let (value_transferred, encoded_beneficiary): (T::Balance, Vec) = + let (value_transferred, beneficiary): (U256, H160) = scale::Decode::decode(&mut &encoded_input[..]) .unwrap_or_else(|err| panic!("input can not be decoded: {err}")); - let beneficiary = - ::decode(&mut &encoded_beneficiary[..]) - .unwrap_or_else(|err| panic!("input can not be decoded: {err}")); assert_eq!(value_transferred, expected_value_transferred_to_beneficiary); assert_eq!(beneficiary, expected_beneficiary); } @@ -443,18 +375,18 @@ pub fn assert_contract_termination( #[macro_export] macro_rules! pay_with_call { ($contract:ident . $message:ident ( $( $params:expr ),* ) , $amount:expr) => {{ - $crate::test::transfer_in::($amount); + $crate::test::transfer_in($amount); $contract.$message($ ($params) ,*) }} } -/// Retrieves the value stored by return_value(). +/// Retrieves the value stored by `return_value()`. pub fn get_return_value() -> Vec { ::on_instance(|instance| instance.get_return_value()) } /// Gets a pseudo code hash for a contract ref. -pub fn upload_code() -> ink_primitives::types::Hash +pub fn upload_code() -> H256 where E: Environment, ContractRef: crate::ContractReverseReference, diff --git a/crates/env/src/engine/off_chain/tests.rs b/crates/env/src/engine/off_chain/tests.rs index 9b9848576cc..ec78c25f036 100644 --- a/crates/env/src/engine/off_chain/tests.rs +++ b/crates/env/src/engine/off_chain/tests.rs @@ -18,10 +18,13 @@ use crate::{ test_api::set_account_balance, }, event::TopicsBuilderBackend, - types::Environment, DefaultEnvironment, Result, }; +use ink::{ + H160, + U256, +}; #[test] fn topics_builder() -> Result<()> { @@ -46,6 +49,7 @@ fn topics_builder() -> Result<()> { Ok(()) }) } + #[test] fn test_set_account_balance() -> Result<()> { pub use ink_engine::ext::ChainSpec; @@ -54,23 +58,14 @@ fn test_set_account_balance() -> Result<()> { let minimum_balance = ChainSpec::default().minimum_balance; let result = std::panic::catch_unwind(|| { - set_account_balance::( - ::AccountId::from([0x1; 32]), - ::Balance::from(minimum_balance - 1), - ) + set_account_balance(H160::from([0x1; 20]), minimum_balance - 1) }); assert!(result.is_err()); - set_account_balance::( - ::AccountId::from([0x1; 32]), - ::Balance::from(0u128), - ); + set_account_balance(H160::from([0x1; 20]), U256::zero()); - set_account_balance::( - ::AccountId::from([0x1; 32]), - ::Balance::from(minimum_balance + 1), - ); + set_account_balance(H160::from([0x1; 20]), minimum_balance + 1); Ok(()) }) diff --git a/crates/env/src/engine/off_chain/types.rs b/crates/env/src/engine/off_chain/types.rs index 0fcbba3459e..b5d240165fd 100644 --- a/crates/env/src/engine/off_chain/types.rs +++ b/crates/env/src/engine/off_chain/types.rs @@ -57,6 +57,9 @@ impl From for AccountError { ink_engine::AccountError::NoAccountForId(acc) => { AccountError::NoAccountForId(acc) } + ink_engine::AccountError::NoContractForId(addr) => { + AccountError::NoContractForId(addr) + } } } } diff --git a/crates/env/src/engine/on_chain/buffer.rs b/crates/env/src/engine/on_chain/buffer.rs index 69875522140..b9444c05e82 100644 --- a/crates/env/src/engine/on_chain/buffer.rs +++ b/crates/env/src/engine/on_chain/buffer.rs @@ -79,7 +79,7 @@ impl<'a> EncodeScope<'a> { } } -impl<'a> scale::Output for EncodeScope<'a> { +impl scale::Output for EncodeScope<'_> { fn write(&mut self, bytes: &[u8]) { debug_assert!( self.len().checked_add(bytes.len()).unwrap() <= self.capacity(), diff --git a/crates/env/src/engine/on_chain/impls/mod.rs b/crates/env/src/engine/on_chain/impls/mod.rs deleted file mode 100644 index 56a0bd1c4a9..00000000000 --- a/crates/env/src/engine/on_chain/impls/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -#[cfg(target_arch = "wasm32")] -mod pallet_contracts; - -#[cfg(target_arch = "riscv32")] -mod pallet_revive; diff --git a/crates/env/src/engine/on_chain/impls/pallet_contracts.rs b/crates/env/src/engine/on_chain/impls/pallet_contracts.rs deleted file mode 100644 index dac1126f814..00000000000 --- a/crates/env/src/engine/on_chain/impls/pallet_contracts.rs +++ /dev/null @@ -1,782 +0,0 @@ -// Copyright (C) Use Ink (UK) Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::{ - call::{ - Call, - CallParams, - CallV1, - ConstructorReturnType, - CreateParams, - DelegateCall, - FromAccountId, - LimitParamsV1, - LimitParamsV2, - }, - engine::{ - on_chain::{ - EncodeScope, - ScopedBuffer, - }, - EnvInstance, - }, - event::{ - Event, - TopicsBuilderBackend, - }, - hash::{ - Blake2x128, - Blake2x256, - CryptoHash, - HashOutput, - Keccak256, - Sha2x256, - }, - Clear, - EnvBackend, - Environment, - types::FromLittleEndian, - Result, - TypedEnvBackend, -}; -use ink_storage_traits::{ - decode_all, - Storable, -}; -use pallet_contracts_uapi::{ - CallFlags, - HostFn, - HostFnImpl as ext, - ReturnErrorCode, - ReturnFlags, -}; -use xcm::VersionedXcm; - -impl CryptoHash for Blake2x128 { - fn hash(input: &[u8], output: &mut ::Type) { - type OutputType = [u8; 16]; - static_assertions::assert_type_eq_all!( - ::Type, - OutputType - ); - let output: &mut OutputType = array_mut_ref!(output, 0, 16); - ext::hash_blake2_128(input, output); - } -} - -impl CryptoHash for Blake2x256 { - fn hash(input: &[u8], output: &mut ::Type) { - type OutputType = [u8; 32]; - static_assertions::assert_type_eq_all!( - ::Type, - OutputType - ); - let output: &mut OutputType = array_mut_ref!(output, 0, 32); - ext::hash_blake2_256(input, output); - } -} - -impl CryptoHash for Sha2x256 { - fn hash(input: &[u8], output: &mut ::Type) { - type OutputType = [u8; 32]; - static_assertions::assert_type_eq_all!( - ::Type, - OutputType - ); - let output: &mut OutputType = array_mut_ref!(output, 0, 32); - ext::hash_sha2_256(input, output); - } -} - -impl CryptoHash for Keccak256 { - fn hash(input: &[u8], output: &mut ::Type) { - type OutputType = [u8; 32]; - static_assertions::assert_type_eq_all!( - ::Type, - OutputType - ); - let output: &mut OutputType = array_mut_ref!(output, 0, 32); - ext::hash_keccak_256(input, output); - } -} - -pub struct TopicsBuilder<'a, E> { - scoped_buffer: ScopedBuffer<'a>, - marker: core::marker::PhantomData E>, -} - -impl<'a, E> From> for TopicsBuilder<'a, E> -where - E: Environment, -{ - fn from(scoped_buffer: ScopedBuffer<'a>) -> Self { - Self { - scoped_buffer, - marker: Default::default(), - } - } -} - -impl<'a, E> TopicsBuilderBackend for TopicsBuilder<'a, E> -where - E: Environment, -{ - type Output = (ScopedBuffer<'a>, &'a mut [u8]); - - fn expect(&mut self, expected_topics: usize) { - self.scoped_buffer - .append_encoded(&scale::Compact(expected_topics as u32)); - } - - fn push_topic(&mut self, topic_value: &T) - where - T: scale::Encode, - { - fn inner(encoded: &mut [u8]) -> ::Hash { - let len_encoded = encoded.len(); - let mut result = ::Hash::CLEAR_HASH; - let len_result = result.as_ref().len(); - if len_encoded <= len_result { - result.as_mut()[..len_encoded].copy_from_slice(encoded); - } else { - let mut hash_output = ::Type::default(); - ::hash(encoded, &mut hash_output); - let copy_len = core::cmp::min(hash_output.len(), len_result); - result.as_mut()[0..copy_len].copy_from_slice(&hash_output[0..copy_len]); - } - result - } - - let mut split = self.scoped_buffer.split(); - let encoded = split.take_encoded(topic_value); - let result = inner::(encoded); - self.scoped_buffer.append_encoded(&result); - } - - fn output(mut self) -> Self::Output { - let encoded_topics = self.scoped_buffer.take_appended(); - (self.scoped_buffer, encoded_topics) - } -} - -impl EnvInstance { - #[inline(always)] - /// Returns a new scoped buffer for the entire scope of the static 16 kB buffer. - fn scoped_buffer(&mut self) -> ScopedBuffer { - ScopedBuffer::from(&mut self.buffer[..]) - } - - /// Returns the contract property value from its little-endian representation. - /// - /// # Note - /// - /// This skips the potentially costly decoding step that is often equivalent to a - /// `memcpy`. - #[inline(always)] - fn get_property_little_endian(&mut self, ext_fn: fn(output: &mut &mut [u8])) -> T - where - T: FromLittleEndian, - { - let mut result = ::Bytes::default(); - ext_fn(&mut result.as_mut()); - ::from_le_bytes(result) - } - - /// Returns the contract property value. - #[inline(always)] - fn get_property(&mut self, ext_fn: fn(output: &mut &mut [u8])) -> Result - where - T: scale::Decode, - { - let full_scope = &mut self.scoped_buffer().take_rest(); - ext_fn(full_scope); - scale::Decode::decode(&mut &full_scope[..]).map_err(Into::into) - } -} - -impl EnvBackend for EnvInstance { - fn set_contract_storage(&mut self, key: &K, value: &V) -> Option - where - K: scale::Encode, - V: Storable, - { - let mut buffer = self.scoped_buffer(); - let key = buffer.take_encoded(key); - let value = buffer.take_storable_encoded(value); - ext::set_storage_v2(key, value) - } - - fn get_contract_storage(&mut self, key: &K) -> Result> - where - K: scale::Encode, - R: Storable, - { - let mut buffer = self.scoped_buffer(); - let key = buffer.take_encoded(key); - let output = &mut buffer.take_rest(); - match ext::get_storage_v1(key, output) { - Ok(_) => (), - Err(ReturnErrorCode::KeyNotFound) => return Ok(None), - Err(_) => panic!("encountered unexpected error"), - } - let decoded = decode_all(&mut &output[..])?; - Ok(Some(decoded)) - } - - fn take_contract_storage(&mut self, key: &K) -> Result> - where - K: scale::Encode, - R: Storable, - { - let mut buffer = self.scoped_buffer(); - let key = buffer.take_encoded(key); - let output = &mut buffer.take_rest(); - match ext::take_storage(key, output) { - Ok(_) => (), - Err(ReturnErrorCode::KeyNotFound) => return Ok(None), - Err(_) => panic!("encountered unexpected error"), - } - let decoded = decode_all(&mut &output[..])?; - Ok(Some(decoded)) - } - - fn contains_contract_storage(&mut self, key: &K) -> Option - where - K: scale::Encode, - { - let mut buffer = self.scoped_buffer(); - let key = buffer.take_encoded(key); - ext::contains_storage_v1(key) - } - - fn clear_contract_storage(&mut self, key: &K) -> Option - where - K: scale::Encode, - { - let mut buffer = self.scoped_buffer(); - let key = buffer.take_encoded(key); - ext::clear_storage_v1(key) - } - - fn decode_input(&mut self) -> Result - where - T: scale::Decode, - { - self.get_property::(ext::input) - } - - fn return_value(&mut self, flags: ReturnFlags, return_value: &R) -> ! - where - R: scale::Encode, - { - let mut scope = EncodeScope::from(&mut self.buffer[..]); - return_value.encode_to(&mut scope); - let len = scope.len(); - ext::return_value(flags, &self.buffer[..][..len]); - } - - #[cfg(not(feature = "ink-debug"))] - /// A no-op. Enable the `ink-debug` feature for debug messages. - fn debug_message(&mut self, _content: &str) {} - - #[cfg(feature = "ink-debug")] - fn debug_message(&mut self, content: &str) { - static mut DEBUG_ENABLED: bool = false; - static mut FIRST_RUN: bool = true; - - // SAFETY: safe because executing in a single threaded context - // We need those two variables in order to make sure that the assignment is - // performed in the "logging enabled" case. This is because during RPC - // execution logging might be enabled while it is disabled during the - // actual execution as part of a transaction. The gas estimation takes - // place during RPC execution. We want to overestimate instead - // of underestimate gas usage. Otherwise using this estimate could lead to a out - // of gas error. - if unsafe { DEBUG_ENABLED || FIRST_RUN } { - let ret_code = ext::debug_message(content.as_bytes()); - if !matches!(ret_code, Err(ReturnErrorCode::LoggingDisabled)) { - // SAFETY: safe because executing in a single threaded context - unsafe { DEBUG_ENABLED = true } - } - // SAFETY: safe because executing in a single threaded context - unsafe { FIRST_RUN = false } - } - } - - fn hash_bytes(&mut self, input: &[u8], output: &mut ::Type) - where - H: CryptoHash, - { - ::hash(input, output) - } - - fn hash_encoded(&mut self, input: &T, output: &mut ::Type) - where - H: CryptoHash, - T: scale::Encode, - { - let mut scope = self.scoped_buffer(); - let enc_input = scope.take_encoded(input); - ::hash(enc_input, output) - } - - fn ecdsa_recover( - &mut self, - signature: &[u8; 65], - message_hash: &[u8; 32], - output: &mut [u8; 33], - ) -> Result<()> { - ext::ecdsa_recover(signature, message_hash, output).map_err(Into::into) - } - - fn ecdsa_to_eth_address( - &mut self, - pubkey: &[u8; 33], - output: &mut [u8; 20], - ) -> Result<()> { - ext::ecdsa_to_eth_address(pubkey, output).map_err(Into::into) - } - - fn sr25519_verify( - &mut self, - signature: &[u8; 64], - message: &[u8], - pub_key: &[u8; 32], - ) -> Result<()> { - ext::sr25519_verify(signature, message, pub_key).map_err(Into::into) - } - - fn call_chain_extension( - &mut self, - id: u32, - input: &I, - status_to_result: F, - decode_to_result: D, - ) -> ::core::result::Result - where - I: scale::Encode, - T: scale::Decode, - E: From, - F: FnOnce(u32) -> ::core::result::Result<(), ErrorCode>, - D: FnOnce(&[u8]) -> ::core::result::Result, - { - let mut scope = self.scoped_buffer(); - let enc_input = scope.take_encoded(input); - let output = &mut scope.take_rest(); - status_to_result(ext::call_chain_extension(id, enc_input, Some(output)))?; - let decoded = decode_to_result(output)?; - Ok(decoded) - } - - fn set_code_hash(&mut self, code_hash_ptr: &[u8]) -> Result<()> { - ext::set_code_hash(code_hash_ptr).map_err(Into::into) - } -} - -impl TypedEnvBackend for EnvInstance { - fn caller(&mut self) -> E::AccountId { - self.get_property::(ext::caller) - .expect("The executed contract must have a caller with a valid account id.") - } - - fn transferred_value(&mut self) -> E::Balance { - self.get_property_little_endian::(ext::value_transferred) - } - - fn gas_left(&mut self) -> u64 { - self.get_property_little_endian::(ext::gas_left) - } - - fn block_timestamp(&mut self) -> E::Timestamp { - self.get_property_little_endian::(ext::now) - } - - fn account_id(&mut self) -> E::AccountId { - self.get_property::(ext::address) - .expect("A contract being executed must have a valid account id.") - } - - fn balance(&mut self) -> E::Balance { - self.get_property_little_endian::(ext::balance) - } - - fn block_number(&mut self) -> E::BlockNumber { - self.get_property_little_endian::(ext::block_number) - } - - fn minimum_balance(&mut self) -> E::Balance { - self.get_property_little_endian::(ext::minimum_balance) - } - - fn emit_event(&mut self, event: Evt) - where - E: Environment, - Evt: Event, - { - let (mut scope, enc_topics) = - event.topics::(TopicsBuilder::from(self.scoped_buffer()).into()); - let enc_data = scope.take_encoded(&event); - ext::deposit_event(enc_topics, enc_data); - } - - fn invoke_contract_v1( - &mut self, - params: &CallParams, Args, R>, - ) -> Result> - where - E: Environment, - Args: scale::Encode, - R: scale::Decode, - { - let mut scope = self.scoped_buffer(); - let gas_limit = params.gas_limit(); - let enc_callee = scope.take_encoded(params.callee()); - let enc_transferred_value = scope.take_encoded(params.transferred_value()); - let call_flags = params.call_flags(); - let enc_input = if !call_flags.contains(CallFlags::FORWARD_INPUT) - && !call_flags.contains(CallFlags::CLONE_INPUT) - { - scope.take_encoded(params.exec_input()) - } else { - &mut [] - }; - let output = &mut scope.take_rest(); - let flags = params.call_flags(); - #[allow(deprecated)] - let call_result = ext::call_v1( - *flags, - enc_callee, - gas_limit, - enc_transferred_value, - enc_input, - Some(output), - ); - match call_result { - Ok(()) | Err(ReturnErrorCode::CalleeReverted) => { - let decoded = scale::DecodeAll::decode_all(&mut &output[..])?; - Ok(decoded) - } - Err(actual_error) => Err(actual_error.into()), - } - } - - fn invoke_contract( - &mut self, - params: &CallParams, Args, R>, - ) -> Result> - where - E: Environment, - Args: scale::Encode, - R: scale::Decode, - { - let mut scope = self.scoped_buffer(); - let ref_time_limit = params.ref_time_limit(); - let proof_size_limit = params.proof_size_limit(); - let storage_deposit_limit = params - .storage_deposit_limit() - .map(|limit| &*scope.take_encoded(limit)); - let enc_callee = scope.take_encoded(params.callee()); - let enc_transferred_value = scope.take_encoded(params.transferred_value()); - let call_flags = params.call_flags(); - let enc_input = if !call_flags.contains(CallFlags::FORWARD_INPUT) - && !call_flags.contains(CallFlags::CLONE_INPUT) - { - scope.take_encoded(params.exec_input()) - } else { - &mut [] - }; - let output = &mut scope.take_rest(); - let flags = params.call_flags(); - #[allow(deprecated)] - let call_result = ext::call_v2( - *flags, - enc_callee, - ref_time_limit, - proof_size_limit, - storage_deposit_limit, - enc_transferred_value, - enc_input, - Some(output), - ); - match call_result { - Ok(()) | Err(ReturnErrorCode::CalleeReverted) => { - let decoded = scale::DecodeAll::decode_all(&mut &output[..])?; - Ok(decoded) - } - Err(actual_error) => Err(actual_error.into()), - } - } - - fn invoke_contract_delegate( - &mut self, - params: &CallParams, Args, R>, - ) -> Result> - where - E: Environment, - Args: scale::Encode, - R: scale::Decode, - { - let mut scope = self.scoped_buffer(); - let call_flags = params.call_flags(); - let enc_code_hash = scope.take_encoded(params.code_hash()); - let enc_input = if !call_flags.contains(CallFlags::FORWARD_INPUT) - && !call_flags.contains(CallFlags::CLONE_INPUT) - { - scope.take_encoded(params.exec_input()) - } else { - &mut [] - }; - let output = &mut scope.take_rest(); - let flags = params.call_flags(); - let call_result = - ext::delegate_call(*flags, enc_code_hash, enc_input, Some(output)); - match call_result { - Ok(()) | Err(ReturnErrorCode::CalleeReverted) => { - let decoded = scale::DecodeAll::decode_all(&mut &output[..])?; - Ok(decoded) - } - Err(actual_error) => Err(actual_error.into()), - } - } - - fn instantiate_contract( - &mut self, - params: &CreateParams, Args, Salt, RetType>, - ) -> Result< - ink_primitives::ConstructorResult< - >::Output, - >, - > - where - E: Environment, - ContractRef: FromAccountId, - Args: scale::Encode, - Salt: AsRef<[u8]>, - RetType: ConstructorReturnType, - { - let mut scoped = self.scoped_buffer(); - let ref_time_limit = params.ref_time_limit(); - let proof_size_limit = params.proof_size_limit(); - let storage_deposit_limit = params - .storage_deposit_limit() - .map(|limit| &*scoped.take_encoded(limit)); - let enc_code_hash = scoped.take_encoded(params.code_hash()); - let enc_endowment = scoped.take_encoded(params.endowment()); - let enc_input = scoped.take_encoded(params.exec_input()); - let out_address = &mut scoped.take_max_encoded_len::(); - let salt = params.salt_bytes().as_ref(); - let out_return_value = &mut scoped.take_rest(); - - let instantiate_result = ext::instantiate_v2( - enc_code_hash, - ref_time_limit, - proof_size_limit, - storage_deposit_limit, - enc_endowment, - enc_input, - Some(out_address), - Some(out_return_value), - salt, - ); - - crate::engine::decode_instantiate_result::<_, E, ContractRef, RetType>( - instantiate_result.map_err(Into::into), - &mut &out_address[..], - &mut &out_return_value[..], - ) - } - - fn instantiate_contract_v1( - &mut self, - params: &CreateParams, - ) -> Result< - ink_primitives::ConstructorResult< - >::Output, - >, - > - where - E: Environment, - ContractRef: FromAccountId, - Args: scale::Encode, - Salt: AsRef<[u8]>, - RetType: ConstructorReturnType, - { - let mut scoped = self.scoped_buffer(); - let gas_limit = params.gas_limit(); - let enc_code_hash = scoped.take_encoded(params.code_hash()); - let enc_endowment = scoped.take_encoded(params.endowment()); - let enc_input = scoped.take_encoded(params.exec_input()); - let out_address = &mut scoped.take_max_encoded_len::(); - let salt = params.salt_bytes().as_ref(); - let out_return_value = &mut scoped.take_rest(); - - #[allow(deprecated)] - let instantiate_result = ext::instantiate_v1( - enc_code_hash, - gas_limit, - enc_endowment, - enc_input, - Some(out_address), - Some(out_return_value), - salt, - ); - - crate::engine::decode_instantiate_result::<_, E, ContractRef, RetType>( - instantiate_result.map_err(Into::into), - &mut &out_address[..], - &mut &out_return_value[..], - ) - } - - fn terminate_contract(&mut self, beneficiary: E::AccountId) -> ! - where - E: Environment, - { - let buffer = self.scoped_buffer().take_encoded(&beneficiary); - ext::terminate_v1(buffer); - } - - fn transfer(&mut self, destination: E::AccountId, value: E::Balance) -> Result<()> - where - E: Environment, - { - let mut scope = self.scoped_buffer(); - let enc_destination = scope.take_encoded(&destination); - let enc_value = scope.take_encoded(&value); - ext::transfer(enc_destination, enc_value).map_err(Into::into) - } - - fn weight_to_fee(&mut self, gas: u64) -> E::Balance { - let mut result = ::Bytes::default(); - ext::weight_to_fee(gas, &mut result.as_mut()); - ::from_le_bytes(result) - } - - fn is_contract(&mut self, account_id: &E::AccountId) -> bool - where - E: Environment, - { - let mut scope = self.scoped_buffer(); - let enc_account_id = scope.take_encoded(account_id); - ext::is_contract(enc_account_id) - } - - fn caller_is_origin(&mut self) -> bool - where - E: Environment, - { - ext::caller_is_origin() - } - - fn caller_is_root(&mut self) -> bool - where - E: Environment, - { - // `ext::caller_is_root()` currently returns `u32`. - // See https://github.com/paritytech/polkadot-sdk/issues/6767 for more details. - let ret = ext::caller_is_root(); - match ret { - 0u32 => false, - 1u32 => true, - _ => panic!("Invalid value for bool conversion: {}", ret), - } - } - - fn code_hash(&mut self, account_id: &E::AccountId) -> Result - where - E: Environment, - { - let mut scope = self.scoped_buffer(); - let output = scope.take_max_encoded_len::(); - scope.append_encoded(account_id); - let enc_account_id = scope.take_appended(); - - ext::code_hash(enc_account_id, output)?; - let hash = scale::Decode::decode(&mut &output[..])?; - Ok(hash) - } - - fn own_code_hash(&mut self) -> Result - where - E: Environment, - { - let output = &mut self.scoped_buffer().take_max_encoded_len::(); - ext::own_code_hash(output); - let hash = scale::Decode::decode(&mut &output[..])?; - Ok(hash) - } - - fn call_runtime(&mut self, call: &Call) -> Result<()> - where - E: Environment, - Call: scale::Encode, - { - let mut scope = self.scoped_buffer(); - let enc_call = scope.take_encoded(call); - ext::call_runtime(enc_call).map_err(Into::into) - } - - fn lock_delegate_dependency(&mut self, code_hash: &E::Hash) - where - E: Environment, - { - let mut scope = self.scoped_buffer(); - let enc_code_hash = scope.take_encoded(code_hash); - ext::lock_delegate_dependency(enc_code_hash) - } - - fn unlock_delegate_dependency(&mut self, code_hash: &E::Hash) - where - E: Environment, - { - let mut scope = self.scoped_buffer(); - let enc_code_hash = scope.take_encoded(code_hash); - ext::unlock_delegate_dependency(enc_code_hash) - } - - fn xcm_execute(&mut self, msg: &VersionedXcm) -> Result<()> - where - E: Environment, - Call: scale::Encode, - { - let mut scope = self.scoped_buffer(); - - let enc_msg = scope.take_encoded(msg); - - #[allow(deprecated)] - ext::xcm_execute(enc_msg).map_err(Into::into) - } - - fn xcm_send( - &mut self, - dest: &xcm::VersionedLocation, - msg: &VersionedXcm, - ) -> Result - where - E: Environment, - Call: scale::Encode, - { - let mut scope = self.scoped_buffer(); - let output = scope.take(32); - scope.append_encoded(dest); - let enc_dest = scope.take_appended(); - - scope.append_encoded(msg); - let enc_msg = scope.take_appended(); - #[allow(deprecated)] - ext::xcm_send(enc_dest, enc_msg, output.try_into().unwrap())?; - let hash: xcm::v4::XcmHash = scale::Decode::decode(&mut &output[..])?; - Ok(hash) - } -} diff --git a/crates/env/src/engine/on_chain/mod.rs b/crates/env/src/engine/on_chain/mod.rs index 274384174b7..1b687703bfa 100644 --- a/crates/env/src/engine/on_chain/mod.rs +++ b/crates/env/src/engine/on_chain/mod.rs @@ -13,7 +13,7 @@ // limitations under the License. mod buffer; -mod impls; +mod pallet_revive; use self::buffer::{ EncodeScope, diff --git a/crates/env/src/engine/on_chain/impls/pallet_revive.rs b/crates/env/src/engine/on_chain/pallet_revive.rs similarity index 78% rename from crates/env/src/engine/on_chain/impls/pallet_revive.rs rename to crates/env/src/engine/on_chain/pallet_revive.rs index 1ec31da4dcf..c96100f2108 100644 --- a/crates/env/src/engine/on_chain/impls/pallet_revive.rs +++ b/crates/env/src/engine/on_chain/pallet_revive.rs @@ -19,7 +19,7 @@ use crate::{ ConstructorReturnType, CreateParams, DelegateCall, - FromAccountId, + FromAddr, LimitParamsV2, }, engine::on_chain::{ @@ -39,13 +39,18 @@ use crate::{ Keccak256, Sha2x256, }, + types::FromLittleEndian, Clear, EnvBackend, Environment, - types::FromLittleEndian, Result, TypedEnvBackend, }; +use ink_primitives::{ + H160, + H256, + U256, +}; use ink_storage_traits::{ decode_all, Storable, @@ -131,11 +136,6 @@ where { type Output = (ScopedBuffer<'a>, &'a mut [u8]); - fn expect(&mut self, expected_topics: usize) { - self.scoped_buffer - .append_encoded(&scale::Compact(expected_topics as u32)); - } - fn push_topic(&mut self, topic_value: &T) where T: scale::Encode, @@ -193,17 +193,6 @@ impl EnvInstance { result.as_mut()[..].copy_from_slice(&u256[..len]); ::from_le_bytes(result) } - - /// Returns the contract property value. - #[inline(always)] - fn get_property(&mut self, ext_fn: fn(output: &mut &mut [u8])) -> Result - where - T: scale::Decode, - { - let full_scope = &mut self.scoped_buffer().take_rest(); - ext_fn(full_scope); - scale::Decode::decode(&mut &full_scope[..]).map_err(Into::into) - } } const STORAGE_FLAGS: StorageFlags = StorageFlags::empty(); @@ -276,7 +265,9 @@ impl EnvBackend for EnvInstance { where T: scale::Decode, { - self.get_property::(ext::input) + let full_scope = &mut self.scoped_buffer().take_rest(); + ext::call_data_copy(full_scope, 0); + scale::Decode::decode(&mut &full_scope[..]).map_err(Into::into) } fn return_value(&mut self, flags: ReturnFlags, return_value: &R) -> ! @@ -382,35 +373,27 @@ impl EnvBackend for EnvInstance { Ok(decoded) } - fn set_code_hash(&mut self, code_hash_ptr: &[u8]) -> Result<()> { - let code_hash: &[u8; 32] = code_hash_ptr.try_into().unwrap(); - ext::set_code_hash(code_hash).map_err(Into::into) + fn set_code_hash(&mut self, code_hash: &H256) -> Result<()> { + ext::set_code_hash(code_hash.as_fixed_bytes()); + Ok(()) // todo } } +// TODO remove anything with hash impl TypedEnvBackend for EnvInstance { - fn caller(&mut self) -> E::AccountId { + fn caller(&mut self) -> H160 { let mut scope = self.scoped_buffer(); let h160: &mut [u8; 20] = scope.take(20).try_into().unwrap(); ext::caller(h160); - - let account_id: &mut [u8; 32] = scope.take(32).try_into().unwrap(); - // TODO - // ext::to_account_id(h160, account_id); - - scale::Decode::decode(&mut &account_id[..]) + scale::Decode::decode(&mut &h160[..]) .expect("The executed contract must have a caller with a valid account id.") } - fn transferred_value(&mut self) -> E::Balance { - self.get_property_little_endian::(ext::value_transferred) + fn transferred_value(&mut self) -> U256 { + self.get_property_little_endian::(ext::value_transferred) } - // fn gas_left(&mut self) -> u64 { - // self.get_property_little_endian::(ext::gas_left) - // } - fn block_timestamp(&mut self) -> E::Timestamp { self.get_property_little_endian::(ext::now) } @@ -418,6 +401,7 @@ impl TypedEnvBackend for EnvInstance { fn account_id(&mut self) -> E::AccountId { let mut scope = self.scoped_buffer(); + // todo this is wrong let account_id: &mut [u8; 32] = scope.take(32).try_into().unwrap(); account_id[20..].fill(0xEE); let h160: &mut [u8; 20] = account_id[..20].as_mut().try_into().unwrap(); @@ -427,8 +411,18 @@ impl TypedEnvBackend for EnvInstance { .expect("A contract being executed must have a valid account id.") } - fn balance(&mut self) -> E::Balance { - self.get_property_little_endian::(ext::balance) + fn address(&mut self) -> H160 { + let mut scope = self.scoped_buffer(); + + let h160: &mut [u8; 20] = scope.take(20).try_into().unwrap(); + ext::address(h160); + + scale::Decode::decode(&mut &h160[..]) + .expect("A contract being executed must have a valid address.") + } + + fn balance(&mut self) -> U256 { + self.get_property_little_endian(ext::balance) } fn block_number(&mut self) -> E::BlockNumber { @@ -447,17 +441,18 @@ impl TypedEnvBackend for EnvInstance { let (mut scope, enc_topics) = event.topics::(TopicsBuilder::from(self.scoped_buffer()).into()); // TODO: improve - let enc_topics = &enc_topics + let enc_topics = enc_topics .chunks_exact(32) .map(|c| c.try_into().unwrap()) - .collect::>(); + .collect::>(); let enc_data = scope.take_encoded(&event); - ext::deposit_event(enc_topics, enc_data); + + ext::deposit_event(&enc_topics[..], enc_data); } fn invoke_contract( &mut self, - params: &CallParams, Args, R>, + params: &CallParams, ) -> Result> where E: Environment, @@ -474,6 +469,7 @@ impl TypedEnvBackend for EnvInstance { enc_storage_limit.into_buffer().try_into().unwrap(); enc_storage_limit }); + let enc_callee: &[u8; 20] = params.callee().as_ref().try_into().unwrap(); let mut enc_transferred_value = EncodeScope::from(scope.take(32)); scale::Encode::encode_to(¶ms.transferred_value(), &mut enc_transferred_value); @@ -489,12 +485,13 @@ impl TypedEnvBackend for EnvInstance { }; let output = &mut scope.take_rest(); let flags = params.call_flags(); - #[allow(deprecated)] + #[allow(deprecated)] // todo let call_result = ext::call( *flags, enc_callee, ref_time_limit, proof_size_limit, + //enc_storage_limit, storage_deposit_limit.as_deref(), enc_transferred_value, enc_input, @@ -511,19 +508,49 @@ impl TypedEnvBackend for EnvInstance { fn invoke_contract_delegate( &mut self, - _params: &CallParams, Args, R>, + params: &CallParams, ) -> Result> where E: Environment, Args: scale::Encode, R: scale::Decode, { - todo!("has to be implemented") + let mut scope = self.scoped_buffer(); + let call_flags = params.call_flags(); + let enc_input = if !call_flags.contains(CallFlags::FORWARD_INPUT) + && !call_flags.contains(CallFlags::CLONE_INPUT) + { + scope.take_encoded(params.exec_input()) + } else { + &mut [] + }; + let output = &mut scope.take_rest(); + let flags = params.call_flags(); + let enc_address: [u8; 20] = params.address().0; + let ref_time_limit = params.ref_time_limit(); + let proof_size_limit = params.proof_size_limit(); + let deposit_limit = params.deposit_limit().as_ref(); + let call_result = ext::delegate_call( + *flags, + &enc_address, + ref_time_limit, + proof_size_limit, + deposit_limit, + enc_input, + Some(output), + ); + match call_result { + Ok(()) | Err(ReturnErrorCode::CalleeReverted) => { + let decoded = scale::DecodeAll::decode_all(&mut &output[..])?; + Ok(decoded) + } + Err(actual_error) => Err(actual_error.into()), + } } - fn instantiate_contract( + fn instantiate_contract( &mut self, - params: &CreateParams, Args, Salt, RetType>, + params: &CreateParams, ) -> Result< ink_primitives::ConstructorResult< >::Output, @@ -531,9 +558,8 @@ impl TypedEnvBackend for EnvInstance { > where E: Environment, - ContractRef: FromAccountId, + ContractRef: FromAddr, Args: scale::Encode, - Salt: AsRef<[u8]>, RetType: ConstructorReturnType, { let mut scoped = self.scoped_buffer(); @@ -554,7 +580,7 @@ impl TypedEnvBackend for EnvInstance { enc_endowment.into_buffer().try_into().unwrap(); let enc_input = scoped.take_encoded(params.exec_input()); let out_address: &mut [u8; 20] = scoped.take(20).try_into().unwrap(); - let salt: &[u8; 32] = params.salt_bytes().as_ref().try_into().unwrap(); + let salt = params.salt_bytes().as_ref(); let out_return_value = &mut scoped.take_rest(); let instantiate_result = ext::instantiate( @@ -566,20 +592,18 @@ impl TypedEnvBackend for EnvInstance { enc_input, Some(out_address), Some(out_return_value), - Some(salt), + salt, ); + //let foo: () = instantiate_result; - crate::engine::decode_instantiate_result::<_, E, ContractRef, RetType>( + crate::engine::decode_instantiate_result::<_, ContractRef, RetType>( instantiate_result.map_err(Into::into), &mut &out_address[..], &mut &out_return_value[..], ) } - fn terminate_contract(&mut self, beneficiary: E::AccountId) -> ! - where - E: Environment, - { + fn terminate_contract(&mut self, beneficiary: H160) -> ! { let buffer: &mut [u8; 20] = self.scoped_buffer().take_encoded(&beneficiary) [0..20] .as_mut() @@ -588,15 +612,61 @@ impl TypedEnvBackend for EnvInstance { ext::terminate(buffer); } - fn transfer( - &mut self, - _destination: E::AccountId, - _value: E::Balance, - ) -> Result<()> + fn transfer(&mut self, destination: H160, value: U256) -> Result<()> where E: Environment, { - todo!("has to be implemented") + let mut scope = self.scoped_buffer(); + /* + let ref_time_limit = params.ref_time_limit(); + let proof_size_limit = params.proof_size_limit(); + let storage_deposit_limit = params.storage_deposit_limit().map(|limit| { + let mut enc_storage_limit = EncodeScope::from(scope.take(32)); + scale::Encode::encode_to(&limit, &mut enc_storage_limit); + let enc_storage_limit: &mut [u8; 32] = + enc_storage_limit.into_buffer().try_into().unwrap(); + enc_storage_limit + }); + */ + + let enc_callee: &[u8; 20] = destination.as_ref().try_into().unwrap(); + + //let value: &[u8] = scale::Encode::encode_to(value, &mut scope); + //let value: u128 = scale::Decode::decode(&mut &value[..]).expect("foo"); + //let value_u128: u128 = value.try_into().expect("oh no"); + // //core::mem::transmute(value); todo + //let value_u128: u128 = unsafe { + //core::mem::transmute_copy::<::Balance, u128>(&value) }; + //let value = scale::Decode::primitive_types::U256::from(value_u128); + //let value = U256::from(value_u128); + let mut enc_value = EncodeScope::from(scope.take(32)); + scale::Encode::encode_to(&value, &mut enc_value); + let enc_value: &mut [u8; 32] = enc_value.into_buffer().try_into().unwrap(); + + let output = &mut scope.take_rest(); + #[allow(deprecated)] + let call_result = ext::call( + CallFlags::empty(), + enc_callee, + 0u64, + 0u64, + None, + //ref_time_limit, + //proof_size_limit, + //storage_deposit_limit.as_deref(), + enc_value, + &[], + Some(output), + ); + match call_result { + Ok(()) => { + // no need to decode, is () + //let decoded = scale::DecodeAll::decode_all(&mut &output[..])?; + //Ok(decoded) + Ok(()) + } + Err(actual_error) => Err(actual_error.into()), + } } fn weight_to_fee(&mut self, gas: u64) -> E::Balance { @@ -610,16 +680,11 @@ impl TypedEnvBackend for EnvInstance { ::from_le_bytes(result) } - fn is_contract(&mut self, account_id: &E::AccountId) -> bool - where - E: Environment, - { + fn is_contract(&mut self, addr: &H160) -> bool { let mut scope = self.scoped_buffer(); - let enc_account_id: &mut [u8; 20] = scope.take_encoded(account_id)[..20] - .as_mut() - .try_into() - .unwrap(); - ext::is_contract(enc_account_id) + let enc_addr: &mut [u8; 20] = + scope.take_encoded(addr)[..20].as_mut().try_into().unwrap(); + ext::is_contract(enc_addr) } fn caller_is_origin(&mut self) -> bool @@ -643,31 +708,22 @@ impl TypedEnvBackend for EnvInstance { } } - fn code_hash(&mut self, account_id: &E::AccountId) -> Result - where - E: Environment, - { + fn code_hash(&mut self, addr: &H160) -> Result { let mut scope = self.scoped_buffer(); - let enc_account_id: &mut [u8; 20] = scope.take_encoded(account_id)[..20] - .as_mut() - .try_into() - .unwrap(); + // todo can be simplified + let enc_addr: &mut [u8; 20] = + scope.take_encoded(addr)[..20].as_mut().try_into().unwrap(); let output: &mut [u8; 32] = - scope.take_max_encoded_len::().try_into().unwrap(); - // TODO - // ext::code_hash(enc_account_id, output)?; - ext::code_hash(enc_account_id, output); + scope.take_max_encoded_len::().try_into().unwrap(); + ext::code_hash(enc_addr, output); let hash = scale::Decode::decode(&mut &output[..])?; Ok(hash) } - fn own_code_hash(&mut self) -> Result - where - E: Environment, - { + fn own_code_hash(&mut self) -> Result { let output: &mut [u8; 32] = &mut self .scoped_buffer() - .take_max_encoded_len::() + .take_max_encoded_len::() .try_into() .unwrap(); ext::own_code_hash(output); @@ -685,7 +741,7 @@ impl TypedEnvBackend for EnvInstance { ext::call_runtime(enc_call).map_err(Into::into) } - fn lock_delegate_dependency(&mut self, code_hash: &E::Hash) + fn lock_delegate_dependency(&mut self, code_hash: &H256) where E: Environment, { @@ -695,7 +751,7 @@ impl TypedEnvBackend for EnvInstance { ext::lock_delegate_dependency(enc_code_hash) } - fn unlock_delegate_dependency(&mut self, code_hash: &E::Hash) + fn unlock_delegate_dependency(&mut self, code_hash: &H256) where E: Environment, { diff --git a/crates/env/src/error.rs b/crates/env/src/error.rs index 195e3978f03..27c0154f107 100644 --- a/crates/env/src/error.rs +++ b/crates/env/src/error.rs @@ -16,9 +16,6 @@ use derive_more::From; #[cfg(any(feature = "std", test, doc))] use crate::engine::off_chain::OffChainError; -#[cfg(not(feature = "revive"))] -use pallet_contracts_uapi::ReturnErrorCode; -#[cfg(feature = "revive")] use pallet_revive_uapi::ReturnErrorCode; /// Errors that can be encountered upon environmental interaction. diff --git a/crates/env/src/event.rs b/crates/env/src/event.rs index 7397b04a6c1..2296e28e804 100644 --- a/crates/env/src/event.rs +++ b/crates/env/src/event.rs @@ -27,9 +27,6 @@ where /// The type of the serialized event topics. type Output; - /// Initialized the backend with the expected number of event topics. - fn expect(&mut self, expected_topics: usize); - /// Pushes another topic for serialization to the backend. fn push_topic(&mut self, topic_value: &T) where @@ -78,15 +75,12 @@ where E: Environment, B: TopicsBuilderBackend, { - /// Initializes the topics builder and informs it about how many topics it must expect - /// to serialize. + /// Initializes the topics builder. /// /// The number of expected topics is given implicitly by the `E` type parameter. pub fn build( - mut self, + self, ) -> TopicsBuilder<::RemainingTopics, E, B> { - self.backend - .expect(<::RemainingTopics as EventTopicsAmount>::AMOUNT); TopicsBuilder { backend: self.backend, state: Default::default(), diff --git a/crates/env/src/lib.rs b/crates/env/src/lib.rs index 25021c6a96d..ce6274466eb 100644 --- a/crates/env/src/lib.rs +++ b/crates/env/src/lib.rs @@ -25,6 +25,7 @@ html_favicon_url = "https://use.ink/crate-docs/favicon.png" )] #![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(docsrs, feature(doc_cfg))] #![deny( missing_docs, bad_style, @@ -51,10 +52,6 @@ #[const_env::from_env("INK_STATIC_BUFFER_SIZE")] pub const BUFFER_SIZE: usize = 16384; -#[cfg(all(not(feature = "std"), target_arch = "wasm32"))] -#[allow(unused_extern_crates)] -extern crate rlibc; - #[cfg(not(any(feature = "std", feature = "no-panic-handler")))] #[allow(unused_variables)] #[panic_handler] @@ -63,16 +60,14 @@ fn panic(info: &core::panic::PanicInfo) -> ! { debug_print!("{}\n", info); cfg_if::cfg_if! { - if #[cfg(target_arch = "wasm32")] { - core::arch::wasm32::unreachable(); - } else if #[cfg(target_arch = "riscv32")] { + if #[cfg(target_arch = "riscv64")] { // Safety: The unimp instruction is guaranteed to trap unsafe { core::arch::asm!("unimp"); core::hint::unreachable_unchecked(); } } else { - core::compile_error!("ink! only supports wasm32 and riscv32"); + core::compile_error!("ink! only supports riscv64"); } } } @@ -99,21 +94,6 @@ mod tests; #[doc(inline)] pub use self::engine::off_chain::test_api as test; -#[cfg(not(feature = "revive"))] -#[doc(inline)] -pub use pallet_contracts_uapi::{ - CallFlags, - ReturnErrorCode, - ReturnFlags, -}; -#[cfg(feature = "revive")] -#[doc(inline)] -pub use pallet_revive_uapi::{ - CallFlags, - ReturnErrorCode, - ReturnFlags, -}; - use self::backend::{ EnvBackend, TypedEnvBackend, @@ -148,6 +128,12 @@ pub use ink_primitives::{ reflect, types, }; +#[doc(inline)] +pub use pallet_revive_uapi::{ + CallFlags, + ReturnErrorCode, + ReturnFlags, +}; cfg_if::cfg_if! { if #[cfg(any(feature = "ink-debug", feature = "std"))] { @@ -162,12 +148,12 @@ cfg_if::cfg_if! { /// extrinsic). The `debug_message` buffer will be: /// - Returned to the RPC caller. /// - Logged as a `debug!` message on the Substrate node, which will be printed to the - /// node console's `stdout` when the log level is set to `-lruntime::contracts=debug`. + /// node console's `stdout` when the log level is set to `-lruntime::revive=debug`. /// /// # Note /// /// This depends on the `debug_message` interface which requires the - /// `"pallet-contracts/unstable-interface"` feature to be enabled in the target runtime. + /// `"pallet-revive/unstable-hostfn"` feature to be enabled in the target runtime. #[macro_export] macro_rules! debug_print { ($($arg:tt)*) => ($crate::debug_message(&$crate::format!($($arg)*))); @@ -179,7 +165,7 @@ cfg_if::cfg_if! { /// # Note /// /// This depends on the `debug_message` interface which requires the - /// `"pallet-contracts/unstable-interface"` feature to be enabled in the target runtime. + /// `"pallet-revive/unstable-hostfn"` feature to be enabled in the target runtime. #[macro_export] macro_rules! debug_println { () => ($crate::debug_print!("\n")); diff --git a/crates/env/src/types.rs b/crates/env/src/types.rs new file mode 100644 index 00000000000..c6cba2babc2 --- /dev/null +++ b/crates/env/src/types.rs @@ -0,0 +1,50 @@ +// Copyright (C) Use Ink (UK) Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Types for the default environment. +//! +//! These are simple mirrored types from the default substrate FRAME configuration. +//! Their interfaces and functionality might not be complete. +//! +//! Users are required to provide their own type definitions and `Environment` +//! implementations in order to write ink! contracts for other chain configurations. +//! +//! # Note +//! +//! When authoring a contract, the concrete `Environment` are available via aliases +//! generated by the `lang` macro. Therefore all functionality of the concrete +//! types is accessible in the contract, not constrained by the required trait +//! bounds. +//! +//! Outside the contract and its tests (e.g. in the off-chain environment), where +//! there is no knowledge of the concrete types, the functionality is restricted to +//! the trait bounds on the `Environment` trait types. + +use super::arithmetic::AtLeast32BitUnsigned; +use ink_primitives::{ + AccountId, + Clear, + Hash, + H160, + U256, +}; +use scale::{ + Decode, + Encode, + MaxEncodedLen, +}; +#[cfg(feature = "std")] +use scale_info::TypeInfo; + +// todo remove file, move comment above diff --git a/crates/ink/Cargo.toml b/crates/ink/Cargo.toml index 59a94d281a6..fe26e88245f 100644 --- a/crates/ink/Cargo.toml +++ b/crates/ink/Cargo.toml @@ -22,15 +22,14 @@ ink_primitives = { workspace = true } ink_metadata = { workspace = true, optional = true } ink_prelude = { workspace = true } ink_macro = { workspace = true } -pallet-contracts-uapi = { workspace = true } pallet-revive-uapi = { workspace = true } scale = { workspace = true } scale-info = { workspace = true, default-features = false, features = ["derive"], optional = true } derive_more = { workspace = true, features = ["from"] } # TODO add explainer -xcm = { workspace = true, default-features = false } -sp-io = { version = "38.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } +xcm = { package = "staging-xcm", git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +sp-io = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } polkavm-derive = { workspace = true } @@ -56,9 +55,6 @@ std = [ ] # Enable contract debug messages via `debug_print!` and `debug_println!`. ink-debug = [ "ink_env/ink-debug" ] -test_instantiate = [ - "ink_env/test_instantiate" -] show-codegen-docs = [] @@ -68,8 +64,9 @@ no-allocator = [ "ink_env/no-allocator" ] # Disable the ink! provided panic handler. no-panic-handler = ["ink_env/no-panic-handler"] -revive = [ - "ink_env/revive", - "ink_storage/revive", - "ink_macro/revive" +# For the ui tests, which use this `Cargo.toml` +[lints.rust.unexpected_cfgs] +level = "warn" +check-cfg = [ + 'cfg(feature, values(any()))', ] diff --git a/crates/ink/codegen/Cargo.toml b/crates/ink/codegen/Cargo.toml index 9290e1f3c82..6674af3718f 100644 --- a/crates/ink/codegen/Cargo.toml +++ b/crates/ink/codegen/Cargo.toml @@ -41,9 +41,16 @@ default = [ "std" ] std = [ "either/use_std", "ink_primitives/std", + "ir/std", "itertools/use_std", "scale/std", "serde/std", "derive_more/std" ] -revive = [ ] + +# For the ui tests, which use this `Cargo.toml` +[lints.rust.unexpected_cfgs] +level = "warn" +check-cfg = [ + 'cfg(feature, values(any()))', +] diff --git a/crates/ink/codegen/src/generator/as_dependency/call_builder.rs b/crates/ink/codegen/src/generator/as_dependency/call_builder.rs index bccf0f15078..dfd687c3721 100644 --- a/crates/ink/codegen/src/generator/as_dependency/call_builder.rs +++ b/crates/ink/codegen/src/generator/as_dependency/call_builder.rs @@ -94,7 +94,7 @@ impl CallBuilder<'_> { )] #[::ink::scale_derive(Encode, Decode, TypeInfo)] pub struct #cb_ident { - account_id: AccountId, + addr: ::ink::H160, } const _: () = { @@ -117,29 +117,29 @@ impl CallBuilder<'_> { let span = self.contract.module().storage().span(); let cb_ident = Self::call_builder_ident(); quote_spanned!(span=> - impl ::ink::env::call::FromAccountId for #cb_ident { + impl ::ink::env::call::FromAddr for #cb_ident { #[inline] - fn from_account_id(account_id: AccountId) -> Self { - Self { account_id } + fn from_addr(addr: ::ink::H160) -> Self { + Self { addr } } } - impl ::ink::ToAccountId for #cb_ident { + impl ::ink::ToAddr for #cb_ident { #[inline] - fn to_account_id(&self) -> AccountId { - ::clone(&self.account_id) + fn to_addr(&self) -> ::ink::H160 { + <::ink::H160 as ::core::clone::Clone>::clone(&self.addr) } } - impl ::core::convert::AsRef for #cb_ident { - fn as_ref(&self) -> &AccountId { - &self.account_id + impl ::core::convert::AsRef<::ink::H160> for #cb_ident { + fn as_ref(&self) -> &::ink::H160 { + &self.addr } } - impl ::core::convert::AsMut for #cb_ident { - fn as_mut(&mut self) -> &mut AccountId { - &mut self.account_id + impl ::core::convert::AsMut<::ink::H160> for #cb_ident { + fn as_mut(&mut self) -> &mut ::ink::H160 { + &mut self.addr } } ) @@ -204,8 +204,9 @@ impl CallBuilder<'_> { // only an `AccountId` to a shared reference to another type of which // we know that it also thinly wraps an `AccountId`. // Furthermore both types use `repr(transparent)`. + // todo unsafe { - &*(&self.account_id as *const AccountId as *const Self::Forwarder) + &*(&self.addr as *const ::ink::H160 as *const Self::Forwarder) } } @@ -218,7 +219,7 @@ impl CallBuilder<'_> { // we know that it also thinly wraps an `AccountId`. // Furthermore both types use `repr(transparent)`. unsafe { - &mut *(&mut self.account_id as *mut AccountId as *mut Self::Forwarder) + &mut *(&mut self.addr as *mut ::ink::H160 as *mut Self::Forwarder) } } @@ -385,7 +386,7 @@ impl CallBuilder<'_> { let output_type = quote_spanned!(output_span=> ::ink::env::call::CallBuilder< Environment, - ::ink::env::call::utils::Set< ::ink::env::call::Call< Environment > >, + ::ink::env::call::utils::Set< ::ink::env::call::Call >, ::ink::env::call::utils::Set< ::ink::env::call::ExecutionInput<#arg_list> >, ::ink::env::call::utils::Set< ::ink::env::call::utils::ReturnType<#return_type> >, > @@ -399,7 +400,7 @@ impl CallBuilder<'_> { #( , #input_bindings : #input_types )* ) -> #output_type { ::ink::env::call::build_call::() - .call(::ink::ToAccountId::to_account_id(self)) + .call(::ink::ToAddr::to_addr(self)) .exec_input( ::ink::env::call::ExecutionInput::new( ::ink::env::call::Selector::new([ #( #selector_bytes ),* ]) diff --git a/crates/ink/codegen/src/generator/as_dependency/contract_ref.rs b/crates/ink/codegen/src/generator/as_dependency/contract_ref.rs index b21b2ca05d3..668ac462123 100644 --- a/crates/ink/codegen/src/generator/as_dependency/contract_ref.rs +++ b/crates/ink/codegen/src/generator/as_dependency/contract_ref.rs @@ -155,33 +155,33 @@ impl ContractRef<'_> { let storage_ident = self.contract.module().storage().ident(); let ref_ident = self.generate_contract_ref_ident(); quote_spanned!(span=> - impl ::ink::env::call::FromAccountId for #ref_ident { + impl ::ink::env::call::FromAddr for #ref_ident { #[inline] - fn from_account_id(account_id: AccountId) -> Self { + fn from_addr(addr: ::ink::H160) -> Self { Self { inner: <<#storage_ident as ::ink::codegen::ContractCallBuilder>::Type - as ::ink::env::call::FromAccountId>::from_account_id(account_id) + as ::ink::env::call::FromAddr>::from_addr(addr) } } } - impl ::ink::ToAccountId for #ref_ident { + impl ::ink::ToAddr for #ref_ident { #[inline] - fn to_account_id(&self) -> AccountId { + fn to_addr(&self) -> ::ink::H160 { <<#storage_ident as ::ink::codegen::ContractCallBuilder>::Type - as ::ink::ToAccountId>::to_account_id(&self.inner) + as ::ink::ToAddr>::to_addr(&self.inner) } } - impl ::core::convert::AsRef for #ref_ident { - fn as_ref(&self) -> &AccountId { - <_ as ::core::convert::AsRef>::as_ref(&self.inner) + impl ::core::convert::AsRef<::ink::H160> for #ref_ident { + fn as_ref(&self) -> &::ink::H160 { + <_ as ::core::convert::AsRef<::ink::H160>>::as_ref(&self.inner) } } - impl ::core::convert::AsMut for #ref_ident { - fn as_mut(&mut self) -> &mut AccountId { - <_ as ::core::convert::AsMut>::as_mut(&mut self.inner) + impl ::core::convert::AsMut<::ink::H160> for #ref_ident { + fn as_mut(&mut self) -> &mut ::ink::H160 { + <_ as ::core::convert::AsMut<::ink::H160>>::as_mut(&mut self.inner) } } ) @@ -448,7 +448,7 @@ impl ContractRef<'_> { let selector_bytes = constructor.composed_selector().hex_lits(); let input_bindings = generator::input_bindings(constructor.inputs()); let input_types = generator::input_types(constructor.inputs()); - let storage_ident = self.contract.module().storage().ident(); + let _storage_ident = self.contract.module().storage().ident(); let arg_list = generator::generate_argument_list(input_types.iter().cloned()); let ret_type = constructor .output() @@ -463,11 +463,8 @@ impl ContractRef<'_> { ) -> ::ink::env::call::CreateBuilder< Environment, Self, - ::ink::env::call::utils::Unset, - ::ink::env::call::utils::Set<::ink::env::call::LimitParamsV2<<#storage_ident as ::ink::env::ContractEnv>::Env>>, - ::ink::env::call::utils::Unset, + ::ink::env::call::utils::Set<::ink::env::call::LimitParamsV2 >, ::ink::env::call::utils::Set<::ink::env::call::ExecutionInput<#arg_list>>, - ::ink::env::call::utils::Unset<::ink::env::call::state::Salt>, ::ink::env::call::utils::Set<::ink::env::call::utils::ReturnType<#ret_type>>, > { ::ink::env::call::build_create::() diff --git a/crates/ink/codegen/src/generator/dispatch.rs b/crates/ink/codegen/src/generator/dispatch.rs index 7660f8ddfb4..093ae824465 100644 --- a/crates/ink/codegen/src/generator/dispatch.rs +++ b/crates/ink/codegen/src/generator/dispatch.rs @@ -84,26 +84,6 @@ impl GenerateCode for Dispatch<'_> { let message_decoder_type = self.generate_message_decoder_type(&messages); let entry_points = self.generate_entry_points(&constructors, &messages); - #[cfg(not(feature = "revive"))] - return quote! { - #contract_dispatchable_constructor_infos - #contract_dispatchable_messages_infos - #constructor_decoder_type - #message_decoder_type - - #[cfg(not(any(test, feature = "std", feature = "ink-as-dependency")))] - /* - const _: () = { - #entry_points - } - */ - mod __do_not_access__ { - use super::*; - #entry_points - } - }; - - #[cfg(feature = "revive")] quote! { #contract_dispatchable_constructor_infos #contract_dispatchable_messages_infos @@ -373,119 +353,32 @@ impl Dispatch<'_> { self.any_constructor_accepts_payment(constructors); let any_message_accepts_payment = self.any_message_accepts_payment(messages); - #[cfg(not(feature = "revive"))] - return quote_spanned!(span=> - #[allow(clippy::nonminimal_bool)] - fn internal_deploy() { - if !#any_constructor_accept_payment { - ::ink::codegen::deny_payment::<<#storage_ident as ::ink::env::ContractEnv>::Env>() - .unwrap_or_else(|error| ::core::panic!("{}", error)) - } - - let dispatchable = match ::ink::env::decode_input::< - <#storage_ident as ::ink::reflect::ContractConstructorDecoder>::Type, - >() { - ::core::result::Result::Ok(decoded_dispatchable) => { - decoded_dispatchable - } - ::core::result::Result::Err(_decoding_error) => { - let error = ::ink::ConstructorResult::Err(::ink::LangError::CouldNotReadInput); - - // At this point we're unable to set the `Ok` variant to be the any "real" - // constructor output since we were unable to figure out what the caller wanted - // to dispatch in the first place, so we set it to `()`. - // - // This is okay since we're going to only be encoding the `Err` variant - // into the output buffer anyways. - ::ink::env::return_value::<::ink::ConstructorResult<()>>( - ::ink::env::ReturnFlags::REVERT, - &error, - ); - } - }; - - <<#storage_ident as ::ink::reflect::ContractConstructorDecoder>::Type - as ::ink::reflect::ExecuteDispatchable>::execute_dispatchable(dispatchable) - .unwrap_or_else(|error| { - ::core::panic!("dispatching ink! message failed: {}", error) - }) - } - - #[allow(clippy::nonminimal_bool)] - fn internal_call() { - if !#any_message_accepts_payment { - ::ink::codegen::deny_payment::<<#storage_ident as ::ink::env::ContractEnv>::Env>() - .unwrap_or_else(|error| ::core::panic!("{}", error)) - } - - let dispatchable = match ::ink::env::decode_input::< - <#storage_ident as ::ink::reflect::ContractMessageDecoder>::Type, - >() { - ::core::result::Result::Ok(decoded_dispatchable) => { - decoded_dispatchable - } - ::core::result::Result::Err(_decoding_error) => { - let error = ::ink::MessageResult::Err(::ink::LangError::CouldNotReadInput); - - // At this point we're unable to set the `Ok` variant to be the any "real" - // message output since we were unable to figure out what the caller wanted - // to dispatch in the first place, so we set it to `()`. - // - // This is okay since we're going to only be encoding the `Err` variant - // into the output buffer anyways. - ::ink::env::return_value::<::ink::MessageResult<()>>( - ::ink::env::ReturnFlags::REVERT, - &error, - ); - } - }; - - <<#storage_ident as ::ink::reflect::ContractMessageDecoder>::Type - as ::ink::reflect::ExecuteDispatchable>::execute_dispatchable(dispatchable) - .unwrap_or_else(|error| { - ::core::panic!("dispatching ink! message failed: {}", error) - }) - } - - #[cfg(target_arch = "wasm32")] - #[no_mangle] - pub extern "C" fn call() { - internal_call() - } - - #[cfg(target_arch = "wasm32")] - #[no_mangle] - pub extern "C" fn deploy() { - internal_deploy() - } - ); - #[cfg(feature = "revive")] let fn_call: syn::ItemFn = syn::parse_quote! { - #[cfg(any(target_arch = "wasm32", target_arch = "riscv32"))] - #[cfg_attr(target_arch = "wasm32", no_mangle)] - #[ink::polkavm_export(abi = ink::polkavm_derive::default_abi)] + #[cfg(target_arch = "riscv64")] + #[::ink::polkavm_export(abi = ::ink::polkavm_derive::default_abi)] pub extern "C" fn call() { internal_call() } }; - #[cfg(feature = "revive")] let fn_deploy: syn::ItemFn = syn::parse_quote! { - #[cfg(any(target_arch = "wasm32", target_arch = "riscv32"))] - #[cfg_attr(target_arch = "wasm32", no_mangle)] - #[ink::polkavm_export(abi = ink::polkavm_derive::default_abi)] + #[cfg(target_arch = "riscv64")] + #[::ink::polkavm_export(abi = ::ink::polkavm_derive::default_abi)] pub extern "C" fn deploy() { + //panic!("---------------err code:\n1: _{:?}_", foo::BarPlain::Success ); internal_deploy() } }; - #[cfg(feature = "revive")] quote_spanned!(span=> + #[allow(dead_code)] // clippy throws a false positive otherwise #[allow(clippy::nonminimal_bool)] + #[cfg(target_arch = "riscv64")] fn internal_deploy() { if !#any_constructor_accept_payment { ::ink::codegen::deny_payment::<<#storage_ident as ::ink::env::ContractEnv>::Env>() .unwrap_or_else(|error| ::core::panic!("{}", error)) } + let dispatchable = match ::ink::env::decode_input::< <#storage_ident as ::ink::reflect::ContractConstructorDecoder>::Type, >() { @@ -495,12 +388,12 @@ impl Dispatch<'_> { ::core::result::Result::Err(_decoding_error) => { let error = ::ink::ConstructorResult::Err(::ink::LangError::CouldNotReadInput); - // At this point we're unable to set the `Ok` variant to be the any "real" + // At this point we're unable to set the `Ok` variant to be the "real" // constructor output since we were unable to figure out what the caller wanted // to dispatch in the first place, so we set it to `()`. // // This is okay since we're going to only be encoding the `Err` variant - // into the output buffer anyways. + // into the output buffer anyway. ::ink::env::return_value::<::ink::ConstructorResult<()>>( ::ink::env::ReturnFlags::REVERT, &error, @@ -511,32 +404,36 @@ impl Dispatch<'_> { <<#storage_ident as ::ink::reflect::ContractConstructorDecoder>::Type as ::ink::reflect::ExecuteDispatchable>::execute_dispatchable(dispatchable) .unwrap_or_else(|error| { - ::core::panic!("dispatching ink! message failed: {}", error) + ::core::panic!("dispatching ink! constructor failed: {}", error) }) } + #[allow(dead_code)] // clippy throws a false positive otherwise #[allow(clippy::nonminimal_bool)] + #[cfg(target_arch = "riscv64")] fn internal_call() { if !#any_message_accepts_payment { ::ink::codegen::deny_payment::<<#storage_ident as ::ink::env::ContractEnv>::Env>() .unwrap_or_else(|error| ::core::panic!("{}", error)) } + //::ink::env::debug_println!("before decode"); let dispatchable = match ::ink::env::decode_input::< <#storage_ident as ::ink::reflect::ContractMessageDecoder>::Type, >() { ::core::result::Result::Ok(decoded_dispatchable) => { + //::ink::env::debug_println!("in ok"); decoded_dispatchable } ::core::result::Result::Err(_decoding_error) => { let error = ::ink::MessageResult::Err(::ink::LangError::CouldNotReadInput); - // At this point we're unable to set the `Ok` variant to be the any "real" + // At this point we're unable to set the `Ok` variant to be the "real" // message output since we were unable to figure out what the caller wanted // to dispatch in the first place, so we set it to `()`. // // This is okay since we're going to only be encoding the `Err` variant - // into the output buffer anyways. + // into the output buffer anyway. ::ink::env::return_value::<::ink::MessageResult<()>>( ::ink::env::ReturnFlags::REVERT, &error, @@ -547,6 +444,7 @@ impl Dispatch<'_> { <<#storage_ident as ::ink::reflect::ContractMessageDecoder>::Type as ::ink::reflect::ExecuteDispatchable>::execute_dispatchable(dispatchable) .unwrap_or_else(|error| { + //::ink::env::debug_println!("dispatching failed"); ::core::panic!("dispatching ink! message failed: {}", error) }) } @@ -716,8 +614,14 @@ impl Dispatch<'_> { &::ink::ConstructorResult::Ok(output_result.map(|_| ())), ); - #[cfg(feature="test_instantiate")] - ::core::result::Result::Ok(()) + #[cfg(feature = "std")] + return ::core::result::Result::Ok(()); + + #[cfg(not(feature = "std"))] + #[cfg_attr(not(feature = "std"), allow(unreachable_code))] + { + ::core::unreachable!("either `return_value` or the `return` before will already have returned"); + } } ) }); @@ -894,6 +798,22 @@ impl Dispatch<'_> { #( #cfg_attrs )* Self::#message_ident(input) => { if #any_message_accepts_payment && #deny_payment { + + /* + let bar = ::ink::reflect::DispatchError::UnknownSelector; + ::ink::env::debug_print!("bar: {:?}", bar); + //let foo = format_args!("{}", bar); + //let s = ::alloc::fmt::format(format_args!("{}", bar)); + let s = ::ink::env::format!("{}", ::ink::reflect::DispatchError::UnknownSelector); + if s.eq("encountered unknown selector") { + ink::env::debug_print!("TRUE"); + } else { + ink::env::debug_print!("FALSE"); + } + */ + + //let foo = Err(::ink::reflect::DispatchError::UnknownSelector); + //foo? ::ink::codegen::deny_payment::< <#storage_ident as ::ink::env::ContractEnv>::Env>()?; } @@ -920,8 +840,14 @@ impl Dispatch<'_> { &::ink::MessageResult::Ok(result), ); - #[cfg(feature="test_instantiate")] - ::core::result::Result::Ok(()) + #[cfg(feature = "std")] + return ::core::result::Result::Ok(()); + + #[cfg(not(feature = "std"))] + #[cfg_attr(not(feature = "std"), allow(unreachable_code))] + { + ::core::unreachable!("either `return_value` or the `return` before will already have returned"); + } } ) }); diff --git a/crates/ink/codegen/src/generator/env.rs b/crates/ink/codegen/src/generator/env.rs index 76adad31c13..37ea1d6ec01 100644 --- a/crates/ink/codegen/src/generator/env.rs +++ b/crates/ink/codegen/src/generator/env.rs @@ -41,6 +41,7 @@ impl GenerateCode for Env<'_> { type BlockNumber = <<#storage_ident as ::ink::env::ContractEnv>::Env as ::ink::env::Environment>::BlockNumber; type ChainExtension = <<#storage_ident as ::ink::env::ContractEnv>::Env as ::ink::env::Environment>::ChainExtension; const MAX_EVENT_TOPICS: usize = <<#storage_ident as ::ink::env::ContractEnv>::Env as ::ink::env::Environment>::MAX_EVENT_TOPICS; + type EventRecord = <<#storage_ident as ::ink::env::ContractEnv>::Env as ::ink::env::Environment>::EventRecord; } } } diff --git a/crates/ink/codegen/src/generator/storage_item.rs b/crates/ink/codegen/src/generator/storage_item.rs index dc5a7e82d05..97f70d393b2 100644 --- a/crates/ink/codegen/src/generator/storage_item.rs +++ b/crates/ink/codegen/src/generator/storage_item.rs @@ -80,7 +80,7 @@ impl GenerateCode for StorageItem<'_> { } } -impl<'a> StorageItem<'a> { +impl StorageItem<'_> { fn generate_struct(&self, struct_item: DataStruct) -> TokenStream2 { let item = self.item; let struct_ident = item.ident(); diff --git a/crates/ink/codegen/src/generator/trait_def/call_builder.rs b/crates/ink/codegen/src/generator/trait_def/call_builder.rs index f111fb2e88b..4a604a6dc5b 100644 --- a/crates/ink/codegen/src/generator/trait_def/call_builder.rs +++ b/crates/ink/codegen/src/generator/trait_def/call_builder.rs @@ -27,7 +27,7 @@ use quote::{ quote_spanned, }; -impl<'a> TraitDefinition<'a> { +impl TraitDefinition<'_> { /// Generates code for the global trait call builder for an ink! trait. /// /// # Note @@ -58,14 +58,14 @@ impl GenerateCode for CallBuilder<'_> { let struct_definition = self.generate_struct_definition(); let storage_layout_impl = self.generate_storage_layout_impl(); let auxiliary_trait_impls = self.generate_auxiliary_trait_impls(); - let to_from_account_id_impls = self.generate_to_from_account_id_impls(); + let to_from_addr_impls = self.generate_to_from_addr_impls(); let message_builder_trait_impl = self.generate_message_builder_trait_impl(); let ink_trait_impl = self.generate_ink_trait_impl(); quote! { #struct_definition #storage_layout_impl #auxiliary_trait_impls - #to_from_account_id_impls + #to_from_addr_impls #message_builder_trait_impl #ink_trait_impl } @@ -113,7 +113,8 @@ impl CallBuilder<'_> { where E: ::ink::env::Environment, { - account_id: ::AccountId, + addr: ::ink::H160, + marker: ::core::marker::PhantomData E>, } ) } @@ -134,7 +135,7 @@ impl CallBuilder<'_> { for #call_builder_ident where E: ::ink::env::Environment, - ::AccountId: ::ink::storage::traits::StorageLayout, + ::ink::H160: ::ink::storage::traits::StorageLayout, { fn layout( __key: &::ink::primitives::Key, @@ -144,8 +145,8 @@ impl CallBuilder<'_> { ::core::stringify!(#call_builder_ident), [ ::ink::metadata::layout::FieldLayout::new( - "account_id", - <::AccountId + "addr", + <::ink::H160 as ::ink::storage::traits::StorageLayout>::layout(__key) ) ] @@ -172,12 +173,13 @@ impl CallBuilder<'_> { impl ::core::clone::Clone for #call_builder_ident where E: ::ink::env::Environment, - ::AccountId: ::core::clone::Clone, + ::ink::H160: ::core::clone::Clone, { #[inline] fn clone(&self) -> Self { Self { - account_id: ::core::clone::Clone::clone(&self.account_id), + addr: ::core::clone::Clone::clone(&self.addr), + marker: self.marker, } } } @@ -186,26 +188,27 @@ impl CallBuilder<'_> { impl ::core::fmt::Debug for #call_builder_ident where E: ::ink::env::Environment, - ::AccountId: ::core::fmt::Debug, + ::ink::H160: ::core::fmt::Debug, { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { f.debug_struct(::core::stringify!(#call_builder_ident)) - .field("account_id", &self.account_id) + .field("addr", &self.addr) .finish() } } #[cfg(feature = "std")] + // todo /// We require this manual implementation since the derive produces incorrect trait bounds. impl ::ink::scale_info::TypeInfo for #call_builder_ident where E: ::ink::env::Environment, - ::AccountId: ::ink::scale_info::TypeInfo + 'static, + ::ink::H160: ::ink::scale_info::TypeInfo + 'static, { - type Identity = ::AccountId; + type Identity = ::ink::H160; fn type_info() -> ::ink::scale_info::Type { - <::AccountId as ::ink::scale_info::TypeInfo>::type_info() + <::ink::H160 as ::ink::scale_info::TypeInfo>::type_info() } } ) @@ -218,56 +221,59 @@ impl CallBuilder<'_> { /// /// This allows user code to conveniently transform from and to `AccountId` when /// interacting with typed contracts. - fn generate_to_from_account_id_impls(&self) -> TokenStream2 { + fn generate_to_from_addr_impls(&self) -> TokenStream2 { let span = self.span(); let call_builder_ident = self.ident(); quote_spanned!(span=> - impl ::ink::env::call::FromAccountId + impl ::ink::env::call::FromAddr for #call_builder_ident where E: ::ink::env::Environment, { #[inline] - fn from_account_id(account_id: ::AccountId) -> Self { - Self { account_id } + fn from_addr(addr: ::ink::H160) -> Self { + Self { + addr, + marker: ::core::default::Default::default(), + } } } - impl ::core::convert::From for #call_builder_ident + impl ::core::convert::From<::ink::H160> for #call_builder_ident where - E: ::ink::env::Environment, - AccountId: ::ink::env::AccountIdGuard, + E: ::ink::env::Environment, + ::ink::H160: ::ink::env::AccountIdGuard, { - fn from(value: AccountId) -> Self { - >::from_account_id(value) + fn from(value: ::ink::H160) -> Self { + ::from_addr(value) } } - impl ::ink::ToAccountId for #call_builder_ident + impl ::ink::ToAddr for #call_builder_ident where E: ::ink::env::Environment, { #[inline] - fn to_account_id(&self) -> ::AccountId { - <::AccountId as ::core::clone::Clone>::clone(&self.account_id) + fn to_addr(&self) -> ::ink::H160 { + <::ink::H160 as ::core::clone::Clone>::clone(&self.addr) } } - impl ::core::convert::AsRef for #call_builder_ident + impl ::core::convert::AsRef<::ink::H160> for #call_builder_ident where - E: ::ink::env::Environment, + E: ::ink::env::Environment, { - fn as_ref(&self) -> &AccountId { - &self.account_id + fn as_ref(&self) -> &::ink::H160 { + &self.addr } } - impl ::core::convert::AsMut for #call_builder_ident + impl ::core::convert::AsMut<::ink::H160> for #call_builder_ident where - E: ::ink::env::Environment, + E: ::ink::env::Environment, { - fn as_mut(&mut self) -> &mut AccountId { - &mut self.account_id + fn as_mut(&mut self) -> &mut ::ink::H160 { + &mut self.addr } } ) @@ -279,7 +285,7 @@ impl CallBuilder<'_> { /// # Note /// /// Through the implementation of this trait it is possible to refer to the - /// ink! trait messsage builder that is associated to this ink! trait call builder. + /// ink! trait message builder that is associated to this ink! trait call builder. fn generate_message_builder_trait_impl(&self) -> TokenStream2 { let span = self.trait_def.span(); let call_builder_ident = self.ident(); @@ -373,7 +379,7 @@ impl CallBuilder<'_> { #( #cfg_attrs )* type #output_ident = ::ink::env::call::CallBuilder< Self::Env, - ::ink::env::call::utils::Set< ::ink::env::call::Call< Self::Env > >, + ::ink::env::call::utils::Set< ::ink::env::call::Call >, ::ink::env::call::utils::Set< ::ink::env::call::ExecutionInput<#arg_list> >, ::ink::env::call::utils::Set< ::ink::env::call::utils::ReturnType<#output_type> >, >; @@ -386,7 +392,7 @@ impl CallBuilder<'_> { ) -> Self::#output_ident { <::ink::env::call::CallBuilder< Self::Env, - ::ink::env::call::utils::Unset< ::ink::env::call::Call< Self::Env > >, + ::ink::env::call::utils::Unset< ::ink::env::call::Call >, ::ink::env::call::utils::Set< ::ink::env::call::ExecutionInput<#arg_list> >, ::ink::env::call::utils::Set< ::ink::env::call::utils::ReturnType<#output_type> >, > as ::core::convert::From::<_>>::from( @@ -400,7 +406,7 @@ impl CallBuilder<'_> { )* ) ) - .call(::ink::ToAccountId::to_account_id(self)) + .call(::ink::ToAddr::to_addr(self)) } ) } diff --git a/crates/ink/codegen/src/generator/trait_def/call_forwarder.rs b/crates/ink/codegen/src/generator/trait_def/call_forwarder.rs index 9904ffbb478..0dd22d3a4ac 100644 --- a/crates/ink/codegen/src/generator/trait_def/call_forwarder.rs +++ b/crates/ink/codegen/src/generator/trait_def/call_forwarder.rs @@ -27,7 +27,7 @@ use quote::{ quote_spanned, }; -impl<'a> TraitDefinition<'a> { +impl TraitDefinition<'_> { /// Generates code for the global trait call forwarder for an ink! trait. /// /// # Note @@ -59,14 +59,14 @@ impl GenerateCode for CallForwarder<'_> { let struct_definition = self.generate_struct_definition(); let storage_layout_impl = self.generate_storage_layout_impl(); let auxiliary_trait_impls = self.generate_auxiliary_trait_impls(); - let to_from_account_id_impls = self.generate_to_from_account_id_impls(); + let to_from_addr_impls = self.generate_to_from_addr_impls(); let call_builder_impl = self.generate_call_builder_trait_impl(); let ink_trait_impl = self.generate_ink_trait_impl(); quote! { #struct_definition #storage_layout_impl #auxiliary_trait_impls - #to_from_account_id_impls + #to_from_addr_impls #call_builder_impl #ink_trait_impl } @@ -136,7 +136,7 @@ impl CallForwarder<'_> { for #call_forwarder_ident where E: ::ink::env::Environment, - ::AccountId: ::ink::storage::traits::StorageLayout, + ::ink::H160: ::ink::storage::traits::StorageLayout, { fn layout( __key: &::ink::primitives::Key, @@ -164,7 +164,7 @@ impl CallForwarder<'_> { impl ::core::clone::Clone for #call_forwarder_ident where E: ::ink::env::Environment, - ::AccountId: ::core::clone::Clone, + ::ink::H160: ::core::clone::Clone, { #[inline] fn clone(&self) -> Self { @@ -179,11 +179,11 @@ impl CallForwarder<'_> { impl ::core::fmt::Debug for #call_forwarder_ident where E: ::ink::env::Environment, - ::AccountId: ::core::fmt::Debug, + ::ink::H160: ::core::fmt::Debug, { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { f.debug_struct(::core::stringify!(#call_forwarder_ident)) - .field("account_id", &self.builder.account_id) + .field("addr", &self.builder.addr) .finish() } } @@ -193,7 +193,7 @@ impl CallForwarder<'_> { impl ::ink::scale_info::TypeInfo for #call_forwarder_ident where E: ::ink::env::Environment, - ::AccountId: ::ink::scale_info::TypeInfo + 'static, + ::ink::H160: ::ink::scale_info::TypeInfo + 'static, { type Identity = < ::Builder as ::ink::scale_info::TypeInfo @@ -215,58 +215,57 @@ impl CallForwarder<'_> { /// /// This allows user code to conveniently transform from and to `AccountId` when /// interacting with typed contracts. - fn generate_to_from_account_id_impls(&self) -> TokenStream2 { + fn generate_to_from_addr_impls(&self) -> TokenStream2 { let span = self.span(); let call_forwarder_ident = self.ident(); quote_spanned!(span=> - impl ::ink::env::call::FromAccountId + impl ::ink::env::call::FromAddr for #call_forwarder_ident where E: ::ink::env::Environment, { #[inline] - fn from_account_id(account_id: ::AccountId) -> Self { + fn from_addr(addr: ::ink::H160) -> Self { Self { builder: <::Builder - as ::ink::env::call::FromAccountId>::from_account_id(account_id) } + as ::ink::env::call::FromAddr>::from_addr(addr) } } } - impl ::core::convert::From for #call_forwarder_ident + impl ::core::convert::From<::ink::H160> for #call_forwarder_ident where - E: ::ink::env::Environment, - AccountId: ::ink::env::AccountIdGuard, + E: ::ink::env::Environment, { - fn from(value: AccountId) -> Self { - >::from_account_id(value) + fn from(addr: ::ink::H160) -> Self { + ::from_addr(addr) } } - impl ::ink::ToAccountId for #call_forwarder_ident + impl ::ink::ToAddr for #call_forwarder_ident where E: ::ink::env::Environment, { #[inline] - fn to_account_id(&self) -> ::AccountId { + fn to_addr(&self) -> ::ink::H160 { <::Builder - as ::ink::ToAccountId>::to_account_id(&self.builder) + as ::ink::ToAddr>::to_addr(&self.builder) } } - impl ::core::convert::AsRef for #call_forwarder_ident + impl ::core::convert::AsRef<::ink::H160> for #call_forwarder_ident where - E: ::ink::env::Environment, + E: ::ink::env::Environment, { - fn as_ref(&self) -> &AccountId { - <_ as ::core::convert::AsRef>::as_ref(&self.builder) + fn as_ref(&self) -> &::ink::H160 { + <_ as ::core::convert::AsRef<::ink::H160>>::as_ref(&self.builder) } } - impl ::core::convert::AsMut for #call_forwarder_ident + impl ::core::convert::AsMut<::ink::H160> for #call_forwarder_ident where - E: ::ink::env::Environment, + E: ::ink::env::Environment, { - fn as_mut(&mut self) -> &mut AccountId { - <_ as ::core::convert::AsMut>::as_mut(&mut self.builder) + fn as_mut(&mut self) -> &mut ::ink::H160 { + <_ as ::core::convert::AsMut<::ink::H160>>::as_mut(&mut self.builder) } } ) diff --git a/crates/ink/codegen/src/generator/trait_def/definition.rs b/crates/ink/codegen/src/generator/trait_def/definition.rs index 9ea66e1f65b..9b256e267dd 100644 --- a/crates/ink/codegen/src/generator/trait_def/definition.rs +++ b/crates/ink/codegen/src/generator/trait_def/definition.rs @@ -23,8 +23,8 @@ use quote::{ quote_spanned, }; -impl<'a> TraitDefinition<'a> { - fn generate_for_message(message: ir::InkTraitMessage<'a>) -> TokenStream2 { +impl TraitDefinition<'_> { + fn generate_for_message(message: ir::InkTraitMessage<'_>) -> TokenStream2 { let span = message.span(); let attrs = message.attrs(); let sig = message.sig(); diff --git a/crates/ink/codegen/src/generator/trait_def/message_builder.rs b/crates/ink/codegen/src/generator/trait_def/message_builder.rs index 1864e8aab1a..4547dc60204 100644 --- a/crates/ink/codegen/src/generator/trait_def/message_builder.rs +++ b/crates/ink/codegen/src/generator/trait_def/message_builder.rs @@ -27,7 +27,7 @@ use quote::{ quote_spanned, }; -impl<'a> TraitDefinition<'a> { +impl TraitDefinition<'_> { /// Generates code for the global trait call builder for an ink! trait. /// /// # Note diff --git a/crates/ink/codegen/src/generator/trait_def/mod.rs b/crates/ink/codegen/src/generator/trait_def/mod.rs index 378ad3d258c..449b6e54163 100644 --- a/crates/ink/codegen/src/generator/trait_def/mod.rs +++ b/crates/ink/codegen/src/generator/trait_def/mod.rs @@ -35,7 +35,7 @@ pub struct TraitDefinition<'a> { trait_def: &'a ir::InkTraitDefinition, } -impl<'a> TraitDefinition<'a> { +impl TraitDefinition<'_> { /// Appends the trait suffix to the string and forms an identifier. /// /// This appends the `_$NAME_$TRAIT_ID` string to the prefix string diff --git a/crates/ink/codegen/src/generator/trait_def/trait_registry.rs b/crates/ink/codegen/src/generator/trait_def/trait_registry.rs index 51fc821cf59..de4c597261b 100644 --- a/crates/ink/codegen/src/generator/trait_def/trait_registry.rs +++ b/crates/ink/codegen/src/generator/trait_def/trait_registry.rs @@ -40,7 +40,7 @@ use syn::{ spanned::Spanned, }; -impl<'a> TraitDefinition<'a> { +impl TraitDefinition<'_> { /// Generates the code for the global trait registry implementation. /// /// This also generates the code for the global trait info object which diff --git a/crates/ink/ir/src/ir/item_impl/callable.rs b/crates/ink/ir/src/ir/item_impl/callable.rs index ea10d9230b9..9391c6809df 100644 --- a/crates/ink/ir/src/ir/item_impl/callable.rs +++ b/crates/ink/ir/src/ir/item_impl/callable.rs @@ -92,7 +92,7 @@ impl<'a, C> CallableWithSelector<'a, C> { } } -impl<'a, C> Callable for CallableWithSelector<'a, C> +impl Callable for CallableWithSelector<'_, C> where C: Callable, { @@ -141,7 +141,7 @@ where } } -impl<'a, C> ::core::ops::Deref for CallableWithSelector<'a, C> { +impl ::core::ops::Deref for CallableWithSelector<'_, C> { type Target = C; fn deref(&self) -> &Self::Target { @@ -539,7 +539,7 @@ impl<'a> Iterator for InputsIter<'a> { } } -impl<'a> ExactSizeIterator for InputsIter<'a> { +impl ExactSizeIterator for InputsIter<'_> { fn len(&self) -> usize { self.iter.len() } diff --git a/crates/ink/ir/src/ir/item_impl/impl_item.rs b/crates/ink/ir/src/ir/item_impl/impl_item.rs index 7727bc55131..5110663d55b 100644 --- a/crates/ink/ir/src/ir/item_impl/impl_item.rs +++ b/crates/ink/ir/src/ir/item_impl/impl_item.rs @@ -70,12 +70,10 @@ impl TryFrom for ImplItem { match attr.first().kind() { ir::AttributeArg::Message => { >::try_from(fn_item) - .map(Into::into) .map(Self::Message) } ir::AttributeArg::Constructor => { >::try_from(fn_item) - .map(Into::into) .map(Self::Constructor) } _ => Err(format_err_spanned!( diff --git a/crates/ink/ir/src/ir/item_mod.rs b/crates/ink/ir/src/ir/item_mod.rs index 865bd2f8aee..8bf1fe36d84 100644 --- a/crates/ink/ir/src/ir/item_mod.rs +++ b/crates/ink/ir/src/ir/item_mod.rs @@ -1299,7 +1299,6 @@ mod tests { pub fn my_constructor() -> Self {} #[ink(message)] - #[cfg(feature = "foo")] pub fn not_allowed(&self) {} } } diff --git a/crates/ink/ir/src/ir/utils.rs b/crates/ink/ir/src/ir/utils.rs index 5854dbfdb9a..0c84742b5e9 100644 --- a/crates/ink/ir/src/ir/utils.rs +++ b/crates/ink/ir/src/ir/utils.rs @@ -92,7 +92,7 @@ impl WhitelistedAttributes { /// a correct format `"foo, bar"` then `foo`, `bar` will be included in /// the whitelist of attributes. Else error about parsing will be returned. pub fn parse_arg_value(&mut self, arg: &MetaNameValue) -> Result<(), syn::Error> { - return if let ast::MetaValue::Lit(syn::Lit::Str(attributes)) = &arg.value { + if let ast::MetaValue::Lit(syn::Lit::Str(attributes)) = &arg.value { attributes.value().split(',').for_each(|attribute| { self.0.insert(attribute.trim().to_string(), ()); }); diff --git a/crates/ink/macro/Cargo.toml b/crates/ink/macro/Cargo.toml index 6adc487305c..6593700aaf8 100644 --- a/crates/ink/macro/Cargo.toml +++ b/crates/ink/macro/Cargo.toml @@ -47,9 +47,10 @@ std = [ "scale-info/std", "ink_codegen/std", ] -revive = [ - "ink/revive", - "ink_env/revive", - "ink_codegen/revive", - "ink_storage/revive" + +# For the ui tests, which use this `Cargo.toml` +[lints.rust.unexpected_cfgs] +level = "warn" +check-cfg = [ + 'cfg(feature, values(any()))', ] diff --git a/crates/ink/macro/src/event/mod.rs b/crates/ink/macro/src/event/mod.rs index 7a7d53266a5..7c9fafe1749 100644 --- a/crates/ink/macro/src/event/mod.rs +++ b/crates/ink/macro/src/event/mod.rs @@ -136,6 +136,7 @@ pub fn event_derive(mut s: synstructure::Structure) -> TokenStream2 { } /// `Event` derive implementation for `struct` types. +#[allow(clippy::arithmetic_side_effects)] // todo fn event_derive_struct(mut s: synstructure::Structure) -> syn::Result { assert_eq!(s.variants().len(), 1, "can only operate on structs"); diff --git a/crates/ink/macro/src/lib.rs b/crates/ink/macro/src/lib.rs index b180506e5b1..ff967e3de94 100644 --- a/crates/ink/macro/src/lib.rs +++ b/crates/ink/macro/src/lib.rs @@ -171,6 +171,7 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// type Timestamp = u64; /// type BlockNumber = u32; /// type ChainExtension = ::ink::env::NoChainExtension; +/// type EventRecord = (); /// } /// ``` /// A user might implement their ink! smart contract using the above custom @@ -189,6 +190,7 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// # type Timestamp = u64; /// # type BlockNumber = u32; /// # type ChainExtension = ::ink::env::NoChainExtension; +/// # type EventRecord = (); /// # } /// # /// # #[ink(storage)] @@ -398,7 +400,7 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// For example it is possible to query the current call's caller via: /// ``` /// # ink_env::test::run_test::(|_| { -/// let caller = ink_env::caller::(); +/// let caller = ink_env::caller(); /// # let _caller = caller; /// # Ok(()) /// # }).unwrap(); @@ -445,23 +447,28 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// ``` /// #[ink::contract] /// mod erc20 { +/// use ink::{ +/// H160, +/// U256, +/// }; +/// /// /// Defines an event that is emitted every time value is transferred. /// #[ink(event)] /// pub struct Transferred { -/// from: Option, -/// to: Option, -/// value: Balance, +/// from: Option, +/// to: Option, +/// value: U256, /// } /// /// #[ink(storage)] /// pub struct Erc20 { -/// total_supply: Balance, +/// total_supply: U256, /// // more fields... /// } /// /// impl Erc20 { /// #[ink(constructor)] -/// pub fn new(initial_supply: Balance) -> Self { +/// pub fn new(initial_supply: U256) -> Self { /// let caller = Self::env().caller(); /// Self::env().emit_event(Transferred { /// from: None, @@ -474,7 +481,7 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// } /// /// #[ink(message)] -/// pub fn total_supply(&self) -> Balance { +/// pub fn total_supply(&self) -> U256 { /// self.total_supply /// } /// } @@ -538,18 +545,15 @@ pub fn contract(attr: TokenStream, item: TokenStream) -> TokenStream { /// # Trait definition: /// /// ``` -/// # type Balance = ::Balance; -/// # type AccountId = ::AccountId; -/// /// #[ink::trait_definition] /// pub trait Erc20 { /// /// Returns the total supply of the ERC-20 smart contract. /// #[ink(message)] -/// fn total_supply(&self) -> Balance; +/// fn total_supply(&self) -> ink::U256; /// /// /// Transfers balance from the caller to the given address. /// #[ink(message)] -/// fn transfer(&mut self, amount: Balance, to: AccountId) -> bool; +/// fn transfer(&mut self, amount: ink::U256, to: ink::H160) -> bool; /// /// // etc. /// } @@ -562,26 +566,27 @@ pub fn contract(attr: TokenStream, item: TokenStream) -> TokenStream { /// ``` /// #[ink::contract] /// mod base_erc20 { +/// use ink::{H160, U256}; /// # // We somehow cannot put the trait in the doc-test crate root due to bugs. /// # #[ink::trait_definition] /// # pub trait Erc20 { /// # /// Returns the total supply of the ERC-20 smart contract. /// # #[ink(message)] -/// # fn total_supply(&self) -> Balance; +/// # fn total_supply(&self) -> U256; /// # /// # /// Transfers balance from the caller to the given address. /// # #[ink(message)] -/// # fn transfer(&mut self, amount: Balance, to: AccountId) -> bool; +/// # fn transfer(&mut self, amount: U256, to: H160) -> bool; /// # } /// # /// #[ink(storage)] /// pub struct BaseErc20 { -/// total_supply: Balance, +/// total_supply: U256, /// } /// /// impl BaseErc20 { /// #[ink(constructor)] -/// pub fn new(initial_supply: Balance) -> Self { +/// pub fn new(initial_supply: U256) -> Self { /// Self { total_supply: initial_supply } /// } /// } @@ -589,12 +594,12 @@ pub fn contract(attr: TokenStream, item: TokenStream) -> TokenStream { /// impl Erc20 for BaseErc20 { /// /// Returns the total supply of the ERC-20 smart contract. /// #[ink(message)] -/// fn total_supply(&self) -> Balance { +/// fn total_supply(&self) -> U256 { /// self.total_supply /// } /// /// #[ink(message)] -/// fn transfer(&mut self, amount: Balance, to: AccountId) -> bool { +/// fn transfer(&mut self, amount: U256, to: H160) -> bool { /// unimplemented!() /// } /// } @@ -1180,6 +1185,7 @@ pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream { /// type Hash = ::Hash; /// type BlockNumber = ::BlockNumber; /// type Timestamp = ::Timestamp; +/// type EventRecord = ::EventRecord; /// /// type ChainExtension = RuntimeReadWrite; /// } @@ -1321,6 +1327,7 @@ pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream { /// # type Hash = ::Hash; /// # type BlockNumber = ::BlockNumber; /// # type Timestamp = ::Timestamp; +/// # type EventRecord = ::EventRecord; /// # /// # type ChainExtension = RuntimeReadWrite; /// # } diff --git a/crates/ink/src/codegen/dispatch/execution.rs b/crates/ink/src/codegen/dispatch/execution.rs index 17b9ed5b334..46629951221 100644 --- a/crates/ink/src/codegen/dispatch/execution.rs +++ b/crates/ink/src/codegen/dispatch/execution.rs @@ -14,6 +14,7 @@ use crate::reflect::DispatchError; use ink_env::Environment; +use ink_primitives::U256; /// Returns `Ok` if the caller did not transfer additional value to the callee. /// @@ -21,12 +22,14 @@ use ink_env::Environment; /// /// If the caller did send some amount of transferred value to the callee. #[inline] +// todo remove E pub fn deny_payment() -> Result<(), DispatchError> where E: Environment, { - let transferred = ink_env::transferred_value::(); - if transferred != ::Balance::from(0_u32) { + // todo + let transferred = ink_env::transferred_value(); + if transferred != U256::zero() { return Err(DispatchError::PaidUnpayableMessage) } Ok(()) diff --git a/crates/ink/src/contract_ref.rs b/crates/ink/src/contract_ref.rs index 2af96cedd2c..10bfdefa6ee 100644 --- a/crates/ink/src/contract_ref.rs +++ b/crates/ink/src/contract_ref.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use ink_env::Environment; +use ink_primitives::H160; /// Generates a wrapper which can be used for interacting with the contract. /// @@ -30,17 +30,21 @@ use ink_env::Environment; /// ```rust /// #[ink::contract] /// mod trait_caller { -/// use ink::contract_ref; +/// use ink::{ +/// contract_ref, +/// H160, +/// U256, +/// }; /// /// #[ink::trait_definition] /// pub trait Erc20 { /// /// Returns the total supply of the ERC-20 smart contract. /// #[ink(message)] -/// fn total_supply(&self) -> Balance; +/// fn total_supply(&self) -> U256; /// /// /// Transfers balance from the caller to the given address. /// #[ink(message)] -/// fn transfer(&mut self, amount: Balance, to: AccountId) -> bool; +/// fn transfer(&mut self, amount: U256, to: H160) -> bool; /// } /// /// #[ink(storage)] @@ -58,20 +62,20 @@ use ink_env::Environment; /// /// /// Example of converting `AccountId` into `contract_ref!` implicitly. /// #[ink(message)] -/// pub fn change_account_id_1(&mut self, new_erc20: AccountId) { +/// pub fn change_account_id_1(&mut self, new_erc20: H160) { /// self.erc20 = new_erc20.into(); /// } /// /// /// Example of converting `AccountId` into `contract_ref!` explicitly. /// #[ink(message)] -/// pub fn change_account_id_2(&mut self, new_erc20: AccountId) { +/// pub fn change_account_id_2(&mut self, new_erc20: H160) { /// let erc20: contract_ref!(Erc20) = new_erc20.into(); /// self.erc20 = erc20; /// } /// /// /// Example of converting `AccountId` into an alias from `contract_ref!`. /// #[ink(message)] -/// pub fn change_account_id_3(&mut self, new_erc20: AccountId) { +/// pub fn change_account_id_3(&mut self, new_erc20: H160) { /// type Erc20Wrapper = contract_ref!(Erc20); /// let erc20: Erc20Wrapper = new_erc20.into(); /// self.erc20 = erc20; @@ -79,29 +83,32 @@ use ink_env::Environment; /// /// /// Example of how to do common calls via fully qualified syntax. /// #[ink(message)] -/// pub fn total_supply_1(&self) -> Balance { +/// pub fn total_supply_1(&self) -> U256 { /// Erc20::total_supply(&self.erc20) /// } /// /// /// Example of how to do common calls without fully qualified syntax. /// #[ink(message)] -/// pub fn total_supply_2(&self) -> Balance { +/// pub fn total_supply_2(&self) -> U256 { /// self.erc20.total_supply() /// } /// /// /// Example of how to use the call builder with `contract_ref!`. /// #[ink(message)] -/// pub fn total_supply_3(&self) -> Balance { +/// pub fn total_supply_3(&self) -> U256 { /// use ink::codegen::TraitCallBuilder; /// // Returns the `CallBuilder` that implements `Erc20` trait. /// let erc20_builder = self.erc20.call(); -/// erc20_builder.total_supply().transferred_value(0).invoke() +/// erc20_builder +/// .total_supply() +/// .transferred_value(U256::from(0)) +/// .invoke() /// } /// /// /// Example of how to do common calls and convert /// /// the `contract_ref!` into `AccountId`. /// #[ink(message)] -/// pub fn transfer_to_erc20(&mut self, amount: Balance) -> bool { +/// pub fn transfer_to_erc20(&mut self, amount: U256) -> bool { /// let erc20_as_account_id = self.erc20.as_ref().clone(); /// self.erc20.transfer(amount, erc20_as_account_id) /// } @@ -120,7 +127,7 @@ use ink_env::Environment; /// ```rust /// use ink::contract_ref; /// use ink_env::DefaultEnvironment; -/// use ink_primitives::AccountId; +/// use ink_primitives::H160; /// /// #[ink::trait_definition] /// pub trait Erc20 { @@ -130,7 +137,7 @@ use ink_env::Environment; /// /// /// Transfers balance from the caller to the given address. /// #[ink(message)] -/// fn transfer(&mut self, amount: u128, to: AccountId) -> bool; +/// fn transfer(&mut self, amount: u128, to: H160) -> bool; /// } /// /// #[derive(Clone)] @@ -144,6 +151,7 @@ use ink_env::Environment; /// type Timestamp = u64; /// type BlockNumber = u64; /// type ChainExtension = (); +/// type EventRecord = (); /// } /// /// type AliasWithDefaultEnv = contract_ref!(Erc20, DefaultEnvironment); @@ -152,7 +160,7 @@ use ink_env::Environment; /// /// fn default(mut contract: contract_ref!(Erc20, DefaultEnvironment)) { /// let total_supply = contract.total_supply(); -/// let to: AccountId = contract.as_ref().clone(); +/// let to: H160 = contract.as_ref().clone(); /// contract.transfer(total_supply, to); /// } /// @@ -162,8 +170,7 @@ use ink_env::Environment; /// /// fn custom(mut contract: contract_ref!(Erc20, CustomEnv)) { /// let total_supply = contract.total_supply(); -/// let to: [u8; 32] = contract.as_ref().clone(); -/// contract.transfer(total_supply, to.into()); +/// contract.transfer(total_supply, contract.as_ref().clone()); /// } /// /// fn custom_alias(mut contract: AliasWithCustomEnv) { @@ -173,7 +180,7 @@ use ink_env::Environment; /// fn generic(mut contract: contract_ref!(Erc20, E)) /// where /// E: ink_env::Environment, -/// A: Into + Clone, +/// A: Into + Clone, /// { /// let total_supply = contract.total_supply(); /// let to = contract.as_ref().clone(); @@ -183,7 +190,7 @@ use ink_env::Environment; /// fn generic_alias(mut contract: AliasWithGenericEnv) /// where /// E: ink_env::Environment, -/// A: Into + Clone, +/// A: Into + Clone, /// { /// generic(contract) /// } @@ -192,7 +199,7 @@ use ink_env::Environment; /// /// fn contract_ref_default_behaviour(mut contract: contract_ref!(Erc20)) { /// let total_supply = contract.total_supply(); -/// let to: AccountId = contract.as_ref().clone(); +/// let to: H160 = contract.as_ref().clone(); /// contract.transfer(total_supply, to); /// } /// ``` @@ -209,13 +216,11 @@ macro_rules! contract_ref { }; } +// todo remove FromAccountId + ToAccountId /// Implemented by contracts that are compiled as dependencies. /// /// Allows them to return their underlying account identifier. -pub trait ToAccountId -where - T: Environment, -{ +pub trait ToAddr { /// Returns the underlying account identifier of the instantiated contract. - fn to_account_id(&self) -> ::AccountId; + fn to_addr(&self) -> H160; } diff --git a/crates/ink/src/env_access.rs b/crates/ink/src/env_access.rs index e1067b93116..5d4b52e4c4f 100644 --- a/crates/ink/src/env_access.rs +++ b/crates/ink/src/env_access.rs @@ -14,11 +14,6 @@ use crate::ChainExtensionInstance; use core::marker::PhantomData; -#[cfg(not(feature = "revive"))] -use ink_env::call::{ - CallV1, - LimitParamsV1, -}; use ink_env::{ call::{ Call, @@ -26,7 +21,7 @@ use ink_env::{ ConstructorReturnType, CreateParams, DelegateCall, - FromAccountId, + FromAddr, LimitParamsV2, }, hash::{ @@ -36,22 +31,24 @@ use ink_env::{ Environment, Result, }; -#[cfg(not(feature = "revive"))] -use pallet_contracts_uapi::ReturnErrorCode; -#[cfg(feature = "revive")] +use ink_primitives::{ + H160, + H256, + U256, +}; use pallet_revive_uapi::ReturnErrorCode; /// The API behind the `self.env()` and `Self::env()` syntax in ink!. /// /// This allows ink! messages to make use of the environment efficiently -/// and user friendly while also maintaining access invariants. +/// and user-friendly while also maintaining access invariants. #[derive(Copy, Clone)] pub struct EnvAccess<'a, E> { /// Tricks the Rust compiler into thinking that we use `E`. marker: PhantomData &'a E>, } -impl<'a, E> Default for EnvAccess<'a, E> { +impl Default for EnvAccess<'_, E> { #[inline] fn default() -> Self { Self { @@ -60,13 +57,13 @@ impl<'a, E> Default for EnvAccess<'a, E> { } } -impl<'a, E> core::fmt::Debug for EnvAccess<'a, E> { +impl core::fmt::Debug for EnvAccess<'_, E> { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { f.debug_struct("EnvAccess").finish() } } -impl<'a, E> EnvAccess<'a, E> +impl EnvAccess<'_, E> where E: Environment, ::ChainExtension: ChainExtensionInstance, @@ -79,7 +76,7 @@ where } } -impl<'a, E> EnvAccess<'a, E> +impl EnvAccess<'_, E> where E: Environment, { @@ -112,8 +109,8 @@ where /// # Note /// /// For more details visit: [`ink_env::caller`] - pub fn caller(self) -> E::AccountId { - ink_env::caller::() + pub fn caller(self) -> H160 { + ink_env::caller() } /// Returns the transferred value for the contract execution. @@ -151,8 +148,8 @@ where /// # Note /// /// For more details visit: [`ink_env::transferred_value`] - pub fn transferred_value(self) -> E::Balance { - ink_env::transferred_value::() + pub fn transferred_value(self) -> U256 { + ink_env::transferred_value() } /// Returns the price for the specified amount of gas. @@ -171,19 +168,22 @@ where /// # Self {} /// # } /// # - /// /// Returns a tuple of - /// /// - the result of adding the `rhs` to the `lhs` - /// /// - the gas costs of this addition operation - /// /// - the price for the gas /// #[ink(message)] - /// pub fn addition_gas_cost(&self, rhs: i32, lhs: i32) -> (i32, u64, Balance) { - /// let before = self.env().gas_left(); - /// let result = rhs + lhs; - /// let after = self.env().gas_left(); - /// let gas_used = after - before; - /// let gas_cost = self.env().weight_to_fee(gas_used); - /// (result, gas_used, gas_cost) - /// } + /// pub fn foo(&self) {} + /// + /// // /// Returns a tuple of + /// // /// - the result of adding the `rhs` to the `lhs` + /// // /// - the gas costs of this addition operation + /// // /// - the price for the gas + /// // #[ink(message)] + /// // pub fn addition_gas_cost(&self, rhs: i32, lhs: i32) -> (i32, u64, Balance) { + /// // let before = self.env().gas_left(); + /// // let result = rhs + lhs; + /// // let after = self.env().gas_left(); + /// // let gas_used = after - before; + /// // let gas_cost = self.env().weight_to_fee(gas_used); + /// // (result, gas_used, gas_cost) + /// //} /// # /// # } /// # } @@ -192,49 +192,11 @@ where /// # Note /// /// For more details visit: [`ink_env::weight_to_fee`] + /// todo: there is now also `gas_price` pub fn weight_to_fee(self, gas: u64) -> E::Balance { ink_env::weight_to_fee::(gas) } - /// Returns the amount of gas left for the contract execution. - /// - /// # Example - /// - /// ``` - /// # #[ink::contract] - /// # pub mod my_contract { - /// # #[ink(storage)] - /// # pub struct MyContract { } - /// # - /// # impl MyContract { - /// # #[ink(constructor)] - /// # pub fn new() -> Self { - /// # Self {} - /// # } - /// # - /// /// Returns a tuple of - /// /// - the result of adding the `rhs` to the `lhs` and - /// /// - the gas used for this addition operation. - /// #[ink(message)] - /// pub fn addition_gas_cost(&self, rhs: i32, lhs: i32) -> (i32, u64) { - /// let before = self.env().gas_left(); - /// let result = rhs + lhs; - /// let after = self.env().gas_left(); - /// (result, after - before) - /// } - /// # - /// # } - /// # } - /// ``` - /// - /// # Note - /// - /// For more details visit: [`ink_env::gas_left`] - #[cfg(not(feature = "revive"))] - pub fn gas_left(self) -> u64 { - ink_env::gas_left::() - } - /// Returns the timestamp of the current block. /// /// # Example @@ -279,12 +241,13 @@ where /// /// # Example /// + /// todo this code example doesn't use `account_id()`. /// ``` /// #[ink::contract] /// pub mod only_owner { /// #[ink(storage)] /// pub struct OnlyOwner { - /// owner: AccountId, + /// owner: ink::H160, /// value: u32, /// } /// @@ -319,6 +282,13 @@ where ink_env::account_id::() } + /// Returns the address of the executed contract. + /// + /// For more details visit: [`ink_env::address`] + pub fn address(self) -> H160 { + ink_env::address() + } + /// Returns the balance of the executed contract. /// /// # Example @@ -337,7 +307,7 @@ where /// # /// /// Returns the contract's balance. /// #[ink(message)] - /// pub fn my_balance(&self) -> Balance { + /// pub fn my_balance(&self) -> ink::U256 { /// self.env().balance() /// } /// # @@ -348,8 +318,8 @@ where /// # Note /// /// For more details visit: [`ink_env::balance`] - pub fn balance(self) -> E::Balance { - ink_env::balance::() + pub fn balance(self) -> U256 { + ink_env::balance() } /// Returns the current block number. @@ -470,18 +440,18 @@ where /// #[ink(message)] /// pub fn instantiate_contract(&self) -> MyContractRef { /// let create_params = build_create::() - /// .code_hash(Hash::from([0x42; 32])) + /// .code_hash(ink::H256::from([0x42; 32])) /// .ref_time_limit(500_000_000) /// .proof_size_limit(100_000) - /// .storage_deposit_limit(500_000_000_000) - /// .endowment(25) + /// .storage_deposit_limit(ink::U256::from(500_000_000_000u64)) + /// .endowment(25.into()) /// .exec_input( /// ExecutionInput::new(Selector::new(ink::selector_bytes!("new"))) /// .push_arg(42) /// .push_arg(true) /// .push_arg(&[0x10u8; 32]), /// ) - /// .salt_bytes(&[0xCA, 0xFE, 0xBA, 0xBE]) + /// .salt_bytes(Some([0x13; 32])) /// .returns::() /// .params(); /// self.env() @@ -505,114 +475,22 @@ where /// # Note /// /// For more details visit: [`ink_env::instantiate_contract`] - pub fn instantiate_contract( + pub fn instantiate_contract( self, - params: &CreateParams, Args, Salt, R>, + params: &CreateParams, ) -> Result< ink_primitives::ConstructorResult< >::Output, >, > where - ContractRef: FromAccountId + ink_env::ContractReverseReference, + ContractRef: FromAddr + ink_env::ContractReverseReference, ::Type: ink_env::reflect::ContractConstructorDecoder, Args: scale::Encode, - Salt: AsRef<[u8]>, R: ConstructorReturnType, { - ink_env::instantiate_contract::(params) - } - - /// Instantiates another contract using the supplied code hash. - /// - /// # Example - /// - /// ``` - /// # #[ink::contract] - /// # pub mod my_contract { - /// # // In order for this to actually work with another contract we'd need a way - /// # // to turn the `ink-as-dependency` crate feature on in doctests, which we - /// # // can't do. - /// # // - /// # // Instead we use our own contract's `Ref`, which is fine for this example - /// # // (just need something that implements the `ContractRef` trait). - /// # pub mod other_contract { - /// # pub use super::MyContractRef as OtherContractRef; - /// # } - /// use ink::env::{ - /// DefaultEnvironment, - /// call::{build_create, Selector, ExecutionInput} - /// }; - /// use other_contract::OtherContractRef; - /// # - /// # #[ink(storage)] - /// # pub struct MyContract { } - /// # - /// # impl MyContract { - /// # #[ink(constructor)] - /// # pub fn new() -> Self { - /// # Self {} - /// # } - /// # - /// - /// /// Instantiates another contract. - /// #[ink(message)] - /// pub fn instantiate_contract(&self) -> MyContractRef { - /// let create_params = build_create::() - /// .instantiate_v1() - /// .code_hash(Hash::from([0x42; 32])) - /// .gas_limit(500_000_000) - /// .endowment(25) - /// .exec_input( - /// ExecutionInput::new(Selector::new(ink::selector_bytes!("new"))) - /// .push_arg(42) - /// .push_arg(true) - /// .push_arg(&[0x10u8; 32]), - /// ) - /// .salt_bytes(&[0xCA, 0xFE, 0xBA, 0xBE]) - /// .returns::() - /// .params(); - /// self.env() - /// .instantiate_contract_v1(&create_params) - /// .unwrap_or_else(|error| { - /// panic!( - /// "Received an error from the Contracts pallet while instantiating: {:?}", - /// error - /// ) - /// }) - /// .unwrap_or_else(|error| panic!("Received a `LangError` while instatiating: {:?}", error)) - /// } - /// # - /// # } - /// # } - /// ``` - /// - /// See [our `delegator` example](https://github.com/use-ink/ink-examples/tree/main/upgradeable-contracts#delegator) - /// for a complete contract example. - /// - /// # Note - /// - /// For more details visit: [`ink_env::instantiate_contract_v1`] - - #[cfg(not(feature = "revive"))] - pub fn instantiate_contract_v1( - self, - params: &CreateParams, - ) -> Result< - ink_primitives::ConstructorResult< - >::Output, - >, - > - where - ContractRef: FromAccountId + ink_env::ContractReverseReference, - ::Type: - ink_env::reflect::ContractConstructorDecoder, - Args: scale::Encode, - Salt: AsRef<[u8]>, - R: ConstructorReturnType, - { - ink_env::instantiate_contract_v1::(params) + ink_env::instantiate_contract::(params) } /// Invokes a contract message and returns its result. @@ -625,7 +503,6 @@ where /// use ink::env::{ /// call::{ /// build_call, - /// CallV1, /// ExecutionInput, /// Selector, /// }, @@ -646,82 +523,10 @@ where /// #[ink(message)] /// pub fn invoke_contract(&self) -> i32 { /// let call_params = build_call::() - /// .call_type( - /// CallV1::new(AccountId::from([0x42; 32])) - /// .gas_limit(5000) - /// .transferred_value(10), - /// ) - /// .exec_input( - /// ExecutionInput::new(Selector::new([0xCA, 0xFE, 0xBA, 0xBE])) - /// .push_arg(42u8) - /// .push_arg(true) - /// .push_arg(&[0x10u8; 32]), - /// ) - /// .returns::() - /// .params(); - /// - /// self.env() - /// .invoke_contract_v1(&call_params) - /// .unwrap_or_else(|env_err| { - /// panic!("Received an error from the Environment: {:?}", env_err) - /// }) - /// .unwrap_or_else(|lang_err| panic!("Received a `LangError`: {:?}", lang_err)) - /// } - /// # - /// # } - /// # } - /// ``` - /// - /// # Note - /// - /// For more details visit: [`ink_env::invoke_contract_v1`] - #[cfg(not(feature = "revive"))] - pub fn invoke_contract_v1( - self, - params: &CallParams, Args, R>, - ) -> Result> - where - Args: scale::Encode, - R: scale::Decode, - { - ink_env::invoke_contract_v1::(params) - } - - /// Invokes a contract message and returns its result. - /// - /// # Example - /// - /// ``` - /// # #[ink::contract] - /// # pub mod my_contract { - /// use ink::env::{ - /// call::{ - /// build_call, - /// CallV1, - /// ExecutionInput, - /// Selector, - /// }, - /// DefaultEnvironment, - /// }; - /// - /// # - /// # #[ink(storage)] - /// # pub struct MyContract { } - /// # - /// # impl MyContract { - /// # #[ink(constructor)] - /// # pub fn new() -> Self { - /// # Self {} - /// # } - /// # - /// /// Invokes a contract message and fetches the result. - /// #[ink(message)] - /// pub fn invoke_contract_v2(&self) -> i32 { - /// let call_params = build_call::() - /// .call(AccountId::from([0x42; 32])) + /// .call(ink::H160::from([0x42; 20])) /// .ref_time_limit(500_000_000) /// .proof_size_limit(100_000) - /// .storage_deposit_limit(1_000_000_000) + /// .storage_deposit_limit(1_000_000_000.into()) /// .exec_input( /// ExecutionInput::new(Selector::new([0xCA, 0xFE, 0xBA, 0xBE])) /// .push_arg(42u8) @@ -748,7 +553,7 @@ where /// For more details visit: [`ink_env::invoke_contract`] pub fn invoke_contract( self, - params: &CallParams, Args, R>, + params: &CallParams, ) -> Result> where Args: scale::Encode, @@ -790,9 +595,7 @@ where /// #[ink(message)] /// pub fn invoke_contract_delegate(&self) -> i32 { /// let call_params = build_call::() - /// .call_type(DelegateCall::new( - /// ::Hash::CLEAR_HASH, - /// )) + /// .call_type(DelegateCall::new(ink::H160::zero())) /// .exec_input( /// ExecutionInput::new(Selector::new([0xCA, 0xFE, 0xBA, 0xBE])) /// .push_arg(42u8) @@ -818,7 +621,7 @@ where /// For more details visit: [`ink_env::invoke_contract_delegate`] pub fn invoke_contract_delegate( self, - params: &CallParams, Args, R>, + params: &CallParams, ) -> Result> where Args: scale::Encode, @@ -846,6 +649,7 @@ where /// /// Terminates with the caller as beneficiary. /// #[ink(message)] /// pub fn terminate_me(&mut self) { + /// // todo check this example. if caller returns origin it's no longer possible. /// self.env().terminate_contract(self.env().caller()); /// } /// # @@ -856,43 +660,44 @@ where /// # Note /// /// For more details visit: [`ink_env::terminate_contract`] - pub fn terminate_contract(self, beneficiary: E::AccountId) -> ! { - ink_env::terminate_contract::(beneficiary) + pub fn terminate_contract(self, beneficiary: H160) -> ! { + ink_env::terminate_contract(beneficiary) } - /// Transfers value from the contract to the destination account ID. - /// - /// # Example - /// - /// ``` - /// # #[ink::contract] - /// # pub mod my_contract { - /// # #[ink(storage)] - /// # pub struct MyContract { } - /// # - /// # impl MyContract { - /// # #[ink(constructor)] - /// # pub fn new() -> Self { - /// # Self {} - /// # } - /// # - /// /// Transfers the token amount ten to the caller. - /// #[ink(message)] - /// pub fn give_me_ten(&mut self) { - /// let value: Balance = 10; - /// self.env() - /// .transfer(self.env().caller(), value) - /// .unwrap_or_else(|err| panic!("transfer failed: {:?}", err)); - /// } - /// # - /// # } - /// # } - /// ``` - /// - /// # Note - /// - /// For more details visit: [`ink_env::transfer`] - pub fn transfer(self, destination: E::AccountId, value: E::Balance) -> Result<()> { + // Transfers value from the current contract to the destination contract. + // + // # Example + // + // ``` + // # #[ink::contract] + // # pub mod my_contract { + // # #[ink(storage)] + // # pub struct MyContract { } + // # + // # impl MyContract { + // # #[ink(constructor)] + // # pub fn new() -> Self { + // # Self {} + // # } + // # + // /// Transfers the token amount ten to the caller. + // #[ink(message)] + // pub fn give_me_ten(&mut self) { + // let value: Balance = 10; + // self.env() + // .transfer(self.env().caller(), value) + // .unwrap_or_else(|err| panic!("transfer failed: {:?}", err)); + // } + // # + // # } + // # } + // ``` + // + // # Note + // + // For more details visit: [`ink_env::transfer`] + pub fn transfer(self, destination: H160, value: U256) -> Result<()> { + // todo remove E ink_env::transfer::(destination, value) } @@ -1116,6 +921,7 @@ where /// /// For more details visit: [`ink_env::sr25519_verify`] /// + /// todo /// **WARNING**: this function is from the [unstable interface](https://github.com/paritytech/substrate/tree/master/frame/contracts#unstable-interfaces), /// which is unsafe and normally is not available on production chains. pub fn sr25519_verify( @@ -1128,7 +934,8 @@ where .map_err(|_| ReturnErrorCode::Sr25519VerifyFailed.into()) } - /// Checks whether a specified account belongs to a contract. + /// Checks whether a contract lives under `addr`. + /// todo update comment /// /// # Example /// @@ -1145,8 +952,8 @@ where /// # } /// # /// #[ink(message)] - /// pub fn is_contract(&mut self, account_id: AccountId) -> bool { - /// self.env().is_contract(&account_id) + /// pub fn is_contract(&mut self, addr: ink::H160) -> bool { + /// self.env().is_contract(&addr) /// } /// # } /// # } @@ -1155,8 +962,8 @@ where /// # Note /// /// For more details visit: [`ink_env::is_contract`] - pub fn is_contract(self, account_id: &E::AccountId) -> bool { - ink_env::is_contract::(account_id) + pub fn is_contract(self, addr: &H160) -> bool { + ink_env::is_contract(addr) } /// Checks whether the caller of the current contract is the origin of the whole call @@ -1239,8 +1046,9 @@ where /// # } /// # /// #[ink(message)] - /// pub fn code_hash(&mut self, account_id: AccountId) -> Option { - /// self.env().code_hash(&account_id).ok() + /// // todo + /// pub fn code_hash(&mut self, addr: ink::H160) -> Option { + /// self.env().code_hash(&addr).ok() /// } /// # } /// # } @@ -1249,8 +1057,8 @@ where /// # Note /// /// For more details visit: [`ink_env::code_hash`] - pub fn code_hash(self, account_id: &E::AccountId) -> Result { - ink_env::code_hash::(account_id) + pub fn code_hash(self, addr: &H160) -> Result { + ink_env::code_hash(addr) } /// Returns the code hash of the contract at the given `account` id. @@ -1270,7 +1078,7 @@ where /// # } /// # /// #[ink(message)] - /// pub fn own_code_hash(&mut self) -> Hash { + /// pub fn own_code_hash(&mut self) -> ink::H256 { /// self.env() /// .own_code_hash() /// .unwrap_or_else(|err| panic!("contract should have a code hash: {:?}", err)) @@ -1282,8 +1090,8 @@ where /// # Note /// /// For more details visit: [`ink_env::own_code_hash`] - pub fn own_code_hash(self) -> Result { - ink_env::own_code_hash::() + pub fn own_code_hash(self) -> Result { + ink_env::own_code_hash() } /// Replace the contract code at the specified address with new code. @@ -1303,7 +1111,7 @@ where /// # } /// # /// #[ink(message)] - /// pub fn set_code_hash(&mut self, code_hash: Hash) { + /// pub fn set_code_hash(&mut self, code_hash: ink::H256) { /// self.env() /// .set_code_hash(&code_hash) /// .unwrap_or_else(|err| panic!("failed to set code hash: {:?}", err)) @@ -1315,7 +1123,7 @@ where /// # Note /// /// For more details visit: [`ink_env::set_code_hash`] - pub fn set_code_hash(self, code_hash: &E::Hash) -> Result<()> { + pub fn set_code_hash(self, code_hash: &H256) -> Result<()> { ink_env::set_code_hash::(code_hash) } @@ -1341,7 +1149,7 @@ where /// # } /// # /// #[ink(message)] - /// pub fn lock_delegate_dependency(&mut self, code_hash: Hash) { + /// pub fn lock_delegate_dependency(&mut self, code_hash: ink::H256) { /// self.env().lock_delegate_dependency(&code_hash) /// } /// # } @@ -1351,7 +1159,7 @@ where /// # Note /// /// For more details visit: [`ink_env::lock_delegate_dependency`] - pub fn lock_delegate_dependency(self, code_hash: &E::Hash) { + pub fn lock_delegate_dependency(self, code_hash: &H256) { ink_env::lock_delegate_dependency::(code_hash) } @@ -1372,7 +1180,7 @@ where /// # } /// # /// #[ink(message)] - /// pub fn unlock_delegate_dependency(&mut self, code_hash: Hash) { + /// pub fn unlock_delegate_dependency(&mut self, code_hash: ink::H256) { /// self.env().unlock_delegate_dependency(&code_hash) /// } /// # } @@ -1382,7 +1190,7 @@ where /// # Note /// /// For more details visit: [`ink_env::unlock_delegate_dependency`] - pub fn unlock_delegate_dependency(self, code_hash: &E::Hash) { + pub fn unlock_delegate_dependency(self, code_hash: &H256) { ink_env::unlock_delegate_dependency::(code_hash) } diff --git a/crates/ink/src/lib.rs b/crates/ink/src/lib.rs index 4916f0b2988..ad89bd09d6e 100644 --- a/crates/ink/src/lib.rs +++ b/crates/ink/src/lib.rs @@ -74,13 +74,14 @@ pub use self::{ Output, ValueReturned, }, - contract_ref::ToAccountId, + contract_ref::ToAddr, env_access::EnvAccess, prelude::IIP2_WILDCARD_COMPLEMENT_SELECTOR, }; +#[allow(unused)] +pub use ink_macro::chain_extension; pub use ink_macro::{ blake2x256, - chain_extension, contract, event, scale_derive, @@ -96,4 +97,7 @@ pub use ink_primitives::{ ConstructorResult, LangError, MessageResult, + H160, + H256, + U256, }; diff --git a/crates/ink/src/message_builder.rs b/crates/ink/src/message_builder.rs index 53425eb4a09..a54602e94c3 100644 --- a/crates/ink/src/message_builder.rs +++ b/crates/ink/src/message_builder.rs @@ -46,6 +46,7 @@ /// use ink_primitives::{ /// AccountId, /// MessageResult, +/// H160, /// }; /// use scale::{ /// Decode, @@ -60,7 +61,7 @@ /// /// /// Transfers balance from the caller to the given address. /// #[ink(message)] -/// fn transfer(&mut self, amount: u128, to: AccountId) -> bool; +/// fn transfer(&mut self, amount: u128, to: H160) -> bool; /// } /// /// #[derive(Clone)] @@ -74,6 +75,7 @@ /// type Timestamp = u64; /// type BlockNumber = u64; /// type ChainExtension = (); +/// type EventRecord = (); /// } /// /// /// To demonstrate implementing an execution environment agnostic executor @@ -107,21 +109,21 @@ /// } /// } /// -/// fn default(to: AccountId) { +/// fn default(to: H160) { /// let executor = ExampleExecutor::::new(); /// let mut contract = message_builder!(Erc20); /// let total_supply = contract.total_supply().exec(&executor).unwrap().unwrap(); /// contract.transfer(total_supply, to).exec(&executor).unwrap(); /// } /// -/// fn custom(to: AccountId) { +/// fn custom(to: H160) { /// let executor = ExampleExecutor::::new(); /// let mut contract = message_builder!(Erc20, CustomEnv); /// let total_supply = contract.total_supply().exec(&executor).unwrap().unwrap(); /// contract.transfer(total_supply, to).exec(&executor).unwrap(); /// } /// -/// fn generic(to: AccountId) +/// fn generic(to: H160) /// where /// E: ink_env::Environment, /// { diff --git a/crates/ink/tests/events_metadata.rs b/crates/ink/tests/events_metadata.rs index cf22f25c030..82470e38c90 100644 --- a/crates/ink/tests/events_metadata.rs +++ b/crates/ink/tests/events_metadata.rs @@ -12,7 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -#![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(not(feature = "std"), no_std, no_main)] +#![allow(unexpected_cfgs)] #[ink::event] /// EventExternal docs diff --git a/crates/ink/tests/return_type_metadata.rs b/crates/ink/tests/return_type_metadata.rs index 0bca2ffcf26..ab0f4775ada 100644 --- a/crates/ink/tests/return_type_metadata.rs +++ b/crates/ink/tests/return_type_metadata.rs @@ -12,7 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -#![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(not(feature = "std"), no_std, no_main)] +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink::trait_definition] diff --git a/crates/ink/tests/ui/chain_extension/E-01-simple.rs b/crates/ink/tests/ui/chain_extension/E-01-simple.rs index fd732644a94..1a22a587527 100644 --- a/crates/ink/tests/ui/chain_extension/E-01-simple.rs +++ b/crates/ink/tests/ui/chain_extension/E-01-simple.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + use ink_env::Environment; /// Custom chain extension to read to and write from the runtime. @@ -115,6 +117,7 @@ impl Environment for CustomEnvironment { type Hash = ::Hash; type BlockNumber = ::BlockNumber; type Timestamp = ::Timestamp; + type EventRecord = ::EventRecord; type ChainExtension = RuntimeReadWrite; } diff --git a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-01.rs b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-01.rs index 639c5cc0080..e5d402e6203 100644 --- a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-01.rs +++ b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-01.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-01.stderr b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-01.stderr index 3fca50b6209..23472168b5b 100644 --- a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-01.stderr +++ b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-01.stderr @@ -6,7 +6,7 @@ error: This `cfg` attribute is not allowed. - `any` - `not` - `all` - --> tests/ui/contract/fail/cfg-forbidden-usage-01.rs:16:25 + --> tests/ui/contract/fail/cfg-forbidden-usage-01.rs:18:25 | -16 | #[cfg(any(test, target_family = "wasm"))] +18 | #[cfg(any(test, target_family = "wasm"))] | ^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-02.rs b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-02.rs index a926fbeae5d..29cd44d8e36 100644 --- a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-02.rs +++ b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-02.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-02.stderr b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-02.stderr index a3f5a4c7d81..9a03ea87810 100644 --- a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-02.stderr +++ b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-02.stderr @@ -6,7 +6,7 @@ error: The feature `std` is not allowed in `cfg`. - `any` - `not` - `all` - --> tests/ui/contract/fail/cfg-forbidden-usage-02.rs:16:19 + --> tests/ui/contract/fail/cfg-forbidden-usage-02.rs:18:19 | -16 | #[cfg(not(feature = "std"))] +18 | #[cfg(not(feature = "std"))] | ^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-03.rs b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-03.rs index 428138f7230..b26530e2603 100644 --- a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-03.rs +++ b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-03.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-03.stderr b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-03.stderr index d376edfbc3a..93d14303911 100644 --- a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-03.stderr +++ b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-03.stderr @@ -6,7 +6,7 @@ error: The feature `std` is not allowed in `cfg`. - `any` - `not` - `all` - --> tests/ui/contract/fail/cfg-forbidden-usage-03.rs:16:23 + --> tests/ui/contract/fail/cfg-forbidden-usage-03.rs:18:23 | -16 | #[cfg(any(not(feature = "std")))] +18 | #[cfg(any(not(feature = "std")))] | ^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-04.rs b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-04.rs index 6cefb0115fc..6e2d019a920 100644 --- a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-04.rs +++ b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-04.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-04.stderr b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-04.stderr index d56a3dd44a5..4cad5bdbfe4 100644 --- a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-04.stderr +++ b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-04.stderr @@ -6,7 +6,7 @@ error: This `cfg` attribute is not allowed. - `any` - `not` - `all` - --> tests/ui/contract/fail/cfg-forbidden-usage-04.rs:7:25 + --> tests/ui/contract/fail/cfg-forbidden-usage-04.rs:9:25 | -7 | #[cfg(any(test, target_family = "wasm", feature = "std"))] +9 | #[cfg(any(test, target_family = "wasm", feature = "std"))] | ^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-05.rs b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-05.rs index bacde3f86d7..67dce2d17b9 100644 --- a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-05.rs +++ b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-05.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-05.stderr b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-05.stderr index 0047a0fbd8a..7d7030226f1 100644 --- a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-05.stderr +++ b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-05.stderr @@ -6,7 +6,7 @@ error: This `cfg` attribute is not allowed. - `any` - `not` - `all` - --> tests/ui/contract/fail/cfg-forbidden-usage-05.rs:16:15 + --> tests/ui/contract/fail/cfg-forbidden-usage-05.rs:18:15 | -16 | #[cfg(target_pointer_width = "32")] +18 | #[cfg(target_pointer_width = "32")] | ^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-06.rs b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-06.rs index 1f626401db1..6b6308976f2 100644 --- a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-06.rs +++ b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-06.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract(keep_attr = "cfg")] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-06.stderr b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-06.stderr index ede0f6d3960..db5273b1969 100644 --- a/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-06.stderr +++ b/crates/ink/tests/ui/contract/fail/cfg-forbidden-usage-06.stderr @@ -6,7 +6,7 @@ error: This `cfg` attribute is not allowed. - `any` - `not` - `all` - --> tests/ui/contract/fail/cfg-forbidden-usage-06.rs:16:15 + --> tests/ui/contract/fail/cfg-forbidden-usage-06.rs:18:15 | -16 | #[cfg(target_os = "wasm")] +18 | #[cfg(target_os = "wasm")] | ^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/config-keep-attr-invalid-type.rs b/crates/ink/tests/ui/contract/fail/config-keep-attr-invalid-type.rs index d929d61dc24..8527e599754 100644 --- a/crates/ink/tests/ui/contract/fail/config-keep-attr-invalid-type.rs +++ b/crates/ink/tests/ui/contract/fail/config-keep-attr-invalid-type.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract(keep_attr = true)] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/config-keep-attr-invalid-type.stderr b/crates/ink/tests/ui/contract/fail/config-keep-attr-invalid-type.stderr index f0bf186da21..c63515a032e 100644 --- a/crates/ink/tests/ui/contract/fail/config-keep-attr-invalid-type.stderr +++ b/crates/ink/tests/ui/contract/fail/config-keep-attr-invalid-type.stderr @@ -1,5 +1,5 @@ error: expected a string with attributes separated by `,` - --> tests/ui/contract/fail/config-keep-attr-invalid-type.rs:1:17 + --> tests/ui/contract/fail/config-keep-attr-invalid-type.rs:3:17 | -1 | #[ink::contract(keep_attr = true)] +3 | #[ink::contract(keep_attr = true)] | ^^^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/config-keep-attr-missing-arg.rs b/crates/ink/tests/ui/contract/fail/config-keep-attr-missing-arg.rs index d0b5c4d6a30..4db2ca9b7d9 100644 --- a/crates/ink/tests/ui/contract/fail/config-keep-attr-missing-arg.rs +++ b/crates/ink/tests/ui/contract/fail/config-keep-attr-missing-arg.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract(keep_attr)] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/config-keep-attr-missing-arg.stderr b/crates/ink/tests/ui/contract/fail/config-keep-attr-missing-arg.stderr index 33054b2fcb1..197e8bde0cf 100644 --- a/crates/ink/tests/ui/contract/fail/config-keep-attr-missing-arg.stderr +++ b/crates/ink/tests/ui/contract/fail/config-keep-attr-missing-arg.stderr @@ -1,5 +1,5 @@ error: expected a string literal value for `keep_attr` ink! configuration argument - --> tests/ui/contract/fail/config-keep-attr-missing-arg.rs:1:17 + --> tests/ui/contract/fail/config-keep-attr-missing-arg.rs:3:17 | -1 | #[ink::contract(keep_attr)] +3 | #[ink::contract(keep_attr)] | ^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/constructor-abi.rs b/crates/ink/tests/ui/contract/fail/constructor-abi.rs index c8d324c79df..4b1e3d19514 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-abi.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-abi.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-abi.stderr b/crates/ink/tests/ui/contract/fail/constructor-abi.stderr index 24857f3fb6e..ac69b6edc50 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-abi.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-abi.stderr @@ -1,5 +1,5 @@ error: ink! constructors must not have explicit ABI - --> tests/ui/contract/fail/constructor-abi.rs:8:13 - | -8 | pub extern "C" fn constructor() -> Self { - | ^^^^^^^^^^ + --> tests/ui/contract/fail/constructor-abi.rs:10:13 + | +10 | pub extern "C" fn constructor() -> Self { + | ^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/constructor-async.rs b/crates/ink/tests/ui/contract/fail/constructor-async.rs index bcd7d09c146..14a9b3a7029 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-async.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-async.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-async.stderr b/crates/ink/tests/ui/contract/fail/constructor-async.stderr index 4d66a08e641..86a797e0c13 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-async.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-async.stderr @@ -1,5 +1,5 @@ error: ink! constructors must not be async - --> tests/ui/contract/fail/constructor-async.rs:8:13 - | -8 | pub async fn constructor() -> Self { - | ^^^^^ + --> tests/ui/contract/fail/constructor-async.rs:10:13 + | +10 | pub async fn constructor() -> Self { + | ^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/constructor-const.rs b/crates/ink/tests/ui/contract/fail/constructor-const.rs index 837758e8083..6a1778cc4e0 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-const.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-const.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-const.stderr b/crates/ink/tests/ui/contract/fail/constructor-const.stderr index d96be9f8f41..4a4b2399fd3 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-const.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-const.stderr @@ -1,5 +1,5 @@ error: ink! constructors must not be const - --> tests/ui/contract/fail/constructor-const.rs:8:13 - | -8 | pub const fn constructor() -> Self { - | ^^^^^ + --> tests/ui/contract/fail/constructor-const.rs:10:13 + | +10 | pub const fn constructor() -> Self { + | ^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/constructor-input-non-codec.rs b/crates/ink/tests/ui/contract/fail/constructor-input-non-codec.rs index f2a044c5d18..ca3682cb081 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-input-non-codec.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-input-non-codec.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[::ink::scale_derive(TypeInfo)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-input-non-codec.stderr b/crates/ink/tests/ui/contract/fail/constructor-input-non-codec.stderr index 284958a258f..70ebe0afa77 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-input-non-codec.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-input-non-codec.stderr @@ -1,8 +1,8 @@ error[E0277]: the trait bound `NonCodecType: WrapperTypeDecode` is not satisfied - --> tests/ui/contract/fail/constructor-input-non-codec.rs:11:28 + --> tests/ui/contract/fail/constructor-input-non-codec.rs:13:28 | -11 | pub fn constructor(_input: NonCodecType) -> Self { - | ^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonCodecType`, which is required by `NonCodecType: ink::parity_scale_codec::Decode` +13 | pub fn constructor(_input: NonCodecType) -> Self { + | ^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonCodecType` | = help: the following other types implement trait `WrapperTypeDecode`: Arc @@ -20,12 +20,12 @@ note: required by a bound in `DispatchInput` | ^^^^^^^^^^^^^ required by this bound in `DispatchInput` error[E0277]: the trait bound `NonCodecType: ink::parity_scale_codec::Decode` is not satisfied - --> tests/ui/contract/fail/constructor-input-non-codec.rs:11:9 + --> tests/ui/contract/fail/constructor-input-non-codec.rs:13:9 | -11 | / pub fn constructor(_input: NonCodecType) -> Self { -12 | | Self {} -13 | | } - | |_________^ the trait `WrapperTypeDecode` is not implemented for `NonCodecType`, which is required by `NonCodecType: ink::parity_scale_codec::Decode` +13 | / pub fn constructor(_input: NonCodecType) -> Self { +14 | | Self {} +15 | | } + | |_________^ the trait `WrapperTypeDecode` is not implemented for `NonCodecType` | = help: the following other types implement trait `WrapperTypeDecode`: Arc @@ -35,14 +35,14 @@ error[E0277]: the trait bound `NonCodecType: ink::parity_scale_codec::Decode` is = note: required for `NonCodecType` to implement `ink::parity_scale_codec::Decode` error[E0277]: the trait bound `NonCodecType: Encode` is not satisfied - --> tests/ui/contract/fail/constructor-input-non-codec.rs:1:1 + --> tests/ui/contract/fail/constructor-input-non-codec.rs:3:1 | -1 | #[ink::contract] - | ^^^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonCodecType`, which is required by `NonCodecType: Encode` +3 | #[ink::contract] + | ^^^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonCodecType` ... -11 | / pub fn constructor(_input: NonCodecType) -> Self { -12 | | Self {} -13 | | } +13 | / pub fn constructor(_input: NonCodecType) -> Self { +14 | | Self {} +15 | | } | |_________- required by a bound introduced by this call | = help: the following other types implement trait `WrapperTypeEncode`: diff --git a/crates/ink/tests/ui/contract/fail/constructor-input-pattern.rs b/crates/ink/tests/ui/contract/fail/constructor-input-pattern.rs index 87b2ee4f792..4462d137a82 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-input-pattern.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-input-pattern.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-input-pattern.stderr b/crates/ink/tests/ui/contract/fail/constructor-input-pattern.stderr index e6cb06757e7..59def8bc720 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-input-pattern.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-input-pattern.stderr @@ -1,5 +1,5 @@ error: ink! constructor arguments must have an identifier - --> tests/ui/contract/fail/constructor-input-pattern.rs:8:28 - | -8 | pub fn constructor((_a, _b): (i32, i32)) -> Self { - | ^^^^^^^^^^^^^^^^^^^^ + --> tests/ui/contract/fail/constructor-input-pattern.rs:10:28 + | +10 | pub fn constructor((_a, _b): (i32, i32)) -> Self { + | ^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/constructor-missing-return.rs b/crates/ink/tests/ui/contract/fail/constructor-missing-return.rs index eb828293d1c..f40b320a722 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-missing-return.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-missing-return.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-missing-return.stderr b/crates/ink/tests/ui/contract/fail/constructor-missing-return.stderr index c20b5889fb2..fda3fa61b5a 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-missing-return.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-missing-return.stderr @@ -1,5 +1,5 @@ error: missing return for ink! constructor - --> tests/ui/contract/fail/constructor-missing-return.rs:8:13 - | -8 | pub fn constructor() {} - | ^^^^^^^^^^^^^^^^ + --> tests/ui/contract/fail/constructor-missing-return.rs:10:13 + | +10 | pub fn constructor() {} + | ^^^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/constructor-multiple-wildcard-selectors.rs b/crates/ink/tests/ui/contract/fail/constructor-multiple-wildcard-selectors.rs index ce2e2b51fea..a4cd7a99bd7 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-multiple-wildcard-selectors.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-multiple-wildcard-selectors.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-multiple-wildcard-selectors.stderr b/crates/ink/tests/ui/contract/fail/constructor-multiple-wildcard-selectors.stderr index d414f29d565..658bd706146 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-multiple-wildcard-selectors.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-multiple-wildcard-selectors.stderr @@ -1,15 +1,15 @@ error: encountered ink! constructor with overlapping wildcard selectors - --> tests/ui/contract/fail/constructor-multiple-wildcard-selectors.rs:13:9 + --> tests/ui/contract/fail/constructor-multiple-wildcard-selectors.rs:15:9 | -13 | / pub fn constructor2() -> Self { -14 | | Self {} -15 | | } +15 | / pub fn constructor2() -> Self { +16 | | Self {} +17 | | } | |_________^ error: first ink! constructor with overlapping wildcard selector here - --> tests/ui/contract/fail/constructor-multiple-wildcard-selectors.rs:8:9 + --> tests/ui/contract/fail/constructor-multiple-wildcard-selectors.rs:10:9 | -8 | / pub fn constructor1() -> Self { -9 | | Self {} -10 | | } +10 | / pub fn constructor1() -> Self { +11 | | Self {} +12 | | } | |_________^ diff --git a/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-1.rs b/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-1.rs index 00f41472601..f4a46432bd2 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-1.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-1.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-1.stderr b/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-1.stderr index dbd62bb61fa..6f0f73fb9de 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-1.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-1.stderr @@ -1,5 +1,5 @@ error: encountered unknown ink! attribute argument: payable - --> tests/ui/contract/fail/constructor-payable-invalid-1.rs:7:28 + --> tests/ui/contract/fail/constructor-payable-invalid-1.rs:9:28 | -7 | #[ink(constructor, payable = true)] +9 | #[ink(constructor, payable = true)] | ^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-2.rs b/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-2.rs index 65ec95cd336..1777fe360d9 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-2.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-2.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-2.stderr b/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-2.stderr index 130ef245956..e8b0605f9a0 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-2.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-payable-invalid-2.stderr @@ -1,5 +1,5 @@ error: encountered unknown ink! attribute argument: payable - --> tests/ui/contract/fail/constructor-payable-invalid-2.rs:7:28 + --> tests/ui/contract/fail/constructor-payable-invalid-2.rs:9:28 | -7 | #[ink(constructor, payable = false)] +9 | #[ink(constructor, payable = false)] | ^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/constructor-return-result-invalid.rs b/crates/ink/tests/ui/contract/fail/constructor-return-result-invalid.rs index dfa7dac6da6..66a506bcd6a 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-return-result-invalid.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-return-result-invalid.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-return-result-invalid.stderr b/crates/ink/tests/ui/contract/fail/constructor-return-result-invalid.stderr index 7df2f3bbc2d..bd033a3a682 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-return-result-invalid.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-return-result-invalid.stderr @@ -1,9 +1,9 @@ error[E0277]: the trait bound `ConstructorOutputValue>: ConstructorOutput` is not satisfied - --> tests/ui/contract/fail/constructor-return-result-invalid.rs:14:9 + --> tests/ui/contract/fail/constructor-return-result-invalid.rs:16:9 | -14 | / pub fn constructor() -> Result { -15 | | Ok(5_u8) -16 | | } +16 | / pub fn constructor() -> Result { +17 | | Ok(5_u8) +18 | | } | |_________^ the trait `ConstructorOutput` is not implemented for `ConstructorOutputValue>` | = help: the following other types implement trait `ConstructorOutput`: @@ -11,32 +11,32 @@ error[E0277]: the trait bound `ConstructorOutputValue> error[E0277]: the trait bound `Result: ConstructorReturnType` is not satisfied - --> tests/ui/contract/fail/constructor-return-result-invalid.rs:14:33 + --> tests/ui/contract/fail/constructor-return-result-invalid.rs:16:33 | -14 | pub fn constructor() -> Result { +16 | pub fn constructor() -> Result { | - ^^^^^^^^^^^^^^^^^ the trait `ConstructorReturnType` is not implemented for `Result` | _________| | | -15 | | Ok(5_u8) -16 | | } +17 | | Ok(5_u8) +18 | | } | |_________- required by a bound introduced by this call | = help: the following other types implement trait `ConstructorReturnType`: `Result` implements `ConstructorReturnType` `Result` implements `ConstructorReturnType` -note: required by a bound in `CreateBuilder::>>::returns` +note: required by a bound in `CreateBuilder::>>::returns` --> $WORKSPACE/crates/env/src/call/create_builder.rs | | pub fn returns( | ------- required by a bound in this associated function ... | R: ConstructorReturnType, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `CreateBuilder::>>::returns` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `CreateBuilder::>>::returns` error[E0277]: the trait bound `ConstructorOutputValue>: ConstructorOutput` is not satisfied - --> tests/ui/contract/fail/constructor-return-result-invalid.rs:4:16 + --> tests/ui/contract/fail/constructor-return-result-invalid.rs:6:16 | -4 | pub struct Contract {} +6 | pub struct Contract {} | ^^^^^^^^ the trait `ConstructorOutput` is not implemented for `ConstructorOutputValue>` | = help: the following other types implement trait `ConstructorOutput`: diff --git a/crates/ink/tests/ui/contract/fail/constructor-return-result-non-codec-error.rs b/crates/ink/tests/ui/contract/fail/constructor-return-result-non-codec-error.rs index 270be017594..efd056d1f22 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-return-result-non-codec-error.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-return-result-non-codec-error.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-return-result-non-codec-error.stderr b/crates/ink/tests/ui/contract/fail/constructor-return-result-non-codec-error.stderr index b8cd9940561..ed1d9061063 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-return-result-non-codec-error.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-return-result-non-codec-error.stderr @@ -1,9 +1,9 @@ error[E0277]: the trait bound `Result, LangError>: Encode` is not satisfied - --> tests/ui/contract/fail/constructor-return-result-non-codec-error.rs:13:9 + --> tests/ui/contract/fail/constructor-return-result-non-codec-error.rs:15:9 | -13 | / pub fn constructor() -> Result { -14 | | Ok(Self {}) -15 | | } +15 | / pub fn constructor() -> Result { +16 | | Ok(Self {}) +17 | | } | |_________^ the trait `Encode` is not implemented for `Result, LangError>` | = help: the trait `Encode` is implemented for `Result` @@ -17,14 +17,14 @@ note: required by a bound in `return_value` | ^^^^^^^^^^^^^ required by this bound in `return_value` error[E0277]: the trait bound `contract::Error: WrapperTypeDecode` is not satisfied - --> tests/ui/contract/fail/constructor-return-result-non-codec-error.rs:13:33 + --> tests/ui/contract/fail/constructor-return-result-non-codec-error.rs:15:33 | -13 | pub fn constructor() -> Result { - | - ^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `contract::Error`, which is required by `Result: ConstructorReturnType` +15 | pub fn constructor() -> Result { + | - ^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `contract::Error` | _________| | | -14 | | Ok(Self {}) -15 | | } +16 | | Ok(Self {}) +17 | | } | |_________- required by a bound introduced by this call | = help: the following other types implement trait `WrapperTypeDecode`: @@ -34,20 +34,20 @@ error[E0277]: the trait bound `contract::Error: WrapperTypeDecode` is not satisf sp_core::Bytes = note: required for `contract::Error` to implement `ink::parity_scale_codec::Decode` = note: required for `Result` to implement `ConstructorReturnType` -note: required by a bound in `CreateBuilder::>>::returns` +note: required by a bound in `CreateBuilder::>>::returns` --> $WORKSPACE/crates/env/src/call/create_builder.rs | | pub fn returns( | ------- required by a bound in this associated function ... | R: ConstructorReturnType, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `CreateBuilder::>>::returns` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `CreateBuilder::>>::returns` error[E0277]: the trait bound `contract::Error: TypeInfo` is not satisfied - --> tests/ui/contract/fail/constructor-return-result-non-codec-error.rs:4:16 + --> tests/ui/contract/fail/constructor-return-result-non-codec-error.rs:6:16 | -4 | pub struct Contract {} - | ^^^^^^^^ the trait `TypeInfo` is not implemented for `contract::Error`, which is required by `Result, LangError>: TypeInfo` +6 | pub struct Contract {} + | ^^^^^^^^ the trait `TypeInfo` is not implemented for `contract::Error` | = help: the following other types implement trait `TypeInfo`: &T diff --git a/crates/ink/tests/ui/contract/fail/constructor-selector-and-wildcard-selector.rs b/crates/ink/tests/ui/contract/fail/constructor-selector-and-wildcard-selector.rs index 95134b7c03d..0eaa8e3bfcd 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-selector-and-wildcard-selector.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-selector-and-wildcard-selector.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-selector-and-wildcard-selector.stderr b/crates/ink/tests/ui/contract/fail/constructor-selector-and-wildcard-selector.stderr index 67893789961..9c2c985c235 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-selector-and-wildcard-selector.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-selector-and-wildcard-selector.stderr @@ -1,11 +1,11 @@ error: encountered ink! attribute arguments with equal kinds - --> tests/ui/contract/fail/constructor-selector-and-wildcard-selector.rs:7:51 + --> tests/ui/contract/fail/constructor-selector-and-wildcard-selector.rs:9:51 | -7 | #[ink(constructor, selector = 0xCAFEBABA, selector = _)] +9 | #[ink(constructor, selector = 0xCAFEBABA, selector = _)] | ^^^^^^^^^^^^ error: first equal ink! attribute argument with equal kind here - --> tests/ui/contract/fail/constructor-selector-and-wildcard-selector.rs:7:28 + --> tests/ui/contract/fail/constructor-selector-and-wildcard-selector.rs:9:28 | -7 | #[ink(constructor, selector = 0xCAFEBABA, selector = _)] +9 | #[ink(constructor, selector = 0xCAFEBABA, selector = _)] | ^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-01.rs b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-01.rs index 35c6d0a7968..4ca6c0a773e 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-01.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-01.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-01.stderr b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-01.stderr index 91ae26852cd..b10addb66d3 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-01.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-01.stderr @@ -1,5 +1,5 @@ error: ink! constructors must have no `self` receiver - --> tests/ui/contract/fail/constructor-self-receiver-01.rs:8:28 - | -8 | pub fn constructor(&self) -> Self { - | ^^^^^ + --> tests/ui/contract/fail/constructor-self-receiver-01.rs:10:28 + | +10 | pub fn constructor(&self) -> Self { + | ^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-02.rs b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-02.rs index 5c688dbff0e..4a7e8cac429 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-02.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-02.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-02.stderr b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-02.stderr index 83d02d72132..f217562f530 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-02.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-02.stderr @@ -1,5 +1,5 @@ error: ink! constructors must have no `self` receiver - --> tests/ui/contract/fail/constructor-self-receiver-02.rs:8:28 - | -8 | pub fn constructor(&mut self) -> Self { - | ^^^^^^^^^ + --> tests/ui/contract/fail/constructor-self-receiver-02.rs:10:28 + | +10 | pub fn constructor(&mut self) -> Self { + | ^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-03.rs b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-03.rs index 83fb3787b95..f1efb53725d 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-03.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-03.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-03.stderr b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-03.stderr index 3ae07a86640..adb6b88224f 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-03.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-03.stderr @@ -1,31 +1,31 @@ error: in the trait associated type is declared without lifetime parameters, so using a borrowed type for them requires that lifetime to come from the implemented type - --> tests/ui/contract/fail/constructor-self-receiver-03.rs:8:34 - | -8 | pub fn constructor(this: &Self) -> Self { - | ^ this lifetime must come from the implemented type + --> tests/ui/contract/fail/constructor-self-receiver-03.rs:10:34 + | +10 | pub fn constructor(this: &Self) -> Self { + | ^ this lifetime must come from the implemented type error[E0411]: cannot find type `Self` in this scope - --> tests/ui/contract/fail/constructor-self-receiver-03.rs:8:35 - | -4 | pub struct Contract {} - | ---------------------- `Self` not allowed in a constant item + --> tests/ui/contract/fail/constructor-self-receiver-03.rs:10:35 + | +6 | pub struct Contract {} + | ---------------------- `Self` not allowed in a constant item ... -8 | pub fn constructor(this: &Self) -> Self { - | ^^^^ `Self` is only available in impls, traits, and type definitions +10 | pub fn constructor(this: &Self) -> Self { + | ^^^^ `Self` is only available in impls, traits, and type definitions error[E0411]: cannot find type `Self` in this scope - --> tests/ui/contract/fail/constructor-self-receiver-03.rs:8:35 - | -1 | #[ink::contract] - | ---------------- `Self` not allowed in a function + --> tests/ui/contract/fail/constructor-self-receiver-03.rs:10:35 + | +3 | #[ink::contract] + | ---------------- `Self` not allowed in a function ... -8 | pub fn constructor(this: &Self) -> Self { - | ^^^^ `Self` is only available in impls, traits, and type definitions +10 | pub fn constructor(this: &Self) -> Self { + | ^^^^ `Self` is only available in impls, traits, and type definitions warning: unused variable: `this` - --> tests/ui/contract/fail/constructor-self-receiver-03.rs:8:28 - | -8 | pub fn constructor(this: &Self) -> Self { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_this` - | - = note: `#[warn(unused_variables)]` on by default + --> tests/ui/contract/fail/constructor-self-receiver-03.rs:10:28 + | +10 | pub fn constructor(this: &Self) -> Self { + | ^^^^ help: if this is intentional, prefix it with an underscore: `_this` + | + = note: `#[warn(unused_variables)]` on by default diff --git a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-04.rs b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-04.rs index a76e79e5c0e..c733348927b 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-04.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-04.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-04.stderr b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-04.stderr index 3c5b41458cc..c5259d8f9bd 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-04.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-04.stderr @@ -1,5 +1,5 @@ error: ink! constructors must have no `self` receiver - --> tests/ui/contract/fail/constructor-self-receiver-04.rs:8:28 - | -8 | pub fn constructor(self) -> Self { - | ^^^^ + --> tests/ui/contract/fail/constructor-self-receiver-04.rs:10:28 + | +10 | pub fn constructor(self) -> Self { + | ^^^^ diff --git a/crates/ink/tests/ui/contract/fail/constructor-unsafe.rs b/crates/ink/tests/ui/contract/fail/constructor-unsafe.rs index 107c3bd061a..47f8fc0b34a 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-unsafe.rs +++ b/crates/ink/tests/ui/contract/fail/constructor-unsafe.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/constructor-unsafe.stderr b/crates/ink/tests/ui/contract/fail/constructor-unsafe.stderr index bbe34d1e0d5..d340ce7205e 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-unsafe.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-unsafe.stderr @@ -1,5 +1,5 @@ error: ink! constructors must not be unsafe - --> tests/ui/contract/fail/constructor-unsafe.rs:8:13 - | -8 | pub unsafe fn constructor() -> Self { - | ^^^^^^ + --> tests/ui/contract/fail/constructor-unsafe.rs:10:13 + | +10 | pub unsafe fn constructor() -> Self { + | ^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/event-conflicting-storage.rs b/crates/ink/tests/ui/contract/fail/event-conflicting-storage.rs index 647d8ec8ce0..894a3905327 100644 --- a/crates/ink/tests/ui/contract/fail/event-conflicting-storage.rs +++ b/crates/ink/tests/ui/contract/fail/event-conflicting-storage.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/event-conflicting-storage.stderr b/crates/ink/tests/ui/contract/fail/event-conflicting-storage.stderr index aa724f77a8e..42ea9e9f95e 100644 --- a/crates/ink/tests/ui/contract/fail/event-conflicting-storage.stderr +++ b/crates/ink/tests/ui/contract/fail/event-conflicting-storage.stderr @@ -1,5 +1,5 @@ error: encountered conflicting ink! attribute argument - --> tests/ui/contract/fail/event-conflicting-storage.rs:7:11 + --> tests/ui/contract/fail/event-conflicting-storage.rs:9:11 | -7 | #[ink(storage)] +9 | #[ink(storage)] | ^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-01.rs b/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-01.rs index 5dd9120f775..7addca0ae42 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-01.rs +++ b/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-01.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-01.stderr b/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-01.stderr index 007126214ec..d0321806683 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-01.stderr +++ b/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-01.stderr @@ -1,63 +1,63 @@ error[E0308]: mismatched types - --> tests/ui/contract/fail/impl-block-for-non-storage-01.rs:18:10 + --> tests/ui/contract/fail/impl-block-for-non-storage-01.rs:20:10 | -18 | impl NonContract { +20 | impl NonContract { | ^^^^^^^^^^^ expected `IsSameType`, found `IsSameType` | = note: expected struct `IsSameType` found struct `IsSameType` error[E0599]: no function or associated item named `constructor_2` found for struct `Contract` in the current scope - --> tests/ui/contract/fail/impl-block-for-non-storage-01.rs:20:16 + --> tests/ui/contract/fail/impl-block-for-non-storage-01.rs:22:16 | -4 | pub struct Contract {} +6 | pub struct Contract {} | _____------------------- | | | | | function or associated item `constructor_2` not found for this struct -5 | | -6 | | impl Contract { -7 | | #[ink(constructor)] +7 | | +8 | | impl Contract { +9 | | #[ink(constructor)] ... | -19 | | #[ink(constructor)] -20 | | pub fn constructor_2() -> Self { +21 | | #[ink(constructor)] +22 | | pub fn constructor_2() -> Self { | | -^^^^^^^^^^^^^ function or associated item not found in `Contract` | |_______________| | | note: if you're trying to build a new `Contract`, consider using `contract::_::::constructor_1` which returns `Contract` - --> tests/ui/contract/fail/impl-block-for-non-storage-01.rs:8:9 + --> tests/ui/contract/fail/impl-block-for-non-storage-01.rs:10:9 | -8 | pub fn constructor_1() -> Self { +10 | pub fn constructor_1() -> Self { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: there is an associated function `constructor_1` with a similar name | -20 | pub fn constructor_1() -> Self { +22 | pub fn constructor_1() -> Self { | ~~~~~~~~~~~~~ error[E0599]: no function or associated item named `message_2` found for struct `Contract` in the current scope - --> tests/ui/contract/fail/impl-block-for-non-storage-01.rs:25:16 + --> tests/ui/contract/fail/impl-block-for-non-storage-01.rs:27:16 | -4 | pub struct Contract {} +6 | pub struct Contract {} | _____------------------- | | | | | function or associated item `message_2` not found for this struct -5 | | -6 | | impl Contract { -7 | | #[ink(constructor)] +7 | | +8 | | impl Contract { +9 | | #[ink(constructor)] ... | -24 | | #[ink(message)] -25 | | pub fn message_2(&self) {} +26 | | #[ink(message)] +27 | | pub fn message_2(&self) {} | | -^^^^^^^^^ function or associated item not found in `Contract` | |_______________| | | note: if you're trying to build a new `Contract`, consider using `contract::_::::constructor_1` which returns `Contract` - --> tests/ui/contract/fail/impl-block-for-non-storage-01.rs:8:9 + --> tests/ui/contract/fail/impl-block-for-non-storage-01.rs:10:9 | -8 | pub fn constructor_1() -> Self { +10 | pub fn constructor_1() -> Self { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: there is a method `message_1` with a similar name, but with different arguments - --> tests/ui/contract/fail/impl-block-for-non-storage-01.rs:13:9 + --> tests/ui/contract/fail/impl-block-for-non-storage-01.rs:15:9 | -13 | pub fn message_1(&self) {} +15 | pub fn message_1(&self) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-02.rs b/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-02.rs index 448febacfe5..b06d948aa37 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-02.rs +++ b/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-02.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-02.stderr b/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-02.stderr index ba0f236a710..1b4484d9d0e 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-02.stderr +++ b/crates/ink/tests/ui/contract/fail/impl-block-for-non-storage-02.stderr @@ -1,7 +1,7 @@ error[E0308]: mismatched types - --> tests/ui/contract/fail/impl-block-for-non-storage-02.rs:19:10 + --> tests/ui/contract/fail/impl-block-for-non-storage-02.rs:21:10 | -19 | impl NonContract {} +21 | impl NonContract {} | ^^^^^^^^^^^ expected `IsSameType`, found `IsSameType` | = note: expected struct `IsSameType` diff --git a/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-identifier.rs b/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-identifier.rs index 8816faca78f..f25930a9af3 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-identifier.rs +++ b/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-identifier.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-identifier.stderr b/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-identifier.stderr index 989acd599e0..d4e5efa7e46 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-identifier.stderr +++ b/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-identifier.stderr @@ -1,5 +1,5 @@ error: encountered invalid Rust identifier for namespace argument - --> tests/ui/contract/fail/impl-block-namespace-invalid-identifier.rs:6:23 + --> tests/ui/contract/fail/impl-block-namespace-invalid-identifier.rs:8:23 | -6 | #[ink(namespace = "::invalid_identifier")] +8 | #[ink(namespace = "::invalid_identifier")] | ^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-type.rs b/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-type.rs index fee88a8d1e7..57d157e3847 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-type.rs +++ b/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-type.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-type.stderr b/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-type.stderr index 423af44a13e..f9334650631 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-type.stderr +++ b/crates/ink/tests/ui/contract/fail/impl-block-namespace-invalid-type.stderr @@ -1,5 +1,5 @@ error: expected string type for `namespace` argument, e.g. #[ink(namespace = "hello")] - --> tests/ui/contract/fail/impl-block-namespace-invalid-type.rs:6:23 + --> tests/ui/contract/fail/impl-block-namespace-invalid-type.rs:8:23 | -6 | #[ink(namespace = true)] +8 | #[ink(namespace = true)] | ^^^^ diff --git a/crates/ink/tests/ui/contract/fail/impl-block-namespace-missing-argument.rs b/crates/ink/tests/ui/contract/fail/impl-block-namespace-missing-argument.rs index b6bcc98b599..03b18cabd29 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-namespace-missing-argument.rs +++ b/crates/ink/tests/ui/contract/fail/impl-block-namespace-missing-argument.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/impl-block-namespace-missing-argument.stderr b/crates/ink/tests/ui/contract/fail/impl-block-namespace-missing-argument.stderr index 7e01a72da39..b09ed8ec0cd 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-namespace-missing-argument.stderr +++ b/crates/ink/tests/ui/contract/fail/impl-block-namespace-missing-argument.stderr @@ -1,5 +1,5 @@ error: encountered #[ink(namespace)] that is missing its string parameter. Did you mean #[ink(namespace = name: str)] ? - --> tests/ui/contract/fail/impl-block-namespace-missing-argument.rs:6:11 + --> tests/ui/contract/fail/impl-block-namespace-missing-argument.rs:8:11 | -6 | #[ink(namespace)] +8 | #[ink(namespace)] | ^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/impl-block-using-env-no-marker.rs b/crates/ink/tests/ui/contract/fail/impl-block-using-env-no-marker.rs index 88088070a96..1bf305c01a0 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-using-env-no-marker.rs +++ b/crates/ink/tests/ui/contract/fail/impl-block-using-env-no-marker.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/impl-block-using-env-no-marker.stderr b/crates/ink/tests/ui/contract/fail/impl-block-using-env-no-marker.stderr index 0897fb1a54c..ce7fc5aa41b 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-using-env-no-marker.stderr +++ b/crates/ink/tests/ui/contract/fail/impl-block-using-env-no-marker.stderr @@ -1,11 +1,11 @@ error[E0599]: no method named `env` found for reference `&Contract` in the current scope - --> tests/ui/contract/fail/impl-block-using-env-no-marker.rs:22:26 + --> tests/ui/contract/fail/impl-block-using-env-no-marker.rs:24:26 | -22 | let _ = self.env().caller(); +24 | let _ = self.env().caller(); | ^^^ method not found in `&Contract` | = help: items from traits can only be used if the trait is in scope help: trait `Env` which provides `env` is implemented but not in scope; perhaps you want to import it | -1 + use ink::codegen::Env; +3 + use ink::codegen::Env; | diff --git a/crates/ink/tests/ui/contract/fail/impl-block-using-static-env-no-marker.rs b/crates/ink/tests/ui/contract/fail/impl-block-using-static-env-no-marker.rs index c59f6337a6f..d6e53535583 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-using-static-env-no-marker.rs +++ b/crates/ink/tests/ui/contract/fail/impl-block-using-static-env-no-marker.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/impl-block-using-static-env-no-marker.stderr b/crates/ink/tests/ui/contract/fail/impl-block-using-static-env-no-marker.stderr index 4e6c38bc762..56cfc630625 100644 --- a/crates/ink/tests/ui/contract/fail/impl-block-using-static-env-no-marker.stderr +++ b/crates/ink/tests/ui/contract/fail/impl-block-using-static-env-no-marker.stderr @@ -1,24 +1,24 @@ error[E0599]: no function or associated item named `env` found for struct `Contract` in the current scope - --> tests/ui/contract/fail/impl-block-using-static-env-no-marker.rs:20:27 + --> tests/ui/contract/fail/impl-block-using-static-env-no-marker.rs:22:27 | -4 | pub struct Contract {} +6 | pub struct Contract {} | ------------------- function or associated item `env` not found for this struct ... -20 | let _ = Self::env().caller(); +22 | let _ = Self::env().caller(); | ^^^ function or associated item not found in `Contract` | note: if you're trying to build a new `Contract` consider using one of the following associated functions: contract::_::::constructor Contract::constructor_impl - --> tests/ui/contract/fail/impl-block-using-static-env-no-marker.rs:8:9 + --> tests/ui/contract/fail/impl-block-using-static-env-no-marker.rs:10:9 | -8 | pub fn constructor() -> Self { +10 | pub fn constructor() -> Self { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ... -19 | fn constructor_impl() -> Self { +21 | fn constructor_impl() -> Self { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = help: items from traits can only be used if the trait is in scope help: trait `StaticEnv` which provides `env` is implemented but not in scope; perhaps you want to import it | -1 + use ink::codegen::StaticEnv; +3 + use ink::codegen::StaticEnv; | diff --git a/crates/ink/tests/ui/contract/fail/message-hygiene-try.rs b/crates/ink/tests/ui/contract/fail/message-hygiene-try.rs index 749a70efdfc..a491037561b 100644 --- a/crates/ink/tests/ui/contract/fail/message-hygiene-try.rs +++ b/crates/ink/tests/ui/contract/fail/message-hygiene-try.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/message-hygiene-try.stderr b/crates/ink/tests/ui/contract/fail/message-hygiene-try.stderr index 95d45537b9e..58b80f0b344 100644 --- a/crates/ink/tests/ui/contract/fail/message-hygiene-try.stderr +++ b/crates/ink/tests/ui/contract/fail/message-hygiene-try.stderr @@ -1,8 +1,8 @@ error[E0592]: duplicate definitions with name `try_message` - --> tests/ui/contract/fail/message-hygiene-try.rs:16:9 + --> tests/ui/contract/fail/message-hygiene-try.rs:18:9 | -1 | #[ink::contract] +3 | #[ink::contract] | ---------------- other definition for `try_message` ... -16 | pub fn try_message(&self) {} +18 | pub fn try_message(&self) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ duplicate definitions for `try_message` diff --git a/crates/ink/tests/ui/contract/fail/message-input-non-codec.rs b/crates/ink/tests/ui/contract/fail/message-input-non-codec.rs index ed14465198c..6f6187b51d2 100644 --- a/crates/ink/tests/ui/contract/fail/message-input-non-codec.rs +++ b/crates/ink/tests/ui/contract/fail/message-input-non-codec.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[::ink::scale_derive(TypeInfo)] diff --git a/crates/ink/tests/ui/contract/fail/message-input-non-codec.stderr b/crates/ink/tests/ui/contract/fail/message-input-non-codec.stderr index aa15638b74c..68c0a1be582 100644 --- a/crates/ink/tests/ui/contract/fail/message-input-non-codec.stderr +++ b/crates/ink/tests/ui/contract/fail/message-input-non-codec.stderr @@ -1,8 +1,8 @@ error[E0277]: the trait bound `NonCodecType: WrapperTypeDecode` is not satisfied - --> tests/ui/contract/fail/message-input-non-codec.rs:16:31 + --> tests/ui/contract/fail/message-input-non-codec.rs:18:31 | -16 | pub fn message(&self, _input: NonCodecType) {} - | ^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonCodecType`, which is required by `NonCodecType: ink::parity_scale_codec::Decode` +18 | pub fn message(&self, _input: NonCodecType) {} + | ^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonCodecType` | = help: the following other types implement trait `WrapperTypeDecode`: Arc @@ -20,10 +20,10 @@ note: required by a bound in `DispatchInput` | ^^^^^^^^^^^^^ required by this bound in `DispatchInput` error[E0277]: the trait bound `NonCodecType: ink::parity_scale_codec::Decode` is not satisfied - --> tests/ui/contract/fail/message-input-non-codec.rs:16:9 + --> tests/ui/contract/fail/message-input-non-codec.rs:18:9 | -16 | pub fn message(&self, _input: NonCodecType) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonCodecType`, which is required by `NonCodecType: ink::parity_scale_codec::Decode` +18 | pub fn message(&self, _input: NonCodecType) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonCodecType` | = help: the following other types implement trait `WrapperTypeDecode`: Arc @@ -33,12 +33,12 @@ error[E0277]: the trait bound `NonCodecType: ink::parity_scale_codec::Decode` is = note: required for `NonCodecType` to implement `ink::parity_scale_codec::Decode` error[E0277]: the trait bound `NonCodecType: Encode` is not satisfied - --> tests/ui/contract/fail/message-input-non-codec.rs:1:1 + --> tests/ui/contract/fail/message-input-non-codec.rs:3:1 | -1 | #[ink::contract] - | ^^^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonCodecType`, which is required by `NonCodecType: Encode` +3 | #[ink::contract] + | ^^^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonCodecType` ... -16 | pub fn message(&self, _input: NonCodecType) {} +18 | pub fn message(&self, _input: NonCodecType) {} | ---------------------------------------------- required by a bound introduced by this call | = help: the following other types implement trait `WrapperTypeEncode`: @@ -61,10 +61,10 @@ note: required by a bound in `ExecutionInput::>::push_arg` -error[E0599]: the method `try_invoke` exists for struct `CallBuilder>, Set, ArgumentList>>>, Set>>`, but its trait bounds were not satisfied - --> tests/ui/contract/fail/message-input-non-codec.rs:16:9 +error[E0599]: the method `try_invoke` exists for struct `CallBuilder, Set, ArgumentList>>>, Set>>`, but its trait bounds were not satisfied + --> tests/ui/contract/fail/message-input-non-codec.rs:18:9 | -16 | pub fn message(&self, _input: NonCodecType) {} +18 | pub fn message(&self, _input: NonCodecType) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ::: $WORKSPACE/crates/env/src/call/execution.rs diff --git a/crates/ink/tests/ui/contract/fail/message-input-pattern.rs b/crates/ink/tests/ui/contract/fail/message-input-pattern.rs index 9e23dc5e1d7..54a428a56bc 100644 --- a/crates/ink/tests/ui/contract/fail/message-input-pattern.rs +++ b/crates/ink/tests/ui/contract/fail/message-input-pattern.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/message-input-pattern.stderr b/crates/ink/tests/ui/contract/fail/message-input-pattern.stderr index c11b1b6f033..f74e49855d4 100644 --- a/crates/ink/tests/ui/contract/fail/message-input-pattern.stderr +++ b/crates/ink/tests/ui/contract/fail/message-input-pattern.stderr @@ -1,5 +1,5 @@ error: ink! message arguments must have an identifier - --> tests/ui/contract/fail/message-input-pattern.rs:13:31 + --> tests/ui/contract/fail/message-input-pattern.rs:15:31 | -13 | pub fn message(&self, (_a, _b): (i32, i32)) {} +15 | pub fn message(&self, (_a, _b): (i32, i32)) {} | ^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/message-multiple-wildcard-selectors.rs b/crates/ink/tests/ui/contract/fail/message-multiple-wildcard-selectors.rs index 8a0c160c8cd..25b2a7d56ad 100644 --- a/crates/ink/tests/ui/contract/fail/message-multiple-wildcard-selectors.rs +++ b/crates/ink/tests/ui/contract/fail/message-multiple-wildcard-selectors.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/message-multiple-wildcard-selectors.stderr b/crates/ink/tests/ui/contract/fail/message-multiple-wildcard-selectors.stderr index 3168335a67c..d063519224f 100644 --- a/crates/ink/tests/ui/contract/fail/message-multiple-wildcard-selectors.stderr +++ b/crates/ink/tests/ui/contract/fail/message-multiple-wildcard-selectors.stderr @@ -1,11 +1,11 @@ error: encountered ink! messages with overlapping wildcard selectors - --> tests/ui/contract/fail/message-multiple-wildcard-selectors.rs:16:9 + --> tests/ui/contract/fail/message-multiple-wildcard-selectors.rs:18:9 | -16 | pub fn message2(&self) {} +18 | pub fn message2(&self) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^ error: first ink! message with overlapping wildcard selector here - --> tests/ui/contract/fail/message-multiple-wildcard-selectors.rs:13:9 + --> tests/ui/contract/fail/message-multiple-wildcard-selectors.rs:15:9 | -13 | pub fn message1(&self) {} +15 | pub fn message1(&self) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/message-returns-non-codec.rs b/crates/ink/tests/ui/contract/fail/message-returns-non-codec.rs index 96335e8ac28..2ccf357b0ec 100644 --- a/crates/ink/tests/ui/contract/fail/message-returns-non-codec.rs +++ b/crates/ink/tests/ui/contract/fail/message-returns-non-codec.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[::ink::scale_derive(TypeInfo)] diff --git a/crates/ink/tests/ui/contract/fail/message-returns-non-codec.stderr b/crates/ink/tests/ui/contract/fail/message-returns-non-codec.stderr index 4240f0173d3..f5e18e2ea6b 100644 --- a/crates/ink/tests/ui/contract/fail/message-returns-non-codec.stderr +++ b/crates/ink/tests/ui/contract/fail/message-returns-non-codec.stderr @@ -1,8 +1,8 @@ error[E0277]: the trait bound `NonCodecType: WrapperTypeEncode` is not satisfied - --> tests/ui/contract/fail/message-returns-non-codec.rs:16:34 + --> tests/ui/contract/fail/message-returns-non-codec.rs:18:34 | -16 | pub fn message(&self) -> NonCodecType { - | ^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonCodecType`, which is required by `NonCodecType: Encode` +18 | pub fn message(&self) -> NonCodecType { + | ^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonCodecType` | = help: the following other types implement trait `WrapperTypeEncode`: &T @@ -25,11 +25,11 @@ note: required by a bound in `DispatchOutput` | ^^^^^^^^^^^^^ required by this bound in `DispatchOutput` error[E0277]: the trait bound `Result: Encode` is not satisfied - --> tests/ui/contract/fail/message-returns-non-codec.rs:16:9 + --> tests/ui/contract/fail/message-returns-non-codec.rs:18:9 | -16 | / pub fn message(&self) -> NonCodecType { -17 | | NonCodecType -18 | | } +18 | / pub fn message(&self) -> NonCodecType { +19 | | NonCodecType +20 | | } | |_________^ the trait `Encode` is not implemented for `Result` | = help: the trait `Encode` is implemented for `Result` @@ -42,15 +42,15 @@ note: required by a bound in `return_value` | R: scale::Encode, | ^^^^^^^^^^^^^ required by this bound in `return_value` -error[E0599]: the method `try_invoke` exists for struct `CallBuilder>, Set>>, Set>>`, but its trait bounds were not satisfied - --> tests/ui/contract/fail/message-returns-non-codec.rs:16:9 +error[E0599]: the method `try_invoke` exists for struct `CallBuilder, Set>>, Set>>`, but its trait bounds were not satisfied + --> tests/ui/contract/fail/message-returns-non-codec.rs:18:9 | -4 | pub struct NonCodecType; +6 | pub struct NonCodecType; | ----------------------- doesn't satisfy `NonCodecType: WrapperTypeDecode` or `NonCodecType: ink::parity_scale_codec::Decode` ... -16 | / pub fn message(&self) -> NonCodecType { -17 | | NonCodecType -18 | | } +18 | / pub fn message(&self) -> NonCodecType { +19 | | NonCodecType +20 | | } | |_________^ | = note: the following trait bounds were not satisfied: diff --git a/crates/ink/tests/ui/contract/fail/message-returns-self.rs b/crates/ink/tests/ui/contract/fail/message-returns-self.rs index 75f5390ca39..d22085ddab1 100644 --- a/crates/ink/tests/ui/contract/fail/message-returns-self.rs +++ b/crates/ink/tests/ui/contract/fail/message-returns-self.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/message-returns-self.stderr b/crates/ink/tests/ui/contract/fail/message-returns-self.stderr index 78aaac0e8d8..7dea02f224d 100644 --- a/crates/ink/tests/ui/contract/fail/message-returns-self.stderr +++ b/crates/ink/tests/ui/contract/fail/message-returns-self.stderr @@ -1,5 +1,5 @@ error: ink! messages must not return `Self` - --> tests/ui/contract/fail/message-returns-self.rs:13:39 + --> tests/ui/contract/fail/message-returns-self.rs:15:39 | -13 | pub fn returns_self(&self) -> Self {} +15 | pub fn returns_self(&self) -> Self {} | ^^^^ diff --git a/crates/ink/tests/ui/contract/fail/message-selector-and-wildcard-selector.rs b/crates/ink/tests/ui/contract/fail/message-selector-and-wildcard-selector.rs index 6cf8a3a5e4b..0f2c9a3966e 100644 --- a/crates/ink/tests/ui/contract/fail/message-selector-and-wildcard-selector.rs +++ b/crates/ink/tests/ui/contract/fail/message-selector-and-wildcard-selector.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/message-selector-and-wildcard-selector.stderr b/crates/ink/tests/ui/contract/fail/message-selector-and-wildcard-selector.stderr index bc619b19899..246e1a606e6 100644 --- a/crates/ink/tests/ui/contract/fail/message-selector-and-wildcard-selector.stderr +++ b/crates/ink/tests/ui/contract/fail/message-selector-and-wildcard-selector.stderr @@ -1,11 +1,11 @@ error: encountered ink! attribute arguments with equal kinds - --> tests/ui/contract/fail/message-selector-and-wildcard-selector.rs:12:47 + --> tests/ui/contract/fail/message-selector-and-wildcard-selector.rs:14:47 | -12 | #[ink(message, selector = 0xCAFEBABA, selector = _)] +14 | #[ink(message, selector = 0xCAFEBABA, selector = _)] | ^^^^^^^^^^^^ error: first equal ink! attribute argument with equal kind here - --> tests/ui/contract/fail/message-selector-and-wildcard-selector.rs:12:24 + --> tests/ui/contract/fail/message-selector-and-wildcard-selector.rs:14:24 | -12 | #[ink(message, selector = 0xCAFEBABA, selector = _)] +14 | #[ink(message, selector = 0xCAFEBABA, selector = _)] | ^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-01.rs b/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-01.rs index 500d780a0ce..f51f4bb9765 100644 --- a/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-01.rs +++ b/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-01.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-01.stderr b/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-01.stderr index 0e47feb6e77..9786542a5e0 100644 --- a/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-01.stderr +++ b/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-01.stderr @@ -1,5 +1,5 @@ error: #[ink(selector = ..)] attributes with string inputs are deprecated. use an integer instead, e.g. #[ink(selector = 1)] or #[ink(selector = 0xC0DECAFE)]. - --> tests/ui/contract/fail/message-selector-invalid-type-01.rs:12:35 + --> tests/ui/contract/fail/message-selector-invalid-type-01.rs:14:35 | -12 | #[ink(message, selector = "0xC0DECAFE")] +14 | #[ink(message, selector = "0xC0DECAFE")] | ^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-02.rs b/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-02.rs index 6f06ddf5f22..6eaa6163a70 100644 --- a/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-02.rs +++ b/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-02.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-02.stderr b/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-02.stderr index ecd9623eed0..3de6b9be62c 100644 --- a/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-02.stderr +++ b/crates/ink/tests/ui/contract/fail/message-selector-invalid-type-02.stderr @@ -1,5 +1,5 @@ error: expected 4-digit hexcode for `selector` argument, e.g. #[ink(selector = 0xC0FEBABE] - --> tests/ui/contract/fail/message-selector-invalid-type-02.rs:12:35 + --> tests/ui/contract/fail/message-selector-invalid-type-02.rs:14:35 | -12 | #[ink(message, selector = true)] +14 | #[ink(message, selector = true)] | ^^^^ diff --git a/crates/ink/tests/ui/contract/fail/message-selector-missing-arg.rs b/crates/ink/tests/ui/contract/fail/message-selector-missing-arg.rs index ee63366754c..048732ed8be 100644 --- a/crates/ink/tests/ui/contract/fail/message-selector-missing-arg.rs +++ b/crates/ink/tests/ui/contract/fail/message-selector-missing-arg.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/message-selector-missing-arg.stderr b/crates/ink/tests/ui/contract/fail/message-selector-missing-arg.stderr index 289105dedd6..2e5d84a55c8 100644 --- a/crates/ink/tests/ui/contract/fail/message-selector-missing-arg.stderr +++ b/crates/ink/tests/ui/contract/fail/message-selector-missing-arg.stderr @@ -1,5 +1,5 @@ error: encountered #[ink(selector)] that is missing its u32 parameter. Did you mean #[ink(selector = value: u32)] ? - --> tests/ui/contract/fail/message-selector-missing-arg.rs:12:24 + --> tests/ui/contract/fail/message-selector-missing-arg.rs:14:24 | -12 | #[ink(message, selector)] +14 | #[ink(message, selector)] | ^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-01.rs b/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-01.rs index 23c950da488..47c1ebfadce 100644 --- a/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-01.rs +++ b/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-01.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-01.stderr b/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-01.stderr index b8069624fb1..2f8df8130e3 100644 --- a/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-01.stderr +++ b/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-01.stderr @@ -1,5 +1,5 @@ error: ink! messages must have `&self` or `&mut self` receiver - --> tests/ui/contract/fail/message-self-receiver-invalid-01.rs:13:24 + --> tests/ui/contract/fail/message-self-receiver-invalid-01.rs:15:24 | -13 | pub fn message(this: &Self) {} +15 | pub fn message(this: &Self) {} | ^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-02.rs b/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-02.rs index b3470c1c774..dcd7f9412ba 100644 --- a/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-02.rs +++ b/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-02.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-02.stderr b/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-02.stderr index e64d38d8146..3caaa0e6a71 100644 --- a/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-02.stderr +++ b/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-02.stderr @@ -1,5 +1,5 @@ error: ink! messages must have `&self` or `&mut self` receiver - --> tests/ui/contract/fail/message-self-receiver-invalid-02.rs:13:24 + --> tests/ui/contract/fail/message-self-receiver-invalid-02.rs:15:24 | -13 | pub fn message(this: &mut Self) {} +15 | pub fn message(this: &mut Self) {} | ^^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-03.rs b/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-03.rs index 9fe4f11023e..ff6156015e2 100644 --- a/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-03.rs +++ b/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-03.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-03.stderr b/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-03.stderr index 6477e778dc0..0c95e3170d5 100644 --- a/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-03.stderr +++ b/crates/ink/tests/ui/contract/fail/message-self-receiver-invalid-03.stderr @@ -1,5 +1,5 @@ error: ink! messages must have `&self` or `&mut self` receiver - --> tests/ui/contract/fail/message-self-receiver-invalid-03.rs:13:24 + --> tests/ui/contract/fail/message-self-receiver-invalid-03.rs:15:24 | -13 | pub fn message(self) {} +15 | pub fn message(self) {} | ^^^^ diff --git a/crates/ink/tests/ui/contract/fail/message-self-receiver-missing.rs b/crates/ink/tests/ui/contract/fail/message-self-receiver-missing.rs index 182c508fe54..d10aca03756 100644 --- a/crates/ink/tests/ui/contract/fail/message-self-receiver-missing.rs +++ b/crates/ink/tests/ui/contract/fail/message-self-receiver-missing.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/message-self-receiver-missing.stderr b/crates/ink/tests/ui/contract/fail/message-self-receiver-missing.stderr index 9b40617be97..5a145a27650 100644 --- a/crates/ink/tests/ui/contract/fail/message-self-receiver-missing.stderr +++ b/crates/ink/tests/ui/contract/fail/message-self-receiver-missing.stderr @@ -1,6 +1,6 @@ error: ink! messages must have `&self` or `&mut self` receiver - --> tests/ui/contract/fail/message-self-receiver-missing.rs:12:9 + --> tests/ui/contract/fail/message-self-receiver-missing.rs:14:9 | -12 | / #[ink(message)] -13 | | pub fn message() {} +14 | / #[ink(message)] +15 | | pub fn message() {} | |___________________________^ diff --git a/crates/ink/tests/ui/contract/fail/message-unknown-property.rs b/crates/ink/tests/ui/contract/fail/message-unknown-property.rs index 375088ce8da..bc969da7fb6 100644 --- a/crates/ink/tests/ui/contract/fail/message-unknown-property.rs +++ b/crates/ink/tests/ui/contract/fail/message-unknown-property.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/message-unknown-property.stderr b/crates/ink/tests/ui/contract/fail/message-unknown-property.stderr index 143ef03a4b7..cd1cf9fcd7e 100644 --- a/crates/ink/tests/ui/contract/fail/message-unknown-property.stderr +++ b/crates/ink/tests/ui/contract/fail/message-unknown-property.stderr @@ -1,5 +1,5 @@ error: encountered unknown ink! attribute argument: unknown_marker - --> tests/ui/contract/fail/message-unknown-property.rs:13:15 + --> tests/ui/contract/fail/message-unknown-property.rs:15:15 | -13 | #[ink(unknown_marker)] +15 | #[ink(unknown_marker)] | ^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/module-missing-constructor.rs b/crates/ink/tests/ui/contract/fail/module-missing-constructor.rs index 84641ad4764..51a1c5cfeeb 100644 --- a/crates/ink/tests/ui/contract/fail/module-missing-constructor.rs +++ b/crates/ink/tests/ui/contract/fail/module-missing-constructor.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/module-missing-constructor.stderr b/crates/ink/tests/ui/contract/fail/module-missing-constructor.stderr index 4f07a523ddf..8b6aa7debb0 100644 --- a/crates/ink/tests/ui/contract/fail/module-missing-constructor.stderr +++ b/crates/ink/tests/ui/contract/fail/module-missing-constructor.stderr @@ -1,10 +1,10 @@ error: missing ink! constructor - --> tests/ui/contract/fail/module-missing-constructor.rs:2:1 + --> tests/ui/contract/fail/module-missing-constructor.rs:4:1 | -2 | / mod contract { -3 | | #[ink(storage)] -4 | | pub struct Contract {} +4 | / mod contract { +5 | | #[ink(storage)] +6 | | pub struct Contract {} ... | -9 | | } -10 | | } +11 | | } +12 | | } | |_^ diff --git a/crates/ink/tests/ui/contract/fail/module-missing-message.rs b/crates/ink/tests/ui/contract/fail/module-missing-message.rs index a6216b40b79..ca1ac8a012c 100644 --- a/crates/ink/tests/ui/contract/fail/module-missing-message.rs +++ b/crates/ink/tests/ui/contract/fail/module-missing-message.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/module-missing-message.stderr b/crates/ink/tests/ui/contract/fail/module-missing-message.stderr index 06fd0a83793..2e31adf649c 100644 --- a/crates/ink/tests/ui/contract/fail/module-missing-message.stderr +++ b/crates/ink/tests/ui/contract/fail/module-missing-message.stderr @@ -1,10 +1,10 @@ error: missing ink! message - --> tests/ui/contract/fail/module-missing-message.rs:2:1 + --> tests/ui/contract/fail/module-missing-message.rs:4:1 | -2 | / mod contract { -3 | | #[ink(storage)] -4 | | pub struct Contract {} +4 | / mod contract { +5 | | #[ink(storage)] +6 | | pub struct Contract {} ... | -11 | | } -12 | | } +13 | | } +14 | | } | |_^ diff --git a/crates/ink/tests/ui/contract/fail/module-missing-storage.rs b/crates/ink/tests/ui/contract/fail/module-missing-storage.rs index 2069cc27434..d671fb9dc38 100644 --- a/crates/ink/tests/ui/contract/fail/module-missing-storage.rs +++ b/crates/ink/tests/ui/contract/fail/module-missing-storage.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { // #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/module-missing-storage.stderr b/crates/ink/tests/ui/contract/fail/module-missing-storage.stderr index fa33734f448..ac922639ddc 100644 --- a/crates/ink/tests/ui/contract/fail/module-missing-storage.stderr +++ b/crates/ink/tests/ui/contract/fail/module-missing-storage.stderr @@ -1,10 +1,10 @@ error: missing ink! storage struct - --> tests/ui/contract/fail/module-missing-storage.rs:2:1 + --> tests/ui/contract/fail/module-missing-storage.rs:4:1 | -2 | / mod contract { -3 | | // #[ink(storage)] -4 | | pub struct Contract {} +4 | / mod contract { +5 | | // #[ink(storage)] +6 | | pub struct Contract {} ... | -12 | | } -13 | | } +14 | | } +15 | | } | |_^ diff --git a/crates/ink/tests/ui/contract/fail/module-multiple-storages.rs b/crates/ink/tests/ui/contract/fail/module-multiple-storages.rs index 1299bac5d27..054240862b1 100644 --- a/crates/ink/tests/ui/contract/fail/module-multiple-storages.rs +++ b/crates/ink/tests/ui/contract/fail/module-multiple-storages.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/module-multiple-storages.stderr b/crates/ink/tests/ui/contract/fail/module-multiple-storages.stderr index dd635dc707a..d5151e82304 100644 --- a/crates/ink/tests/ui/contract/fail/module-multiple-storages.stderr +++ b/crates/ink/tests/ui/contract/fail/module-multiple-storages.stderr @@ -1,22 +1,22 @@ error: encountered multiple ink! storage structs, expected exactly one - --> tests/ui/contract/fail/module-multiple-storages.rs:2:1 + --> tests/ui/contract/fail/module-multiple-storages.rs:4:1 | -2 | / mod contract { -3 | | #[ink(storage)] -4 | | pub struct Contract {} +4 | / mod contract { +5 | | #[ink(storage)] +6 | | pub struct Contract {} ... | -27 | | } -28 | | } +29 | | } +30 | | } | |_^ error: ink! storage struct here - --> tests/ui/contract/fail/module-multiple-storages.rs:4:5 + --> tests/ui/contract/fail/module-multiple-storages.rs:6:5 | -4 | pub struct Contract {} +6 | pub struct Contract {} | ^^^^^^^^^^^^^^^^^^^^^^ error: ink! storage struct here - --> tests/ui/contract/fail/module-multiple-storages.rs:17:5 + --> tests/ui/contract/fail/module-multiple-storages.rs:19:5 | -17 | pub struct Contract2 {} +19 | pub struct Contract2 {} | ^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/module-use-forbidden-idents.rs b/crates/ink/tests/ui/contract/fail/module-use-forbidden-idents.rs index b3076b6cc5e..355db03d644 100644 --- a/crates/ink/tests/ui/contract/fail/module-use-forbidden-idents.rs +++ b/crates/ink/tests/ui/contract/fail/module-use-forbidden-idents.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod __ink_contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/module-use-forbidden-idents.stderr b/crates/ink/tests/ui/contract/fail/module-use-forbidden-idents.stderr index 1ff16a1a3e5..2a326233af2 100644 --- a/crates/ink/tests/ui/contract/fail/module-use-forbidden-idents.stderr +++ b/crates/ink/tests/ui/contract/fail/module-use-forbidden-idents.stderr @@ -1,83 +1,83 @@ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:2:5 + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:4:5 | -2 | mod __ink_contract { +4 | mod __ink_contract { | ^^^^^^^^^^^^^^ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:4:16 + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:6:16 | -4 | pub struct __ink_Contract {} +6 | pub struct __ink_Contract {} | ^^^^^^^^^^^^^^ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:6:11 + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:8:11 | -6 | const __ink_CONST: () = (); +8 | const __ink_CONST: () = (); | ^^^^^^^^^^^ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:7:12 + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:9:12 | -7 | static __ink_STATIC: () = (); +9 | static __ink_STATIC: () = (); | ^^^^^^^^^^^^ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:8:10 - | -8 | type __ink_Type = (); - | ^^^^^^^^^^ + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:10:10 + | +10 | type __ink_Type = (); + | ^^^^^^^^^^ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:10:10 + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:12:10 | -10 | impl __ink_Contract { +12 | impl __ink_Contract { | ^^^^^^^^^^^^^^ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:12:16 + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:14:16 | -12 | pub fn __ink_constructor(__ink_input: __ink_Type) -> Self { +14 | pub fn __ink_constructor(__ink_input: __ink_Type) -> Self { | ^^^^^^^^^^^^^^^^^ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:12:34 + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:14:34 | -12 | pub fn __ink_constructor(__ink_input: __ink_Type) -> Self { +14 | pub fn __ink_constructor(__ink_input: __ink_Type) -> Self { | ^^^^^^^^^^^ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:12:47 + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:14:47 | -12 | pub fn __ink_constructor(__ink_input: __ink_Type) -> Self { +14 | pub fn __ink_constructor(__ink_input: __ink_Type) -> Self { | ^^^^^^^^^^ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:17:16 + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:19:16 | -17 | pub fn __ink_message(&self, __ink_input: __ink_Type) -> __ink_Type { +19 | pub fn __ink_message(&self, __ink_input: __ink_Type) -> __ink_Type { | ^^^^^^^^^^^^^ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:17:37 + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:19:37 | -17 | pub fn __ink_message(&self, __ink_input: __ink_Type) -> __ink_Type { +19 | pub fn __ink_message(&self, __ink_input: __ink_Type) -> __ink_Type { | ^^^^^^^^^^^ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:17:50 + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:19:50 | -17 | pub fn __ink_message(&self, __ink_input: __ink_Type) -> __ink_Type { +19 | pub fn __ink_message(&self, __ink_input: __ink_Type) -> __ink_Type { | ^^^^^^^^^^ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:17:65 + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:19:65 | -17 | pub fn __ink_message(&self, __ink_input: __ink_Type) -> __ink_Type { +19 | pub fn __ink_message(&self, __ink_input: __ink_Type) -> __ink_Type { | ^^^^^^^^^^ error: encountered invalid identifier starting with __ink_ - --> tests/ui/contract/fail/module-use-forbidden-idents.rs:18:17 + --> tests/ui/contract/fail/module-use-forbidden-idents.rs:20:17 | -18 | let __ink_first = (); +20 | let __ink_first = (); | ^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/storage-conflicting-event.rs b/crates/ink/tests/ui/contract/fail/storage-conflicting-event.rs index 897c6ae8d3f..0d4b5615b9b 100644 --- a/crates/ink/tests/ui/contract/fail/storage-conflicting-event.rs +++ b/crates/ink/tests/ui/contract/fail/storage-conflicting-event.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/storage-conflicting-event.stderr b/crates/ink/tests/ui/contract/fail/storage-conflicting-event.stderr index b4095f6eda2..84ef72bc72b 100644 --- a/crates/ink/tests/ui/contract/fail/storage-conflicting-event.stderr +++ b/crates/ink/tests/ui/contract/fail/storage-conflicting-event.stderr @@ -1,5 +1,5 @@ error: encountered conflicting ink! attribute argument - --> tests/ui/contract/fail/storage-conflicting-event.rs:4:11 + --> tests/ui/contract/fail/storage-conflicting-event.rs:6:11 | -4 | #[ink(event)] +6 | #[ink(event)] | ^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/storage-unknown-marker.rs b/crates/ink/tests/ui/contract/fail/storage-unknown-marker.rs index d2b33c3c300..211a6ebefba 100644 --- a/crates/ink/tests/ui/contract/fail/storage-unknown-marker.rs +++ b/crates/ink/tests/ui/contract/fail/storage-unknown-marker.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/fail/storage-unknown-marker.stderr b/crates/ink/tests/ui/contract/fail/storage-unknown-marker.stderr index b3c9cbbd14d..0d1143674a8 100644 --- a/crates/ink/tests/ui/contract/fail/storage-unknown-marker.stderr +++ b/crates/ink/tests/ui/contract/fail/storage-unknown-marker.stderr @@ -1,5 +1,5 @@ error: encountered unknown ink! attribute argument: unknown_or_unsupported - --> tests/ui/contract/fail/storage-unknown-marker.rs:4:11 + --> tests/ui/contract/fail/storage-unknown-marker.rs:6:11 | -4 | #[ink(unknown_or_unsupported)] +6 | #[ink(unknown_or_unsupported)] | ^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/ink/tests/ui/contract/fail/trait-impl-namespace-invalid.rs b/crates/ink/tests/ui/contract/fail/trait-impl-namespace-invalid.rs index dd314e3c756..e55024c8a51 100644 --- a/crates/ink/tests/ui/contract/fail/trait-impl-namespace-invalid.rs +++ b/crates/ink/tests/ui/contract/fail/trait-impl-namespace-invalid.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::trait_definition] pub trait TraitDefinition { #[ink(message)] diff --git a/crates/ink/tests/ui/contract/fail/trait-impl-namespace-invalid.stderr b/crates/ink/tests/ui/contract/fail/trait-impl-namespace-invalid.stderr index 3d6a3f352d7..bf03fd4337f 100644 --- a/crates/ink/tests/ui/contract/fail/trait-impl-namespace-invalid.stderr +++ b/crates/ink/tests/ui/contract/fail/trait-impl-namespace-invalid.stderr @@ -1,9 +1,9 @@ error: namespace ink! property is not allowed on ink! trait implementation blocks - --> tests/ui/contract/fail/trait-impl-namespace-invalid.rs:21:5 + --> tests/ui/contract/fail/trait-impl-namespace-invalid.rs:23:5 | -21 | / #[ink(namespace = "namespace")] -22 | | impl TraitDefinition for Contract { -23 | | #[ink(message)] -24 | | fn message(&self) {} -25 | | } +23 | / #[ink(namespace = "namespace")] +24 | | impl TraitDefinition for Contract { +25 | | #[ink(message)] +26 | | fn message(&self) {} +27 | | } | |_____^ diff --git a/crates/ink/tests/ui/contract/fail/trait-message-payable-mismatch.rs b/crates/ink/tests/ui/contract/fail/trait-message-payable-mismatch.rs index 0acc8494869..8d58e9e6dcf 100644 --- a/crates/ink/tests/ui/contract/fail/trait-message-payable-mismatch.rs +++ b/crates/ink/tests/ui/contract/fail/trait-message-payable-mismatch.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::trait_definition] pub trait TraitDefinition { #[ink(message)] diff --git a/crates/ink/tests/ui/contract/fail/trait-message-payable-mismatch.stderr b/crates/ink/tests/ui/contract/fail/trait-message-payable-mismatch.stderr index 3dd203b4d4a..4c6a717217f 100644 --- a/crates/ink/tests/ui/contract/fail/trait-message-payable-mismatch.stderr +++ b/crates/ink/tests/ui/contract/fail/trait-message-payable-mismatch.stderr @@ -1,7 +1,7 @@ error[E0308]: mismatched types - --> tests/ui/contract/fail/trait-message-payable-mismatch.rs:23:9 + --> tests/ui/contract/fail/trait-message-payable-mismatch.rs:25:9 | -23 | fn message(&self) {} +25 | fn message(&self) {} | ^^^^^^^^^^^^^^^^^^^^ expected `false`, found `true` | = note: expected struct `TraitMessagePayable` diff --git a/crates/ink/tests/ui/contract/fail/trait-message-selector-mismatch.rs b/crates/ink/tests/ui/contract/fail/trait-message-selector-mismatch.rs index 9ef7bae22ce..8c3cd3531fb 100644 --- a/crates/ink/tests/ui/contract/fail/trait-message-selector-mismatch.rs +++ b/crates/ink/tests/ui/contract/fail/trait-message-selector-mismatch.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::trait_definition] pub trait TraitDefinition { #[ink(message, selector = 1)] diff --git a/crates/ink/tests/ui/contract/fail/trait-message-selector-mismatch.stderr b/crates/ink/tests/ui/contract/fail/trait-message-selector-mismatch.stderr index abb792b0038..c1070999dba 100644 --- a/crates/ink/tests/ui/contract/fail/trait-message-selector-mismatch.stderr +++ b/crates/ink/tests/ui/contract/fail/trait-message-selector-mismatch.stderr @@ -1,7 +1,7 @@ error[E0308]: mismatched types - --> tests/ui/contract/fail/trait-message-selector-mismatch.rs:23:9 + --> tests/ui/contract/fail/trait-message-selector-mismatch.rs:25:9 | -23 | fn message(&self) {} +25 | fn message(&self) {} | ^^^^^^^^^^^^^^^^^^^^ expected `1`, found `2` | = note: expected struct `TraitMessageSelector<1>` diff --git a/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-1.rs b/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-1.rs index 1f1cd9ef636..7748290264a 100644 --- a/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-1.rs +++ b/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-1.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + mod foo1 { #[ink::trait_definition] pub trait TraitDefinition { diff --git a/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-1.stderr b/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-1.stderr index 1520d4d85f8..2c41a8b2fbe 100644 --- a/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-1.stderr +++ b/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-1.stderr @@ -1,31 +1,31 @@ error[E0119]: conflicting implementations of trait `DispatchableMessageInfo<1083895717>` for type `Contract` - --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:41:9 + --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:43:9 | -36 | fn message(&self) {} +38 | fn message(&self) {} | -------------------- first implementation here ... -41 | fn message(&self) {} +43 | fn message(&self) {} | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Contract` error[E0119]: conflicting implementations of trait `TraitCallForwarderFor<1083895717>` for type `contract::_::CallBuilder` - --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:39:5 + --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:41:5 | -34 | / impl TraitDefinition1 for Contract { -35 | | #[ink(message)] -36 | | fn message(&self) {} -37 | | } +36 | / impl TraitDefinition1 for Contract { +37 | | #[ink(message)] +38 | | fn message(&self) {} +39 | | } | |_____- first implementation here -38 | -39 | / impl TraitDefinition2 for Contract { -40 | | #[ink(message)] -41 | | fn message(&self) {} -42 | | } +40 | +41 | / impl TraitDefinition2 for Contract { +42 | | #[ink(message)] +43 | | fn message(&self) {} +44 | | } | |_____^ conflicting implementation for `contract::_::CallBuilder` error[E0283]: type annotations needed - --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:17:1 + --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:19:1 | -17 | #[ink::contract] +19 | #[ink::contract] | ^^^^^^^^^^^^^^^^ | | | cannot infer type @@ -40,20 +40,20 @@ error[E0283]: type annotations needed - impl ImpliesReturn for T; = note: associated types cannot be accessed directly on a `trait`, they can only be accessed through a specific `impl` note: required by a bound in `foo1::TraitDefinition::messageOutput` - --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:4:9 + --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:6:9 | -2 | #[ink::trait_definition] +4 | #[ink::trait_definition] | ------------------------ required by a bound in this associated type -3 | pub trait TraitDefinition { -4 | / #[ink(message)] -5 | | fn message(&self); +5 | pub trait TraitDefinition { +6 | / #[ink(message)] +7 | | fn message(&self); | |__________________________^ required by this bound in `TraitDefinition::messageOutput` = note: this error originates in the attribute macro `ink::contract` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0283]: type annotations needed - --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:17:1 + --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:19:1 | -17 | #[ink::contract] +19 | #[ink::contract] | ^^^^^^^^^^^^^^^^ | | | cannot infer type @@ -68,28 +68,28 @@ error[E0283]: type annotations needed - impl ImpliesReturn for T; = note: associated types cannot be accessed directly on a `trait`, they can only be accessed through a specific `impl` note: required by a bound in `foo2::TraitDefinition::messageOutput` - --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:12:9 + --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:14:9 | -10 | #[ink::trait_definition] +12 | #[ink::trait_definition] | ------------------------ required by a bound in this associated type -11 | pub trait TraitDefinition { -12 | / #[ink(message)] -13 | | fn message(&self); +13 | pub trait TraitDefinition { +14 | / #[ink(message)] +15 | | fn message(&self); | |__________________________^ required by this bound in `TraitDefinition::messageOutput` = note: this error originates in the attribute macro `ink::contract` (in Nightly builds, run with -Z macro-backtrace for more info) warning: this function depends on never type fallback being `()` - --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:25:5 + --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:27:5 | -25 | pub struct Contract {} +27 | pub struct Contract {} | ^^^^^^^^^^^^^^^^^^^^^^ | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in Rust 2024 and in a future release in all editions! = note: for more information, see issue #123748 = help: specify the types explicitly note: in edition 2024, the requirement `!: WrapperTypeDecode` will fail - --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:36:9 + --> tests/ui/contract/fail/trait-message-selector-overlap-1.rs:38:9 | -36 | fn message(&self) {} +38 | fn message(&self) {} | ^^^^^^^^^^^^^^^^^^^^ = note: `#[warn(dependency_on_unit_never_type_fallback)]` on by default diff --git a/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-2.rs b/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-2.rs index 5d4a6cb0c44..d85bb969cbc 100644 --- a/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-2.rs +++ b/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-2.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + mod foo1 { #[ink::trait_definition(namespace = "same")] pub trait TraitDefinition { diff --git a/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-2.stderr b/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-2.stderr index 395c19177c9..15138d2d317 100644 --- a/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-2.stderr +++ b/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-2.stderr @@ -1,31 +1,31 @@ error[E0119]: conflicting implementations of trait `DispatchableMessageInfo<1518209067>` for type `Contract` - --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:41:9 + --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:43:9 | -36 | fn message(&self) {} +38 | fn message(&self) {} | -------------------- first implementation here ... -41 | fn message(&self) {} +43 | fn message(&self) {} | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Contract` error[E0119]: conflicting implementations of trait `TraitCallForwarderFor<1518209067>` for type `contract::_::CallBuilder` - --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:39:5 + --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:41:5 | -34 | / impl TraitDefinition1 for Contract { -35 | | #[ink(message)] -36 | | fn message(&self) {} -37 | | } +36 | / impl TraitDefinition1 for Contract { +37 | | #[ink(message)] +38 | | fn message(&self) {} +39 | | } | |_____- first implementation here -38 | -39 | / impl TraitDefinition2 for Contract { -40 | | #[ink(message)] -41 | | fn message(&self) {} -42 | | } +40 | +41 | / impl TraitDefinition2 for Contract { +42 | | #[ink(message)] +43 | | fn message(&self) {} +44 | | } | |_____^ conflicting implementation for `contract::_::CallBuilder` error[E0283]: type annotations needed - --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:17:1 + --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:19:1 | -17 | #[ink::contract] +19 | #[ink::contract] | ^^^^^^^^^^^^^^^^ | | | cannot infer type @@ -40,20 +40,20 @@ error[E0283]: type annotations needed - impl ImpliesReturn for T; = note: associated types cannot be accessed directly on a `trait`, they can only be accessed through a specific `impl` note: required by a bound in `foo1::TraitDefinition::messageOutput` - --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:4:9 + --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:6:9 | -2 | #[ink::trait_definition(namespace = "same")] +4 | #[ink::trait_definition(namespace = "same")] | -------------------------------------------- required by a bound in this associated type -3 | pub trait TraitDefinition { -4 | / #[ink(message)] -5 | | fn message(&self); +5 | pub trait TraitDefinition { +6 | / #[ink(message)] +7 | | fn message(&self); | |__________________________^ required by this bound in `TraitDefinition::messageOutput` = note: this error originates in the attribute macro `ink::contract` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0283]: type annotations needed - --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:17:1 + --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:19:1 | -17 | #[ink::contract] +19 | #[ink::contract] | ^^^^^^^^^^^^^^^^ | | | cannot infer type @@ -68,28 +68,28 @@ error[E0283]: type annotations needed - impl ImpliesReturn for T; = note: associated types cannot be accessed directly on a `trait`, they can only be accessed through a specific `impl` note: required by a bound in `foo2::TraitDefinition::messageOutput` - --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:12:9 + --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:14:9 | -10 | #[ink::trait_definition(namespace = "same")] +12 | #[ink::trait_definition(namespace = "same")] | -------------------------------------------- required by a bound in this associated type -11 | pub trait TraitDefinition { -12 | / #[ink(message)] -13 | | fn message(&self); +13 | pub trait TraitDefinition { +14 | / #[ink(message)] +15 | | fn message(&self); | |__________________________^ required by this bound in `TraitDefinition::messageOutput` = note: this error originates in the attribute macro `ink::contract` (in Nightly builds, run with -Z macro-backtrace for more info) warning: this function depends on never type fallback being `()` - --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:25:5 + --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:27:5 | -25 | pub struct Contract {} +27 | pub struct Contract {} | ^^^^^^^^^^^^^^^^^^^^^^ | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in Rust 2024 and in a future release in all editions! = note: for more information, see issue #123748 = help: specify the types explicitly note: in edition 2024, the requirement `!: WrapperTypeDecode` will fail - --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:36:9 + --> tests/ui/contract/fail/trait-message-selector-overlap-2.rs:38:9 | -36 | fn message(&self) {} +38 | fn message(&self) {} | ^^^^^^^^^^^^^^^^^^^^ = note: `#[warn(dependency_on_unit_never_type_fallback)]` on by default diff --git a/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-3.rs b/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-3.rs index b327a3b5d00..ed967fb3d24 100644 --- a/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-3.rs +++ b/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-3.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + mod foo1 { #[ink::trait_definition] pub trait TraitDefinition1 { diff --git a/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-3.stderr b/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-3.stderr index 7ae1cf120f7..bdd8dec8236 100644 --- a/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-3.stderr +++ b/crates/ink/tests/ui/contract/fail/trait-message-selector-overlap-3.stderr @@ -1,31 +1,31 @@ error[E0119]: conflicting implementations of trait `DispatchableMessageInfo<42>` for type `Contract` - --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:41:9 + --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:43:9 | -36 | fn message1(&self) {} +38 | fn message1(&self) {} | --------------------- first implementation here ... -41 | fn message2(&self) {} +43 | fn message2(&self) {} | ^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Contract` error[E0119]: conflicting implementations of trait `TraitCallForwarderFor<42>` for type `contract::_::CallBuilder` - --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:39:5 + --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:41:5 | -34 | / impl TraitDefinition1 for Contract { -35 | | #[ink(message)] -36 | | fn message1(&self) {} -37 | | } +36 | / impl TraitDefinition1 for Contract { +37 | | #[ink(message)] +38 | | fn message1(&self) {} +39 | | } | |_____- first implementation here -38 | -39 | / impl TraitDefinition2 for Contract { -40 | | #[ink(message)] -41 | | fn message2(&self) {} -42 | | } +40 | +41 | / impl TraitDefinition2 for Contract { +42 | | #[ink(message)] +43 | | fn message2(&self) {} +44 | | } | |_____^ conflicting implementation for `contract::_::CallBuilder` error[E0283]: type annotations needed - --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:17:1 + --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:19:1 | -17 | #[ink::contract] +19 | #[ink::contract] | ^^^^^^^^^^^^^^^^ | | | cannot infer type @@ -40,20 +40,20 @@ error[E0283]: type annotations needed - impl ImpliesReturn for T; = note: associated types cannot be accessed directly on a `trait`, they can only be accessed through a specific `impl` note: required by a bound in `TraitDefinition1::message1Output` - --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:4:9 + --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:6:9 | -2 | #[ink::trait_definition] +4 | #[ink::trait_definition] | ------------------------ required by a bound in this associated type -3 | pub trait TraitDefinition1 { -4 | / #[ink(message, selector = 42)] -5 | | fn message1(&self); +5 | pub trait TraitDefinition1 { +6 | / #[ink(message, selector = 42)] +7 | | fn message1(&self); | |___________________________^ required by this bound in `TraitDefinition1::message1Output` = note: this error originates in the attribute macro `ink::contract` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0283]: type annotations needed - --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:17:1 + --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:19:1 | -17 | #[ink::contract] +19 | #[ink::contract] | ^^^^^^^^^^^^^^^^ | | | cannot infer type @@ -68,28 +68,28 @@ error[E0283]: type annotations needed - impl ImpliesReturn for T; = note: associated types cannot be accessed directly on a `trait`, they can only be accessed through a specific `impl` note: required by a bound in `TraitDefinition2::message2Output` - --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:12:9 + --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:14:9 | -10 | #[ink::trait_definition] +12 | #[ink::trait_definition] | ------------------------ required by a bound in this associated type -11 | pub trait TraitDefinition2 { -12 | / #[ink(message, selector = 42)] -13 | | fn message2(&self); +13 | pub trait TraitDefinition2 { +14 | / #[ink(message, selector = 42)] +15 | | fn message2(&self); | |___________________________^ required by this bound in `TraitDefinition2::message2Output` = note: this error originates in the attribute macro `ink::contract` (in Nightly builds, run with -Z macro-backtrace for more info) warning: this function depends on never type fallback being `()` - --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:25:5 + --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:27:5 | -25 | pub struct Contract {} +27 | pub struct Contract {} | ^^^^^^^^^^^^^^^^^^^^^^ | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in Rust 2024 and in a future release in all editions! = note: for more information, see issue #123748 = help: specify the types explicitly note: in edition 2024, the requirement `!: WrapperTypeDecode` will fail - --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:36:9 + --> tests/ui/contract/fail/trait-message-selector-overlap-3.rs:38:9 | -36 | fn message1(&self) {} +38 | fn message1(&self) {} | ^^^^^^^^^^^^^^^^^^^^^ = note: `#[warn(dependency_on_unit_never_type_fallback)]` on by default diff --git a/crates/ink/tests/ui/contract/fail/trait-message-wildcard-selector.rs b/crates/ink/tests/ui/contract/fail/trait-message-wildcard-selector.rs index 6ade19e6e97..bd72ec0954e 100644 --- a/crates/ink/tests/ui/contract/fail/trait-message-wildcard-selector.rs +++ b/crates/ink/tests/ui/contract/fail/trait-message-wildcard-selector.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + mod foo { #[ink::trait_definition] pub trait TraitDefinition { diff --git a/crates/ink/tests/ui/contract/fail/trait-message-wildcard-selector.stderr b/crates/ink/tests/ui/contract/fail/trait-message-wildcard-selector.stderr index a4e6d9e5ea8..7f3d044c24e 100644 --- a/crates/ink/tests/ui/contract/fail/trait-message-wildcard-selector.stderr +++ b/crates/ink/tests/ui/contract/fail/trait-message-wildcard-selector.stderr @@ -1,17 +1,17 @@ error: encountered conflicting ink! attribute argument - --> tests/ui/contract/fail/trait-message-wildcard-selector.rs:4:24 + --> tests/ui/contract/fail/trait-message-wildcard-selector.rs:6:24 | -4 | #[ink(message, selector = _)] +6 | #[ink(message, selector = _)] | ^^^^^^^^^^^^ error: wildcard selectors are only supported for inherent ink! messages or constructors, not for traits. - --> tests/ui/contract/fail/trait-message-wildcard-selector.rs:4:24 + --> tests/ui/contract/fail/trait-message-wildcard-selector.rs:6:24 | -4 | #[ink(message, selector = _)] +6 | #[ink(message, selector = _)] | ^^^^^^^^^^^^ error[E0432]: unresolved import `super::foo::TraitDefinition` - --> tests/ui/contract/fail/trait-message-wildcard-selector.rs:11:9 + --> tests/ui/contract/fail/trait-message-wildcard-selector.rs:13:9 | -11 | use super::foo::TraitDefinition; +13 | use super::foo::TraitDefinition; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ no `TraitDefinition` in `foo` diff --git a/crates/ink/tests/ui/contract/pass/cfg-allowed-usage-01.rs b/crates/ink/tests/ui/contract/pass/cfg-allowed-usage-01.rs index 94c34474f9f..ce99a2a818a 100644 --- a/crates/ink/tests/ui/contract/pass/cfg-allowed-usage-01.rs +++ b/crates/ink/tests/ui/contract/pass/cfg-allowed-usage-01.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/cfg-allowed-usage-02.rs b/crates/ink/tests/ui/contract/pass/cfg-allowed-usage-02.rs index 65e44806121..20180a06042 100644 --- a/crates/ink/tests/ui/contract/pass/cfg-allowed-usage-02.rs +++ b/crates/ink/tests/ui/contract/pass/cfg-allowed-usage-02.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/config-custom-env.rs b/crates/ink/tests/ui/contract/pass/config-custom-env.rs index d81a50ce30d..fc6b72e4342 100644 --- a/crates/ink/tests/ui/contract/pass/config-custom-env.rs +++ b/crates/ink/tests/ui/contract/pass/config-custom-env.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[derive(Clone)] pub struct CustomEnv; @@ -9,6 +11,7 @@ impl ink_env::Environment for CustomEnv { type Timestamp = u64; type BlockNumber = u64; type ChainExtension = (); + type EventRecord = (); } #[ink::contract(env = super::CustomEnv)] diff --git a/crates/ink/tests/ui/contract/pass/config-keep-attr.rs b/crates/ink/tests/ui/contract/pass/config-keep-attr.rs index 768424b482a..896f2b18e79 100644 --- a/crates/ink/tests/ui/contract/pass/config-keep-attr.rs +++ b/crates/ink/tests/ui/contract/pass/config-keep-attr.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract(keep_attr = "foo, bar")] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/constructor-aliases.rs b/crates/ink/tests/ui/contract/pass/constructor-aliases.rs index 5313880ab74..7cd32c14b48 100644 --- a/crates/ink/tests/ui/contract/pass/constructor-aliases.rs +++ b/crates/ink/tests/ui/contract/pass/constructor-aliases.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/constructor-many-inputs.rs b/crates/ink/tests/ui/contract/pass/constructor-many-inputs.rs index a70b4d5bfc7..cd70323678d 100644 --- a/crates/ink/tests/ui/contract/pass/constructor-many-inputs.rs +++ b/crates/ink/tests/ui/contract/pass/constructor-many-inputs.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/constructor-non-payable-multiple.rs b/crates/ink/tests/ui/contract/pass/constructor-non-payable-multiple.rs index 39ba033c2f0..d477e9748b1 100644 --- a/crates/ink/tests/ui/contract/pass/constructor-non-payable-multiple.rs +++ b/crates/ink/tests/ui/contract/pass/constructor-non-payable-multiple.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/constructor-non-payable.rs b/crates/ink/tests/ui/contract/pass/constructor-non-payable.rs index afb751f1073..9707ffe0ef1 100644 --- a/crates/ink/tests/ui/contract/pass/constructor-non-payable.rs +++ b/crates/ink/tests/ui/contract/pass/constructor-non-payable.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/constructor-payable-multiple.rs b/crates/ink/tests/ui/contract/pass/constructor-payable-multiple.rs index bad4dd1adcb..3d51e05c675 100644 --- a/crates/ink/tests/ui/contract/pass/constructor-payable-multiple.rs +++ b/crates/ink/tests/ui/contract/pass/constructor-payable-multiple.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/constructor-payable.rs b/crates/ink/tests/ui/contract/pass/constructor-payable.rs index f189dd98a52..ce3f739db24 100644 --- a/crates/ink/tests/ui/contract/pass/constructor-payable.rs +++ b/crates/ink/tests/ui/contract/pass/constructor-payable.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/constructor-return-result-alias.rs b/crates/ink/tests/ui/contract/pass/constructor-return-result-alias.rs index 644231392db..71dfe3d9210 100644 --- a/crates/ink/tests/ui/contract/pass/constructor-return-result-alias.rs +++ b/crates/ink/tests/ui/contract/pass/constructor-return-result-alias.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/constructor-return-result-cross-contract.rs b/crates/ink/tests/ui/contract/pass/constructor-return-result-cross-contract.rs index fd1ed118173..034b613c121 100644 --- a/crates/ink/tests/ui/contract/pass/constructor-return-result-cross-contract.rs +++ b/crates/ink/tests/ui/contract/pass/constructor-return-result-cross-contract.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract_callee { #[ink(storage)] @@ -44,36 +46,36 @@ fn main() { // fn new_self() -> Self let _: fn() -> CalleeRef = || { CalleeRef::new_self() - .code_hash(ink_primitives::Clear::CLEAR_HASH) - .endowment(25) - .salt_bytes([0xDE, 0xAD, 0xBE, 0xEF]) + .code_hash(ink::primitives::H256::zero()) + .endowment(ink::U256::from(25)) + .salt_bytes(Some([1u8; 32])) .instantiate() }; // fn new_storage_name() -> Callee let _: fn() -> CalleeRef = || { CalleeRef::new_storage_name() - .code_hash(ink_primitives::Clear::CLEAR_HASH) - .endowment(25) - .salt_bytes([0xDE, 0xAD, 0xBE, 0xEF]) + .code_hash(ink::primitives::H256::zero()) + .endowment(ink::U256::from(25)) + .salt_bytes(Some([1u8; 32])) .instantiate() }; // fn new_result_self() -> Result let _: fn() -> Result = || { CalleeRef::new_result_self() - .code_hash(ink_primitives::Clear::CLEAR_HASH) - .endowment(25) - .salt_bytes([0xDE, 0xAD, 0xBE, 0xEF]) + .code_hash(ink::primitives::H256::zero()) + .endowment(ink::U256::from(25)) + .salt_bytes(Some([1u8; 32])) .instantiate() }; // fn new_result_storage_name() -> Result let _: fn() -> Result = || { CalleeRef::new_result_self() - .code_hash(ink_primitives::Clear::CLEAR_HASH) - .endowment(25) - .salt_bytes([0xDE, 0xAD, 0xBE, 0xEF]) + .code_hash(ink::primitives::H256::zero()) + .endowment(ink::U256::from(25)) + .salt_bytes(Some([1u8; 32])) .instantiate() }; } diff --git a/crates/ink/tests/ui/contract/pass/constructor-return-result-err.rs b/crates/ink/tests/ui/contract/pass/constructor-return-result-err.rs index d028e26e1fb..4c26ff3e8d5 100644 --- a/crates/ink/tests/ui/contract/pass/constructor-return-result-err.rs +++ b/crates/ink/tests/ui/contract/pass/constructor-return-result-err.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/constructor-return-result-explicit.rs b/crates/ink/tests/ui/contract/pass/constructor-return-result-explicit.rs index 413e65d1bbd..74d91e01340 100644 --- a/crates/ink/tests/ui/contract/pass/constructor-return-result-explicit.rs +++ b/crates/ink/tests/ui/contract/pass/constructor-return-result-explicit.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/constructor-return-result-ok.rs b/crates/ink/tests/ui/contract/pass/constructor-return-result-ok.rs index 1039c89bb9b..a0935672edc 100644 --- a/crates/ink/tests/ui/contract/pass/constructor-return-result-ok.rs +++ b/crates/ink/tests/ui/contract/pass/constructor-return-result-ok.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/constructor-selector.rs b/crates/ink/tests/ui/contract/pass/constructor-selector.rs index ca02f8d5346..d05abd609b1 100644 --- a/crates/ink/tests/ui/contract/pass/constructor-selector.rs +++ b/crates/ink/tests/ui/contract/pass/constructor-selector.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + use contract::Contract; use ink::selector_bytes; diff --git a/crates/ink/tests/ui/contract/pass/constructor-wildcard-selector.rs b/crates/ink/tests/ui/contract/pass/constructor-wildcard-selector.rs index ddbde85d60b..583b655980d 100644 --- a/crates/ink/tests/ui/contract/pass/constructor-wildcard-selector.rs +++ b/crates/ink/tests/ui/contract/pass/constructor-wildcard-selector.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/dispatch-decoder-works.rs b/crates/ink/tests/ui/contract/pass/dispatch-decoder-works.rs index 0dd13b3d217..f1d4f2008fa 100644 --- a/crates/ink/tests/ui/contract/pass/dispatch-decoder-works.rs +++ b/crates/ink/tests/ui/contract/pass/dispatch-decoder-works.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + use ink::{ reflect::{ ContractConstructorDecoder, diff --git a/crates/ink/tests/ui/contract/pass/env-access.rs b/crates/ink/tests/ui/contract/pass/env-access.rs index 0b8df9e09b3..ce657d817e1 100644 --- a/crates/ink/tests/ui/contract/pass/env-access.rs +++ b/crates/ink/tests/ui/contract/pass/env-access.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] @@ -11,7 +13,6 @@ mod contract { let _ = Self::env().block_timestamp(); let _ = Self::env().block_number(); let _ = Self::env().caller(); - let _ = Self::env().gas_left(); let _ = Self::env().minimum_balance(); let _ = Self::env().transferred_value(); let _ = Self::env().weight_to_fee(0); @@ -25,7 +26,6 @@ mod contract { let _ = self.env().block_timestamp(); let _ = self.env().block_number(); let _ = self.env().caller(); - let _ = self.env().gas_left(); let _ = self.env().minimum_balance(); let _ = self.env().transferred_value(); let _ = self.env().weight_to_fee(0); diff --git a/crates/ink/tests/ui/contract/pass/event-anonymous.rs b/crates/ink/tests/ui/contract/pass/event-anonymous.rs index 371d10e595e..103fc345c2e 100644 --- a/crates/ink/tests/ui/contract/pass/event-anonymous.rs +++ b/crates/ink/tests/ui/contract/pass/event-anonymous.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/event-config-more-topics.rs b/crates/ink/tests/ui/contract/pass/event-config-more-topics.rs index f12a25878ce..92ea19af9a8 100644 --- a/crates/ink/tests/ui/contract/pass/event-config-more-topics.rs +++ b/crates/ink/tests/ui/contract/pass/event-config-more-topics.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + use ink_env::{ DefaultEnvironment, Environment, @@ -15,6 +17,7 @@ impl ink_env::Environment for EnvironmentMoreTopics { type Timestamp = ::Timestamp; type BlockNumber = ::BlockNumber; type ChainExtension = (); + type EventRecord = ::EventRecord; } #[ink::contract(env = super::EnvironmentMoreTopics)] diff --git a/crates/ink/tests/ui/contract/pass/event-many-definitions.rs b/crates/ink/tests/ui/contract/pass/event-many-definitions.rs index 00f9400dbe9..b4c53106b58 100644 --- a/crates/ink/tests/ui/contract/pass/event-many-definitions.rs +++ b/crates/ink/tests/ui/contract/pass/event-many-definitions.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/event-single-definition.rs b/crates/ink/tests/ui/contract/pass/event-single-definition.rs index 6932d4dc3f6..7684e5e011f 100644 --- a/crates/ink/tests/ui/contract/pass/event-single-definition.rs +++ b/crates/ink/tests/ui/contract/pass/event-single-definition.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/event-topics.rs b/crates/ink/tests/ui/contract/pass/event-topics.rs index 236e63a0c7f..f9215f8b906 100644 --- a/crates/ink/tests/ui/contract/pass/event-topics.rs +++ b/crates/ink/tests/ui/contract/pass/event-topics.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/example-erc20-works.rs b/crates/ink/tests/ui/contract/pass/example-erc20-works.rs index ec3b35ee166..22913acaf61 100644 --- a/crates/ink/tests/ui/contract/pass/example-erc20-works.rs +++ b/crates/ink/tests/ui/contract/pass/example-erc20-works.rs @@ -1,5 +1,8 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod erc20 { + use ink::H160; use ink_storage::Mapping; /// A simple ERC-20 contract. @@ -9,19 +12,19 @@ mod erc20 { /// Total token supply. total_supply: Balance, /// Mapping from owner to number of owned token. - balances: Mapping, + balances: Mapping, /// Mapping of the token amount which an account is allowed to withdraw /// from another account. - allowances: Mapping<(AccountId, AccountId), Balance>, + allowances: Mapping<(H160, H160), Balance>, } /// Event emitted when a token transfer occurs. #[ink(event)] pub struct Transfer { #[ink(topic)] - from: Option, + from: Option, #[ink(topic)] - to: Option, + to: Option, value: Balance, } @@ -30,9 +33,9 @@ mod erc20 { #[ink(event)] pub struct Approval { #[ink(topic)] - owner: AccountId, + owner: H160, #[ink(topic)] - spender: AccountId, + spender: H160, value: Balance, } @@ -78,7 +81,7 @@ mod erc20 { /// /// Returns `0` if the account is non-existent. #[ink(message)] - pub fn balance_of(&self, owner: AccountId) -> Balance { + pub fn balance_of(&self, owner: H160) -> Balance { self.balance_of_impl(&owner) } @@ -91,7 +94,7 @@ mod erc20 { /// Prefer to call this method over `balance_of` since this /// works using references which are more efficient in Wasm. #[inline] - fn balance_of_impl(&self, owner: &AccountId) -> Balance { + fn balance_of_impl(&self, owner: &H160) -> Balance { self.balances.get(owner).unwrap_or_default() } @@ -99,7 +102,7 @@ mod erc20 { /// /// Returns `0` if no allowance has been set. #[ink(message)] - pub fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance { + pub fn allowance(&self, owner: H160, spender: H160) -> Balance { self.allowance_impl(&owner, &spender) } @@ -112,7 +115,7 @@ mod erc20 { /// Prefer to call this method over `allowance` since this /// works using references which are more efficient in Wasm. #[inline] - fn allowance_impl(&self, owner: &AccountId, spender: &AccountId) -> Balance { + fn allowance_impl(&self, owner: &H160, spender: &H160) -> Balance { self.allowances.get((owner, spender)).unwrap_or_default() } @@ -125,7 +128,7 @@ mod erc20 { /// Returns `InsufficientBalance` error if there are not enough tokens on /// the caller's account balance. #[ink(message)] - pub fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()> { + pub fn transfer(&mut self, to: H160, value: Balance) -> Result<()> { let from = self.env().caller(); self.transfer_from_to(&from, &to, value) } @@ -138,7 +141,7 @@ mod erc20 { /// /// An `Approval` event is emitted. #[ink(message)] - pub fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()> { + pub fn approve(&mut self, spender: H160, value: Balance) -> Result<()> { let owner = self.env().caller(); self.allowances.insert((&owner, &spender), &value); self.env().emit_event(Approval { @@ -166,8 +169,8 @@ mod erc20 { #[ink(message)] pub fn transfer_from( &mut self, - from: AccountId, - to: AccountId, + from: H160, + to: H160, value: Balance, ) -> Result<()> { let caller = self.env().caller(); @@ -191,8 +194,8 @@ mod erc20 { /// the caller's account balance. fn transfer_from_to( &mut self, - from: &AccountId, - to: &AccountId, + from: &H160, + to: &H160, value: Balance, ) -> Result<()> { let from_balance = self.balance_of_impl(from); diff --git a/crates/ink/tests/ui/contract/pass/example-erc721-works.rs b/crates/ink/tests/ui/contract/pass/example-erc721-works.rs index c948c2e3284..5b70d09924a 100644 --- a/crates/ink/tests/ui/contract/pass/example-erc721-works.rs +++ b/crates/ink/tests/ui/contract/pass/example-erc721-works.rs @@ -1,5 +1,8 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod erc721 { + use ink::H160; use ink_storage::Mapping; /// A token ID. @@ -9,13 +12,13 @@ mod erc721 { #[derive(Default)] pub struct Erc721 { /// Mapping from token to owner. - token_owner: Mapping, + token_owner: Mapping, /// Mapping from token to approvals users. - token_approvals: Mapping, + token_approvals: Mapping, /// Mapping from owner to number of owned token. - owned_tokens_count: Mapping, + owned_tokens_count: Mapping, /// Mapping from owner to operator approvals. - operator_approvals: Mapping<(AccountId, AccountId), ()>, + operator_approvals: Mapping<(H160, H160), ()>, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] @@ -34,9 +37,9 @@ mod erc721 { #[ink(event)] pub struct Transfer { #[ink(topic)] - from: Option, + from: Option, #[ink(topic)] - to: Option, + to: Option, #[ink(topic)] id: TokenId, } @@ -45,9 +48,9 @@ mod erc721 { #[ink(event)] pub struct Approval { #[ink(topic)] - from: AccountId, + from: H160, #[ink(topic)] - to: AccountId, + to: H160, #[ink(topic)] id: TokenId, } @@ -57,9 +60,9 @@ mod erc721 { #[ink(event)] pub struct ApprovalForAll { #[ink(topic)] - owner: AccountId, + owner: H160, #[ink(topic)] - operator: AccountId, + operator: H160, approved: bool, } @@ -74,25 +77,25 @@ mod erc721 { /// /// This represents the amount of unique tokens the owner has. #[ink(message)] - pub fn balance_of(&self, owner: AccountId) -> u32 { + pub fn balance_of(&self, owner: H160) -> u32 { self.balance_of_or_zero(&owner) } /// Returns the owner of the token. #[ink(message)] - pub fn owner_of(&self, id: TokenId) -> Option { + pub fn owner_of(&self, id: TokenId) -> Option { self.token_owner.get(&id) } /// Returns the approved account ID for this token if any. #[ink(message)] - pub fn get_approved(&self, id: TokenId) -> Option { + pub fn get_approved(&self, id: TokenId) -> Option { self.token_approvals.get(&id) } /// Returns `true` if the operator is approved by the owner. #[ink(message)] - pub fn is_approved_for_all(&self, owner: AccountId, operator: AccountId) -> bool { + pub fn is_approved_for_all(&self, owner: H160, operator: H160) -> bool { self.approved_for_all(owner, operator) } @@ -100,7 +103,7 @@ mod erc721 { #[ink(message)] pub fn set_approval_for_all( &mut self, - to: AccountId, + to: H160, approved: bool, ) -> Result<(), Error> { self.approve_for_all(to, approved)?; @@ -109,18 +112,14 @@ mod erc721 { /// Approves the account to transfer the specified token on behalf of the caller. #[ink(message)] - pub fn approve(&mut self, to: AccountId, id: TokenId) -> Result<(), Error> { + pub fn approve(&mut self, to: H160, id: TokenId) -> Result<(), Error> { self.approve_for(&to, id)?; Ok(()) } /// Transfers the token from the caller to the given destination. #[ink(message)] - pub fn transfer( - &mut self, - destination: AccountId, - id: TokenId, - ) -> Result<(), Error> { + pub fn transfer(&mut self, destination: H160, id: TokenId) -> Result<(), Error> { let caller = self.env().caller(); self.transfer_token_from(&caller, &destination, id)?; Ok(()) @@ -130,8 +129,8 @@ mod erc721 { #[ink(message)] pub fn transfer_from( &mut self, - from: AccountId, - to: AccountId, + from: H160, + to: H160, id: TokenId, ) -> Result<(), Error> { self.transfer_token_from(&from, &to, id)?; @@ -144,7 +143,7 @@ mod erc721 { let caller = self.env().caller(); self.add_token_to(&caller, id)?; self.env().emit_event(Transfer { - from: Some(AccountId::from([0x0; 32])), + from: Some(H160::from([0x0; 20])), to: Some(caller), id, }); @@ -175,18 +174,18 @@ mod erc721 { self.env().emit_event(Transfer { from: Some(caller), - to: Some(AccountId::from([0x0; 32])), + to: Some(H160::from([0x0; 20])), id, }); Ok(()) } - /// Transfers token `id` `from` the sender to the `to` `AccountId`. + /// Transfers token `id` `from` the sender to the `to` `H160`. fn transfer_token_from( &mut self, - from: &AccountId, - to: &AccountId, + from: &H160, + to: &H160, id: TokenId, ) -> Result<(), Error> { let caller = self.env().caller(); @@ -208,11 +207,7 @@ mod erc721 { } /// Removes token `id` from the owner. - fn remove_token_from( - &mut self, - from: &AccountId, - id: TokenId, - ) -> Result<(), Error> { + fn remove_token_from(&mut self, from: &H160, id: TokenId) -> Result<(), Error> { let Self { token_owner, owned_tokens_count, @@ -234,7 +229,7 @@ mod erc721 { } /// Adds the token `id` to the `to` AccountID. - fn add_token_to(&mut self, to: &AccountId, id: TokenId) -> Result<(), Error> { + fn add_token_to(&mut self, to: &H160, id: TokenId) -> Result<(), Error> { let Self { token_owner, owned_tokens_count, @@ -245,7 +240,7 @@ mod erc721 { return Err(Error::TokenExists) } - if *to == AccountId::from([0x0; 32]) { + if *to == H160::from([0x0; 20]) { return Err(Error::NotAllowed) }; @@ -258,11 +253,7 @@ mod erc721 { } /// Approves or disapproves the operator to transfer all tokens of the caller. - fn approve_for_all( - &mut self, - to: AccountId, - approved: bool, - ) -> Result<(), Error> { + fn approve_for_all(&mut self, to: H160, approved: bool) -> Result<(), Error> { let caller = self.env().caller(); if to == caller { return Err(Error::NotAllowed) @@ -282,18 +273,18 @@ mod erc721 { Ok(()) } - /// Approve the passed `AccountId` to transfer the specified token on behalf of + /// Approve the passed `H160` to transfer the specified token on behalf of /// the message's sender. - fn approve_for(&mut self, to: &AccountId, id: TokenId) -> Result<(), Error> { + fn approve_for(&mut self, to: &H160, id: TokenId) -> Result<(), Error> { let caller = self.env().caller(); let owner = self.owner_of(id); if !(owner == Some(caller) - || self.approved_for_all(owner.expect("Error with AccountId"), caller)) + || self.approved_for_all(owner.expect("Error with H160"), caller)) { return Err(Error::NotAllowed) }; - if *to == AccountId::from([0x0; 32]) { + if *to == H160::from([0x0; 20]) { return Err(Error::NotAllowed) }; @@ -318,25 +309,25 @@ mod erc721 { } // Returns the total number of tokens from an account. - fn balance_of_or_zero(&self, of: &AccountId) -> u32 { + fn balance_of_or_zero(&self, of: &H160) -> u32 { self.owned_tokens_count.get(of).unwrap_or(0) } /// Gets an operator on other Account's behalf. - fn approved_for_all(&self, owner: AccountId, operator: AccountId) -> bool { + fn approved_for_all(&self, owner: H160, operator: H160) -> bool { self.operator_approvals.get((&owner, &operator)).is_some() } - /// Returns true if the `AccountId` `from` is the owner of token `id` + /// Returns true if the `H160` `from` is the owner of token `id` /// or it has been approved on behalf of the token `id` owner. - fn approved_or_owner(&self, from: Option, id: TokenId) -> bool { + fn approved_or_owner(&self, from: Option, id: TokenId) -> bool { let owner = self.owner_of(id); - from != Some(AccountId::from([0x0; 32])) + from != Some(H160::from([0x0; 20])) && (from == owner || from == self.token_approvals.get(&id) || self.approved_for_all( - owner.expect("Error with AccountId"), - from.expect("Error with AccountId"), + owner.expect("Error with H160"), + from.expect("Error with H160"), )) } diff --git a/crates/ink/tests/ui/contract/pass/example-flipper-works.rs b/crates/ink/tests/ui/contract/pass/example-flipper-works.rs index d3dad86775a..e71d4a08614 100644 --- a/crates/ink/tests/ui/contract/pass/example-flipper-works.rs +++ b/crates/ink/tests/ui/contract/pass/example-flipper-works.rs @@ -1,4 +1,7 @@ +#![allow(unexpected_cfgs)] + use flipper::Flipper; + #[ink::contract] mod flipper { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/example-incrementer-works.rs b/crates/ink/tests/ui/contract/pass/example-incrementer-works.rs index 746ed2bca41..e81bfd8a118 100644 --- a/crates/ink/tests/ui/contract/pass/example-incrementer-works.rs +++ b/crates/ink/tests/ui/contract/pass/example-incrementer-works.rs @@ -1,4 +1,7 @@ +#![allow(unexpected_cfgs)] + use incrementer::Incrementer; + #[ink::contract] mod incrementer { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/example-return-err-works.rs b/crates/ink/tests/ui/contract/pass/example-return-err-works.rs index 26a813319f2..8437f514569 100644 --- a/crates/ink/tests/ui/contract/pass/example-return-err-works.rs +++ b/crates/ink/tests/ui/contract/pass/example-return-err-works.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + use return_err::{ Error, ReturnErr, diff --git a/crates/ink/tests/ui/contract/pass/example-trait-flipper-works.rs b/crates/ink/tests/ui/contract/pass/example-trait-flipper-works.rs index 310751993dd..419ae7c88d3 100644 --- a/crates/ink/tests/ui/contract/pass/example-trait-flipper-works.rs +++ b/crates/ink/tests/ui/contract/pass/example-trait-flipper-works.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + use flipper::Flipper; #[ink::trait_definition] diff --git a/crates/ink/tests/ui/contract/pass/example-trait-incrementer-works.rs b/crates/ink/tests/ui/contract/pass/example-trait-incrementer-works.rs index c0f051a62ce..881793f2c4c 100644 --- a/crates/ink/tests/ui/contract/pass/example-trait-incrementer-works.rs +++ b/crates/ink/tests/ui/contract/pass/example-trait-incrementer-works.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + use incrementer::Incrementer; #[ink::trait_definition] diff --git a/crates/ink/tests/ui/contract/pass/impl-alias-storage.rs b/crates/ink/tests/ui/contract/pass/impl-alias-storage.rs index da998e0e035..21b4cdae0ab 100644 --- a/crates/ink/tests/ui/contract/pass/impl-alias-storage.rs +++ b/crates/ink/tests/ui/contract/pass/impl-alias-storage.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/impl-block-namespace.rs b/crates/ink/tests/ui/contract/pass/impl-block-namespace.rs index 1b78f47b692..9e0a55e5947 100644 --- a/crates/ink/tests/ui/contract/pass/impl-block-namespace.rs +++ b/crates/ink/tests/ui/contract/pass/impl-block-namespace.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/impl-block-using-env.rs b/crates/ink/tests/ui/contract/pass/impl-block-using-env.rs index 389634100a0..29768e9d5ad 100644 --- a/crates/ink/tests/ui/contract/pass/impl-block-using-env.rs +++ b/crates/ink/tests/ui/contract/pass/impl-block-using-env.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/impl-with-property.rs b/crates/ink/tests/ui/contract/pass/impl-with-property.rs index d87818be282..08f7b567678 100644 --- a/crates/ink/tests/ui/contract/pass/impl-with-property.rs +++ b/crates/ink/tests/ui/contract/pass/impl-with-property.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/message-checked-variant.rs b/crates/ink/tests/ui/contract/pass/message-checked-variant.rs index 13c42a4f2dc..6854b833c8d 100644 --- a/crates/ink/tests/ui/contract/pass/message-checked-variant.rs +++ b/crates/ink/tests/ui/contract/pass/message-checked-variant.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/message-many-inputs.rs b/crates/ink/tests/ui/contract/pass/message-many-inputs.rs index 73553408544..233e82cae31 100644 --- a/crates/ink/tests/ui/contract/pass/message-many-inputs.rs +++ b/crates/ink/tests/ui/contract/pass/message-many-inputs.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/message-many-outputs.rs b/crates/ink/tests/ui/contract/pass/message-many-outputs.rs index 4a02a7d7eb2..0b03086df9d 100644 --- a/crates/ink/tests/ui/contract/pass/message-many-outputs.rs +++ b/crates/ink/tests/ui/contract/pass/message-many-outputs.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/message-payable.rs b/crates/ink/tests/ui/contract/pass/message-payable.rs index fd88f42edaa..298c23100c0 100644 --- a/crates/ink/tests/ui/contract/pass/message-payable.rs +++ b/crates/ink/tests/ui/contract/pass/message-payable.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/message-selector.rs b/crates/ink/tests/ui/contract/pass/message-selector.rs index 2f689a52057..3a9212c4eae 100644 --- a/crates/ink/tests/ui/contract/pass/message-selector.rs +++ b/crates/ink/tests/ui/contract/pass/message-selector.rs @@ -1,4 +1,7 @@ +#![allow(unexpected_cfgs)] + use contract::Contract; + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/message-wildcard-selector.rs b/crates/ink/tests/ui/contract/pass/message-wildcard-selector.rs index 26a999d9bb0..886a0840842 100644 --- a/crates/ink/tests/ui/contract/pass/message-wildcard-selector.rs +++ b/crates/ink/tests/ui/contract/pass/message-wildcard-selector.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/minimal-contract.rs b/crates/ink/tests/ui/contract/pass/minimal-contract.rs index 14a14067b6d..b049e62eecb 100644 --- a/crates/ink/tests/ui/contract/pass/minimal-contract.rs +++ b/crates/ink/tests/ui/contract/pass/minimal-contract.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/module-env-types.rs b/crates/ink/tests/ui/contract/pass/module-env-types.rs index 0ad412f726a..72af124c16d 100644 --- a/crates/ink/tests/ui/contract/pass/module-env-types.rs +++ b/crates/ink/tests/ui/contract/pass/module-env-types.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/module-non-ink-items.rs b/crates/ink/tests/ui/contract/pass/module-non-ink-items.rs index b01d87d55d1..547f82a88ba 100644 --- a/crates/ink/tests/ui/contract/pass/module-non-ink-items.rs +++ b/crates/ink/tests/ui/contract/pass/module-non-ink-items.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] @@ -13,14 +15,17 @@ mod contract { pub fn message(&self) {} } + #[allow(dead_code)] pub enum RustEnum { A, B, } + #[allow(dead_code)] pub union RustUnion { pub field_a: i32, pub field_b: [u8; 4], } + #[allow(dead_code)] pub struct RustStruct { pub a: i32, pub b: i32, diff --git a/crates/ink/tests/ui/contract/pass/no-implicit-prelude.rs b/crates/ink/tests/ui/contract/pass/no-implicit-prelude.rs deleted file mode 100644 index 398ab402dfa..00000000000 --- a/crates/ink/tests/ui/contract/pass/no-implicit-prelude.rs +++ /dev/null @@ -1,29 +0,0 @@ -#![no_implicit_prelude] - -#[::ink::contract] -mod contract { - #[ink(storage)] - pub struct Contract {} - - impl Contract { - #[ink(constructor)] - pub fn constructor() -> Self { - Self {} - } - - #[ink(constructor)] - pub fn constructor_result() -> ::core::result::Result { - ::core::result::Result::Ok(Self {}) - } - - #[ink(message)] - pub fn message(&self) {} - - #[ink(message)] - pub fn message_result(&self) -> ::core::result::Result<(), ()> { - ::core::result::Result::Ok(()) - } - } -} - -fn main() {} diff --git a/crates/ink/tests/ui/contract/pass/storage-many-fields.rs b/crates/ink/tests/ui/contract/pass/storage-many-fields.rs index b02278b1eb0..478d846eb79 100644 --- a/crates/ink/tests/ui/contract/pass/storage-many-fields.rs +++ b/crates/ink/tests/ui/contract/pass/storage-many-fields.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/storage-packed-fields.rs b/crates/ink/tests/ui/contract/pass/storage-packed-fields.rs index 9df561c61d7..f2032a2bb49 100644 --- a/crates/ink/tests/ui/contract/pass/storage-packed-fields.rs +++ b/crates/ink/tests/ui/contract/pass/storage-packed-fields.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { use ink::storage::traits::StorageLayout; diff --git a/crates/ink/tests/ui/contract/pass/storage-single-field.rs b/crates/ink/tests/ui/contract/pass/storage-single-field.rs index 18aaebeba7c..a50675f9781 100644 --- a/crates/ink/tests/ui/contract/pass/storage-single-field.rs +++ b/crates/ink/tests/ui/contract/pass/storage-single-field.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/storage-with-derives.rs b/crates/ink/tests/ui/contract/pass/storage-with-derives.rs index b3f6aafc814..f05575e60cf 100644 --- a/crates/ink/tests/ui/contract/pass/storage-with-derives.rs +++ b/crates/ink/tests/ui/contract/pass/storage-with-derives.rs @@ -1,4 +1,7 @@ +#![allow(unexpected_cfgs)] + use contract::Contract; + #[ink::contract] mod contract { #[ink(storage)] diff --git a/crates/ink/tests/ui/contract/pass/trait-message-payable-guard.rs b/crates/ink/tests/ui/contract/pass/trait-message-payable-guard.rs index 6e6b2559431..8c70b682ded 100644 --- a/crates/ink/tests/ui/contract/pass/trait-message-payable-guard.rs +++ b/crates/ink/tests/ui/contract/pass/trait-message-payable-guard.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::trait_definition] pub trait TraitDefinition { #[ink(message, payable)] diff --git a/crates/ink/tests/ui/contract/pass/trait-message-selector-guard.rs b/crates/ink/tests/ui/contract/pass/trait-message-selector-guard.rs index 6b6f7ce24c9..fff0f735819 100644 --- a/crates/ink/tests/ui/contract/pass/trait-message-selector-guard.rs +++ b/crates/ink/tests/ui/contract/pass/trait-message-selector-guard.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::trait_definition] pub trait TraitDefinition { #[ink(message, selector = 1)] diff --git a/crates/ink/tests/ui/contract/pass/traits-messages-same-name.rs b/crates/ink/tests/ui/contract/pass/traits-messages-same-name.rs index f57bbd0fdb8..609b54fda90 100644 --- a/crates/ink/tests/ui/contract/pass/traits-messages-same-name.rs +++ b/crates/ink/tests/ui/contract/pass/traits-messages-same-name.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::trait_definition] pub trait TraitDefinition1 { #[ink(message)] diff --git a/crates/ink/tests/ui/pay_with_call/pass/multiple_args.rs b/crates/ink/tests/ui/pay_with_call/pass/multiple_args.rs index 77fbfdab6ff..b82b5c9755d 100644 --- a/crates/ink/tests/ui/pay_with_call/pass/multiple_args.rs +++ b/crates/ink/tests/ui/pay_with_call/pass/multiple_args.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] + #[ink::contract] mod contract { #[ink(storage)] @@ -18,10 +20,11 @@ mod contract { #[ink(message)] pub fn message2(&self, _arg1: u8, _arg2: (u8, AccountId)) {} + #[allow(dead_code)] fn check_compiles(&self) { - ink::env::pay_with_call!(self.message0(), 0); - ink::env::pay_with_call!(self.message1(0), 0); - ink::env::pay_with_call!(self.message2(0, (0, Self::env().account_id())), 0); + ink::env::pay_with_call!(self.message0(), 0.into()); + ink::env::pay_with_call!(self.message1(0), 0.into()); + ink::env::pay_with_call!(self.message2(0, (0, Self::env().account_id())), 0.into()); } } } diff --git a/crates/ink/tests/ui/storage_item/fail/collections_only_packed_1.stderr b/crates/ink/tests/ui/storage_item/fail/collections_only_packed_1.stderr index 0f84d326b28..cf8cd00c78b 100644 --- a/crates/ink/tests/ui/storage_item/fail/collections_only_packed_1.stderr +++ b/crates/ink/tests/ui/storage_item/fail/collections_only_packed_1.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `Vec: Packed` is not satisfied --> tests/ui/storage_item/fail/collections_only_packed_1.rs:11:8 | 11 | a: Vec, - | ^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `Vec`, which is required by `Vec: AutoStorableHint>` + | ^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `Vec` | = help: the trait `ink::parity_scale_codec::Decode` is implemented for `Vec` = note: required for `Vec` to implement `Packed` @@ -13,7 +13,7 @@ error[E0277]: the trait bound `[NonPacked]: Encode` is not satisfied --> tests/ui/storage_item/fail/collections_only_packed_1.rs:11:8 | 11 | a: Vec, - | ^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `[NonPacked]`, which is required by `Vec: AutoStorableHint>` + | ^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `[NonPacked]` | = help: the following other types implement trait `Encode`: [T; N] @@ -27,7 +27,7 @@ error[E0277]: the trait bound `Vec: ink::parity_scale_codec::Decode` --> tests/ui/storage_item/fail/collections_only_packed_1.rs:10:8 | 10 | struct Contract { - | ^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `Vec`, which is required by `Contract: Sized` + | ^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `Vec` | = help: the trait `ink::parity_scale_codec::Decode` is implemented for `Vec` = note: required for `Vec` to implement `Packed` @@ -48,7 +48,7 @@ error[E0277]: the trait bound `[NonPacked]: Encode` is not satisfied --> tests/ui/storage_item/fail/collections_only_packed_1.rs:10:8 | 10 | struct Contract { - | ^^^^^^^^ the trait `Encode` is not implemented for `[NonPacked]`, which is required by `Contract: Sized` + | ^^^^^^^^ the trait `Encode` is not implemented for `[NonPacked]` | = help: the following other types implement trait `Encode`: [T; N] @@ -72,7 +72,7 @@ error[E0277]: the trait bound `Vec: ink::parity_scale_codec::Decode` --> tests/ui/storage_item/fail/collections_only_packed_1.rs:10:8 | 10 | struct Contract { - | ^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `Vec`, which is required by `Contract: Sized` + | ^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `Vec` | = help: the trait `ink::parity_scale_codec::Decode` is implemented for `Vec` = note: required for `Vec` to implement `Packed` @@ -93,7 +93,7 @@ error[E0277]: the trait bound `[NonPacked]: Encode` is not satisfied --> tests/ui/storage_item/fail/collections_only_packed_1.rs:10:8 | 10 | struct Contract { - | ^^^^^^^^ the trait `Encode` is not implemented for `[NonPacked]`, which is required by `Contract: Sized` + | ^^^^^^^^ the trait `Encode` is not implemented for `[NonPacked]` | = help: the following other types implement trait `Encode`: [T; N] @@ -117,7 +117,7 @@ error[E0277]: the trait bound `Vec: ink::parity_scale_codec::Decode` --> tests/ui/storage_item/fail/collections_only_packed_1.rs:9:1 | 9 | #[ink::storage_item] - | ^^^^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `Vec`, which is required by `Contract: Sized` + | ^^^^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `Vec` | = help: the trait `ink::parity_scale_codec::Decode` is implemented for `Vec` = note: required for `Vec` to implement `Packed` @@ -139,7 +139,7 @@ error[E0277]: the trait bound `[NonPacked]: Encode` is not satisfied --> tests/ui/storage_item/fail/collections_only_packed_1.rs:9:1 | 9 | #[ink::storage_item] - | ^^^^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `[NonPacked]`, which is required by `Contract: Sized` + | ^^^^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `[NonPacked]` | = help: the following other types implement trait `Encode`: [T; N] @@ -164,7 +164,7 @@ error[E0277]: the trait bound `Vec: Packed` is not satisfied --> tests/ui/storage_item/fail/collections_only_packed_1.rs:11:5 | 11 | a: Vec, - | ^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `Vec`, which is required by `Vec: AutoStorableHint>` + | ^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `Vec` | = help: the trait `ink::parity_scale_codec::Decode` is implemented for `Vec` = note: required for `Vec` to implement `Packed` @@ -175,7 +175,7 @@ error[E0277]: the trait bound `[NonPacked]: Encode` is not satisfied --> tests/ui/storage_item/fail/collections_only_packed_1.rs:11:5 | 11 | a: Vec, - | ^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `[NonPacked]`, which is required by `Vec: AutoStorableHint>` + | ^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `[NonPacked]` | = help: the following other types implement trait `Encode`: [T; N] @@ -189,7 +189,7 @@ error[E0277]: the trait bound `Vec: Packed` is not satisfied --> tests/ui/storage_item/fail/collections_only_packed_1.rs:9:1 | 9 | #[ink::storage_item] - | ^^^^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `Vec`, which is required by `Vec: AutoStorableHint>` + | ^^^^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `Vec` | = help: the trait `ink::parity_scale_codec::Decode` is implemented for `Vec` = note: required for `Vec` to implement `Packed` @@ -201,7 +201,7 @@ error[E0277]: the trait bound `[NonPacked]: Encode` is not satisfied --> tests/ui/storage_item/fail/collections_only_packed_1.rs:9:1 | 9 | #[ink::storage_item] - | ^^^^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `[NonPacked]`, which is required by `Vec: AutoStorableHint>` + | ^^^^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `[NonPacked]` | = help: the following other types implement trait `Encode`: [T; N] @@ -216,7 +216,7 @@ error[E0277]: the trait bound `NonPacked: WrapperTypeDecode` is not satisfied --> tests/ui/storage_item/fail/collections_only_packed_1.rs:11:8 | 11 | a: Vec, - | ^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonPacked`, which is required by `Vec: StorageLayout` + | ^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonPacked` | = help: the following other types implement trait `WrapperTypeDecode`: Arc @@ -231,7 +231,7 @@ error[E0277]: the trait bound `NonPacked: WrapperTypeEncode` is not satisfied --> tests/ui/storage_item/fail/collections_only_packed_1.rs:11:8 | 11 | a: Vec, - | ^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonPacked`, which is required by `Vec: StorageLayout` + | ^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonPacked` | = help: the following other types implement trait `WrapperTypeEncode`: &T diff --git a/crates/ink/tests/ui/storage_item/fail/collections_only_packed_2.stderr b/crates/ink/tests/ui/storage_item/fail/collections_only_packed_2.stderr index e1cb2adaef0..ed9ac08b384 100644 --- a/crates/ink/tests/ui/storage_item/fail/collections_only_packed_2.stderr +++ b/crates/ink/tests/ui/storage_item/fail/collections_only_packed_2.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `BTreeMap: Packed` is not satisfi --> tests/ui/storage_item/fail/collections_only_packed_2.rs:11:8 | 11 | a: BTreeMap, - | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `BTreeMap`, which is required by `BTreeMap: AutoStorableHint>` + | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `BTreeMap` | = help: the trait `ink::parity_scale_codec::Decode` is implemented for `BTreeMap` = note: required for `BTreeMap` to implement `Packed` @@ -13,7 +13,7 @@ error[E0277]: the trait bound `BTreeMap: Packed` is not satisfi --> tests/ui/storage_item/fail/collections_only_packed_2.rs:11:8 | 11 | a: BTreeMap, - | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `BTreeMap`, which is required by `BTreeMap: AutoStorableHint>` + | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `BTreeMap` | = help: the trait `Encode` is implemented for `BTreeMap` = note: required for `BTreeMap` to implement `Packed` @@ -24,7 +24,7 @@ error[E0277]: the trait bound `BTreeMap: ink::parity_scale_code --> tests/ui/storage_item/fail/collections_only_packed_2.rs:10:8 | 10 | struct Contract { - | ^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `BTreeMap`, which is required by `Contract: Sized` + | ^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `BTreeMap` | = help: the trait `ink::parity_scale_codec::Decode` is implemented for `BTreeMap` = note: required for `BTreeMap` to implement `Packed` @@ -45,7 +45,7 @@ error[E0277]: the trait bound `BTreeMap: Encode` is not satisfi --> tests/ui/storage_item/fail/collections_only_packed_2.rs:10:8 | 10 | struct Contract { - | ^^^^^^^^ the trait `Encode` is not implemented for `BTreeMap`, which is required by `Contract: Sized` + | ^^^^^^^^ the trait `Encode` is not implemented for `BTreeMap` | = help: the trait `Encode` is implemented for `BTreeMap` = note: required for `BTreeMap` to implement `Packed` @@ -66,7 +66,7 @@ error[E0277]: the trait bound `BTreeMap: ink::parity_scale_code --> tests/ui/storage_item/fail/collections_only_packed_2.rs:10:8 | 10 | struct Contract { - | ^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `BTreeMap`, which is required by `Contract: Sized` + | ^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `BTreeMap` | = help: the trait `ink::parity_scale_codec::Decode` is implemented for `BTreeMap` = note: required for `BTreeMap` to implement `Packed` @@ -87,7 +87,7 @@ error[E0277]: the trait bound `BTreeMap: Encode` is not satisfi --> tests/ui/storage_item/fail/collections_only_packed_2.rs:10:8 | 10 | struct Contract { - | ^^^^^^^^ the trait `Encode` is not implemented for `BTreeMap`, which is required by `Contract: Sized` + | ^^^^^^^^ the trait `Encode` is not implemented for `BTreeMap` | = help: the trait `Encode` is implemented for `BTreeMap` = note: required for `BTreeMap` to implement `Packed` @@ -108,7 +108,7 @@ error[E0277]: the trait bound `BTreeMap: ink::parity_scale_code --> tests/ui/storage_item/fail/collections_only_packed_2.rs:9:1 | 9 | #[ink::storage_item] - | ^^^^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `BTreeMap`, which is required by `Contract: Sized` + | ^^^^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `BTreeMap` | = help: the trait `ink::parity_scale_codec::Decode` is implemented for `BTreeMap` = note: required for `BTreeMap` to implement `Packed` @@ -130,7 +130,7 @@ error[E0277]: the trait bound `BTreeMap: Encode` is not satisfi --> tests/ui/storage_item/fail/collections_only_packed_2.rs:9:1 | 9 | #[ink::storage_item] - | ^^^^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `BTreeMap`, which is required by `Contract: Sized` + | ^^^^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `BTreeMap` | = help: the trait `Encode` is implemented for `BTreeMap` = note: required for `BTreeMap` to implement `Packed` @@ -152,7 +152,7 @@ error[E0277]: the trait bound `BTreeMap: Packed` is not satisfi --> tests/ui/storage_item/fail/collections_only_packed_2.rs:11:5 | 11 | a: BTreeMap, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `BTreeMap`, which is required by `BTreeMap: AutoStorableHint>` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `BTreeMap` | = help: the trait `ink::parity_scale_codec::Decode` is implemented for `BTreeMap` = note: required for `BTreeMap` to implement `Packed` @@ -163,7 +163,7 @@ error[E0277]: the trait bound `BTreeMap: Packed` is not satisfi --> tests/ui/storage_item/fail/collections_only_packed_2.rs:11:5 | 11 | a: BTreeMap, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `BTreeMap`, which is required by `BTreeMap: AutoStorableHint>` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `BTreeMap` | = help: the trait `Encode` is implemented for `BTreeMap` = note: required for `BTreeMap` to implement `Packed` @@ -174,7 +174,7 @@ error[E0277]: the trait bound `BTreeMap: Packed` is not satisfi --> tests/ui/storage_item/fail/collections_only_packed_2.rs:9:1 | 9 | #[ink::storage_item] - | ^^^^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `BTreeMap`, which is required by `BTreeMap: AutoStorableHint>` + | ^^^^^^^^^^^^^^^^^^^^ the trait `ink::parity_scale_codec::Decode` is not implemented for `BTreeMap` | = help: the trait `ink::parity_scale_codec::Decode` is implemented for `BTreeMap` = note: required for `BTreeMap` to implement `Packed` @@ -186,7 +186,7 @@ error[E0277]: the trait bound `BTreeMap: Packed` is not satisfi --> tests/ui/storage_item/fail/collections_only_packed_2.rs:9:1 | 9 | #[ink::storage_item] - | ^^^^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `BTreeMap`, which is required by `BTreeMap: AutoStorableHint>` + | ^^^^^^^^^^^^^^^^^^^^ the trait `Encode` is not implemented for `BTreeMap` | = help: the trait `Encode` is implemented for `BTreeMap` = note: required for `BTreeMap` to implement `Packed` @@ -198,7 +198,7 @@ error[E0277]: the trait bound `NonPacked: WrapperTypeDecode` is not satisfied --> tests/ui/storage_item/fail/collections_only_packed_2.rs:11:8 | 11 | a: BTreeMap, - | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonPacked`, which is required by `BTreeMap: StorageLayout` + | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonPacked` | = help: the following other types implement trait `WrapperTypeDecode`: Arc @@ -213,7 +213,7 @@ error[E0277]: the trait bound `NonPacked: WrapperTypeEncode` is not satisfied --> tests/ui/storage_item/fail/collections_only_packed_2.rs:11:8 | 11 | a: BTreeMap, - | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonPacked`, which is required by `BTreeMap: StorageLayout` + | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonPacked` | = help: the following other types implement trait `WrapperTypeEncode`: &T diff --git a/crates/ink/tests/ui/storage_item/fail/packed_is_not_derived_automatically.stderr b/crates/ink/tests/ui/storage_item/fail/packed_is_not_derived_automatically.stderr index 604f498302c..ba32039ea91 100644 --- a/crates/ink/tests/ui/storage_item/fail/packed_is_not_derived_automatically.stderr +++ b/crates/ink/tests/ui/storage_item/fail/packed_is_not_derived_automatically.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `NonPacked: Packed` is not satisfied --> tests/ui/storage_item/fail/packed_is_not_derived_automatically.rs:15:30 | 15 | let _ = consume_packed::(); - | ^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonPacked`, which is required by `NonPacked: Packed` + | ^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonPacked` | = help: the following other types implement trait `WrapperTypeDecode`: Arc @@ -21,7 +21,7 @@ error[E0277]: the trait bound `NonPacked: Packed` is not satisfied --> tests/ui/storage_item/fail/packed_is_not_derived_automatically.rs:15:30 | 15 | let _ = consume_packed::(); - | ^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonPacked`, which is required by `NonPacked: Packed` + | ^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonPacked` | = help: the following other types implement trait `WrapperTypeEncode`: &T diff --git a/crates/ink/tests/ui/storage_item/pass/argument_derive_false.rs b/crates/ink/tests/ui/storage_item/pass/argument_derive_false.rs index 336ad249f52..57ac56d2084 100644 --- a/crates/ink/tests/ui/storage_item/pass/argument_derive_false.rs +++ b/crates/ink/tests/ui/storage_item/pass/argument_derive_false.rs @@ -4,6 +4,7 @@ use ink::storage::traits::{ StorageKey, }; +#[allow(dead_code)] #[ink::storage_item(derive = false)] #[derive(Default)] struct Contract> { @@ -12,7 +13,7 @@ struct Contract> { c: u128, } -// Disabling of deriving allow to implement the trait manually +// Disabling of deriving allows to implement the trait manually impl Storable for Contract { fn encode(&self, _dest: &mut T) {} diff --git a/crates/ink/tests/ui/trait_def/fail/message_input_non_codec.stderr b/crates/ink/tests/ui/trait_def/fail/message_input_non_codec.stderr index 0d26b7f221c..48be60277fa 100644 --- a/crates/ink/tests/ui/trait_def/fail/message_input_non_codec.stderr +++ b/crates/ink/tests/ui/trait_def/fail/message_input_non_codec.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `NonCodec: WrapperTypeDecode` is not satisfied --> tests/ui/trait_def/fail/message_input_non_codec.rs:6:23 | 6 | fn message(&self, input: NonCodec); - | ^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonCodec`, which is required by `NonCodec: ink::parity_scale_codec::Decode` + | ^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `NonCodec` | = help: the following other types implement trait `WrapperTypeDecode`: Arc @@ -23,7 +23,7 @@ error[E0277]: the trait bound `NonCodec: Encode` is not satisfied --> tests/ui/trait_def/fail/message_input_non_codec.rs:3:1 | 3 | #[ink::trait_definition] - | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonCodec`, which is required by `NonCodec: Encode` + | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonCodec` 4 | pub trait TraitDefinition { 5 | / #[ink(message)] 6 | | fn message(&self, input: NonCodec); @@ -67,12 +67,8 @@ note: required by a bound in `Execution::::new` ... | pub fn new(input: ExecutionInput) -> Self { | --- required by a bound in this associated function -help: consider removing this method call, as the receiver has type `ExecutionInput>` and `ExecutionInput>: Encode` trivially holds - | -6 | fn message(&self, input: NonCodec); - | -error[E0599]: the method `try_invoke` exists for struct `CallBuilder>, Set, ArgumentList>>>, Set>>`, but its trait bounds were not satisfied +error[E0599]: the method `try_invoke` exists for struct `CallBuilder, Set, ArgumentList>>>, Set>>`, but its trait bounds were not satisfied --> tests/ui/trait_def/fail/message_input_non_codec.rs:5:5 | 5 | #[ink(message)] diff --git a/crates/ink/tests/ui/trait_def/fail/message_output_non_codec.stderr b/crates/ink/tests/ui/trait_def/fail/message_output_non_codec.stderr index eae68a68907..7968c62bcf3 100644 --- a/crates/ink/tests/ui/trait_def/fail/message_output_non_codec.stderr +++ b/crates/ink/tests/ui/trait_def/fail/message_output_non_codec.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `NonCodec: WrapperTypeEncode` is not satisfied --> tests/ui/trait_def/fail/message_output_non_codec.rs:6:26 | 6 | fn message(&self) -> NonCodec; - | ^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonCodec`, which is required by `NonCodec: Encode` + | ^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `NonCodec` | = help: the following other types implement trait `WrapperTypeEncode`: &T @@ -29,7 +29,7 @@ error[E0277]: the trait bound `NonCodec: ink::parity_scale_codec::Decode` is not | 5 | / #[ink(message)] 6 | | fn message(&self) -> NonCodec; - | |__________________________________^ the trait `WrapperTypeDecode` is not implemented for `NonCodec`, which is required by `NonCodec: ink::parity_scale_codec::Decode` + | |__________________________________^ the trait `WrapperTypeDecode` is not implemented for `NonCodec` | = help: the following other types implement trait `WrapperTypeDecode`: Arc @@ -46,7 +46,7 @@ note: required by a bound in `Execution::::new` | pub fn new(input: ExecutionInput) -> Self { | --- required by a bound in this associated function -error[E0599]: the method `try_invoke` exists for struct `CallBuilder>, Set>>, Set>>`, but its trait bounds were not satisfied +error[E0599]: the method `try_invoke` exists for struct `CallBuilder, Set>>, Set>>`, but its trait bounds were not satisfied --> tests/ui/trait_def/fail/message_output_non_codec.rs:5:5 | 1 | pub struct NonCodec; diff --git a/crates/ink/tests/ui/trait_def/pass/no-implicit-prelude.rs b/crates/ink/tests/ui/trait_def/pass/no-implicit-prelude.rs deleted file mode 100644 index b8002dbbad0..00000000000 --- a/crates/ink/tests/ui/trait_def/pass/no-implicit-prelude.rs +++ /dev/null @@ -1,11 +0,0 @@ -#![no_implicit_prelude] - -#[::ink::trait_definition] -pub trait TraitDefinition { - #[ink(message)] - fn message(&self); - #[ink(message)] - fn message_mut(&mut self); -} - -fn main() {} diff --git a/crates/metadata/src/specs.rs b/crates/metadata/src/specs.rs index 267a73a5921..56072273213 100644 --- a/crates/metadata/src/specs.rs +++ b/crates/metadata/src/specs.rs @@ -268,6 +268,7 @@ where TypeSpec: Default, { /// Finalizes construction of the contract specification. + #[allow(clippy::arithmetic_side_effects)] // todo pub fn done(self) -> ContractSpec { assert!( !self.spec.constructors.is_empty(), diff --git a/crates/metadata/src/utils.rs b/crates/metadata/src/utils.rs index 85a13d55dda..66125da6b05 100644 --- a/crates/metadata/src/utils.rs +++ b/crates/metadata/src/utils.rs @@ -34,7 +34,7 @@ where { struct Visitor; - impl<'b> serde::de::Visitor<'b> for Visitor { + impl serde::de::Visitor<'_> for Visitor { type Value = Vec; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { diff --git a/crates/prelude/src/lib.rs b/crates/prelude/src/lib.rs index 4ed51120b34..ce3ba7754d2 100644 --- a/crates/prelude/src/lib.rs +++ b/crates/prelude/src/lib.rs @@ -67,6 +67,8 @@ cfg_if! { string, vec, }; + //pub use core::sync::Mutex; + //pub use sync::Mutex; /// Collection types. pub mod collections { diff --git a/crates/primitives/Cargo.toml b/crates/primitives/Cargo.toml index 15a26936272..b98872eb781 100644 --- a/crates/primitives/Cargo.toml +++ b/crates/primitives/Cargo.toml @@ -18,10 +18,12 @@ include = ["/Cargo.toml", "src/**/*.rs", "/README.md", "/LICENSE"] derive_more = { workspace = true, features = ["from", "display"] } ink_prelude = { workspace = true } scale = { workspace = true, features = ["max-encoded-len"] } -scale-decode = { workspace = true, features = ["derive"], optional = true } +scale-decode = { workspace = true, features = ["derive"] } scale-encode = { workspace = true, features = ["derive"], optional = true } +primitive-types = { version = "0.13.1", default-features = false, features = ["codec"]} scale-info = { workspace = true, features = ["derive"], optional = true } xxhash-rust = { workspace = true, features = ["const_xxh32"] } +serde = { version = "1.0.215", features = ["derive"], default-features = false, optional = true } cfg-if = { workspace = true } num-traits = { workspace = true, features = ["i128"] } @@ -35,12 +37,16 @@ std = [ "ink/std", "ink_env/std", "ink_prelude/std", - "scale-decode", + "num-traits/std", + "serde", + "serde/std", + "scale-decode/std", "scale-encode", "scale-info/std", "scale/std", - "scale-decode?/std", "scale-encode?/std", + "primitive-types/std", + "primitive-types/scale-info", "derive_more/std", "xxhash-rust/std" ] diff --git a/crates/primitives/src/contract.rs b/crates/primitives/src/contract.rs index 5c3f3d65ea2..e1ea2573218 100644 --- a/crates/primitives/src/contract.rs +++ b/crates/primitives/src/contract.rs @@ -1,3 +1,19 @@ +// Copyright (C) Use Ink (UK) Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::types::Environment; + /// Stores the used host environment type of the ink! smart contract. /// /// # Note @@ -58,6 +74,7 @@ /// type BlockNumber = u32; /// type Timestamp = u64; /// type ChainExtension = ::ChainExtension; +/// type EventRecord = ::EventRecord; /// } /// /// #[ink::contract(env = super::CustomEnvironment)] @@ -90,7 +107,7 @@ /// ``` pub trait ContractEnv { /// The environment type. - type Env: crate::Environment; + type Env: Environment; } /// Refers to the generated ink! smart contract reference type. diff --git a/crates/primitives/src/lib.rs b/crates/primitives/src/lib.rs index 3ed9a8c5ff3..0ce6a21b50e 100644 --- a/crates/primitives/src/lib.rs +++ b/crates/primitives/src/lib.rs @@ -41,17 +41,23 @@ pub use self::{ types::{ AccountId, Clear, - Environment, + DepositLimit, Hash, }, }; pub mod contract; +pub use primitive_types::{ + H160, + H256, + U256, +}; + /// An error emitted by the smart contracting language. /// /// This is different than errors from: /// - Errors from the contract, which are programmer defined -/// - Errors from the underlying execution environment (e.g `pallet-contracts`) +/// - Errors from the underlying execution environment (e.g `pallet-revive`) #[non_exhaustive] #[repr(u32)] #[derive(Debug, Copy, Clone, PartialEq, Eq, ::scale::Encode, ::scale::Decode)] diff --git a/crates/primitives/src/reflect/dispatch.rs b/crates/primitives/src/reflect/dispatch.rs index fa262b58fb4..f1b498d9785 100644 --- a/crates/primitives/src/reflect/dispatch.rs +++ b/crates/primitives/src/reflect/dispatch.rs @@ -485,6 +485,7 @@ pub trait ExecuteDispatchable { } /// An error that can occur during dispatch of ink! dispatchables. +/// todo: add tests for other errors beside `PaidUnpayableMessage` #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum DispatchError { /// Failed to decode into a valid dispatch selector. @@ -508,7 +509,7 @@ impl Display for DispatchError { impl DispatchError { /// Returns a string representation of the error. #[inline] - fn as_str(&self) -> &'static str { + pub fn as_str(&self) -> &'static str { match self { Self::InvalidSelector => "unable to decode selector", Self::UnknownSelector => "encountered unknown selector", diff --git a/crates/primitives/src/reflect/event.rs b/crates/primitives/src/reflect/event.rs deleted file mode 100644 index 69181659e3c..00000000000 --- a/crates/primitives/src/reflect/event.rs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2018-2022 Parity Technologies (UK) Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/// Defines a base event type for the contract. -/// -/// This is usually the event enum that comprises all defined event types. -/// -/// # Usage -/// -/// ``` -/// #[ink::contract] -/// pub mod contract { -/// #[ink(storage)] -/// pub struct Contract {} -/// -/// #[ink(event)] -/// pub struct Event1 {} -/// -/// #[ink(event)] -/// pub struct Event2 {} -/// -/// impl Contract { -/// #[ink(constructor)] -/// pub fn constructor() -> Self { -/// Self {} -/// } -/// -/// #[ink(message)] -/// pub fn message(&self) {} -/// } -/// } -/// -/// use contract::Contract; -/// # use ink::reflect::ContractEventBase; -/// -/// type BaseEvent = ::Type; -/// ``` -pub trait ContractEventBase { - /// The generated base event enum. - type Type; -} diff --git a/crates/primitives/src/reflect/trait_def/registry.rs b/crates/primitives/src/reflect/trait_def/registry.rs index c80cdcc7449..41bc4c48fff 100644 --- a/crates/primitives/src/reflect/trait_def/registry.rs +++ b/crates/primitives/src/reflect/trait_def/registry.rs @@ -12,7 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::contract::ContractEnv; +use crate::{ + contract::ContractEnv, + types::Environment, +}; use core::marker::PhantomData; /// Type that is guaranteed by ink! to implement all ink! trait definitions. @@ -56,7 +59,7 @@ pub struct TraitDefinitionRegistry { impl ContractEnv for TraitDefinitionRegistry where - E: crate::Environment, + E: Environment, { type Env = E; } diff --git a/crates/primitives/src/types.rs b/crates/primitives/src/types.rs index 348eb0bd7ea..4b668b90132 100644 --- a/crates/primitives/src/types.rs +++ b/crates/primitives/src/types.rs @@ -15,6 +15,10 @@ use crate::arithmetic::AtLeast32BitUnsigned; use core::array::TryFromSliceError; use derive_more::From; +use primitive_types::{ + H160, + U256, +}; use scale::{ Decode, Encode, @@ -165,6 +169,38 @@ impl Clear for Hash { } } +// impl Clear for H256 { +// const CLEAR_HASH: Self = H256::CLEAR_HASH; +// +// fn is_clear(&self) -> bool { +// self.as_bytes().iter().all(|&byte| byte == 0x00) +// } +// } + +#[derive(Debug, Clone, Eq, PartialEq, Encode, Decode)] +#[cfg_attr( + feature = "std", + derive( + scale_info::TypeInfo, + EncodeAsType, + serde::Serialize, + serde::Deserialize + ) +)] +pub enum DepositLimit { + /// Allows bypassing all balance transfer checks. + Unchecked, + + /// Specifies a maximum allowable balance for a deposit. + Balance(Balance), +} + +impl From for DepositLimit { + fn from(value: T) -> Self { + Self::Balance(value) + } +} + /// Allows to instantiate a type from its little-endian bytes representation. pub trait FromLittleEndian { /// The little-endian bytes representation. @@ -219,6 +255,17 @@ impl FromLittleEndian for u128 { } } +impl FromLittleEndian for U256 { + type Bytes = [u8; 32]; + + #[inline] + fn from_le_bytes(bytes: Self::Bytes) -> Self { + U256::from_little_endian(&bytes) + //U256::from_le_bytes(bytes) + } +} + +/// todo remove /// A trait to enforce that a type should be an [`Environment::AccountId`]. /// /// If you have an [`Environment`] which uses an [`Environment::AccountId`] type other @@ -231,6 +278,8 @@ pub trait AccountIdGuard {} /// used in the [`DefaultEnvironment`]. impl AccountIdGuard for AccountId {} +impl AccountIdGuard for H160 {} + cfg_if::cfg_if! { if #[cfg(feature = "std")] { pub trait CodecAsType: scale_decode::DecodeAsType + scale_encode::EncodeAsType {} @@ -252,6 +301,7 @@ pub trait Environment: Clone { /// The account id type. type AccountId: 'static + scale::Codec + + scale::MaxEncodedLen + CodecAsType + Clone + PartialEq @@ -274,6 +324,7 @@ pub trait Environment: Clone { /// The type of hash. type Hash: 'static + scale::Codec + + scale::MaxEncodedLen + CodecAsType + Copy + Clone @@ -312,8 +363,11 @@ pub trait Environment: Clone { /// macro. For more information about usage and definition click /// [this][chain_extension] link. /// - /// [chain_extension]: https://paritytech.github.io/ink/ink/attr.chain_extension.html + /// [chain_extension]: https://use-ink.github.io/ink/ink/attr.chain_extension.html type ChainExtension; + + /// TODO comment + type EventRecord: 'static + scale::Codec; } /// Placeholder for chains that have no defined chain extension. @@ -334,6 +388,7 @@ impl Environment for DefaultEnvironment { type Timestamp = Timestamp; type BlockNumber = BlockNumber; type ChainExtension = NoChainExtension; + type EventRecord = EventRecord; } /// The default balance type. @@ -347,3 +402,41 @@ pub type Gas = u64; /// The default block number type. pub type BlockNumber = u32; + +// todo replace with () +#[derive(Encode, Decode, MaxEncodedLen, Debug)] +pub struct RuntimeEvent(); + +/// The default event record type. +pub type EventRecord = EventRecordFoo; + +#[derive(Encode, Decode, Debug)] +#[cfg_attr(feature = "std", derive(TypeInfo))] +pub struct EventRecordFoo { + /// The phase of the block it happened in. + pub phase: Phase, + /// The event itself. + pub event: E, + /// The list of the topics this event has. + pub topics: ink_prelude::vec::Vec, +} + +/// A phase of a block's execution. +#[derive(Debug, Encode, Decode, MaxEncodedLen)] +#[cfg_attr(feature = "std", derive(PartialEq, Eq, Clone, TypeInfo))] +pub enum Phase { + /// Applying an extrinsic. + ApplyExtrinsic(u32), + /// Finalizing the block. + Finalization, + /// Initializing the block. + Initialization, +} + +/// The type of origins supported by `pallet-revive`. +#[derive(Clone, ::scale::Encode, ::scale::Decode, PartialEq)] +#[cfg_attr(feature = "std", derive(::scale_info::TypeInfo))] +pub enum Origin { + Root, + Signed(E::AccountId), +} diff --git a/crates/storage/Cargo.toml b/crates/storage/Cargo.toml index ad7d8b5a498..5db2a4f298b 100644 --- a/crates/storage/Cargo.toml +++ b/crates/storage/Cargo.toml @@ -20,7 +20,6 @@ ink_metadata = { workspace = true, optional = true } ink_primitives = { workspace = true } ink_storage_traits = { workspace = true } ink_prelude = { workspace = true } -pallet-contracts-uapi = { workspace = true} pallet-revive-uapi = { workspace = true} scale = { workspace = true } @@ -49,4 +48,3 @@ std = [ "derive_more/std" ] ink-fuzz-tests = [ "std" ] -revive = [ "ink_env/revive", "ink/revive"] diff --git a/crates/storage/src/lazy/mapping.rs b/crates/storage/src/lazy/mapping.rs index 80ac5fcff30..9d27b8a674a 100644 --- a/crates/storage/src/lazy/mapping.rs +++ b/crates/storage/src/lazy/mapping.rs @@ -48,23 +48,21 @@ use scale::{ /// /// This is an example of how you can do this: /// ```rust -/// # use ink::env::{ -/// # Environment, -/// # DefaultEnvironment, -/// # }; -/// # type AccountId = ::AccountId; -/// /// # #[ink::contract] /// # mod my_module { -/// use ink::storage::{ -/// traits::ManualKey, -/// Mapping, +/// use ink::{ +/// storage::{ +/// traits::ManualKey, +/// Mapping, +/// }, +/// H160, +/// U256, /// }; /// /// #[ink(storage)] /// #[derive(Default)] /// pub struct MyContract { -/// balances: Mapping>, +/// balances: Mapping>, /// } /// /// impl MyContract { @@ -72,7 +70,7 @@ use scale::{ /// pub fn new() -> Self { /// let mut instance = Self::default(); /// let caller = Self::env().caller(); -/// let value: Balance = Default::default(); +/// let value: U256 = Default::default(); /// instance.balances.insert(&caller, &value); /// instance /// } diff --git a/crates/storage/src/lazy/mod.rs b/crates/storage/src/lazy/mod.rs index e3a170c36eb..28ed9fc8a19 100644 --- a/crates/storage/src/lazy/mod.rs +++ b/crates/storage/src/lazy/mod.rs @@ -64,19 +64,22 @@ use scale::{ /// # Environment, /// # DefaultEnvironment, /// # }; -/// # type AccountId = ::AccountId; /// /// # #[ink::contract] /// # mod my_module { -/// use ink::storage::{ -/// traits::ManualKey, -/// Lazy, +/// use ink::{ +/// storage::{ +/// traits::ManualKey, +/// Lazy, +/// }, +/// H160, /// }; /// /// #[ink(storage)] /// #[derive(Default)] /// pub struct MyContract { -/// owner: Lazy, +/// owner: Lazy, +/// // todo maybe use something else than `Balance`? /// balance: Lazy>, /// } /// diff --git a/crates/storage/traits/src/layout/impls.rs b/crates/storage/traits/src/layout/impls.rs index 83ee842d12c..2d443130423 100644 --- a/crates/storage/traits/src/layout/impls.rs +++ b/crates/storage/traits/src/layout/impls.rs @@ -40,6 +40,9 @@ use ink_primitives::{ AccountId, Hash, Key, + H160, + H256, + U256, }; use scale_info::TypeInfo; @@ -57,6 +60,7 @@ macro_rules! impl_storage_layout_for_primitives { #[rustfmt::skip] impl_storage_layout_for_primitives!( AccountId, Hash, String, + H160, H256, U256, bool, char, (), u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, diff --git a/integration-tests/internal/call-builder-return-value/lib.rs b/integration-tests/internal/call-builder-return-value/lib.rs index 081c18d67ab..bd67a05cd9c 100755 --- a/integration-tests/internal/call-builder-return-value/lib.rs +++ b/integration-tests/internal/call-builder-return-value/lib.rs @@ -20,6 +20,7 @@ mod call_builder { ToString, }, }, + H160, }; #[ink(storage)] @@ -38,11 +39,11 @@ mod call_builder { /// Delegate a call to the given contract/selector and return the result. #[ink(message)] - pub fn delegate_call(&mut self, code_hash: Hash, selector: [u8; 4]) -> i32 { + pub fn delegate_call(&mut self, address: ink::H160, selector: [u8; 4]) -> i32 { use ink::env::call::build_call; build_call::() - .delegate(code_hash) + .delegate(address) .exec_input(ExecutionInput::new(Selector::new(selector))) .returns::() .invoke() @@ -53,13 +54,13 @@ mod call_builder { #[ink(message)] pub fn delegate_call_short_return_type( &mut self, - code_hash: Hash, + address: ink::H160, selector: [u8; 4], ) -> Result { use ink::env::call::build_call; let result = build_call::() - .delegate(code_hash) + .delegate(address) .exec_input(ExecutionInput::new(Selector::new(selector))) .returns::() .try_invoke(); @@ -74,7 +75,7 @@ mod call_builder { /// Forward a call to the given contract/selector and return the result. #[ink(message)] - pub fn forward_call(&mut self, address: AccountId, selector: [u8; 4]) -> i32 { + pub fn forward_call(&mut self, address: H160, selector: [u8; 4]) -> i32 { use ink::env::call::build_call; build_call::() @@ -89,7 +90,7 @@ mod call_builder { #[ink(message)] pub fn forward_call_short_return_type( &mut self, - address: AccountId, + address: H160, selector: [u8; 4], ) -> Result { use ink::env::call::build_call; @@ -139,15 +140,16 @@ mod call_builder { .expect("instantiate failed"); let mut call_builder = contract.call_builder::(); - let code_hash = client - .upload("incrementer", &origin) + let mut incrementer_constructor = incrementer::IncrementerRef::new(42); + let address = client + .instantiate("incrementer", &origin, &mut incrementer_constructor) .submit() .await - .expect("upload `incrementer` failed") - .code_hash; + .expect("instantiating `incrementer` failed") + .addr; let selector = ink::selector_bytes!("get"); - let call = call_builder.delegate_call(code_hash, selector); + let call = call_builder.delegate_call(address, selector); let call_result = client .call(&origin, &call) .submit() @@ -181,15 +183,16 @@ mod call_builder { .expect("instantiate failed"); let mut call_builder = contract.call_builder::(); - let code_hash = client - .upload("incrementer", &origin) + let mut incrementer_constructor = incrementer::IncrementerRef::new(42); + let address = client + .instantiate("incrementer", &origin, &mut incrementer_constructor) .submit() .await - .expect("upload `incrementer` failed") - .code_hash; + .expect("instantiating `incrementer` failed") + .addr; let selector = ink::selector_bytes!("get"); - let call = call_builder.delegate_call_short_return_type(code_hash, selector); + let call = call_builder.delegate_call_short_return_type(address, selector); let call_result: Result = client.call(&origin, &call).dry_run().await?.return_value(); @@ -233,7 +236,7 @@ mod call_builder { .expect("instantiate failed"); let selector = ink::selector_bytes!("get"); - let call = call_builder.forward_call(incrementer.account_id, selector); + let call = call_builder.forward_call(incrementer.addr, selector); let call_result = client .call(&origin, &call) .submit() @@ -276,8 +279,8 @@ mod call_builder { .expect("instantiate failed"); let selector = ink::selector_bytes!("get"); - let call = call_builder - .forward_call_short_return_type(incrementer.account_id, selector); + let call = + call_builder.forward_call_short_return_type(incrementer.addr, selector); let call_result: Result = client.call(&origin, &call).dry_run().await?.return_value(); diff --git a/integration-tests/internal/e2e-runtime-only-backend/lib.rs b/integration-tests/internal/e2e-runtime-only-backend/lib.rs index 65484ae4e14..c8742abc65a 100644 --- a/integration-tests/internal/e2e-runtime-only-backend/lib.rs +++ b/integration-tests/internal/e2e-runtime-only-backend/lib.rs @@ -34,9 +34,16 @@ pub mod flipper { /// Returns the current balance of the Flipper. #[ink(message)] - pub fn get_contract_balance(&self) -> Balance { + pub fn get_contract_balance(&self) -> ink::U256 { self.env().balance() } + + /// todo + /// Returns the `AccountId` of this contract. + #[ink(message)] + pub fn account_id(&mut self) -> AccountId { + self.env().account_id() + } } #[cfg(all(test, feature = "e2e-tests"))] @@ -108,7 +115,16 @@ pub mod flipper { .submit() .await .expect("deploy failed"); - let call_builder = contract.call_builder::(); + let mut call_builder = contract.call_builder::(); + + // todo + let acc = call_builder.account_id(); + let call_res = client + .call(&ink_e2e::alice(), &acc) + .submit() + .await + .expect("call failed"); + let account_id: AccountId = call_res.return_value(); let old_balance = client .call(&ink_e2e::alice(), &call_builder.get_contract_balance()) @@ -121,7 +137,9 @@ pub mod flipper { // when let call_data = vec![ - Value::unnamed_variant("Id", [Value::from_bytes(contract.account_id)]), + // todo addr + Value::unnamed_variant("Id", [Value::from_bytes(account_id)]), + // todo check next line Value::u128(ENDOWMENT), ]; client diff --git a/integration-tests/internal/lang-err/call-builder-delegate/lib.rs b/integration-tests/internal/lang-err/call-builder-delegate/lib.rs index ce0c6e2def7..e6674d97d00 100755 --- a/integration-tests/internal/lang-err/call-builder-delegate/lib.rs +++ b/integration-tests/internal/lang-err/call-builder-delegate/lib.rs @@ -52,11 +52,11 @@ mod call_builder { #[ink(message)] pub fn delegate( &mut self, - code_hash: Hash, + address: ink::H160, selector: [u8; 4], ) -> Option { let result = build_call::() - .delegate(code_hash) + .delegate(address) .exec_input(ExecutionInput::new(Selector::new(selector))) .returns::() .try_invoke() @@ -80,11 +80,11 @@ mod call_builder { /// This message does not allow the caller to handle any `LangErrors`, for that /// use the `call` message instead. #[ink(message)] - pub fn invoke(&mut self, code_hash: Hash, selector: [u8; 4]) -> i32 { + pub fn invoke(&mut self, address: ink::H160, selector: [u8; 4]) -> i32 { use ink::env::call::build_call; build_call::() - .delegate(code_hash) + .delegate(address) .exec_input(ExecutionInput::new(Selector::new(selector))) .returns::() .invoke() @@ -117,15 +117,16 @@ mod call_builder { .expect("instantiate failed"); let mut call_builder = contract.call_builder::(); - let code_hash = client - .upload("incrementer", &origin) + let mut incrementer_constructor = incrementer::IncrementerRef::new(42); + let address = client + .instantiate("incrementer", &origin, &mut incrementer_constructor) .submit() .await - .expect("upload `incrementer` failed") - .code_hash; + .expect("instantiating `incrementer` failed") + .addr; let selector = ink::selector_bytes!("invalid_selector"); - let call = call_builder.delegate(code_hash, selector); + let call = call_builder.delegate(address, selector); let call_result = client .call(&origin, &call) .submit() @@ -153,20 +154,21 @@ mod call_builder { .instantiate("call_builder_delegate", &origin, &mut constructor) .submit() .await - .expect("instantiate failed"); + .expect("instantiating `call_builder_delegate` failed"); let mut call_builder = contract.call_builder::(); - let code_hash = client - .upload("incrementer", &origin) + let mut incrementer_constructor = incrementer::IncrementerRef::new(42); + let address = client + .instantiate("incrementer", &origin, &mut incrementer_constructor) .submit() .await - .expect("upload `incrementer` failed") - .code_hash; + .expect("instantiating `incrementer` failed") + .addr; // Since `LangError`s can't be handled by the `CallBuilder::invoke()` method // we expect this to panic. let selector = ink::selector_bytes!("invalid_selector"); - let call = call_builder.invoke(code_hash, selector); + let call = call_builder.invoke(address, selector); let call_result = client.call(&origin, &call).dry_run().await; if let Err(ink_e2e::Error::CallDryRun(dry_run)) = call_result { diff --git a/integration-tests/internal/lang-err/call-builder/lib.rs b/integration-tests/internal/lang-err/call-builder/lib.rs index 9aee41f00e8..2ba76536b88 100755 --- a/integration-tests/internal/lang-err/call-builder/lib.rs +++ b/integration-tests/internal/lang-err/call-builder/lib.rs @@ -19,13 +19,17 @@ #[ink::contract] mod call_builder { use constructors_return_value::ConstructorsReturnValueRef; - use ink::env::{ - call::{ - build_call, - ExecutionInput, - Selector, + use ink::{ + env::{ + call::{ + build_call, + ExecutionInput, + Selector, + }, + DefaultEnvironment, }, - DefaultEnvironment, + H160, + H256, }; #[ink(storage)] @@ -49,7 +53,7 @@ mod call_builder { #[ink(message)] pub fn call( &mut self, - address: AccountId, + address: H160, selector: [u8; 4], ) -> Option { let result = build_call::() @@ -77,7 +81,7 @@ mod call_builder { /// This message does not allow the caller to handle any `LangErrors`, for that /// use the `call` message instead. #[ink(message)] - pub fn invoke(&mut self, address: AccountId, selector: [u8; 4]) { + pub fn invoke(&mut self, address: H160, selector: [u8; 4]) { use ink::env::call::build_call; build_call::() @@ -98,14 +102,14 @@ mod call_builder { #[ink(message)] pub fn call_instantiate( &mut self, - code_hash: Hash, + code_hash: H256, selector: [u8; 4], init_value: bool, ) -> Option { let mut params = ConstructorsReturnValueRef::new(init_value) .code_hash(code_hash) - .endowment(0) - .salt_bytes(&[0xDE, 0xAD, 0xBE, 0xEF]) + .endowment(0.into()) + .salt_bytes(Some([1u8; 32])) .params(); params.update_selector(Selector::new(selector)); @@ -134,19 +138,19 @@ mod call_builder { #[ink(message)] pub fn call_instantiate_fallible( &mut self, - code_hash: Hash, + code_hash: H256, selector: [u8; 4], init_value: bool, ) -> Option< Result< - Result, + Result, ink::LangError, >, > { let mut params = ConstructorsReturnValueRef::try_new(init_value) .code_hash(code_hash) - .endowment(0) - .salt_bytes(&[0xDE, 0xAD, 0xBE, 0xEF]) + .endowment(0.into()) + .salt_bytes(Some([1u8; 32])) .params(); params.update_selector(Selector::new(selector)); @@ -156,7 +160,7 @@ mod call_builder { .expect("Error from the Contracts pallet."); Some(lang_result.map(|contract_result| { - contract_result.map(|inner| ink::ToAccountId::to_account_id(&inner)) + contract_result.map(|inner| ink::ToAddr::to_addr(&inner)) })) } } @@ -204,7 +208,7 @@ mod call_builder { let initial_value = get_call_result.return_value(); let selector = ink::selector_bytes!("invalid_selector"); - let call = call_builder.call(flipper.account_id, selector); + let call = call_builder.call(flipper.addr, selector); let call_result = client .call(&origin, &call) .submit() @@ -252,7 +256,7 @@ mod call_builder { // Since `LangError`s can't be handled by the `CallBuilder::invoke()` method // we expect this to panic. let invalid_selector = [0x00, 0x00, 0x00, 0x00]; - let call = call_builder.invoke(flipper.account_id, invalid_selector); + let call = call_builder.invoke(flipper.addr, invalid_selector); let call_result = client.call(&origin, &call).dry_run().await; if let Err(ink_e2e::Error::CallDryRun(dry_run)) = call_result { diff --git a/integration-tests/internal/lang-err/constructors-return-value/lib.rs b/integration-tests/internal/lang-err/constructors-return-value/lib.rs index 8caf9dc298e..4442f88be30 100644 --- a/integration-tests/internal/lang-err/constructors-return-value/lib.rs +++ b/integration-tests/internal/lang-err/constructors-return-value/lib.rs @@ -8,6 +8,8 @@ pub use self::constructors_return_value::{ #[ink::contract] pub mod constructors_return_value { + use ink::H160; + #[ink(storage)] pub struct ConstructorsReturnValue { value: bool, @@ -38,10 +40,14 @@ pub mod constructors_return_value { /// encoded return value. #[ink(constructor)] pub fn revert_new(_init_value: bool) -> Self { - ink::env::return_value::>( + ink::env::return_value::>( ink::env::ReturnFlags::REVERT, - &Ok(AccountId::from([0u8; 32])), - ) + &Ok(H160::from([0u8; 20])), + ); + #[allow(unreachable_code)] + { + unreachable!("`return_value` will end the contract execution"); + } } /// A constructor which reverts and fills the output buffer with an erroneously @@ -49,14 +55,18 @@ pub mod constructors_return_value { #[ink(constructor)] pub fn try_revert_new(init_value: bool) -> Result { let value = if init_value { - Ok(Ok(AccountId::from([0u8; 32]))) + Ok(Ok(H160::from([0u8; 20]))) } else { Err(ink::LangError::CouldNotReadInput) }; ink::env::return_value::< - ink::ConstructorResult>, - >(ink::env::ReturnFlags::REVERT, &value) + ink::ConstructorResult>, + >(ink::env::ReturnFlags::REVERT, &value); + #[allow(unreachable_code)] + { + unreachable!("`return_value` will end the contract execution"); + } } /// Returns the current value of the contract storage. @@ -193,10 +203,7 @@ pub mod constructors_return_value { .await? .return_value(); - assert_eq!( - true, value, - "Contract success should write to contract storage" - ); + assert!(value, "Contract success should write to contract storage"); Ok(()) } diff --git a/integration-tests/internal/lang-err/contract-ref/lib.rs b/integration-tests/internal/lang-err/contract-ref/lib.rs index 9c47e9c7e72..9bd0487850a 100755 --- a/integration-tests/internal/lang-err/contract-ref/lib.rs +++ b/integration-tests/internal/lang-err/contract-ref/lib.rs @@ -11,24 +11,26 @@ mod contract_ref { impl ContractRef { #[ink(constructor)] - pub fn new(version: u32, flipper_code_hash: Hash) -> Self { - let salt = version.to_le_bytes(); + pub fn new(version: u32, flipper_code_hash: ink::H256) -> Self { let flipper = FlipperRef::new_default() - .endowment(0) + .endowment(0.into()) .code_hash(flipper_code_hash) - .salt_bytes(salt) + .salt_bytes(salt_from_version(version)) .instantiate(); Self { flipper } } #[ink(constructor)] - pub fn try_new(version: u32, flipper_code_hash: Hash, succeed: bool) -> Self { - let salt = version.to_le_bytes(); + pub fn try_new( + version: u32, + flipper_code_hash: ink::H256, + succeed: bool, + ) -> Self { let flipper = FlipperRef::try_new(succeed) - .endowment(0) + .endowment(0.into()) .code_hash(flipper_code_hash) - .salt_bytes(salt) + .salt_bytes(salt_from_version(version)) .instantiate() .unwrap_or_else(|error| { panic!( @@ -65,6 +67,13 @@ mod contract_ref { } } + fn salt_from_version(version: u32) -> Option<[u8; 32]> { + let version: [u8; 4] = version.to_le_bytes(); + let mut salt: [u8; 32] = [0u8; 32]; + salt[..4].copy_from_slice(&version); + Some(salt) + } + #[cfg(all(test, feature = "e2e-tests"))] mod e2e_tests { use super::*; @@ -120,7 +129,7 @@ mod contract_ref { async fn e2e_fallible_ref_can_be_instantiated( mut client: Client, ) -> E2EResult<()> { - let flipper_hash = client + let flipper_hash: ink::H256 = client .upload("integration_flipper", &ink_e2e::bob()) .submit() .await @@ -133,7 +142,7 @@ mod contract_ref { .instantiate("contract_ref", &ink_e2e::bob(), &mut constructor) .submit() .await - .expect("instantiate failed"); + .expect("instantiating `contract_ref failed"); let mut call_builder = contract_ref.call_builder::(); let get_check = call_builder.get_check(); diff --git a/integration-tests/internal/mother/lib.rs b/integration-tests/internal/mother/lib.rs index e70c6c69e21..cb62973f4b4 100755 --- a/integration-tests/internal/mother/lib.rs +++ b/integration-tests/internal/mother/lib.rs @@ -18,13 +18,16 @@ #[ink::contract] mod mother { - use ink::prelude::{ - format, - string::{ - String, - ToString, + use ink::{ + prelude::{ + format, + string::{ + String, + ToString, + }, + vec::Vec, }, - vec::Vec, + H160, }; use ink::storage::{ @@ -38,7 +41,7 @@ mod mother { #[derive(Default, PartialEq, Eq, Debug, Clone)] #[cfg_attr(feature = "std", derive(ink::storage::traits::StorageLayout))] #[ink::scale_derive(Encode, Decode, TypeInfo)] - pub struct Bids(Vec>>); + pub struct Bids(Vec>>); /// Auction outline. #[derive(PartialEq, Eq, Debug, Clone)] @@ -130,7 +133,7 @@ mod mother { #[derive(Default)] pub struct Mother { auction: Auction, - balances: Mapping, + balances: Mapping, log: StorageVec, } diff --git a/integration-tests/internal/storage-types/lib.rs b/integration-tests/internal/storage-types/lib.rs index fe405e533fa..c8a97bb606f 100755 --- a/integration-tests/internal/storage-types/lib.rs +++ b/integration-tests/internal/storage-types/lib.rs @@ -251,7 +251,7 @@ mod storage_types { } #[ink(message, payable)] - pub fn payable(&self) -> Result { + pub fn payable(&self) -> Result { Ok(self.env().transferred_value()) } } diff --git a/integration-tests/public/call-runtime/Cargo.toml b/integration-tests/public/call-runtime/Cargo.toml index 3573327039a..b3ab5f99fd8 100644 --- a/integration-tests/public/call-runtime/Cargo.toml +++ b/integration-tests/public/call-runtime/Cargo.toml @@ -14,8 +14,8 @@ ink = { path = "../../../crates/ink", default-features = false } # (especially for global allocator). # # See also: https://substrate.stackexchange.com/questions/4733/error-when-compiling-a-contract-using-the-xcm-chain-extension. -sp-io = { version = "23.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } -sp-runtime = { version = "24.0.0", default-features = false } +sp-io = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } +sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } [dev-dependencies] ink_e2e = { path = "../../../crates/e2e" } diff --git a/integration-tests/public/call-runtime/README.md b/integration-tests/public/call-runtime/README.md index acf3c726f21..9a3c2cc2784 100644 --- a/integration-tests/public/call-runtime/README.md +++ b/integration-tests/public/call-runtime/README.md @@ -9,10 +9,10 @@ It demonstrates how to call a runtime dispatchable from an ink! contract. To integrate this example into Substrate you need to adjust pallet contracts configuration in your runtime: ```rust // In your node's runtime configuration file (runtime.rs) - impl pallet_contracts::Config for Runtime { + impl pallet_revive::Config for Runtime { … // `Everything` or anything that will allow for the `Balances::transfer` extrinsic. - type CallFilter = frame_support::traits::Everything; + type CallFilter = frame_support::traits::Everything; type UnsafeUnstableInterface = ConstBool; … } @@ -21,7 +21,7 @@ To integrate this example into Substrate you need to adjust pallet contracts con ## Comparison to `ChainExtension` Just as a chain extension, `call_runtime` API allows contracts for direct calling to the runtime. -You can trigger any extrinsic that is not forbidden by `pallet_contracts::Config::CallFilter`. +You can trigger any extrinsic that is not forbidden by `pallet_revive::Config::CallFilter`. Consider writing a chain extension if you need to perform one of the following tasks: - Return data. - Provide functionality **exclusively** to contracts. diff --git a/integration-tests/public/call-runtime/lib.rs b/integration-tests/public/call-runtime/lib.rs index 0511e3a1dd1..1a8b46e1257 100644 --- a/integration-tests/public/call-runtime/lib.rs +++ b/integration-tests/public/call-runtime/lib.rs @@ -67,7 +67,7 @@ mod runtime_call { EnvError::ReturnError(ReturnErrorCode::CallRuntimeFailed) => { RuntimeError::CallRuntimeFailed } - _ => panic!("Unexpected error from `pallet-contracts`."), + _ => panic!("Unexpected error from `pallet-revive`."), } } } @@ -112,6 +112,13 @@ mod runtime_call { pub fn call_nonexistent_extrinsic(&mut self) -> Result<(), RuntimeError> { self.env().call_runtime(&()).map_err(Into::into) } + + /// todo + /// Returns the `AccountId` of this contract. + #[ink(message)] + pub fn account_id(&mut self) -> AccountId { + self.env().account_id() + } } #[cfg(all(test, feature = "e2e-tests"))] @@ -122,13 +129,7 @@ mod runtime_call { ContractsBackend, }; - use ink::{ - env::{ - test::default_accounts, - DefaultEnvironment, - }, - primitives::AccountId, - }; + use ink::primitives::AccountId; type E2EResult = Result>; @@ -167,10 +168,20 @@ mod runtime_call { .expect("instantiate failed"); let mut call_builder = contract.call_builder::(); - let receiver: AccountId = default_accounts::().bob; + // todo + let acc = call_builder.account_id(); + let call_res = client + .call(&ink_e2e::alice(), &acc) + .submit() + .await + .expect("call failed"); + let account_id: AccountId = call_res.return_value(); + + //let receiver: AccountId = default_accounts().bob; + let receiver = AccountId::from([0x02; 32]); let contract_balance_before = client - .free_balance(contract.account_id) + .free_balance(account_id) .await .expect("Failed to get account balance"); let receiver_balance_before = client @@ -192,7 +203,7 @@ mod runtime_call { // then let contract_balance_after = client - .free_balance(contract.account_id) + .free_balance(account_id) .await .expect("Failed to get account balance"); let receiver_balance_after = client @@ -231,7 +242,8 @@ mod runtime_call { .expect("instantiate failed"); let mut call_builder = contract.call_builder::(); - let receiver: AccountId = default_accounts::().bob; + //let receiver: ink::H160 = default_accounts().bob; + let receiver = AccountId::from([0x02; 32]); // when let transfer_message = call_builder diff --git a/integration-tests/public/combined-extension/lib.rs b/integration-tests/public/combined-extension/lib.rs index 5c5cd76a8a0..3a6306ff8de 100755 --- a/integration-tests/public/combined-extension/lib.rs +++ b/integration-tests/public/combined-extension/lib.rs @@ -1,8 +1,11 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] -use ink::env::{ - DefaultEnvironment, - Environment, +use ink::{ + env::{ + DefaultEnvironment, + Environment, + }, + U256, }; use psp22_extension::Psp22Extension; use rand_extension::{ @@ -42,6 +45,7 @@ impl Environment for CustomEnvironment { type Hash = ::Hash; type Timestamp = ::Timestamp; type BlockNumber = ::BlockNumber; + type EventRecord = ::EventRecord; /// Setting up the combined chain extension as a primary extension. /// @@ -78,7 +82,7 @@ mod combined_extension { /// Returns the total supply from PSP22 extension. #[ink(message)] - pub fn get_total_supply(&self) -> Result { + pub fn get_total_supply(&self) -> Result { self.env().extension().psp22.total_supply(0) } } @@ -126,7 +130,9 @@ mod combined_extension { assert_eq!(contract.get_rand(), Ok(RANDOM_VALUE)); } - const TOTAL_SUPPLY: u128 = 1377; + fn total_supply() -> U256 { + U256::from(1337) + } /// Mocking the PSP22 extension to return results that we want in the tests. /// @@ -143,7 +149,7 @@ mod combined_extension { fn call(&mut self, func_id: u16, _input: &[u8], output: &mut Vec) -> u32 { match func_id { 0x162d /* `func_id` of the `total_supply` function */ => { - ink::scale::Encode::encode_to(&TOTAL_SUPPLY, output); + ink::scale::Encode::encode_to(&total_supply(), output); 0 } _ => { @@ -166,7 +172,7 @@ mod combined_extension { ink::env::test::register_chain_extension(MockedPSP22Extension); // then - assert_eq!(contract.get_total_supply(), Ok(TOTAL_SUPPLY)); + assert_eq!(contract.get_total_supply(), Ok(total_supply())); } #[ink::test] @@ -183,7 +189,7 @@ mod combined_extension { // then assert_eq!(contract.get_rand(), Ok(RANDOM_VALUE)); - assert_eq!(contract.get_total_supply(), Ok(TOTAL_SUPPLY)); + assert_eq!(contract.get_total_supply(), Ok(total_supply())); } } } diff --git a/integration-tests/public/conditional-compilation/lib.rs b/integration-tests/public/conditional-compilation/lib.rs index 8619493b9d4..86bd55bd819 100755 --- a/integration-tests/public/conditional-compilation/lib.rs +++ b/integration-tests/public/conditional-compilation/lib.rs @@ -27,7 +27,7 @@ pub mod conditional_compilation { // attributing event field with `cfg` is not allowed new_value: bool, #[ink(topic)] - by: AccountId, + by: ink::H160, } /// Feature gated event @@ -37,7 +37,7 @@ pub mod conditional_compilation { // attributing event field with `cfg` is not allowed new_value: bool, #[ink(topic)] - by: AccountId, + by: ink::H160, when: BlockNumber, } diff --git a/integration-tests/public/contract-invocation/Cargo.toml b/integration-tests/public/contract-invocation/Cargo.toml index 3e9c3c7057d..0474cd97db9 100644 --- a/integration-tests/public/contract-invocation/Cargo.toml +++ b/integration-tests/public/contract-invocation/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Víctor M. González "] path = "lib.rs" [features] -default = ["std", "test_instantiate"] +default = ["std"] std = [ "ink/std", "scale/std", @@ -21,14 +21,6 @@ std = [ ] ink-as-dependency = [] e2e-tests = [] -test_instantiate = [ - "ink/test_instantiate", - "contract1/test_instantiate", - "contract2/test_instantiate", - "virtual_contract/test_instantiate", - "virtual_contract_ver1/test_instantiate", - "virtual_contract_ver2/test_instantiate", -] [dependencies] ink = { path = "../../../crates/ink", default-features = false } diff --git a/integration-tests/public/contract-invocation/README.md b/integration-tests/public/contract-invocation/README.md index c0a20566257..623a8d01457 100644 --- a/integration-tests/public/contract-invocation/README.md +++ b/integration-tests/public/contract-invocation/README.md @@ -6,7 +6,7 @@ pub fn instantiate_contract( ) -> Result>::Output>> where E: Environment, - ContractRef: FromAccountId, + ContractRef: FromAddr, Args: Encode, Salt: AsRef<[u8]>, R: ConstructorReturnType, diff --git a/integration-tests/public/contract-invocation/contract1/Cargo.toml b/integration-tests/public/contract-invocation/contract1/Cargo.toml index 8dce80b4796..b4a2ba2504e 100644 --- a/integration-tests/public/contract-invocation/contract1/Cargo.toml +++ b/integration-tests/public/contract-invocation/contract1/Cargo.toml @@ -8,13 +8,10 @@ authors = ["Víctor M. González "] path = "lib.rs" [features] -default = ["std", "test_instantiate"] +default = ["std"] std = ["ink/std", "scale/std", "scale-info/std"] ink-as-dependency = [] e2e-tests = [] -test_instantiate = [ - "ink/test_instantiate" -] [dependencies] ink = { path = "../../../../crates/ink", default-features = false } diff --git a/integration-tests/public/contract-invocation/contract1/lib.rs b/integration-tests/public/contract-invocation/contract1/lib.rs index 2f1053ac60d..3ded69a1aa6 100644 --- a/integration-tests/public/contract-invocation/contract1/lib.rs +++ b/integration-tests/public/contract-invocation/contract1/lib.rs @@ -27,11 +27,19 @@ mod contract1 { self.x } + /// Returns the address of the contract. + #[ink(message)] + pub fn own_addr(&self) -> ink::H160 { + self.env().address() + } + + /* /// Returns the hash code of the contract through the function 'own_code_hash'. #[ink(message)] - pub fn own_code_hash(&self) -> Hash { + pub fn own_code_hash(&self) -> ink::H256 { self.env().own_code_hash().unwrap() } + */ } impl Default for Contract1 { diff --git a/integration-tests/public/contract-invocation/contract2/Cargo.toml b/integration-tests/public/contract-invocation/contract2/Cargo.toml index 4888f746b2c..d83014aa22e 100644 --- a/integration-tests/public/contract-invocation/contract2/Cargo.toml +++ b/integration-tests/public/contract-invocation/contract2/Cargo.toml @@ -8,13 +8,10 @@ authors = ["Víctor M. González "] path = "lib.rs" [features] -default = ["std", "test_instantiate"] +default = ["std"] std = ["ink/std", "scale/std", "scale-info/std"] ink-as-dependency = [] e2e-tests = [] -test_instantiate = [ - "ink/test_instantiate" -] [dependencies] ink = { path = "../../../../crates/ink", default-features = false } diff --git a/integration-tests/public/contract-invocation/contract2/lib.rs b/integration-tests/public/contract-invocation/contract2/lib.rs index 01172827d38..07dc3f6efeb 100644 --- a/integration-tests/public/contract-invocation/contract2/lib.rs +++ b/integration-tests/public/contract-invocation/contract2/lib.rs @@ -27,11 +27,18 @@ mod contract2 { self.x = x; } + /// Returns the address of the contract through the function 'own_address'. + #[ink(message)] + pub fn own_address(&self) -> ink::H160 { + self.env().address() + } + /* /// Returns the hash code of the contract through the function 'own_code_hash'. #[ink(message)] pub fn own_code_hash(&self) -> Hash { - self.env().own_code_hash().unwrap() + self.env().address() } + */ } impl Default for Contract2 { diff --git a/integration-tests/public/contract-invocation/lib.rs b/integration-tests/public/contract-invocation/lib.rs index a56fc7a3f8f..6d990e8910b 100644 --- a/integration-tests/public/contract-invocation/lib.rs +++ b/integration-tests/public/contract-invocation/lib.rs @@ -4,13 +4,15 @@ mod instantiate_contract { use contract1::Contract1Ref; use contract2::Contract2Ref; - use ink::env::{ - call::{ - build_create, + use ink::{ + env::call::{ build_call, + build_create, ExecutionInput, Selector, }, + H160, + H256, }; #[ink(storage)] @@ -19,19 +21,21 @@ mod instantiate_contract { impl ContractTester { #[ink(constructor)] pub fn new() -> Self { - Self{ } + Self {} } #[ink(message)] - pub fn instantiate_contract1(&self, code_hash: Hash, salt: u32) -> Contract1Ref { - let salt = salt.to_le_bytes(); + pub fn instantiate_contract1(&self, code_hash: H256, salt: u32) -> Contract1Ref { + let mut salt_bytes = [0u8; 32]; + salt_bytes[..4].copy_from_slice(&salt.to_le_bytes()); + let create_params = build_create::() .code_hash(code_hash) - .endowment(0) - .exec_input(ExecutionInput::new( - Selector::new(ink::selector_bytes!("new")), - )) - .salt_bytes(&salt) + .endowment(0.into()) + .exec_input(ExecutionInput::new(Selector::new(ink::selector_bytes!( + "new" + )))) + .salt_bytes(Some(salt_bytes)) .returns::() .params(); @@ -49,15 +53,16 @@ mod instantiate_contract { } #[ink(message)] - pub fn instantiate_contract2(&self, code_hash: Hash, salt: u32) -> Contract2Ref { - let salt = salt.to_le_bytes(); + pub fn instantiate_contract2(&self, code_hash: H256, salt: u32) -> Contract2Ref { + let mut salt_bytes = [0u8; 32]; + salt_bytes[..4].copy_from_slice(&salt.to_le_bytes()); let create_params = build_create::() .code_hash(code_hash) - .endowment(0) - .exec_input(ExecutionInput::new( - Selector::new(ink::selector_bytes!("new")), - )) - .salt_bytes(&salt) + .endowment(0.into()) + .exec_input(ExecutionInput::new(Selector::new(ink::selector_bytes!( + "new" + )))) + .salt_bytes(Some(salt_bytes)) .returns::() .params(); @@ -75,13 +80,13 @@ mod instantiate_contract { } #[ink(message)] - pub fn contract1_get_x(&self, contract1_address: [u8; 32]) -> u32 { + pub fn contract1_get_x(&self, contract1_address: H160) -> u32 { let call = build_call() - .call(AccountId::from(contract1_address)) - .transferred_value(0) - .exec_input( - ExecutionInput::new(Selector::new(ink::selector_bytes!("get_x"))) - ) + .call(contract1_address) + .transferred_value(0.into()) + .exec_input(ExecutionInput::new(Selector::new(ink::selector_bytes!( + "get_x" + )))) .returns::() .params(); @@ -90,17 +95,19 @@ mod instantiate_contract { .unwrap_or_else(|env_err| { panic!("Received an error from the Environment: {:?}", env_err) }) - .unwrap_or_else(|lang_err| panic!("Received a `LangError`: {:?}", lang_err)) + .unwrap_or_else(|lang_err| { + panic!("Received a `LangError`: {:?}", lang_err) + }) } #[ink(message)] - pub fn contract2_get_x(&self, contract2_address: [u8; 32]) -> u32 { + pub fn contract2_get_x(&self, contract2_address: H160) -> u32 { let call = build_call() - .call(AccountId::from(contract2_address)) - .transferred_value(0) - .exec_input( - ExecutionInput::new(Selector::new(ink::selector_bytes!("get_x"))) - ) + .call(contract2_address) + .transferred_value(0.into()) + .exec_input(ExecutionInput::new(Selector::new(ink::selector_bytes!( + "get_x" + )))) .returns::() .params(); @@ -109,17 +116,19 @@ mod instantiate_contract { .unwrap_or_else(|env_err| { panic!("Received an error from the Environment: {:?}", env_err) }) - .unwrap_or_else(|lang_err| panic!("Received a `LangError`: {:?}", lang_err)) + .unwrap_or_else(|lang_err| { + panic!("Received a `LangError`: {:?}", lang_err) + }) } #[ink(message)] - pub fn contract1_set_x(&self, contract1_address: [u8; 32], new_x: u32) { + pub fn contract1_set_x(&self, contract1_address: H160, new_x: u32) { let call = ink::env::call::build_call() - .call(AccountId::from(contract1_address)) - .transferred_value(0) + .call(contract1_address) + .transferred_value(0.into()) .exec_input( ExecutionInput::new(Selector::new(ink::selector_bytes!("set_x"))) - .push_arg(new_x) + .push_arg(new_x), ) .returns::<()>() .params(); @@ -129,17 +138,19 @@ mod instantiate_contract { .unwrap_or_else(|env_err| { panic!("Received an error from the Environment: {:?}", env_err) }) - .unwrap_or_else(|lang_err| panic!("Received a `LangError`: {:?}", lang_err)) + .unwrap_or_else(|lang_err| { + panic!("Received a `LangError`: {:?}", lang_err) + }) } #[ink(message)] - pub fn contract2_set_x(&self, contract2_address: [u8; 32], new_x: u64) { + pub fn contract2_set_x(&self, contract2_address: H160, new_x: u64) { let call = ink::env::call::build_call() - .call(AccountId::from(contract2_address)) - .transferred_value(0) + .call(contract2_address) + .transferred_value(0.into()) .exec_input( ExecutionInput::new(Selector::new(ink::selector_bytes!("set_x"))) - .push_arg(new_x) + .push_arg(new_x), ) .returns::<()>() .params(); @@ -149,7 +160,9 @@ mod instantiate_contract { .unwrap_or_else(|env_err| { panic!("Received an error from the Environment: {:?}", env_err) }) - .unwrap_or_else(|lang_err| panic!("Received a `LangError`: {:?}", lang_err)) + .unwrap_or_else(|lang_err| { + panic!("Received a `LangError`: {:?}", lang_err) + }) } } @@ -159,61 +172,57 @@ mod instantiate_contract { } } - #[cfg(all(test, feature = "test_instantiate"))] + #[cfg(test)] mod tests { use super::*; - use ink::{ - env::{ - DefaultEnvironment, - }, - primitives::AccountId, - }; use virtual_contract::VirtualContractRef; use virtual_contract_ver1::VirtualContractVer1Ref; use virtual_contract_ver2::VirtualContractVer2Ref; - fn instantiate_contract1(contract: &ContractTester, code_hash: Hash, salt: u32) -> AccountId{ + fn instantiate_contract1( + contract: &ContractTester, + code_hash: H256, + salt: u32, + ) -> H160 { let cr = contract.instantiate_contract1(code_hash, salt); - ink::ToAccountId::::to_account_id(&cr) + ink::ToAddr::to_addr(&cr) } - fn instantiate_contract2(contract: &ContractTester, code_hash: Hash, salt: u32) -> AccountId{ + fn instantiate_contract2( + contract: &ContractTester, + code_hash: H256, + salt: u32, + ) -> H160 { let cr = contract.instantiate_contract2(code_hash, salt); - ink::ToAccountId::::to_account_id(&cr) - } - - fn to_array(address: &mut AccountId) -> [u8; 32]{ - let temp: &[u8; 32] = address.as_mut(); - *temp + ink::ToAddr::to_addr(&cr) } #[ink::test] fn test_invoke() { let contract = ContractTester::new(); - let code_hash1 = ink::env::test::upload_code::(); - let code_hash2 = ink::env::test::upload_code::(); - - let mut contract1_address1_account = instantiate_contract1(&contract, code_hash1, 1); - let mut contract1_address2_account = instantiate_contract1(&contract, code_hash1, 2); - let mut contract2_address1_account = instantiate_contract2(&contract, code_hash2, 3); - let mut contract2_address2_account = instantiate_contract2(&contract, code_hash2, 4); - - let contract1_address1 = to_array(&mut contract1_address1_account); - let contract1_address2 = to_array(&mut contract1_address2_account); - let contract2_address1 = to_array(&mut contract2_address1_account); - let contract2_address2 = to_array(&mut contract2_address2_account); - - let check_hashes = |a, b, c|{ - let x = ink::env::code_hash::(a) - .expect("failed to get code hash"); - let y = ink::env::code_hash::(b) - .expect("failed to get code hash"); + let code_hash1 = ink::env::test::upload_code::< + ink::env::DefaultEnvironment, + Contract1Ref, + >(); + let code_hash2 = ink::env::test::upload_code::< + ink::env::DefaultEnvironment, + Contract2Ref, + >(); + + let contract1_address1 = instantiate_contract1(&contract, code_hash1, 1); + let contract1_address2 = instantiate_contract1(&contract, code_hash1, 2); + let contract2_address1 = instantiate_contract2(&contract, code_hash2, 3); + let contract2_address2 = instantiate_contract2(&contract, code_hash2, 4); + + let check_hashes = |a, b, c| { + let x = ink::env::code_hash(a).expect("failed to get code hash"); + let y = ink::env::code_hash(b).expect("failed to get code hash"); assert_eq!(x, c); assert_eq!(y, c); }; - check_hashes(&contract1_address1_account, &contract1_address2_account, code_hash1); - check_hashes(&contract2_address1_account, &contract2_address2_account, code_hash2); + check_hashes(&contract1_address1, &contract1_address2, code_hash1); + check_hashes(&contract2_address1, &contract2_address2, code_hash2); let check_values1 = |a, b| { let x = contract.contract1_get_x(contract1_address1); @@ -240,26 +249,82 @@ mod instantiate_contract { contract.contract1_set_x(contract1_address2, 321); check_values1(123, 321); check_values2(123456, 123456); - } #[ink::test] fn test_invoke_delegate() { - let code_hash1 = ink::env::test::upload_code::(); - let code_hash2 = ink::env::test::upload_code::(); - let code_hash3 = ink::env::test::upload_code::(); + let code_hash1 = ink::env::test::upload_code::< + ink::env::DefaultEnvironment, + VirtualContractRef, + >(); + let code_hash2 = ink::env::test::upload_code::< + ink::env::DefaultEnvironment, + VirtualContractVer1Ref, + >(); + let code_hash3 = ink::env::test::upload_code::< + ink::env::DefaultEnvironment, + VirtualContractVer2Ref, + >(); + + let create_params = build_create::() + .code_hash(code_hash2) + .endowment(0.into()) + .exec_input(ExecutionInput::new(Selector::new(ink::selector_bytes!( + "new" + )))) + .returns::() + .params(); - let ic = |hash, salt: u32, x|{ - let salt = salt.to_le_bytes(); + let addr2 = ink::env::instantiate_contract(&create_params) + .unwrap_or_else(|error| { + panic!( + "Received an error from the Contracts pallet while instantiating: {:?}", + error + ) + }) + .unwrap_or_else(|error| { + panic!("Received a `LangError` while instatiating: {:?}", error) + }); + + use ink::ToAddr; + let addr2: H160 = addr2.to_addr(); + + let create_params = build_create::() + .code_hash(code_hash3) + .endowment(0.into()) + .exec_input(ExecutionInput::new(Selector::new(ink::selector_bytes!( + "new" + )))) + .returns::() + .params(); + + let addr3 = ink::env::instantiate_contract(&create_params) + .unwrap_or_else(|error| { + panic!( + "Received an error from the Contracts pallet while instantiating: {:?}", + error + ) + }) + .unwrap_or_else(|error| { + panic!("Received a `LangError` while instatiating: {:?}", error) + }); + let addr3: H160 = addr3.to_addr(); + + // creates `code_hash1` contract and puts `hash` + `x` as the constructor + // arguments + let instantiate = |delegate_addr: H160, salt: u32, x| { + let mut salt_bytes = [0u8; 32]; + salt_bytes[..4].copy_from_slice(&salt.to_le_bytes()); let create_params = build_create::() .code_hash(code_hash1) - .endowment(0) + .endowment(0.into()) .exec_input( ExecutionInput::new(Selector::new(ink::selector_bytes!("new"))) - .push_arg(hash) + //.push_arg(H256::zero()) // todo should result in err, but doesn't + .push_arg(delegate_addr) .push_arg(x), ) - .salt_bytes(&salt) + .salt_bytes(Some(salt_bytes)) .returns::() .params(); @@ -275,19 +340,20 @@ mod instantiate_contract { }) }; - let mut ref1 = ic(code_hash2, 1, 42); - let mut ref2 = ic(code_hash3, 2, 74); - - let check_values = |r1: &VirtualContractRef, r2: &VirtualContractRef, a, b, c, d|{ - let v1 = r1.real_get_x(); - let v2 = r2.real_get_x(); - let v3 = r1.get_x(); - let v4 = r2.get_x(); - assert_eq!(v1, a); - assert_eq!(v2, b); - assert_eq!(v3, c); - assert_eq!(v4, d); - }; + let mut ref1 = instantiate(addr2, 1, 42); + let mut ref2 = instantiate(addr3, 2, 74); + + let check_values = + |r1: &VirtualContractRef, r2: &VirtualContractRef, a, b, c, d| { + let v1 = r1.real_get_x(); + let v2 = r2.real_get_x(); + let v3 = r1.get_x(); + let v4 = r2.get_x(); + assert_eq!(v1, a); + assert_eq!(v2, b); + assert_eq!(v3, c); + assert_eq!(v4, d); + }; check_values(&ref1, &ref2, 42, 74, 43, 148); ref1.set_x(15); @@ -298,7 +364,162 @@ mod instantiate_contract { check_values(&ref1, &ref2, 15, 74, 16, 148); ref2.real_set_x(39); check_values(&ref1, &ref2, 15, 39, 16, 78); + } + } + + #[cfg(all(test, feature = "e2e-tests"))] + mod e2e_tests { + use ink_e2e::{ + ChainBackend, + ContractsBackend, + E2EBackend, + InstantiationResult, + }; + use virtual_contract::{ + virtual_contract::VirtualContract, + VirtualContractRef, + }; + use virtual_contract_ver1::VirtualContractVer1Ref; + use virtual_contract_ver2::VirtualContractVer2Ref; + + type E2EResult = std::result::Result>; + + async fn check_values( + origin: &ink_e2e::Keypair, + client: &mut Client, + + ver1: &InstantiationResult, + ver2: &InstantiationResult, + + a: u32, + b: u32, + c: u32, + d: u32, + ) where + Client: E2EBackend, + E: ink::env::Environment, + { + let r1 = ver1.call_builder::(); + let r2 = ver2.call_builder::(); + + let v1_get = r1.real_get_x(); + let v1 = client + .call(&origin, &v1_get) + .dry_run() + .await + .unwrap_or_else(|_| panic!("foo")) + .return_value(); + + let v2_get = r2.real_get_x(); + let v2 = client + .call(&origin, &v2_get) + .dry_run() + .await + .unwrap_or_else(|_| panic!("foo")) + .return_value(); + + let v3_get = r1.get_x(); + let v3 = client + .call(&origin, &v3_get) + .dry_run() + .await + .unwrap_or_else(|_| panic!("foo")) + .return_value(); + + let v4_get = r2.get_x(); + let v4 = client + .call(&origin, &v4_get) + .dry_run() + .await + .unwrap_or_else(|_| panic!("foo")) + .return_value(); + + assert_eq!(v1, a); + assert_eq!(v2, b); + assert_eq!(v3, c); + assert_eq!(v4, d); + } + #[ink_e2e::test] + async fn test_invoke_delegate_e2e( + mut client: Client, + ) -> E2EResult<()> { + let origin = client + .create_and_fund_account(&ink_e2e::alice(), 10_000_000_000_000) + .await; + + let mut constructor = VirtualContractVer1Ref::new(); + let addr_virtual_ver1 = client + .instantiate("virtual_contract_ver1", &origin, &mut constructor) + .submit() + .await + .expect("instantiate `delegatee` failed"); + + let mut constructor = VirtualContractVer2Ref::new(); + let addr_virtual_ver2 = client + .instantiate("virtual_contract_ver2", &origin, &mut constructor) + .submit() + .await + .expect("instantiate `delegatee` failed"); + + let mut constructor = VirtualContractRef::new(addr_virtual_ver1.addr, 42); + let ver1 = client + .instantiate("virtual_contract", &origin, &mut constructor) + .submit() + .await + .expect("instantiate `delegatee` failed"); + + let mut constructor = VirtualContractRef::new(addr_virtual_ver2.addr, 74); + let ver2 = client + .instantiate("virtual_contract", &origin, &mut constructor) + .submit() + .await + .expect("instantiate `delegatee` failed"); + + // contract code_hash1 with argument code_hash2 + check_values(&origin, &mut client, &ver1, &ver2, 42, 74, 43, 148).await; + + let mut call_builder = ver1.call_builder::(); + let call = call_builder.set_x(15); + let _call_result = client + .call(&origin, &call) + .submit() + .await + .expect("Calling `call_builder::call` failed"); + + check_values(&origin, &mut client, &ver1, &ver2, 42, 74, 43, 148).await; + + let mut call_builder = ver1.call_builder::(); + let call = call_builder.real_set_x(15); + let _call_result = client + .call(&origin, &call) + .submit() + .await + .expect("Calling `call_builder::call` failed"); + + check_values(&origin, &mut client, &ver1, &ver2, 15, 74, 16, 148).await; + + let mut call_builder = ver2.call_builder::(); + let call = call_builder.set_x(39); + let _call_result = client + .call(&origin, &call) + .submit() + .await + .expect("Calling `call_builder::call` failed"); + + check_values(&origin, &mut client, &ver1, &ver2, 15, 74, 16, 148).await; + + let mut call_builder = ver2.call_builder::(); + let call = call_builder.real_set_x(39); + let _call_result = client + .call(&origin, &call) + .submit() + .await + .expect("Calling `call_builder::call` failed"); + + check_values(&origin, &mut client, &ver1, &ver2, 15, 39, 16, 78).await; + + Ok(()) } } } diff --git a/integration-tests/public/contract-invocation/virtual_contract/Cargo.toml b/integration-tests/public/contract-invocation/virtual_contract/Cargo.toml index 9cb1783ac82..699dee19e80 100644 --- a/integration-tests/public/contract-invocation/virtual_contract/Cargo.toml +++ b/integration-tests/public/contract-invocation/virtual_contract/Cargo.toml @@ -8,13 +8,10 @@ authors = ["Víctor M. González "] path = "lib.rs" [features] -default = ["std", "test_instantiate"] +default = ["std"] std = ["ink/std", "scale/std", "scale-info/std"] ink-as-dependency = [] e2e-tests = [] -test_instantiate = [ - "ink/test_instantiate" -] [dependencies] ink = { path = "../../../../crates/ink", default-features = false } diff --git a/integration-tests/public/contract-invocation/virtual_contract/lib.rs b/integration-tests/public/contract-invocation/virtual_contract/lib.rs index 60011b78647..13768b70745 100644 --- a/integration-tests/public/contract-invocation/virtual_contract/lib.rs +++ b/integration-tests/public/contract-invocation/virtual_contract/lib.rs @@ -3,31 +3,31 @@ pub use self::virtual_contract::VirtualContractRef; #[ink::contract()] -mod virtual_contract { - use ink::env::call::{ - build_call, - ExecutionInput, - Selector, +pub mod virtual_contract { + use ink::{ + env::call::{ + build_call, + ExecutionInput, + Selector, + }, + H160, }; #[ink(storage)] pub struct VirtualContract { - version: [u8; 32], + version: ink::H160, x: u32, } impl VirtualContract { /// Creates a new Template contract. #[ink(constructor)] - pub fn new(version: [u8; 32], x: u32) -> Self { - Self { - version, - x, - } + pub fn new(version: H160, x: u32) -> Self { + Self { version, x } } #[ink(message)] - pub fn set_version(&mut self, version: [u8; 32]) { + pub fn set_version(&mut self, version: H160) { self.version = version; } @@ -44,10 +44,10 @@ mod virtual_contract { #[ink(message)] pub fn set_x(&mut self, x: u32) { let call = build_call() - .delegate(Hash::from(self.version)) + .delegate(self.version) .exec_input( ExecutionInput::new(Selector::new(ink::selector_bytes!("set_x"))) - .push_arg(x) + .push_arg(x), ) .returns::<()>() .params(); @@ -57,16 +57,18 @@ mod virtual_contract { .unwrap_or_else(|env_err| { panic!("Received an error from the Environment: {:?}", env_err) }) - .unwrap_or_else(|lang_err| panic!("Received a `LangError`: {:?}", lang_err)); + .unwrap_or_else(|lang_err| { + panic!("Received a `LangError`: {:?}", lang_err) + }); } #[ink(message)] pub fn get_x(&self) -> u32 { let call = build_call() - .delegate(Hash::from(self.version)) - .exec_input( - ExecutionInput::new(Selector::new(ink::selector_bytes!("get_x"))) - ) + .delegate(self.version) + .exec_input(ExecutionInput::new(Selector::new(ink::selector_bytes!( + "get_x" + )))) .returns::() .params(); @@ -75,13 +77,15 @@ mod virtual_contract { .unwrap_or_else(|env_err| { panic!("Received an error from the Environment: {:?}", env_err) }) - .unwrap_or_else(|lang_err| panic!("Received a `LangError`: {:?}", lang_err)) + .unwrap_or_else(|lang_err| { + panic!("Received a `LangError`: {:?}", lang_err) + }) } } impl Default for VirtualContract { fn default() -> Self { - Self::new([0; 32], 0) + Self::new(H160::default(), 0) } } } diff --git a/integration-tests/public/contract-invocation/virtual_contract_ver1/Cargo.toml b/integration-tests/public/contract-invocation/virtual_contract_ver1/Cargo.toml index 9050db60316..85c7d755bef 100644 --- a/integration-tests/public/contract-invocation/virtual_contract_ver1/Cargo.toml +++ b/integration-tests/public/contract-invocation/virtual_contract_ver1/Cargo.toml @@ -8,13 +8,10 @@ authors = ["Víctor M. González "] path = "lib.rs" [features] -default = ["std", "test_instantiate"] +default = ["std"] std = ["ink/std", "scale/std", "scale-info/std"] ink-as-dependency = [] e2e-tests = [] -test_instantiate = [ - "ink/test_instantiate" -] [dependencies] ink = { path = "../../../../crates/ink", default-features = false } diff --git a/integration-tests/public/contract-invocation/virtual_contract_ver1/lib.rs b/integration-tests/public/contract-invocation/virtual_contract_ver1/lib.rs index d9d39cad73d..74aae604a94 100644 --- a/integration-tests/public/contract-invocation/virtual_contract_ver1/lib.rs +++ b/integration-tests/public/contract-invocation/virtual_contract_ver1/lib.rs @@ -7,7 +7,7 @@ mod virtual_contract_ver1 { #[ink(storage)] pub struct VirtualContractVer1 { - version: [u8; 32], + version: ink::H160, x: u32, } @@ -16,8 +16,8 @@ mod virtual_contract_ver1 { #[ink(constructor)] pub fn new() -> Self { Self { - version: [0; 32], - x: 42 + version: ink::H160::zero(), + x: 42, } } diff --git a/integration-tests/public/contract-invocation/virtual_contract_ver2/Cargo.toml b/integration-tests/public/contract-invocation/virtual_contract_ver2/Cargo.toml index f8d36cf17c3..8433a13b01e 100644 --- a/integration-tests/public/contract-invocation/virtual_contract_ver2/Cargo.toml +++ b/integration-tests/public/contract-invocation/virtual_contract_ver2/Cargo.toml @@ -8,13 +8,10 @@ authors = ["Víctor M. González "] path = "lib.rs" [features] -default = ["std", "test_instantiate"] +default = ["std"] std = ["ink/std", "scale/std", "scale-info/std"] ink-as-dependency = [] e2e-tests = [] -test_instantiate = [ - "ink/test_instantiate" -] [dependencies] ink = { path = "../../../../crates/ink", default-features = false } diff --git a/integration-tests/public/contract-invocation/virtual_contract_ver2/lib.rs b/integration-tests/public/contract-invocation/virtual_contract_ver2/lib.rs index 6ef2ea29207..c6de31c8b3a 100644 --- a/integration-tests/public/contract-invocation/virtual_contract_ver2/lib.rs +++ b/integration-tests/public/contract-invocation/virtual_contract_ver2/lib.rs @@ -7,7 +7,7 @@ mod virtual_contract_ver2 { #[ink(storage)] pub struct VirtualContractVer2 { - version: [u8; 32], + version: ink::H160, x: u32, } @@ -16,8 +16,8 @@ mod virtual_contract_ver2 { #[ink(constructor)] pub fn new() -> Self { Self { - version: [0; 32], - x: 42 + version: ink::H160::zero(), + x: 7, } } diff --git a/integration-tests/public/contract-terminate/Cargo.toml b/integration-tests/public/contract-terminate/Cargo.toml index e959e0515f6..abc5073a5c5 100644 --- a/integration-tests/public/contract-terminate/Cargo.toml +++ b/integration-tests/public/contract-terminate/Cargo.toml @@ -19,5 +19,6 @@ default = ["std"] std = [ "ink/std", ] + ink-as-dependency = [] e2e-tests = [] diff --git a/integration-tests/public/contract-terminate/lib.rs b/integration-tests/public/contract-terminate/lib.rs index c2430bb8bfb..7a3e0199903 100644 --- a/integration-tests/public/contract-terminate/lib.rs +++ b/integration-tests/public/contract-terminate/lib.rs @@ -31,14 +31,10 @@ pub mod just_terminates { #[ink::test] fn terminating_works() { // given - let accounts = - ink::env::test::default_accounts::(); - let contract_id = ink::env::test::callee::(); - ink::env::test::set_caller::(accounts.alice); - ink::env::test::set_account_balance::( - contract_id, - 100, - ); + let accounts = ink::env::test::default_accounts(); + let contract_id = ink::env::test::callee(); + ink::env::test::set_caller(accounts.alice); + ink::env::test::set_account_balance(contract_id, 100.into()); let mut contract = JustTerminate::new(); // when @@ -48,7 +44,7 @@ pub mod just_terminates { ink::env::test::assert_contract_termination::( should_terminate, accounts.alice, - 100, + 100.into(), ); } } @@ -89,7 +85,7 @@ pub mod just_terminates { // then assert!(call_res.contains_event("System", "KilledAccount")); assert!(call_res.contains_event("Balances", "Withdraw")); - assert!(call_res.contains_event("Contracts", "Terminated")); + assert!(call_res.contains_event("Revive", "Terminated")); Ok(()) } diff --git a/integration-tests/public/contract-transfer/lib.rs b/integration-tests/public/contract-transfer/lib.rs index c175f7195f1..5ec25d8162b 100644 --- a/integration-tests/public/contract-transfer/lib.rs +++ b/integration-tests/public/contract-transfer/lib.rs @@ -6,6 +6,7 @@ #[ink::contract] pub mod give_me { + use ink::primitives::U256; /// No storage is needed for this simple contract. #[ink(storage)] pub struct GiveMe {} @@ -26,7 +27,7 @@ pub mod give_me { /// balance below the minimum balance (i.e. the chain's existential deposit). /// - Panics in case the transfer failed for another reason. #[ink(message)] - pub fn give_me(&mut self, value: Balance) { + pub fn give_me(&mut self, value: U256) { ink::env::debug_println!("requested value: {}", value); ink::env::debug_println!("contract balance: {}", self.env().balance()); @@ -55,41 +56,52 @@ pub mod give_me { "received payment: {}", self.env().transferred_value() ); - assert!(self.env().transferred_value() == 10, "payment was not ten"); + assert!( + self.env().transferred_value() == U256::from(10), + "payment was not ten" + ); + } + + /// todo + /// Returns the `AccountId` of this contract. + #[ink(message)] + pub fn account_id(&mut self) -> AccountId { + self.env().account_id() } } #[cfg(test)] mod tests { use super::*; + use ink::H160; #[ink::test] fn transfer_works() { // given - let contract_balance = 100; + let contract_balance = 100.into(); let accounts = default_accounts(); let mut give_me = create_contract(contract_balance); // when set_sender(accounts.eve); - set_balance(accounts.eve, 0); - give_me.give_me(80); + set_balance(accounts.eve, 0.into()); + give_me.give_me(80.into()); // then - assert_eq!(get_balance(accounts.eve), 80); + assert_eq!(get_balance(accounts.eve), 80.into()); } #[ink::test] #[should_panic(expected = "insufficient funds!")] fn transfer_fails_insufficient_funds() { // given - let contract_balance = 100; + let contract_balance = 100.into(); let accounts = default_accounts(); let mut give_me = create_contract(contract_balance); // when set_sender(accounts.eve); - give_me.give_me(120); + give_me.give_me(120.into()); // then // `give_me` must already have panicked here @@ -100,28 +112,28 @@ pub mod give_me { use ink::codegen::Env; // given let accounts = default_accounts(); - let give_me = create_contract(100); - let contract_account = give_me.env().account_id(); + let give_me = create_contract(100.into()); + let contract_account = give_me.env().address(); // when // Push the new execution context which sets initial balances and // sets Eve as the caller - set_balance(accounts.eve, 100); - set_balance(contract_account, 0); + set_balance(accounts.eve, 100.into()); + set_balance(contract_account, 0.into()); set_sender(accounts.eve); // then // we use helper macro to emulate method invocation coming with payment, // and there must be no panic - ink::env::pay_with_call!(give_me.was_it_ten(), 10); + ink::env::pay_with_call!(give_me.was_it_ten(), 10.into()); // and // balances should be changed properly let contract_new_balance = get_balance(contract_account); let caller_new_balance = get_balance(accounts.eve); - assert_eq!(caller_new_balance, 100 - 10); - assert_eq!(contract_new_balance, 10); + assert_eq!(caller_new_balance, (100 - 10).into()); + assert_eq!(contract_new_balance, 10.into()); } #[ink::test] @@ -129,14 +141,14 @@ pub mod give_me { fn test_transferred_value_must_fail() { // given let accounts = default_accounts(); - let give_me = create_contract(100); + let give_me = create_contract(100.into()); // when // Push the new execution context which sets Eve as caller and // the `mock_transferred_value` as the value which the contract // will see as transferred to it. set_sender(accounts.eve); - ink::env::test::set_value_transferred::(13); + ink::env::test::set_value_transferred(13.into()); // then give_me.was_it_ten(); @@ -145,37 +157,35 @@ pub mod give_me { /// Creates a new instance of `GiveMe` with `initial_balance`. /// /// Returns the `contract_instance`. - fn create_contract(initial_balance: Balance) -> GiveMe { + fn create_contract(initial_balance: U256) -> GiveMe { let accounts = default_accounts(); set_sender(accounts.alice); set_balance(contract_id(), initial_balance); GiveMe::new() } - fn contract_id() -> AccountId { - ink::env::test::callee::() + fn contract_id() -> H160 { + ink::env::test::callee() } - fn set_sender(sender: AccountId) { - ink::env::test::set_caller::(sender); + fn set_sender(sender: H160) { + ink::env::test::set_caller(sender); } - fn default_accounts( - ) -> ink::env::test::DefaultAccounts { - ink::env::test::default_accounts::() + fn default_accounts() -> ink::env::test::DefaultAccounts { + ink::env::test::default_accounts() } - fn set_balance(account_id: AccountId, balance: Balance) { - ink::env::test::set_account_balance::( - account_id, balance, - ) + // todo change all to addr + fn set_balance(account_id: H160, balance: U256) { + ink::env::test::set_account_balance(account_id, balance) } - fn get_balance(account_id: AccountId) -> Balance { + fn get_balance(account_id: H160) -> U256 { ink::env::test::get_account_balance::( account_id, ) - .expect("Cannot get account balance") + .expect("Cannot get contract balance") } } @@ -197,27 +207,31 @@ pub mod give_me { let mut constructor = GiveMeRef::new(); let contract = client .instantiate("contract_transfer", &ink_e2e::alice(), &mut constructor) - .value(1000) + .value(1_000_000_000) .submit() .await .expect("instantiate failed"); let mut call_builder = contract.call_builder::(); // when - let transfer = call_builder.give_me(120); + let transfer = call_builder.give_me(120_000_000.into()); let call_res = client .call(&ink_e2e::bob(), &transfer) - .value(10) + .value(10_000_000) .submit() .await; // then + assert!(call_res.is_err(), "call must have errored"); + /* + // todo bug with wrong printing of message if let Err(ink_e2e::Error::CallDryRun(dry_run)) = call_res { assert!(dry_run.debug_message.contains("paid an unpayable message")) } else { panic!("Paying an unpayable message should fail") } + */ Ok(()) } @@ -229,19 +243,27 @@ pub mod give_me { let mut constructor = GiveMeRef::new(); let contract = client .instantiate("contract_transfer", &ink_e2e::bob(), &mut constructor) - .value(1337) + .value(1_337_000_000) .submit() .await .expect("instantiate failed"); let mut call_builder = contract.call_builder::(); + let acc = call_builder.account_id(); + let call_res = client + .call(&ink_e2e::eve(), &acc) + .submit() + .await + .expect("call failed"); + let account_id: AccountId = call_res.return_value(); + let balance_before: Balance = client - .free_balance(contract.account_id.clone()) + .free_balance(account_id) .await .expect("getting balance failed"); // when - let transfer = call_builder.give_me(120); + let transfer = call_builder.give_me(120_000_000.into()); let call_res = client .call(&ink_e2e::eve(), &transfer) @@ -250,10 +272,12 @@ pub mod give_me { .expect("call failed"); // then - assert!(call_res.debug_message().contains("requested value: 120\n")); + assert!(call_res + .debug_message() + .contains("requested value: 120000000\n")); let balance_after: Balance = client - .free_balance(contract.account_id.clone()) + .free_balance(account_id) .await .expect("getting balance failed"); assert_eq!(balance_before - balance_after, 120); diff --git a/integration-tests/public/contract-xcm/Cargo.toml b/integration-tests/public/contract-xcm/Cargo.toml index 25d0bdbcd64..96f95c12756 100644 --- a/integration-tests/public/contract-xcm/Cargo.toml +++ b/integration-tests/public/contract-xcm/Cargo.toml @@ -7,8 +7,8 @@ publish = false [dependencies] ink = { path = "../../../crates/ink", default-features = false } -frame-support = { version = "38.0.0", default-features = false } -pallet-balances = { version = "39.0.0", default-features = false } +frame-support = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } [dev-dependencies] ink_e2e = { path = "../../../crates/e2e", features = ["sandbox"] } diff --git a/integration-tests/public/contract-xcm/lib.rs b/integration-tests/public/contract-xcm/lib.rs index 92015d6e7f4..85631d0a6ea 100644 --- a/integration-tests/public/contract-xcm/lib.rs +++ b/integration-tests/public/contract-xcm/lib.rs @@ -1,3 +1,4 @@ +// todo example needs to be fixed, but this requires the map AccountId -> H160 function #![cfg_attr(not(feature = "std"), no_std, no_main)] #[ink::contract] @@ -5,6 +6,7 @@ mod contract_xcm { use ink::{ env::Error as EnvError, xcm::prelude::*, + //xcm::v4::*, }; /// A trivial contract used to exercise XCM API. @@ -29,7 +31,7 @@ mod contract_xcm { EnvError::ReturnError(ReturnErrorCode::XcmSendFailed) => { RuntimeError::XcmSendFailed } - _ => panic!("Unexpected error from `pallet-contracts`."), + _ => panic!("Unexpected error from `pallet-revive`."), } } } @@ -61,14 +63,14 @@ mod contract_xcm { id: *receiver.as_ref(), }; - let message: Xcm<()> = Xcm::builder() + let message: ink::xcm::v5::Xcm<()> = Xcm::builder() .withdraw_asset(asset.clone()) .buy_execution(asset.clone(), Unlimited) .deposit_asset(asset, beneficiary) .build(); self.env() - .xcm_execute(&VersionedXcm::V4(message)) + .xcm_execute(&VersionedXcm::V5(message)) .map_err(Into::into) } @@ -85,11 +87,13 @@ mod contract_xcm { value: Balance, fee: Balance, ) -> Result { - let destination: Location = Parent.into(); + let destination: ink::xcm::v5::Location = ink::xcm::v5::Parent.into(); let asset: Asset = (Here, value).into(); + //let alice = AccountId32::from(ink_e2e::alice().public_key().0); let beneficiary = AccountId32 { network: None, - id: *self.env().caller().as_ref(), + // todo + id: [0x01; 32], }; let message: Xcm<()> = Xcm::builder() @@ -99,12 +103,19 @@ mod contract_xcm { .build(); let hash = self.env().xcm_send( - &VersionedLocation::V4(destination), - &VersionedXcm::V4(message), + &VersionedLocation::V5(destination), + &VersionedXcm::V5(message), )?; Ok(hash) } + + /// todo + /// Returns the `AccountId` of this contract. + #[ink(message)] + pub fn account_id(&mut self) -> AccountId { + self.env().account_id() + } } #[cfg(all(test, feature = "e2e-tests"))] @@ -113,13 +124,7 @@ mod contract_xcm { sp_runtime::AccountId32, traits::tokens::currency::Currency, }; - use ink::{ - env::{ - test::default_accounts, - DefaultEnvironment, - }, - primitives::AccountId, - }; + use ink::primitives::AccountId; use ink_e2e::{ preset::mock_network::{ self, @@ -161,10 +166,20 @@ mod contract_xcm { .expect("instantiate failed"); let mut call_builder = contract.call_builder::(); - let receiver: AccountId = default_accounts::().bob; + //let receiver: AccountId = default_accounts().bob; + let receiver = AccountId::from([0x02; 32]); + + // todo + let acc = call_builder.account_id(); + let call_res = client + .call(&ink_e2e::alice(), &acc) + .submit() + .await + .expect("call failed"); + let account_id: AccountId = call_res.return_value(); let contract_balance_before = client - .free_balance(contract.account_id) + .free_balance(account_id) .await .expect("Failed to get account balance"); let receiver_balance_before = client @@ -186,7 +201,7 @@ mod contract_xcm { // then let contract_balance_after = client - .free_balance(contract.account_id) + .free_balance(account_id) .await .expect("Failed to get account balance"); let receiver_balance_after = client @@ -215,7 +230,8 @@ mod contract_xcm { // This will fail since we have insufficient balance let transfer_message = call_builder.transfer_through_xcm( - default_accounts::().bob, + //default_accounts().bob, + AccountId::from([0x02; 32]), CONTRACT_BALANCE + 1, ); @@ -238,13 +254,27 @@ mod contract_xcm { .submit() .await .expect("instantiate failed"); + let mut call_builder = contract.call_builder::(); + + // todo + let acc = call_builder.account_id(); + let call_res = client + .call(&ink_e2e::alice(), &acc) + .submit() + .await + .expect("call failed"); + let account_id: AccountId = call_res.return_value(); Relay::execute_with(|| { let sovereign_account = parachain_account_sovereign_account_id( 1u32, - AccountId32::from(contract.account_id.0), + //AccountId32::from(contract.account_id.0), + AccountId32::from(account_id.0), + //account_id.into() ); + // The contract will be given 1000 tokens during instantiation. + //pub const CONTRACT_BALANCE: u128 = 1_000 * UNITS; // Fund the contract's derivative account, so we can use it as a sink, to // transfer funds to the caller. relay_chain::Balances::make_free_balance_be( @@ -262,7 +292,8 @@ mod contract_xcm { assert!(call_res.return_value().is_ok()); Relay::execute_with(|| { - let alice = AccountId32::from(ink_e2e::alice().public_key().0); + //let alice = AccountId32::from(ink_e2e::alice().public_key().0); + let alice = AccountId32::from([0x01; 32]); assert_eq!(relay_chain::Balances::free_balance(&alice), amount - fee); }); diff --git a/integration-tests/public/cross-contract-calls/Cargo.toml b/integration-tests/public/cross-contract-calls/Cargo.toml index 0ca220ceea8..5d1ec446723 100755 --- a/integration-tests/public/cross-contract-calls/Cargo.toml +++ b/integration-tests/public/cross-contract-calls/Cargo.toml @@ -12,6 +12,7 @@ ink = { path = "../../../crates/ink", default-features = false } # # If we don't we will end up with linking errors! other-contract = { path = "other-contract", default-features = false, features = ["ink-as-dependency"] } +pallet-revive-uapi = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false, features = ["unstable-hostfn"] } [dev-dependencies] ink_e2e = { path = "../../../crates/e2e" } diff --git a/integration-tests/public/cross-contract-calls/e2e_tests.rs b/integration-tests/public/cross-contract-calls/e2e_tests.rs index 26d168aa0ad..59bc43ad966 100644 --- a/integration-tests/public/cross-contract-calls/e2e_tests.rs +++ b/integration-tests/public/cross-contract-calls/e2e_tests.rs @@ -4,38 +4,7 @@ use ink_e2e::ContractsBackend; type E2EResult = std::result::Result>; #[ink_e2e::test] -async fn flip_and_get(mut client: Client) -> E2EResult<()> { - // given - let other_contract_code = client - .upload("other-contract", &ink_e2e::alice()) - .submit() - .await - .expect("other_contract upload failed"); - - let mut constructor = CrossContractCallsRef::new_v1(other_contract_code.code_hash); - let contract = client - .instantiate("cross-contract-calls", &ink_e2e::alice(), &mut constructor) - .submit() - .await - .expect("basic-contract-caller instantiate failed"); - let mut call_builder = contract.call_builder::(); - let call = call_builder.flip_and_get_v1(); - - // when - let result = client - .call(&ink_e2e::alice(), &call) - .submit() - .await - .expect("Calling `flip_and_get` failed") - .return_value(); - - assert!(!result); - - Ok(()) -} - -#[ink_e2e::test] -async fn instantiate_v2_with_insufficient_storage_deposit_limit( +async fn instantiate_with_insufficient_storage_deposit_limit( mut client: Client, ) -> E2EResult<()> { // given @@ -45,38 +14,43 @@ async fn instantiate_v2_with_insufficient_storage_deposit_limit( +async fn instantiate_with_sufficient_limits( mut client: Client, ) -> E2EResult<()> { // given @@ -86,15 +60,17 @@ async fn instantiate_v2_with_sufficient_limits( .await .expect("other_contract upload failed"); - const REF_TIME_LIMIT: u64 = 500_000_000; - const PROOF_SIZE_LIMIT: u64 = 100_000; - const STORAGE_DEPOSIT_LIMIT: u128 = 500_000_000_000; + const REF_TIME_LIMIT: u64 = 500_000_000_000_000; + const PROOF_SIZE_LIMIT: u64 = 100_000_000_000; + // todo remove the last group of `000` to get an `OutOfGas` error in + // `pallet-revive`. but they should throw an error about `StorageLimitExhausted`. + let storage_deposit_limit = ink::U256::from(100_000_000_000_000u64); - let mut constructor = CrossContractCallsRef::new_v2_with_limits( + let mut constructor = CrossContractCallsRef::new_with_limits( other_contract_code.code_hash, REF_TIME_LIMIT, PROOF_SIZE_LIMIT, - STORAGE_DEPOSIT_LIMIT, + storage_deposit_limit, ); let contract = client .instantiate("cross-contract-calls", &ink_e2e::alice(), &mut constructor) @@ -107,9 +83,7 @@ async fn instantiate_v2_with_sufficient_limits( } #[ink_e2e::test] -async fn instantiate_v2_no_limits( - mut client: Client, -) -> E2EResult<()> { +async fn instantiate_no_limits(mut client: Client) -> E2EResult<()> { // given let other_contract_code = client .upload("other-contract", &ink_e2e::alice()) @@ -118,7 +92,7 @@ async fn instantiate_v2_no_limits( .expect("other_contract upload failed"); let mut constructor = - CrossContractCallsRef::new_v2_no_limits(other_contract_code.code_hash); + CrossContractCallsRef::new_no_limits(other_contract_code.code_hash); let contract = client .instantiate("cross-contract-calls", &ink_e2e::alice(), &mut constructor) .submit() @@ -130,7 +104,7 @@ async fn instantiate_v2_no_limits( } #[ink_e2e::test] -async fn flip_and_get_v2(mut client: Client) -> E2EResult<()> { +async fn flip_and_get(mut client: Client) -> E2EResult<()> { // given let other_contract_code = client .upload("other-contract", &ink_e2e::alice()) @@ -138,7 +112,8 @@ async fn flip_and_get_v2(mut client: Client) -> E2EResult<() .await .expect("other_contract upload failed"); - let mut constructor = CrossContractCallsRef::new_v1(other_contract_code.code_hash); + let mut constructor = + CrossContractCallsRef::new_no_limits(other_contract_code.code_hash); let contract = client .instantiate("cross-contract-calls", &ink_e2e::alice(), &mut constructor) .submit() @@ -148,29 +123,29 @@ async fn flip_and_get_v2(mut client: Client) -> E2EResult<() const REF_TIME_LIMIT: u64 = 500_000_000; const PROOF_SIZE_LIMIT: u64 = 100_000; - const STORAGE_DEPOSIT_LIMIT: u128 = 1_000_000_000; + let storage_deposit_limit = ink::U256::from(1_000_000_000); // when - let call = call_builder.flip_and_get_invoke_v2_with_limits( + let call = call_builder.flip_and_get_invoke_with_limits( REF_TIME_LIMIT, PROOF_SIZE_LIMIT, - STORAGE_DEPOSIT_LIMIT, + storage_deposit_limit, ); let result = client .call(&ink_e2e::alice(), &call) .submit() .await - .expect("Calling `flip_and_get` failed") + .expect("Calling `flip_and_get_invoke_with_limits` failed") .return_value(); assert!(!result); - let call = call_builder.flip_and_get_invoke_v2_no_weight_limit(); + let call = call_builder.flip_and_get_invoke_no_weight_limit(); let result = client .call(&ink_e2e::alice(), &call) .submit() .await - .expect("Calling `flip_and_get` failed") + .expect("Calling `flip_and_get_invoke_no_weight_limit` failed") .return_value(); assert!(result); diff --git a/integration-tests/public/cross-contract-calls/lib.rs b/integration-tests/public/cross-contract-calls/lib.rs index 297c544d2a6..2106df756a0 100755 --- a/integration-tests/public/cross-contract-calls/lib.rs +++ b/integration-tests/public/cross-contract-calls/lib.rs @@ -12,19 +12,19 @@ mod cross_contract_calls { impl CrossContractCalls { /// Initializes the contract by instantiating the code at the given code hash via - /// `instantiate_v2` host function with the supplied weight and storage + /// `instantiate` host function with the supplied weight and storage /// limits. #[ink(constructor)] - pub fn new_v2_with_limits( - other_contract_code_hash: Hash, + pub fn new_with_limits( + other_contract_code_hash: ink::H256, ref_time_limit: u64, proof_size_limit: u64, - storage_deposit_limit: Balance, + storage_deposit_limit: ink::U256, ) -> Self { let other_contract = OtherContractRef::new(true) .code_hash(other_contract_code_hash) - .endowment(0) - .salt_bytes([0xDE, 0xAD, 0xBE, 0xEF]) + .endowment(0.into()) + .salt_bytes(Some([1u8; 32])) .ref_time_limit(ref_time_limit) .proof_size_limit(proof_size_limit) .storage_deposit_limit(storage_deposit_limit) @@ -34,56 +34,30 @@ mod cross_contract_calls { } /// Initializes the contract by instantiating the code at the given code hash via - /// the `instantiate_v2` host function with no weight or storage limits. + /// the `instantiate` host function with no weight or storage limits. #[ink(constructor)] - pub fn new_v2_no_limits(other_contract_code_hash: Hash) -> Self { + pub fn new_no_limits(other_contract_code_hash: ink::H256) -> Self { let other_contract = OtherContractRef::new(true) .code_hash(other_contract_code_hash) - .endowment(0) - .salt_bytes([0xDE, 0xAD, 0xBE, 0xEF]) + .endowment(0.into()) + .salt_bytes(Some([1u8; 32])) .instantiate(); Self { other_contract } } - /// Initializes the contract by instantiating the code at the given code hash via - /// the original `instantiate` host function. - #[ink(constructor)] - pub fn new_v1(other_contract_code_hash: Hash) -> Self { - let other_contract = OtherContractRef::new(true) - .instantiate_v1() - .code_hash(other_contract_code_hash) - .endowment(0) - .salt_bytes([0xDE, 0xAD, 0xBE, 0xEF]) - .instantiate(); - - Self { other_contract } - } - - /// Basic invocation of the other contract via the contract reference. - /// - /// *Note* this will invoke the original `call` (V1) host function, which will be - /// deprecated in the future. - #[ink(message)] - pub fn flip_and_get_v1(&mut self) -> bool { - let call_builder = self.other_contract.call_mut(); - - call_builder.flip().call_v1().invoke(); - call_builder.get().call_v1().invoke() - } - - /// Use the new `call_v2` host function via the call builder to forward calls to + /// Use the `call` host function via the call builder to forward calls to /// the other contract, initially calling `flip` and then `get` to return the /// result. /// /// This demonstrates how to set the new weight and storage limit parameters via /// the call builder API. #[ink(message)] - pub fn flip_and_get_invoke_v2_with_limits( + pub fn flip_and_get_invoke_with_limits( &mut self, ref_time_limit: u64, proof_size_limit: u64, - storage_deposit_limit: Balance, + storage_deposit_limit: ink::U256, ) -> bool { let call_builder = self.other_contract.call_mut(); @@ -102,10 +76,10 @@ mod cross_contract_calls { .invoke() } - /// Demonstrate that the `call_v2` succeeds without having specified the weight + /// Demonstrate that the `call` succeeds without having specified the weight /// and storage limit parameters #[ink(message)] - pub fn flip_and_get_invoke_v2_no_weight_limit(&mut self) -> bool { + pub fn flip_and_get_invoke_no_weight_limit(&mut self) -> bool { self.other_contract.flip(); self.other_contract.get() } diff --git a/integration-tests/public/cross-contract-calls/other-contract/Cargo.toml b/integration-tests/public/cross-contract-calls/other-contract/Cargo.toml index 699ca0455aa..48b30784aae 100755 --- a/integration-tests/public/cross-contract-calls/other-contract/Cargo.toml +++ b/integration-tests/public/cross-contract-calls/other-contract/Cargo.toml @@ -7,6 +7,7 @@ publish = false [dependencies] ink = { path = "../../../../crates/ink", default-features = false } +pallet-revive-uapi = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false, features = ["unstable-hostfn"] } [dev-dependencies] ink_e2e = { path = "../../../../crates/e2e" } diff --git a/integration-tests/public/custom-allocator/Cargo.toml b/integration-tests/public/custom-allocator/Cargo.toml index 2648b5936ae..5b1e7b7f5c6 100755 --- a/integration-tests/public/custom-allocator/Cargo.toml +++ b/integration-tests/public/custom-allocator/Cargo.toml @@ -10,8 +10,10 @@ publish = false # first need to disable the included memory allocator. ink = { path = "../../../crates/ink", default-features = false, features = ["no-allocator"] } +#foo = { path = "../../../foo", default-features = false } # This is going to be our new global memory allocator. -dlmalloc = {version = "0.2", default-features = false, features = ["global"] } +#dlmalloc = {version = "0.2", default-features = false, features = ["global"] } +#bumpalo = "3.16.0" [dev-dependencies] ink_e2e = { path = "../../../crates/e2e" } diff --git a/integration-tests/public/custom-allocator/lib.rs b/integration-tests/public/custom-allocator/lib.rs index cc99a259adc..649a3c34312 100755 --- a/integration-tests/public/custom-allocator/lib.rs +++ b/integration-tests/public/custom-allocator/lib.rs @@ -27,14 +27,64 @@ //! Providing your own allocator lets you choose the right tradeoffs for your use case. #![cfg_attr(not(feature = "std"), no_std, no_main)] - // Here we set `dlmalloc` to be the global memory allocator. // // The [`GlobalAlloc`](https://doc.rust-lang.org/std/alloc/trait.GlobalAlloc.html) trait is // important to understand if you're swapping our your allocator. +//#[cfg(not(feature = "std"))] +//#[global_allocator] +//static ALLOC: dlmalloc::GlobalDlmalloc = dlmalloc::GlobalDlmalloc; +#![feature(sync_unsafe_cell)] +#![feature(allocator_api)] +use core::{ + alloc::{ + GlobalAlloc, + Layout, + }, + cell::SyncUnsafeCell, +}; + #[cfg(not(feature = "std"))] #[global_allocator] -static ALLOC: dlmalloc::GlobalDlmalloc = dlmalloc::GlobalDlmalloc; +static ALLOC: BumpAllocator = BumpAllocator {}; + +pub struct BumpAllocator {} + +struct BumpMemory { + buffer: [u8; 1024 * 1024], // Pre-allocated memory buffer + offset: usize, // Current allocation offset +} + +static mut MEMORY: Option> = None; + +#[allow(clippy::arithmetic_side_effects)] +unsafe impl GlobalAlloc for BumpAllocator { + #[allow(static_mut_refs)] + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + if MEMORY.is_none() { + MEMORY = Some(SyncUnsafeCell::new(BumpMemory { + buffer: [0; 1024 * 1024], + offset: 0, + })); + } + let memory = unsafe { &mut *MEMORY.as_ref().unwrap().get() }; + let start = memory.offset; + let end = start + layout.size(); + + if end > memory.buffer.len() { + panic!("too large"); + } else { + memory.offset = end; + //ink::env::debug_println!("Allocated {} from {start} to {}", end-start, + // end-1); + &mut memory.buffer[start] + } + } + + unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) { + // No-op: deallocation is unsupported in a bump allocator. + } +} #[ink::contract] mod custom_allocator { @@ -129,7 +179,7 @@ mod custom_allocator { // Then let get = call_builder.get(); let get_result = client.call(&ink_e2e::alice(), &get).dry_run().await?; - assert!(matches!(get_result.return_value(), false)); + assert!(!get_result.return_value()); Ok(()) } @@ -149,7 +199,7 @@ mod custom_allocator { let get = call_builder.get(); let get_result = client.call(&ink_e2e::bob(), &get).dry_run().await?; - assert!(matches!(get_result.return_value(), false)); + assert!(!get_result.return_value()); // When let flip = call_builder.flip(); @@ -162,7 +212,7 @@ mod custom_allocator { // Then let get = call_builder.get(); let get_result = client.call(&ink_e2e::bob(), &get).dry_run().await?; - assert!(matches!(get_result.return_value(), true)); + assert!(get_result.return_value()); Ok(()) } diff --git a/integration-tests/public/custom-environment/README.md b/integration-tests/public/custom-environment/README.md index 8bd35b4614e..237980c7809 100644 --- a/integration-tests/public/custom-environment/README.md +++ b/integration-tests/public/custom-environment/README.md @@ -11,8 +11,8 @@ To integrate this example into Substrate you need to adjust pallet contracts con ```rust // In your node's runtime configuration file (runtime.rs) parameter_types! { - pub Schedule: pallet_contracts::Schedule = pallet_contracts::Schedule:: { - limits: pallet_contracts::Limits { + pub Schedule: pallet_revive::Schedule = pallet_revive::Schedule:: { + limits: pallet_revive::Limits { event_topics: 6, ..Default::default() }, @@ -20,7 +20,7 @@ parameter_types! { }; } -impl pallet_contracts::Config for Runtime { +impl pallet_revive::Config for Runtime { … type Schedule = Schedule; … diff --git a/integration-tests/public/custom-environment/lib.rs b/integration-tests/public/custom-environment/lib.rs index f78f2c239b9..441b6b11192 100644 --- a/integration-tests/public/custom-environment/lib.rs +++ b/integration-tests/public/custom-environment/lib.rs @@ -23,6 +23,7 @@ impl Environment for EnvironmentWithManyTopics { type Hash = ::Hash; type BlockNumber = ::BlockNumber; type Timestamp = ::Timestamp; + type EventRecord = ::EventRecord; type ChainExtension = ::ChainExtension; } @@ -109,7 +110,7 @@ mod runtime_call { .expect("call failed"); // then - call_res.contains_event("Contracts", "ContractEmitted"); + assert!(call_res.contains_event("Revive", "ContractEmitted")); Ok(()) } diff --git a/integration-tests/public/dns/lib.rs b/integration-tests/public/dns/lib.rs index a46cdb6e9ea..24239dad26f 100644 --- a/integration-tests/public/dns/lib.rs +++ b/integration-tests/public/dns/lib.rs @@ -2,39 +2,43 @@ #[ink::contract] mod dns { - use ink::storage::Mapping; + use ink::{ + storage::Mapping, + H160, + H256, + }; /// Emitted whenever a new name is being registered. #[ink(event)] pub struct Register { #[ink(topic)] - name: Hash, + name: H256, #[ink(topic)] - from: AccountId, + from: H160, } /// Emitted whenever an address changes. #[ink(event)] pub struct SetAddress { #[ink(topic)] - name: Hash, - from: AccountId, + name: H256, + from: H160, #[ink(topic)] - old_address: Option, + old_address: Option, #[ink(topic)] - new_address: AccountId, + new_address: H160, } /// Emitted whenever a name is being transferred. #[ink(event)] pub struct Transfer { #[ink(topic)] - name: Hash, - from: AccountId, + name: H256, + from: H160, #[ink(topic)] - old_owner: Option, + old_owner: Option, #[ink(topic)] - new_owner: AccountId, + new_owner: H160, } /// Domain name service contract inspired by @@ -55,19 +59,19 @@ mod dns { #[ink(storage)] pub struct DomainNameService { /// A hashmap to store all name to addresses mapping. - name_to_address: Mapping, + name_to_address: Mapping, /// A hashmap to store all name to owners mapping. - name_to_owner: Mapping, + name_to_owner: Mapping, /// The default address. - default_address: AccountId, + default_address: H160, } impl Default for DomainNameService { fn default() -> Self { let mut name_to_address = Mapping::new(); - name_to_address.insert(Hash::default(), &zero_address()); + name_to_address.insert(H256::default(), &zero_address()); let mut name_to_owner = Mapping::new(); - name_to_owner.insert(Hash::default(), &zero_address()); + name_to_owner.insert(H256::default(), &zero_address()); Self { name_to_address, @@ -99,7 +103,7 @@ mod dns { /// Register specific name with caller as owner. #[ink(message)] - pub fn register(&mut self, name: Hash) -> Result<()> { + pub fn register(&mut self, name: H256) -> Result<()> { let caller = self.env().caller(); if self.name_to_owner.contains(name) { return Err(Error::NameAlreadyExists) @@ -113,7 +117,7 @@ mod dns { /// Set address for specific name. #[ink(message)] - pub fn set_address(&mut self, name: Hash, new_address: AccountId) -> Result<()> { + pub fn set_address(&mut self, name: H256, new_address: H160) -> Result<()> { let caller = self.env().caller(); let owner = self.get_owner_or_default(name); if caller != owner { @@ -134,7 +138,7 @@ mod dns { /// Transfer owner to another address. #[ink(message)] - pub fn transfer(&mut self, name: Hash, to: AccountId) -> Result<()> { + pub fn transfer(&mut self, name: H256, to: H160) -> Result<()> { let caller = self.env().caller(); let owner = self.get_owner_or_default(name); if caller != owner { @@ -156,23 +160,23 @@ mod dns { /// Get address for specific name. #[ink(message)] - pub fn get_address(&self, name: Hash) -> AccountId { + pub fn get_address(&self, name: H256) -> H160 { self.get_address_or_default(name) } /// Get owner of specific name. #[ink(message)] - pub fn get_owner(&self, name: Hash) -> AccountId { + pub fn get_owner(&self, name: H256) -> H160 { self.get_owner_or_default(name) } /// Returns the owner given the hash or the default address. - fn get_owner_or_default(&self, name: Hash) -> AccountId { + fn get_owner_or_default(&self, name: H256) -> H160 { self.name_to_owner.get(name).unwrap_or(self.default_address) } /// Returns the address given the hash or the default address. - fn get_address_or_default(&self, name: Hash) -> AccountId { + fn get_address_or_default(&self, name: H256) -> H160 { self.name_to_address .get(name) .unwrap_or(self.default_address) @@ -182,27 +186,26 @@ mod dns { /// Helper for referencing the zero address (`0x00`). Note that in practice this /// address should not be treated in any special way (such as a default /// placeholder) since it has a known private key. - fn zero_address() -> AccountId { - [0u8; 32].into() + fn zero_address() -> H160 { + [0u8; 20].into() } #[cfg(test)] mod tests { use super::*; - fn default_accounts( - ) -> ink::env::test::DefaultAccounts { - ink::env::test::default_accounts::() + fn default_accounts() -> ink::env::test::DefaultAccounts { + ink::env::test::default_accounts() } - fn set_next_caller(caller: AccountId) { - ink::env::test::set_caller::(caller); + fn set_next_caller(caller: H160) { + ink::env::test::set_caller(caller); } #[ink::test] fn register_works() { let default_accounts = default_accounts(); - let name = Hash::from([0x99; 32]); + let name = H256::from([0x99; 32]); set_next_caller(default_accounts.alice); let mut contract = DomainNameService::new(); @@ -214,7 +217,7 @@ mod dns { #[ink::test] fn set_address_works() { let accounts = default_accounts(); - let name = Hash::from([0x99; 32]); + let name = H256::from([0x99; 32]); set_next_caller(accounts.alice); @@ -237,7 +240,7 @@ mod dns { #[ink::test] fn transfer_works() { let accounts = default_accounts(); - let name = Hash::from([0x99; 32]); + let name = H256::from([0x99; 32]); set_next_caller(accounts.alice); diff --git a/integration-tests/public/e2e-call-runtime/lib.rs b/integration-tests/public/e2e-call-runtime/lib.rs index aa8941f5e08..ec3eb92c2e0 100644 --- a/integration-tests/public/e2e-call-runtime/lib.rs +++ b/integration-tests/public/e2e-call-runtime/lib.rs @@ -13,9 +13,16 @@ pub mod e2e_call_runtime { } #[ink(message)] - pub fn get_contract_balance(&self) -> Balance { + pub fn get_contract_balance(&self) -> ink::U256 { self.env().balance() } + + /// todo + /// Returns the `AccountId` of this contract. + #[ink(message)] + pub fn account_id(&mut self) -> AccountId { + self.env().account_id() + } } #[cfg(all(test, feature = "e2e-tests"))] @@ -40,8 +47,18 @@ pub mod e2e_call_runtime { .submit() .await .expect("instantiate failed"); - let call_builder = contract.call_builder::(); + let mut call_builder = contract.call_builder::(); + + // todo + let acc = call_builder.account_id(); + let call_res = client + .call(&ink_e2e::alice(), &acc) + .submit() + .await + .expect("call failed"); + let account_id: AccountId = call_res.return_value(); + // todo let transfer_amount = 100_000_000_000u128; // when @@ -49,7 +66,7 @@ pub mod e2e_call_runtime { // A value representing a `MultiAddress`. We want the // "Id" variant, and that will ultimately contain the // bytes for our destination address - Value::unnamed_variant("Id", [Value::from_bytes(&contract.account_id)]), + Value::unnamed_variant("Id", [Value::from_bytes(account_id)]), // A value representing the amount we'd like to transfer. Value::u128(transfer_amount), ]; @@ -79,8 +96,10 @@ pub mod e2e_call_runtime { .dry_run() .await?; + // todo NativeToEthRatio should be part of `Environment` + let native_to_eth_ratio = ink::U256::from(1_000_000); assert_eq!( - get_balance_res.return_value(), + get_balance_res.return_value() / native_to_eth_ratio, pre_balance + transfer_amount ); diff --git a/integration-tests/public/erc1155/lib.rs b/integration-tests/public/erc1155/lib.rs index f6cbf56971d..98c1f60c809 100644 --- a/integration-tests/public/erc1155/lib.rs +++ b/integration-tests/public/erc1155/lib.rs @@ -2,7 +2,8 @@ use ink::{ prelude::vec::Vec, - primitives::AccountId, + H160, + U256, }; // This is the return value that we expect if a smart contract supports receiving ERC-1155 @@ -25,8 +26,6 @@ const _ON_ERC_1155_BATCH_RECEIVED_SELECTOR: [u8; 4] = [0xBC, 0x19, 0x7C, 0x81]; /// A type representing the unique IDs of tokens managed by this contract. pub type TokenId = u128; -type Balance = ::Balance; - // The ERC-1155 error types. #[derive(Debug, PartialEq, Eq)] #[ink::scale_derive(Encode, Decode, TypeInfo)] @@ -38,7 +37,7 @@ pub enum Error { /// The caller is not approved to transfer tokens on behalf of the account. NotApproved, /// The account does not have enough funds to complete the transfer. - InsufficientBalance, + InsufficientU256, /// An account does not need to approve themselves to transfer tokens. SelfApproval, /// The number of tokens being transferred does not match the specified number of @@ -79,10 +78,10 @@ pub trait Erc1155 { #[ink(message)] fn safe_transfer_from( &mut self, - from: AccountId, - to: AccountId, + from: H160, + to: H160, token_id: TokenId, - value: Balance, + value: U256, data: Vec, ) -> Result<()>; @@ -97,16 +96,16 @@ pub trait Erc1155 { #[ink(message)] fn safe_batch_transfer_from( &mut self, - from: AccountId, - to: AccountId, + from: H160, + to: H160, token_ids: Vec, - values: Vec, + values: Vec, data: Vec, ) -> Result<()>; /// Query the balance of a specific token for the provided account. #[ink(message)] - fn balance_of(&self, owner: AccountId, token_id: TokenId) -> Balance; + fn balance_of(&self, owner: H160, token_id: TokenId) -> U256; /// Query the balances for a set of tokens for a set of accounts. /// @@ -116,24 +115,19 @@ pub trait Erc1155 { /// This will return all the balances for a given owner before moving on to the next /// owner. In the example above this means that the return value should look like: /// - /// [Alice Balance of Token ID 1, Alice Balance of Token ID 2, Bob Balance of Token ID - /// 1, Bob Balance of Token ID 2] + /// [Alice U256 of Token ID 1, Alice U256 of Token ID 2, Bob U256 of Token ID + /// 1, Bob U256 of Token ID 2] #[ink(message)] - fn balance_of_batch( - &self, - owners: Vec, - token_ids: Vec, - ) -> Vec; + fn balance_of_batch(&self, owners: Vec, token_ids: Vec) -> Vec; /// Enable or disable a third party, known as an `operator`, to control all tokens on /// behalf of the caller. #[ink(message)] - fn set_approval_for_all(&mut self, operator: AccountId, approved: bool) - -> Result<()>; + fn set_approval_for_all(&mut self, operator: H160, approved: bool) -> Result<()>; /// Query if the given `operator` is allowed to control all of `owner`'s tokens. #[ink(message)] - fn is_approved_for_all(&self, owner: AccountId, operator: AccountId) -> bool; + fn is_approved_for_all(&self, owner: H160, operator: H160) -> bool; } /// The interface for an ERC-1155 Token Receiver contract. @@ -160,10 +154,10 @@ pub trait Erc1155TokenReceiver { #[ink(message, selector = 0xF23A6E61)] fn on_received( &mut self, - operator: AccountId, - from: AccountId, + operator: H160, + from: H160, token_id: TokenId, - value: Balance, + value: U256, data: Vec, ) -> Vec; @@ -181,10 +175,10 @@ pub trait Erc1155TokenReceiver { #[ink(message, selector = 0xBC197C81)] fn on_batch_received( &mut self, - operator: AccountId, - from: AccountId, + operator: H160, + from: H160, token_ids: Vec, - values: Vec, + values: Vec, data: Vec, ) -> Vec; } @@ -193,10 +187,14 @@ pub trait Erc1155TokenReceiver { mod erc1155 { use super::*; - use ink::storage::Mapping; + use ink::{ + storage::Mapping, + H160, + U256, + }; - type Owner = AccountId; - type Operator = AccountId; + type Owner = H160; + type Operator = H160; /// Indicate that a token transfer has occured. /// @@ -204,22 +202,22 @@ mod erc1155 { #[ink(event)] pub struct TransferSingle { #[ink(topic)] - operator: Option, + operator: Option, #[ink(topic)] - from: Option, + from: Option, #[ink(topic)] - to: Option, + to: Option, token_id: TokenId, - value: Balance, + value: U256, } /// Indicate that an approval event has happened. #[ink(event)] pub struct ApprovalForAll { #[ink(topic)] - owner: AccountId, + owner: H160, #[ink(topic)] - operator: AccountId, + operator: H160, approved: bool, } @@ -237,7 +235,7 @@ mod erc1155 { pub struct Contract { /// Tracks the balances of accounts across the different tokens that they might /// be holding. - balances: Mapping<(AccountId, TokenId), Balance>, + balances: Mapping<(H160, TokenId), U256>, /// Which accounts (called operators) have been approved to spend funds on behalf /// of an owner. approvals: Mapping<(Owner, Operator), ()>, @@ -262,7 +260,7 @@ mod erc1155 { /// this contract in a production environment you'd probably want to lock down /// the addresses that are allowed to create tokens. #[ink(message)] - pub fn create(&mut self, value: Balance) -> TokenId { + pub fn create(&mut self, value: U256) -> TokenId { let caller = self.env().caller(); // Given that TokenId is a `u128` the likelihood of this overflowing is pretty @@ -277,7 +275,11 @@ mod erc1155 { self.env().emit_event(TransferSingle { operator: Some(caller), from: None, - to: if value == 0 { None } else { Some(caller) }, + to: if value == U256::zero() { + None + } else { + Some(caller) + }, token_id: self.token_id_nonce, value, }); @@ -294,7 +296,7 @@ mod erc1155 { /// this contract in a production environment you'd probably want to lock down /// the addresses that are allowed to mint tokens. #[ink(message)] - pub fn mint(&mut self, token_id: TokenId, value: Balance) -> Result<()> { + pub fn mint(&mut self, token_id: TokenId, value: U256) -> Result<()> { ensure!(token_id <= self.token_id_nonce, Error::UnexistentToken); let caller = self.env().caller(); @@ -323,10 +325,10 @@ mod erc1155 { // If `from` does not hold any `token_id` tokens. fn perform_transfer( &mut self, - from: AccountId, - to: AccountId, + from: H160, + to: H160, token_id: TokenId, - value: Balance, + value: U256, ) { let mut sender_balance = self .balances @@ -339,7 +341,8 @@ mod erc1155 { } self.balances.insert((from, token_id), &sender_balance); - let mut recipient_balance = self.balances.get((to, token_id)).unwrap_or(0); + let mut recipient_balance = + self.balances.get((to, token_id)).unwrap_or(U256::zero()); recipient_balance = recipient_balance.checked_add(value).unwrap(); self.balances.insert((to, token_id), &recipient_balance); @@ -362,11 +365,11 @@ mod erc1155 { #[cfg_attr(test, allow(unused_variables))] fn transfer_acceptance_check( &mut self, - caller: AccountId, - from: AccountId, - to: AccountId, + caller: H160, + from: H160, + to: H160, token_id: TokenId, - value: Balance, + value: U256, data: Vec, ) { // This is disabled during tests due to the use of `invoke_contract()` not @@ -417,8 +420,11 @@ mod erc1155 { match e { ink::env::Error::ReturnError( - ReturnErrorCode::CodeNotFound - | ReturnErrorCode::NotCallable, + ReturnErrorCode::Unknown, /* todo: these error codes + * don't exist in uapi yet, + * fallback + * is `Unknown` + * ReturnErrorCode::CodeNotFound | ReturnErrorCode::NotCallable, */ ) => { // Our recipient wasn't a smart contract, so there's // nothing more for @@ -444,10 +450,10 @@ mod erc1155 { #[ink(message)] fn safe_transfer_from( &mut self, - from: AccountId, - to: AccountId, + from: H160, + to: H160, token_id: TokenId, - value: Balance, + value: U256, data: Vec, ) -> Result<()> { let caller = self.env().caller(); @@ -458,7 +464,7 @@ mod erc1155 { ensure!(to != zero_address(), Error::ZeroAddressTransfer); let balance = self.balance_of(from, token_id); - ensure!(balance >= value, Error::InsufficientBalance); + ensure!(balance >= value, Error::InsufficientU256); self.perform_transfer(from, to, token_id, value); self.transfer_acceptance_check(caller, from, to, token_id, value, data); @@ -469,10 +475,10 @@ mod erc1155 { #[ink(message)] fn safe_batch_transfer_from( &mut self, - from: AccountId, - to: AccountId, + from: H160, + to: H160, token_ids: Vec, - values: Vec, + values: Vec, data: Vec, ) -> Result<()> { let caller = self.env().caller(); @@ -490,14 +496,14 @@ mod erc1155 { let transfers = token_ids.iter().zip(values.iter()); for (&id, &v) in transfers.clone() { let balance = self.balance_of(from, id); - ensure!(balance >= v, Error::InsufficientBalance); + ensure!(balance >= v, Error::InsufficientU256); } for (&id, &v) in transfers { self.perform_transfer(from, to, id, v); } - // Can use the any token ID/value here, we really just care about knowing if + // Can use any token ID/value here, we really just care about knowing if // `to` is a smart contract which accepts transfers self.transfer_acceptance_check( caller, @@ -512,16 +518,16 @@ mod erc1155 { } #[ink(message)] - fn balance_of(&self, owner: AccountId, token_id: TokenId) -> Balance { - self.balances.get((owner, token_id)).unwrap_or(0) + fn balance_of(&self, owner: H160, token_id: TokenId) -> U256 { + self.balances.get((owner, token_id)).unwrap_or(0.into()) } #[ink(message)] fn balance_of_batch( &self, - owners: Vec, + owners: Vec, token_ids: Vec, - ) -> Vec { + ) -> Vec { let mut output = Vec::new(); for o in &owners { for t in &token_ids { @@ -533,11 +539,7 @@ mod erc1155 { } #[ink(message)] - fn set_approval_for_all( - &mut self, - operator: AccountId, - approved: bool, - ) -> Result<()> { + fn set_approval_for_all(&mut self, operator: H160, approved: bool) -> Result<()> { let caller = self.env().caller(); ensure!(operator != caller, Error::SelfApproval); @@ -557,7 +559,7 @@ mod erc1155 { } #[ink(message)] - fn is_approved_for_all(&self, owner: AccountId, operator: AccountId) -> bool { + fn is_approved_for_all(&self, owner: H160, operator: H160) -> bool { self.approvals.contains((&owner, &operator)) } } @@ -566,10 +568,10 @@ mod erc1155 { #[ink(message, selector = 0xF23A6E61)] fn on_received( &mut self, - _operator: AccountId, - _from: AccountId, + _operator: H160, + _from: H160, _token_id: TokenId, - _value: Balance, + _value: U256, _data: Vec, ) -> Vec { // The ERC-1155 standard dictates that if a contract does not accept token @@ -589,10 +591,10 @@ mod erc1155 { #[ink(message, selector = 0xBC197C81)] fn on_batch_received( &mut self, - _operator: AccountId, - _from: AccountId, + _operator: H160, + _from: H160, _token_ids: Vec, - _values: Vec, + _values: Vec, _data: Vec, ) -> Vec { // The ERC-1155 standard dictates that if a contract does not accept token @@ -613,8 +615,8 @@ mod erc1155 { /// Helper for referencing the zero address (`0x00`). Note that in practice this /// address should not be treated in any special way (such as a default /// placeholder) since it has a known private key. - fn zero_address() -> AccountId { - [0u8; 32].into() + fn zero_address() -> H160 { + [0u8; 20].into() } #[cfg(test)] @@ -623,31 +625,32 @@ mod erc1155 { use super::*; use crate::Erc1155; - fn set_sender(sender: AccountId) { - ink::env::test::set_caller::(sender); + fn set_sender(sender: H160) { + ink::env::test::set_caller(sender); } - fn default_accounts() -> ink::env::test::DefaultAccounts { - ink::env::test::default_accounts::() + fn default_accounts() -> ink::env::test::DefaultAccounts { + ink::env::test::default_accounts() } - fn alice() -> AccountId { + fn alice() -> H160 { default_accounts().alice } - fn bob() -> AccountId { + fn bob() -> H160 { default_accounts().bob } - fn charlie() -> AccountId { + fn charlie() -> H160 { default_accounts().charlie } fn init_contract() -> Contract { + set_sender(alice()); let mut erc = Contract::new(); - erc.balances.insert((alice(), 1), &10); - erc.balances.insert((alice(), 2), &20); - erc.balances.insert((bob(), 1), &10); + erc.balances.insert((alice(), 1), &U256::from(10)); + erc.balances.insert((alice(), 2), &U256::from(20)); + erc.balances.insert((bob(), 1), &U256::from(10)); erc } @@ -656,10 +659,10 @@ mod erc1155 { fn can_get_correct_balance_of() { let erc = init_contract(); - assert_eq!(erc.balance_of(alice(), 1), 10); - assert_eq!(erc.balance_of(alice(), 2), 20); - assert_eq!(erc.balance_of(alice(), 3), 0); - assert_eq!(erc.balance_of(bob(), 2), 0); + assert_eq!(erc.balance_of(alice(), 1), U256::from(10)); + assert_eq!(erc.balance_of(alice(), 2), U256::from(20)); + assert_eq!(erc.balance_of(alice(), 3), U256::zero()); + assert_eq!(erc.balance_of(bob(), 2), U256::zero()); } #[ink::test] @@ -668,16 +671,23 @@ mod erc1155 { assert_eq!( erc.balance_of_batch(vec![alice()], vec![1, 2, 3]), - vec![10, 20, 0] + vec![U256::from(10), 20.into(), 0.into()] ); assert_eq!( erc.balance_of_batch(vec![alice(), bob()], vec![1]), - vec![10, 10] + vec![U256::from(10), 10.into()] ); assert_eq!( erc.balance_of_batch(vec![alice(), bob(), charlie()], vec![1, 2]), - vec![10, 20, 10, 0, 0, 0] + vec![ + U256::from(10), + 20.into(), + 10.into(), + 0.into(), + 0.into(), + 0.into() + ] ); } @@ -685,28 +695,32 @@ mod erc1155 { fn can_send_tokens_between_accounts() { let mut erc = init_contract(); - assert!(erc.safe_transfer_from(alice(), bob(), 1, 5, vec![]).is_ok()); - assert_eq!(erc.balance_of(alice(), 1), 5); - assert_eq!(erc.balance_of(bob(), 1), 15); + assert!(erc + .safe_transfer_from(alice(), bob(), 1, 5.into(), vec![]) + .is_ok()); + assert_eq!(erc.balance_of(alice(), 1), U256::from(5)); + assert_eq!(erc.balance_of(bob(), 1), U256::from(15)); - assert!(erc.safe_transfer_from(alice(), bob(), 2, 5, vec![]).is_ok()); - assert_eq!(erc.balance_of(alice(), 2), 15); - assert_eq!(erc.balance_of(bob(), 2), 5); + assert!(erc + .safe_transfer_from(alice(), bob(), 2, 5.into(), vec![]) + .is_ok()); + assert_eq!(erc.balance_of(alice(), 2), U256::from(15)); + assert_eq!(erc.balance_of(bob(), 2), U256::from(5)); } #[ink::test] fn sending_too_many_tokens_fails() { let mut erc = init_contract(); - let res = erc.safe_transfer_from(alice(), bob(), 1, 99, vec![]); - assert_eq!(res.unwrap_err(), Error::InsufficientBalance); + let res = erc.safe_transfer_from(alice(), bob(), 1, 99.into(), vec![]); + assert_eq!(res.unwrap_err(), Error::InsufficientU256); } #[ink::test] fn sending_tokens_to_zero_address_fails() { - let burn: AccountId = [0; 32].into(); + let burn: H160 = [0; 20].into(); let mut erc = init_contract(); - let res = erc.safe_transfer_from(alice(), burn, 1, 10, vec![]); + let res = erc.safe_transfer_from(alice(), burn, 1, 10.into(), vec![]); assert_eq!(res.unwrap_err(), Error::ZeroAddressTransfer); } @@ -714,11 +728,20 @@ mod erc1155 { fn can_send_batch_tokens() { let mut erc = init_contract(); assert!(erc - .safe_batch_transfer_from(alice(), bob(), vec![1, 2], vec![5, 10], vec![]) + .safe_batch_transfer_from( + alice(), + bob(), + vec![1, 2], + vec![U256::from(5), U256::from(10)], + vec![] + ) .is_ok()); let balances = erc.balance_of_batch(vec![alice(), bob()], vec![1, 2]); - assert_eq!(balances, vec![5, 10, 15, 10]) + assert_eq!( + balances, + vec![U256::from(5), 10.into(), 15.into(), 10.into()] + ); } #[ink::test] @@ -728,7 +751,7 @@ mod erc1155 { alice(), bob(), vec![1, 2, 3], - vec![5], + vec![U256::from(5)], vec![], ); assert_eq!(res.unwrap_err(), Error::BatchTransferMismatch); @@ -754,10 +777,10 @@ mod erc1155 { set_sender(operator); assert!(erc - .safe_transfer_from(owner, charlie(), 1, 5, vec![]) + .safe_transfer_from(owner, charlie(), 1, 5.into(), vec![]) .is_ok()); - assert_eq!(erc.balance_of(alice(), 1), 5); - assert_eq!(erc.balance_of(charlie(), 1), 5); + assert_eq!(erc.balance_of(alice(), 1), U256::from(5)); + assert_eq!(erc.balance_of(charlie(), 1), U256::from(5)); } #[ink::test] @@ -787,18 +810,18 @@ mod erc1155 { let mut erc = Contract::new(); set_sender(alice()); - assert_eq!(erc.create(0), 1); - assert_eq!(erc.balance_of(alice(), 1), 0); + assert_eq!(erc.create(0.into()), 1); + assert_eq!(erc.balance_of(alice(), 1), U256::zero()); - assert!(erc.mint(1, 123).is_ok()); - assert_eq!(erc.balance_of(alice(), 1), 123); + assert!(erc.mint(1, 123.into()).is_ok()); + assert_eq!(erc.balance_of(alice(), 1), U256::from(123)); } #[ink::test] fn minting_not_allowed_for_nonexistent_tokens() { let mut erc = Contract::new(); - let res = erc.mint(1, 123); + let res = erc.mint(1, 123.into()); assert_eq!(res.unwrap_err(), Error::UnexistentToken); } } diff --git a/integration-tests/public/erc20/lib.rs b/integration-tests/public/erc20/lib.rs index 82a4c438b5d..2368cd294f2 100644 --- a/integration-tests/public/erc20/lib.rs +++ b/integration-tests/public/erc20/lib.rs @@ -2,29 +2,33 @@ #[ink::contract] mod erc20 { - use ink::storage::Mapping; + use ink::{ + storage::Mapping, + H160, + U256, + }; /// A simple ERC-20 contract. #[ink(storage)] #[derive(Default)] pub struct Erc20 { /// Total token supply. - total_supply: Balance, + total_supply: U256, /// Mapping from owner to number of owned token. - balances: Mapping, + balances: Mapping, /// Mapping of the token amount which an account is allowed to withdraw /// from another account. - allowances: Mapping<(AccountId, AccountId), Balance>, + allowances: Mapping<(H160, H160), U256>, } /// Event emitted when a token transfer occurs. #[ink(event)] pub struct Transfer { #[ink(topic)] - from: Option, + from: Option, #[ink(topic)] - to: Option, - value: Balance, + to: Option, + value: U256, } /// Event emitted when an approval occurs that `spender` is allowed to withdraw @@ -32,10 +36,10 @@ mod erc20 { #[ink(event)] pub struct Approval { #[ink(topic)] - owner: AccountId, + owner: H160, #[ink(topic)] - spender: AccountId, - value: Balance, + spender: H160, + value: U256, } /// The ERC-20 error types. @@ -54,7 +58,7 @@ mod erc20 { impl Erc20 { /// Creates a new ERC-20 contract with the specified initial supply. #[ink(constructor)] - pub fn new(total_supply: Balance) -> Self { + pub fn new(total_supply: U256) -> Self { let mut balances = Mapping::default(); let caller = Self::env().caller(); balances.insert(caller, &total_supply); @@ -72,7 +76,7 @@ mod erc20 { /// Returns the total token supply. #[ink(message)] - pub fn total_supply(&self) -> Balance { + pub fn total_supply(&self) -> U256 { self.total_supply } @@ -80,7 +84,7 @@ mod erc20 { /// /// Returns `0` if the account is non-existent. #[ink(message)] - pub fn balance_of(&self, owner: AccountId) -> Balance { + pub fn balance_of(&self, owner: H160) -> U256 { self.balance_of_impl(&owner) } @@ -93,7 +97,7 @@ mod erc20 { /// Prefer to call this method over `balance_of` since this /// works using references which are more efficient in Wasm. #[inline] - fn balance_of_impl(&self, owner: &AccountId) -> Balance { + fn balance_of_impl(&self, owner: &H160) -> U256 { self.balances.get(owner).unwrap_or_default() } @@ -101,7 +105,7 @@ mod erc20 { /// /// Returns `0` if no allowance has been set. #[ink(message)] - pub fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance { + pub fn allowance(&self, owner: H160, spender: H160) -> U256 { self.allowance_impl(&owner, &spender) } @@ -114,7 +118,7 @@ mod erc20 { /// Prefer to call this method over `allowance` since this /// works using references which are more efficient in Wasm. #[inline] - fn allowance_impl(&self, owner: &AccountId, spender: &AccountId) -> Balance { + fn allowance_impl(&self, owner: &H160, spender: &H160) -> U256 { self.allowances.get((owner, spender)).unwrap_or_default() } @@ -127,7 +131,7 @@ mod erc20 { /// Returns `InsufficientBalance` error if there are not enough tokens on /// the caller's account balance. #[ink(message)] - pub fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()> { + pub fn transfer(&mut self, to: H160, value: U256) -> Result<()> { let from = self.env().caller(); self.transfer_from_to(&from, &to, value) } @@ -140,7 +144,7 @@ mod erc20 { /// /// An `Approval` event is emitted. #[ink(message)] - pub fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()> { + pub fn approve(&mut self, spender: H160, value: U256) -> Result<()> { let owner = self.env().caller(); self.allowances.insert((&owner, &spender), &value); self.env().emit_event(Approval { @@ -166,12 +170,7 @@ mod erc20 { /// Returns `InsufficientBalance` error if there are not enough tokens on /// the account balance of `from`. #[ink(message)] - pub fn transfer_from( - &mut self, - from: AccountId, - to: AccountId, - value: Balance, - ) -> Result<()> { + pub fn transfer_from(&mut self, from: H160, to: H160, value: U256) -> Result<()> { let caller = self.env().caller(); let allowance = self.allowance_impl(&from, &caller); if allowance < value { @@ -195,9 +194,9 @@ mod erc20 { /// the caller's account balance. fn transfer_from_to( &mut self, - from: &AccountId, - to: &AccountId, - value: Balance, + from: &H160, + to: &H160, + value: U256, ) -> Result<()> { let from_balance = self.balance_of_impl(from); if from_balance < value { @@ -218,6 +217,11 @@ mod erc20 { } } + #[cfg(test)] + fn set_caller(sender: H160) { + ink::env::test::set_caller(sender); + } + #[cfg(test)] mod tests { use super::*; @@ -229,9 +233,9 @@ mod erc20 { fn assert_transfer_event( event: &ink::env::test::EmittedEvent, - expected_from: Option, - expected_to: Option, - expected_value: Balance, + expected_from: Option, + expected_to: Option, + expected_value: U256, ) { let decoded_event = ::decode(&mut &event.data[..]) @@ -243,8 +247,7 @@ mod erc20 { let mut expected_topics = Vec::new(); expected_topics.push( - ink::blake2x256!("Transfer(Option,Option,Balance)") - .into(), + ink::blake2x256!("Transfer(Option,Option,U256)").into(), ); if let Some(from) = expected_from { expected_topics.push(encoded_into_hash(from)); @@ -277,7 +280,8 @@ mod erc20 { #[ink::test] fn new_works() { // Constructor works. - let _erc20 = Erc20::new(100); + set_caller(H160::from([0x01; 20])); + let _erc20 = Erc20::new(100.into()); // Transfer event triggered during initial construction. let emitted_events = ink::env::test::recorded_events().collect::>(); @@ -286,8 +290,8 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), - 100, + Some(H160::from([0x01; 20])), + 100.into(), ); } @@ -295,53 +299,56 @@ mod erc20 { #[ink::test] fn total_supply_works() { // Constructor works. - let erc20 = Erc20::new(100); + set_caller(H160::from([0x01; 20])); + let erc20 = Erc20::new(100.into()); // Transfer event triggered during initial construction. let emitted_events = ink::env::test::recorded_events().collect::>(); assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), - 100, + Some(H160::from([0x01; 20])), + 100.into(), ); // Get the token total supply. - assert_eq!(erc20.total_supply(), 100); + assert_eq!(erc20.total_supply(), U256::from(100)); } /// Get the actual balance of an account. #[ink::test] fn balance_of_works() { + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); + // Constructor works - let erc20 = Erc20::new(100); + let erc20 = Erc20::new(100.into()); // Transfer event triggered during initial construction let emitted_events = ink::env::test::recorded_events().collect::>(); assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), - 100, + Some(H160::from([0x01; 20])), + 100.into(), ); - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); // Alice owns all the tokens on contract instantiation - assert_eq!(erc20.balance_of(accounts.alice), 100); + assert_eq!(erc20.balance_of(accounts.alice), U256::from(100)); // Bob does not owns tokens - assert_eq!(erc20.balance_of(accounts.bob), 0); + assert_eq!(erc20.balance_of(accounts.bob), U256::zero()); } #[ink::test] fn transfer_works() { + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); + // Constructor works. - let mut erc20 = Erc20::new(100); + let mut erc20 = Erc20::new(100.into()); // Transfer event triggered during initial construction. - let accounts = - ink::env::test::default_accounts::(); - - assert_eq!(erc20.balance_of(accounts.bob), 0); + assert_eq!(erc20.balance_of(accounts.bob), U256::zero()); // Alice transfers 10 tokens to Bob. - assert_eq!(erc20.transfer(accounts.bob, 10), Ok(())); + assert_eq!(erc20.transfer(accounts.bob, U256::from(10)), Ok(())); // Bob owns 10 tokens. - assert_eq!(erc20.balance_of(accounts.bob), 10); + assert_eq!(erc20.balance_of(accounts.bob), U256::from(10)); let emitted_events = ink::env::test::recorded_events().collect::>(); assert_eq!(emitted_events.len(), 2); @@ -349,41 +356,43 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), - 100, + Some(H160::from([0x01; 20])), + 100.into(), ); // Check the second transfer event relating to the actual trasfer. assert_transfer_event( &emitted_events[1], - Some(AccountId::from([0x01; 32])), - Some(AccountId::from([0x02; 32])), - 10, + Some(H160::from([0x01; 20])), + Some(H160::from([0x02; 20])), + 10.into(), ); } #[ink::test] fn invalid_transfer_should_fail() { // Constructor works. - let mut erc20 = Erc20::new(100); - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); + + let initial_supply = 100.into(); + let mut erc20 = Erc20::new(initial_supply); - assert_eq!(erc20.balance_of(accounts.bob), 0); + assert_eq!(erc20.balance_of(accounts.bob), U256::zero()); // Set the contract as callee and Bob as caller. - let contract = ink::env::account_id::(); - ink::env::test::set_callee::(contract); - ink::env::test::set_caller::(accounts.bob); + let contract = ink::env::address(); + ink::env::test::set_callee(contract); + set_caller(accounts.bob); - // Bob fails to transfers 10 tokens to Eve. + // Bob fails to transfer 10 tokens to Eve. assert_eq!( - erc20.transfer(accounts.eve, 10), + erc20.transfer(accounts.eve, 10.into()), Err(Error::InsufficientBalance) ); // Alice owns all the tokens. - assert_eq!(erc20.balance_of(accounts.alice), 100); - assert_eq!(erc20.balance_of(accounts.bob), 0); - assert_eq!(erc20.balance_of(accounts.eve), 0); + assert_eq!(erc20.balance_of(accounts.alice), U256::from(100)); + assert_eq!(erc20.balance_of(accounts.bob), U256::zero()); + assert_eq!(erc20.balance_of(accounts.eve), U256::zero()); // Transfer event triggered during initial construction. let emitted_events = ink::env::test::recorded_events().collect::>(); @@ -391,42 +400,42 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), - 100, + Some(H160::from([0x01; 20])), + 100.into(), ); } #[ink::test] fn transfer_from_works() { // Constructor works. - let mut erc20 = Erc20::new(100); - // Transfer event triggered during initial construction. - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); + + let mut erc20 = Erc20::new(100.into()); // Bob fails to transfer tokens owned by Alice. assert_eq!( - erc20.transfer_from(accounts.alice, accounts.eve, 10), + erc20.transfer_from(accounts.alice, accounts.eve, 10.into()), Err(Error::InsufficientAllowance) ); // Alice approves Bob for token transfers on her behalf. - assert_eq!(erc20.approve(accounts.bob, 10), Ok(())); + assert_eq!(erc20.approve(accounts.bob, 10.into()), Ok(())); // The approve event takes place. assert_eq!(ink::env::test::recorded_events().count(), 2); // Set the contract as callee and Bob as caller. - let contract = ink::env::account_id::(); - ink::env::test::set_callee::(contract); - ink::env::test::set_caller::(accounts.bob); + let contract = ink::env::address(); + ink::env::test::set_callee(contract); + ink::env::test::set_caller(accounts.bob); // Bob transfers tokens from Alice to Eve. assert_eq!( - erc20.transfer_from(accounts.alice, accounts.eve, 10), + erc20.transfer_from(accounts.alice, accounts.eve, 10.into()), Ok(()) ); // Eve owns tokens. - assert_eq!(erc20.balance_of(accounts.eve), 10); + assert_eq!(erc20.balance_of(accounts.eve), U256::from(10)); // Check all transfer events that happened during the previous calls: let emitted_events = ink::env::test::recorded_events().collect::>(); @@ -434,24 +443,24 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), - 100, + Some(H160::from([0x01; 20])), + 100.into(), ); // The second event `emitted_events[1]` is an Approve event that we skip // checking. assert_transfer_event( &emitted_events[2], - Some(AccountId::from([0x01; 32])), - Some(AccountId::from([0x05; 32])), - 10, + Some(H160::from([0x01; 20])), + Some(H160::from([0x05; 20])), + 10.into(), ); } #[ink::test] fn allowance_must_not_change_on_failed_transfer() { - let mut erc20 = Erc20::new(100); - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); + let mut erc20 = Erc20::new(100.into()); // Alice approves Bob for token transfers on her behalf. let alice_balance = erc20.balance_of(accounts.alice); @@ -459,14 +468,18 @@ mod erc20 { assert_eq!(erc20.approve(accounts.bob, initial_allowance), Ok(())); // Get contract address. - let callee = ink::env::account_id::(); - ink::env::test::set_callee::(callee); - ink::env::test::set_caller::(accounts.bob); + let callee = ink::env::address(); + ink::env::test::set_callee(callee); + ink::env::test::set_caller(accounts.bob); // Bob tries to transfer tokens from Alice to Eve. let emitted_events_before = ink::env::test::recorded_events().count(); assert_eq!( - erc20.transfer_from(accounts.alice, accounts.eve, alice_balance + 1), + erc20.transfer_from( + accounts.alice, + accounts.eve, + alice_balance + U256::from(1) + ), Err(Error::InsufficientBalance) ); // Allowance must have stayed the same @@ -521,7 +534,7 @@ mod erc20 { #[ink_e2e::test] async fn e2e_transfer(mut client: Client) -> E2EResult<()> { // given - let total_supply = 1_000_000_000; + let total_supply = U256::from(1_000_000_000); let mut constructor = Erc20Ref::new(total_supply); let erc20 = client .instantiate("erc20", &ink_e2e::alice(), &mut constructor) @@ -537,8 +550,8 @@ mod erc20 { .dry_run() .await?; - let bob_account = ink_e2e::account_id(ink_e2e::AccountKeyring::Bob); - let transfer_to_bob = 500_000_000u128; + let bob_account = ink_e2e::address(ink_e2e::Sr25519Keyring::Bob); + let transfer_to_bob = U256::from(500_000_000); let transfer = call_builder.transfer(bob_account, transfer_to_bob); let _transfer_res = client .call(&ink_e2e::alice(), &transfer) @@ -566,7 +579,7 @@ mod erc20 { #[ink_e2e::test] async fn e2e_allowances(mut client: Client) -> E2EResult<()> { // given - let total_supply = 1_000_000_000; + let total_supply = U256::from(1_000_000_000); let mut constructor = Erc20Ref::new(total_supply); let erc20 = client .instantiate("erc20", &ink_e2e::bob(), &mut constructor) @@ -577,10 +590,10 @@ mod erc20 { // when - let bob_account = ink_e2e::account_id(ink_e2e::AccountKeyring::Bob); - let charlie_account = ink_e2e::account_id(ink_e2e::AccountKeyring::Charlie); + let bob_account = ink_e2e::address(ink_e2e::Sr25519Keyring::Bob); + let charlie_account = ink_e2e::address(ink_e2e::Sr25519Keyring::Charlie); - let amount = 500_000_000u128; + let amount = U256::from(500_000_000); // tx let transfer_from = call_builder.transfer_from(bob_account, charlie_account, amount); @@ -595,7 +608,7 @@ mod erc20 { ); // Bob approves Charlie to transfer up to amount on his behalf - let approved_value = 1_000u128; + let approved_value = U256::from(1_000); let approve_call = call_builder.approve(charlie_account, approved_value); client .call(&ink_e2e::bob(), &approve_call) @@ -623,7 +636,7 @@ mod erc20 { // `transfer_from` again, this time exceeding the approved amount let transfer_from = - call_builder.transfer_from(bob_account, charlie_account, 1); + call_builder.transfer_from(bob_account, charlie_account, 1.into()); let transfer_from_result = client .call(&ink_e2e::charlie(), &transfer_from) .submit() diff --git a/integration-tests/public/erc721/lib.rs b/integration-tests/public/erc721/lib.rs index 5b2cbafd944..98ae93f18dd 100644 --- a/integration-tests/public/erc721/lib.rs +++ b/integration-tests/public/erc721/lib.rs @@ -54,7 +54,10 @@ #[ink::contract] mod erc721 { - use ink::storage::Mapping; + use ink::{ + storage::Mapping, + H160, + }; /// A token ID. pub type TokenId = u32; @@ -63,13 +66,13 @@ mod erc721 { #[derive(Default)] pub struct Erc721 { /// Mapping from token to owner. - token_owner: Mapping, + token_owner: Mapping, /// Mapping from token to approvals users. - token_approvals: Mapping, + token_approvals: Mapping, /// Mapping from owner to number of owned token. - owned_tokens_count: Mapping, + owned_tokens_count: Mapping, /// Mapping from owner to operator approvals. - operator_approvals: Mapping<(AccountId, AccountId), ()>, + operator_approvals: Mapping<(H160, H160), ()>, } #[derive(Debug, PartialEq, Eq, Copy, Clone)] @@ -88,9 +91,9 @@ mod erc721 { #[ink(event)] pub struct Transfer { #[ink(topic)] - from: Option, + from: Option, #[ink(topic)] - to: Option, + to: Option, #[ink(topic)] id: TokenId, } @@ -99,9 +102,9 @@ mod erc721 { #[ink(event)] pub struct Approval { #[ink(topic)] - from: AccountId, + from: H160, #[ink(topic)] - to: AccountId, + to: H160, #[ink(topic)] id: TokenId, } @@ -111,9 +114,9 @@ mod erc721 { #[ink(event)] pub struct ApprovalForAll { #[ink(topic)] - owner: AccountId, + owner: H160, #[ink(topic)] - operator: AccountId, + operator: H160, approved: bool, } @@ -128,25 +131,25 @@ mod erc721 { /// /// This represents the amount of unique tokens the owner has. #[ink(message)] - pub fn balance_of(&self, owner: AccountId) -> u32 { + pub fn balance_of(&self, owner: H160) -> u32 { self.balance_of_or_zero(&owner) } /// Returns the owner of the token. #[ink(message)] - pub fn owner_of(&self, id: TokenId) -> Option { + pub fn owner_of(&self, id: TokenId) -> Option { self.token_owner.get(id) } /// Returns the approved account ID for this token if any. #[ink(message)] - pub fn get_approved(&self, id: TokenId) -> Option { + pub fn get_approved(&self, id: TokenId) -> Option { self.token_approvals.get(id) } /// Returns `true` if the operator is approved by the owner. #[ink(message)] - pub fn is_approved_for_all(&self, owner: AccountId, operator: AccountId) -> bool { + pub fn is_approved_for_all(&self, owner: H160, operator: H160) -> bool { self.approved_for_all(owner, operator) } @@ -154,7 +157,7 @@ mod erc721 { #[ink(message)] pub fn set_approval_for_all( &mut self, - to: AccountId, + to: H160, approved: bool, ) -> Result<(), Error> { self.approve_for_all(to, approved)?; @@ -163,18 +166,14 @@ mod erc721 { /// Approves the account to transfer the specified token on behalf of the caller. #[ink(message)] - pub fn approve(&mut self, to: AccountId, id: TokenId) -> Result<(), Error> { + pub fn approve(&mut self, to: H160, id: TokenId) -> Result<(), Error> { self.approve_for(&to, id)?; Ok(()) } /// Transfers the token from the caller to the given destination. #[ink(message)] - pub fn transfer( - &mut self, - destination: AccountId, - id: TokenId, - ) -> Result<(), Error> { + pub fn transfer(&mut self, destination: H160, id: TokenId) -> Result<(), Error> { let caller = self.env().caller(); self.transfer_token_from(&caller, &destination, id)?; Ok(()) @@ -184,8 +183,8 @@ mod erc721 { #[ink(message)] pub fn transfer_from( &mut self, - from: AccountId, - to: AccountId, + from: H160, + to: H160, id: TokenId, ) -> Result<(), Error> { self.transfer_token_from(&from, &to, id)?; @@ -198,7 +197,7 @@ mod erc721 { let caller = self.env().caller(); self.add_token_to(&caller, id)?; self.env().emit_event(Transfer { - from: Some(AccountId::from([0x0; 32])), + from: Some(H160::from([0x0; 20])), to: Some(caller), id, }); @@ -230,18 +229,18 @@ mod erc721 { self.env().emit_event(Transfer { from: Some(caller), - to: Some(AccountId::from([0x0; 32])), + to: Some(H160::from([0x0; 20])), id, }); Ok(()) } - /// Transfers token `id` `from` the sender to the `to` `AccountId`. + /// Transfers token `id` `from` the sender to the `to` `H160`. fn transfer_token_from( &mut self, - from: &AccountId, - to: &AccountId, + from: &H160, + to: &H160, id: TokenId, ) -> Result<(), Error> { let caller = self.env().caller(); @@ -264,11 +263,7 @@ mod erc721 { } /// Removes token `id` from the owner. - fn remove_token_from( - &mut self, - from: &AccountId, - id: TokenId, - ) -> Result<(), Error> { + fn remove_token_from(&mut self, from: &H160, id: TokenId) -> Result<(), Error> { let Self { token_owner, owned_tokens_count, @@ -290,7 +285,7 @@ mod erc721 { } /// Adds the token `id` to the `to` AccountID. - fn add_token_to(&mut self, to: &AccountId, id: TokenId) -> Result<(), Error> { + fn add_token_to(&mut self, to: &H160, id: TokenId) -> Result<(), Error> { let Self { token_owner, owned_tokens_count, @@ -301,7 +296,7 @@ mod erc721 { return Err(Error::TokenExists); } - if *to == AccountId::from([0x0; 32]) { + if *to == H160::from([0x0; 20]) { return Err(Error::NotAllowed); }; @@ -317,11 +312,7 @@ mod erc721 { } /// Approves or disapproves the operator to transfer all tokens of the caller. - fn approve_for_all( - &mut self, - to: AccountId, - approved: bool, - ) -> Result<(), Error> { + fn approve_for_all(&mut self, to: H160, approved: bool) -> Result<(), Error> { let caller = self.env().caller(); if to == caller { return Err(Error::NotAllowed); @@ -341,16 +332,16 @@ mod erc721 { Ok(()) } - /// Approve the passed `AccountId` to transfer the specified token on behalf of + /// Approve the passed `H160` to transfer the specified token on behalf of /// the message's sender. - fn approve_for(&mut self, to: &AccountId, id: TokenId) -> Result<(), Error> { + fn approve_for(&mut self, to: &H160, id: TokenId) -> Result<(), Error> { let caller = self.env().caller(); let owner = self.owner_of(id).ok_or(Error::TokenNotFound)?; if !(owner == caller || self.approved_for_all(owner, caller)) { return Err(Error::NotAllowed); }; - if *to == AccountId::from([0x0; 32]) { + if *to == H160::from([0x0; 20]) { return Err(Error::NotAllowed); }; @@ -375,24 +366,19 @@ mod erc721 { } // Returns the total number of tokens from an account. - fn balance_of_or_zero(&self, of: &AccountId) -> u32 { + fn balance_of_or_zero(&self, of: &H160) -> u32 { self.owned_tokens_count.get(of).unwrap_or(0) } /// Gets an operator on other Account's behalf. - fn approved_for_all(&self, owner: AccountId, operator: AccountId) -> bool { + fn approved_for_all(&self, owner: H160, operator: H160) -> bool { self.operator_approvals.contains((&owner, &operator)) } - /// Returns true if the `AccountId` `from` is the owner of token `id` + /// Returns true if the `H160` `from` is the owner of token `id` /// or it has been approved on behalf of the token `id` owner. - fn approved_or_owner( - &self, - from: AccountId, - id: TokenId, - owner: AccountId, - ) -> bool { - from != AccountId::from([0x0; 32]) + fn approved_or_owner(&self, from: H160, id: TokenId, owner: H160) -> bool { + from != H160::from([0x0; 20]) && (from == owner || self.token_approvals.get(id) == Some(from) || self.approved_for_all(owner, from)) @@ -407,8 +393,8 @@ mod erc721 { #[ink::test] fn mint_works() { - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); // Create a new contract instance. let mut erc721 = Erc721::new(); // Token 1 does not exists. @@ -423,8 +409,8 @@ mod erc721 { #[ink::test] fn mint_existing_should_fail() { - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); // Create a new contract instance. let mut erc721 = Erc721::new(); // Create token Id 1. @@ -442,8 +428,8 @@ mod erc721 { #[ink::test] fn transfer_works() { - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); // Create a new contract instance. let mut erc721 = Erc721::new(); // Create token Id 1 for Alice @@ -464,8 +450,8 @@ mod erc721 { #[ink::test] fn invalid_transfer_should_fail() { - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); // Create a new contract instance. let mut erc721 = Erc721::new(); // Transfer token fails if it does not exists. @@ -486,8 +472,8 @@ mod erc721 { #[ink::test] fn approved_transfer_works() { - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); // Create a new contract instance. let mut erc721 = Erc721::new(); // Create token Id 1. @@ -515,8 +501,8 @@ mod erc721 { #[ink::test] fn approved_for_all_works() { - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); // Create a new contract instance. let mut erc721 = Erc721::new(); // Create token Id 1. @@ -558,8 +544,8 @@ mod erc721 { #[ink::test] fn approve_nonexistent_token_should_fail() { - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); // Create a new contract instance. let mut erc721 = Erc721::new(); // Approve transfer of nonexistent token id 1 @@ -568,8 +554,8 @@ mod erc721 { #[ink::test] fn not_approved_transfer_should_fail() { - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); // Create a new contract instance. let mut erc721 = Erc721::new(); // Create token Id 1. @@ -597,8 +583,8 @@ mod erc721 { #[ink::test] fn burn_works() { - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); // Create a new contract instance. let mut erc721 = Erc721::new(); // Create token Id 1 for Alice @@ -625,8 +611,8 @@ mod erc721 { #[ink::test] fn burn_fails_not_owner() { - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); // Create a new contract instance. let mut erc721 = Erc721::new(); // Create token Id 1 for Alice @@ -638,8 +624,8 @@ mod erc721 { #[ink::test] fn burn_clears_approval() { - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); // Create a new contract instance. let mut erc721 = Erc721::new(); // Create token Id 1 for Alice @@ -663,8 +649,8 @@ mod erc721 { #[ink::test] fn transfer_from_fails_not_owner() { - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); // Create a new contract instance. let mut erc721 = Erc721::new(); // Create token Id 1 for Alice @@ -686,8 +672,8 @@ mod erc721 { #[ink::test] fn transfer_fails_not_owner() { - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); // Create a new contract instance. let mut erc721 = Erc721::new(); // Create token Id 1 for Alice @@ -700,8 +686,8 @@ mod erc721 { assert_eq!(erc721.transfer(accounts.bob, 1), Err(Error::NotOwner)); } - fn set_caller(sender: AccountId) { - ink::env::test::set_caller::(sender); + fn set_caller(sender: H160) { + ink::env::test::set_caller(sender); } } } diff --git a/integration-tests/public/events/Cargo.toml b/integration-tests/public/events/Cargo.toml index 6d8842a534a..47b7c78a1a2 100644 --- a/integration-tests/public/events/Cargo.toml +++ b/integration-tests/public/events/Cargo.toml @@ -29,7 +29,7 @@ std = [ ink-as-dependency = [] e2e-tests = [] -[profile.test] +#[profile.test] # Need this for linkme crate to work for the event metadata unit test. # See https://github.com/dtolnay/linkme/issues/61#issuecomment-1503653702 -lto = "thin" +#lto = "thin" diff --git a/integration-tests/public/events/expand2.rs b/integration-tests/public/events/expand2.rs new file mode 100644 index 00000000000..42f5f0a5192 --- /dev/null +++ b/integration-tests/public/events/expand2.rs @@ -0,0 +1,3006 @@ +#![feature(prelude_import)] +#![no_std] +#![no_main] +#[prelude_import] +use core::prelude::rust_2021::*; +#[macro_use] +extern crate core; +extern crate compiler_builtins as _; +#[codec(crate = ::ink::scale)] +#[ink(anonymous)] +pub struct AnonymousEvent { + #[ink(topic)] + pub topic: [u8; 32], + pub field_1: u32, +} +#[allow(deprecated)] +const _: () = { + #[automatically_derived] + impl ::ink::scale::Decode for AnonymousEvent { + fn decode<__CodecInputEdqy: ::ink::scale::Input>( + __codec_input_edqy: &mut __CodecInputEdqy, + ) -> ::core::result::Result { + ::core::result::Result::Ok(AnonymousEvent { + topic: { + let __codec_res_edqy = <[u8; 32] 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 `AnonymousEvent::topic`"), + ); + } + ::core::result::Result::Ok(__codec_res_edqy) => __codec_res_edqy, + } + }, + field_1: { + 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 `AnonymousEvent::field_1`"), + ); + } + ::core::result::Result::Ok(__codec_res_edqy) => __codec_res_edqy, + } + }, + }) + } + } +}; +#[allow(deprecated)] +const _: () = { + #[automatically_derived] + impl ::ink::scale::Encode for AnonymousEvent { + fn size_hint(&self) -> usize { + 0_usize + .saturating_add(::ink::scale::Encode::size_hint(&self.topic)) + .saturating_add(::ink::scale::Encode::size_hint(&self.field_1)) + } + fn encode_to<__CodecOutputEdqy: ::ink::scale::Output + ?::core::marker::Sized>( + &self, + __codec_dest_edqy: &mut __CodecOutputEdqy, + ) { + ::ink::scale::Encode::encode_to(&self.topic, __codec_dest_edqy); + ::ink::scale::Encode::encode_to(&self.field_1, __codec_dest_edqy); + } + } + #[automatically_derived] + impl ::ink::scale::EncodeLike for AnonymousEvent {} +}; +const _: () = { + impl ::ink::env::Event for AnonymousEvent { + type RemainingTopics = [::ink::env::event::state::HasRemainingTopics; 1usize]; + const SIGNATURE_TOPIC: ::core::option::Option<[::core::primitive::u8; 32]> = ::core::option::Option::None; + fn topics( + &self, + builder: ::ink::env::event::TopicsBuilder< + ::ink::env::event::state::Uninit, + E, + B, + >, + ) -> >::Output + where + E: ::ink::env::Environment, + B: ::ink::env::event::TopicsBuilderBackend, + { + match self { + AnonymousEvent { topic: __binding_0, .. } => { + builder + .build::() + .push_topic({ + #[allow(unused_imports)] + use ::ink::option_info::AsOptionFallback as _; + ::ink::option_info::AsOption(&__binding_0).value() + }) + .finish() + } + } + } + } +}; +pub mod events { + impl ::ink::env::ContractEnv for Events { + type Env = ::ink::env::DefaultEnvironment; + } + 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; + type EventRecord = <::Env as ::ink::env::Environment>::EventRecord; + const _: () = { + struct Check { + salt: (), + field_0: bool, + } + }; + #[cfg(not(target_vendor = "fortanix"))] + pub struct Events { + value: , + >>::Type, + } + const _: () = { + impl< + __ink_generic_salt: ::ink::storage::traits::StorageKey, + > ::ink::storage::traits::StorableHint<__ink_generic_salt> for Events { + type Type = Events; + type PreferredKey = ::ink::storage::traits::AutoKey; + } + }; + const _: () = { + impl ::ink::storage::traits::StorageKey for Events { + const KEY: ::ink::primitives::Key = <() as ::ink::storage::traits::StorageKey>::KEY; + } + }; + const _: () = { + impl ::ink::storage::traits::Storable for Events { + #[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(Events { + value: <, + >>::Type as ::ink::storage::traits::Storable>::decode(__input)?, + }) + } + #[inline(always)] + #[allow(non_camel_case_types)] + fn encode<__ink_O: ::ink::scale::Output + ?::core::marker::Sized>( + &self, + __dest: &mut __ink_O, + ) { + match self { + Events { value: __binding_0 } => { + ::ink::storage::traits::Storable::encode(__binding_0, __dest); + } + } + } + #[inline(always)] + #[allow(non_camel_case_types)] + fn encoded_size(&self) -> ::core::primitive::usize { + match self { + Events { value: __binding_0 } => { + ::core::primitive::usize::MIN + .saturating_add( + ::ink::storage::traits::Storable::encoded_size(__binding_0), + ) + } + } + } + } + }; + const _: () = { + impl ::ink::reflect::ContractName for Events { + const NAME: &'static str = "Events"; + } + }; + const _: () = { + impl<'a> ::ink::codegen::Env for &'a Events { + type EnvAccess = ::ink::EnvAccess< + 'a, + ::Env, + >; + fn env(self) -> Self::EnvAccess { + <::EnvAccess as ::core::default::Default>::default() + } + } + impl<'a> ::ink::codegen::StaticEnv for Events { + 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 _}; + }; + #[codec(crate = ::ink::scale)] + pub struct InlineFlipped { + value: bool, + } + #[allow(deprecated)] + const _: () = { + #[automatically_derived] + impl ::ink::scale::Decode for InlineFlipped { + fn decode<__CodecInputEdqy: ::ink::scale::Input>( + __codec_input_edqy: &mut __CodecInputEdqy, + ) -> ::core::result::Result { + ::core::result::Result::Ok(InlineFlipped { + value: { + 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 `InlineFlipped::value`"), + ); + } + ::core::result::Result::Ok(__codec_res_edqy) => { + __codec_res_edqy + } + } + }, + }) + } + } + }; + #[allow(deprecated)] + const _: () = { + #[automatically_derived] + impl ::ink::scale::Encode for InlineFlipped { + fn size_hint(&self) -> usize { + ::ink::scale::Encode::size_hint(&&self.value) + } + fn encode_to< + __CodecOutputEdqy: ::ink::scale::Output + ?::core::marker::Sized, + >(&self, __codec_dest_edqy: &mut __CodecOutputEdqy) { + ::ink::scale::Encode::encode_to(&&self.value, __codec_dest_edqy) + } + fn encode(&self) -> ::ink::scale::alloc::vec::Vec<::core::primitive::u8> { + ::ink::scale::Encode::encode(&&self.value) + } + fn using_encoded< + __CodecOutputReturn, + __CodecUsingEncodedCallback: ::core::ops::FnOnce( + &[::core::primitive::u8], + ) -> __CodecOutputReturn, + >(&self, f: __CodecUsingEncodedCallback) -> __CodecOutputReturn { + ::ink::scale::Encode::using_encoded(&&self.value, f) + } + } + #[automatically_derived] + impl ::ink::scale::EncodeLike for InlineFlipped {} + }; + const _: () = { + impl ::ink::env::Event for InlineFlipped { + type RemainingTopics = [::ink::env::event::state::HasRemainingTopics; 1usize]; + const SIGNATURE_TOPIC: ::core::option::Option<[::core::primitive::u8; 32]> = ::core::option::Option::Some([ + 0xAB_u8, + 0x76_u8, + 0x8E_u8, + 0xF7_u8, + 0x7E_u8, + 0x8F_u8, + 0xD0_u8, + 0xC0_u8, + 0x74_u8, + 0x0C_u8, + 0x52_u8, + 0x32_u8, + 0x52_u8, + 0xAE_u8, + 0xBD_u8, + 0x65_u8, + 0xD3_u8, + 0x7B_u8, + 0xB2_u8, + 0xB5_u8, + 0xF5_u8, + 0x08_u8, + 0xD2_u8, + 0x30_u8, + 0x6F_u8, + 0x87_u8, + 0x63_u8, + 0x96_u8, + 0xCA_u8, + 0x7E_u8, + 0x44_u8, + 0x47_u8, + ]); + fn topics( + &self, + builder: ::ink::env::event::TopicsBuilder< + ::ink::env::event::state::Uninit, + E, + B, + >, + ) -> >::Output + where + E: ::ink::env::Environment, + B: ::ink::env::event::TopicsBuilderBackend, + { + match self { + InlineFlipped { .. } => { + builder + .build::() + .push_topic(Self::SIGNATURE_TOPIC.as_ref()) + .finish() + } + } + } + } + }; + #[codec(crate = ::ink::scale)] + #[ink( + signature_topic = "1111111111111111111111111111111111111111111111111111111111111111" + )] + pub struct InlineCustomFlipped { + value: bool, + } + #[allow(deprecated)] + const _: () = { + #[automatically_derived] + impl ::ink::scale::Decode for InlineCustomFlipped { + fn decode<__CodecInputEdqy: ::ink::scale::Input>( + __codec_input_edqy: &mut __CodecInputEdqy, + ) -> ::core::result::Result { + ::core::result::Result::Ok(InlineCustomFlipped { + value: { + 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 `InlineCustomFlipped::value`"), + ); + } + ::core::result::Result::Ok(__codec_res_edqy) => { + __codec_res_edqy + } + } + }, + }) + } + } + }; + #[allow(deprecated)] + const _: () = { + #[automatically_derived] + impl ::ink::scale::Encode for InlineCustomFlipped { + fn size_hint(&self) -> usize { + ::ink::scale::Encode::size_hint(&&self.value) + } + fn encode_to< + __CodecOutputEdqy: ::ink::scale::Output + ?::core::marker::Sized, + >(&self, __codec_dest_edqy: &mut __CodecOutputEdqy) { + ::ink::scale::Encode::encode_to(&&self.value, __codec_dest_edqy) + } + fn encode(&self) -> ::ink::scale::alloc::vec::Vec<::core::primitive::u8> { + ::ink::scale::Encode::encode(&&self.value) + } + fn using_encoded< + __CodecOutputReturn, + __CodecUsingEncodedCallback: ::core::ops::FnOnce( + &[::core::primitive::u8], + ) -> __CodecOutputReturn, + >(&self, f: __CodecUsingEncodedCallback) -> __CodecOutputReturn { + ::ink::scale::Encode::using_encoded(&&self.value, f) + } + } + #[automatically_derived] + impl ::ink::scale::EncodeLike for InlineCustomFlipped {} + }; + const _: () = { + impl ::ink::env::Event for InlineCustomFlipped { + type RemainingTopics = [::ink::env::event::state::HasRemainingTopics; 1usize]; + const SIGNATURE_TOPIC: ::core::option::Option<[::core::primitive::u8; 32]> = ::core::option::Option::Some([ + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + 17u8, + ]); + fn topics( + &self, + builder: ::ink::env::event::TopicsBuilder< + ::ink::env::event::state::Uninit, + E, + B, + >, + ) -> >::Output + where + E: ::ink::env::Environment, + B: ::ink::env::event::TopicsBuilderBackend, + { + match self { + InlineCustomFlipped { .. } => { + builder + .build::() + .push_topic(Self::SIGNATURE_TOPIC.as_ref()) + .finish() + } + } + } + } + }; + #[codec(crate = ::ink::scale)] + #[ink(anonymous)] + pub struct InlineAnonymousEvent { + #[ink(topic)] + pub topic: [u8; 32], + pub field_1: u32, + } + #[allow(deprecated)] + const _: () = { + #[automatically_derived] + impl ::ink::scale::Decode for InlineAnonymousEvent { + fn decode<__CodecInputEdqy: ::ink::scale::Input>( + __codec_input_edqy: &mut __CodecInputEdqy, + ) -> ::core::result::Result { + ::core::result::Result::Ok(InlineAnonymousEvent { + topic: { + let __codec_res_edqy = <[u8; 32] 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 `InlineAnonymousEvent::topic`"), + ); + } + ::core::result::Result::Ok(__codec_res_edqy) => { + __codec_res_edqy + } + } + }, + field_1: { + 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 `InlineAnonymousEvent::field_1`"), + ); + } + ::core::result::Result::Ok(__codec_res_edqy) => { + __codec_res_edqy + } + } + }, + }) + } + } + }; + #[allow(deprecated)] + const _: () = { + #[automatically_derived] + impl ::ink::scale::Encode for InlineAnonymousEvent { + fn size_hint(&self) -> usize { + 0_usize + .saturating_add(::ink::scale::Encode::size_hint(&self.topic)) + .saturating_add(::ink::scale::Encode::size_hint(&self.field_1)) + } + fn encode_to< + __CodecOutputEdqy: ::ink::scale::Output + ?::core::marker::Sized, + >(&self, __codec_dest_edqy: &mut __CodecOutputEdqy) { + ::ink::scale::Encode::encode_to(&self.topic, __codec_dest_edqy); + ::ink::scale::Encode::encode_to(&self.field_1, __codec_dest_edqy); + } + } + #[automatically_derived] + impl ::ink::scale::EncodeLike for InlineAnonymousEvent {} + }; + const _: () = { + impl ::ink::env::Event for InlineAnonymousEvent { + type RemainingTopics = [::ink::env::event::state::HasRemainingTopics; 1usize]; + const SIGNATURE_TOPIC: ::core::option::Option<[::core::primitive::u8; 32]> = ::core::option::Option::None; + fn topics( + &self, + builder: ::ink::env::event::TopicsBuilder< + ::ink::env::event::state::Uninit, + E, + B, + >, + ) -> >::Output + where + E: ::ink::env::Environment, + B: ::ink::env::event::TopicsBuilderBackend, + { + match self { + InlineAnonymousEvent { topic: __binding_0, .. } => { + builder + .build::() + .push_topic({ + #[allow(unused_imports)] + use ::ink::option_info::AsOptionFallback as _; + ::ink::option_info::AsOption(&__binding_0).value() + }) + .finish() + } + } + } + } + }; + impl ::ink::reflect::DispatchableConstructorInfo<0x9BAE9D5E_u32> for Events { + type Input = bool; + type Output = Self; + type Storage = Events; + 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 = |__ink_binding_0| { + Events::new(__ink_binding_0) + }; + const PAYABLE: ::core::primitive::bool = false; + 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<0x7F167334_u32> for Events { + type Input = (); + type Output = (); + type Storage = Events; + const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | + storage, + _| + { Events::flip_with_foreign_event(storage) }; + const SELECTOR: [::core::primitive::u8; 4usize] = [ + 0x7F_u8, + 0x16_u8, + 0x73_u8, + 0x34_u8, + ]; + const PAYABLE: ::core::primitive::bool = false; + const MUTATES: ::core::primitive::bool = true; + const LABEL: &'static ::core::primitive::str = "flip_with_foreign_event"; + } + impl ::ink::reflect::DispatchableMessageInfo<0xDDF6121E_u32> for Events { + type Input = (); + type Output = (); + type Storage = Events; + const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | + storage, + _| + { Events::flip_with_inline_event(storage) }; + const SELECTOR: [::core::primitive::u8; 4usize] = [ + 0xDD_u8, + 0xF6_u8, + 0x12_u8, + 0x1E_u8, + ]; + const PAYABLE: ::core::primitive::bool = false; + const MUTATES: ::core::primitive::bool = true; + const LABEL: &'static ::core::primitive::str = "flip_with_inline_event"; + } + impl ::ink::reflect::DispatchableMessageInfo<0xB7771685_u32> for Events { + type Input = (); + type Output = (); + type Storage = Events; + const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | + storage, + _| + { Events::flip_with_inline_custom_event(storage) }; + const SELECTOR: [::core::primitive::u8; 4usize] = [ + 0xB7_u8, + 0x77_u8, + 0x16_u8, + 0x85_u8, + ]; + const PAYABLE: ::core::primitive::bool = false; + const MUTATES: ::core::primitive::bool = true; + const LABEL: &'static ::core::primitive::str = "flip_with_inline_custom_event"; + } + impl ::ink::reflect::DispatchableMessageInfo<0xEB243827_u32> for Events { + type Input = Option<[u8; 32]>; + type Output = (); + type Storage = Events; + const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | + storage, + __ink_binding_0| + { Events::emit_32_byte_topic_event(storage, __ink_binding_0) }; + const SELECTOR: [::core::primitive::u8; 4usize] = [ + 0xEB_u8, + 0x24_u8, + 0x38_u8, + 0x27_u8, + ]; + const PAYABLE: ::core::primitive::bool = false; + const MUTATES: ::core::primitive::bool = false; + const LABEL: &'static ::core::primitive::str = "emit_32_byte_topic_event"; + } + impl ::ink::reflect::DispatchableMessageInfo<0x3C111980_u32> for Events { + type Input = Option<[u8; 32]>; + type Output = (); + type Storage = Events; + const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | + storage, + __ink_binding_0| + { Events::emit_event_from_a_different_crate(storage, __ink_binding_0) }; + const SELECTOR: [::core::primitive::u8; 4usize] = [ + 0x3C_u8, + 0x11_u8, + 0x19_u8, + 0x80_u8, + ]; + const PAYABLE: ::core::primitive::bool = false; + const MUTATES: ::core::primitive::bool = false; + const LABEL: &'static ::core::primitive::str = "emit_event_from_a_different_crate"; + } + impl ::ink::reflect::DispatchableMessageInfo<0x889DE210_u32> for Events { + type Input = [u8; 32]; + type Output = (); + type Storage = Events; + const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | + storage, + __ink_binding_0| + { Events::emit_anonymous_events(storage, __ink_binding_0) }; + const SELECTOR: [::core::primitive::u8; 4usize] = [ + 0x88_u8, + 0x9D_u8, + 0xE2_u8, + 0x10_u8, + ]; + const PAYABLE: ::core::primitive::bool = false; + const MUTATES: ::core::primitive::bool = false; + const LABEL: &'static ::core::primitive::str = "emit_anonymous_events"; + } + impl ::ink::reflect::DispatchableMessageInfo< + { + ::core::primitive::u32::from_be_bytes({ + <<::ink::reflect::TraitDefinitionRegistry< + ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR + }) + }, + > for Events { + type Input = (); + type Output = (); + type Storage = Events; + const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | + storage, + _| + { ::flip(storage) }; + const SELECTOR: [::core::primitive::u8; 4usize] = { + <<::ink::reflect::TraitDefinitionRegistry< + ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR + }; + const PAYABLE: ::core::primitive::bool = { + <<::ink::reflect::TraitDefinitionRegistry< + ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::PAYABLE + }; + const MUTATES: ::core::primitive::bool = true; + const LABEL: &'static ::core::primitive::str = "FlipperTrait::flip"; + } + 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< + Events, + >>::as_result(&output_value); + if let ::core::result::Result::Ok(contract) + = output_result.as_ref() + { + ::ink::env::set_contract_storage::< + ::ink::primitives::Key, + Events, + >( + &::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 Events { + type Type = __ink_ConstructorDecoder; + } + }; + const _: () = { + #[allow(non_camel_case_types)] + pub enum __ink_MessageDecoder { + Message0( + >::Input, + ), + Message1( + >::Input, + ), + Message2( + >::Input, + ), + Message3( + >::Input, + ), + Message4( + >::Input, + ), + Message5( + >::Input, + ), + Message6( + ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::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; + const MESSAGE_5: [::core::primitive::u8; 4usize] = >::SELECTOR; + const MESSAGE_6: [::core::primitive::u8; 4usize] = ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::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 + })?, + ), + ) + } + MESSAGE_5 => { + ::core::result::Result::Ok( + Self::Message5( + <>::Input as ::ink::scale::Decode>::decode(input) + .map_err(|_| { + ::ink::reflect::DispatchError::InvalidParameters + })?, + ), + ) + } + MESSAGE_6 => { + ::core::result::Result::Ok( + Self::Message6( + <::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::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, + Events, + >(&::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 + } + || { + let message_5 = false; + let message_5 = >::PAYABLE; + message_5 + } + || { + let message_6 = false; + let message_6 = ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::PAYABLE; + message_6 + } + } + && !>::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 + } + || { + let message_5 = false; + let message_5 = >::PAYABLE; + message_5 + } + || { + let message_6 = false; + let message_6 = ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::PAYABLE; + message_6 + } + } + && !>::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 + } + || { + let message_5 = false; + let message_5 = >::PAYABLE; + message_5 + } + || { + let message_6 = false; + let message_6 = ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::PAYABLE; + message_6 + } + } + && !>::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 + } + || { + let message_5 = false; + let message_5 = >::PAYABLE; + message_5 + } + || { + let message_6 = false; + let message_6 = ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::PAYABLE; + message_6 + } + } + && !>::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 + } + || { + let message_5 = false; + let message_5 = >::PAYABLE; + message_5 + } + || { + let message_6 = false; + let message_6 = ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::PAYABLE; + message_6 + } + } + && !>::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::Message5(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 + } + || { + let message_5 = false; + let message_5 = >::PAYABLE; + message_5 + } + || { + let message_6 = false; + let message_6 = ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::PAYABLE; + message_6 + } + } + && !>::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::Message6(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 + } + || { + let message_5 = false; + let message_5 = >::PAYABLE; + message_5 + } + || { + let message_6 = false; + let message_6 = ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::PAYABLE; + message_6 + } + } + && !::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::PAYABLE + { + ::ink::codegen::deny_payment::< + ::Env, + >()?; + } + let result: ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::Output = ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::CALLABLE(&mut contract, input); + let is_reverted = { + #[allow(unused_imports)] + use ::ink::result_info::IsResultTypeFallback as _; + ::ink::result_info::IsResultType::< + ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::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, + ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::MUTATES, + ); + } + ::ink::env::return_value::< + ::ink::MessageResult< + ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::Output, + >, + >(flag, &::ink::MessageResult::Ok(result)) + } + }; + } + } + impl ::ink::reflect::ContractMessageDecoder for Events { + type Type = __ink_MessageDecoder; + } + }; + #[cfg(not(any(test, feature = "std", feature = "ink-as-dependency")))] + mod __do_not_access__ { + use super::*; + #[allow(dead_code)] + #[allow(clippy::nonminimal_bool)] + #[cfg(target_arch = "riscv64")] + fn internal_deploy() { + if !{ + false + || { + let constructor_0 = false; + let constructor_0 = >::PAYABLE; + constructor_0 + } + } { + ::ink::codegen::deny_payment::< + ::Env, + >() + .unwrap_or_else(|error| { + #[cold] + #[track_caller] + #[inline(never)] + #[rustc_const_panic_str] + #[rustc_do_not_const_check] + const fn panic_cold_display( + arg: &T, + ) -> ! { + ::core::panicking::panic_display(arg) + } + panic_cold_display(&error); + }) + } + let dispatchable = match ::ink::env::decode_input::< + ::Type, + >() { + ::core::result::Result::Ok(decoded_dispatchable) => decoded_dispatchable, + ::core::result::Result::Err(_decoding_error) => { + let error = ::ink::ConstructorResult::Err( + ::ink::LangError::CouldNotReadInput, + ); + ::ink::env::return_value::< + ::ink::ConstructorResult<()>, + >(::ink::env::ReturnFlags::REVERT, &error); + } + }; + <::Type as ::ink::reflect::ExecuteDispatchable>::execute_dispatchable( + dispatchable, + ) + .unwrap_or_else(|error| { + { + ::core::panicking::panic_fmt( + format_args!( + "dispatching ink! constructor failed: {0}", error + ), + ); + } + }) + } + #[allow(dead_code)] + #[allow(clippy::nonminimal_bool)] + #[cfg(target_arch = "riscv64")] + fn internal_call() { + 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 + } + || { + let message_5 = false; + let message_5 = >::PAYABLE; + message_5 + } + || { + let message_6 = false; + let message_6 = ::Env, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitMessageInfo< + 0x633AA551_u32, + >>::SELECTOR, + ) + }, + >>::PAYABLE; + message_6 + } + } { + ::ink::codegen::deny_payment::< + ::Env, + >() + .unwrap_or_else(|error| { + #[cold] + #[track_caller] + #[inline(never)] + #[rustc_const_panic_str] + #[rustc_do_not_const_check] + const fn panic_cold_display( + arg: &T, + ) -> ! { + ::core::panicking::panic_display(arg) + } + panic_cold_display(&error); + }) + } + let dispatchable = match ::ink::env::decode_input::< + ::Type, + >() { + ::core::result::Result::Ok(decoded_dispatchable) => decoded_dispatchable, + ::core::result::Result::Err(_decoding_error) => { + let error = ::ink::MessageResult::Err( + ::ink::LangError::CouldNotReadInput, + ); + ::ink::env::return_value::< + ::ink::MessageResult<()>, + >(::ink::env::ReturnFlags::REVERT, &error); + } + }; + <::Type as ::ink::reflect::ExecuteDispatchable>::execute_dispatchable( + dispatchable, + ) + .unwrap_or_else(|error| { + { + ::core::panicking::panic_fmt( + format_args!("dispatching ink! message failed: {0}", error), + ); + } + }) + } + #[cfg(target_arch = "riscv64")] + pub fn call() { + internal_call() + } + #[cfg(target_arch = "riscv64")] + pub fn deploy() { + internal_deploy() + } + } + const _: () = { + use ::ink::codegen::{Env as _, StaticEnv as _}; + const _: ::ink::codegen::utils::IsSameType = ::ink::codegen::utils::IsSameType::< + Events, + >::new(); + impl Events { + /// Creates a new events smart contract initialized with the given value. + #[cfg(not(target_os = "dragonfly"))] + pub fn new(init_value: bool) -> Self { + Self { value: init_value } + } + /// Flips the current value of the boolean. + pub fn flip_with_foreign_event(&mut self) { + self.value = !self.value; + self.env() + .emit_event(event_def::ForeignFlipped { + value: self.value, + }) + } + /// Flips the current value of the boolean. + pub fn flip_with_inline_event(&mut self) { + self.value = !self.value; + self.env().emit_event(InlineFlipped { value: self.value }) + } + /// Flips the current value of the boolean. + pub fn flip_with_inline_custom_event(&mut self) { + self.value = !self.value; + self.env() + .emit_event(InlineCustomFlipped { + value: self.value, + }) + } + /// Emit an event with a 32 byte topic. + pub fn emit_32_byte_topic_event(&self, maybe_hash: Option<[u8; 32]>) { + self.env() + .emit_event(event_def::ThirtyTwoByteTopics { + hash: [0x42; 32], + maybe_hash, + }) + } + /// Emit an event from a different crate. + pub fn emit_event_from_a_different_crate( + &self, + maybe_hash: Option<[u8; 32]>, + ) { + self.env() + .emit_event(event_def2::EventDefAnotherCrate { + hash: [0x42; 32], + maybe_hash, + }) + } + /// Emit a inline and standalone anonymous events + pub fn emit_anonymous_events(&self, topic: [u8; 32]) { + self.env() + .emit_event(InlineAnonymousEvent { + topic, + field_1: 42, + }); + self.env() + .emit_event(super::AnonymousEvent { + topic, + field_1: 42, + }); + } + } + const _: ::ink::codegen::utils::IsSameType = ::ink::codegen::utils::IsSameType::< + Events, + >::new(); + /// Implementing the trait from the `event_def_unused` crate includes all defined + /// events there. + impl event_def_unused::FlipperTrait for Events { + type __ink_TraitInfo = <::ink::reflect::TraitDefinitionRegistry< + Environment, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo; + type flipOutput = (); + fn flip(&mut self) -> Self::flipOutput { + self.value = !self.value; + } + } + const _: () = { + ::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::DispatchInput<[u8; 32]>, + >(); + }; + }; + const _: () = { + #[codec(crate = ::ink::scale)] + /// 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 { + addr: ::ink::H160, + } + #[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 { + addr: { + let __codec_res_edqy = <::ink::H160 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 `CallBuilder::addr`"), + ); + } + ::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::<::ink::H160>(), + &::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::<::ink::H160>() > 0 { 1 } else { 0 } + <= 1) + { + ::core::panicking::panic( + "assertion failed: if ::core::mem::size_of::<::ink::H160>() > 0 { 1 } else { 0 } <= 1", + ) + } + { + let dst_: &mut ::core::mem::MaybeUninit = dst_; + let dst_: &mut ::core::mem::MaybeUninit<::ink::H160> = unsafe { + &mut *dst_ + .as_mut_ptr() + .cast::<::core::mem::MaybeUninit<::ink::H160>>() + }; + <::ink::H160 as ::ink::scale::Decode>::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.addr) + } + fn encode_to< + __CodecOutputEdqy: ::ink::scale::Output + ?::core::marker::Sized, + >(&self, __codec_dest_edqy: &mut __CodecOutputEdqy) { + ::ink::scale::Encode::encode_to(&&self.addr, __codec_dest_edqy) + } + fn encode( + &self, + ) -> ::ink::scale::alloc::vec::Vec<::core::primitive::u8> { + ::ink::scale::Encode::encode(&&self.addr) + } + fn using_encoded< + __CodecOutputReturn, + __CodecUsingEncodedCallback: ::core::ops::FnOnce( + &[::core::primitive::u8], + ) -> __CodecOutputReturn, + >(&self, f: __CodecUsingEncodedCallback) -> __CodecOutputReturn { + ::ink::scale::Encode::using_encoded(&&self.addr, 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", + "addr", + &&self.addr, + ) + } + } + #[automatically_derived] + impl ::core::hash::Hash for CallBuilder { + #[inline] + fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () { + ::core::hash::Hash::hash(&self.addr, 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.addr == other.addr + } + } + #[automatically_derived] + impl ::core::cmp::Eq for CallBuilder { + #[inline] + #[doc(hidden)] + #[coverage(off)] + fn assert_receiver_is_total_eq(&self) -> () { + let _: ::core::cmp::AssertParamIsEq<::ink::H160>; + } + } + #[automatically_derived] + impl ::core::clone::Clone for CallBuilder { + #[inline] + fn clone(&self) -> CallBuilder { + CallBuilder { + addr: ::core::clone::Clone::clone(&self.addr), + } + } + } + const _: () = { + impl ::ink::codegen::ContractCallBuilder for Events { + type Type = CallBuilder; + } + impl ::ink::env::ContractEnv for CallBuilder { + type Env = ::Env; + } + }; + impl ::ink::env::call::FromAddr for CallBuilder { + #[inline] + fn from_addr(addr: ::ink::H160) -> Self { + Self { addr } + } + } + impl ::ink::ToAddr for CallBuilder { + #[inline] + fn to_addr(&self) -> ::ink::H160 { + <::ink::H160 as ::core::clone::Clone>::clone(&self.addr) + } + } + impl ::core::convert::AsRef<::ink::H160> for CallBuilder { + fn as_ref(&self) -> &::ink::H160 { + &self.addr + } + } + impl ::core::convert::AsMut<::ink::H160> for CallBuilder { + fn as_mut(&mut self) -> &mut ::ink::H160 { + &mut self.addr + } + } + #[doc(hidden)] + impl ::ink::codegen::TraitCallForwarderFor< + { + <<::ink::reflect::TraitDefinitionRegistry< + Environment, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitInfo>::ID + }, + > for CallBuilder { + type Forwarder = <::__ink_TraitInfo as ::ink::codegen::TraitCallForwarder>::Forwarder; + #[inline] + fn forward(&self) -> &Self::Forwarder { + unsafe { &*(&self.addr as *const ::ink::H160 as *const Self::Forwarder) } + } + #[inline] + fn forward_mut(&mut self) -> &mut Self::Forwarder { + unsafe { + &mut *(&mut self.addr as *mut ::ink::H160 as *mut Self::Forwarder) + } + } + #[inline] + fn build( + &self, + ) -> &::Builder { + <_ as ::ink::codegen::TraitCallBuilder>::call( + as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitInfo>::ID + }, + >>::forward(self), + ) + } + #[inline] + fn build_mut( + &mut self, + ) -> &mut ::Builder { + <_ as ::ink::codegen::TraitCallBuilder>::call_mut( + as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitInfo>::ID + }, + >>::forward_mut(self), + ) + } + } + impl event_def_unused::FlipperTrait for CallBuilder { + type __ink_TraitInfo = <::ink::reflect::TraitDefinitionRegistry< + Environment, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo; + type flipOutput = << as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitInfo>::ID + }, + >>::Forwarder as ::ink::codegen::TraitCallBuilder>::Builder as event_def_unused::FlipperTrait>::flipOutput; + #[inline] + fn flip(&mut self) -> Self::flipOutput { + <_ as event_def_unused::FlipperTrait>::flip( + as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitInfo>::ID + }, + >>::build_mut(self), + ) + } + } + impl CallBuilder { + /// Flips the current value of the boolean. + #[allow(clippy::type_complexity)] + #[inline] + pub fn flip_with_foreign_event( + &mut self, + ) -> ::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::EmptyArgumentList, + >, + >, + ::ink::env::call::utils::Set<::ink::env::call::utils::ReturnType<()>>, + > { + ::ink::env::call::build_call::() + .call(::ink::ToAddr::to_addr(self)) + .exec_input( + ::ink::env::call::ExecutionInput::new( + ::ink::env::call::Selector::new([ + 0x7F_u8, + 0x16_u8, + 0x73_u8, + 0x34_u8, + ]), + ), + ) + .returns::<()>() + } + /// Flips the current value of the boolean. + #[allow(clippy::type_complexity)] + #[inline] + pub fn flip_with_inline_event( + &mut self, + ) -> ::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::EmptyArgumentList, + >, + >, + ::ink::env::call::utils::Set<::ink::env::call::utils::ReturnType<()>>, + > { + ::ink::env::call::build_call::() + .call(::ink::ToAddr::to_addr(self)) + .exec_input( + ::ink::env::call::ExecutionInput::new( + ::ink::env::call::Selector::new([ + 0xDD_u8, + 0xF6_u8, + 0x12_u8, + 0x1E_u8, + ]), + ), + ) + .returns::<()>() + } + /// Flips the current value of the boolean. + #[allow(clippy::type_complexity)] + #[inline] + pub fn flip_with_inline_custom_event( + &mut self, + ) -> ::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::EmptyArgumentList, + >, + >, + ::ink::env::call::utils::Set<::ink::env::call::utils::ReturnType<()>>, + > { + ::ink::env::call::build_call::() + .call(::ink::ToAddr::to_addr(self)) + .exec_input( + ::ink::env::call::ExecutionInput::new( + ::ink::env::call::Selector::new([ + 0xB7_u8, + 0x77_u8, + 0x16_u8, + 0x85_u8, + ]), + ), + ) + .returns::<()>() + } + /// Emit an event with a 32 byte topic. + #[allow(clippy::type_complexity)] + #[inline] + pub fn emit_32_byte_topic_event( + &self, + __ink_binding_0: Option<[u8; 32]>, + ) -> ::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::ToAddr::to_addr(self)) + .exec_input( + ::ink::env::call::ExecutionInput::new( + ::ink::env::call::Selector::new([ + 0xEB_u8, + 0x24_u8, + 0x38_u8, + 0x27_u8, + ]), + ) + .push_arg(__ink_binding_0), + ) + .returns::<()>() + } + /// Emit an event from a different crate. + #[allow(clippy::type_complexity)] + #[inline] + pub fn emit_event_from_a_different_crate( + &self, + __ink_binding_0: Option<[u8; 32]>, + ) -> ::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::ToAddr::to_addr(self)) + .exec_input( + ::ink::env::call::ExecutionInput::new( + ::ink::env::call::Selector::new([ + 0x3C_u8, + 0x11_u8, + 0x19_u8, + 0x80_u8, + ]), + ) + .push_arg(__ink_binding_0), + ) + .returns::<()>() + } + /// Emit a inline and standalone anonymous events + #[allow(clippy::type_complexity)] + #[inline] + pub fn emit_anonymous_events( + &self, + __ink_binding_0: [u8; 32], + ) -> ::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<[u8; 32]>, + ::ink::env::call::utils::EmptyArgumentList, + >, + >, + >, + ::ink::env::call::utils::Set<::ink::env::call::utils::ReturnType<()>>, + > { + ::ink::env::call::build_call::() + .call(::ink::ToAddr::to_addr(self)) + .exec_input( + ::ink::env::call::ExecutionInput::new( + ::ink::env::call::Selector::new([ + 0x88_u8, + 0x9D_u8, + 0xE2_u8, + 0x10_u8, + ]), + ) + .push_arg(__ink_binding_0), + ) + .returns::<()>() + } + } + }; + #[codec(crate = ::ink::scale)] + pub struct EventsRef { + inner: ::Type, + } + #[allow(deprecated)] + const _: () = { + #[automatically_derived] + impl ::ink::scale::Decode for EventsRef { + fn decode<__CodecInputEdqy: ::ink::scale::Input>( + __codec_input_edqy: &mut __CodecInputEdqy, + ) -> ::core::result::Result { + ::core::result::Result::Ok(EventsRef { + 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 `EventsRef::inner`"), + ); + } + ::core::result::Result::Ok(__codec_res_edqy) => { + __codec_res_edqy + } + } + }, + }) + } + } + }; + #[allow(deprecated)] + const _: () = { + #[automatically_derived] + impl ::ink::scale::Encode for EventsRef { + 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 EventsRef {} + }; + #[automatically_derived] + impl ::core::fmt::Debug for EventsRef { + #[inline] + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + ::core::fmt::Formatter::debug_struct_field1_finish( + f, + "EventsRef", + "inner", + &&self.inner, + ) + } + } + #[automatically_derived] + impl ::core::hash::Hash for EventsRef { + #[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 EventsRef {} + #[automatically_derived] + impl ::core::cmp::PartialEq for EventsRef { + #[inline] + fn eq(&self, other: &EventsRef) -> bool { + self.inner == other.inner + } + } + #[automatically_derived] + impl ::core::cmp::Eq for EventsRef { + #[inline] + #[doc(hidden)] + #[coverage(off)] + fn assert_receiver_is_total_eq(&self) -> () { + let _: ::core::cmp::AssertParamIsEq< + ::Type, + >; + } + } + #[automatically_derived] + impl ::core::clone::Clone for EventsRef { + #[inline] + fn clone(&self) -> EventsRef { + EventsRef { + inner: ::core::clone::Clone::clone(&self.inner), + } + } + } + const _: () = { + impl ::ink::env::ContractReference for Events { + type Type = EventsRef; + } + impl ::ink::env::call::ConstructorReturnType for Events { + type Output = EventsRef; + type Error = (); + fn ok(value: EventsRef) -> 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: EventsRef) -> 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 EventsRef { + type Env = ::Env; + } + }; + /// Implementing the trait from the `event_def_unused` crate includes all defined + /// events there. + impl event_def_unused::FlipperTrait for EventsRef { + type __ink_TraitInfo = <::ink::reflect::TraitDefinitionRegistry< + Environment, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo; + type flipOutput = <::Forwarder as event_def_unused::FlipperTrait>::flipOutput; + #[inline] + fn flip(&mut self) -> Self::flipOutput { + <_ as event_def_unused::FlipperTrait>::flip( + <_ as ::ink::codegen::TraitCallForwarderFor< + { + <<::ink::reflect::TraitDefinitionRegistry< + Environment, + > as event_def_unused::FlipperTrait>::__ink_TraitInfo as ::ink::reflect::TraitInfo>::ID + }, + >>::forward_mut( + ::call_mut(self), + ), + ) + } + } + impl EventsRef { + /// Creates a new events smart contract initialized with the given value. + #[inline] + #[allow(clippy::type_complexity)] + pub fn new( + __ink_binding_0: bool, + ) -> ::ink::env::call::CreateBuilder< + Environment, + Self, + ::ink::env::call::utils::Set<::ink::env::call::LimitParamsV2>, + ::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_create::() + .exec_input( + ::ink::env::call::ExecutionInput::new( + ::ink::env::call::Selector::new([ + 0x9B_u8, + 0xAE_u8, + 0x9D_u8, + 0x5E_u8, + ]), + ) + .push_arg(__ink_binding_0), + ) + .returns::() + } + /// Flips the current value of the boolean. + #[inline] + pub fn flip_with_foreign_event(&mut self) { + self.try_flip_with_foreign_event() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", "Events", + "flip_with_foreign_event", error + ), + ); + }) + } + /// Flips the current value of the boolean. + #[inline] + pub fn try_flip_with_foreign_event(&mut self) -> ::ink::MessageResult<()> { + ::call_mut(self) + .flip_with_foreign_event() + .try_invoke() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", "Events", + "flip_with_foreign_event", error + ), + ); + }) + } + /// Flips the current value of the boolean. + #[inline] + pub fn flip_with_inline_event(&mut self) { + self.try_flip_with_inline_event() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", "Events", + "flip_with_inline_event", error + ), + ); + }) + } + /// Flips the current value of the boolean. + #[inline] + pub fn try_flip_with_inline_event(&mut self) -> ::ink::MessageResult<()> { + ::call_mut(self) + .flip_with_inline_event() + .try_invoke() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", "Events", + "flip_with_inline_event", error + ), + ); + }) + } + /// Flips the current value of the boolean. + #[inline] + pub fn flip_with_inline_custom_event(&mut self) { + self.try_flip_with_inline_custom_event() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", "Events", + "flip_with_inline_custom_event", error + ), + ); + }) + } + /// Flips the current value of the boolean. + #[inline] + pub fn try_flip_with_inline_custom_event(&mut self) -> ::ink::MessageResult<()> { + ::call_mut(self) + .flip_with_inline_custom_event() + .try_invoke() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", "Events", + "flip_with_inline_custom_event", error + ), + ); + }) + } + /// Emit an event with a 32 byte topic. + #[inline] + pub fn emit_32_byte_topic_event(&self, maybe_hash: Option<[u8; 32]>) { + self.try_emit_32_byte_topic_event(maybe_hash) + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", "Events", + "emit_32_byte_topic_event", error + ), + ); + }) + } + /// Emit an event with a 32 byte topic. + #[inline] + pub fn try_emit_32_byte_topic_event( + &self, + maybe_hash: Option<[u8; 32]>, + ) -> ::ink::MessageResult<()> { + ::call(self) + .emit_32_byte_topic_event(maybe_hash) + .try_invoke() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", "Events", + "emit_32_byte_topic_event", error + ), + ); + }) + } + /// Emit an event from a different crate. + #[inline] + pub fn emit_event_from_a_different_crate(&self, maybe_hash: Option<[u8; 32]>) { + self.try_emit_event_from_a_different_crate(maybe_hash) + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", "Events", + "emit_event_from_a_different_crate", error + ), + ); + }) + } + /// Emit an event from a different crate. + #[inline] + pub fn try_emit_event_from_a_different_crate( + &self, + maybe_hash: Option<[u8; 32]>, + ) -> ::ink::MessageResult<()> { + ::call(self) + .emit_event_from_a_different_crate(maybe_hash) + .try_invoke() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", "Events", + "emit_event_from_a_different_crate", error + ), + ); + }) + } + /// Emit a inline and standalone anonymous events + #[inline] + pub fn emit_anonymous_events(&self, topic: [u8; 32]) { + self.try_emit_anonymous_events(topic) + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", "Events", + "emit_anonymous_events", error + ), + ); + }) + } + /// Emit a inline and standalone anonymous events + #[inline] + pub fn try_emit_anonymous_events( + &self, + topic: [u8; 32], + ) -> ::ink::MessageResult<()> { + ::call(self) + .emit_anonymous_events(topic) + .try_invoke() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", "Events", + "emit_anonymous_events", error + ), + ); + }) + } + } + const _: () = { + impl ::ink::codegen::TraitCallBuilder for EventsRef { + 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::FromAddr for EventsRef { + #[inline] + fn from_addr(addr: ::ink::H160) -> Self { + Self { + inner: <::Type as ::ink::env::call::FromAddr>::from_addr( + addr, + ), + } + } + } + impl ::ink::ToAddr for EventsRef { + #[inline] + fn to_addr(&self) -> ::ink::H160 { + <::Type as ::ink::ToAddr>::to_addr( + &self.inner, + ) + } + } + impl ::core::convert::AsRef<::ink::H160> for EventsRef { + fn as_ref(&self) -> &::ink::H160 { + <_ as ::core::convert::AsRef<::ink::H160>>::as_ref(&self.inner) + } + } + impl ::core::convert::AsMut<::ink::H160> for EventsRef { + fn as_mut(&mut self) -> &mut ::ink::H160 { + <_ as ::core::convert::AsMut<::ink::H160>>::as_mut(&mut self.inner) + } + } +} diff --git a/integration-tests/public/events/lib.rs b/integration-tests/public/events/lib.rs index 211b55b33ae..a8ab658a160 100644 --- a/integration-tests/public/events/lib.rs +++ b/integration-tests/public/events/lib.rs @@ -238,10 +238,8 @@ pub mod events { #[cfg(all(test, feature = "e2e-tests"))] mod e2e_tests { use super::*; - use ink_e2e::{ - ContractsBackend, - H256, - }; + use ink::H256; + use ink_e2e::ContractsBackend; type E2EResult = std::result::Result>; @@ -404,6 +402,7 @@ pub mod events { // then assert_eq!(1, contract_events.len()); + // todo the emitted event is not actually checked here let signature_topic = ::SIGNATURE_TOPIC; diff --git a/integration-tests/public/flipper/Cargo.toml b/integration-tests/public/flipper/Cargo.toml index 3211be6eb7f..38548649c23 100644 --- a/integration-tests/public/flipper/Cargo.toml +++ b/integration-tests/public/flipper/Cargo.toml @@ -7,6 +7,7 @@ publish = false [dependencies] ink = { path = "../../../crates/ink", default-features = false } +#foo = { path = "../../../foo", default-features = false } [dev-dependencies] ink_e2e = { path = "../../../crates/e2e" } @@ -22,4 +23,3 @@ std = [ ] ink-as-dependency = [] e2e-tests = [] -revive = ["ink/revive", "ink_e2e/revive"] diff --git a/integration-tests/public/flipper/lib.rs b/integration-tests/public/flipper/lib.rs index 3730b8e2261..178e27aa888 100644 --- a/integration-tests/public/flipper/lib.rs +++ b/integration-tests/public/flipper/lib.rs @@ -72,7 +72,7 @@ pub mod flipper { let get = call_builder.get(); let get_res = client.call(&ink_e2e::bob(), &get).dry_run().await?; - assert!(matches!(get_res.return_value(), false)); + assert!(!get_res.return_value()); // when let flip = call_builder.flip(); @@ -85,7 +85,7 @@ pub mod flipper { // then let get = call_builder.get(); let get_res = client.call(&ink_e2e::bob(), &get).dry_run().await?; - assert!(matches!(get_res.return_value(), true)); + assert!(get_res.return_value()); Ok(()) } @@ -106,7 +106,7 @@ pub mod flipper { // then let get = call_builder.get(); let get_res = client.call(&ink_e2e::bob(), &get).dry_run().await?; - assert!(matches!(get_res.return_value(), false)); + assert!(!get_res.return_value()); Ok(()) } @@ -144,11 +144,12 @@ pub mod flipper { mut client: Client, ) -> E2EResult<()> { // given + use ink::H160; let addr = std::env::var("CONTRACT_ADDR_HEX") .unwrap() .replace("0x", ""); - let acc_id = hex::decode(addr).unwrap(); - let acc_id = AccountId::try_from(&acc_id[..]).unwrap(); + let addr_bytes: Vec = hex::decode(addr).unwrap(); + let addr = H160::from_slice(&addr_bytes[..]); use std::str::FromStr; let suri = ink_e2e::subxt_signer::SecretUri::from_str("//Alice").unwrap(); @@ -156,12 +157,12 @@ pub mod flipper { // when // Invoke `Flipper::get()` from `caller`'s account - let call_builder = ink_e2e::create_call_builder::(acc_id); + let call_builder = ink_e2e::create_call_builder::(addr); let get = call_builder.get(); let get_res = client.call(&caller, &get).dry_run().await?; // then - assert_eq!(get_res.return_value(), true); + assert!(get_res.return_value()); Ok(()) } diff --git a/integration-tests/public/lazyvec/lib.rs b/integration-tests/public/lazyvec/lib.rs index 8c520680c2f..d1c503a0d12 100755 --- a/integration-tests/public/lazyvec/lib.rs +++ b/integration-tests/public/lazyvec/lib.rs @@ -39,7 +39,7 @@ mod lazyvec { /// Checks whether given account is allowed to vote and didn't already /// participate. - fn is_eligible(&self, _voter: AccountId) -> bool { + fn is_eligible(&self, _voter: ink::H160) -> bool { // ToDo: In production, the contract would actually verify eligible voters. // For example, a merkle proof could be an efficient way to do this. true @@ -110,7 +110,7 @@ mod lazyvec { let mut call_builder = contract.call_builder::(); // when - let create = call_builder.create_proposal(vec![0x41], 5, 1); + let create = call_builder.create_proposal(vec![0x41], 15, 1); let _ = client .call(&ink_e2e::alice(), &create) .submit() diff --git a/integration-tests/public/mapping/.cargo/config.toml b/integration-tests/public/mapping/.cargo/config.toml deleted file mode 100644 index fcfc9c88880..00000000000 --- a/integration-tests/public/mapping/.cargo/config.toml +++ /dev/null @@ -1,3 +0,0 @@ -[env] -# Makes testing the fallible storage methods more efficient -INK_STATIC_BUFFER_SIZE = "256" diff --git a/integration-tests/public/mapping/Cargo.toml b/integration-tests/public/mapping/Cargo.toml index e56aea1b7e7..c223cbeb8cc 100755 --- a/integration-tests/public/mapping/Cargo.toml +++ b/integration-tests/public/mapping/Cargo.toml @@ -13,6 +13,7 @@ ink_e2e = { path = "../../../crates/e2e" } [lib] path = "lib.rs" +doctest = false [features] default = ["std"] diff --git a/integration-tests/public/mapping/lib.rs b/integration-tests/public/mapping/lib.rs index 3a2e221c188..a3fcb2faa5c 100755 --- a/integration-tests/public/mapping/lib.rs +++ b/integration-tests/public/mapping/lib.rs @@ -10,6 +10,8 @@ mod mapping { vec::Vec, }, storage::Mapping, + H160, + U256, }; #[derive(Debug, PartialEq)] @@ -23,9 +25,9 @@ mod mapping { #[derive(Default)] pub struct Mappings { /// Mapping from owner to number of owned token. - balances: Mapping, + balances: Mapping, /// Mapping from owner to aliases. - names: Mapping>, + names: Mapping>, } impl Mappings { @@ -44,7 +46,7 @@ mod mapping { /// Returns the balance of an account, or `None` if the account is not in the /// `Mapping`. #[ink(message)] - pub fn get_balance(&self) -> Option { + pub fn get_balance(&self) -> Option { let caller = Self::env().caller(); self.balances.get(caller) } @@ -56,7 +58,7 @@ mod mapping { /// Returns the size of the pre-existing balance at the specified key if any. /// Returns `None` if the account was not previously in the `Mapping`. #[ink(message)] - pub fn insert_balance(&mut self, value: Balance) -> Option { + pub fn insert_balance(&mut self, value: U256) -> Option { let caller = Self::env().caller(); self.balances.insert(caller, &value) } @@ -95,7 +97,7 @@ mod mapping { /// /// Returns `None` if the account is not in the `Mapping`. #[ink(message)] - pub fn take_balance(&mut self) -> Option { + pub fn take_balance(&mut self) -> Option { let caller = Self::env().caller(); self.balances.take(caller) } @@ -109,17 +111,28 @@ mod mapping { /// Returns `Err(_)` if the mapping value couldn't be encoded. #[ink(message)] pub fn try_insert_name(&mut self, name: String) -> Result<(), ContractError> { + ink::env::debug_println!("_____80"); let caller = Self::env().caller(); let mut names = match self.names.try_take(caller) { - None => Vec::new(), - Some(value) => value.map_err(|_| ContractError::ValueTooLarge)?, + None => { + ink::env::debug_println!("_____81"); + Vec::new() + } + Some(value) => { + ink::env::debug_println!("_____82"); + value.map_err(|_| ContractError::ValueTooLarge)? + } }; + ink::env::debug_println!("_____83"); names.push(name); - self.names - .try_insert(caller, &names) - .map_err(|_| ContractError::ValueTooLarge)?; + self.names.try_insert(caller, &names).map_err(|_| { + ink::env::debug_println!("_____84"); + ContractError::ValueTooLarge + })?; + + ink::env::debug_println!("_____85"); Ok(()) } @@ -161,7 +174,7 @@ mod mapping { let mut call_builder = contract.call_builder::(); // when - let insert = call_builder.insert_balance(1_000); + let insert = call_builder.insert_balance(1_000.into()); let size = client .call(&ink_e2e::alice(), &insert) .submit() @@ -178,7 +191,7 @@ mod mapping { .return_value(); assert!(size.is_none()); - assert_eq!(balance, Some(1_000)); + assert_eq!(balance, Some(1_000.into())); Ok(()) } @@ -197,7 +210,7 @@ mod mapping { let mut call_builder = contract.call_builder::(); // when - let insert = call_builder.insert_balance(1_000); + let insert = call_builder.insert_balance(1_000.into()); let _ = client .call(&ink_e2e::bob(), &insert) .submit() @@ -230,7 +243,7 @@ mod mapping { let mut call_builder = contract.call_builder::(); // when - let first_insert = call_builder.insert_balance(1_000); + let first_insert = call_builder.insert_balance(1_000.into()); let _ = client .call(&ink_e2e::charlie(), &first_insert) .submit() @@ -238,7 +251,7 @@ mod mapping { .expect("Calling `insert_balance` failed") .return_value(); - let insert = call_builder.insert_balance(10_000); + let insert = call_builder.insert_balance(10_000.into()); let size = client .call(&ink_e2e::charlie(), &insert) .submit() @@ -256,7 +269,7 @@ mod mapping { .await? .return_value(); - assert_eq!(balance, Some(10_000)); + assert_eq!(balance, Some(10_000.into())); Ok(()) } @@ -275,7 +288,7 @@ mod mapping { let mut call_builder = contract.call_builder::(); // when - let insert = call_builder.insert_balance(3_000); + let insert = call_builder.insert_balance(3_000.into()); let _ = client .call(&ink_e2e::dave(), &insert) .submit() @@ -317,7 +330,7 @@ mod mapping { let mut call_builder = contract.call_builder::(); // when - let insert = call_builder.insert_balance(4_000); + let insert = call_builder.insert_balance(4_000.into()); let _ = client .call(&ink_e2e::eve(), &insert) .submit() @@ -334,7 +347,7 @@ mod mapping { .return_value(); // then - assert_eq!(balance, Some(4_000)); + assert_eq!(balance, Some(4_000.into())); let contains = call_builder.contains_balance(); let is_there = client @@ -352,6 +365,12 @@ mod mapping { async fn fallible_storage_methods_work( mut client: Client, ) -> E2EResult<()> { + // Makes testing the fallible storage methods more efficient + const ERR: &str = "For this test the env variable `INK_STATIC_BUFFER_SIZE` needs to be set to `256`"; + let buffer_size = std::env::var("INK_STATIC_BUFFER_SIZE") + .unwrap_or_else(|err| panic!("{} {}", ERR, err)); + assert_eq!(buffer_size, "256", "{}", ERR); + // given let mut constructor = MappingsRef::new(); let contract = client @@ -370,12 +389,12 @@ mod mapping { } // then adding another one should fail gracefully - let expected_insert_result = client + let received_insert_result = client .call(&ink_e2e::ferdie(), &insert) .dry_run() .await? .return_value(); - let received_insert_result = + let expected_insert_result = Err(crate::mapping::ContractError::ValueTooLarge); assert_eq!(received_insert_result, expected_insert_result); diff --git a/integration-tests/public/multi-contract-caller/accumulator/Cargo.toml b/integration-tests/public/multi-contract-caller/accumulator/Cargo.toml index e40ae1b909d..4903d4ba0ec 100644 --- a/integration-tests/public/multi-contract-caller/accumulator/Cargo.toml +++ b/integration-tests/public/multi-contract-caller/accumulator/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" [dependencies] ink = { path = "../../../../crates/ink", default-features = false } + [lib] path = "lib.rs" diff --git a/integration-tests/public/multi-contract-caller/lib.rs b/integration-tests/public/multi-contract-caller/lib.rs index bab0f4f858f..70b3043b90e 100644 --- a/integration-tests/public/multi-contract-caller/lib.rs +++ b/integration-tests/public/multi-contract-caller/lib.rs @@ -52,24 +52,26 @@ mod multi_contract_caller { pub fn new( init_value: i32, version: u32, - accumulator_code_hash: Hash, - adder_code_hash: Hash, - subber_code_hash: Hash, + accumulator_code_hash: ink::H256, + adder_code_hash: ink::H256, + subber_code_hash: ink::H256, ) -> Self { let total_balance = Self::env().balance(); - let salt = version.to_le_bytes(); + let one_fourth = total_balance.checked_div(4.into()).expect("div failed"); + + let salt = salt_from_version(version); let accumulator = AccumulatorRef::new(init_value) - .endowment(total_balance / 4) + .endowment(one_fourth) .code_hash(accumulator_code_hash) .salt_bytes(salt) .instantiate(); let adder = AdderRef::new(accumulator.clone()) - .endowment(total_balance / 4) + .endowment(one_fourth) .code_hash(adder_code_hash) .salt_bytes(salt) .instantiate(); let subber = SubberRef::new(accumulator.clone()) - .endowment(total_balance / 4) + .endowment(one_fourth) .code_hash(subber_code_hash) .salt_bytes(salt) .instantiate(); @@ -110,6 +112,13 @@ mod multi_contract_caller { } } + fn salt_from_version(version: u32) -> Option<[u8; 32]> { + let version: [u8; 4] = version.to_le_bytes(); + let mut salt: [u8; 32] = [0u8; 32]; + salt[..4].copy_from_slice(&version); + Some(salt) + } + #[cfg(all(test, feature = "e2e-tests"))] mod e2e_tests { use super::*; @@ -153,7 +162,7 @@ mod multi_contract_caller { let multi_contract_caller = client .instantiate("multi_contract_caller", &ink_e2e::alice(), &mut constructor) - .value(10_000_000_000_000) + .value(100_000_000_000) .submit() .await .expect("instantiate failed"); diff --git a/integration-tests/public/multisig/lib.rs b/integration-tests/public/multisig/lib.rs index f7c0bf62146..3d5dce0e027 100755 --- a/integration-tests/public/multisig/lib.rs +++ b/integration-tests/public/multisig/lib.rs @@ -74,6 +74,8 @@ mod multisig { prelude::vec::Vec, scale::Output, storage::Mapping, + H160, + U256, }; /// Tune this to your liking but be wary that allowing too many owners will not @@ -90,7 +92,7 @@ mod multisig { #[derive(Clone)] struct CallInput<'a>(&'a [u8]); - impl<'a> ink::scale::Encode for CallInput<'a> { + impl ink::scale::Encode for CallInput<'_> { fn encode_to(&self, dest: &mut T) { dest.write(self.0); } @@ -117,15 +119,15 @@ mod multisig { )] #[ink::scale_derive(Encode, Decode, TypeInfo)] pub struct Transaction { - /// The `AccountId` of the contract that is called in this transaction. - pub callee: AccountId, + /// The address of the contract that is called in this transaction. + pub callee: H160, /// The selector bytes that identifies the function of the callee that should be /// called. pub selector: [u8; 4], /// The SCALE encoded parameters that are passed to the called function. pub input: Vec, /// The amount of chain balance that is transferred to the callee. - pub transferred_value: Balance, + pub transferred_value: U256, /// Gas limit for the execution of the call. pub ref_time_limit: u64, /// If set to true the transaction will be allowed to re-enter the multisig @@ -167,7 +169,7 @@ mod multisig { transaction: TransactionId, /// The owner that sent the confirmation. #[ink(topic)] - from: AccountId, + from: H160, /// The confirmation status after this confirmation was applied. #[ink(topic)] status: ConfirmationStatus, @@ -181,7 +183,7 @@ mod multisig { transaction: TransactionId, /// The owner that sent the revocation. #[ink(topic)] - from: AccountId, + from: H160, } /// Emitted when an owner submits a transaction. @@ -219,7 +221,7 @@ mod multisig { pub struct OwnerAddition { /// The owner that was added. #[ink(topic)] - owner: AccountId, + owner: H160, } /// Emitted when an owner is removed from the wallet. @@ -227,7 +229,7 @@ mod multisig { pub struct OwnerRemoval { /// The owner that was removed. #[ink(topic)] - owner: AccountId, + owner: H160, } /// Emitted when the requirement changed. @@ -242,7 +244,7 @@ mod multisig { pub struct Multisig { /// Every entry in this map represents the confirmation of an owner for a /// transaction. This is effectively a set rather than a map. - confirmations: Mapping<(TransactionId, AccountId), ()>, + confirmations: Mapping<(TransactionId, H160), ()>, /// The amount of confirmations for every transaction. This is a redundant /// information and is kept in order to prevent iterating through the /// confirmation set to check if a transaction is confirmed. @@ -254,9 +256,9 @@ mod multisig { transaction_list: Transactions, /// The list is a vector because iterating over it is necessary when cleaning /// up the confirmation set. - owners: Vec, + owners: Vec, /// Redundant information to speed up the check whether a caller is an owner. - is_owner: Mapping, + is_owner: Mapping, /// Minimum number of owners that have to confirm a transaction to be executed. requirement: u32, } @@ -271,7 +273,7 @@ mod multisig { /// /// If `requirement` violates our invariant. #[ink(constructor)] - pub fn new(requirement: u32, mut owners: Vec) -> Self { + pub fn new(requirement: u32, mut owners: Vec) -> Self { let mut contract = Multisig::default(); owners.sort_unstable(); owners.dedup(); @@ -321,20 +323,18 @@ mod multisig { /// Transaction, /// }; /// - /// type AccountId = ::AccountId; - /// /// // address of an existing `Multisig` contract - /// let wallet_id: AccountId = [7u8; 32].into(); + /// let wallet_id: ink::H160 = [7u8; 20].into(); /// /// // first create the transaction that adds `alice` through `add_owner` - /// let alice: AccountId = [1u8; 32].into(); + /// let alice: ink::H160 = [1u8; 20].into(); /// let add_owner_args = ArgumentList::empty().push_arg(&alice); /// /// let transaction_candidate = Transaction { /// callee: wallet_id, /// selector: selector_bytes!("add_owner"), /// input: add_owner_args.encode(), - /// transferred_value: 0, + /// transferred_value: ink::U256::zero(), /// ref_time_limit: 0, /// allow_reentry: true, /// }; @@ -365,7 +365,7 @@ mod multisig { /// .invoke(); /// ``` #[ink(message)] - pub fn add_owner(&mut self, new_owner: AccountId) { + pub fn add_owner(&mut self, new_owner: H160) { self.ensure_from_wallet(); self.ensure_no_owner(&new_owner); ensure_requirement_is_valid( @@ -387,7 +387,7 @@ mod multisig { /// /// If `owner` is no owner of the wallet. #[ink(message)] - pub fn remove_owner(&mut self, owner: AccountId) { + pub fn remove_owner(&mut self, owner: H160) { self.ensure_from_wallet(); self.ensure_owner(&owner); // If caller is an owner the len has to be > 0 @@ -411,7 +411,7 @@ mod multisig { /// /// If `old_owner` is no owner or if `new_owner` already is one. #[ink(message)] - pub fn replace_owner(&mut self, old_owner: AccountId, new_owner: AccountId) { + pub fn replace_owner(&mut self, old_owner: H160, new_owner: H160) { self.ensure_from_wallet(); self.ensure_owner(&old_owner); self.ensure_no_owner(&new_owner); @@ -620,7 +620,7 @@ mod multisig { /// by `confirmer`. fn confirm_by_caller( &mut self, - confirmer: AccountId, + confirmer: H160, transaction: TransactionId, ) -> ConfirmationStatus { let mut count = self.confirmation_count.get(transaction).unwrap_or(0); @@ -652,7 +652,7 @@ mod multisig { /// Get the index of `owner` in `self.owners`. /// Panics if `owner` is not found in `self.owners`. - fn owner_index(&self, owner: &AccountId) -> u32 { + fn owner_index(&self, owner: &H160) -> u32 { self.owners.iter().position(|x| *x == *owner).expect( "This is only called after it was already verified that the id is actually an owner.", @@ -682,7 +682,7 @@ mod multisig { /// Remove all confirmation state associated with `owner`. /// Also adjusts the `self.confirmation_count` variable. - fn clean_owner_confirmations(&mut self, owner: &AccountId) { + fn clean_owner_confirmations(&mut self, owner: &H160) { for trans_id in &self.transaction_list.transactions { let key = (*trans_id, *owner); if self.confirmations.contains(key) { @@ -717,16 +717,16 @@ mod multisig { /// Panic if the sender is not this wallet. fn ensure_from_wallet(&self) { - assert_eq!(self.env().caller(), self.env().account_id()); + assert_eq!(self.env().caller(), self.env().address()); } /// Panic if `owner` is not an owner, - fn ensure_owner(&self, owner: &AccountId) { + fn ensure_owner(&self, owner: &H160) { assert!(self.is_owner.contains(owner)); } /// Panic if `owner` is an owner. - fn ensure_no_owner(&self, owner: &AccountId) { + fn ensure_no_owner(&self, owner: &H160) { assert!(!self.is_owner.contains(owner)); } } @@ -745,7 +745,7 @@ mod multisig { test, }; - const WALLET: [u8; 32] = [7; 32]; + const WALLET: [u8; 20] = [7; 20]; impl Transaction { fn change_requirement(requirement: u32) -> Self { @@ -754,22 +754,22 @@ mod multisig { // Multisig::change_requirement() Self { - callee: AccountId::from(WALLET), + callee: H160::from(WALLET), selector: ink::selector_bytes!("change_requirement"), input: call_args.encode(), - transferred_value: 0, + transferred_value: U256::zero(), ref_time_limit: 1000000, allow_reentry: false, } } } - fn set_caller(sender: AccountId) { - ink::env::test::set_caller::(sender); + fn set_caller(sender: H160) { + ink::env::test::set_caller(sender); } fn set_from_wallet() { - let callee = AccountId::from(WALLET); + let callee = H160::from(WALLET); set_caller(callee); } @@ -783,14 +783,14 @@ mod multisig { set_caller(accounts.django); } - fn default_accounts() -> test::DefaultAccounts { - ink::env::test::default_accounts::() + fn default_accounts() -> test::DefaultAccounts { + ink::env::test::default_accounts() } fn build_contract() -> Multisig { // Set the contract's address as `WALLET`. - let callee: AccountId = AccountId::from(WALLET); - ink::env::test::set_callee::(callee); + let callee: H160 = H160::from(WALLET); + ink::env::test::set_callee(callee); let accounts = default_accounts(); let owners = vec![accounts.alice, accounts.bob, accounts.eve]; diff --git a/integration-tests/public/own-code-hash/Cargo.toml b/integration-tests/public/own-code-hash/Cargo.toml index 61dd31d32a5..3663b3b5f7f 100644 --- a/integration-tests/public/own-code-hash/Cargo.toml +++ b/integration-tests/public/own-code-hash/Cargo.toml @@ -17,7 +17,7 @@ ink_e2e = { path = "../../../crates/e2e" } path = "lib.rs" [features] -default = ["std", "test_instantiate"] +default = ["std"] std = [ "ink/std", "scale/std", @@ -25,6 +25,3 @@ std = [ ] ink-as-dependency = [] e2e-tests = [] -test_instantiate = [ - "ink/test_instantiate", -] diff --git a/integration-tests/public/own-code-hash/lib.rs b/integration-tests/public/own-code-hash/lib.rs index fa2f6438269..853ae3ab708 100644 --- a/integration-tests/public/own-code-hash/lib.rs +++ b/integration-tests/public/own-code-hash/lib.rs @@ -2,6 +2,7 @@ #[ink::contract] mod own_code_hash { + use ink::H256; #[ink(storage)] pub struct OwnCodeHash {} @@ -14,15 +15,15 @@ mod own_code_hash { /// Returns the code hash of the contract #[ink(message)] - pub fn own_code_hash(&self) -> Hash { + pub fn own_code_hash(&self) -> H256 { self.env().own_code_hash().unwrap() } - /// Returns the code hash of the contract by providing it's `account_id` + /// Returns the code hash of the contract by providing its `account_id` #[ink(message)] - pub fn get_code(&self) -> Hash { + pub fn get_code(&self) -> H256 { self.env() - .code_hash(&self.env().account_id()) + .code_hash(&self.env().address()) .expect("Failed to get code hash") } } @@ -33,22 +34,23 @@ mod own_code_hash { } } - #[cfg(all(test, feature = "test_instantiate"))] + #[cfg(test)] mod tests { use super::*; #[ink::test] fn get_own_code_hash() { - let code_hash = ink::env::test::upload_code::(); - let address = - { + let code_hash = ink::env::test::upload_code::< + ink::env::DefaultEnvironment, + OwnCodeHashRef, + >(); + let address = { let create_params = ink::env::call::build_create::() .code_hash(code_hash) - .endowment(0) + .endowment(0.into()) .exec_input(ink::env::call::ExecutionInput::new( ink::env::call::Selector::new(ink::selector_bytes!("new")), )) - .salt_bytes(&[0_u8; 4]) .returns::() .params(); @@ -62,12 +64,12 @@ mod own_code_hash { .unwrap_or_else(|error| { panic!("Received a `LangError` while instatiating: {:?}", error) }); - ink::ToAccountId::::to_account_id(&cr) + ink::ToAddr::to_addr(&cr) }; let own_code_hash = OwnCodeHash::new(); - ink::env::test::set_callee::(address); - let code_hash_via_own: Hash = own_code_hash.own_code_hash(); + ink::env::test::set_callee(address); + let code_hash_via_own: H256 = own_code_hash.own_code_hash(); assert_eq!(code_hash_via_own, code_hash); } @@ -75,33 +77,31 @@ mod own_code_hash { #[cfg(all(test, feature = "e2e-tests"))] mod e2e_tests { - use ink_e2e::build_message; - use super::*; + use ink_e2e::ContractsBackend; type E2EResult = std::result::Result>; #[ink_e2e::test] async fn get_own_code_hash(mut client: ink_e2e::Client) -> E2EResult<()> { - let constructor = OwnCodeHashRef::new(); - let contract_acc_id = client - .instantiate("own_code_hash", &ink_e2e::bob(), constructor, 0, None) + let mut constructor = OwnCodeHashRef::new(); + let contract = client + .instantiate("own_code_hash", &ink_e2e::bob(), &mut constructor) + .submit() .await - .expect("instantiate failed") - .account_id; + .expect("instantiate failed"); - let own_code_hash = build_message::(contract_acc_id) - .call(|contract| contract.own_code_hash()); + let call_builder = contract.call_builder::(); let own_code_hash_res = client - .call(&ink_e2e::bob(), own_code_hash, 0, None) + .call(&ink_e2e::bob(), &call_builder.own_code_hash()) + .submit() .await .expect("own_code_hash failed"); // Compare codes obtained differently with own_code_hash and code_hash - let get_code = build_message::(contract_acc_id) - .call(|contract| contract.get_code()); let get_code_res = client - .call(&ink_e2e::alice(), get_code, 0, None) + .call(&ink_e2e::alice(), &call_builder.get_code()) + .submit() .await .expect("get_code failed"); @@ -113,4 +113,4 @@ mod own_code_hash { Ok(()) } } -} \ No newline at end of file +} diff --git a/integration-tests/public/payment-channel/Cargo.toml b/integration-tests/public/payment-channel/Cargo.toml index 8ad117e1634..13405eaa21f 100755 --- a/integration-tests/public/payment-channel/Cargo.toml +++ b/integration-tests/public/payment-channel/Cargo.toml @@ -10,7 +10,7 @@ ink = { path = "../../../crates/ink", default-features = false } [dev-dependencies] hex-literal = { version = "0.4.1" } -sp-core = { version = "21.0.0", default-features = false } +sp-core = { version = "35.0.0", default-features = false } [lib] path = "lib.rs" diff --git a/integration-tests/public/payment-channel/lib.rs b/integration-tests/public/payment-channel/lib.rs index 877d039370a..825609a6465 100755 --- a/integration-tests/public/payment-channel/lib.rs +++ b/integration-tests/public/payment-channel/lib.rs @@ -24,7 +24,7 @@ //! //! ### Deposits //! -//! The creator of the contract, i.e the `sender`, can deposit funds to the payment +//! The creator of the contract, i.e. the `sender`, can deposit funds to the payment //! channel while creating the payment channel. Any subsequent deposits can be made by //! transferring funds to the contract's address. //! @@ -41,21 +41,25 @@ #[ink::contract] mod payment_channel { + use ink::{ + H160, + U256, + }; /// Struct for storing the payment channel details. - /// The creator of the contract, i.e the `sender`, can deposit funds to the payment + /// The creator of the contract, i.e. the `sender`, can deposit funds to the payment /// channel while deploying the contract. #[ink(storage)] pub struct PaymentChannel { - /// The `AccountId` of the sender of the payment channel. - sender: AccountId, - /// The `AccountId` of the recipient of the payment channel. - recipient: AccountId, + /// The `H160` of the sender of the payment channel. + sender: H160, + /// The `H160` of the recipient of the payment channel. + recipient: H160, /// The `Timestamp` at which the contract expires. The field is optional. /// The contract never expires if set to `None`. expiration: Option, /// The `Amount` withdrawn by the recipient. - withdrawn: Balance, + withdrawn: U256, /// The `Timestamp` which will be added to the current time when the sender /// wishes to close the channel. This will be set at the time of contract /// instantiation. @@ -71,7 +75,7 @@ mod payment_channel { /// Returned if caller is not the `recipient` while required to. CallerIsNotRecipient, /// Returned if the requested withdrawal amount is less than the amount - /// that is already already withdrawn. + /// that is already withdrawn. AmountIsLessThanWithdrawn, /// Returned if the requested transfer failed. This can be the case if the /// contract does not have sufficient free funds or if the transfer would @@ -104,12 +108,12 @@ mod payment_channel { /// this. `sender` will be able to claim the remaining balance by calling /// `claim_timeout` after `expiration` has passed. #[ink(constructor)] - pub fn new(recipient: AccountId, close_duration: Timestamp) -> Self { + pub fn new(recipient: H160, close_duration: Timestamp) -> Self { Self { sender: Self::env().caller(), recipient, expiration: None, - withdrawn: 0, + withdrawn: 0.into(), close_duration, } } @@ -118,13 +122,13 @@ mod payment_channel { /// `amount` will be sent to the `recipient` and the remainder will go /// back to the `sender`. #[ink(message)] - pub fn close(&mut self, amount: Balance, signature: [u8; 65]) -> Result<()> { + pub fn close(&mut self, amount: U256, signature: [u8; 65]) -> Result<()> { self.close_inner(amount, signature)?; self.env().terminate_contract(self.sender); } /// We split this out in order to make testing `close` simpler. - fn close_inner(&mut self, amount: Balance, signature: [u8; 65]) -> Result<()> { + fn close_inner(&mut self, amount: U256, signature: [u8; 65]) -> Result<()> { if self.env().caller() != self.recipient { return Err(Error::CallerIsNotRecipient) } @@ -194,7 +198,7 @@ mod payment_channel { /// The `recipient` can withdraw the funds from the channel at any time. #[ink(message)] - pub fn withdraw(&mut self, amount: Balance, signature: [u8; 65]) -> Result<()> { + pub fn withdraw(&mut self, amount: U256, signature: [u8; 65]) -> Result<()> { if self.env().caller() != self.recipient { return Err(Error::CallerIsNotRecipient) } @@ -223,13 +227,13 @@ mod payment_channel { /// Returns the `sender` of the contract. #[ink(message)] - pub fn get_sender(&self) -> AccountId { + pub fn get_sender(&self) -> H160 { self.sender } /// Returns the `recipient` of the contract. #[ink(message)] - pub fn get_recipient(&self) -> AccountId { + pub fn get_recipient(&self) -> H160 { self.recipient } @@ -241,7 +245,7 @@ mod payment_channel { /// Returns the `withdrawn` amount of the contract. #[ink(message)] - pub fn get_withdrawn(&self) -> Balance { + pub fn get_withdrawn(&self) -> U256 { self.withdrawn } @@ -253,15 +257,15 @@ mod payment_channel { /// Returns the `balance` of the contract. #[ink(message)] - pub fn get_balance(&self) -> Balance { + pub fn get_balance(&self) -> U256 { self.env().balance() } } #[ink(impl)] impl PaymentChannel { - fn is_signature_valid(&self, amount: Balance, signature: [u8; 65]) -> bool { - let encodable = (self.env().account_id(), amount); + fn is_signature_valid(&self, amount: U256, signature: [u8; 65]) -> bool { + let encodable = (self.env().address(), amount); let mut message = ::Type::default(); ink::env::hash_encoded::( @@ -278,7 +282,7 @@ mod payment_channel { &mut signature_account_id, ); - self.recipient == signature_account_id.into() + self.recipient == H160::from_slice(&signature_account_id[..20]) } } @@ -292,22 +296,19 @@ mod payment_channel { Pair, }; - fn default_accounts( - ) -> ink::env::test::DefaultAccounts { - ink::env::test::default_accounts::() + fn default_accounts() -> ink::env::test::DefaultAccounts { + ink::env::test::default_accounts() } - fn set_next_caller(caller: AccountId) { - ink::env::test::set_caller::(caller); + fn set_next_caller(caller: H160) { + ink::env::test::set_caller(caller); } - fn set_account_balance(account: AccountId, balance: Balance) { - ink::env::test::set_account_balance::( - account, balance, - ); + fn set_account_balance(account: H160, balance: U256) { + ink::env::test::set_account_balance(account, balance); } - fn get_account_balance(account: AccountId) -> Balance { + fn get_account_balance(account: H160) -> U256 { ink::env::test::get_account_balance::(account) .expect("Cannot get account balance") } @@ -324,7 +325,7 @@ mod payment_channel { + since_the_epoch.subsec_nanos() as u64 / 1_000_000_000 } - fn get_dan() -> AccountId { + fn get_dan() -> H160 { // Use Dan's seed // `subkey inspect //Dan --scheme Ecdsa --output-type json | jq .secretSeed` let seed = hex_literal::hex!( @@ -340,17 +341,17 @@ mod payment_channel { &compressed_pub_key, &mut account_id, ); - account_id.into() + H160::from_slice(&account_id[..20]) } - fn contract_id() -> AccountId { + fn contract_id() -> H160 { let accounts = default_accounts(); let contract_id = accounts.charlie; - ink::env::test::set_callee::(contract_id); + ink::env::test::set_callee(contract_id); contract_id } - fn sign(contract_id: AccountId, amount: Balance) -> [u8; 65] { + fn sign(contract_id: H160, amount: U256) -> [u8; 65] { let encodable = (contract_id, amount); let mut hash = ::Type::default(); // 256-bit buffer @@ -371,9 +372,9 @@ mod payment_channel { fn test_deposit() { // given let accounts = default_accounts(); - let initial_balance = 10_000; + let initial_balance = 10_000.into(); let close_duration = 360_000; - let mock_deposit_value = 1_000; + let mock_deposit_value = 1_000.into(); set_account_balance(accounts.alice, initial_balance); set_account_balance(accounts.bob, initial_balance); @@ -396,9 +397,9 @@ mod payment_channel { let accounts = default_accounts(); let dan = get_dan(); let close_duration = 360_000; - let mock_deposit_value = 1_000; - let amount = 500; - let initial_balance = 10_000; + let mock_deposit_value = 1_000.into(); + let amount = 500.into(); + let initial_balance = 10_000.into(); set_account_balance(accounts.alice, initial_balance); set_account_balance(dan, initial_balance); @@ -425,11 +426,11 @@ mod payment_channel { // given let accounts = default_accounts(); let dan = get_dan(); - let mock_deposit_value = 1_000; + let mock_deposit_value = 1_000.into(); let close_duration = 360_000; - let amount = 400; - let unexpected_amount = amount + 1; - let initial_balance = 10_000; + let amount = 400.into(); + let unexpected_amount = amount + U256::from(1); + let initial_balance = 10_000.into(); set_account_balance(accounts.alice, initial_balance); set_account_balance(dan, initial_balance); @@ -452,10 +453,10 @@ mod payment_channel { // given let accounts = default_accounts(); let dan = get_dan(); - let initial_balance = 10_000; - let mock_deposit_value = 1_000; + let initial_balance = 10_000.into(); + let mock_deposit_value = 1_000.into(); let close_duration = 360_000; - let amount = 500; + let amount = 500.into(); set_account_balance(accounts.alice, initial_balance); set_account_balance(dan, initial_balance); @@ -481,11 +482,11 @@ mod payment_channel { // given let accounts = default_accounts(); let dan = get_dan(); - let initial_balance = 10_000; + let initial_balance = 10_000.into(); let close_duration = 360_000; - let amount = 400; - let unexpected_amount = amount + 1; - let mock_deposit_value = 1_000; + let amount = 400.into(); + let unexpected_amount = amount + U256::from(1); + let mock_deposit_value = 1_000.into(); set_account_balance(accounts.alice, initial_balance); set_account_balance(dan, initial_balance); @@ -507,8 +508,8 @@ mod payment_channel { fn test_start_sender_close() { // given let accounts = default_accounts(); - let initial_balance = 10_000; - let mock_deposit_value = 1_000; + let initial_balance = 10_000.into(); + let mock_deposit_value = 1_000.into(); let close_duration = 1; set_account_balance(accounts.alice, initial_balance); set_account_balance(accounts.bob, initial_balance); @@ -533,9 +534,9 @@ mod payment_channel { fn test_claim_timeout() { // given let accounts = default_accounts(); - let initial_balance = 10_000; + let initial_balance = 10_000.into(); let close_duration = 1; - let mock_deposit_value = 1_000; + let mock_deposit_value = 1_000.into(); set_account_balance(accounts.alice, initial_balance); set_account_balance(accounts.bob, initial_balance); @@ -567,8 +568,8 @@ mod payment_channel { fn test_getters() { // given let accounts = default_accounts(); - let initial_balance = 10_000; - let mock_deposit_value = 1_000; + let initial_balance = 10_000.into(); + let mock_deposit_value = 1_000.into(); let close_duration = 360_000; set_account_balance(accounts.alice, initial_balance); set_account_balance(accounts.bob, initial_balance); @@ -584,7 +585,7 @@ mod payment_channel { assert_eq!(payment_channel.get_recipient(), accounts.bob); assert_eq!(payment_channel.get_balance(), mock_deposit_value); assert_eq!(payment_channel.get_close_duration(), close_duration); - assert_eq!(payment_channel.get_withdrawn(), 0); + assert_eq!(payment_channel.get_withdrawn(), U256::zero()); } } } diff --git a/integration-tests/public/psp22-extension/README.md b/integration-tests/public/psp22-extension/README.md index feab477a852..40f77bb7363 100644 --- a/integration-tests/public/psp22-extension/README.md +++ b/integration-tests/public/psp22-extension/README.md @@ -27,9 +27,9 @@ To integrate this example into Substrate you need to do two things: You can just copy/paste that file as a new module, e.g. `runtime/src/chain_extension.rs`. * In your runtime, use the implementation as the associated type `ChainExtension` of the - trait `pallet_contracts::Config`: + trait `pallet_revive::Config`: ```rust - impl pallet_contracts::Config for Runtime { + impl pallet_revive::Config for Runtime { … type ChainExtension = Psp22Extension; … diff --git a/integration-tests/public/psp22-extension/lib.rs b/integration-tests/public/psp22-extension/lib.rs index 3691ca280f4..5cec8b62c35 100755 --- a/integration-tests/public/psp22-extension/lib.rs +++ b/integration-tests/public/psp22-extension/lib.rs @@ -3,11 +3,10 @@ use ink::{ env::Environment, prelude::vec::Vec, + H160, + U256, }; -type DefaultAccountId = ::AccountId; -type DefaultBalance = ::Balance; - #[ink::chain_extension(extension = 13)] pub trait Psp22Extension { type ErrorCode = Psp22Error; @@ -26,55 +25,33 @@ pub trait Psp22Extension { // PSP22 interface queries #[ink(function = 0x162d)] - fn total_supply(asset_id: u32) -> Result; + fn total_supply(asset_id: u32) -> Result; #[ink(function = 0x6568)] - fn balance_of(asset_id: u32, owner: DefaultAccountId) -> Result; + fn balance_of(asset_id: u32, owner: H160) -> Result; #[ink(function = 0x4d47)] - fn allowance( - asset_id: u32, - owner: DefaultAccountId, - spender: DefaultAccountId, - ) -> Result; + fn allowance(asset_id: u32, owner: H160, spender: H160) -> Result; // PSP22 transfer #[ink(function = 0xdb20)] - fn transfer(asset_id: u32, to: DefaultAccountId, value: DefaultBalance) - -> Result<()>; + fn transfer(asset_id: u32, to: H160, value: U256) -> Result<()>; // PSP22 transfer_from #[ink(function = 0x54b3)] - fn transfer_from( - asset_id: u32, - from: DefaultAccountId, - to: DefaultAccountId, - value: DefaultBalance, - ) -> Result<()>; + fn transfer_from(asset_id: u32, from: H160, to: H160, value: U256) -> Result<()>; // PSP22 approve #[ink(function = 0xb20f)] - fn approve( - asset_id: u32, - spender: DefaultAccountId, - value: DefaultBalance, - ) -> Result<()>; + fn approve(asset_id: u32, spender: H160, value: U256) -> Result<()>; // PSP22 increase_allowance #[ink(function = 0x96d6)] - fn increase_allowance( - asset_id: u32, - spender: DefaultAccountId, - value: DefaultBalance, - ) -> Result<()>; + fn increase_allowance(asset_id: u32, spender: H160, value: U256) -> Result<()>; // PSP22 decrease_allowance #[ink(function = 0xfecb)] - fn decrease_allowance( - asset_id: u32, - spender: DefaultAccountId, - value: DefaultBalance, - ) -> Result<()>; + fn decrease_allowance(asset_id: u32, spender: H160, value: U256) -> Result<()>; } #[derive(Debug, PartialEq, Eq)] @@ -110,11 +87,12 @@ impl Environment for CustomEnvironment { const MAX_EVENT_TOPICS: usize = ::MAX_EVENT_TOPICS; - type AccountId = DefaultAccountId; - type Balance = DefaultBalance; + type AccountId = ::AccountId; + type Balance = ::Balance; type Hash = ::Hash; type Timestamp = ::Timestamp; type BlockNumber = ::BlockNumber; + type EventRecord = ::EventRecord; type ChainExtension = crate::Psp22Extension; } @@ -125,6 +103,10 @@ mod psp22_ext { Result, Vec, }; + use ink::{ + H160, + U256, + }; /// A chain extension which implements the PSP-22 fungible token standard. /// For more details see @@ -163,13 +145,13 @@ mod psp22_ext { /// Returns the total token supply of the specified asset. #[ink(message, selector = 0x162df8c2)] - pub fn total_supply(&self, asset_id: u32) -> Result { + pub fn total_supply(&self, asset_id: u32) -> Result { self.env().extension().total_supply(asset_id) } /// Returns the account balance for the specified asset & owner. #[ink(message, selector = 0x6568382f)] - pub fn balance_of(&self, asset_id: u32, owner: AccountId) -> Result { + pub fn balance_of(&self, asset_id: u32, owner: H160) -> Result { self.env().extension().balance_of(asset_id, owner) } @@ -179,9 +161,9 @@ mod psp22_ext { pub fn allowance( &self, asset_id: u32, - owner: AccountId, - spender: AccountId, - ) -> Result { + owner: H160, + spender: H160, + ) -> Result { self.env().extension().allowance(asset_id, owner, spender) } @@ -190,12 +172,7 @@ mod psp22_ext { /// Transfers `value` amount of specified asset from the caller's account to the /// account `to`. #[ink(message, selector = 0xdb20f9f5)] - pub fn transfer( - &mut self, - asset_id: u32, - to: AccountId, - value: Balance, - ) -> Result<()> { + pub fn transfer(&mut self, asset_id: u32, to: H160, value: U256) -> Result<()> { self.env().extension().transfer(asset_id, to, value) } @@ -207,9 +184,9 @@ mod psp22_ext { pub fn transfer_from( &mut self, asset_id: u32, - from: AccountId, - to: AccountId, - value: Balance, + from: H160, + to: H160, + value: U256, ) -> Result<()> { self.env() .extension() @@ -224,8 +201,8 @@ mod psp22_ext { pub fn approve( &mut self, asset_id: u32, - spender: AccountId, - value: Balance, + spender: H160, + value: U256, ) -> Result<()> { self.env().extension().approve(asset_id, spender, value) } @@ -238,8 +215,8 @@ mod psp22_ext { pub fn increase_allowance( &mut self, asset_id: u32, - spender: AccountId, - value: Balance, + spender: H160, + value: U256, ) -> Result<()> { self.env() .extension() @@ -254,8 +231,8 @@ mod psp22_ext { pub fn decrease_allowance( &mut self, asset_id: u32, - spender: AccountId, - value: Balance, + spender: H160, + value: U256, ) -> Result<()> { self.env() .extension() diff --git a/integration-tests/public/psp22-extension/runtime/psp22-extension-example.rs b/integration-tests/public/psp22-extension/runtime/psp22-extension-example.rs index aa11d819cdb..e696586f838 100644 --- a/integration-tests/public/psp22-extension/runtime/psp22-extension-example.rs +++ b/integration-tests/public/psp22-extension/runtime/psp22-extension-example.rs @@ -1,3 +1,4 @@ +// todo use codec::{ Decode, Encode, @@ -24,7 +25,7 @@ use pallet_assets::{ self, WeightInfo, }; -use pallet_contracts::chain_extension::{ +use pallet_revive::chain_extension::{ ChainExtension, Environment, Ext, @@ -151,7 +152,7 @@ fn metadata( env: Environment, ) -> Result<(), DispatchError> where - T: pallet_assets::Config + pallet_contracts::Config, + T: pallet_assets::Config + pallet_revive::Config, ::AccountId: UncheckedFrom<::Hash> + AsRef<[u8]>, E: Ext, { @@ -187,7 +188,7 @@ fn query( env: Environment, ) -> Result<(), DispatchError> where - T: pallet_assets::Config + pallet_contracts::Config, + T: pallet_assets::Config + pallet_revive::Config, ::AccountId: UncheckedFrom<::Hash> + AsRef<[u8]>, E: Ext, { @@ -225,7 +226,7 @@ where fn transfer(env: Environment) -> Result<(), DispatchError> where - T: pallet_assets::Config + pallet_contracts::Config, + T: pallet_assets::Config + pallet_revive::Config, ::AccountId: UncheckedFrom<::Hash> + AsRef<[u8]>, E: Ext, { @@ -234,7 +235,7 @@ where // debug_message weight is a good approximation of the additional overhead of going // from contract layer to substrate layer. let overhead = Weight::from_ref_time( - ::Schedule::get() + ::Schedule::get() .host_fn_weights .debug_message, ); @@ -267,7 +268,7 @@ where fn transfer_from(env: Environment) -> Result<(), DispatchError> where - T: pallet_assets::Config + pallet_contracts::Config, + T: pallet_assets::Config + pallet_revive::Config, ::AccountId: UncheckedFrom<::Hash> + AsRef<[u8]>, E: Ext, { @@ -276,7 +277,7 @@ where // debug_message weight is a good approximation of the additional overhead of going // from contract layer to substrate layer. let overhead = Weight::from_ref_time( - ::Schedule::get() + ::Schedule::get() .host_fn_weights .debug_message, ); @@ -308,7 +309,7 @@ where fn approve(env: Environment) -> Result<(), DispatchError> where - T: pallet_assets::Config + pallet_contracts::Config, + T: pallet_assets::Config + pallet_revive::Config, ::AccountId: UncheckedFrom<::Hash> + AsRef<[u8]>, E: Ext, { @@ -317,7 +318,7 @@ where // debug_message weight is a good approximation of the additional overhead of going // from contract layer to substrate layer. let overhead = Weight::from_ref_time( - ::Schedule::get() + ::Schedule::get() .host_fn_weights .debug_message, ); @@ -346,7 +347,7 @@ where fn decrease_allowance(env: Environment) -> Result<(), DispatchError> where - T: pallet_assets::Config + pallet_contracts::Config, + T: pallet_assets::Config + pallet_revive::Config, ::AccountId: UncheckedFrom<::Hash> + AsRef<[u8]>, E: Ext, { @@ -361,7 +362,7 @@ where // debug_message weight is a good approximation of the additional overhead of going // from contract layer to substrate layer. let overhead = Weight::from_ref_time( - ::Schedule::get() + ::Schedule::get() .host_fn_weights .debug_message, ); @@ -417,7 +418,7 @@ where impl ChainExtension for Psp22Extension where - T: pallet_assets::Config + pallet_contracts::Config, + T: pallet_assets::Config + pallet_revive::Config, ::AccountId: UncheckedFrom<::Hash> + AsRef<[u8]>, { fn call( diff --git a/integration-tests/public/rand-extension/README.md b/integration-tests/public/rand-extension/README.md index 19d4cc48c7a..f3e75b31d14 100644 --- a/integration-tests/public/rand-extension/README.md +++ b/integration-tests/public/rand-extension/README.md @@ -21,9 +21,9 @@ To integrate this example into Substrate you need to do two things: You can just copy/paste the content of that file into e.g. your `runtime/src/lib.rs`. * Use the implementation as the associated type `ChainExtension` of the trait - `pallet_contracts::Config`: + `pallet_revive::Config`: ```rust - impl pallet_contracts::Config for Runtime { + impl pallet_revive::Config for Runtime { … type ChainExtension = FetchRandomExtension; … diff --git a/integration-tests/public/rand-extension/lib.rs b/integration-tests/public/rand-extension/lib.rs index 861c9f96674..c96cc498002 100755 --- a/integration-tests/public/rand-extension/lib.rs +++ b/integration-tests/public/rand-extension/lib.rs @@ -47,6 +47,7 @@ impl Environment for CustomEnvironment { type Hash = ::Hash; type BlockNumber = ::BlockNumber; type Timestamp = ::Timestamp; + type EventRecord = ::EventRecord; type ChainExtension = FetchRandom; } diff --git a/integration-tests/public/rand-extension/runtime/chain-extension-example.rs b/integration-tests/public/rand-extension/runtime/chain-extension-example.rs index 4d4a4a9bcbe..9cbd865ad55 100644 --- a/integration-tests/public/rand-extension/runtime/chain-extension-example.rs +++ b/integration-tests/public/rand-extension/runtime/chain-extension-example.rs @@ -3,7 +3,7 @@ use frame_support::log::{ error, trace, }; -use pallet_contracts::chain_extension::{ +use pallet_revive::chain_extension::{ ChainExtension, Environment, Ext, diff --git a/integration-tests/public/runtime-call-contract/Cargo.toml b/integration-tests/public/runtime-call-contract/Cargo.toml index d1166af5c16..2493f812d84 100644 --- a/integration-tests/public/runtime-call-contract/Cargo.toml +++ b/integration-tests/public/runtime-call-contract/Cargo.toml @@ -5,15 +5,17 @@ members = ["sandbox-runtime", "traits"] authors = ["Use Ink "] edition = "2021" homepage = "https://use.ink" -keywords = ["wasm", "ink", "webassembly", "blockchain", "edsl"] license = "Apache-2.0" repository = "https://github.com/use-ink/ink" +keywords = ["polkavm", "ink", "riscv", "blockchain", "edsl"] +publish = false [workspace.dependencies] -frame-support = { version = "38.0.0", default-features = false } -frame-system = { version = "38.0.0", default-features = false } -pallet-contracts = { version = "38.0.0", default-features = false } -sp-runtime = { version = "39.0.2", default-features = false } +frame-support = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +frame-system = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +pallet-revive = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } scale-info = { version = "2.11.1", default-features = false } @@ -34,7 +36,7 @@ sandbox-runtime = { path = "sandbox-runtime", default-features = false } scale-value = "0.18.0" # can't use workspace dependency because of `cargo-contract` build not # working with workspace dependencies -frame-support = { version = "38.0.0", default-features = false } +frame-support = { git = "https://github.com/paritytech/polkadot-sdk", rev = "645878a27115db52e5d63115699b4bbb89034067", default-features = false } [lib] path = "lib.rs" diff --git a/integration-tests/public/runtime-call-contract/e2e_tests.rs b/integration-tests/public/runtime-call-contract/e2e_tests.rs index 13055cf947a..0a9ae532f84 100644 --- a/integration-tests/public/runtime-call-contract/e2e_tests.rs +++ b/integration-tests/public/runtime-call-contract/e2e_tests.rs @@ -29,6 +29,7 @@ async fn instantiate_and_get(mut client: Client) -> E2EResul .dry_run() .await?; let gas_required = flip_dry_run.exec_result.gas_required; + // todo do same thing as above with storage_deposit_limit // call pallet dispatchable client @@ -37,7 +38,7 @@ async fn instantiate_and_get(mut client: Client) -> E2EResul "ContractCaller", "contract_call_flip", vec![ - ink_e2e::subxt::dynamic::Value::from_bytes(contract.account_id), + ink_e2e::subxt::dynamic::Value::from_bytes(contract.addr), ink_e2e::subxt::ext::scale_value::serde::to_value( frame_support::weights::Weight::from_parts( gas_required.ref_time(), @@ -45,7 +46,8 @@ async fn instantiate_and_get(mut client: Client) -> E2EResul ), ) .unwrap(), - ink_e2e::subxt::ext::scale_value::serde::to_value(None::).unwrap(), + // todo + ink_e2e::subxt::ext::scale_value::serde::to_value(0u128).unwrap(), ], ) .await diff --git a/integration-tests/public/runtime-call-contract/sandbox-runtime/Cargo.toml b/integration-tests/public/runtime-call-contract/sandbox-runtime/Cargo.toml index fabffd81120..771e6192431 100644 --- a/integration-tests/public/runtime-call-contract/sandbox-runtime/Cargo.toml +++ b/integration-tests/public/runtime-call-contract/sandbox-runtime/Cargo.toml @@ -10,7 +10,7 @@ repository.workspace = true [dependencies] ink_sandbox = { path = "../../../../crates/e2e/sandbox" } -pallet-contract-caller = { path = "pallet-contract-caller", default-features = false } +pallet-revive-caller = { path = "pallet-revive-caller", default-features = false } frame-support = { workspace = true } frame-system = { workspace = true } codec = { workspace = true } @@ -19,5 +19,5 @@ scale-info = { workspace = true } [features] default = ["std"] std = [ - "pallet-contract-caller/std", + "pallet-revive-caller/std", ] diff --git a/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-contract-caller/src/executor.rs b/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-contract-caller/src/executor.rs deleted file mode 100644 index 214cf5fda91..00000000000 --- a/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-contract-caller/src/executor.rs +++ /dev/null @@ -1,59 +0,0 @@ -use crate::{ - AccountIdOf, - BalanceOf, -}; -use frame_support::pallet_prelude::Weight; -use ink::env::{ - call::{ - ExecutionInput, - Executor, - }, - Environment, -}; - -pub struct PalletContractsExecutor { - pub origin: AccountIdOf, - pub contract: AccountIdOf, - pub value: BalanceOf, - pub gas_limit: Weight, - pub storage_deposit_limit: Option>, - pub marker: core::marker::PhantomData, -} - -impl Executor for PalletContractsExecutor -where - E: Environment, - R: pallet_contracts::Config, -{ - type Error = sp_runtime::DispatchError; - - fn exec( - &self, - input: &ExecutionInput, - ) -> Result, Self::Error> - where - Args: codec::Encode, - Output: codec::Decode, - { - let data = codec::Encode::encode(&input); - - let result = pallet_contracts::Pallet::::bare_call( - self.origin.clone(), - self.contract.clone(), - self.value, - self.gas_limit, - self.storage_deposit_limit, - data, - pallet_contracts::DebugInfo::UnsafeDebug, - pallet_contracts::CollectEvents::Skip, - pallet_contracts::Determinism::Enforced, - ); - - let output = result.result?.data; - let result = codec::Decode::decode(&mut &output[..]).map_err(|_| { - sp_runtime::DispatchError::Other("Failed to decode contract output") - })?; - - Ok(result) - } -} diff --git a/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-contract-caller/Cargo.toml b/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-revive-caller/Cargo.toml similarity index 88% rename from integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-contract-caller/Cargo.toml rename to integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-revive-caller/Cargo.toml index bf1ea87a95a..76470b751d9 100644 --- a/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-contract-caller/Cargo.toml +++ b/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-revive-caller/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "pallet-contract-caller" +name = "pallet-revive-caller" version = "0.1.0" description = "Demonstrate calling an ink! contract from a pallet" authors = ["Use Ink "] @@ -19,7 +19,7 @@ frame-support = { workspace = true, default-features = false, features = ["try-r frame-system = { workspace = true, default-features = false } sp-runtime = { workspace = true, default-features = false } -pallet-contracts = { workspace = true, default-features = false } +pallet-revive = { workspace = true, default-features = false, features = ["try-runtime"] } flipper-traits = { path = "../../traits", default-features = false } ink = { path = "../../../../../crates/ink", features = ["no-panic-handler", "no-allocator"] } @@ -31,7 +31,7 @@ std = [ "frame-system/std", "sp-runtime/std", "scale-info/std", - "pallet-contracts/std", + "pallet-revive/std", "ink/std" ] try-runtime = [] diff --git a/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-revive-caller/src/executor.rs b/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-revive-caller/src/executor.rs new file mode 100644 index 00000000000..334d2f1a76b --- /dev/null +++ b/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-revive-caller/src/executor.rs @@ -0,0 +1,77 @@ +use crate::BalanceOf; +use frame_support::{ + pallet_prelude::Weight, + traits::IsType, +}; +use frame_system::pallet_prelude::OriginFor; +use ink::{ + env::{ + call::{ + ExecutionInput, + Executor, + }, + Environment, + }, + primitives::U256, + H160, +}; +use pallet_revive::{ + DepositLimit, + MomentOf, +}; +use sp_runtime::traits::Bounded; + +pub struct PalletReviveExecutor { + //pub origin: AccountIdOf, + pub origin: OriginFor, + pub contract: H160, + pub value: BalanceOf, + pub gas_limit: Weight, + //pub storage_deposit_limit: Option>, + //pub storage_deposit_limit: u128, + pub marker: core::marker::PhantomData, +} + +impl Executor for PalletReviveExecutor +where + E: Environment, + R: pallet_revive::Config, + + BalanceOf: Into + TryFrom + Bounded, + MomentOf: Into, + ::Hash: IsType, +{ + type Error = sp_runtime::DispatchError; + + fn exec( + &self, + input: &ExecutionInput, + ) -> Result, Self::Error> + where + Args: codec::Encode, + Output: codec::Decode, + { + let data = codec::Encode::encode(&input); + + let result = pallet_revive::Pallet::::bare_call( + self.origin.clone(), + // ::AddressMapper::to_account_id(&self. + // contract), + self.contract, + self.value, + self.gas_limit, + // self.storage_deposit_limit, + DepositLimit::Unchecked, // todo + data, + pallet_revive::DebugInfo::UnsafeDebug, + pallet_revive::CollectEvents::Skip, + ); + + let output = result.result?.data; + let result = codec::Decode::decode(&mut &output[..]).map_err(|_| { + sp_runtime::DispatchError::Other("Failed to decode contract output") + })?; + + Ok(result) + } +} diff --git a/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-contract-caller/src/lib.rs b/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-revive-caller/src/lib.rs similarity index 58% rename from integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-contract-caller/src/lib.rs rename to integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-revive-caller/src/lib.rs index cf7abdd411a..f73677640c0 100644 --- a/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-contract-caller/src/lib.rs +++ b/integration-tests/public/runtime-call-contract/sandbox-runtime/pallet-revive-caller/src/lib.rs @@ -12,8 +12,8 @@ use frame_support::{ }; pub use pallet::*; -type AccountIdOf = ::AccountId; -type BalanceOf = <::Currency as Inspect< +//type AccountIdOf = ::AccountId; +type BalanceOf = <::Currency as Inspect< ::AccountId, >>::Balance; @@ -26,12 +26,17 @@ pub mod pallet { traits::fungible::Inspect, }; use frame_system::pallet_prelude::*; + use pallet_revive::{ + evm::*, + MomentOf, + }; + use sp_runtime::traits::Bounded; #[pallet::pallet] pub struct Pallet(_); #[pallet::config] - pub trait Config: frame_system::Config + pallet_contracts::Config {} + pub trait Config: frame_system::Config + pallet_revive::Config {} #[pallet::error] pub enum Error {} @@ -40,28 +45,34 @@ pub mod pallet { impl Pallet where [u8; 32]: From<::AccountId>, - <::Currency as Inspect< + <::Currency as Inspect< ::AccountId, >>::Balance: From, + + BalanceOf: Into + TryFrom + Bounded, + MomentOf: Into, + ::Hash: IsType, { /// Call the flip method on the contract at the given `contract` account. #[pallet::call_index(0)] - #[pallet::weight(::call().saturating_add(*gas_limit))] + #[pallet::weight(::call().saturating_add(*gas_limit))] pub fn contract_call_flip( origin: OriginFor, - contract: AccountIdOf, + contract: H160, gas_limit: Weight, - storage_deposit_limit: Option>, + // todo remove + _storage_deposit_limit: u128, + //storage_deposit_limit: Option>, ) -> DispatchResult { - let who = ensure_signed(origin)?; + let _who = ensure_signed(origin.clone())?; let executor = - executor::PalletContractsExecutor:: { - origin: who.clone(), - contract: contract.clone(), + executor::PalletReviveExecutor:: { + origin: origin.clone(), + contract, value: 0.into(), gas_limit, - storage_deposit_limit, + //storage_deposit_limit, marker: Default::default(), }; diff --git a/integration-tests/public/runtime-call-contract/sandbox-runtime/src/lib.rs b/integration-tests/public/runtime-call-contract/sandbox-runtime/src/lib.rs index 78a39d89705..65feb89bc0c 100644 --- a/integration-tests/public/runtime-call-contract/sandbox-runtime/src/lib.rs +++ b/integration-tests/public/runtime-call-contract/sandbox-runtime/src/lib.rs @@ -5,7 +5,7 @@ #![cfg_attr(not(feature = "std"), no_std)] ink_sandbox::create_sandbox!(ContractCallerSandbox, ContractCallerSandboxRuntime, (), (), { - ContractCaller: pallet_contract_caller, + ContractCaller: pallet_revive_caller, }); -impl pallet_contract_caller::Config for ContractCallerSandboxRuntime {} +impl pallet_revive_caller::Config for ContractCallerSandboxRuntime {} diff --git a/integration-tests/public/static-buffer/README.md b/integration-tests/public/static-buffer/README.md index eb4f58723db..01fbc130920 100644 --- a/integration-tests/public/static-buffer/README.md +++ b/integration-tests/public/static-buffer/README.md @@ -1,17 +1,17 @@ # Static buffer configuration demo This is a dummy contract illustrating how the [static buffer](/ARCHITECTURE.md#communication-with-the-pallet) -can be be configured using the environmental variables. +can be configured using the environmental variables. Simply, run: ```bash cargo clean -INK_STATIC_BUFFER_SIZE=30 cargo test -F e2e-tests +INK_STATIC_BUFFER_SIZE=32 cargo test -F e2e-tests ``` This will configure the buffer to have enough space to instantiate the contract, -but not enough space to retrieve the caller's address as it is of 32 bytes, -but we only allocated 30 bytes to the contract. +but not enough space to retrieve two times the caller's address as it is of 40 bytes, +but we only allocated 32 bytes to the contract. ## Note You must run `cargo clean` every time you want to modify the buffer size diff --git a/integration-tests/public/static-buffer/lib.rs b/integration-tests/public/static-buffer/lib.rs index 9f813f46551..8db86cbce5d 100644 --- a/integration-tests/public/static-buffer/lib.rs +++ b/integration-tests/public/static-buffer/lib.rs @@ -9,6 +9,7 @@ pub mod static_buffer { #[allow(unused_imports)] use ink::env::BUFFER_SIZE; + #[ink(storage)] pub struct StaticBuffer { value: bool, @@ -28,10 +29,11 @@ pub mod static_buffer { } /// Returns the caller of the contract. - /// Should panic if the buffer size is less than 32 bytes. + /// Should panic if the buffer size is less than 40 bytes (2 * 20 bytes + /// for each `H160`). #[ink(message)] - pub fn get_caller(&self) -> AccountId { - self.env().caller() + pub fn get_caller(&self) -> (ink::H160, ink::H160) { + (self.env().caller(), self.env().caller()) } #[ink(message)] @@ -48,18 +50,6 @@ pub mod static_buffer { } } - #[cfg(test)] - mod tests { - use super::*; - - #[ink::test] - #[should_panic(expected = "the output buffer is too small!")] - fn run_out_buffer_memory() { - let flipper = StaticBuffer::new(false); - flipper.get_caller() - } - } - #[cfg(all(test, feature = "e2e-tests"))] mod e2e_tests { use super::*; @@ -67,12 +57,22 @@ pub mod static_buffer { type E2EResult = std::result::Result>; + fn assert_buffer_size() { + // this is because we need 32 byte for the instantiation to succeed. + // for the call we provoke an exhaustion of the static buffer. + const ERR: &str = "For this test the env variable `INK_STATIC_BUFFER_SIZE` needs to be set to `32`"; + let buffer_size = std::env::var("INK_STATIC_BUFFER_SIZE") + .unwrap_or_else(|err| panic!("{} {}", ERR, err)); + assert_eq!(buffer_size, "32", "{}", ERR); + } + #[ink_e2e::test] async fn e2e_run_out_of_buffer_memory( mut client: Client, ) -> E2EResult<()> { // given - let mut constructor = StaticBufferRef::new(false); + assert_buffer_size(); + let mut constructor = StaticBufferRef::new(true); let contract = client .instantiate("static_buffer", &ink_e2e::alice(), &mut constructor) .submit() @@ -82,13 +82,15 @@ pub mod static_buffer { // when let get = call_builder.get_caller(); - // then panics if `INK_STATIC_BUFFER_SIZE` is less than 32 bytes. + + // then panics if `INK_STATIC_BUFFER_SIZE` is less than 20 bytes. let res = client.call(&ink_e2e::bob(), &get).dry_run().await; - println!("{}", super::BUFFER_SIZE); assert!( res.is_err(), - "Buffer size was larger than expected: {}", - super::BUFFER_SIZE.to_string() + "Call should have failed, but succeeded. Likely because the \ + used buffer size was too large: {} {:?}", + super::BUFFER_SIZE.to_string(), + std::env::var("INK_STATIC_BUFFER_SIZE") ); Ok(()) @@ -97,6 +99,7 @@ pub mod static_buffer { #[ink_e2e::test] async fn buffer(mut client: Client) -> E2EResult<()> { // given + assert_buffer_size(); let mut constructor = StaticBufferRef::new_default(); // when @@ -116,8 +119,8 @@ pub mod static_buffer { let value = value.unwrap(); let padding = value.0; let align = value.1; - assert_eq!(padding, 8); - assert_eq!(align, 4); + assert_eq!(align, 8, "align incorrect, should be 8"); + assert_eq!(padding, 4, "padding incorrect, should be 4"); Ok(()) } } diff --git a/integration-tests/public/trait-dyn-cross-contract-calls/lib.rs b/integration-tests/public/trait-dyn-cross-contract-calls/lib.rs index d49911ba522..12d1cdf2bce 100644 --- a/integration-tests/public/trait-dyn-cross-contract-calls/lib.rs +++ b/integration-tests/public/trait-dyn-cross-contract-calls/lib.rs @@ -21,7 +21,7 @@ pub mod caller { impl Caller { /// Creates a new caller smart contract around the `incrementer` account id. #[ink(constructor)] - pub fn new(incrementer: AccountId) -> Self { + pub fn new(incrementer: ink::H160) -> Self { Self { incrementer: incrementer.into(), } @@ -89,7 +89,7 @@ mod e2e_tests { .expect("instantiate failed"); let incrementer_call = incrementer.call_builder::(); - let mut constructor = CallerRef::new(incrementer.account_id.clone()); + let mut constructor = CallerRef::new(incrementer.addr.clone()); let caller = client .instantiate( diff --git a/integration-tests/public/trait-erc20/lib.rs b/integration-tests/public/trait-erc20/lib.rs index 56c9c739751..594647b4f9d 100644 --- a/integration-tests/public/trait-erc20/lib.rs +++ b/integration-tests/public/trait-erc20/lib.rs @@ -2,7 +2,11 @@ #[ink::contract] mod erc20 { - use ink::storage::Mapping; + use ink::{ + storage::Mapping, + H160, + U256, + }; /// The ERC-20 error types. #[derive(Debug, PartialEq, Eq)] @@ -22,33 +26,28 @@ mod erc20 { pub trait BaseErc20 { /// Returns the total token supply. #[ink(message)] - fn total_supply(&self) -> Balance; + fn total_supply(&self) -> U256; /// Returns the account balance for the specified `owner`. #[ink(message)] - fn balance_of(&self, owner: AccountId) -> Balance; + fn balance_of(&self, owner: H160) -> U256; /// Returns the amount which `spender` is still allowed to withdraw from `owner`. #[ink(message)] - fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance; + fn allowance(&self, owner: H160, spender: H160) -> U256; /// Transfers `value` amount of tokens from the caller's account to account `to`. #[ink(message)] - fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()>; + fn transfer(&mut self, to: H160, value: U256) -> Result<()>; /// Allows `spender` to withdraw from the caller's account multiple times, up to /// the `value` amount. #[ink(message)] - fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()>; + fn approve(&mut self, spender: H160, value: U256) -> Result<()>; /// Transfers `value` tokens on the behalf of `from` to the account `to`. #[ink(message)] - fn transfer_from( - &mut self, - from: AccountId, - to: AccountId, - value: Balance, - ) -> Result<()>; + fn transfer_from(&mut self, from: H160, to: H160, value: U256) -> Result<()>; } /// A simple ERC-20 contract. @@ -56,23 +55,23 @@ mod erc20 { #[derive(Default)] pub struct Erc20 { /// Total token supply. - total_supply: Balance, + total_supply: U256, /// Mapping from owner to number of owned token. - balances: Mapping, + balances: Mapping, /// Mapping of the token amount which an account is allowed to withdraw /// from another account. - allowances: Mapping<(AccountId, AccountId), Balance>, + allowances: Mapping<(H160, H160), U256>, } /// Event emitted when a token transfer occurs. #[ink(event)] pub struct Transfer { #[ink(topic)] - from: Option, + from: Option, #[ink(topic)] - to: Option, + to: Option, #[ink(topic)] - value: Balance, + value: U256, } /// Event emitted when an approval occurs that `spender` is allowed to withdraw @@ -80,17 +79,17 @@ mod erc20 { #[ink(event)] pub struct Approval { #[ink(topic)] - owner: AccountId, + owner: H160, #[ink(topic)] - spender: AccountId, + spender: H160, #[ink(topic)] - value: Balance, + value: U256, } impl Erc20 { /// Creates a new ERC-20 contract with the specified initial supply. #[ink(constructor)] - pub fn new(total_supply: Balance) -> Self { + pub fn new(total_supply: U256) -> Self { let mut balances = Mapping::default(); let caller = Self::env().caller(); balances.insert(caller, &total_supply); @@ -110,7 +109,7 @@ mod erc20 { impl BaseErc20 for Erc20 { /// Returns the total token supply. #[ink(message)] - fn total_supply(&self) -> Balance { + fn total_supply(&self) -> U256 { self.total_supply } @@ -118,7 +117,7 @@ mod erc20 { /// /// Returns `0` if the account is non-existent. #[ink(message)] - fn balance_of(&self, owner: AccountId) -> Balance { + fn balance_of(&self, owner: H160) -> U256 { self.balance_of_impl(&owner) } @@ -126,7 +125,7 @@ mod erc20 { /// /// Returns `0` if no allowance has been set. #[ink(message)] - fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance { + fn allowance(&self, owner: H160, spender: H160) -> U256 { self.allowance_impl(&owner, &spender) } @@ -139,7 +138,7 @@ mod erc20 { /// Returns `InsufficientBalance` error if there are not enough tokens on /// the caller's account balance. #[ink(message)] - fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()> { + fn transfer(&mut self, to: H160, value: U256) -> Result<()> { let from = self.env().caller(); self.transfer_from_to(&from, &to, value) } @@ -152,7 +151,7 @@ mod erc20 { /// /// An `Approval` event is emitted. #[ink(message)] - fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()> { + fn approve(&mut self, spender: H160, value: U256) -> Result<()> { let owner = self.env().caller(); self.allowances.insert((&owner, &spender), &value); self.env().emit_event(Approval { @@ -178,12 +177,7 @@ mod erc20 { /// Returns `InsufficientBalance` error if there are not enough tokens on /// the account balance of `from`. #[ink(message)] - fn transfer_from( - &mut self, - from: AccountId, - to: AccountId, - value: Balance, - ) -> Result<()> { + fn transfer_from(&mut self, from: H160, to: H160, value: U256) -> Result<()> { let caller = self.env().caller(); let allowance = self.allowance_impl(&from, &caller); if allowance < value { @@ -209,7 +203,7 @@ mod erc20 { /// Prefer to call this method over `balance_of` since this /// works using references which are more efficient in Wasm. #[inline] - fn balance_of_impl(&self, owner: &AccountId) -> Balance { + fn balance_of_impl(&self, owner: &H160) -> U256 { self.balances.get(owner).unwrap_or_default() } @@ -222,7 +216,7 @@ mod erc20 { /// Prefer to call this method over `allowance` since this /// works using references which are more efficient in Wasm. #[inline] - fn allowance_impl(&self, owner: &AccountId, spender: &AccountId) -> Balance { + fn allowance_impl(&self, owner: &H160, spender: &H160) -> U256 { self.allowances.get((owner, spender)).unwrap_or_default() } @@ -236,9 +230,9 @@ mod erc20 { /// the caller's account balance. fn transfer_from_to( &mut self, - from: &AccountId, - to: &AccountId, - value: Balance, + from: &H160, + to: &H160, + value: U256, ) -> Result<()> { let from_balance = self.balance_of_impl(from); if from_balance < value { @@ -275,9 +269,9 @@ mod erc20 { fn assert_transfer_event( event: &ink::env::test::EmittedEvent, - expected_from: Option, - expected_to: Option, - expected_value: Balance, + expected_from: Option, + expected_to: Option, + expected_value: U256, ) { let decoded_event = ::decode(&mut &event.data[..]) @@ -309,8 +303,7 @@ mod erc20 { let mut expected_topics = Vec::new(); expected_topics.push( - ink::blake2x256!("Transfer(Option,Option,Balance)") - .into(), + ink::blake2x256!("Transfer(Option,Option,U256)").into(), ); if let Some(from) = expected_from { expected_topics.push(encoded_into_hash(from)); @@ -337,7 +330,8 @@ mod erc20 { #[ink::test] fn new_works() { // Constructor works. - let initial_supply = 100; + set_caller(H160::from([0x01; 20])); + let initial_supply = 100.into(); let erc20 = Erc20::new(initial_supply); // The `BaseErc20` trait has indeed been implemented. @@ -350,8 +344,8 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), - 100, + Some(H160::from([0x01; 20])), + 100.into(), ); } @@ -359,56 +353,58 @@ mod erc20 { #[ink::test] fn total_supply_works() { // Constructor works. - let initial_supply = 100; + set_caller(H160::from([0x01; 20])); + let initial_supply = 100.into(); let erc20 = Erc20::new(initial_supply); // Transfer event triggered during initial construction. let emitted_events = ink::env::test::recorded_events().collect::>(); assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), - 100, + Some(H160::from([0x01; 20])), + 100.into(), ); // Get the token total supply. - assert_eq!(erc20.total_supply(), 100); + assert_eq!(erc20.total_supply(), 100.into()); } /// Get the actual balance of an account. #[ink::test] fn balance_of_works() { + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); + // Constructor works - let initial_supply = 100; + let initial_supply = 100.into(); let erc20 = Erc20::new(initial_supply); // Transfer event triggered during initial construction let emitted_events = ink::env::test::recorded_events().collect::>(); assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), - 100, + Some(H160::from([0x01; 20])), + 100.into(), ); - let accounts = - ink::env::test::default_accounts::(); // Alice owns all the tokens on contract instantiation - assert_eq!(erc20.balance_of(accounts.alice), 100); + assert_eq!(erc20.balance_of(accounts.alice), 100.into()); // Bob does not owns tokens - assert_eq!(erc20.balance_of(accounts.bob), 0); + assert_eq!(erc20.balance_of(accounts.bob), U256::zero()); } #[ink::test] fn transfer_works() { + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); + // Constructor works. - let initial_supply = 100; + let initial_supply = 100.into(); let mut erc20 = Erc20::new(initial_supply); // Transfer event triggered during initial construction. - let accounts = - ink::env::test::default_accounts::(); - - assert_eq!(erc20.balance_of(accounts.bob), 0); + assert_eq!(erc20.balance_of(accounts.bob), U256::zero()); // Alice transfers 10 tokens to Bob. - assert_eq!(erc20.transfer(accounts.bob, 10), Ok(())); + assert_eq!(erc20.transfer(accounts.bob, U256::from(10)), Ok(())); // Bob owns 10 tokens. - assert_eq!(erc20.balance_of(accounts.bob), 10); + assert_eq!(erc20.balance_of(accounts.bob), U256::from(10)); let emitted_events = ink::env::test::recorded_events().collect::>(); assert_eq!(emitted_events.len(), 2); @@ -416,39 +412,40 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), - 100, + Some(H160::from([0x01; 20])), + 100.into(), ); // Check the second transfer event relating to the actual trasfer. assert_transfer_event( &emitted_events[1], - Some(AccountId::from([0x01; 32])), - Some(AccountId::from([0x02; 32])), - 10, + Some(H160::from([0x01; 20])), + Some(H160::from([0x02; 20])), + 10.into(), ); } #[ink::test] fn invalid_transfer_should_fail() { // Constructor works. - let initial_supply = 100; + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); + + let initial_supply = 100.into(); let mut erc20 = Erc20::new(initial_supply); - let accounts = - ink::env::test::default_accounts::(); - assert_eq!(erc20.balance_of(accounts.bob), 0); + assert_eq!(erc20.balance_of(accounts.bob), U256::zero()); // Set Bob as caller set_caller(accounts.bob); - // Bob fails to transfers 10 tokens to Eve. + // Bob fails to transfer 10 tokens to Eve. assert_eq!( - erc20.transfer(accounts.eve, 10), + erc20.transfer(accounts.eve, 10.into()), Err(Error::InsufficientBalance) ); // Alice owns all the tokens. - assert_eq!(erc20.balance_of(accounts.alice), 100); - assert_eq!(erc20.balance_of(accounts.bob), 0); - assert_eq!(erc20.balance_of(accounts.eve), 0); + assert_eq!(erc20.balance_of(accounts.alice), 100.into()); + assert_eq!(erc20.balance_of(accounts.bob), U256::zero()); + assert_eq!(erc20.balance_of(accounts.eve), U256::zero()); // Transfer event triggered during initial construction. let emitted_events = ink::env::test::recorded_events().collect::>(); @@ -456,27 +453,30 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), - 100, + Some(H160::from([0x01; 20])), + 100.into(), ); } #[ink::test] fn transfer_from_works() { // Constructor works. - let initial_supply = 100; + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); + + let initial_supply = 100.into(); let mut erc20 = Erc20::new(initial_supply); + // Transfer event triggered during initial construction. - let accounts = - ink::env::test::default_accounts::(); + let accounts = ink::env::test::default_accounts(); // Bob fails to transfer tokens owned by Alice. assert_eq!( - erc20.transfer_from(accounts.alice, accounts.eve, 10), + erc20.transfer_from(accounts.alice, accounts.eve, 10.into()), Err(Error::InsufficientAllowance) ); // Alice approves Bob for token transfers on her behalf. - assert_eq!(erc20.approve(accounts.bob, 10), Ok(())); + assert_eq!(erc20.approve(accounts.bob, U256::from(10)), Ok(())); // The approve event takes place. assert_eq!(ink::env::test::recorded_events().count(), 2); @@ -486,11 +486,11 @@ mod erc20 { // Bob transfers tokens from Alice to Eve. assert_eq!( - erc20.transfer_from(accounts.alice, accounts.eve, 10), + erc20.transfer_from(accounts.alice, accounts.eve, 10.into()), Ok(()) ); // Eve owns tokens. - assert_eq!(erc20.balance_of(accounts.eve), 10); + assert_eq!(erc20.balance_of(accounts.eve), U256::from(10)); // Check all transfer events that happened during the previous calls: let emitted_events = ink::env::test::recorded_events().collect::>(); @@ -498,29 +498,29 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), - 100, + Some(H160::from([0x01; 20])), + 100.into(), ); // The second event `emitted_events[1]` is an Approve event that we skip // checking. assert_transfer_event( &emitted_events[2], - Some(AccountId::from([0x01; 32])), - Some(AccountId::from([0x05; 32])), - 10, + Some(H160::from([0x01; 20])), + Some(H160::from([0x05; 20])), + 10.into(), ); } #[ink::test] fn allowance_must_not_change_on_failed_transfer() { - let initial_supply = 100; + let accounts = ink::env::test::default_accounts(); + set_caller(accounts.alice); + let initial_supply = 100.into(); let mut erc20 = Erc20::new(initial_supply); - let accounts = - ink::env::test::default_accounts::(); // Alice approves Bob for token transfers on her behalf. let alice_balance = erc20.balance_of(accounts.alice); - let initial_allowance = alice_balance + 2; + let initial_allowance = alice_balance + U256::from(2); assert_eq!(erc20.approve(accounts.bob, initial_allowance), Ok(())); // Set Bob as caller. @@ -529,7 +529,11 @@ mod erc20 { // Bob tries to transfer tokens from Alice to Eve. let emitted_events_before = ink::env::test::recorded_events(); assert_eq!( - erc20.transfer_from(accounts.alice, accounts.eve, alice_balance + 1), + erc20.transfer_from( + accounts.alice, + accounts.eve, + alice_balance + U256::from(1) + ), Err(Error::InsufficientBalance) ); // Allowance must have stayed the same @@ -542,8 +546,8 @@ mod erc20 { assert_eq!(emitted_events_before.count(), emitted_events_after.count()); } - fn set_caller(sender: AccountId) { - ink::env::test::set_caller::(sender); + fn set_caller(sender: H160) { + ink::env::test::set_caller(sender); } } } diff --git a/integration-tests/public/trait-flipper/lib.rs b/integration-tests/public/trait-flipper/lib.rs index 7be1ac641ed..9077c4e21b6 100644 --- a/integration-tests/public/trait-flipper/lib.rs +++ b/integration-tests/public/trait-flipper/lib.rs @@ -1,7 +1,7 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] #![allow(clippy::new_without_default)] -#[ink::trait_definition] +#[::ink::trait_definition] pub trait Flip { /// Flips the current value of the Flipper's boolean. #[ink(message)] @@ -12,7 +12,7 @@ pub trait Flip { fn get(&self) -> bool; } -#[ink::contract] +#[::ink::contract] pub mod flipper { use super::Flip; @@ -25,9 +25,7 @@ pub mod flipper { /// Creates a new flipper smart contract initialized to `false`. #[ink(constructor)] pub fn new() -> Self { - Self { - value: Default::default(), - } + Self { value: true } } } @@ -47,13 +45,13 @@ pub mod flipper { mod tests { use super::*; - #[ink::test] + #[::ink::test] fn default_works() { let flipper = Flipper::new(); assert!(!flipper.get()); } - #[ink::test] + #[::ink::test] fn it_works() { let mut flipper = Flipper::new(); // Can call using universal call syntax using the trait. diff --git a/integration-tests/public/upgradeable-contracts/delegator/delegatee/lib.rs b/integration-tests/public/upgradeable-contracts/delegator/delegatee/lib.rs index af761b5bd55..846bdd7ac7c 100644 --- a/integration-tests/public/upgradeable-contracts/delegator/delegatee/lib.rs +++ b/integration-tests/public/upgradeable-contracts/delegator/delegatee/lib.rs @@ -2,13 +2,16 @@ #[ink::contract] pub mod delegatee { - use ink::storage::{ - traits::ManualKey, - Mapping, + use ink::{ + storage::{ + traits::ManualKey, + Mapping, + }, + H160, }; #[ink(storage)] pub struct Delegatee { - addresses: Mapping>, + addresses: Mapping>, counter: i32, // Uncommenting below line will break storage compatibility. // flag: bool, @@ -22,9 +25,16 @@ pub mod delegatee { #[allow(clippy::new_without_default)] #[ink(constructor)] pub fn new() -> Self { + /* unreachable!( "Constructors are not called when upgrading using `set_code_hash`." ) + + */ + Self { + addresses: Mapping::default(), + counter: 0, + } } /// Increments the current value. @@ -39,5 +49,14 @@ pub mod delegatee { let caller = self.env().caller(); self.addresses.insert(caller, &self.counter); } + + /// Increments the current value. + /// todo + #[ink(message)] + pub fn code_hash(&self) -> ink::H256 { + self.env() + .code_hash(&self.env().address()) + .expect("no code hash could be found") + } } } diff --git a/integration-tests/public/upgradeable-contracts/delegator/delegatee2/lib.rs b/integration-tests/public/upgradeable-contracts/delegator/delegatee2/lib.rs index 447db46e00f..6640106b341 100644 --- a/integration-tests/public/upgradeable-contracts/delegator/delegatee2/lib.rs +++ b/integration-tests/public/upgradeable-contracts/delegator/delegatee2/lib.rs @@ -2,13 +2,16 @@ #[ink::contract] pub mod delegatee2 { - use ink::storage::{ - traits::ManualKey, - Mapping, + use ink::{ + storage::{ + traits::ManualKey, + Mapping, + }, + H160, }; #[ink(storage)] pub struct Delegatee2 { - addresses: Mapping>, + addresses: Mapping>, counter: i32, } @@ -16,9 +19,15 @@ pub mod delegatee2 { #[allow(clippy::new_without_default)] #[ink(constructor)] pub fn new() -> Self { + /* unreachable!( "Constructors are not called when upgrading using `set_code_hash`." ) + */ + Self { + addresses: Mapping::default(), + counter: 0, + } } /// Increments the current value. @@ -33,5 +42,14 @@ pub mod delegatee2 { let caller = self.env().caller(); self.addresses.insert(caller, &self.counter); } + + /// Increments the current value. + /// todo + #[ink(message)] + pub fn code_hash(&self) -> ink::H256 { + self.env() + .code_hash(&self.env().address()) + .expect("no code hash could be found") + } } } diff --git a/integration-tests/public/upgradeable-contracts/delegator/lib.rs b/integration-tests/public/upgradeable-contracts/delegator/lib.rs index 75b43bb04ea..2d06c253db5 100644 --- a/integration-tests/public/upgradeable-contracts/delegator/lib.rs +++ b/integration-tests/public/upgradeable-contracts/delegator/lib.rs @@ -12,18 +12,20 @@ pub mod delegator { CallFlags, DefaultEnvironment, }, + primitives::H256, storage::{ traits::ManualKey, Lazy, Mapping, }, + H160, }; #[ink(storage)] pub struct Delegator { - addresses: Mapping>, + addresses: Mapping>, counter: i32, - delegate_to: Lazy, + delegate_to: Lazy<(H256, H160)>, } impl Delegator { @@ -33,15 +35,20 @@ pub mod delegator { /// Additionally, this code hash will be locked to prevent its deletion, since /// this contract depends on it. #[ink(constructor)] - pub fn new(init_value: i32, hash: Hash) -> Self { + pub fn new(init_value: i32, hash: H256, addr: H160) -> Self { let v = Mapping::new(); + let mut delegate_to = Lazy::new(); + delegate_to.set(&(hash, addr)); + // todo locking is no longer necessary, as the contract needs + // to be instantiated anyway. and the code can anyway not be removed, + // as long as there is a contract for it. + /* // Initialize the hash of the contract to delegate to. // Adds a delegate dependency lock, ensuring that the delegated to code cannot // be removed. - let mut delegate_to = Lazy::new(); - delegate_to.set(&hash); Self::env().lock_delegate_dependency(&hash); + */ Self { addresses: v, @@ -56,12 +63,13 @@ pub mod delegator { /// - Adds a new delegate dependency lock, ensuring that the new delegated to code /// cannot be removed. #[ink(message)] - pub fn update_delegate_to(&mut self, hash: Hash) { - if let Some(old_hash) = self.delegate_to.get() { - self.env().unlock_delegate_dependency(&old_hash) + pub fn update_delegate_to(&mut self, hash: H256, addr: H160) { + if let Some(delegate_to) = self.delegate_to.get() { + let _old_hash = delegate_to.0; + //self.env().unlock_delegate_dependency(&old_hash) } - self.env().lock_delegate_dependency(&hash); - self.delegate_to.set(&hash); + //self.env().lock_delegate_dependency(&hash); + self.delegate_to.set(&(hash, addr)); } /// Increment the current value using delegate call. @@ -69,7 +77,7 @@ pub mod delegator { pub fn inc_delegate(&mut self) { let selector = ink::selector_bytes!("inc"); let _ = build_call::() - .delegate(self.delegate_to()) + .delegate(self.delegate_to().1) // We specify `CallFlags::TAIL_CALL` to use the delegatee last memory frame // as the end of the execution cycle. // So any mutations to `Packed` types, made by delegatee, @@ -91,7 +99,7 @@ pub mod delegator { pub fn add_entry_delegate(&mut self) { let selector = ink::selector_bytes!("append_address_value"); let _ = build_call::() - .delegate(self.delegate_to()) + .delegate(self.delegate_to().1) .exec_input(ExecutionInput::new(Selector::new(selector))) .returns::<()>() .try_invoke(); @@ -105,11 +113,11 @@ pub mod delegator { /// Returns the current value of the address. #[ink(message)] - pub fn get_value(&self, address: AccountId) -> (AccountId, Option) { + pub fn get_value(&self, address: H160) -> (H160, Option) { (self.env().caller(), self.addresses.get(address)) } - fn delegate_to(&self) -> Hash { + fn delegate_to(&self) -> (H256, H160) { self.delegate_to .get() .expect("delegate_to always has a value") @@ -119,6 +127,14 @@ pub mod delegator { #[cfg(all(test, feature = "e2e-tests"))] mod e2e_tests { use super::*; + use delegatee::delegatee::{ + Delegatee, + DelegateeRef, + }; + use delegatee2::delegatee2::{ + Delegatee2, + Delegatee2Ref, + }; use ink_e2e::{ ChainBackend, ContractsBackend, @@ -135,14 +151,31 @@ pub mod delegator { .create_and_fund_account(&ink_e2e::alice(), 10_000_000_000_000) .await; + /* let code_hash = client .upload("delegatee", &origin) .submit() .await .expect("upload `delegatee` failed") .code_hash; + */ - let mut constructor = DelegatorRef::new(0, code_hash); + let mut constructor = DelegateeRef::new(); + let contract = client + .instantiate("delegatee", &origin, &mut constructor) + .submit() + .await + .expect("instantiate `delegatee` failed"); + let call_builder = contract.call_builder::(); + let call_delegatee = call_builder.code_hash(); + let result = client + .call(&origin, &call_delegatee) + .dry_run() + .await + .expect("code_hash call failed"); + let code_hash = result.return_value(); + + let mut constructor = DelegatorRef::new(0, code_hash, contract.addr); let contract = client .instantiate("delegator", &origin, &mut constructor) .submit() @@ -187,15 +220,32 @@ pub mod delegator { .create_and_fund_account(&ink_e2e::alice(), 10_000_000_000_000) .await; + /* let code_hash = client .upload("delegatee", &origin) .submit() .await .expect("upload `delegatee` failed") .code_hash; + */ + + let mut constructor = DelegateeRef::new(); + let contract = client + .instantiate("delegatee", &origin, &mut constructor) + .submit() + .await + .expect("instantiate `delegatee` failed"); + let call_builder = contract.call_builder::(); + let call_delegatee = call_builder.code_hash(); + let result = client + .call(&origin, &call_delegatee) + .dry_run() + .await + .expect("code_hash call failed"); + let code_hash = result.return_value(); // given - let mut constructor = DelegatorRef::new(10, code_hash); + let mut constructor = DelegatorRef::new(10, code_hash, contract.addr); let contract = client .instantiate("delegator", &origin, &mut constructor) .submit() @@ -214,7 +264,9 @@ pub mod delegator { // assigned to Alice. let expected_value = 10; // Alice's address - let address = AccountId::from(origin.public_key().to_account_id().0); + // todo + let acc = origin.public_key().to_account_id().0; + let address = H160::from_slice(&acc[0..20]); let call_get_value = call_builder.get_value(address); let call_get_result = client @@ -242,21 +294,55 @@ pub mod delegator { .create_and_fund_account(&ink_e2e::alice(), 10_000_000_000_000) .await; + /* let code_hash = client .upload("delegatee", &origin) .submit() .await .expect("upload `delegatee` failed") .code_hash; + */ + let mut constructor = DelegateeRef::new(); + let contract = client + .instantiate("delegatee", &origin, &mut constructor) + .submit() + .await + .expect("instantiate `delegatee` failed"); + let call_builder = contract.call_builder::(); + let call_delegatee = call_builder.code_hash(); + let result = client + .call(&origin, &call_delegatee) + .dry_run() + .await + .expect("code_hash call to delegatee failed"); + let code_hash = result.return_value(); + let delegatee_addr = contract.addr; + /* let code_hash2 = client .upload("delegatee2", &origin) .submit() .await .expect("upload `delegatee2` failed") .code_hash; + */ + let mut constructor = Delegatee2Ref::new(); + let contract2 = client + .instantiate("delegatee2", &origin, &mut constructor) + .submit() + .await + .expect("instantiate `delegatee2` failed"); + let call_builder2 = contract.call_builder::(); + let call_delegatee2 = call_builder2.code_hash(); + let result2 = client + .call(&origin, &call_delegatee2) + .dry_run() + .await + .expect("code_hash call to delegatee2 failed"); + let code_hash2 = result2.return_value(); + let delegatee2_addr = contract2.addr; - let mut constructor = DelegatorRef::new(10, code_hash); + let mut constructor = DelegatorRef::new(10, code_hash, delegatee_addr); let contract = client .instantiate("delegator", &origin, &mut constructor) .submit() @@ -265,14 +351,18 @@ pub mod delegator { let mut call_builder = contract.call_builder::(); // when - let call_delegate = call_builder.update_delegate_to(code_hash2); + let call_delegate = + call_builder.update_delegate_to(code_hash2, delegatee2_addr); let result = client.call(&origin, &call_delegate).submit().await; assert!(result.is_ok(), "update_delegate_to failed."); // then + // todo this doesn't work right now, as the contract is still alive and + // thus the code in use. // remove the original delegatee code. // should succeed because the delegate dependency has been removed. + /* let original_code_removed = client.remove_code(&origin, code_hash).submit().await; assert!(original_code_removed.is_ok()); @@ -281,6 +371,7 @@ pub mod delegator { // should fail because of the delegate dependency. let new_code_removed = client.remove_code(&origin, code_hash2).submit().await; assert!(new_code_removed.is_err()); + */ Ok(()) } diff --git a/integration-tests/public/upgradeable-contracts/set-code-hash-migration/e2e_tests.rs b/integration-tests/public/upgradeable-contracts/set-code-hash-migration/e2e_tests.rs index dbbd029a8b0..12637b2810c 100644 --- a/integration-tests/public/upgradeable-contracts/set-code-hash-migration/e2e_tests.rs +++ b/integration-tests/public/upgradeable-contracts/set-code-hash-migration/e2e_tests.rs @@ -37,7 +37,6 @@ async fn migration_works(mut client: Client) -> E2EResult<() .await .expect("uploading `updated-incrementer` failed") .code_hash; - let new_code_hash = new_code_hash.as_ref().try_into().unwrap(); // Upload the code for the migration contract. let migration_contract = client @@ -45,7 +44,7 @@ async fn migration_works(mut client: Client) -> E2EResult<() .submit() .await .expect("uploading `migration` failed"); - let migration_code_hash = migration_contract.code_hash.as_ref().try_into().unwrap(); + let migration_code_hash = migration_contract.code_hash; // When diff --git a/integration-tests/public/upgradeable-contracts/set-code-hash-migration/lib.rs b/integration-tests/public/upgradeable-contracts/set-code-hash-migration/lib.rs index ea67cf199aa..b63399913fb 100644 --- a/integration-tests/public/upgradeable-contracts/set-code-hash-migration/lib.rs +++ b/integration-tests/public/upgradeable-contracts/set-code-hash-migration/lib.rs @@ -56,7 +56,7 @@ pub mod incrementer { /// /// In a production contract you would do some authorization here! #[ink(message)] - pub fn set_code(&mut self, code_hash: Hash) { + pub fn set_code(&mut self, code_hash: ink::H256) { self.env().set_code_hash(&code_hash).unwrap_or_else(|err| { panic!("Failed to `set_code_hash` to {code_hash:?} due to {err:?}") }); diff --git a/integration-tests/public/upgradeable-contracts/set-code-hash-migration/migration/lib.rs b/integration-tests/public/upgradeable-contracts/set-code-hash-migration/migration/lib.rs index 93d13cc6f19..18d84567132 100644 --- a/integration-tests/public/upgradeable-contracts/set-code-hash-migration/migration/lib.rs +++ b/integration-tests/public/upgradeable-contracts/set-code-hash-migration/migration/lib.rs @@ -49,7 +49,7 @@ pub mod incrementer { /// would be implicitly written to storage following the function execution, /// overwriting the migrated storage. #[ink(message)] - pub fn migrate(&self, inc_by: u8, code_hash: Hash) { + pub fn migrate(&self, inc_by: u8, code_hash: ink::H256) { let incrementer_new = IncrementerNew { count: self.count as u64, inc_by, diff --git a/integration-tests/public/upgradeable-contracts/set-code-hash-migration/updated-incrementer/lib.rs b/integration-tests/public/upgradeable-contracts/set-code-hash-migration/updated-incrementer/lib.rs index 7ac05c80e3d..ea272193e34 100644 --- a/integration-tests/public/upgradeable-contracts/set-code-hash-migration/updated-incrementer/lib.rs +++ b/integration-tests/public/upgradeable-contracts/set-code-hash-migration/updated-incrementer/lib.rs @@ -65,7 +65,7 @@ pub mod incrementer { /// /// In a production contract you would do some authorization here! #[ink(message)] - pub fn set_code(&mut self, code_hash: Hash) { + pub fn set_code(&mut self, code_hash: ink::H256) { self.env().set_code_hash(&code_hash).unwrap_or_else(|err| { panic!("Failed to `set_code_hash` to {code_hash:?} due to {err:?}") }); diff --git a/integration-tests/public/upgradeable-contracts/set-code-hash/lib.rs b/integration-tests/public/upgradeable-contracts/set-code-hash/lib.rs index c7f9993bea6..66420819a9e 100644 --- a/integration-tests/public/upgradeable-contracts/set-code-hash/lib.rs +++ b/integration-tests/public/upgradeable-contracts/set-code-hash/lib.rs @@ -57,7 +57,7 @@ pub mod incrementer { /// /// In a production contract you would do some authorization here! #[ink(message)] - pub fn set_code(&mut self, code_hash: Hash) { + pub fn set_code(&mut self, code_hash: ink::H256) { self.env().set_code_hash(&code_hash).unwrap_or_else(|err| { panic!("Failed to `set_code_hash` to {code_hash:?} due to {err:?}") }); @@ -106,7 +106,6 @@ pub mod incrementer { .expect("uploading `updated_incrementer` failed") .code_hash; - let new_code_hash = new_code_hash.as_ref().try_into().unwrap(); let set_code = call_builder.set_code(new_code_hash); let _set_code_result = client diff --git a/integration-tests/public/upgradeable-contracts/set-code-hash/updated-incrementer/lib.rs b/integration-tests/public/upgradeable-contracts/set-code-hash/updated-incrementer/lib.rs index 7741181a20e..c44d59ca794 100644 --- a/integration-tests/public/upgradeable-contracts/set-code-hash/updated-incrementer/lib.rs +++ b/integration-tests/public/upgradeable-contracts/set-code-hash/updated-incrementer/lib.rs @@ -59,7 +59,7 @@ pub mod incrementer { /// /// In a production contract you would do some authorization here! #[ink(message)] - pub fn set_code(&mut self, code_hash: Hash) { + pub fn set_code(&mut self, code_hash: ink::H256) { self.env().set_code_hash(&code_hash).unwrap_or_else(|err| { panic!("Failed to `set_code_hash` to {code_hash:?} due to {err:?}") }); diff --git a/integration-tests/public/wildcard-selector/lib.rs b/integration-tests/public/wildcard-selector/lib.rs index 1e99545ba34..5235144369d 100644 --- a/integration-tests/public/wildcard-selector/lib.rs +++ b/integration-tests/public/wildcard-selector/lib.rs @@ -49,7 +49,7 @@ pub mod wildcard_selector { type Environment = ::Env; fn build_message( - account_id: AccountId, + addr: ink::H160, selector: [u8; 4], message: String, ) -> ink_e2e::CallBuilderFinal< @@ -58,7 +58,7 @@ pub mod wildcard_selector { (), > { ink::env::call::build_call::() - .call(account_id) + .call(addr) .exec_input( ink::env::call::ExecutionInput::new(ink::env::call::Selector::new( selector, @@ -79,7 +79,7 @@ pub mod wildcard_selector { .submit() .await .expect("instantiate failed") - .account_id; + .addr; // when const ARBITRARY_SELECTOR: [u8; 4] = [0xF9, 0xF9, 0xF9, 0xF9]; @@ -135,7 +135,7 @@ pub mod wildcard_selector { .submit() .await .expect("instantiate failed") - .account_id; + .addr; // when let wildcard_complement_message = "WILDCARD COMPLEMENT MESSAGE".to_string(); diff --git a/linting/extra/Cargo.toml b/linting/extra/Cargo.toml index 0fd19323e4e..4251c1cc9bd 100644 --- a/linting/extra/Cargo.toml +++ b/linting/extra/Cargo.toml @@ -17,7 +17,7 @@ include = ["Cargo.toml", "*.rs", "LICENSE"] crate-type = ["cdylib"] [dependencies] -dylint_linting = "3.2.0" +dylint_linting = "3.3.0" if_chain = "1.0.2" log = "0.4.14" regex = "1.5.4" @@ -27,7 +27,7 @@ ink_env = { version = "=5.1.0", path = "../../crates/env", default-features = fa #rustc_middle = {path = "/Users/michi/.rustup/toolchains/nightly-2024-09-05-aarch64-apple-darwin/lib/rustlib/rustc-src/rust/compiler/rustc_middle", optional = true} [dev-dependencies] -dylint_testing = "3.2.0" +dylint_testing = "3.3.0" # The ink! dependencies used to build the `ui` tests and to compile the linting # library with `--default-features=std` (see the `features` section bellow). @@ -89,8 +89,6 @@ std = [ "scale-info/std", ] ink-as-dependency = [] -revive = [ - "ink/revive", - "ink_env/revive", - "ink_storage/revive" -] + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(dylint_lib, values("ink_linting"))'] } diff --git a/linting/extra/src/non_fallible_api.rs b/linting/extra/src/non_fallible_api.rs index 529b32ad272..080cf77f873 100644 --- a/linting/extra/src/non_fallible_api.rs +++ b/linting/extra/src/non_fallible_api.rs @@ -249,7 +249,7 @@ impl<'a, 'tcx> APIUsageChecker<'a, 'tcx> { } } -impl<'a, 'tcx> Visitor<'tcx> for APIUsageChecker<'a, 'tcx> { +impl<'tcx> Visitor<'tcx> for APIUsageChecker<'_, 'tcx> { type NestedFilter = nested_filter::OnlyBodies; fn visit_expr(&mut self, e: &'tcx Expr<'tcx>) { diff --git a/linting/extra/src/strict_balance_equality.rs b/linting/extra/src/strict_balance_equality.rs index ad14f5a49c7..b9b18a73fde 100644 --- a/linting/extra/src/strict_balance_equality.rs +++ b/linting/extra/src/strict_balance_equality.rs @@ -57,10 +57,7 @@ use rustc_middle::{ }, ty as mir_ty, }; -use rustc_mir_dataflow::{ - Analysis, - AnalysisDomain, -}; +use rustc_mir_dataflow::Analysis; use rustc_session::{ declare_lint, declare_lint_pass, @@ -219,7 +216,8 @@ impl<'a, 'tcx> StrictBalanceEqualityAnalysis<'a, 'tcx> { } } -impl<'a, 'tcx> AnalysisDomain<'tcx> for StrictBalanceEqualityAnalysis<'a, 'tcx> { +/// The implementation of the transfer function for the dataflow problem +impl<'tcx> Analysis<'tcx> for StrictBalanceEqualityAnalysis<'_, 'tcx> { /// A lattice that represents program's state. `BitSet` is a powerset over MIR Locals /// defined in the analyzed function. Inclusion to the set means that the Local is /// tainted with some operation with `self.env().balance()`. @@ -244,10 +242,6 @@ impl<'a, 'tcx> AnalysisDomain<'tcx> for StrictBalanceEqualityAnalysis<'a, 'tcx> ) } } -} - -/// The implementation of the transfer function for the dataflow problem -impl<'a, 'tcx> Analysis<'tcx> for StrictBalanceEqualityAnalysis<'a, 'tcx> { fn apply_statement_effect( &mut self, state: &mut Self::Domain, @@ -351,7 +345,7 @@ impl Visitor<'_> for TransferFunction<'_, '_> { } } -impl<'tcx> TransferFunction<'_, 'tcx> { +impl TransferFunction<'_, '_> { fn binop_strict_eq(&self, binop: &BinOp) -> bool { matches!(binop, BinOp::Eq | BinOp::Ne) } @@ -484,8 +478,7 @@ impl<'tcx> TransferFunction<'_, 'tcx> { self.fun_cache, init_taints, ) - .into_engine(self.cx.tcx, fn_mir) - .iterate_to_fixpoint() + .iterate_to_fixpoint(self.cx.tcx, fn_mir, None) .into_results_cursor(fn_mir); let taint_results = if let Some((last, _)) = traversal::reverse_postorder(fn_mir).last() { @@ -558,19 +551,18 @@ impl<'tcx> LateLintPass<'tcx> for StrictBalanceEquality { } } -impl<'tcx> StrictBalanceEquality { +impl StrictBalanceEquality { /// Checks a function from the contract implementation fn check_contract_fun( &mut self, - cx: &LateContext<'tcx>, + cx: &LateContext<'_>, fun_cache: &mut VisitedFunctionsCache, fn_span: Span, fn_def_id: DefId, ) { let fn_mir = cx.tcx.optimized_mir(fn_def_id); let mut taint_results = StrictBalanceEqualityAnalysis::new(cx, fun_cache) - .into_engine(cx.tcx, fn_mir) - .iterate_to_fixpoint() + .iterate_to_fixpoint(cx.tcx, fn_mir, None) .into_results_cursor(fn_mir); for (bb, bb_data) in traversal::preorder(fn_mir) { taint_results.seek_to_block_end(bb); diff --git a/linting/extra/ui/fail/strict_balance_equality.rs b/linting/extra/ui/fail/strict_balance_equality.rs index 6f31e837e92..580d637de42 100644 --- a/linting/extra/ui/fail/strict_balance_equality.rs +++ b/linting/extra/ui/fail/strict_balance_equality.rs @@ -2,29 +2,31 @@ #[ink::contract] pub mod strict_balance_equality { + use ink::U256; + #[ink(storage)] - pub struct StrictBalanceEquality {} + pub struct StrictU256Equality {} - impl StrictBalanceEquality { + impl StrictU256Equality { #[ink(constructor)] pub fn new() -> Self { Self {} } // Return value tainted with balance - fn get_balance_1(&self) -> Balance { + fn get_balance_1(&self) -> U256 { self.env().balance() } - fn get_balance_2(&self) -> Balance { + fn get_balance_2(&self) -> U256 { let tmp = self.env().balance(); tmp } - fn get_balance_3(&self) -> Balance { + fn get_balance_3(&self) -> U256 { let tmp = self.env().balance(); tmp + 42 } - fn get_balance_recursive(&self, acc: &Balance) -> Balance { - if acc < &10_u128 { + fn get_balance_recursive(&self, acc: &U256) -> U256 { + if acc < &U256::from(10) { self.get_balance_recursive(&(acc + 1)) } else { self.env().balance() @@ -32,53 +34,53 @@ pub mod strict_balance_equality { } // Return the result of comparison with balance - fn cmp_balance_1(&self, value: &Balance) -> bool { + fn cmp_balance_1(&self, value: &U256) -> bool { *value == self.env().balance() } - fn cmp_balance_2(&self, value: &Balance, threshold: &Balance) -> bool { + fn cmp_balance_2(&self, value: &U256, threshold: &U256) -> bool { value != threshold } - fn cmp_balance_3(&self, value: Balance, threshold: Balance) -> bool { + fn cmp_balance_3(&self, value: U256, threshold: U256) -> bool { value != threshold } // Tainted `&mut` input argument - fn get_balance_arg_1(&self, value: &mut Balance) { + fn get_balance_arg_1(&self, value: &mut U256) { *value = self.env().balance(); } - fn get_balance_arg_indirect(&self, value: &mut Balance) { + fn get_balance_arg_indirect(&self, value: &mut U256) { self.get_balance_arg_1(value) } #[ink(message)] pub fn do_nothing(&mut self) { - let threshold: Balance = 100; - let value: Balance = self.env().balance(); + let threshold = U256::from(100); + let value: U256 = self.env().balance(); // Bad: Strict equality with balance - if self.env().balance() == 10 { /* ... */ } - if value == 11 { /* ... */ } + if self.env().balance() == U256::from(10) { /* ... */ } + if value == 11.into() { /* ... */ } if self.env().balance() == threshold { /* ... */ } // Bad: Strict equality in function call: return value - if self.get_balance_1() == 10 { /* ... */ } - if self.get_balance_2() == 10 { /* ... */ } - if self.get_balance_3() == 10 { /* ... */ } - if self.get_balance_recursive(&10) == 10 { /* ... */ } + if self.get_balance_1() == 10.into() { /* ... */ } + if self.get_balance_2() == U256::from(10) { /* ... */ } + if self.get_balance_3() == U256::from(10) { /* ... */ } + if self.get_balance_recursive(&10.into()) == 10.into() { /* ... */ } // Bad: Strict equality in function call: return value contains the result of // comparison - if self.cmp_balance_1(&10) { /* ... */ } + if self.cmp_balance_1(&U256::from(10)) { /* ... */ } if self.cmp_balance_2(&self.env().balance(), &threshold) { /* ... */ } if self.cmp_balance_3(self.env().balance(), threshold) { /* ... */ } // Bad: Strict equality in function: tainted arguments - let mut res_1 = 0_u128; + let mut res_1 = U256::zero(); self.get_balance_arg_1(&mut res_1); - if res_1 == 10 { /* ... */ } - let mut res_2 = 0_u128; + if res_1 == U256::from(10) { /* ... */ } + let mut res_2 = U256::from(0); self.get_balance_arg_indirect(&mut res_2); - if res_2 == 10 { /* ... */ } + if res_2 == 10.into() { /* ... */ } } } } diff --git a/linting/extra/ui/fail/strict_balance_equality.stderr b/linting/extra/ui/fail/strict_balance_equality.stderr index 979fa012162..522807d4617 100644 --- a/linting/extra/ui/fail/strict_balance_equality.stderr +++ b/linting/extra/ui/fail/strict_balance_equality.stderr @@ -1,22 +1,22 @@ warning: dangerous strict balance equality - --> $DIR/strict_balance_equality.rs:59:16 + --> $DIR/strict_balance_equality.rs:61:16 | -LL | if self.env().balance() == 10 { /* ... */ } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` +LL | if self.env().balance() == U256::from(10) { /* ... */ } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` | = help: for further information visit https://use.ink/linter/rules/strict_balance_equality = note: `#[warn(strict_balance_equality)]` on by default warning: dangerous strict balance equality - --> $DIR/strict_balance_equality.rs:60:16 + --> $DIR/strict_balance_equality.rs:62:16 | -LL | if value == 11 { /* ... */ } - | ^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` +LL | if value == 11.into() { /* ... */ } + | ^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` | = help: for further information visit https://use.ink/linter/rules/strict_balance_equality warning: dangerous strict balance equality - --> $DIR/strict_balance_equality.rs:61:16 + --> $DIR/strict_balance_equality.rs:63:16 | LL | if self.env().balance() == threshold { /* ... */ } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` @@ -24,39 +24,39 @@ LL | if self.env().balance() == threshold { /* ... */ } = help: for further information visit https://use.ink/linter/rules/strict_balance_equality warning: dangerous strict balance equality - --> $DIR/strict_balance_equality.rs:64:16 + --> $DIR/strict_balance_equality.rs:66:16 | -LL | if self.get_balance_1() == 10 { /* ... */ } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` +LL | if self.get_balance_1() == 10.into() { /* ... */ } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` | = help: for further information visit https://use.ink/linter/rules/strict_balance_equality warning: dangerous strict balance equality - --> $DIR/strict_balance_equality.rs:65:16 + --> $DIR/strict_balance_equality.rs:67:16 | -LL | if self.get_balance_2() == 10 { /* ... */ } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` +LL | if self.get_balance_2() == U256::from(10) { /* ... */ } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` | = help: for further information visit https://use.ink/linter/rules/strict_balance_equality warning: dangerous strict balance equality - --> $DIR/strict_balance_equality.rs:67:16 + --> $DIR/strict_balance_equality.rs:69:16 | -LL | if self.get_balance_recursive(&10) == 10 { /* ... */ } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` +LL | if self.get_balance_recursive(&10.into()) == 10.into() { /* ... */ } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` | = help: for further information visit https://use.ink/linter/rules/strict_balance_equality warning: dangerous strict balance equality - --> $DIR/strict_balance_equality.rs:71:16 + --> $DIR/strict_balance_equality.rs:73:16 | -LL | if self.cmp_balance_1(&10) { /* ... */ } - | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` +LL | if self.cmp_balance_1(&U256::from(10)) { /* ... */ } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` | = help: for further information visit https://use.ink/linter/rules/strict_balance_equality warning: dangerous strict balance equality - --> $DIR/strict_balance_equality.rs:72:16 + --> $DIR/strict_balance_equality.rs:74:16 | LL | if self.cmp_balance_2(&self.env().balance(), &threshold) { /* ... */ } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` @@ -64,7 +64,7 @@ LL | if self.cmp_balance_2(&self.env().balance(), &threshold) { /* . = help: for further information visit https://use.ink/linter/rules/strict_balance_equality warning: dangerous strict balance equality - --> $DIR/strict_balance_equality.rs:73:16 + --> $DIR/strict_balance_equality.rs:75:16 | LL | if self.cmp_balance_3(self.env().balance(), threshold) { /* ... */ } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` @@ -72,18 +72,18 @@ LL | if self.cmp_balance_3(self.env().balance(), threshold) { /* ... = help: for further information visit https://use.ink/linter/rules/strict_balance_equality warning: dangerous strict balance equality - --> $DIR/strict_balance_equality.rs:78:16 + --> $DIR/strict_balance_equality.rs:80:16 | -LL | if res_1 == 10 { /* ... */ } - | ^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` +LL | if res_1 == U256::from(10) { /* ... */ } + | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` | = help: for further information visit https://use.ink/linter/rules/strict_balance_equality warning: dangerous strict balance equality - --> $DIR/strict_balance_equality.rs:81:16 + --> $DIR/strict_balance_equality.rs:83:16 | -LL | if res_2 == 10 { /* ... */ } - | ^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` +LL | if res_2 == 10.into() { /* ... */ } + | ^^^^^^^^^^^^^^^^^^ help: consider using non-strict equality operators instead: `<`, `>` | = help: for further information visit https://use.ink/linter/rules/strict_balance_equality diff --git a/linting/extra/ui/pass/strict_balance_equality.rs b/linting/extra/ui/pass/strict_balance_equality.rs index 18eea954837..b14caa3f012 100644 --- a/linting/extra/ui/pass/strict_balance_equality.rs +++ b/linting/extra/ui/pass/strict_balance_equality.rs @@ -2,29 +2,31 @@ #[ink::contract] pub mod strict_balance_equality { + use ink::U256; + #[ink(storage)] - pub struct StrictBalanceEquality {} + pub struct StrictU256Equality {} - impl StrictBalanceEquality { + impl StrictU256Equality { #[ink(constructor)] pub fn new() -> Self { Self {} } // Return value tainted with balance - fn get_balance_1(&self) -> Balance { + fn get_balance_1(&self) -> U256 { self.env().balance() } - fn get_balance_2(&self) -> Balance { + fn get_balance_2(&self) -> U256 { let tmp = self.env().balance(); tmp } - fn get_balance_3(&self) -> Balance { + fn get_balance_3(&self) -> U256 { let tmp = self.env().balance(); - tmp + 42 + tmp + U256::from(42) } - fn get_balance_recursive(&self, acc: &Balance) -> Balance { - if acc < &10_u128 { + fn get_balance_recursive(&self, acc: &U256) -> U256 { + if acc < &U256::from(10) { self.get_balance_recursive(&(acc + 1)) } else { self.env().balance() @@ -32,57 +34,60 @@ pub mod strict_balance_equality { } // Return the result of non-strict comparison with balance - fn cmp_balance_1(&self, value: &Balance) -> bool { + fn cmp_balance_1(&self, value: &U256) -> bool { *value < self.env().balance() } - fn cmp_balance_2(&self, value: &Balance, threshold: &Balance) -> bool { + fn cmp_balance_2(&self, value: &U256, threshold: &U256) -> bool { value > threshold } - fn cmp_balance_3(&self, value: Balance, threshold: Balance) -> bool { + fn cmp_balance_3(&self, value: U256, threshold: U256) -> bool { value >= threshold } // `&mut` input argument gets the balance value - fn get_balance_arg_1(&self, value: &mut Balance) { + fn get_balance_arg_1(&self, value: &mut U256) { *value = self.env().balance(); } - fn get_balance_arg_indirect(&self, value: &mut Balance) { + fn get_balance_arg_indirect(&self, value: &mut U256) { self.get_balance_arg_1(value) } #[ink(message)] pub fn do_nothing(&mut self) { - let threshold: Balance = 100; - let value: Balance = self.env().balance(); + let threshold = U256::from(100); + let value: U256 = self.env().balance(); // Good: Non-strict equality with balance - if self.env().balance() < 10 { /* ... */ } - if value > 11 { /* ... */ } + if self.env().balance() < 10.into() { /* ... */ } + if value > 11.into() { /* ... */ } if self.env().balance() < threshold { /* ... */ } // Good: Non-strict equality in function call: return value - if self.get_balance_1() < 10 { /* ... */ } - if self.get_balance_2() > 10 { /* ... */ } - if self.get_balance_3() >= 10 { /* ... */ } - if self.get_balance_recursive(&10) <= 10 { /* ... */ } + if self.get_balance_1() < 10.into() { /* ... */ } + if self.get_balance_2() > 10.into() { /* ... */ } + if self.get_balance_3() >= U256::from(10) { /* ... */ } + if self.get_balance_recursive(&10.into()) <= U256::from(10) { /* ... */ } // Good: Non-strict equality in function call: return value contains the // result of comparison - if self.cmp_balance_1(&10) { /* ... */ } + if self.cmp_balance_1(&10.into()) { /* ... */ } if self.cmp_balance_2(&self.env().balance(), &threshold) { /* ... */ } if self.cmp_balance_3(self.env().balance(), threshold) { /* ... */ } // Good: Non-strict equality in function: tainted arguments - let mut res_1 = 0_u128; + let mut res_1 = U256::zero(); self.get_balance_arg_1(&mut res_1); - if res_1 < 10 { /* ... */ } - let mut res_2 = 0_u128; + if res_1 < U256::from(10) { /* ... */ } + let mut res_2 = U256::from(0); self.get_balance_arg_indirect(&mut res_2); - if res_2 > 10 { /* ... */ } + if res_2 > 10.into() { /* ... */ } // Good: warning is suppressed #[cfg_attr(dylint_lib = "ink_linting", allow(strict_balance_equality))] - if self.env().balance() == 10 { /* ... */ } + if self.env().balance() == 10.into() { /* ... */ } + + #[cfg_attr(dylint_lib = "ink_linting", allow(strict_balance_equality))] + if self.env().balance() == U256::from(10) { /* ... */ } } } } diff --git a/linting/mandatory/Cargo.toml b/linting/mandatory/Cargo.toml index 433c60552c7..17ef8715787 100644 --- a/linting/mandatory/Cargo.toml +++ b/linting/mandatory/Cargo.toml @@ -17,14 +17,14 @@ include = ["Cargo.toml", "*.rs", "LICENSE"] crate-type = ["cdylib"] [dependencies] -dylint_linting = "3.2.0" +dylint_linting = "3.3.0" if_chain = "1.0.2" log = "0.4.14" regex = "1.5.4" ink_linting_utils = { workspace = true } [dev-dependencies] -dylint_testing = "3.2.0" +dylint_testing = "3.3.0" # The ink! dependencies used to build the `ui` tests and to compile the linting # library with `--default-features=std` (see the `features` section bellow). @@ -66,3 +66,6 @@ std = [ "scale-info/std", ] ink-as-dependency = [] + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(dylint_lib, values("ink_linting"))'] } diff --git a/linting/rust-toolchain.toml b/linting/rust-toolchain.toml index 4e7138b8d15..8e7154ab4fa 100644 --- a/linting/rust-toolchain.toml +++ b/linting/rust-toolchain.toml @@ -1,6 +1,6 @@ # This file corresponds to the `rust-toolchain` file used for the `dylint` examples here: -# https://github.com/trailofbits/dylint/blob/ef7210cb08aac920c18d2141604efe210029f2a2/internal/template/rust-toolchain +# https://github.com/trailofbits/dylint/blob/master/internal/template/rust-toolchain [toolchain] -channel = "nightly-2024-11-01" +channel = "nightly-2024-11-28" components = ["llvm-tools-preview", "rustc-dev"] diff --git a/linting/utils/Cargo.toml b/linting/utils/Cargo.toml index d6e10bf9fb3..e7da294d425 100644 --- a/linting/utils/Cargo.toml +++ b/linting/utils/Cargo.toml @@ -15,7 +15,7 @@ include = ["Cargo.toml", "*.rs", "LICENSE"] [dependencies] if_chain = "1.0.2" -parity_clippy_utils = { package = "clippy_utils", git = "https://github.com/rust-lang/rust-clippy", rev = "a95afe2d0a2051d97b723b0b197393b7811bc4e4" } +parity_clippy_utils = { package = "clippy_utils", git = "https://github.com/rust-lang/rust-clippy", rev = "ff4a26d442bead94a4c96fb1de967374bc4fbd8e" } [package.metadata.rust-analyzer] rustc_private = true diff --git a/linting/utils/src/lib.rs b/linting/utils/src/lib.rs index 713b70eb5d1..eb4120082bd 100644 --- a/linting/utils/src/lib.rs +++ b/linting/utils/src/lib.rs @@ -139,7 +139,7 @@ fn find_contract_ty_hir<'tcx>( if match_def_path( cx, trait_ref.skip_binder().def_id, - &["ink_env", "contract", "ContractEnv"], + &["ink_primitives", "contract", "ContractEnv"], ); then { Some(&item_impl.self_ty) } else { None } } diff --git a/scripts/contract_size.sh b/scripts/contract_size.sh index 5a470ba8de7..2cfd85e0553 100755 --- a/scripts/contract_size.sh +++ b/scripts/contract_size.sh @@ -27,7 +27,7 @@ if [ -z "$manifest_path" ]; then exit 1 fi -build_result=$(cargo contract build --manifest-path "$manifest_path" --release --quiet --output-json) +build_result=$(cargo +nightly contract build --manifest-path "$manifest_path" --release --quiet --output-json) if [ $? -eq 0 ]; then # only print the contract name and size if the build was successful diff --git a/scripts/for_all_contracts_exec.sh b/scripts/for_all_contracts_exec.sh index 75e4085abe5..3547de8ee70 100755 --- a/scripts/for_all_contracts_exec.sh +++ b/scripts/for_all_contracts_exec.sh @@ -1,5 +1,7 @@ #!/bin/bash +set -eu + script_name="${BASH_SOURCE[0]}" scripts_path=$( cd "$(dirname "$script_name")" || exit; pwd -P ) @@ -50,6 +52,7 @@ options=$(getopt -o p:i:q: --long path:,ignore:,quiet:,partition: -- "$@") eval set -- "$options" ignore=() quiet=false +partitioning=false while true; do case "$1" in -p|--path) @@ -90,6 +93,7 @@ fi successes=() failures=() +# todo: error when more than one "{}" placeholder is present # default to adding the argument as the last argument to the command arg_index=${#command[@]} # find the index of the argument placeholder "{}", if present @@ -139,7 +143,7 @@ for (( i = start; i <= end; i++ )); do if [ "$quiet" = false ]; then >&2 echo Running: "${command[@]}" fi - "${command[@]}" + eval "${command[@]}"; if [ $? -eq 0 ]; then successes+=("$manifest_path") diff --git a/scripts/is_contract.sh b/scripts/is_contract.sh index 8523522140f..912d8ceb01d 100755 --- a/scripts/is_contract.sh +++ b/scripts/is_contract.sh @@ -1,5 +1,7 @@ #!/bin/bash +set -eu + SCRIPT_NAME="${BASH_SOURCE[0]}" MANIFEST_PATH=$1