Coder Social home page Coder Social logo

gakonst / ethers-rs Goto Github PK

View Code? Open in Web Editor NEW
2.4K 2.4K 749.0 9.52 MB

Complete Ethereum & Celo library and wallet implementation in Rust. https://docs.rs/ethers

License: Apache License 2.0

Rust 98.37% Shell 0.15% Solidity 1.42% Yul 0.01% Nix 0.05%
celo ethereum rust web3

ethers-rs's Introduction

ethers-rs

A complete Ethereum and Celo Rust library

Github Actions Telegram Chat Crates.io

Warning

This library is in the process of being deprecated. See #2667 for more information.

Quickstart

Add this to your Cargo.toml:

[dependencies]
ethers = "2.0"

And this to your code:

use ethers::prelude::*;

Documentation

View the API reference here or the online book here.

Examples are organized into individual crates under the /examples folder. You can run any of the examples by executing:

# cargo run -p <example-crate-name> --example <name>
cargo run -p examples-big-numbers --example math_operations

EVM-compatible chains support

There are many chains live which are Ethereum JSON-RPC & EVM compatible, but do not yet have support for EIP-2718 Typed Transactions. This means that transactions submitted to them by default in ethers-rs will have invalid serialization. To address that, you must use the legacy feature flag:

[dependencies]
ethers = { version = "2.0", features = ["legacy"] }

Polygon support

There is abigen support for Polygon and the Mumbai test network. It is recommended that you set the POLYGONSCAN_API_KEY environment variable. You can get one here.

Avalanche support

There is abigen support for Avalanche and the Fuji test network. It is recommended that you set the SNOWTRACE_API_KEY environment variable. You can get one here.

Optimism support

Optimism is supported via the optimism feature flag:

[dependencies]
ethers = { version = "2.0", features = ["optimism"] }

Optimism has a new transaction type: Deposited Transactions with type ID 0x7E, which requires 3 new fields:

  • sourceHash: The hash which uniquely identifies the origin of the deposit
  • mint: The ETH value to mint on L2.
  • isSystemTx: True if the tx does not interact with the L2 block gas pool

Note: the optimism and celo features are mutually exclusive.

Celo Support

Celo support is turned on via the feature-flag celo:

[dependencies]
ethers = { version = "2.0", features = ["celo"] }

