fix: WASM example (#1719)

* fix: wasm example

* fix: webpack 5.0

* fix: scripts
This commit is contained in:
DaniPopes 2022-09-19 19:49:27 +02:00 committed by GitHub
parent e89c7a378b
commit 59a82a1c8f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 1263 additions and 2679 deletions

25
Cargo.lock generated
View File

@ -1500,7 +1500,7 @@ dependencies = [
"ethers", "ethers",
"hex", "hex",
"serde", "serde",
"serde_derive", "serde-wasm-bindgen",
"serde_json", "serde_json",
"wasm-bindgen", "wasm-bindgen",
"wasm-bindgen-futures", "wasm-bindgen-futures",
@ -3433,9 +3433,9 @@ checksum = "930c0acf610d3fdb5e2ab6213019aaa04e227ebe9547b0649ba599b16d788bd7"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.137" version = "1.0.144"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1" checksum = "0f747710de3dcd43b88c9168773254e809d8ddbdf9653b84e2554ab219f17860"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
@ -3450,6 +3450,17 @@ dependencies = [
"serde_json", "serde_json",
] ]
[[package]]
name = "serde-wasm-bindgen"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cfc62771e7b829b517cb213419236475f434fb480eddd76112ae182d274434a"
dependencies = [
"js-sys",
"serde",
"wasm-bindgen",
]
[[package]] [[package]]
name = "serde_cbor" name = "serde_cbor"
version = "0.11.2" version = "0.11.2"
@ -3462,9 +3473,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.137" version = "1.0.144"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be" checksum = "94ed3a816fb1d101812f83e789f888322c34e291f894f19590dc310963e87a00"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -3473,9 +3484,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.79" version = "1.0.85"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e8d9fa5c3b304765ce1fd9c4c8a3de2c8db365a5b91be52f186efc675681d95" checksum = "e55a28e3aaef9d5ce0506d0a14dbba8054ddc7e499ef522dd8b26859ec9d4a44"
dependencies = [ dependencies = [
"itoa 1.0.1", "itoa 1.0.1",
"ryu", "ryu",

View File

@ -5,4 +5,5 @@ bin/
pkg/ pkg/
wasm-pack.log wasm-pack.log
node_modules/ node_modules/
yarn-error.log yarn-error.log
dist

View File

@ -1,16 +1,15 @@
[package] [package]
name = "ethers-wasm" name = "ethers-wasm"
version = "0.1.0" version = "0.1.0"
authors = ["Matthias Seitz <matthias.seitz@outlook.de>"]
edition = "2018" edition = "2018"
rust-version = "1.62"
authors = ["Matthias Seitz <matthias.seitz@outlook.de>"]
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
readme = "README.md" readme = "README.md"
documentation = "https://docs.rs/ethers" documentation = "https://docs.rs/ethers"
repository = "https://github.com/gakonst/ethers-rs" repository = "https://github.com/gakonst/ethers-rs"
homepage = "https://docs.rs/ethers" homepage = "https://docs.rs/ethers"
description = """ description = "How to use ethers in the browser with WASM."
How to use ethers in the browser with WASM.
"""
[lib] [lib]
crate-type = ["cdylib", "rlib"] crate-type = ["cdylib", "rlib"]
@ -20,10 +19,13 @@ default = ["console_error_panic_hook"]
[dependencies] [dependencies]
ethers = { path = "../..", version = "0.17.0", features = ["abigen", "legacy", "ws"] } ethers = { path = "../..", version = "0.17.0", features = ["abigen", "legacy", "ws"] }
serde_derive = "1.0.137"
wasm-bindgen-futures = "0.4.33" wasm-bindgen-futures = "0.4.33"
serde_json = "1.0.64" wasm-bindgen = { version = "0.2.83", features = ["serde-serialize"] }
wasm-bindgen = { version = "0.2.81", features = ["serde-serialize"] }
serde = { version = "1.0.144", features = ["derive"] }
serde_json = "1.0.85"
serde-wasm-bindgen = "0.4.3"
# The `console_error_panic_hook` crate provides better debugging of panics by # The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires # logging them with `console.error`. This is great for development, but requires
@ -38,9 +40,9 @@ console_error_panic_hook = { version = "0.1.6", optional = true }
# Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now. # Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now.
wee_alloc = { version = "0.4.5", optional = true } wee_alloc = { version = "0.4.5", optional = true }
serde = { version = "1.0.126", features = ["derive"] } web-sys = { version = "0.3.60", features = ["console"] }
hex = "0.4.3" hex = "0.4.3"
web-sys = "0.3.60"
[dev-dependencies] [dev-dependencies]
wasm-bindgen-test = "0.3.33" wasm-bindgen-test = "0.3.33"

View File

@ -1,15 +1,19 @@
## Example usage of ethers-rs from WASM # ethers-wasm
## Example
Install wasm-pack with Install wasm-pack with
yarn install yarn install
Start a local ganache instance Start a local Anvil or Ganache instance
yarn anvil
or
yarn ganache yarn ganache
Then you can build the example locally with: Build the example locally with:
yarn serve yarn serve
and then visiting http://localhost:8080 in a browser should run the example! Visit http://localhost:8080 in a browser to run the example!

View File

@ -1,18 +1,20 @@
{ {
"name": "ethers-wasm", "name": "ethers-wasm",
"license": "MIT OR Apache-2.0", "license": "MIT OR Apache-2.0",
"scripts": { "private": "true",
"build": "webpack", "scripts": {
"serve": "webpack-dev-server", "build": "webpack",
"ganache": "ganache-cli --blockTime 2 -m \"stuff inherit faith park genre spread huge knee ecology private marble supreme\"" "serve": "webpack-dev-server",
}, "anvil": "anvil -m 'stuff inherit faith park genre spread huge knee ecology private marble supreme'",
"devDependencies": { "ganache": "ganache-cli -m 'stuff inherit faith park genre spread huge knee ecology private marble supreme'"
"@wasm-tool/wasm-pack-plugin": "1.0.1", },
"html-webpack-plugin": "^3.2.0", "devDependencies": {
"text-encoding": "^0.7.0", "@wasm-tool/wasm-pack-plugin": "^1.6",
"webpack": "^4.29.4", "html-webpack-plugin": "^5.5",
"webpack-cli": "^3.1.1", "text-encoding": "^0.7",
"webpack-dev-server": "^3.1.0", "webpack": "^5.74",
"ganache-cli": "^6.12.2" "webpack-cli": "^4.10",
} "webpack-dev-server": "^4.11",
"ganache-cli": "^6.12"
}
} }

View File

@ -1,17 +1,12 @@
#![allow(clippy::all)] use crate::utils::SIMPLECONTRACT_BIN;
use std::sync::Arc;
use wasm_bindgen::prelude::*;
use web_sys::console;
use ethers::{ use ethers::{
contract::abigen, contract::abigen,
prelude::{ContractFactory, Provider, SignerMiddleware}, prelude::{ContractFactory, Provider, SignerMiddleware},
providers::Ws, providers::Ws,
}; };
use std::sync::Arc;
use crate::utils::SIMPLECONTRACT_BIN; use wasm_bindgen::prelude::*;
use web_sys::console;
pub mod utils; pub mod utils;
@ -26,6 +21,7 @@ macro_rules! log {
web_sys::console::log_1(&format!( $( $t )* ).into()); web_sys::console::log_1(&format!( $( $t )* ).into());
} }
} }
abigen!( abigen!(
SimpleContract, SimpleContract,
"./../contract_abi.json", "./../contract_abi.json",
@ -38,16 +34,16 @@ pub async fn deploy() {
console::log_2( console::log_2(
&"SimpleContract ABI: ".into(), &"SimpleContract ABI: ".into(),
&JsValue::from_serde(&*SIMPLECONTRACT_ABI).unwrap(), &serde_wasm_bindgen::to_value(&*SIMPLECONTRACT_ABI).unwrap(),
); );
let wallet = utils::key(0); let wallet = utils::key(0);
log!("Wallet: {:?}", wallet); log!("Wallet: {:?}", wallet);
let endpoint = "ws://127.0.0.1:8545"; let endpoint = "ws://127.0.0.1:8545";
let provider = Provider::new(Ws::connect(endpoint).await.unwrap()); let provider = Provider::<Ws>::connect(endpoint).await.unwrap();
let client = Arc::new(SignerMiddleware::new(provider, wallet)); let client = Arc::new(SignerMiddleware::new(provider, wallet));
log!("Provider connected to `{}`", endpoint); log!("Connected to: `{}`", endpoint);
let bytecode = hex::decode(SIMPLECONTRACT_BIN).unwrap(); let bytecode = hex::decode(SIMPLECONTRACT_BIN).unwrap();
let factory = ContractFactory::new(SIMPLECONTRACT_ABI.clone(), bytecode.into(), client.clone()); let factory = ContractFactory::new(SIMPLECONTRACT_ABI.clone(), bytecode.into(), client.clone());
@ -62,7 +58,7 @@ pub async fn deploy() {
let value = "bye from WASM!"; let value = "bye from WASM!";
log!("Setting value... `{}`", value); log!("Setting value... `{}`", value);
let receipt = contract.set_value(value.to_owned()).send().await.unwrap().await.unwrap(); let receipt = contract.set_value(value.to_owned()).send().await.unwrap().await.unwrap();
console::log_2(&"Set value receipt: ".into(), &JsValue::from_serde(&receipt).unwrap()); console::log_2(&"Set value receipt: ".into(), &serde_wasm_bindgen::to_value(&receipt).unwrap());
log!("Fetching logs..."); log!("Fetching logs...");
let logs = contract.value_changed_filter().from_block(0u64).query().await.unwrap(); let logs = contract.value_changed_filter().from_block(0u64).query().await.unwrap();
@ -71,6 +67,6 @@ pub async fn deploy() {
console::log_2( console::log_2(
&format!("Value: `{}`. Logs: ", value).into(), &format!("Value: `{}`. Logs: ", value).into(),
&JsValue::from_serde(&logs).unwrap(), &serde_wasm_bindgen::to_value(&logs).unwrap(),
); );
} }

View File

@ -1,29 +1,31 @@
const path = require('path'); const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin'); const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require('webpack'); const webpack = require("webpack");
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin"); const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");
module.exports = { module.exports = {
entry: './index.js', entry: "./index.js",
output: { output: {
path: path.resolve(__dirname, 'dist'), path: path.resolve(__dirname, "dist"),
filename: 'index.js', filename: "index.js",
}, },
plugins: [ plugins: [
new HtmlWebpackPlugin({ new HtmlWebpackPlugin({
template: './index.html', template: "./index.html",
inject: false inject: false,
} }),
),
new WasmPackPlugin({ new WasmPackPlugin({
crateDirectory: path.resolve(__dirname, ".") crateDirectory: path.resolve(__dirname, "."),
}), }),
// Have this example work in Edge which doesn't ship `TextEncoder` or // Have this example work in Edge which doesn't ship `TextEncoder` or
// `TextDecoder` at this time. // `TextDecoder` at this time.
new webpack.ProvidePlugin({ new webpack.ProvidePlugin({
TextDecoder: ['text-encoding', 'TextDecoder'], TextDecoder: ["text-encoding", "TextDecoder"],
TextEncoder: ['text-encoding', 'TextEncoder'] TextEncoder: ["text-encoding", "TextEncoder"],
}) }),
], ],
mode: 'development' experiments: {
}; asyncWebAssembly: true,
},
mode: "development",
};

File diff suppressed because it is too large Load Diff