Skip to content
This repository has been archived by the owner on Oct 19, 2024. It is now read-only.

Commit

Permalink
refactor: examples (#1940)
Browse files Browse the repository at this point in the history
* ToC

* Big numbers section

* Middleware examples: builder

* Middleware examples: gas_escalator

* Middleware examples: gas_oracle

* Middleware examples: signer

* Middleware examples: missing stubs

* review: applied DaniPopes suggestions to big numbers

* typo

* Middleware examples: nonce_manager

* cargo +nightly fmt

* update roadmap

* Middleware examples: policy

* Middleware examples: added docs

* Contracts examples: created folder; included abigen example

* Contracts examples: refactor abigen docs. Fixed cargo example reference

* Contracts examples: contract_events; minor docs changes

* Moved each example under its own crate.
Cargo builds locally
TODO: Fix broken examples CI

* Big numbers examples: used regular operators for math

* Single examples run correctly (missing overall CI execution)
Example crates dependencies
Removed duplicates

* review: Applied gakonst note to remove commented items in workspace manifest

* review: Applied gakonst note to restore visibility on contract constructor

* ci:
- Run/Build  examples in a single step to avoid duplicated scripts
- Removed ci.yaml step "Build all examples"

* cargo +nightly fmt

* ci: fix WASM step error

* Removed deprecated EthGasStation example

* WASM example uses local copy of `contract_abi.json`. In this way we keep the WASM example auto-consistent, at the cost of a small duplication

* Cargo.lock aligned to master branch

* Removed useless comments in examples

* review: Applied gakonst note to add panic!() on the policy middleware example

* review: Applied gakonst suggestion to add a custom middleware example

* typos in docs

* Update examples/big-numbers/examples/bn_math_operations.rs

review: Accepted commit suggested by DaniPopes

Co-authored-by: DaniPopes <[email protected]>

* review: Applied DaniPopes suggestion on assert_eq!

* Update examples/big-numbers/README.md

review: Accepted DaniPopes suggestion on big-numbers docs

Co-authored-by: DaniPopes <[email protected]>

* review: All imports now reference the "ethers" crate

* ci: added features ["ws", "rustls"] where needed
cargo +nigthly fmt

* Examples with special features (e.g. ipc, trezor etc.) are built alongside them. This is expressed as a "default" requirement in their respective Cargo.toml

* cargo +nightly fmt

* Examples: Gas oracle API keys from env
Added missing features in middleware Cargo.toml

* typo: use expect() instead of unwrap()

* Updated ToC
Moved 2 examples under more relevant folders

* Gas oracle examples raise panic on middleware errors

* review: removed useless [[example]] in Cargo.toml

* review: removed #[allow(unused_must_use)] from gas_escalator example

* review: Removed prefixes from file names

* review: removed useless [[example]] in Cargo.toml

* docs: Updated description to run examples in the workspace README.md

Co-authored-by: Andrea Simeoni <>
Co-authored-by: DaniPopes <[email protected]>
  • Loading branch information
0xMelkor and DaniPopes authored Dec 29, 2022
1 parent e26ede2 commit 10310ce
Show file tree
Hide file tree
Showing 82 changed files with 1,623 additions and 207 deletions.
27 changes: 1 addition & 26 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -232,32 +232,7 @@ jobs:
- uses: Swatinem/rust-cache@v1
with:
cache-on-failure: true
- name: Build all examples
run: |
export PATH=$HOME/bin:$PATH
examples=$(cargo metadata --format-version 1 | \
jq -c '.packages[]
| select(.name == "ethers")
| .targets[]
| select(.kind[] | contains("example"))
| with_entries(select([.key]
| inside(["name", "required-features"])))'
)
for example in $examples; do
name="$(echo "$example" | jq -r '.name')"
args=(
-p ethers
--example "$name"
)
features="$(echo "$example" | jq -r 'try(."required-features" | join(","))')"
if [[ ! -z "$features" ]]; then
args+=(--features "$features")
fi
echo "building $name"
cargo build "${args[@]}"
done
- name: Run all examples
- name: Build and run all examples
run: |
export PATH=$HOME/bin:$PATH
chmod +x ./scripts/examples.sh
Expand Down
105 changes: 105 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

62 changes: 2 additions & 60 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ members = [
"ethers-middleware",
"ethers-etherscan",
"ethers-solc",
"examples/ethers-wasm",
# Example crates
"examples/*",
]

default-members = [
Expand Down Expand Up @@ -128,62 +129,3 @@ bytes = "1.3.0"
# Tell `rustc` to optimize for small code size.
opt-level = "s"

[[example]]
name = "abigen"
path = "examples/abigen.rs"
required-features = ["ethers-solc"]

[[example]]
name = "contract_human_readable"
path = "examples/contract_human_readable.rs"
required-features = ["ethers-solc"]

[[example]]
name = "contract_with_abi"
path = "examples/contract_with_abi.rs"
required-features = ["ethers-solc"]

[[example]]
name = "contract_with_abi_and_bytecode"
path = "examples/contract_with_abi_and_bytecode.rs"
required-features = ["ethers-solc"]

[[example]]
name = "ipc"
path = "examples/ipc.rs"
required-features = ["ipc"]

[[example]]
name = "ledger"
path = "examples/ledger.rs"
required-features = ["ledger"]

[[example]]
name = "moonbeam_with_abi"
path = "examples/moonbeam_with_abi.rs"
required-features = ["legacy", "ethers-solc"]

[[example]]
name = "trezor"
path = "examples/trezor.rs"
required-features = ["trezor"]

[[example]]
name = "yubi"
path = "examples/yubi.rs"
required-features = ["yubi"]

[[example]]
name = "paginated_logs"
path = "examples/paginated_logs.rs"
required-features = ["rustls"]

[[example]]
name = "subscribe_contract_events"
path = "examples/subscribe_contract_events.rs"
required-features = ["rustls", "ws"]

[[example]]
name = "subscribe_contract_events_with_meta"
path = "examples/subscribe_contract_events_with_meta.rs"
required-features = ["rustls", "ws"]
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ Extensive documentation and examples are available [here](https://docs.rs/ethers

Alternatively, you may clone the repository and run `cd ethers/ && cargo doc --open`

You can also run any of the examples by executing: `cargo run -p ethers --example <name>`
Examples are organized into individual crates under the `/examples` folder.
You can run any of the examples by executing:
```bash
# cargo run -p <example-crate-name> --example <name>
cargo run -p examples-big-numbers --example math_operations
```

## Add ethers-rs to your repository

Expand Down
81 changes: 81 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Examples
- [ ] Address book
- [ ] Anvil
- [ ] Boot anvil
- [ ] Deploy contracts
- [x] Fork
- [ ] Testing
- [x] Big numbers
- [x] Comparison and equivalence
- [x] Conversion
- [x] Creating Instances
- [x] Math operations
- [x] Utilities
- [ ] Contracts
- [x] Abigen
- [x] Compile
- [ ] Creating Instances
- [x] Deploy Anvil
- [x] Deploy from ABI and bytecode
- [x] Deploy Moonbeam
- [x] Events
- [x] Events with meta
- [ ] Methods
- [ ] Events
- [ ] Logs and filtering
- [ ] Solidity topics
- [ ] Middleware
- [x] Builder
- [x] Create custom middleware
- [x] Gas escalator
- [x] Gas oracle
- [x] Nonce manager
- [x] Policy
- [x] Signer
- [ ] Time lag
- [ ] Transformer
- [ ] Providers
- [ ] Http
- [x] IPC
- [ ] Mock
- [x] Quorum
- [ ] Retry
- [x] RW
- [ ] WS
- [ ] Queries
- [ ] Blocks
- [x] Contracts
- [ ] Events
- [x] Paginated logs
- [x] UniswapV2 pair
- [ ] Transactions
- [x] Subscriptions
- [x] Watch blocks
- [x] Subscribe events by type
- [x] Subscribe logs
- [ ] Transactions
- [x] Call override
- [ ] Create raw transaction
- [ ] Create typed transaction
- [x] Decode input
- [ ] EIP-1559
- [x] ENS
- [ ] Estimate gas
- [ ] Get gas price
- [x] Get gas price USD
- [x] Remove liquidity
- [ ] Set gas for a transaction
- [ ] Send raw transaction
- [ ] Send typed transaction
- [x] Trace
- [ ] Transaction receipt
- [ ] Transaction status
- [x] Transfer ETH
- [x] Wallets
- [x] Mnemonic
- [x] Ledger
- [x] Local
- [x] Permit hash
- [x] Sign message
- [x] Trezor
- [x] Yubi
10 changes: 10 additions & 0 deletions examples/anvil/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "examples-anvil"
version = "1.0.2"
authors = ["Andrea Simeoni <[email protected]>"]
edition = "2021"

[dev-dependencies]
ethers = { path = "../..", version = "1.0.0" }
eyre = "0.6"
tokio = { version = "1.18", features = ["full"] }
Empty file added examples/anvil/README.md
Empty file.
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
//! Spawn an [anvil](https://github.com/foundry-rs/foundry/tree/master/anvil) instance in forking mode
use ethers::utils::Anvil;
use eyre::Result;

#[tokio::main]
async fn main() -> eyre::Result<()> {
async fn main() -> Result<()> {
// ensure `anvil` is available in $PATH
let anvil =
Anvil::new().fork("https://mainnet.infura.io/v3/c60b0bb42f8a4c6481ecd229eddaca27").spawn();
Expand Down
10 changes: 10 additions & 0 deletions examples/big-numbers/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "examples-big-numbers"
version = "1.0.2"
authors = ["Andrea Simeoni <[email protected]>"]
edition = "2021"

[dev-dependencies]
#ethers-core = { version = "^1.0.0", path = "../../ethers-core" }
ethers = { path = "../..", version = "1.0.0" }

7 changes: 7 additions & 0 deletions examples/big-numbers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Big numbers
Ethereum uses big numbers (also known as "bignums" or "arbitrary-precision integers") to represent certain values in its codebase and in blockchain transactions. This is necessary because [the EVM](https://ethereum.org/en/developers/docs/evm) operates on a 256-bit word size, which is different from the usual 32-bit or 64-bit of modern machines. This was chosen for the ease of use with 256-bit cryptography (such as Keccak-256 hashes or secp256k1 signatures).

It is worth noting that Ethereum is not the only blockchain or cryptocurrency that uses big numbers. Many other blockchains and cryptocurrencies also use big numbers to represent values in their respective systems.

## Utilities
In order to create an application, it is often necessary to convert between the representation of values that is easily understood by humans (such as ether) and the machine-readable form that is used by contracts and math functions (such as wei). This is particularly important when working with Ethereum, as certain values, such as balances and gas prices, must be expressed in wei when sending transactions, even if they are displayed to the user in a different format, such as ether or gwei. To help with this conversion, ethers-rs provides two functions, `parse_units` and `format_units`, which allow you to easily convert between human-readable and machine-readable forms of values. `parse_units` can be used to convert a string representing a value in ether, such as "1.1", into a big number in wei, which can be used in contracts and math functions. `format_units` can be used to convert a big number value into a human-readable string, which is useful for displaying values to users.
32 changes: 32 additions & 0 deletions examples/big-numbers/examples/comparison_equivalence.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use ethers::types::U256;

fn main() {
// a == b
let a = U256::from(100_u32);
let b = U256::from(100_u32);
assert!(a == b);

// a < b
let a = U256::from(1_u32);
let b = U256::from(100_u32);
assert!(a < b);

// a <= b
let a = U256::from(100_u32);
let b = U256::from(100_u32);
assert!(a <= b);

// a > b
let a = U256::from(100_u32);
let b = U256::from(1_u32);
assert!(a > b);

// a >= b
let a = U256::from(100_u32);
let b = U256::from(100_u32);
assert!(a >= b);

// a == 0
let a = U256::zero();
assert!(a.is_zero());
}
Loading

0 comments on commit 10310ce

Please sign in to comment.