Celo's transactions differ from Ethereum transactions by including 3 new fields:

  • fee_currency: The currency fees are paid in (None for CELO, otherwise it's an Address)
  • gateway_fee_recipient: The address of the fee recipient (None for no gateway fee paid)
  • gateway_fee: Gateway fee amount (None for no gateway fee paid)

The feature flag enables these additional fields in the transaction request builders and in the transactions which are fetched over JSON-RPC.

Note: the optimism and celo features are mutually exclusive.

Features

  • Ethereum JSON-RPC Client
  • Interacting and deploying smart contracts
  • Type safe smart contract bindings code generation
  • Querying past events
  • Event monitoring as Streams
  • ENS as a first class citizen
  • Celo support
  • Polygon support
  • Avalanche support
  • Optimism support
  • Websockets / eth_subscribe
  • Hardware Wallet Support
  • Parity APIs (tracing, parity_blockWithReceipts)
  • Geth TxPool API
  • WASM Bindings (see note)
  • FFI Bindings (see note)
  • CLI for common operations

Websockets

Websockets support is turned on via the feature-flag ws:

[dependencies]
ethers = { version = "2.0", features = ["ws"] }

Interprocess Communication (IPC)

IPC support is turned on via the feature-flag ipc:

[dependencies]
ethers = { version = "2.0", features = ["ipc"] }

HTTP Secure (HTTPS)

If you are looking to connect to a HTTPS endpoint, then you need to enable the rustls or openssl feature. feature-flags.

To enable rustls:

[dependencies]
ethers = { version = "2.0", features = ["rustls"] }

To enable openssl:

[dependencies]
ethers = { version = "2.0", features = ["openssl"] }

Note on WASM and FFI bindings

You should be able to build a wasm app that uses ethers-rs (see the example for reference). If ethers fails to compile in WASM, please open an issue. There is currently no plan to provide an official JS/TS-accessible library interface, as we believe viem or ethers.js serve that need very well.

Similarly, you should be able to build FFI bindings to ethers-rs. If ethers fails to compile in C library formats, please open an issue. There is currently no plan to provide official FFI bindings.

Getting Help

First, see if the answer to your question can be found in the API documentation. If the answer is not there, try opening an issue with the question.

Join the ethers-rs telegram to chat with the community!

Contributing

Thanks for your help improving the project! We are so happy to have you! We have a contributing guide to help you get involved in the ethers-rs project.

If you open a Pull Request, do not forget to add your changes in the CHANGELOG, ensure your code is properly formatted with cargo +nightly fmt and that Clippy is happy cargo clippy; you can even try to let clippy fix simple issues itself: cargo +nightly clippy --fix

Running the tests

Tests require the following installed:

  1. solc (>=0.8.0). We also recommend using svm for more flexibility.
  2. anvil
  3. geth

Additionally, the ETHERSCAN_API_KEY environment variable has to be set to run ethers-etherscan tests. You can get one here.

Projects using ethers-rs

Credits

This library would not have been possible without the great work done in:

A lot of the code was inspired and adapted from them, to a unified and opinionated interface, built with async/await and std futures from the ground up.

ethers-rs's People

Contributors

0xmelkor avatar agostbiro avatar clifton avatar danipopes avatar dbelv avatar dependabot-preview[bot] avatar dependabot[bot] avatar evalir avatar gakonst avatar georgewhewell avatar guanqun avatar joshiedo avatar luketchang avatar mattsse avatar meetmangukiya avatar merklefruit avatar oblique avatar odyslam avatar onbjerg avatar prestwich avatar rjected avatar rkrasiuk avatar roynalnaruto avatar shekhirin avatar tarrencev avatar tomtau avatar tynes avatar will-smith11 avatar wolflo avatar xjonathanlei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ethers-rs's Issues

Refactor ethers-contract

Is your feature request related to a problem? Please describe.
Ethers-contract currently requires that it's connected to a Middleware in order to be able to broadcast the transactions.

It'd be nicer if we were able to have a base contract struct which simply takes the ABI and produces ABI encoded data for its functions (and for filters if given a vec of addresses as the filter's address). You'd then wrap that with an address and a middleware, and you'd get the equivalent functionality of the current Contract.

It'd also be nice if we supported human readable ABIs. We could do the tokenization by looking at a function's parentheses

Flaky Celo Test

Version
5b7578296b9f695300a5ef7f931e3aa2883d68fd

Description

running 1 test
test celo_tests::deploy_and_call_contract ... FAILED

failures:

---- celo_tests::deploy_and_call_contract stdout ----
thread 'celo_tests::deploy_and_call_contract' panicked at 'assertion failed: `(left == right)`
  left: `0`,
 right: `1`', ethers-contract/tests/contract.rs:395:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

This test is flaky. Sometimes it succeeds, sometimes it fails. The transaction gets broadcast properly, but it runs out of gas for some reason.

Example failing tx: https://alfajores-blockscout.celo-testnet.org/tx/0x33192056516baec27694f01607586e7043ef90c07dab255d2a379ab897dcd117/internal_transactions.

Example success: https://alfajores-blockscout.celo-testnet.org/tx/0x4cdf69696ab2f62877dbd04b1a3056f89fe315c1881c38c5de33e866914c56f5/internal_transactions

Events from Receipts

Ideally for the following contract's events:

contract C {
    event X(...);
    event Y(...);
}

The resulting codegen should be

#[derive(EthEvent)]
struct X {
   ...
}

#[derive(EthEvent)]
struct Y {
  ...
}

#[derive(EthEvent)]
enum XY {
       X(X),
       Y(Y),
}

// parse_logs will try to decode each individual log inside the receipt as either X or Y 
let ev: Vec<XY> = ethers_contract::parse_logs(tx_receipt)?;

It should be possible to use the enum as a union type to parse event logs of various types, allowing us to e.g. loop over a transaction's logs. Also, it'd be nice if we had this in a function like all_events (see here for the macro def).

WASM Support

What is the WASM support status on this lib?

What needs to be done?

Mempool APIs

It'd be nice if we supported some of the txpool APIs. Rust-web3 added support for that recently. https://github.com/tomusdrw/rust-web3/pull/382/files. We should also try to further parse the responses (instead of returning unparsed strings).

