diff --git a/Cargo.lock b/Cargo.lock index cf75334f495b08f4ed385ef7c59f7828040cceb1..5457e44aeaabec67176f82aff87d84f71b3a4b8f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6664,23 +6664,6 @@ dependencies = [ "windows-sys 0.48.0", ] -[[package]] -name = "ethabi" -version = "18.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7413c5f74cc903ea37386a8965a936cbeb334bd270862fdece542c1b2dcbc898" -dependencies = [ - "ethereum-types 0.14.1", - "hex", - "once_cell", - "regex", - "serde", - "serde_json", - "sha3 0.10.8", - "thiserror 1.0.65", - "uint 0.9.5", -] - [[package]] name = "ethabi-decode" version = "1.0.0" @@ -15170,7 +15153,6 @@ dependencies = [ "anyhow", "clap 4.5.13", "env_logger 0.11.3", - "ethabi", "futures", "git2", "hex", diff --git a/prdoc/pr_7660.prdoc b/prdoc/pr_7660.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..41a37d0893bd9fed2e2dd66891360d5d41fd8467 --- /dev/null +++ b/prdoc/pr_7660.prdoc @@ -0,0 +1,8 @@ +title: '[pallet-revive] Remove js examples' +doc: +- audience: Runtime Dev + description: |- + Remove JS examples, they now belongs to the evm-test-suite repo +crates: +- name: pallet-revive-eth-rpc + bump: minor diff --git a/substrate/frame/revive/rpc/Cargo.toml b/substrate/frame/revive/rpc/Cargo.toml index 33d447e67a20369f2a1f18623a8a879bf654fce1..0353cf23709520fb205f3fd97ccce48d24cf2c99 100644 --- a/substrate/frame/revive/rpc/Cargo.toml +++ b/substrate/frame/revive/rpc/Cargo.toml @@ -17,26 +17,6 @@ path = "src/main.rs" name = "eth-rpc-tester" path = "src/eth-rpc-tester.rs" -[[example]] -name = "deploy" -path = "examples/rust/deploy.rs" - -[[example]] -name = "transfer" -path = "examples/rust/transfer.rs" - -[[example]] -name = "rpc-playground" -path = "examples/rust/rpc-playground.rs" - -[[example]] -name = "extrinsic" -path = "examples/rust/extrinsic.rs" - -[[example]] -name = "remark-extrinsic" -path = "examples/rust/remark-extrinsic.rs" - [dependencies] anyhow = { workspace = true } clap = { workspace = true, features = ["derive", "env"] } @@ -70,7 +50,6 @@ tokio = { workspace = true, features = ["full"] } [dev-dependencies] env_logger = { workspace = true } -ethabi = { version = "18.0.0" } pretty_assertions = { workspace = true } static_init = { workspace = true } substrate-cli-test-utils = { workspace = true } diff --git a/substrate/frame/revive/rpc/examples/README.md b/substrate/frame/revive/rpc/examples/README.md index 1079c254b9c2070fb798c7b8362aa8788d89ab79..5bbd6255713cf56a96d0ec1144f5606e49f51956 100644 --- a/substrate/frame/revive/rpc/examples/README.md +++ b/substrate/frame/revive/rpc/examples/README.md @@ -47,21 +47,7 @@ RUST_LOG="info,eth-rpc=debug" cargo run -p pallet-revive-eth-rpc --example deplo ## JS examples -Interact with the node using MetaMask & Ether.js, by starting the example web app: - -```bash - -cd substrate/frame/revive/rpc/examples/js -bun install -bun run dev -``` - -Alternatively, you can run the example script directly: - -```bash -cd substrate/frame/revive/rpc/examples/js -bun src/script.ts -``` +JS examples have been moved to the [evm-test-suite](https://github.com/paritytech/evm-test-suite) repository. ### Configure MetaMask diff --git a/substrate/frame/revive/rpc/examples/bun.lockb b/substrate/frame/revive/rpc/examples/bun.lockb deleted file mode 100755 index 3a7a0df5cea48f9e639655bd11d1b9b94751e6b1..0000000000000000000000000000000000000000 Binary files a/substrate/frame/revive/rpc/examples/bun.lockb and /dev/null differ diff --git a/substrate/frame/revive/rpc/examples/rust/deploy.rs b/substrate/frame/revive/rpc/examples/deploy.rs similarity index 100% rename from substrate/frame/revive/rpc/examples/rust/deploy.rs rename to substrate/frame/revive/rpc/examples/deploy.rs diff --git a/substrate/frame/revive/rpc/examples/rust/extrinsic.rs b/substrate/frame/revive/rpc/examples/extrinsic.rs similarity index 100% rename from substrate/frame/revive/rpc/examples/rust/extrinsic.rs rename to substrate/frame/revive/rpc/examples/extrinsic.rs diff --git a/substrate/frame/revive/rpc/examples/js/.gitignore b/substrate/frame/revive/rpc/examples/js/.gitignore deleted file mode 100644 index a547bf36d8d11a4f89c59c144f24795749086dd1..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* -lerna-debug.log* - -node_modules -dist -dist-ssr -*.local - -# Editor directories and files -.vscode/* -!.vscode/extensions.json -.idea -.DS_Store -*.suo -*.ntvs* -*.njsproj -*.sln -*.sw? diff --git a/substrate/frame/revive/rpc/examples/js/.prettierrc.json b/substrate/frame/revive/rpc/examples/js/.prettierrc.json deleted file mode 100644 index 123daf08ec5d7921159a3040f9ba327767b52648..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/.prettierrc.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "trailingComma": "es5", - "tabWidth": 4, - "semi": false, - "singleQuote": true -} diff --git a/substrate/frame/revive/rpc/examples/js/.solhint.json b/substrate/frame/revive/rpc/examples/js/.solhint.json deleted file mode 100644 index 83a795a1f4eefd55b00f2bac87366260feddc761..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/.solhint.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "solhint:recommended", - "rules": { - "compiler-version": ["error", "^0.8.0"], - "gas-custom-errors": "off", - "one-contract-per-file": "off", - "no-empty-blocks": "off" - } -} diff --git a/substrate/frame/revive/rpc/examples/js/abi/Errors.json b/substrate/frame/revive/rpc/examples/js/abi/Errors.json deleted file mode 100644 index 2d8dccc771e8b6eef12fde6a27556d9b52899ed0..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/Errors.json +++ /dev/null @@ -1,106 +0,0 @@ -[ - { - "inputs": [ - { - "internalType": "string", - "name": "message", - "type": "string" - } - ], - "name": "CustomError", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "bool", - "name": "newState", - "type": "bool" - } - ], - "name": "setState", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "state", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "triggerAssertError", - "outputs": [], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [], - "name": "triggerCustomError", - "outputs": [], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [], - "name": "triggerDivisionByZero", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [], - "name": "triggerOutOfBoundsError", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [], - "name": "triggerRequireError", - "outputs": [], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [], - "name": "triggerRevertError", - "outputs": [], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "value", - "type": "uint256" - } - ], - "name": "valueMatch", - "outputs": [], - "stateMutability": "payable", - "type": "function" - } -] \ No newline at end of file diff --git a/substrate/frame/revive/rpc/examples/js/abi/Errors.ts b/substrate/frame/revive/rpc/examples/js/abi/Errors.ts deleted file mode 100644 index b39567531c6d3d2cf979234d2d30fcf31b305852..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/Errors.ts +++ /dev/null @@ -1,106 +0,0 @@ -export const ErrorsAbi = [ - { - inputs: [ - { - internalType: "string", - name: "message", - type: "string", - }, - ], - name: "CustomError", - type: "error", - }, - { - inputs: [ - { - internalType: "bool", - name: "newState", - type: "bool", - }, - ], - name: "setState", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [], - name: "state", - outputs: [ - { - internalType: "bool", - name: "", - type: "bool", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "triggerAssertError", - outputs: [], - stateMutability: "pure", - type: "function", - }, - { - inputs: [], - name: "triggerCustomError", - outputs: [], - stateMutability: "pure", - type: "function", - }, - { - inputs: [], - name: "triggerDivisionByZero", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256", - }, - ], - stateMutability: "pure", - type: "function", - }, - { - inputs: [], - name: "triggerOutOfBoundsError", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256", - }, - ], - stateMutability: "pure", - type: "function", - }, - { - inputs: [], - name: "triggerRequireError", - outputs: [], - stateMutability: "pure", - type: "function", - }, - { - inputs: [], - name: "triggerRevertError", - outputs: [], - stateMutability: "pure", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "value", - type: "uint256", - }, - ], - name: "valueMatch", - outputs: [], - stateMutability: "payable", - type: "function", - }, -] as const; diff --git a/substrate/frame/revive/rpc/examples/js/abi/EventExample.json b/substrate/frame/revive/rpc/examples/js/abi/EventExample.json deleted file mode 100644 index a64c920c40687eda7e6e856d3d6e959b87d8bdf6..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/EventExample.json +++ /dev/null @@ -1,34 +0,0 @@ -[ - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "sender", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "value", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "string", - "name": "message", - "type": "string" - } - ], - "name": "ExampleEvent", - "type": "event" - }, - { - "inputs": [], - "name": "triggerEvent", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - } -] \ No newline at end of file diff --git a/substrate/frame/revive/rpc/examples/js/abi/EventExample.ts b/substrate/frame/revive/rpc/examples/js/abi/EventExample.ts deleted file mode 100644 index efb0d741b48fd82c7899e8e5848142203baadcf9..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/EventExample.ts +++ /dev/null @@ -1,34 +0,0 @@ -export const EventExampleAbi = [ - { - anonymous: false, - inputs: [ - { - indexed: true, - internalType: "address", - name: "sender", - type: "address", - }, - { - indexed: false, - internalType: "uint256", - name: "value", - type: "uint256", - }, - { - indexed: false, - internalType: "string", - name: "message", - type: "string", - }, - ], - name: "ExampleEvent", - type: "event", - }, - { - inputs: [], - name: "triggerEvent", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, -] as const; diff --git a/substrate/frame/revive/rpc/examples/js/abi/Flipper.json b/substrate/frame/revive/rpc/examples/js/abi/Flipper.json deleted file mode 100644 index 4c1b163d2943d561d07086ce939b732e916dd8c1..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/Flipper.json +++ /dev/null @@ -1,35 +0,0 @@ -[ - { - "inputs": [], - "name": "flip", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "getValue", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "value", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - } -] \ No newline at end of file diff --git a/substrate/frame/revive/rpc/examples/js/abi/Flipper.ts b/substrate/frame/revive/rpc/examples/js/abi/Flipper.ts deleted file mode 100644 index d7428beb6aa961b07c5a0d2dc55ab13bd783f42e..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/Flipper.ts +++ /dev/null @@ -1,35 +0,0 @@ -export const FlipperAbi = [ - { - inputs: [], - name: "flip", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [], - name: "getValue", - outputs: [ - { - internalType: "bool", - name: "", - type: "bool", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "value", - outputs: [ - { - internalType: "bool", - name: "", - type: "bool", - }, - ], - stateMutability: "view", - type: "function", - }, -] as const; diff --git a/substrate/frame/revive/rpc/examples/js/abi/FlipperCaller.json b/substrate/frame/revive/rpc/examples/js/abi/FlipperCaller.json deleted file mode 100644 index c4ed4228f47dcd974274d7fda6bf963606a8ff6d..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/FlipperCaller.json +++ /dev/null @@ -1,46 +0,0 @@ -[ - { - "inputs": [ - { - "internalType": "address", - "name": "_flipperAddress", - "type": "address" - } - ], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "inputs": [], - "name": "callFlip", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "callGetValue", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "flipperAddress", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - } -] \ No newline at end of file diff --git a/substrate/frame/revive/rpc/examples/js/abi/FlipperCaller.ts b/substrate/frame/revive/rpc/examples/js/abi/FlipperCaller.ts deleted file mode 100644 index 2d695886d9602fe1df5de42e54f39fe8549ea780..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/FlipperCaller.ts +++ /dev/null @@ -1,46 +0,0 @@ -export const FlipperCallerAbi = [ - { - inputs: [ - { - internalType: "address", - name: "_flipperAddress", - type: "address", - }, - ], - stateMutability: "nonpayable", - type: "constructor", - }, - { - inputs: [], - name: "callFlip", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [], - name: "callGetValue", - outputs: [ - { - internalType: "bool", - name: "", - type: "bool", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "flipperAddress", - outputs: [ - { - internalType: "address", - name: "", - type: "address", - }, - ], - stateMutability: "view", - type: "function", - }, -] as const; diff --git a/substrate/frame/revive/rpc/examples/js/abi/PiggyBank.json b/substrate/frame/revive/rpc/examples/js/abi/PiggyBank.json deleted file mode 100644 index e6655889e21aac45a3152854808b08b19d4625bb..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/PiggyBank.json +++ /dev/null @@ -1,65 +0,0 @@ -[ - { - "inputs": [], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "inputs": [], - "name": "deposit", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "payable", - "type": "function" - }, - { - "inputs": [], - "name": "getDeposit", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "owner", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "withdrawAmount", - "type": "uint256" - } - ], - "name": "withdraw", - "outputs": [ - { - "internalType": "uint256", - "name": "remainingBal", - "type": "uint256" - } - ], - "stateMutability": "nonpayable", - "type": "function" - } -] \ No newline at end of file diff --git a/substrate/frame/revive/rpc/examples/js/abi/RevertExample.ts b/substrate/frame/revive/rpc/examples/js/abi/RevertExample.ts deleted file mode 100644 index ab483b1811c4a930e05dd5642d8df0daa762052f..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/RevertExample.ts +++ /dev/null @@ -1,14 +0,0 @@ -export const RevertExampleAbi = [ - { - inputs: [], - stateMutability: "nonpayable", - type: "constructor", - }, - { - inputs: [], - name: "doRevert", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, -] as const; diff --git a/substrate/frame/revive/rpc/examples/js/abi/piggyBank.ts b/substrate/frame/revive/rpc/examples/js/abi/piggyBank.ts deleted file mode 100644 index a6b8c1b0be56fb4d72fdb00dad93d16fbd93bc70..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/piggyBank.ts +++ /dev/null @@ -1,65 +0,0 @@ -export const PiggyBankAbi = [ - { - inputs: [], - stateMutability: "nonpayable", - type: "constructor", - }, - { - inputs: [], - name: "deposit", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256", - }, - ], - stateMutability: "payable", - type: "function", - }, - { - inputs: [], - name: "getDeposit", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "owner", - outputs: [ - { - internalType: "address", - name: "", - type: "address", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "withdrawAmount", - type: "uint256", - }, - ], - name: "withdraw", - outputs: [ - { - internalType: "uint256", - name: "remainingBal", - type: "uint256", - }, - ], - stateMutability: "nonpayable", - type: "function", - }, -] as const; diff --git a/substrate/frame/revive/rpc/examples/js/bun.lockb b/substrate/frame/revive/rpc/examples/js/bun.lockb deleted file mode 100755 index 3b8ad3d048b079b71dffad82cf37fd1952375ce2..0000000000000000000000000000000000000000 Binary files a/substrate/frame/revive/rpc/examples/js/bun.lockb and /dev/null differ diff --git a/substrate/frame/revive/rpc/examples/js/contracts/Errors.sol b/substrate/frame/revive/rpc/examples/js/contracts/Errors.sol deleted file mode 100644 index abbdba8d32eb4a2eb3abda6f39589cca2b14f168..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/contracts/Errors.sol +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -contract Errors { - bool public state; - - // Payable function that can be used to test insufficient funds errors - function valueMatch(uint256 value) public payable { - require(msg.value == value , "msg.value does not match value"); - } - - function setState(bool newState) public { - state = newState; - } - - // Trigger a require statement failure with a custom error message - function triggerRequireError() public pure { - require(false, "This is a require error"); - } - - // Trigger an assert statement failure - function triggerAssertError() public pure { - assert(false); - } - - // Trigger a revert statement with a custom error message - function triggerRevertError() public pure { - revert("This is a revert error"); - } - - // Trigger a division by zero error - function triggerDivisionByZero() public pure returns (uint256) { - uint256 a = 1; - uint256 b = 0; - return a / b; - } - - // Trigger an out-of-bounds array access - function triggerOutOfBoundsError() public pure returns (uint256) { - uint256[] memory arr = new uint256[](1); - return arr[2]; - } - - // Trigger a custom error - error CustomError(string message); - - function triggerCustomError() public pure { - revert CustomError("This is a custom error"); - } -} - diff --git a/substrate/frame/revive/rpc/examples/js/contracts/Event.sol b/substrate/frame/revive/rpc/examples/js/contracts/Event.sol deleted file mode 100644 index 1e4ce7cf87659319f1071a24f678da1d376f3825..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/contracts/Event.sol +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -contract EventExample { - event ExampleEvent(address indexed sender, uint256 value, string message); - - function triggerEvent() public { - uint256 value = 12345; - string memory message = "Hello world"; - emit ExampleEvent(msg.sender, value, message); - } -} - diff --git a/substrate/frame/revive/rpc/examples/js/contracts/Flipper.sol b/substrate/frame/revive/rpc/examples/js/contracts/Flipper.sol deleted file mode 100644 index 93b09f08c27235fee4529c76b52dd24f347e388b..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/contracts/Flipper.sol +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -// Flipper - Stores and toggles a boolean value -contract Flipper { - bool public value; - - function flip() external { - value = !value; - } - - function getValue() external view returns (bool) { - return value; - } -} - -// FlipperCaller - Interacts with the Flipper contract -contract FlipperCaller { - // Address of the Flipper contract - address public flipperAddress; - - // Constructor to initialize Flipper's address - constructor(address _flipperAddress) public { - flipperAddress = _flipperAddress; - } - - function callFlip() external { - Flipper(flipperAddress).flip(); - } - - function callGetValue() external view returns (bool) { - return Flipper(flipperAddress).getValue(); - } -} - diff --git a/substrate/frame/revive/rpc/examples/js/contracts/PiggyBank.sol b/substrate/frame/revive/rpc/examples/js/contracts/PiggyBank.sol deleted file mode 100644 index 89be1b2589dd5c0a94c057c37e34653e4d7e4567..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/contracts/PiggyBank.sol +++ /dev/null @@ -1,32 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -contract PiggyBank { - - uint256 private balance; - address public owner; - - constructor() public { - owner = msg.sender; - balance = 0; - } - - function deposit() public payable returns (uint256) { - balance += msg.value; - return balance; - } - - function getDeposit() public view returns (uint256) { - return balance; - } - - function withdraw(uint256 withdrawAmount) public returns (uint256 remainingBal) { - require(msg.sender == owner, "You are not the owner"); - balance -= withdrawAmount; - (bool success, ) = payable(msg.sender).call{value: withdrawAmount}(""); - require(success, "Transfer failed"); - - return balance; - } -} - diff --git a/substrate/frame/revive/rpc/examples/js/contracts/Tracing.sol b/substrate/frame/revive/rpc/examples/js/contracts/Tracing.sol deleted file mode 100644 index c7867fc4a053661622d1e83c3736a8f106dbe3c5..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/contracts/Tracing.sol +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -contract TracingCaller { - event TraceEvent(uint256 value, string message); - address payable public callee; - - constructor(address payable _callee) public payable { - require(_callee != address(0), "Callee address cannot be zero"); - callee = _callee; - } - - function start(uint256 counter) external { - if (counter == 0) { - return; - } - - uint256 paymentAmount = 0.01 ether; - callee.transfer(paymentAmount); - - emit TraceEvent(counter, "before"); - TracingCallee(callee).consumeGas(counter); - emit TraceEvent(counter, "after"); - - try TracingCallee(callee).failingFunction{value: paymentAmount}() { - } catch { - } - - this.start(counter - 1); - } -} - -contract TracingCallee { - event CalleeCalled(uint256 counter); - - function consumeGas(uint256 counter) external { - // burn some gas - for (uint256 i = 0; i < 10; i++) { - uint256(keccak256(abi.encodePacked(i))); - } - - emit CalleeCalled(counter); - } - - function failingFunction() external payable { - require(false, "This function always fails"); - } - - // Enable contract to receive Ether - receive() external payable {} -} - diff --git a/substrate/frame/revive/rpc/examples/js/evm/.gitkeep b/substrate/frame/revive/rpc/examples/js/evm/.gitkeep deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/substrate/frame/revive/rpc/examples/js/index.html b/substrate/frame/revive/rpc/examples/js/index.html deleted file mode 100644 index 97efebe180ea1dc8c1d79cb99712ce9751142539..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/index.html +++ /dev/null @@ -1,38 +0,0 @@ -<!doctype html> -<html lang="en"> - <head> - <meta charset="UTF-8" /> - <link rel="icon" href="https://polkadot.com/favicon.ico" /> - <meta name="viewport" content="width=device-width, initial-scale=1.0" /> - <title>MetaMask Playground</title> - <style> - input { - width: 300px; - margin-right: 10px; - } - - button { - display: block; - margin-bottom: 10px; - } - </style> - </head> - <body> - <input - id="transferInput" - type="text" - style="float: left" - placeholder="Destination address" - value="0x3cd0a705a2dc65e5b1e1205896baa2be8a07c6e0" - /> - <button id="transferButton">Transfer coins</button> - - <button id="deployButton">Deploy Contract</button> - - <input id="callInput" type="text" style="float: left" placeholder="Contract address" /> - <button id="callButton">Call Contract</button> - - <button id="deployAndCallButton">Deploy and Call Contract</button> - <script type="module" src="src/web.ts"></script> - </body> -</html> diff --git a/substrate/frame/revive/rpc/examples/js/package-lock.json b/substrate/frame/revive/rpc/examples/js/package-lock.json deleted file mode 100644 index 5c7db0abc936464077ed01a147472fe662729671..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/package-lock.json +++ /dev/null @@ -1,443 +0,0 @@ -{ - "name": "demo", - "version": "0.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "demo", - "version": "0.0.0", - "dependencies": { - "ethers": "^6.13.1", - "solc": "^0.8.28" - }, - "devDependencies": { - "typescript": "^5.5.3", - "vite": "^5.4.8" - } - }, - "node_modules/@adraffy/ens-normalize": { - "version": "1.10.1", - "license": "MIT" - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.21.5", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@noble/curves": { - "version": "1.2.0", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.3.2" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@noble/hashes": { - "version": "1.3.2", - "license": "MIT", - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.24.0", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.24.0", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@types/estree": { - "version": "1.0.6", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "18.15.13", - "license": "MIT" - }, - "node_modules/aes-js": { - "version": "4.0.0-beta.5", - "license": "MIT" - }, - "node_modules/command-exists": { - "version": "1.2.9", - "resolved": "https://registry.npmjs.org/command-exists/-/command-exists-1.2.9.tgz", - "integrity": "sha512-LTQ/SGc+s0Xc0Fu5WaKnR0YiygZkm9eKFvyS+fRsU7/ZWFF8ykFM6Pc9aCVf1+xasOOZpO3BAVgVrKvsqKHV7w==", - "license": "MIT" - }, - "node_modules/commander": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz", - "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==", - "license": "MIT", - "engines": { - "node": ">= 12" - } - }, - "node_modules/esbuild": { - "version": "0.21.5", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=12" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.21.5", - "@esbuild/android-arm": "0.21.5", - "@esbuild/android-arm64": "0.21.5", - "@esbuild/android-x64": "0.21.5", - "@esbuild/darwin-arm64": "0.21.5", - "@esbuild/darwin-x64": "0.21.5", - "@esbuild/freebsd-arm64": "0.21.5", - "@esbuild/freebsd-x64": "0.21.5", - "@esbuild/linux-arm": "0.21.5", - "@esbuild/linux-arm64": "0.21.5", - "@esbuild/linux-ia32": "0.21.5", - "@esbuild/linux-loong64": "0.21.5", - "@esbuild/linux-mips64el": "0.21.5", - "@esbuild/linux-ppc64": "0.21.5", - "@esbuild/linux-riscv64": "0.21.5", - "@esbuild/linux-s390x": "0.21.5", - "@esbuild/linux-x64": "0.21.5", - "@esbuild/netbsd-x64": "0.21.5", - "@esbuild/openbsd-x64": "0.21.5", - "@esbuild/sunos-x64": "0.21.5", - "@esbuild/win32-arm64": "0.21.5", - "@esbuild/win32-ia32": "0.21.5", - "@esbuild/win32-x64": "0.21.5" - } - }, - "node_modules/ethers": { - "version": "6.13.3", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/ethers-io/" - }, - { - "type": "individual", - "url": "https://www.buymeacoffee.com/ricmoo" - } - ], - "license": "MIT", - "dependencies": { - "@adraffy/ens-normalize": "1.10.1", - "@noble/curves": "1.2.0", - "@noble/hashes": "1.3.2", - "@types/node": "18.15.13", - "aes-js": "4.0.0-beta.5", - "tslib": "2.4.0", - "ws": "8.17.1" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/follow-redirects": { - "version": "1.15.9", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", - "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/RubenVerborgh" - } - ], - "license": "MIT", - "engines": { - "node": ">=4.0" - }, - "peerDependenciesMeta": { - "debug": { - "optional": true - } - } - }, - "node_modules/js-sha3": { - "version": "0.8.0", - "resolved": "https://registry.npmjs.org/js-sha3/-/js-sha3-0.8.0.tgz", - "integrity": "sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q==", - "license": "MIT" - }, - "node_modules/memorystream": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz", - "integrity": "sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw==", - "engines": { - "node": ">= 0.10.0" - } - }, - "node_modules/nanoid": { - "version": "3.3.7", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/os-tmpdir": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", - "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/picocolors": { - "version": "1.1.0", - "dev": true, - "license": "ISC" - }, - "node_modules/postcss": { - "version": "8.4.47", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.7", - "picocolors": "^1.1.0", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/rollup": { - "version": "4.24.0", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "1.0.6" - }, - "bin": { - "rollup": "dist/bin/rollup" - }, - "engines": { - "node": ">=18.0.0", - "npm": ">=8.0.0" - }, - "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.24.0", - "@rollup/rollup-android-arm64": "4.24.0", - "@rollup/rollup-darwin-arm64": "4.24.0", - "@rollup/rollup-darwin-x64": "4.24.0", - "@rollup/rollup-linux-arm-gnueabihf": "4.24.0", - "@rollup/rollup-linux-arm-musleabihf": "4.24.0", - "@rollup/rollup-linux-arm64-gnu": "4.24.0", - "@rollup/rollup-linux-arm64-musl": "4.24.0", - "@rollup/rollup-linux-powerpc64le-gnu": "4.24.0", - "@rollup/rollup-linux-riscv64-gnu": "4.24.0", - "@rollup/rollup-linux-s390x-gnu": "4.24.0", - "@rollup/rollup-linux-x64-gnu": "4.24.0", - "@rollup/rollup-linux-x64-musl": "4.24.0", - "@rollup/rollup-win32-arm64-msvc": "4.24.0", - "@rollup/rollup-win32-ia32-msvc": "4.24.0", - "@rollup/rollup-win32-x64-msvc": "4.24.0", - "fsevents": "~2.3.2" - } - }, - "node_modules/semver": { - "version": "5.7.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", - "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", - "license": "ISC", - "bin": { - "semver": "bin/semver" - } - }, - "node_modules/solc": { - "version": "0.8.28", - "resolved": "https://registry.npmjs.org/solc/-/solc-0.8.28.tgz", - "integrity": "sha512-AFCiJ+b4RosyyNhnfdVH4ZR1+TxiL91iluPjw0EJslIu4LXGM9NYqi2z5y8TqochC4tcH9QsHfwWhOIC9jPDKA==", - "license": "MIT", - "dependencies": { - "command-exists": "^1.2.8", - "commander": "^8.1.0", - "follow-redirects": "^1.12.1", - "js-sha3": "0.8.0", - "memorystream": "^0.3.1", - "semver": "^5.5.0", - "tmp": "0.0.33" - }, - "bin": { - "solcjs": "solc.js" - }, - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/tmp": { - "version": "0.0.33", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", - "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", - "license": "MIT", - "dependencies": { - "os-tmpdir": "~1.0.2" - }, - "engines": { - "node": ">=0.6.0" - } - }, - "node_modules/tslib": { - "version": "2.4.0", - "license": "0BSD" - }, - "node_modules/typescript": { - "version": "5.6.3", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/vite": { - "version": "5.4.8", - "dev": true, - "license": "MIT", - "dependencies": { - "esbuild": "^0.21.3", - "postcss": "^8.4.43", - "rollup": "^4.20.0" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^18.0.0 || >=20.0.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^18.0.0 || >=20.0.0", - "less": "*", - "lightningcss": "^1.21.0", - "sass": "*", - "sass-embedded": "*", - "stylus": "*", - "sugarss": "*", - "terser": "^5.4.0" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "less": { - "optional": true - }, - "lightningcss": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - } - } - }, - "node_modules/ws": { - "version": "8.17.1", - "license": "MIT", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - } - } -} diff --git a/substrate/frame/revive/rpc/examples/js/package.json b/substrate/frame/revive/rpc/examples/js/package.json deleted file mode 100644 index 5b225711dc55277ef32f224d5b0ddaeb75e6e902..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "demo", - "private": true, - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "vite", - "build": "tsc && vite build", - "preview": "vite preview", - "prettier": "prettier --write .", - "solhint": "solhint \"contracts/**/*.sol\"" - }, - "dependencies": { - "@parity/revive": "^0.0.9", - "ethers": "^6.13.5", - "solc": "^0.8.28", - "solhint": "^5.0.5", - "viem": "^2.22.4" - }, - "devDependencies": { - "prettier": "^3.4.2", - "@types/bun": "^1.1.15", - "typescript": "^5.7.2", - "vite": "^5.4.11" - } -} diff --git a/substrate/frame/revive/rpc/examples/js/pvm/Errors.polkavm b/substrate/frame/revive/rpc/examples/js/pvm/Errors.polkavm deleted file mode 100644 index 48de6e0aa0c6cc1604008ba4e65c237dd557675b..0000000000000000000000000000000000000000 Binary files a/substrate/frame/revive/rpc/examples/js/pvm/Errors.polkavm and /dev/null differ diff --git a/substrate/frame/revive/rpc/examples/js/pvm/EventExample.polkavm b/substrate/frame/revive/rpc/examples/js/pvm/EventExample.polkavm deleted file mode 100644 index cea22e46adcad0dc9bf6375e676dd4923c624c89..0000000000000000000000000000000000000000 Binary files a/substrate/frame/revive/rpc/examples/js/pvm/EventExample.polkavm and /dev/null differ diff --git a/substrate/frame/revive/rpc/examples/js/pvm/Flipper.polkavm b/substrate/frame/revive/rpc/examples/js/pvm/Flipper.polkavm deleted file mode 100644 index 67f11e68f117309169a317d415ba547020c1f568..0000000000000000000000000000000000000000 Binary files a/substrate/frame/revive/rpc/examples/js/pvm/Flipper.polkavm and /dev/null differ diff --git a/substrate/frame/revive/rpc/examples/js/pvm/FlipperCaller.polkavm b/substrate/frame/revive/rpc/examples/js/pvm/FlipperCaller.polkavm deleted file mode 100644 index b7b037c1c7b31018fccc0d7bfc0e058d05b68588..0000000000000000000000000000000000000000 Binary files a/substrate/frame/revive/rpc/examples/js/pvm/FlipperCaller.polkavm and /dev/null differ diff --git a/substrate/frame/revive/rpc/examples/js/pvm/PiggyBank.polkavm b/substrate/frame/revive/rpc/examples/js/pvm/PiggyBank.polkavm deleted file mode 100644 index 2fc5e139825aa174d85127c3f29543fd7ebe05fc..0000000000000000000000000000000000000000 Binary files a/substrate/frame/revive/rpc/examples/js/pvm/PiggyBank.polkavm and /dev/null differ diff --git a/substrate/frame/revive/rpc/examples/js/src/balance.ts b/substrate/frame/revive/rpc/examples/js/src/balance.ts deleted file mode 100644 index 1261dcab7812f9248c2cce86afb2874c15174507..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/balance.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { walletClient } from './lib.ts' - -const recipient = '0x8D97689C9818892B700e27F316cc3E41e17fBeb9' -try { - console.log(`Recipient balance: ${await walletClient.getBalance({ address: recipient })}`) -} catch (err) { - console.error(err) -} diff --git a/substrate/frame/revive/rpc/examples/js/src/build-contracts.ts b/substrate/frame/revive/rpc/examples/js/src/build-contracts.ts deleted file mode 100644 index 17f5dffd9973e1edf0a22ecbb98bf75bef5b1ebf..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/build-contracts.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { compile, SolcOutput } from '@parity/revive' -import { format } from 'prettier' -import { parseArgs } from 'node:util' -import solc from 'solc' -import { readdirSync, readFileSync, writeFileSync } from 'fs' -import { basename, join } from 'path' - -type CompileInput = Parameters<typeof compile>[0] - -const { - values: { filter, solcOnly }, -} = parseArgs({ - args: process.argv.slice(2), - options: { - filter: { - type: 'string', - short: 'f', - }, - solcOnly: { - type: 'boolean', - short: 's', - }, - }, -}) - -function evmCompile(sources: CompileInput) { - const input = { - language: 'Solidity', - sources, - settings: { - outputSelection: { - '*': { - '*': ['*'], - }, - }, - }, - } - - return solc.compile(JSON.stringify(input)) -} - -console.log('Compiling contracts...') - -const rootDir = join(__dirname, '..') -const contractsDir = join(rootDir, 'contracts') -const abiDir = join(rootDir, 'abi') -const pvmDir = join(rootDir, 'pvm') -const evmDir = join(rootDir, 'evm') - -const input = readdirSync(contractsDir) - .filter((f) => f.endsWith('.sol')) - .filter((f) => !filter || f.includes(filter)) - -for (const file of input) { - console.log(`🔨 Compiling ${file}...`) - const name = basename(file, '.sol') - const input = { - [name]: { content: readFileSync(join(contractsDir, file), 'utf8') }, - } - - if (!solcOnly) { - console.log('Compiling with revive...') - const reviveOut = await compile(input, { bin: 'resolc' }) - - for (const contracts of Object.values(reviveOut.contracts)) { - for (const [name, contract] of Object.entries(contracts)) { - console.log(`📜 Add PVM contract ${name}`) - writeFileSync( - join(pvmDir, `${name}.polkavm`), - Buffer.from(contract.evm.bytecode.object, 'hex') - ) - } - } - } - - console.log(`Compile with solc ${file}`) - const evmOut = JSON.parse(evmCompile(input)) as SolcOutput - - for (const contracts of Object.values(evmOut.contracts)) { - for (const [name, contract] of Object.entries(contracts)) { - console.log(`📜 Add EVM contract ${name}`) - writeFileSync( - join(evmDir, `${name}.bin`), - Buffer.from(contract.evm.bytecode.object, 'hex') - ) - - const abi = contract.abi - const abiName = `${name}Abi` - writeFileSync(join(abiDir, `${name}.json`), JSON.stringify(abi, null, 2)) - - writeFileSync( - join(abiDir, `${name}.ts`), - await format(`export const ${abiName} = ${JSON.stringify(abi, null, 2)} as const`, { - parser: 'typescript', - }) - ) - } - } -} diff --git a/substrate/frame/revive/rpc/examples/js/src/event.ts b/substrate/frame/revive/rpc/examples/js/src/event.ts deleted file mode 100644 index 2e672a9772ff412ae6f8e8c5bd36c41f5c9105a5..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/event.ts +++ /dev/null @@ -1,29 +0,0 @@ -//! Run with bun run script-event.ts - -import { abi } from '../abi/event.ts' -import { assert, getByteCode, walletClient } from './lib.ts' - -const deployHash = await walletClient.deployContract({ - abi, - bytecode: getByteCode('event'), -}) -const deployReceipt = await walletClient.waitForTransactionReceipt({ hash: deployHash }) -const contractAddress = deployReceipt.contractAddress -console.log('Contract deployed:', contractAddress) -assert(contractAddress, 'Contract address should be set') - -const { request } = await walletClient.simulateContract({ - account: walletClient.account, - address: contractAddress, - abi, - functionName: 'triggerEvent', -}) - -const hash = await walletClient.writeContract(request) -const receipt = await walletClient.waitForTransactionReceipt({ hash }) -console.log(`Receipt: ${receipt.status}`) -console.log(`Logs receipt: ${receipt.status}`) - -for (const log of receipt.logs) { - console.log('Event log:', log) -} diff --git a/substrate/frame/revive/rpc/examples/js/src/fixtures/debug_traceCall.json b/substrate/frame/revive/rpc/examples/js/src/fixtures/debug_traceCall.json deleted file mode 100644 index b017c97693ddc51577edd400bb6c67ccdbabe8e9..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/fixtures/debug_traceCall.json +++ /dev/null @@ -1,143 +0,0 @@ -{ - "from": "0x0000000000000000000000000000000000000000", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_addr>", - "input": "0x95805dad0000000000000000000000000000000000000000000000000000000000000002", - "calls": [ - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0x", - "value": "0x2386f26fc10000", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0xa329e8de0000000000000000000000000000000000000000000000000000000000000002", - "logs": [ - { - "address": "<contract_callee_addr>", - "topics": [ - "0xa07465e8ec189714f79f3786a8f616baf78ebd9cb1769bd61f18de45f2567360" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000002", - "position": "0x0" - } - ], - "value": "0x0", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0xd1b96663", - "output": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001a546869732066756e6374696f6e20616c77617973206661696c73000000000000", - "error": "execution reverted", - "revertReason": "This function always fails", - "value": "0x2386f26fc10000", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_addr>", - "input": "0x95805dad0000000000000000000000000000000000000000000000000000000000000001", - "calls": [ - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0x", - "value": "0x2386f26fc10000", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0xa329e8de0000000000000000000000000000000000000000000000000000000000000001", - "logs": [ - { - "address": "<contract_callee_addr>", - "topics": [ - "0xa07465e8ec189714f79f3786a8f616baf78ebd9cb1769bd61f18de45f2567360" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000001", - "position": "0x0" - } - ], - "value": "0x0", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0xd1b96663", - "output": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001a546869732066756e6374696f6e20616c77617973206661696c73000000000000", - "error": "execution reverted", - "revertReason": "This function always fails", - "value": "0x2386f26fc10000", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_addr>", - "input": "0x95805dad0000000000000000000000000000000000000000000000000000000000000000", - "value": "0x0", - "type": "CALL" - } - ], - "logs": [ - { - "address": "<contract_addr>", - "topics": [ - "0x25d760f35a7a9cb2bffd2ea8756913655b3786c642f300a702e2934062763549" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000066265666f72650000000000000000000000000000000000000000000000000000", - "position": "0x1" - }, - { - "address": "<contract_addr>", - "topics": [ - "0x25d760f35a7a9cb2bffd2ea8756913655b3786c642f300a702e2934062763549" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000056166746572000000000000000000000000000000000000000000000000000000", - "position": "0x2" - } - ], - "value": "0x0", - "type": "CALL" - } - ], - "logs": [ - { - "address": "<contract_addr>", - "topics": ["0x25d760f35a7a9cb2bffd2ea8756913655b3786c642f300a702e2934062763549"], - "data": "0x0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000066265666f72650000000000000000000000000000000000000000000000000000", - "position": "0x1" - }, - { - "address": "<contract_addr>", - "topics": ["0x25d760f35a7a9cb2bffd2ea8756913655b3786c642f300a702e2934062763549"], - "data": "0x0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000056166746572000000000000000000000000000000000000000000000000000000", - "position": "0x2" - } - ], - "value": "0x0", - "type": "CALL" -} diff --git a/substrate/frame/revive/rpc/examples/js/src/fixtures/trace_block.json b/substrate/frame/revive/rpc/examples/js/src/fixtures/trace_block.json deleted file mode 100644 index 952c1c5ce084eb6997684f1afb346a540f0c13b5..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/fixtures/trace_block.json +++ /dev/null @@ -1,152 +0,0 @@ -[ - { - "txHash": "<hash>", - "result": { - "from": "<caller>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_addr>", - "input": "0x95805dad0000000000000000000000000000000000000000000000000000000000000002", - "calls": [ - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0x", - "value": "0x2386f26fc10000", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0xa329e8de0000000000000000000000000000000000000000000000000000000000000002", - "logs": [ - { - "address": "<contract_callee_addr>", - "topics": [ - "0xa07465e8ec189714f79f3786a8f616baf78ebd9cb1769bd61f18de45f2567360" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000002", - "position": "0x0" - } - ], - "value": "0x0", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0xd1b96663", - "output": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001a546869732066756e6374696f6e20616c77617973206661696c73000000000000", - "error": "execution reverted", - "revertReason": "This function always fails", - "value": "0x2386f26fc10000", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_addr>", - "input": "0x95805dad0000000000000000000000000000000000000000000000000000000000000001", - "calls": [ - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0x", - "value": "0x2386f26fc10000", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0xa329e8de0000000000000000000000000000000000000000000000000000000000000001", - "logs": [ - { - "address": "<contract_callee_addr>", - "topics": [ - "0xa07465e8ec189714f79f3786a8f616baf78ebd9cb1769bd61f18de45f2567360" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000001", - "position": "0x0" - } - ], - "value": "0x0", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0xd1b96663", - "output": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001a546869732066756e6374696f6e20616c77617973206661696c73000000000000", - "error": "execution reverted", - "revertReason": "This function always fails", - "value": "0x2386f26fc10000", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_addr>", - "input": "0x95805dad0000000000000000000000000000000000000000000000000000000000000000", - "value": "0x0", - "type": "CALL" - } - ], - "logs": [ - { - "address": "<contract_addr>", - "topics": [ - "0x25d760f35a7a9cb2bffd2ea8756913655b3786c642f300a702e2934062763549" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000066265666f72650000000000000000000000000000000000000000000000000000", - "position": "0x1" - }, - { - "address": "<contract_addr>", - "topics": [ - "0x25d760f35a7a9cb2bffd2ea8756913655b3786c642f300a702e2934062763549" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000056166746572000000000000000000000000000000000000000000000000000000", - "position": "0x2" - } - ], - "value": "0x0", - "type": "CALL" - } - ], - "logs": [ - { - "address": "<contract_addr>", - "topics": [ - "0x25d760f35a7a9cb2bffd2ea8756913655b3786c642f300a702e2934062763549" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000066265666f72650000000000000000000000000000000000000000000000000000", - "position": "0x1" - }, - { - "address": "<contract_addr>", - "topics": [ - "0x25d760f35a7a9cb2bffd2ea8756913655b3786c642f300a702e2934062763549" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000056166746572000000000000000000000000000000000000000000000000000000", - "position": "0x2" - } - ], - "value": "0x0", - "type": "CALL" - } - } -] diff --git a/substrate/frame/revive/rpc/examples/js/src/fixtures/trace_transaction.json b/substrate/frame/revive/rpc/examples/js/src/fixtures/trace_transaction.json deleted file mode 100644 index 9ef9c7c4dfca71cbd0067a58317304c5325bf19d..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/fixtures/trace_transaction.json +++ /dev/null @@ -1,143 +0,0 @@ -{ - "from": "<caller>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_addr>", - "input": "0x95805dad0000000000000000000000000000000000000000000000000000000000000002", - "calls": [ - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0x", - "value": "0x2386f26fc10000", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0xa329e8de0000000000000000000000000000000000000000000000000000000000000002", - "logs": [ - { - "address": "<contract_callee_addr>", - "topics": [ - "0xa07465e8ec189714f79f3786a8f616baf78ebd9cb1769bd61f18de45f2567360" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000002", - "position": "0x0" - } - ], - "value": "0x0", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0xd1b96663", - "output": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001a546869732066756e6374696f6e20616c77617973206661696c73000000000000", - "error": "execution reverted", - "revertReason": "This function always fails", - "value": "0x2386f26fc10000", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_addr>", - "input": "0x95805dad0000000000000000000000000000000000000000000000000000000000000001", - "calls": [ - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0x", - "value": "0x2386f26fc10000", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0xa329e8de0000000000000000000000000000000000000000000000000000000000000001", - "logs": [ - { - "address": "<contract_callee_addr>", - "topics": [ - "0xa07465e8ec189714f79f3786a8f616baf78ebd9cb1769bd61f18de45f2567360" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000001", - "position": "0x0" - } - ], - "value": "0x0", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_callee_addr>", - "input": "0xd1b96663", - "output": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001a546869732066756e6374696f6e20616c77617973206661696c73000000000000", - "error": "execution reverted", - "revertReason": "This function always fails", - "value": "0x2386f26fc10000", - "type": "CALL" - }, - { - "from": "<contract_addr>", - "gas": "0x42", - "gasUsed": "0x42", - "to": "<contract_addr>", - "input": "0x95805dad0000000000000000000000000000000000000000000000000000000000000000", - "value": "0x0", - "type": "CALL" - } - ], - "logs": [ - { - "address": "<contract_addr>", - "topics": [ - "0x25d760f35a7a9cb2bffd2ea8756913655b3786c642f300a702e2934062763549" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000066265666f72650000000000000000000000000000000000000000000000000000", - "position": "0x1" - }, - { - "address": "<contract_addr>", - "topics": [ - "0x25d760f35a7a9cb2bffd2ea8756913655b3786c642f300a702e2934062763549" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000056166746572000000000000000000000000000000000000000000000000000000", - "position": "0x2" - } - ], - "value": "0x0", - "type": "CALL" - } - ], - "logs": [ - { - "address": "<contract_addr>", - "topics": ["0x25d760f35a7a9cb2bffd2ea8756913655b3786c642f300a702e2934062763549"], - "data": "0x0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000066265666f72650000000000000000000000000000000000000000000000000000", - "position": "0x1" - }, - { - "address": "<contract_addr>", - "topics": ["0x25d760f35a7a9cb2bffd2ea8756913655b3786c642f300a702e2934062763549"], - "data": "0x0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000056166746572000000000000000000000000000000000000000000000000000000", - "position": "0x2" - } - ], - "value": "0x0", - "type": "CALL" -} diff --git a/substrate/frame/revive/rpc/examples/js/src/geth-diff.test.ts b/substrate/frame/revive/rpc/examples/js/src/geth-diff.test.ts deleted file mode 100644 index 33e38fccd8a81d5358db9bd62f5d189e2d46da05..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/geth-diff.test.ts +++ /dev/null @@ -1,531 +0,0 @@ -import { - jsonRpcErrors, - createEnv, - getByteCode, - killProcessOnPort, - waitForHealth, - polkadotSdkPath, - visit, -} from './util.ts' -import { afterAll, afterEach, describe, expect, test } from 'bun:test' -import { encodeFunctionData, Hex, parseEther, decodeEventLog } from 'viem' -import { ErrorsAbi } from '../abi/Errors' -import { EventExampleAbi } from '../abi/EventExample' -import { TracingCallerAbi } from '../abi/TracingCaller' -import { TracingCalleeAbi } from '../abi/TracingCallee' -import { Subprocess, spawn } from 'bun' -import { fail } from 'node:assert' - -const procs: Subprocess[] = [] -if (process.env.START_GETH) { - process.env.USE_GETH = 'true' - procs.push( - // Run geth on port 8546 - await (async () => { - killProcessOnPort(8546) - console.log('Starting geth') - const proc = spawn( - 'geth --http --http.api web3,eth,debug,personal,net --http.port 8546 --dev --verbosity 0'.split( - ' ' - ), - { stdout: Bun.file('/tmp/geth.out.log'), stderr: Bun.file('/tmp/geth.err.log') } - ) - - await waitForHealth('http://localhost:8546').catch() - return proc - })() - ) -} - -if (process.env.START_SUBSTRATE_NODE) { - procs.push( - //Run the substate node - (() => { - killProcessOnPort(9944) - console.log('Starting substrate node') - return spawn( - [ - './target/debug/substrate-node', - '--dev', - '-l=error,evm=debug,sc_rpc_server=info,runtime::revive=debug', - ], - { - stdout: Bun.file('/tmp/substrate-node.out.log'), - stderr: Bun.file('/tmp/substrate-node.err.log'), - cwd: polkadotSdkPath, - } - ) - })() - ) -} - -if (process.env.START_ETH_RPC) { - process.env.USE_ETH_RPC = 'true' - // Run eth-rpc on 8545 - procs.push( - await (async () => { - killProcessOnPort(8545) - console.log('Starting eth-rpc') - const proc = spawn( - [ - './target/debug/eth-rpc', - '--dev', - '--node-rpc-url=ws://localhost:9944', - '-l=rpc-metrics=debug,eth-rpc=debug', - ], - { - stdout: Bun.file('/tmp/eth-rpc.out.log'), - stderr: Bun.file('/tmp/eth-rpc.err.log'), - cwd: polkadotSdkPath, - } - ) - await waitForHealth('http://localhost:8545').catch() - return proc - })() - ) -} - -afterEach(() => { - jsonRpcErrors.length = 0 -}) - -afterAll(async () => { - procs.forEach((proc) => proc.kill()) -}) - -const envs = await Promise.all([ - ...(process.env.USE_GETH ? [createEnv('geth')] : []), - ...(process.env.USE_ETH_RPC ? [createEnv('eth-rpc')] : []), -]) - -for (const env of envs) { - describe(env.serverWallet.chain.name, () => { - const getErrorTesterAddr = (() => { - let contractAddress: Hex = '0x' - return async () => { - if (contractAddress !== '0x') { - return contractAddress - } - const hash = await env.serverWallet.deployContract({ - abi: ErrorsAbi, - bytecode: getByteCode('Errors', env.evm), - }) - const deployReceipt = await env.serverWallet.waitForTransactionReceipt({ hash }) - contractAddress = deployReceipt.contractAddress! - return contractAddress - } - })() - - const getEventExampleAddr = (() => { - let contractAddress: Hex = '0x' - return async () => { - if (contractAddress !== '0x') { - return contractAddress - } - const hash = await env.serverWallet.deployContract({ - abi: EventExampleAbi, - bytecode: getByteCode('EventExample', env.evm), - }) - const deployReceipt = await env.serverWallet.waitForTransactionReceipt({ hash }) - contractAddress = deployReceipt.contractAddress! - return contractAddress - } - })() - - const getTracingExampleAddrs = (() => { - let callerAddr: Hex = '0x' - let calleeAddr: Hex = '0x' - return async () => { - if (callerAddr !== '0x') { - return [callerAddr, calleeAddr] - } - calleeAddr = await (async () => { - const hash = await env.serverWallet.deployContract({ - abi: TracingCalleeAbi, - bytecode: getByteCode('TracingCallee', env.evm), - }) - const receipt = await env.serverWallet.waitForTransactionReceipt({ - hash, - }) - return receipt.contractAddress! - })() - - callerAddr = await (async () => { - const hash = await env.serverWallet.deployContract({ - abi: TracingCallerAbi, - args: [calleeAddr], - bytecode: getByteCode('TracingCaller', env.evm), - value: parseEther('10'), - }) - const receipt = await env.serverWallet.waitForTransactionReceipt({ - hash, - }) - return receipt.contractAddress! - })() - - return [callerAddr, calleeAddr] - } - })() - - test('triggerAssertError', async () => { - try { - await env.accountWallet.readContract({ - address: await getErrorTesterAddr(), - abi: ErrorsAbi, - functionName: 'triggerAssertError', - }) - fail('Expect call to fail') - } catch (err) { - const lastJsonRpcError = jsonRpcErrors.pop() - expect(lastJsonRpcError?.code).toBe(3) - expect(lastJsonRpcError?.data).toBe( - '0x4e487b710000000000000000000000000000000000000000000000000000000000000001' - ) - expect(lastJsonRpcError?.message).toBeOneOf([ - 'execution reverted: assert(false)', - 'execution reverted: panic: assertion failed (0x01)', - ]) - } - }) - - test('triggerRevertError', async () => { - try { - await env.accountWallet.readContract({ - address: await getErrorTesterAddr(), - abi: ErrorsAbi, - functionName: 'triggerRevertError', - }) - fail('Expect call to fail') - } catch (err) { - const lastJsonRpcError = jsonRpcErrors.pop() - expect(lastJsonRpcError?.code).toBe(3) - expect(lastJsonRpcError?.message).toBeOneOf([ - 'execution reverted: This is a revert error', - 'execution reverted: revert: This is a revert error', - ]) - expect(lastJsonRpcError?.data).toBe( - '0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001654686973206973206120726576657274206572726f7200000000000000000000' - ) - } - }) - - test('triggerDivisionByZero', async () => { - try { - await env.accountWallet.readContract({ - address: await getErrorTesterAddr(), - abi: ErrorsAbi, - functionName: 'triggerDivisionByZero', - }) - expect.assertions(3) - } catch (err) { - const lastJsonRpcError = jsonRpcErrors.pop() - expect(lastJsonRpcError?.code).toBe(3) - expect(lastJsonRpcError?.data).toBe( - '0x4e487b710000000000000000000000000000000000000000000000000000000000000012' - ) - expect(lastJsonRpcError?.message).toBeOneOf([ - 'execution reverted: division or modulo by zero', - 'execution reverted: panic: division or modulo by zero (0x12)', - ]) - } - }) - - test('triggerOutOfBoundsError', async () => { - try { - await env.accountWallet.readContract({ - address: await getErrorTesterAddr(), - abi: ErrorsAbi, - functionName: 'triggerOutOfBoundsError', - }) - fail('Expect call to fail') - } catch (err) { - const lastJsonRpcError = jsonRpcErrors.pop() - expect(lastJsonRpcError?.code).toBe(3) - expect(lastJsonRpcError?.data).toBe( - '0x4e487b710000000000000000000000000000000000000000000000000000000000000032' - ) - expect(lastJsonRpcError?.message).toBeOneOf([ - 'execution reverted: out-of-bounds access of an array or bytesN', - 'execution reverted: panic: array out-of-bounds access (0x32)', - ]) - } - }) - - test('triggerCustomError', async () => { - try { - await env.accountWallet.readContract({ - address: await getErrorTesterAddr(), - abi: ErrorsAbi, - functionName: 'triggerCustomError', - }) - fail('Expect call to fail') - } catch (err) { - const lastJsonRpcError = jsonRpcErrors.pop() - expect(lastJsonRpcError?.code).toBe(3) - expect(lastJsonRpcError?.data).toBe( - '0x8d6ea8be0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001654686973206973206120637573746f6d206572726f7200000000000000000000' - ) - expect(lastJsonRpcError?.message).toBe('execution reverted') - } - }) - - test('eth_call (not enough funds)', async () => { - try { - await env.emptyWallet.simulateContract({ - address: await getErrorTesterAddr(), - abi: ErrorsAbi, - functionName: 'valueMatch', - value: parseEther('10'), - args: [parseEther('10')], - }) - fail('Expect call to fail') - } catch (err) { - const lastJsonRpcError = jsonRpcErrors.pop() - expect(lastJsonRpcError?.code).toBe(-32000) - expect(lastJsonRpcError?.message).toInclude('insufficient funds') - expect(lastJsonRpcError?.data).toBeUndefined() - } - }) - - test('eth_call transfer (not enough funds)', async () => { - const value = parseEther('10') - const balance = await env.emptyWallet.getBalance(env.emptyWallet.account) - expect(balance, 'Balance should be less than 10').toBeLessThan(value) - try { - await env.emptyWallet.sendTransaction({ - to: '0x75E480dB528101a381Ce68544611C169Ad7EB342', - value, - }) - fail('Expect call to fail') - } catch (err) { - const lastJsonRpcError = jsonRpcErrors.pop() - expect(lastJsonRpcError?.code).toBe(-32000) - expect(lastJsonRpcError?.message).toInclude('insufficient funds') - expect(lastJsonRpcError?.data).toBeUndefined() - } - }) - - test('eth_estimate (not enough funds)', async () => { - try { - await env.emptyWallet.estimateContractGas({ - address: await getErrorTesterAddr(), - abi: ErrorsAbi, - functionName: 'valueMatch', - value: parseEther('10'), - args: [parseEther('10')], - }) - fail('Expect call to fail') - } catch (err) { - const lastJsonRpcError = jsonRpcErrors.pop() - expect(lastJsonRpcError?.code).toBe(-32000) - expect(lastJsonRpcError?.message).toInclude('insufficient funds') - expect(lastJsonRpcError?.data).toBeUndefined() - } - }) - - test('eth_estimate call caller (not enough funds)', async () => { - try { - await env.emptyWallet.estimateContractGas({ - address: await getErrorTesterAddr(), - abi: ErrorsAbi, - functionName: 'valueMatch', - value: parseEther('10'), - args: [parseEther('10')], - }) - fail('Expect call to fail') - } catch (err) { - const lastJsonRpcError = jsonRpcErrors.pop() - expect(lastJsonRpcError?.code).toBe(-32000) - expect(lastJsonRpcError?.message).toInclude('insufficient funds') - expect(lastJsonRpcError?.data).toBeUndefined() - } - }) - - test('eth_estimate (revert)', async () => { - try { - await env.serverWallet.estimateContractGas({ - address: await getErrorTesterAddr(), - abi: ErrorsAbi, - functionName: 'valueMatch', - value: parseEther('11'), - args: [parseEther('10')], - }) - fail('Expect call to fail') - } catch (err) { - const lastJsonRpcError = jsonRpcErrors.pop() - expect(lastJsonRpcError?.code).toBe(3) - expect(lastJsonRpcError?.message).toBeOneOf([ - 'execution reverted: msg.value does not match value', - 'execution reverted: revert: msg.value does not match value', - ]) - expect(lastJsonRpcError?.data).toBe( - '0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001e6d73672e76616c756520646f6573206e6f74206d617463682076616c75650000' - ) - } - }) - - test('eth_get_balance (no account)', async () => { - const balance = await env.serverWallet.getBalance({ - address: '0x0000000000000000000000000000000000000123', - }) - expect(balance).toBe(0n) - }) - - test('eth_estimate (not enough funds to cover gas specified)', async () => { - let balance = await env.serverWallet.getBalance(env.emptyWallet.account) - expect(balance).toBe(0n) - try { - await env.emptyWallet.estimateContractGas({ - address: await getErrorTesterAddr(), - abi: ErrorsAbi, - functionName: 'setState', - args: [true], - }) - fail('Expect call to fail') - } catch (err) { - const lastJsonRpcError = jsonRpcErrors.pop() - expect(lastJsonRpcError?.code).toBe(-32000) - expect(lastJsonRpcError?.message).toInclude('insufficient funds') - expect(lastJsonRpcError?.data).toBeUndefined() - } - }) - - test('eth_estimate (no gas specified)', async () => { - let balance = await env.serverWallet.getBalance(env.emptyWallet.account) - expect(balance).toBe(0n) - - const data = encodeFunctionData({ - abi: ErrorsAbi, - functionName: 'setState', - args: [true], - }) - - await env.emptyWallet.request({ - method: 'eth_estimateGas', - params: [ - { - data, - from: env.emptyWallet.account.address, - to: await getErrorTesterAddr(), - }, - ], - }) - }) - - test('logs', async () => { - let address = await getEventExampleAddr() - let { request } = await env.serverWallet.simulateContract({ - address, - abi: EventExampleAbi, - functionName: 'triggerEvent', - }) - - let hash = await env.serverWallet.writeContract(request) - let receipt = await env.serverWallet.waitForTransactionReceipt({ hash }) - const logs = await env.serverWallet.getLogs({ - address, - blockHash: receipt.blockHash, - }) - expect(logs).toHaveLength(1) - expect(logs[0]).toMatchObject({ - address, - data: '0x00000000000000000000000000000000000000000000000000000000000030390000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20776f726c64000000000000000000000000000000000000000000', - transactionHash: hash, - }) - - expect( - decodeEventLog({ - abi: EventExampleAbi, - data: logs[0].data, - topics: logs[0].topics, - }) - ).toEqual({ - eventName: 'ExampleEvent', - args: { - sender: env.serverWallet.account.address, - value: 12345n, - message: 'Hello world', - }, - }) - }) - - test('tracing', async () => { - let [callerAddr, calleeAddr] = await getTracingExampleAddrs() - - const receipt = await (async () => { - const { request } = await env.serverWallet.simulateContract({ - address: callerAddr, - abi: TracingCallerAbi, - functionName: 'start', - args: [2n], - }) - const hash = await env.serverWallet.writeContract(request) - return await env.serverWallet.waitForTransactionReceipt({ hash }) - })() - - const visitor: Parameters<typeof visit>[1] = (key, value) => { - switch (key) { - case 'address': - case 'from': - case 'to': { - if (value === callerAddr) { - return '<contract_addr>' - } else if (value === calleeAddr) { - return '<contract_callee_addr>' - } else if (value == env.serverWallet.account.address.toLowerCase()) { - return '<caller>' - } - - return value - } - case 'revertReason': - return value.startsWith('revert: ') ? value.slice('revert: '.length) : value - - case 'gas': - case 'gasUsed': { - return '0x42' - } - case 'txHash': { - return '<hash>' - } - default: { - return value - } - } - } - - // test debug_traceTransaction - { - const fixture = await Bun.file('./src/fixtures/trace_transaction.json').json() - const res = await env.debugClient.traceTransaction(receipt.transactionHash, { - withLog: true, - }) - expect(visit(res, visitor)).toEqual(fixture) - } - - // test debug_traceBlock - { - const res = await env.debugClient.traceBlock(receipt.blockNumber, { withLog: true }) - const fixture = await Bun.file('./src/fixtures/trace_block.json').json() - expect(visit(res, visitor)).toEqual(fixture) - } - - // test debug_traceCall - { - const fixture = await Bun.file('./src/fixtures/debug_traceCall.json').json() - const res = await env.debugClient.traceCall( - { - to: callerAddr, - data: encodeFunctionData({ - abi: TracingCallerAbi, - functionName: 'start', - args: [2n], - }), - }, - { withLog: true } - ) - expect(visit(res, visitor)).toEqual(fixture) - } - }) - }) -} diff --git a/substrate/frame/revive/rpc/examples/js/src/lib.ts b/substrate/frame/revive/rpc/examples/js/src/lib.ts deleted file mode 100644 index 1470f492e34d6d451f90ddc161c054701f125863..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/lib.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { readFileSync } from 'node:fs' -import { spawn } from 'node:child_process' -import { parseArgs } from 'node:util' -import { createWalletClient, defineChain, Hex, http, parseEther, publicActions } from 'viem' -import { privateKeyToAccount } from 'viem/accounts' - -const { - values: { geth, proxy, westend, endowment, ['private-key']: privateKey }, -} = parseArgs({ - args: process.argv.slice(2), - options: { - ['private-key']: { - type: 'string', - short: 'k', - }, - endowment: { - type: 'string', - short: 'e', - }, - proxy: { - type: 'boolean', - }, - geth: { - type: 'boolean', - }, - westend: { - type: 'boolean', - }, - }, -}) - -if (geth) { - console.log('Testing with Geth') - const child = spawn( - 'geth', - [ - '--http', - '--http.api', - 'web3,eth,debug,personal,net', - '--http.port', - process.env.GETH_PORT ?? '8546', - '--dev', - '--verbosity', - '0', - ], - { stdio: 'inherit' } - ) - - process.on('exit', () => child.kill()) - child.unref() - await new Promise((resolve) => setTimeout(resolve, 500)) -} -const rpcUrl = proxy - ? 'http://localhost:8080' - : westend - ? 'https://westend-asset-hub-eth-rpc.polkadot.io' - : geth - ? 'http://localhost:8546' - : 'http://localhost:8545' - -export const chain = defineChain({ - id: geth ? 1337 : 420420420, - name: 'Asset Hub Westend', - network: 'asset-hub', - nativeCurrency: { - name: 'Westie', - symbol: 'WST', - decimals: 18, - }, - rpcUrls: { - default: { - http: [rpcUrl], - }, - }, - testnet: true, -}) - -const wallet = createWalletClient({ - transport: http(), - chain, -}) -const [account] = await wallet.getAddresses() -export const serverWalletClient = createWalletClient({ - account, - transport: http(), - chain, -}) - -export const walletClient = await (async () => { - if (privateKey) { - const account = privateKeyToAccount(`0x${privateKey}`) - console.log(`Wallet address ${account.address}`) - - const wallet = createWalletClient({ - account, - transport: http(), - chain, - }) - - if (endowment) { - await serverWalletClient.sendTransaction({ - to: account.address, - value: parseEther(endowment), - }) - console.log(`Endowed address ${account.address} with: ${endowment}`) - } - - return wallet.extend(publicActions) - } else { - return serverWalletClient.extend(publicActions) - } -})() - -/** - * Get one of the pre-built contracts - * @param name - the contract name - */ -export function getByteCode(name: string): Hex { - const bytecode = geth ? readFileSync(`evm/${name}.bin`) : readFileSync(`pvm/${name}.polkavm`) - return `0x${Buffer.from(bytecode).toString('hex')}` -} - -export function assert(condition: any, message: string): asserts condition { - if (!condition) { - throw new Error(message) - } -} diff --git a/substrate/frame/revive/rpc/examples/js/src/piggy-bank.ts b/substrate/frame/revive/rpc/examples/js/src/piggy-bank.ts deleted file mode 100644 index 4983a6f3b301ea311fa7b5ff00f60a46eda3e607..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/piggy-bank.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { assert, getByteCode, walletClient } from './lib.ts' -import { PiggyBankAbi } from '../abi/piggyBank.ts' -import { parseEther } from 'viem' - -const hash = await walletClient.deployContract({ - abi: PiggyBankAbi, - bytecode: getByteCode('PiggyBank'), -}) -const deployReceipt = await walletClient.waitForTransactionReceipt({ hash }) -const contractAddress = deployReceipt.contractAddress -console.log('Contract deployed:', contractAddress) -assert(contractAddress, 'Contract address should be set') - -// Deposit 10 WST -{ - const result = await walletClient.estimateContractGas({ - account: walletClient.account, - address: contractAddress, - abi: PiggyBankAbi, - functionName: 'deposit', - value: parseEther('10'), - }) - - console.log(`Gas estimate: ${result}`) - - const { request } = await walletClient.simulateContract({ - account: walletClient.account, - address: contractAddress, - abi: PiggyBankAbi, - functionName: 'deposit', - value: parseEther('10'), - }) - - const hash = await walletClient.writeContract(request) - const receipt = await walletClient.waitForTransactionReceipt({ hash }) - console.log(`Deposit receipt: ${receipt.status}`) -} - -// Withdraw 5 WST -{ - const { request } = await walletClient.simulateContract({ - account: walletClient.account, - address: contractAddress, - abi: PiggyBankAbi, - functionName: 'withdraw', - args: [parseEther('5')], - }) - - const hash = await walletClient.writeContract(request) - const receipt = await walletClient.waitForTransactionReceipt({ hash }) - console.log(`Withdraw receipt: ${receipt.status}`) - - // Check remaining balance - const balance = await walletClient.readContract({ - address: contractAddress, - abi: PiggyBankAbi, - functionName: 'getDeposit', - }) - - console.log(`Get deposit: ${balance}`) - console.log( - `Get contract balance: ${await walletClient.getBalance({ address: contractAddress })}` - ) -} diff --git a/substrate/frame/revive/rpc/examples/js/src/solc.d.ts b/substrate/frame/revive/rpc/examples/js/src/solc.d.ts deleted file mode 100644 index 813829f40b6dcbc0d1448c0fd31673ffb5ed3ab5..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/solc.d.ts +++ /dev/null @@ -1,83 +0,0 @@ -declare module 'solc' { - // Basic types for input/output handling - export interface CompileInput { - language: string - sources: { - [fileName: string]: { - content: string - } - } - settings?: { - optimizer?: { - enabled: boolean - runs: number - } - outputSelection: { - [fileName: string]: { - [contractName: string]: string[] - } - } - } - } - - export interface CompileOutput { - errors?: Array<{ - component: string - errorCode: string - formattedMessage: string - message: string - severity: string - sourceLocation?: { - file: string - start: number - end: number - } - type: string - }> - sources?: { - [fileName: string]: { - id: number - ast: object - } - } - contracts?: { - [fileName: string]: { - [contractName: string]: { - abi: object[] - evm: { - bytecode: { - object: string - sourceMap: string - linkReferences: { - [fileName: string]: { - [libraryName: string]: Array<{ - start: number - length: number - }> - } - } - } - deployedBytecode: { - object: string - sourceMap: string - linkReferences: { - [fileName: string]: { - [libraryName: string]: Array<{ - start: number - length: number - }> - } - } - } - } - } - } - } - } - - // Main exported functions - export function compile( - input: string | CompileInput, - options?: { import: (path: string) => { contents: string } } - ): string -} diff --git a/substrate/frame/revive/rpc/examples/js/src/spammer.ts b/substrate/frame/revive/rpc/examples/js/src/spammer.ts deleted file mode 100644 index 682bfcabb26981001fea569f6dc15d2f65841623..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/spammer.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { spawn } from 'bun' -import { - createEnv, - getByteCode, - killProcessOnPort, - polkadotSdkPath, - wait, - waitForHealth, -} from './util' -import { FlipperAbi } from '../abi/Flipper' - -if (process.env.START_SUBSTRATE_NODE) { - //Run the substate node - console.log('🚀 Start substrate-node...') - killProcessOnPort(9944) - spawn( - [ - './target/debug/substrate-node', - '--dev', - '-l=error,evm=debug,sc_rpc_server=info,runtime::revive=debug', - ], - { - stdout: Bun.file('/tmp/substrate-node.out.log'), - stderr: Bun.file('/tmp/substrate-node.err.log'), - cwd: polkadotSdkPath, - } - ) -} - -// Run eth-rpc on 8545 -if (process.env.START_ETH_RPC) { - console.log('🚀 Start eth-rpc...') - killProcessOnPort(8545) - spawn( - [ - './target/debug/eth-rpc', - '--dev', - '--node-rpc-url=ws://localhost:9944', - '-l=rpc-metrics=debug,eth-rpc=debug', - ], - { - stdout: Bun.file('/tmp/eth-rpc.out.log'), - stderr: Bun.file('/tmp/eth-rpc.err.log'), - cwd: polkadotSdkPath, - } - ) -} - -await waitForHealth('http://localhost:8545').catch() -const env = await createEnv('eth-rpc') -const wallet = env.accountWallet - -console.log('🚀 Deploy flipper...') -const hash = await wallet.deployContract({ - abi: FlipperAbi, - bytecode: getByteCode('Flipper'), -}) - -const deployReceipt = await wallet.waitForTransactionReceipt({ hash }) -if (!deployReceipt.contractAddress) throw new Error('Contract address should be set') -const flipperAddr = deployReceipt.contractAddress - -let nonce = await wallet.getTransactionCount(wallet.account) - -console.log('🔄 Starting loop...') -console.log('Starting nonce:', nonce) -try { - while (true) { - console.log(`Call flip (nonce: ${nonce})...`) - const { request } = await wallet.simulateContract({ - account: wallet.account, - address: flipperAddr, - abi: FlipperAbi, - functionName: 'flip', - nonce, - }) - - const hash = await wallet.writeContract(request) - console.time(hash) - wallet.waitForTransactionReceipt({ hash }).then((receipt) => { - console.timeEnd(hash) - console.log('-----------------------------------') - console.log(`status: ${receipt.status ? '✅' : 'âŒ'}`) - console.log(`block: ${receipt.blockNumber} - hash: ${receipt.blockHash}`) - console.log(`tx: ${hash}`) - console.log('-----------------------------------') - }) - await wait(1_000) - nonce++ - } -} catch (err) { - console.error('Failed with error:', err) -} diff --git a/substrate/frame/revive/rpc/examples/js/src/transfer.ts b/substrate/frame/revive/rpc/examples/js/src/transfer.ts deleted file mode 100644 index 711e4eb893796fcc6afa19058c63e204920158e1..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/transfer.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { parseEther } from 'viem' -import { walletClient } from './lib.ts' - -const recipient = '0x75E480dB528101a381Ce68544611C169Ad7EB342' -try { - console.log(`Signer balance: ${await walletClient.getBalance(walletClient.account)}`) - console.log(`Recipient balance: ${await walletClient.getBalance({ address: recipient })}`) - - let resp = await walletClient.sendTransaction({ - to: recipient, - value: parseEther('1.0'), - }) - console.log(`Transaction hash: ${resp}`) - console.log(`Sent: ${parseEther('1.0')}`) - console.log(`Signer balance: ${await walletClient.getBalance(walletClient.account)}`) - console.log(`Recipient balance: ${await walletClient.getBalance({ address: recipient })}`) -} catch (err) { - console.error(err) -} diff --git a/substrate/frame/revive/rpc/examples/js/src/util.ts b/substrate/frame/revive/rpc/examples/js/src/util.ts deleted file mode 100644 index cf5c08d2561069b7330cf27b104810c06a0e40f9..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/util.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { spawnSync } from 'bun' -import { resolve } from 'path' -import { readFileSync } from 'fs' -import { - CallParameters, - createClient, - createWalletClient, - defineChain, - formatTransactionRequest, - type Hex, - hexToNumber, - http, - publicActions, -} from 'viem' -import { privateKeyToAccount, nonceManager } from 'viem/accounts' - -export function getByteCode(name: string, evm: boolean = false): Hex { - const bytecode = evm ? readFileSync(`evm/${name}.bin`) : readFileSync(`pvm/${name}.polkavm`) - return `0x${Buffer.from(bytecode).toString('hex')}` -} - -export type JsonRpcError = { - code: number - message: string - data: Hex -} - -export const polkadotSdkPath = resolve(__dirname, '../../../../../../..') - -export function killProcessOnPort(port: number) { - // Check which process is using the specified port - const result = spawnSync(['lsof', '-ti', `:${port}`]) - const output = result.stdout.toString().trim() - - if (output) { - console.log(`Port ${port} is in use. Killing process...`) - const pids = output.split('\n') - - // Kill each process using the port - for (const pid of pids) { - spawnSync(['kill', '-9', pid]) - console.log(`Killed process with PID: ${pid}`) - } - } -} - -export let jsonRpcErrors: JsonRpcError[] = [] -export async function createEnv(name: 'geth' | 'eth-rpc') { - const gethPort = process.env.GETH_PORT || '8546' - const ethRpcPort = process.env.ETH_RPC_PORT || '8545' - const url = `http://localhost:${name == 'geth' ? gethPort : ethRpcPort}` - - let id = await (async () => { - const resp = await fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_chainId', id: 1 }), - }) - let { result } = await resp.json() - return hexToNumber(result) - })() - - const chain = defineChain({ - id, - name, - nativeCurrency: { - name: 'Westie', - symbol: 'WST', - decimals: 18, - }, - rpcUrls: { - default: { - http: [url], - }, - }, - testnet: true, - }) - - const transport = http(url, { - onFetchResponse: async (response) => { - const raw = await response.clone().json() - if (raw.error) { - jsonRpcErrors.push(raw.error as JsonRpcError) - } - }, - }) - - const wallet = createWalletClient({ - transport, - chain, - }) - - const [account] = await wallet.getAddresses() - const serverWallet = createWalletClient({ - account, - transport, - chain, - }).extend(publicActions) - - const accountWallet = createWalletClient({ - account: privateKeyToAccount( - '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133', - { nonceManager } - ), - transport, - chain, - }).extend(publicActions) - - const emptyWallet = createWalletClient({ - account: privateKeyToAccount( - '0x4450c571bae82da0528ecf76fcf7079e12ecc46dc873c9cacb6db8b75ed22f41', - { nonceManager } - ), - transport, - chain, - }).extend(publicActions) - - const debugClient = createClient({ - chain, - transport, - }).extend((client) => ({ - async traceTransaction(txHash: Hex, tracerConfig: { withLog: boolean }) { - return client.request({ - method: 'debug_traceTransaction' as any, - params: [txHash, { tracer: 'callTracer', tracerConfig } as any], - }) - }, - async traceBlock(blockNumber: bigint, tracerConfig: { withLog: boolean }) { - return client.request({ - method: 'debug_traceBlockByNumber' as any, - params: [ - `0x${blockNumber.toString(16)}`, - { tracer: 'callTracer', tracerConfig } as any, - ], - }) - }, - - async traceCall(args: CallParameters, tracerConfig: { withLog: boolean }) { - return client.request({ - method: 'debug_traceCall' as any, - params: [ - formatTransactionRequest(args), - 'latest', - { tracer: 'callTracer', tracerConfig } as any, - ], - }) - }, - })) - - return { debugClient, emptyWallet, serverWallet, accountWallet, evm: name == 'geth' } -} - -export type Env = Awaited<ReturnType<typeof createEnv>> - -export function wait(ms: number) { - return new Promise((resolve) => setTimeout(resolve, ms)) -} - -export function timeout(ms: number) { - return new Promise((_resolve, reject) => setTimeout(() => reject(new Error('timeout hit')), ms)) -} - -// wait for http request to return 200 -export function waitForHealth(url: string) { - return new Promise<void>((resolve, reject) => { - const start = Date.now() - const interval = setInterval(async () => { - try { - const res = await fetch(url, { - method: 'POST', - headers: { - 'content-type': 'application/json', - }, - body: JSON.stringify({ - jsonrpc: '2.0', - method: 'eth_syncing', - params: [], - id: 1, - }), - }) - - if (res.status !== 200) { - return - } - - clearInterval(interval) - resolve() - } catch (_err) { - const elapsed = Date.now() - start - if (elapsed > 30_000) { - clearInterval(interval) - reject(new Error('hit timeout')) - } - } - }, 1000) - }) -} - -export function visit(obj: any, callback: (key: string, value: any) => any): any { - if (Array.isArray(obj)) { - return obj.map((item) => visit(item, callback)) - } else if (typeof obj === 'object' && obj !== null) { - return Object.keys(obj).reduce((acc, key) => { - acc[key] = visit(callback(key, obj[key]), callback) - return acc - }, {} as any) - } else { - return obj - } -} diff --git a/substrate/frame/revive/rpc/examples/js/src/web.ts b/substrate/frame/revive/rpc/examples/js/src/web.ts deleted file mode 100644 index ee7c8ed034da7d1d552e56fd46a02429354abe5c..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/web.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { - AddressLike, - BrowserProvider, - Contract, - ContractFactory, - Eip1193Provider, - JsonRpcSigner, - parseEther, -} from 'ethers' - -declare global { - interface Window { - ethereum?: Eip1193Provider - } -} - -function str_to_bytes(str: string): Uint8Array { - return new TextEncoder().encode(str) -} - -document.addEventListener('DOMContentLoaded', async () => { - if (typeof window.ethereum == 'undefined') { - return console.log('MetaMask is not installed') - } - - console.log('MetaMask is installed!') - const provider = new BrowserProvider(window.ethereum) - - console.log('Getting signer...') - let signer: JsonRpcSigner - try { - signer = await provider.getSigner() - console.log(`Signer: ${signer.address}`) - } catch (e) { - console.error('Failed to get signer', e) - return - } - - console.log('Getting block number...') - try { - const blockNumber = await provider.getBlockNumber() - console.log(`Block number: ${blockNumber}`) - } catch (e) { - console.error('Failed to get block number', e) - return - } - - const nonce = await signer.getNonce() - console.log(`Nonce: ${nonce}`) - - document.getElementById('transferButton')?.addEventListener('click', async () => { - const address = (document.getElementById('transferInput') as HTMLInputElement).value - await transfer(address) - }) - - document.getElementById('deployButton')?.addEventListener('click', async () => { - await deploy() - }) - document.getElementById('deployAndCallButton')?.addEventListener('click', async () => { - const nonce = await signer.getNonce() - console.log(`deploy with nonce: ${nonce}`) - - const address = await deploy() - if (address) { - const nonce = await signer.getNonce() - console.log(`call with nonce: ${nonce}`) - await call(address) - } - }) - document.getElementById('callButton')?.addEventListener('click', async () => { - const address = (document.getElementById('callInput') as HTMLInputElement).value - await call(address) - }) - - async function deploy() { - console.log('Deploying contract...') - - const bytecode = await fetch('rpc_demo.polkavm') - .then((response) => { - if (!response.ok) { - throw new Error('Network response was not ok') - } - return response.arrayBuffer() - }) - .then((arrayBuffer) => new Uint8Array(arrayBuffer)) - - const contractFactory = new ContractFactory( - ['constructor(bytes memory _data)'], - bytecode, - signer - ) - - try { - const args = str_to_bytes('hello') - const contract = await contractFactory.deploy(args) - await contract.waitForDeployment() - const address = await contract.getAddress() - console.log(`Contract deployed: ${address}`) - return address - } catch (e) { - console.error('Failed to deploy contract', e) - return - } - } - - async function call(address: string) { - const abi = ['function call(bytes data)'] - const contract = new Contract(address, abi, signer) - const tx = await contract.call(str_to_bytes('world')) - - console.log('Transaction hash:', tx.hash) - } - - async function transfer(to: AddressLike) { - console.log(`transferring 1 DOT to ${to}...`) - try { - const tx = await signer.sendTransaction({ - to, - value: parseEther('1.0'), - }) - - const receipt = await tx.wait() - console.log(`Transaction hash: ${receipt?.hash}`) - } catch (e) { - console.error('Failed to send transaction', e) - return - } - } -}) diff --git a/substrate/frame/revive/rpc/examples/js/tsconfig.json b/substrate/frame/revive/rpc/examples/js/tsconfig.json deleted file mode 100644 index 55cb8379e886a60de1b8b27109d29f4e396708c2..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/js/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "useDefineForClassFields": true, - "module": "ESNext", - "lib": ["ES2020", "DOM", "DOM.Iterable"], - "skipLibCheck": true, - - /* Bundler mode */ - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "isolatedModules": true, - "moduleDetection": "force", - "noEmit": true, - - /* Linting */ - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true - }, - "include": ["src"] -} diff --git a/substrate/frame/revive/rpc/examples/rust/remark-extrinsic.rs b/substrate/frame/revive/rpc/examples/remark-extrinsic.rs similarity index 100% rename from substrate/frame/revive/rpc/examples/rust/remark-extrinsic.rs rename to substrate/frame/revive/rpc/examples/remark-extrinsic.rs diff --git a/substrate/frame/revive/rpc/examples/rust/rpc-playground.rs b/substrate/frame/revive/rpc/examples/rpc-playground.rs similarity index 100% rename from substrate/frame/revive/rpc/examples/rust/rpc-playground.rs rename to substrate/frame/revive/rpc/examples/rpc-playground.rs diff --git a/substrate/frame/revive/rpc/examples/rpc_demo.polkavm b/substrate/frame/revive/rpc/examples/rpc_demo.polkavm deleted file mode 120000 index 63925dfcc544896a7382b642240a3f5ff1703604..0000000000000000000000000000000000000000 --- a/substrate/frame/revive/rpc/examples/rpc_demo.polkavm +++ /dev/null @@ -1 +0,0 @@ -../../../../../target/pallet-revive-fixtures/rpc_demo.polkavm \ No newline at end of file diff --git a/substrate/frame/revive/rpc/examples/rust/transfer.rs b/substrate/frame/revive/rpc/examples/transfer.rs similarity index 100% rename from substrate/frame/revive/rpc/examples/rust/transfer.rs rename to substrate/frame/revive/rpc/examples/transfer.rs diff --git a/substrate/frame/revive/rpc/src/tests.rs b/substrate/frame/revive/rpc/src/tests.rs index 375e3a5dd3f8c116bdf874cdc884ba8cc8dbea8e..87178ccdfd78897d0a0f6a1fa3f105cee78175e7 100644 --- a/substrate/frame/revive/rpc/src/tests.rs +++ b/substrate/frame/revive/rpc/src/tests.rs @@ -15,6 +15,8 @@ // See the License for the specific language governing permissions and // limitations under the License. //! Test the eth-rpc cli with the kitchensink node. +//! This only includes basic transaction tests, most of the other tests are in the +//! [evm-test-suite](https://github.com/paritytech/evm-test-suite) repository. use crate::{ cli::{self, CliCommand}, @@ -22,7 +24,6 @@ use crate::{ EthRpcClient, }; use clap::Parser; -use ethabi::Token; use jsonrpsee::ws_client::{WsClient, WsClientBuilder}; use pallet_revive::{ create1, @@ -48,17 +49,6 @@ async fn ws_client_with_retry(url: &str) -> WsClient { .expect("Hit timeout") } -fn get_contract(name: &str) -> anyhow::Result<(Vec<u8>, ethabi::Contract)> { - let pvm_dir: std::path::PathBuf = "./examples/js/pvm".into(); - let abi_dir: std::path::PathBuf = "./examples/js/abi".into(); - let bytecode = std::fs::read(pvm_dir.join(format!("{}.polkavm", name)))?; - - let abi = std::fs::read(abi_dir.join(format!("{}.json", name)))?; - let contract = ethabi::Contract::load(abi.as_slice())?; - - Ok((bytecode, contract)) -} - struct SharedResources { _node_handle: std::thread::JoinHandle<()>, _rpc_handle: std::thread::JoinHandle<()>, @@ -210,54 +200,6 @@ async fn deploy_and_call() -> anyhow::Result<()> { Ok(()) } -#[tokio::test] -async fn revert_call() -> anyhow::Result<()> { - let _lock = SHARED_RESOURCES.write(); - let client = Arc::new(SharedResources::client().await); - let (bytecode, contract) = get_contract("Errors")?; - let receipt = TransactionBuilder::new(&client) - .input(bytecode) - .send() - .await? - .wait_for_receipt() - .await?; - - let err = TransactionBuilder::new(&client) - .to(receipt.contract_address.unwrap()) - .input(contract.function("triggerRequireError")?.encode_input(&[])?.to_vec()) - .send() - .await - .unwrap_err(); - - let call_err = unwrap_call_err!(err.source().unwrap()); - assert_eq!(call_err.message(), "execution reverted: revert: This is a require error"); - assert_eq!(call_err.code(), 3); - Ok(()) -} - -#[tokio::test] -async fn event_logs() -> anyhow::Result<()> { - let _lock = SHARED_RESOURCES.write(); - let client = Arc::new(SharedResources::client().await); - let (bytecode, contract) = get_contract("EventExample")?; - let receipt = TransactionBuilder::new(&client) - .input(bytecode) - .send() - .await? - .wait_for_receipt() - .await?; - - let receipt = TransactionBuilder::new(&client) - .to(receipt.contract_address.unwrap()) - .input(contract.function("triggerEvent")?.encode_input(&[])?.to_vec()) - .send() - .await? - .wait_for_receipt() - .await?; - assert_eq!(receipt.logs.len(), 1, "There should be one log."); - Ok(()) -} - #[tokio::test] async fn invalid_transaction() -> anyhow::Result<()> { let _lock = SHARED_RESOURCES.write(); @@ -277,50 +219,3 @@ async fn invalid_transaction() -> anyhow::Result<()> { Ok(()) } - -#[tokio::test] -async fn native_evm_ratio_works() -> anyhow::Result<()> { - let _lock = SHARED_RESOURCES.write(); - let client = Arc::new(SharedResources::client().await); - let (bytecode, contract) = get_contract("PiggyBank")?; - let contract_address = TransactionBuilder::new(&client) - .input(bytecode) - .send() - .await? - .wait_for_receipt() - .await? - .contract_address - .unwrap(); - - let value = 10_000_000_000_000_000_000u128; // 10 eth - TransactionBuilder::new(&client) - .to(contract_address) - .input(contract.function("deposit")?.encode_input(&[])?.to_vec()) - .value(value.into()) - .send() - .await? - .wait_for_receipt() - .await?; - - let contract_value = client.get_balance(contract_address, BlockTag::Latest.into()).await?; - assert_eq!(contract_value, value.into()); - - let withdraw_value = 1_000_000_000_000_000_000u128; // 1 eth - TransactionBuilder::new(&client) - .to(contract_address) - .input( - contract - .function("withdraw")? - .encode_input(&[Token::Uint(withdraw_value.into())])? - .to_vec(), - ) - .send() - .await? - .wait_for_receipt() - .await?; - - let contract_value = client.get_balance(contract_address, BlockTag::Latest.into()).await?; - assert_eq!(contract_value, (value - withdraw_value).into()); - - Ok(()) -}