If we supported that, we could probably write a new gas escalation policy which also inspects the mempool, enabling devs to build basic (or advanced?) frontrunning infra

ds-proxy native integration

Is your feature request related to a problem? Please describe.

It'd be nice if we could have some native integration to ds-proxy, similar to how we support Multicall.

Describe the solution you'd like

Some API which accepts solidity in-line along with all the necessary arguments and calls ds-proxy

proxy.execute("""
write some solidity
"""
, some args)

Possibly wrong implementation of "format_units"

Description

I was looking to use the format-units function, part of ethers-core::utils. I was expecting the same behaviour as in the canonical ethers.js, but the format_units function behaves differently in ethers-rs.

Actual Behaviour

Take the following Rust code:

use ethers::{prelude::*, utils::format_units};
let eth_in_wei = U256::from_dec_str("1000000000000000000").unwrap();
let eth_in_gwei = format_units(eth_in_wei, 9);
println!("eth_in_gwei: {:?}", eth_in_gwei);

This logs the following:

eth_in_gwei: 111111111111111111

Expected Behaviour

Take the following JavaScript code:

const { ethers } = require("ethers");
let eth_in_wei = "1000000000000000000";
const eth_in_gwei = ethers.utils.formatUnits(eth_in_wei, 9);
console.log({ eth_in_gwei });

This logs the following:

{ eth_in_gwei: '1000000000.0' }

Which is correct, as per the identity 1 eth = 1e9 gwei = 1e18 wei.

Possible Solution

Rewrite the format_units function to divide by 10^(decimals) instead of just decimals.

Environment

Using [email protected]

ABI Encoder v2 Nested Structs

Is your feature request related to a problem? Please describe.

ABI Encoder v2 support to abigen was introduced in #17. It only works if there's no nesting. If there's a nested struct, e.g.

contract UserDirectory {
    struct Contact {
        string email;
        string phone;
    }
    struct User {
        string name;
        address addr;
        Contact contact;
    }
}

...then a generated function which uses User would be something like: fn add_user(&self, user: (String, Address, (String, String))). The tuple unfortunately does not implement Tokenize or Detokenize.

Describe the solution you'd like

We need to find a way to implement Tokenize/Detokenize for nested structs. Maybe a more elaborate macro implementation?

Describe alternatives you've considered

Ideally we should get these done with generics, but doesn't seem possible?

Race condition using WebSockets

Hi,

I'm using ethers v0.2.1. When doing heavily parallel RPCs over a websocket connection, there seem to be multiple requests using the same JSONRPC request ID, which leads to messages like "Replacing a pending request with id xxx".

I originally tried to reproduce in a test, but I was never able to. However a program is able to reliably exhibit the problem:

use std::sync::Arc;
use std::error::Error;
use ethers::prelude::*;

async fn do_rpc(ws: Arc<Provider<Ws>>) {
    ws.get_chainid().await.unwrap();
}

#[tokio::main]
async fn main() {
    let p = Arc::new(Provider::<Ws>::connect("ws://NODE_URL_HERE").await.unwrap());

    for _ in 0..8192 {
        tokio::task::spawn(do_rpc(p.clone()));
    };
}

Beginning of the output when running it:

Replacing a pending request with id 43
Replacing a pending request with id 59
thread 'tokio-runtime-worker' panicked at 'called `Result::unwrap()` on an `Err` value: JsonRpcClientError(Canceled(Canceled))', main.rs:6:28
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'tokio-runtime-worker' panicked at 'called `Result::unwrap()` on an `Err` value: JsonRpcClientError(Canceled(Canceled))', main.rs:6:28
Replacing a pending request with id 152
Replacing a pending request with id 153
thread 'tokio-runtime-worker' panicked at 'called `Result::unwrap()` on an `Err` value: JsonRpcClientError(Canceled(Canceled))', main.rs:6:28
Replacing a pending request with id 369
Replacing a pending request with id 405
Replacing a pending request with id 538
Replacing a pending request with id 552

Trim Dependencies

Start using default-features = false everywhere and remove any unused deps to make the lib smaller.

Cannot spawn futures

Due to async_trait(?Send) being used in Signer, futures cannot be spawned. This is done because Ledger's futures are not Send. We could block_on on the .exchange call in the ledger to get around that, but maybe there's a better way (and it could be problematic? @prestwich)

Missing License

This project is still missing a license, adding one would help contributors and people wanting to use the library.

JSON RPC request with no parameters is incorrectly serialized

Version
0.1.3

Platform
5.7.2-arch1-1

Description
The serialization of a JSON RPC request with no parameters is invalid. We should expect the field to be omitted as per the 2.0 spec, but instead we encode null.

Note that such a request does (incorrectly) work with ganache but not buidler.

npx ganache-cli
npx buidler node
curl -X POST --data '{"jsonrpc":"2.0","method":"eth_gasPrice","params":null,"id":8}' localhost:8545

String/fragment based Interface/ABI support

Heyo,

Killing it Georgios.

Is there the Interface/String based ABI decoder in ethers.rs.

I'd like to describe contract ABI that way, ie:

[ "function someMethod() returns (uint256)", "function ..." ]

The trait Detokenize is not implemented for a vector of tuples

Version
List the versions of all ethers-rs crates you are using. The easiest way to get
this information is using cargo-tree.

I am using the latest master branch of this repository

Platform

Darwin Rohits-MacBook-Pro.local 19.4.0 Darwin Kernel Version 19.4.0: Wed Mar  4 22:28:40 PST 2020; root:xnu-6153.101.6~15/RELEASE_X86_64 x86_64

Description
The trait Detokenize is not implemented for a vector of tuples Vec<(A, B, ...)>.

This happens because, in impl Detokenize for T, the type T (which is Vec<(A, B)> in this case) should implement Tokenizable. This requires (A, B) to implement TokenizableItem according to impl Tokenizable for Vec<T>.

So I believe the problem is because a tuple does not implement TokenizableItem.

In order to reproduce the above scenario, I added this line:

let _vec_of_tuple: Vec<(Address, String)> = output();

to the this test.

Source
Just to summarise how I ended up with this test is that, I generated Rust bindings for the Multicall contract. The contract receives a struct array for the aggregate function:

function aggregate(Call[] memory calls) public returns (uint256 blockNumber, bytes[] memory returnData)

where:

struct Call {
    address target;
    bytes callData;
}

So if the described issue is fixed, then we should be able to add this line to the abi/tokens.rs test:

let _aggregate_input: Vec<(Address, Vec<Vec<u8>>)> = output();

Transaction Resubmit Policy

Is your feature request related to a problem? Please describe.

Currently if a transaction gets submitted with too low gas price, it can potentially get stuck in the mempool. It would be nice if we could work around that by automatically bumping its fee according to some policy which is defined by the caller.

Describe the solution you'd like

A similar implementation to PendingTransaction which takes the re-submission policy as a constructor argument. Its Future implementation would then try to get the receipt, and if the receipt returns an error, instead of directly queuing up the receipt check, it'd first re-submit the transaction with a new gas price, according to the policy.

Note: h/t @stonecoldpat the tx hash will change for every bump so you have to adjust it after each submission

Middleware Architecture

Is your feature request related to a problem? Please describe.

So far, we're adding plugins to the Client / Provider by adding optional variables (e.g. Signer, ENS, Gas Oracle, Nonce Manager). Instead, we could have a trait Client which would require implementing all JSON-RPC methods. Then, each time you want to write a plug-in, you would implement the method you need (e.g. for ENS methods, you'd resolve to/from from names to addresses) and then you'd pass the data to the same function in the next level (e.g. self.inner.send_transaction). This seems straightforward to do with 2 exceptions

  1. It is cumbersome to have to re-implement every trait method when creating wrapper structs. It'd be nice if we can have some smart way (e.g. a macro) which does trait delegation. Unfortuntely, due to using
  2. Error handling: We cannot have a variant in a thiserror like InnerError(#[from] I::Error) because it potentially allows for a recursive type.

Describe the solution you'd like

A middleware-based architecture for sending RPC requests which allows creating new middleware wrappers "easily", ideally w/o having to write a lot of boilerplate which does delegation to each inner layer manually.

Then, we'd be able to do:

let provider = Provider::new("http://localhost:8545");
let provider = SignerMiddleware::new("privateKey", provider);
let provider = NonceManagerMiddleware::new(provider);
let provider = GasEscalatorMiddleware::new(provider);
let provider = EnsMiddleware::new(provider);

...and so on

Describe alternatives you've considered

So far, I've tried implementing this here: #65.

Error: failed to get `yubihsm` as a dependency of package

Description

I followed the instructions in the contributing guide and ran this command:

cargo build --all-features

But I'm getting this error:

error: failed to get `yubihsm` as a dependency of package `ethers-signers v0.1.3 (/Users/paulrberg/Workspace/Pad/ethers-rs/ethers-signers)`

Caused by:
  failed to load source for dependency `yubihsm`

Caused by:
  Unable to update https://github.com/iqlusioninc/yubihsm.rs.git?branch=develop#a8fa868f

Caused by:
  object not found - no match for id (a8fa868fbc50b8a326c46ab2b178f42e3e7a4e88); class=Odb (9); code=NotFound (-3)

Environment

Plus I have the following setting in my global .gitconfig:

[url "git@github.com:"]
    insteadOf = https://github.com/
	pushInsteadOf = "github:"
	pushInsteadOf = "git://github.com/"

To favour SSH over HTTPS.

Middleware::pending_transaction hangs or panics

Version
873cf09
ethers = { git = "https://github.com/gakonst/ethers-rs", features = ["full"] }

Platform
5.4.0-58-generic #64-Ubuntu SMP Wed Dec 9 08:16:25 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

Description
Call of pending_transaction(tx_hash) after send_transaction(tx) hangs or panics.

I tried this code:

let tx_hash = client.send_transaction(tx, None).await?;
let receipt = client.pending_transaction(tx_hash).await?;
dbg!(receipt);

I expected to see the contents of the receipt.

Instead, the program hangs or panics with following message:
thread 'tokio-runtime-worker' panicked at 'WS Server panic: NoResponse'

I've prepared two mininal projects to reproduce this behaviour (please see corresponding README files):
https://github.com/vakond/ethers-ganache-pending
https://github.com/vakond/ethers-geth-pending
The bug (if it's a bug) can also be observed with the Kovan testnet.

It seems only one variant panics: Ganache+Ws. Ganache+Http just hangs. Other variants: {Geth, Kovan}+{Ws, Http} all hang.

`estimateGas` and `calldata` on contract methods

Is your feature request related to a problem? Please describe.

We do not have an ergonomic way to print the expected gas cost of a function or the ABI encoded data which would be added to the data field of a contract call.

Describe the solution you'd like

A nice syntax would be contract.method("foo").estimate_gas() and .calldata().

This can be easily implemented by adding these as methods in the ContractCall struct.

  • estimate_gas() would call self.client.estimate_gas(self.tx)
  • calldata would simply return self.tx.data

eth_newFilter doesn't return any logs

Version

git+https://github.com/gakonst/ethers-rs#6f02bb54365f5a786db1214497b9d1ebf8304995

Platform
Linux XPS-15-9570 5.4.0-40-generic #44-Ubuntu SMP Tue Jun 23 00:01:04 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

Description
Using eth_newFilter doesn't seem to return any events. I've never used the ethers.js equivalent, so I suspect it's a problem on my end.

I tried this code:

https://github.com/Vypo/ethers-newfilter

With this contract:

// SPDX-License-Identifier: Unlicense

pragma solidity ^0.6.8;

contract Banana {
    event EatDaBanana(uint256 indexed a0, uint256 indexed a1, uint256 indexed a2);
    
    constructor() public {
        emit EatDaBanana(1, 2, 3);
        selfdestruct(msg.sender);
    }
}

I expected to see this happen: Logs to be printed to the terminal.

Instead, nothing happened.

Cannot use ethers-rs as dependency (E0034)

Version

ethers-rs:

ethers-test v0.1.0 (/home/dev/repos/rust/ethers-test)
└── ethers v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465)
    ├── ethers-contract v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465)
    │   ├── ethers-contract-abigen v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465)
    │   │   ├── ethers-core v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465)
    │   ├── ethers-contract-derive v0.2.0 (proc-macro) (https://github.com/gakonst/ethers-rs#457c6465)
    │   │   ├── ethers-contract-abigen v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465) (*)
    │   │   ├── ethers-core v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465) (*)
    │   ├── ethers-core v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465) (*)
    │   ├── ethers-providers v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465)
    │   │   ├── ethers-core v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465) (*)
    ├── ethers-core v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465) (*)
    ├── ethers-middleware v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465)
    │   ├── ethers-contract v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465) (*)
    │   ├── ethers-core v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465) (*)
    │   ├── ethers-providers v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465) (*)
    │   ├── ethers-signers v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465)
    │   │   ├── ethers-core v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465) (*)
    ├── ethers-providers v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465) (*)
    └── ethers-signers v0.2.0 (https://github.com/gakonst/ethers-rs#457c6465) (*)

rustc:

rustc 1.50.0 (cb75ad5db 2021-02-10)

Platform

Linux dev 5.8.0-43-generic #49~20.04.1-Ubuntu SMP Fri Feb 5 09:57:56 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

Description

Adding ethers-rs as dependency to a freshly created Rust project results in an error.

Steps to reproduce

  • cargo init in an empty directory
  • add ethers = { git = "https://github.com/gakonst/ethers-rs" } to the dependencies section as instructed
  • cargo build

Expected result

The project should compile successfully.

Actual result

Compilation fails with errors:

error: aborting due to 43 previous errors

Some errors have detailed explanations: E0034, E0308.
For more information about an error, try `rustc --explain E0034`.
error: could not compile `bitvec`

To learn more, run the command again with --verbose.
warning: build failed, waiting for other jobs to finish...
error: build failed

Note

Instead of installing from GitHub, I've also tried using the published crate by adding ethers = "0.2.0" instead, but resulted in the same errors.

I can compile the ethers-rs repository without issues. However, the same errors show up once I remove the Cargo.lock file. This looks like a dependency issue.

Parity TxPool API

Is your feature request related to a problem? Please describe.

It'd be nice if we supported Parity's tx pool api https://ethereum.stackexchange.com/questions/25454/in-parity-what-is-the-equivalent-rpc-call-to-geths-txpool-content

Describe the solution you'd like

Extra Provider methods for Parity's APIs. Ideally, we should be able to unify the 2 function types to 1 and normalize the return types. We could use a web3_clientVersion API call to find if we're talking to geth/parity and call the corresponding API.

Add support for EIP-234 and EIP-1898

EIP-234: Add blockHash to JSON-RPC filter options.
EIP-1898: Add blockHash to JSON-RPC methods which accept a default block parameter.

These two EIPs are closely related, and allow for querying the blockchain's state at a specified block hash. I've a draft implementation of these two ready and tested :)

There are two issues I'd like some guidance on, though.

The first is that, the way I was approaching it,EIP-1898 requires changing the signatures of a reasonable amount of methods of the trait etheres_providers::Middleware. Specifically, changing the types of Option<BlockNumber> to Option<BlockId>. Is this reasonable? I've also tried changing the type to something like Option<T> where T: Into<BlockId>. However, this has the downside that every time we pass a None, we have to type annotate the calls. Thoughts?

The second relates to testing. Ganache does not implement EIP-1898 (trufflesuite/ganache#745). It can be tested with geth, however, which is what I did.

How should I proceed? Should I open a PR?

Cheers!

int256 types not supported by abigen!

Version
0.2.0

Platform
Ubuntu 20.04 - WSL2 Environment

Description
Attempting to use abigen! to generate rust bindings for a contract which uses int256 types. I saw that this was not tokenizable so I refactored all instances of int256 types to uint256 types and it correctly ran the macro.

I tried this code:

abigen!(
        Layer2ClearingHouseContract,
        "./src/contracts/abi/ClearingHouse.json"
    );

With an ABI JSON file which extensively used the int256 type. I refactored the example abigen! as well to use int256 for setValue and that throws an error too.

    abigen!(
        SimpleContract,
        r#"[
            function setValue(int256)
            function getValue() external view (string)
            event ValueChanged(address indexed author, address indexed oldAuthor, string oldValue, string newValue)
        ]"#,
        event_derives(serde::Deserialize, serde::Serialize)
    );

Refactoring to uint256 works as well, but I am not sure if it has any implications to the contract. I would love to help contribute but I am literally a newborn baby to the world of Rust and tried to navigate the ethers-rs source code...but I got as far as abigen.rs and had no clue what was going on haha....

I expected to see this happen: Rust bindings for contract generated

Instead, this happened: Macro error

Use tracing for logging

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Currently the library offers no logging.

Describe the solution you'd like

Tracing provides great logging support with various levels of verbosity along with contexts, instead of using println calls. Example of past integration:

celo-org/snark-setup#44
celo-org/snark-setup#43

Remove Dependency on Solc

Is your feature request related to a problem? Please describe.

Currently we require that solc is installed on the user's system in order to use ethers::utils::Solc.

Describe the solution you'd like

It'd be nice if we could use the bindings behind a nicer API, kind of similar to what @spalladino built here

Describe alternatives you've considered

Maybe we can get away with not bringing solc in the library and just make the errors nicer? Maybe feature gate it?

Gas Price API clients

Is your feature request related to a problem? Please describe.
It'd be nice if we could plug in one of the existing gas price APIs instead of relying on eth_gasPrice.

Describe the solution you'd like

A port of Maker's python implementation could be a good candidate.

Make tx_hash on PendingTransaction public

Is your feature request related to a problem? Please describe.

I'm using ethers-rs in a daemon application that acts in a "fire and forget" fashion. It doesn't care about whether the transactions succeed or not, but only about broadcasting them.

I need to log the transaction hash once a transaction is sent. However, the tx_hash field on struct PendingTransaction is made private, forcing me to await it and get the receipt instead.

Describe the solution you'd like

Simply make the tx_hash field on PendingTransaction public.

Note

Though I've been using ethers in TypeScript for quite a while, I'm pretty new to ethers-rs and Rust in general. So please forgive me if I'm missing anything. Thanks!

Nonce not updated in NonceManagerMiddleware due to clone in "send" method

Description

In older versions of ethers-rs, sending a contract call via the send method defined in call.rs used to mutate the nonce field of the TransactionRequest instance (when the middleware is the NonceManagerMiddleware, of course).

But in v0.2.0, this is no longer the case. I tracked the git history and noticed this commit 3a2fd3e, which changed this code:

self.client
    .send_transaction(self.tx, self.block)
    .await
    .map_err(ContractError::MiddlewareError)

To the following:

self.client
    .send_transaction(self.tx.clone(), self.block)
    .await
    .map_err(ContractError::MiddlewareError)

So the nonce gets updated on the TransactionRequest clone, not in the user's instance of TransactionRequest.

This has the (likely unintended) consequence that a replacement tx will not re-use the same nonce as the first submitted tx, because the nonce Option will be None in both cases. In other words, the get_transaction_count_with_manager method ends up being called twice in nonce_manager.rs.

Environment

Using [email protected]

Batched Transactions

Is your feature request related to a problem? Please describe.

Currently, submitting multiple transactions can be done either by:

  1. joining multiple futures together: problem -> not atomic
  2. using a smart contract which would have internal business logic for each transaction type: problem -> inflexible

It'd be nice if we could batch together a bunch of transactions atomically in a flexible way.

Describe the solution you'd like

We should provide a nice API to the MultiCall contract, similar to Multicall.js. Liquity has another JS impl for something similar.

EthEvent::new method for getting typed event data without instantiating a contract

Is your feature request related to a problem? Please describe.

We could add a new method to EthEvent, which would allow us to do something like what we do here.

trait EthEvent {
    fn new<M: Middleware>(filter: &Filter, provider: &M) -> Result<Vec<Self>, SomeError> {
          let filter = filter.clone().event(Self::abi_signature());
          Event {
               filter,
               provider,
               datatype: PhantomData,
               event: <... something that's compatible with the ABI definition>
         }
    }

    // <... other methods>
}

#[derive(Debug, Clone, EthEvent)]
struct MyEvent {
     address foo;
}

let filter = Filter::new().address(MY_ADDRESS).from_block(0).to_block(100);
let provider = Provider::<Http>::try_from("...")?;
let events = MyEvent::new(filter, provider).query().await?;

This allows us to conveniently query and subscribe to strongly typed events, without having to instantiate a full contract object (like we show in the examples)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.