mirror of
https://github.com/logos-storage/nim-ethers.git
synced 2026-01-02 13:43:06 +00:00
Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
965b8cd752 | ||
|
|
30871c7b1d | ||
|
|
bbced46733 | ||
|
|
c85192ae34 | ||
|
|
f9d115ae75 | ||
|
|
a29e86bfc8 | ||
|
|
4441050c3d | ||
|
|
e37f454761 | ||
|
|
def12bfdc1 | ||
|
|
51aa7bc1b3 | ||
|
|
518afa3e4c | ||
|
|
af3d7379c8 | ||
|
|
7081e6922f | ||
|
|
5d07b5dbcf | ||
|
|
b505ef1ab8 | ||
|
|
d2b11a8657 | ||
|
|
26342d3e27 | ||
|
|
0f98528758 | ||
|
|
c7c57113ce | ||
|
|
037bef0256 | ||
|
|
04d3548553 | ||
|
|
2808a05488 | ||
|
|
5c93971f97 | ||
|
|
c0cc437aa2 | ||
|
|
4642545309 | ||
|
|
d88e4614b1 |
13
.github/workflows/ci.yml
vendored
13
.github/workflows/ci.yml
vendored
@ -1,6 +1,11 @@
|
||||
name: CI
|
||||
|
||||
on: [push, pull_request, workflow_dispatch]
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
@ -8,10 +13,12 @@ jobs:
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
matrix:
|
||||
nim: [1.6.20, stable]
|
||||
nim: [2.0.14, 2.2.2]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
|
||||
- name: Install Nim
|
||||
uses: iffy/install-nim@v4
|
||||
@ -32,7 +39,7 @@ jobs:
|
||||
run: npm start &
|
||||
|
||||
- name: Build
|
||||
run: nimble install -y
|
||||
run: nimble install -y --maximumtaggedversions=2
|
||||
|
||||
- name: Test
|
||||
run: nimble test -y
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@ -6,3 +6,4 @@ nimble.paths
|
||||
.idea
|
||||
.nimble
|
||||
.envrc
|
||||
nimbledeps
|
||||
|
||||
29
Readme.md
29
Readme.md
@ -14,7 +14,13 @@ Use the [Nimble][2] package manager to add `ethers` to an existing
|
||||
project. Add the following to its .nimble file:
|
||||
|
||||
```nim
|
||||
requires "ethers >= 0.10.0 & < 0.11.0"
|
||||
requires "ethers >= 2.0.0 & < 3.0.0"
|
||||
```
|
||||
|
||||
To avoid conflicts with previous versions of `contractabi`, use the following command to install dependencies:
|
||||
|
||||
```bash
|
||||
nimble install --maximumtaggedversions=2
|
||||
```
|
||||
|
||||
Usage
|
||||
@ -131,14 +137,22 @@ You can now subscribe to Transfer events by calling `subscribe` on the contract
|
||||
instance.
|
||||
|
||||
```nim
|
||||
proc handleTransfer(transfer: Transfer) =
|
||||
echo "received transfer: ", transfer
|
||||
proc handleTransfer(transferResult: ?!Transfer) =
|
||||
if transferResult.isOk:
|
||||
echo "received transfer: ", transferResult.value
|
||||
else:
|
||||
echo "error during transfer: ", transferResult.error.msg
|
||||
|
||||
let subscription = await token.subscribe(Transfer, handleTransfer)
|
||||
```
|
||||
|
||||
When a Transfer event is emitted, the `handleTransfer` proc that you just
|
||||
defined will be called.
|
||||
defined will be called with a [Result](https://github.com/arnetheduck/nim-results) type
|
||||
which contains the event value.
|
||||
|
||||
In case there is some underlying error in the event subscription, the handler will
|
||||
be called as well, but the Result will contain error instead, so do proper error
|
||||
management in your handlers.
|
||||
|
||||
When you're no longer interested in these events, you can unsubscribe:
|
||||
|
||||
@ -190,6 +204,13 @@ This library ships with some optional modules that provides convenience utilitie
|
||||
|
||||
- `ethers/erc20` module provides you with ERC20 token implementation and its events
|
||||
|
||||
Hardhat websockets workaround
|
||||
---------
|
||||
|
||||
If you're working with Hardhat, you might encounter an issue where [websocket subscriptions stop working after 5 minutes](https://github.com/NomicFoundation/hardhat/issues/2053).
|
||||
|
||||
This library provides a workaround using the compile time `ws_resubscribe` symbol. When this symbol is defined and set to a value greater than 0, websocket subscriptions will automatically resubscribe after the amount of time (in seconds) specified. The recommended value is 240 seconds (4 minutes), eg `--define:ws_resubscribe=240`.
|
||||
|
||||
Contribution
|
||||
------------
|
||||
|
||||
|
||||
@ -5,3 +5,6 @@
|
||||
when fileExists("nimble.paths"):
|
||||
include "nimble.paths"
|
||||
# end Nimble config
|
||||
|
||||
when (NimMajor, NimMinor) >= (2, 0):
|
||||
--mm:refc
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
import ./ethers/provider
|
||||
import ./ethers/signer
|
||||
import ./ethers/providers/jsonrpc
|
||||
import ./ethers/contract
|
||||
import ./ethers/contracts
|
||||
import ./ethers/wallet
|
||||
|
||||
export provider
|
||||
export signer
|
||||
export jsonrpc
|
||||
export contract
|
||||
export wallet
|
||||
export contracts
|
||||
export wallet
|
||||
|
||||
@ -1,18 +1,18 @@
|
||||
version = "0.10.1"
|
||||
version = "2.1.0"
|
||||
author = "Nim Ethers Authors"
|
||||
description = "library for interacting with Ethereum"
|
||||
license = "MIT"
|
||||
|
||||
requires "nim >= 1.6.0"
|
||||
requires "chronicles >= 0.10.3 & < 0.11.0"
|
||||
requires "chronos >= 4.0.0 & < 4.1.0"
|
||||
requires "contractabi >= 0.6.0 & < 0.7.0"
|
||||
requires "nim >= 2.0.14"
|
||||
requires "chronicles >= 0.10.3 & < 0.13.0"
|
||||
requires "chronos >= 4.0.4 & < 4.1.0"
|
||||
requires "contractabi >= 0.7.2 & < 0.8.0"
|
||||
requires "questionable >= 0.10.2 & < 0.11.0"
|
||||
requires "https://github.com/codex-storage/nim-json-rpc >= 0.5.0 & < 0.6.0"
|
||||
requires "json_rpc >= 0.5.0 & < 0.6.0"
|
||||
requires "serde >= 1.2.1 & < 1.3.0"
|
||||
requires "https://github.com/codex-storage/nim-stint-versioned >= 1.0.0 & < 2.0.0"
|
||||
requires "https://github.com/codex-storage/nim-stew-versioned >= 1.0.0 & < 2.0.0"
|
||||
requires "https://github.com/codex-storage/nim-eth-versioned >= 1.0.0 & < 2.0.0"
|
||||
requires "stint >= 0.8.1 & < 0.9.0"
|
||||
requires "stew >= 0.2.0"
|
||||
requires "eth >= 0.6.0 & < 0.10.0"
|
||||
|
||||
task test, "Run the test suite":
|
||||
# exec "nimble install -d -y"
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import pkg/stint
|
||||
import pkg/questionable
|
||||
|
||||
{.push raises:[].}
|
||||
|
||||
@ -41,3 +42,10 @@ func `==`*(a, b: BlockTag): bool =
|
||||
a.stringValue == b.stringValue
|
||||
of numberBlockTag:
|
||||
a.numberValue == b.numberValue
|
||||
|
||||
func number*(blockTag: BlockTag): ?UInt256 =
|
||||
case blockTag.kind
|
||||
of stringBlockTag:
|
||||
UInt256.none
|
||||
of numberBlockTag:
|
||||
blockTag.numberValue.some
|
||||
|
||||
@ -1,376 +0,0 @@
|
||||
import pkg/serde
|
||||
import std/macros
|
||||
import std/sequtils
|
||||
import pkg/chronicles
|
||||
import pkg/chronos
|
||||
import pkg/contractabi
|
||||
import ./basics
|
||||
import ./provider
|
||||
import ./signer
|
||||
import ./events
|
||||
import ./errors
|
||||
import ./errors/conversion
|
||||
import ./fields
|
||||
|
||||
export basics
|
||||
export provider
|
||||
export events
|
||||
export errors.SolidityError
|
||||
export errors.errors
|
||||
|
||||
logScope:
|
||||
topics = "ethers contract"
|
||||
|
||||
type
|
||||
Contract* = ref object of RootObj
|
||||
provider: Provider
|
||||
signer: ?Signer
|
||||
address: Address
|
||||
TransactionOverrides* = ref object of RootObj
|
||||
nonce*: ?UInt256
|
||||
chainId*: ?UInt256
|
||||
gasPrice*: ?UInt256
|
||||
maxFee*: ?UInt256
|
||||
maxPriorityFee*: ?UInt256
|
||||
gasLimit*: ?UInt256
|
||||
CallOverrides* = ref object of TransactionOverrides
|
||||
blockTag*: ?BlockTag
|
||||
ContractError* = object of EthersError
|
||||
Confirmable* = object
|
||||
response*: ?TransactionResponse
|
||||
convert*: ConvertCustomErrors
|
||||
EventHandler*[E: Event] = proc(event: E) {.gcsafe, raises:[].}
|
||||
|
||||
func new*(ContractType: type Contract,
|
||||
address: Address,
|
||||
provider: Provider): ContractType =
|
||||
ContractType(provider: provider, address: address)
|
||||
|
||||
func new*(ContractType: type Contract,
|
||||
address: Address,
|
||||
signer: Signer): ContractType =
|
||||
ContractType(signer: some signer, provider: signer.provider, address: address)
|
||||
|
||||
func connect*[T: Contract](contract: T, provider: Provider | Signer): T =
|
||||
T.new(contract.address, provider)
|
||||
|
||||
func provider*(contract: Contract): Provider =
|
||||
contract.provider
|
||||
|
||||
func signer*(contract: Contract): ?Signer =
|
||||
contract.signer
|
||||
|
||||
func address*(contract: Contract): Address =
|
||||
contract.address
|
||||
|
||||
template raiseContractError(message: string) =
|
||||
raise newException(ContractError, message)
|
||||
|
||||
proc createTransaction(contract: Contract,
|
||||
function: string,
|
||||
parameters: tuple,
|
||||
overrides = TransactionOverrides()): Transaction =
|
||||
let selector = selector(function, typeof parameters).toArray
|
||||
let data = @selector & AbiEncoder.encode(parameters)
|
||||
Transaction(
|
||||
to: contract.address,
|
||||
data: data,
|
||||
nonce: overrides.nonce,
|
||||
chainId: overrides.chainId,
|
||||
gasPrice: overrides.gasPrice,
|
||||
maxFee: overrides.maxFee,
|
||||
maxPriorityFee: overrides.maxPriorityFee,
|
||||
gasLimit: overrides.gasLimit,
|
||||
)
|
||||
|
||||
proc decodeResponse(T: type, bytes: seq[byte]): T =
|
||||
without decoded =? AbiDecoder.decode(bytes, T):
|
||||
raiseContractError "unable to decode return value as " & $T
|
||||
return decoded
|
||||
|
||||
proc call(provider: Provider,
|
||||
transaction: Transaction,
|
||||
overrides: TransactionOverrides): Future[seq[byte]] {.async: (raises: [ProviderError]).} =
|
||||
if overrides of CallOverrides and
|
||||
blockTag =? CallOverrides(overrides).blockTag:
|
||||
await provider.call(transaction, blockTag)
|
||||
else:
|
||||
await provider.call(transaction)
|
||||
|
||||
proc call(contract: Contract,
|
||||
function: string,
|
||||
parameters: tuple,
|
||||
overrides = TransactionOverrides()) {.async: (raises: [ProviderError, SignerError]).} =
|
||||
var transaction = createTransaction(contract, function, parameters, overrides)
|
||||
|
||||
if signer =? contract.signer and transaction.sender.isNone:
|
||||
transaction.sender = some(await signer.getAddress())
|
||||
|
||||
discard await contract.provider.call(transaction, overrides)
|
||||
|
||||
proc call(contract: Contract,
|
||||
function: string,
|
||||
parameters: tuple,
|
||||
ReturnType: type,
|
||||
overrides = TransactionOverrides()): Future[ReturnType] {.async: (raises: [ProviderError, SignerError, ContractError]).} =
|
||||
var transaction = createTransaction(contract, function, parameters, overrides)
|
||||
|
||||
if signer =? contract.signer and transaction.sender.isNone:
|
||||
transaction.sender = some(await signer.getAddress())
|
||||
|
||||
let response = await contract.provider.call(transaction, overrides)
|
||||
return decodeResponse(ReturnType, response)
|
||||
|
||||
proc send(
|
||||
contract: Contract,
|
||||
function: string,
|
||||
parameters: tuple,
|
||||
overrides = TransactionOverrides()
|
||||
): Future[?TransactionResponse] {.async: (raises: [AsyncLockError, CancelledError, CatchableError]).} =
|
||||
|
||||
if signer =? contract.signer:
|
||||
withLock(signer):
|
||||
let transaction = createTransaction(contract, function, parameters, overrides)
|
||||
let populated = await signer.populateTransaction(transaction)
|
||||
trace "sending contract transaction", function, params = $parameters
|
||||
let txResp = await signer.sendTransaction(populated)
|
||||
return txResp.some
|
||||
else:
|
||||
await call(contract, function, parameters, overrides)
|
||||
return TransactionResponse.none
|
||||
|
||||
func getParameterTuple(procedure: NimNode): NimNode =
|
||||
let parameters = procedure[3]
|
||||
var tupl = newNimNode(nnkTupleConstr, parameters)
|
||||
for parameter in parameters[2..^1]:
|
||||
for name in parameter[0..^3]:
|
||||
tupl.add name
|
||||
return tupl
|
||||
|
||||
func getErrorTypes(procedure: NimNode): NimNode =
|
||||
let pragmas = procedure[4]
|
||||
var tupl = newNimNode(nnkTupleConstr)
|
||||
for pragma in pragmas:
|
||||
if pragma.kind == nnkExprColonExpr:
|
||||
if pragma[0].eqIdent "errors":
|
||||
pragma[1].expectKind(nnkBracket)
|
||||
for error in pragma[1]:
|
||||
tupl.add error
|
||||
if tupl.len == 0:
|
||||
quote do: tuple[]
|
||||
else:
|
||||
tupl
|
||||
|
||||
func isGetter(procedure: NimNode): bool =
|
||||
let pragmas = procedure[4]
|
||||
for pragma in pragmas:
|
||||
if pragma.eqIdent "getter":
|
||||
return true
|
||||
false
|
||||
|
||||
func isConstant(procedure: NimNode): bool =
|
||||
let pragmas = procedure[4]
|
||||
for pragma in pragmas:
|
||||
if pragma.eqIdent "view":
|
||||
return true
|
||||
elif pragma.eqIdent "pure":
|
||||
return true
|
||||
elif pragma.eqIdent "getter":
|
||||
return true
|
||||
false
|
||||
|
||||
func isMultipleReturn(returnType: NimNode): bool =
|
||||
(returnType.kind == nnkPar and returnType.len > 1) or
|
||||
(returnType.kind == nnkTupleConstr) or
|
||||
(returnType.kind == nnkTupleTy)
|
||||
|
||||
func addOverrides(procedure: var NimNode) =
|
||||
procedure[3].add(
|
||||
newIdentDefs(
|
||||
ident("overrides"),
|
||||
newEmptyNode(),
|
||||
quote do: TransactionOverrides()
|
||||
)
|
||||
)
|
||||
|
||||
func addContractCall(procedure: var NimNode) =
|
||||
let contract = procedure[3][1][0]
|
||||
let function = $basename(procedure[0])
|
||||
let parameters = getParameterTuple(procedure)
|
||||
let returnType = procedure[3][0]
|
||||
let isGetter = procedure.isGetter
|
||||
|
||||
procedure.addOverrides()
|
||||
let errors = getErrorTypes(procedure)
|
||||
|
||||
func call: NimNode =
|
||||
if returnType.kind == nnkEmpty:
|
||||
quote:
|
||||
await call(`contract`, `function`, `parameters`, overrides)
|
||||
elif returnType.isMultipleReturn or isGetter:
|
||||
quote:
|
||||
return await call(
|
||||
`contract`, `function`, `parameters`, `returnType`, overrides
|
||||
)
|
||||
else:
|
||||
quote:
|
||||
# solidity functions return a tuple, so wrap return type in a tuple
|
||||
let tupl = await call(
|
||||
`contract`, `function`, `parameters`, (`returnType`,), overrides
|
||||
)
|
||||
return tupl[0]
|
||||
|
||||
func send: NimNode =
|
||||
if returnType.kind == nnkEmpty:
|
||||
quote:
|
||||
discard await send(`contract`, `function`, `parameters`, overrides)
|
||||
else:
|
||||
quote:
|
||||
when typeof(result) isnot Confirmable:
|
||||
{.error:
|
||||
"unexpected return type, " &
|
||||
"missing {.view.}, {.pure.} or {.getter.} ?"
|
||||
.}
|
||||
let response = await send(`contract`, `function`, `parameters`, overrides)
|
||||
let convert = customErrorConversion(`errors`)
|
||||
Confirmable(response: response, convert: convert)
|
||||
|
||||
procedure[6] =
|
||||
if procedure.isConstant:
|
||||
call()
|
||||
else:
|
||||
send()
|
||||
|
||||
func addErrorHandling(procedure: var NimNode) =
|
||||
let body = procedure[6]
|
||||
let errors = getErrorTypes(procedure)
|
||||
procedure[6] = quote do:
|
||||
try:
|
||||
`body`
|
||||
except ProviderError as error:
|
||||
if data =? error.data:
|
||||
let convert = customErrorConversion(`errors`)
|
||||
raise convert(error)
|
||||
else:
|
||||
raise error
|
||||
|
||||
func addFuture(procedure: var NimNode) =
|
||||
let returntype = procedure[3][0]
|
||||
if returntype.kind != nnkEmpty:
|
||||
procedure[3][0] = quote: Future[`returntype`]
|
||||
|
||||
func addAsyncPragma(procedure: var NimNode) =
|
||||
let pragmas = procedure[4]
|
||||
if pragmas.kind == nnkEmpty:
|
||||
procedure[4] = newNimNode(nnkPragma)
|
||||
procedure[4].add ident("async")
|
||||
|
||||
macro contract*(procedure: untyped{nkProcDef|nkMethodDef}): untyped =
|
||||
|
||||
let parameters = procedure[3]
|
||||
let body = procedure[6]
|
||||
|
||||
parameters.expectMinLen(2) # at least return type and contract instance
|
||||
body.expectKind(nnkEmpty)
|
||||
|
||||
var contractcall = copyNimTree(procedure)
|
||||
contractcall.addContractCall()
|
||||
contractcall.addErrorHandling()
|
||||
contractcall.addFuture()
|
||||
contractcall.addAsyncPragma()
|
||||
contractcall
|
||||
|
||||
template view* {.pragma.}
|
||||
template pure* {.pragma.}
|
||||
template getter* {.pragma.}
|
||||
|
||||
proc subscribe*[E: Event](contract: Contract,
|
||||
_: type E,
|
||||
handler: EventHandler[E]):
|
||||
Future[Subscription] =
|
||||
|
||||
let topic = topic($E, E.fieldTypes).toArray
|
||||
let filter = EventFilter(address: contract.address, topics: @[topic])
|
||||
|
||||
proc logHandler(log: Log) {.raises: [].} =
|
||||
if event =? E.decode(log.data, log.topics):
|
||||
handler(event)
|
||||
|
||||
contract.provider.subscribe(filter, logHandler)
|
||||
|
||||
proc confirm(tx: Confirmable, confirmations, timeout: int):
|
||||
Future[TransactionReceipt] {.async.} =
|
||||
|
||||
without response =? tx.response:
|
||||
raise newException(
|
||||
EthersError,
|
||||
"Transaction hash required. Possibly was a call instead of a send?"
|
||||
)
|
||||
|
||||
try:
|
||||
return await response.confirm(confirmations, timeout)
|
||||
except ProviderError as error:
|
||||
let convert = tx.convert
|
||||
raise convert(error)
|
||||
|
||||
proc confirm*(tx: Future[Confirmable],
|
||||
confirmations: int = EthersDefaultConfirmations,
|
||||
timeout: int = EthersReceiptTimeoutBlks):
|
||||
Future[TransactionReceipt] {.async.} =
|
||||
## Convenience method that allows confirm to be chained to a contract
|
||||
## transaction, eg:
|
||||
## `await token.connect(signer0)
|
||||
## .mint(accounts[1], 100.u256)
|
||||
## .confirm(3)`
|
||||
return await (await tx).confirm(confirmations, timeout)
|
||||
|
||||
proc queryFilter[E: Event](contract: Contract,
|
||||
_: type E,
|
||||
filter: EventFilter):
|
||||
Future[seq[E]] {.async.} =
|
||||
|
||||
var logs = await contract.provider.getLogs(filter)
|
||||
logs.keepItIf(not it.removed)
|
||||
|
||||
var events: seq[E] = @[]
|
||||
for log in logs:
|
||||
if event =? E.decode(log.data, log.topics):
|
||||
events.add event
|
||||
|
||||
return events
|
||||
|
||||
proc queryFilter*[E: Event](contract: Contract,
|
||||
_: type E):
|
||||
Future[seq[E]] =
|
||||
|
||||
let topic = topic($E, E.fieldTypes).toArray
|
||||
let filter = EventFilter(address: contract.address,
|
||||
topics: @[topic])
|
||||
|
||||
contract.queryFilter(E, filter)
|
||||
|
||||
proc queryFilter*[E: Event](contract: Contract,
|
||||
_: type E,
|
||||
blockHash: BlockHash):
|
||||
Future[seq[E]] =
|
||||
|
||||
let topic = topic($E, E.fieldTypes).toArray
|
||||
let filter = FilterByBlockHash(address: contract.address,
|
||||
topics: @[topic],
|
||||
blockHash: blockHash)
|
||||
|
||||
contract.queryFilter(E, filter)
|
||||
|
||||
proc queryFilter*[E: Event](contract: Contract,
|
||||
_: type E,
|
||||
fromBlock: BlockTag,
|
||||
toBlock: BlockTag):
|
||||
Future[seq[E]] =
|
||||
|
||||
let topic = topic($E, E.fieldTypes).toArray
|
||||
let filter = Filter(address: contract.address,
|
||||
topics: @[topic],
|
||||
fromBlock: fromBlock,
|
||||
toBlock: toBlock)
|
||||
|
||||
contract.queryFilter(E, filter)
|
||||
31
ethers/contracts.nim
Normal file
31
ethers/contracts.nim
Normal file
@ -0,0 +1,31 @@
|
||||
import std/macros
|
||||
import ./contracts/contract
|
||||
import ./contracts/overrides
|
||||
import ./contracts/confirmation
|
||||
import ./contracts/events
|
||||
import ./contracts/filters
|
||||
import ./contracts/syntax
|
||||
import ./contracts/gas
|
||||
import ./contracts/function
|
||||
|
||||
export contract
|
||||
export overrides
|
||||
export confirmation
|
||||
export events
|
||||
export filters
|
||||
export syntax.view
|
||||
export syntax.pure
|
||||
export syntax.getter
|
||||
export syntax.errors
|
||||
export gas.estimateGas
|
||||
|
||||
{.push raises: [].}
|
||||
|
||||
macro contract*(procedure: untyped{nkProcDef | nkMethodDef}): untyped =
|
||||
procedure.params.expectMinLen(2) # at least return type and contract instance
|
||||
procedure.body.expectKind(nnkEmpty)
|
||||
|
||||
newStmtList(
|
||||
createContractFunction(procedure),
|
||||
createGasEstimationCall(procedure)
|
||||
)
|
||||
45
ethers/contracts/confirmation.nim
Normal file
45
ethers/contracts/confirmation.nim
Normal file
@ -0,0 +1,45 @@
|
||||
import ../provider
|
||||
import ./errors/conversion
|
||||
|
||||
{.push raises: [].}
|
||||
|
||||
type Confirmable* = object
|
||||
response*: ?TransactionResponse
|
||||
convert*: ConvertCustomErrors
|
||||
|
||||
proc confirm(tx: Confirmable, confirmations, timeout: int):
|
||||
Future[TransactionReceipt] {.async: (raises: [CancelledError, EthersError]).} =
|
||||
|
||||
without response =? tx.response:
|
||||
raise newException(
|
||||
EthersError,
|
||||
"Transaction hash required. Possibly was a call instead of a send?"
|
||||
)
|
||||
|
||||
try:
|
||||
return await response.confirm(confirmations, timeout)
|
||||
except ProviderError as error:
|
||||
let convert = tx.convert
|
||||
raise convert(error)
|
||||
|
||||
proc confirm*(tx: Future[Confirmable],
|
||||
confirmations: int = EthersDefaultConfirmations,
|
||||
timeout: int = EthersReceiptTimeoutBlks):
|
||||
Future[TransactionReceipt] {.async: (raises: [CancelledError, EthersError]).} =
|
||||
## Convenience method that allows confirm to be chained to a contract
|
||||
## transaction, eg:
|
||||
## `await token.connect(signer0)
|
||||
## .mint(accounts[1], 100.u256)
|
||||
## .confirm(3)`
|
||||
try:
|
||||
return await (await tx).confirm(confirmations, timeout)
|
||||
except CancelledError as e:
|
||||
raise e
|
||||
except EthersError as e:
|
||||
raise e
|
||||
except CatchableError as e:
|
||||
raise newException(
|
||||
EthersError,
|
||||
"Error when trying to confirm the contract transaction: " & e.msg
|
||||
)
|
||||
|
||||
36
ethers/contracts/contract.nim
Normal file
36
ethers/contracts/contract.nim
Normal file
@ -0,0 +1,36 @@
|
||||
import ../basics
|
||||
import ../provider
|
||||
import ../signer
|
||||
|
||||
{.push raises:[].}
|
||||
|
||||
type Contract* = ref object of RootObj
|
||||
provider: Provider
|
||||
signer: ?Signer
|
||||
address: Address
|
||||
|
||||
func new*(ContractType: type Contract,
|
||||
address: Address,
|
||||
provider: Provider): ContractType =
|
||||
ContractType(provider: provider, address: address)
|
||||
|
||||
func new*(ContractType: type Contract,
|
||||
address: Address,
|
||||
signer: Signer): ContractType {.raises: [SignerError].} =
|
||||
ContractType(signer: some signer, provider: signer.provider, address: address)
|
||||
|
||||
func connect*[C: Contract](contract: C, provider: Provider): C =
|
||||
C.new(contract.address, provider)
|
||||
|
||||
func connect*[C: Contract](contract: C, signer: Signer): C {.raises: [SignerError].} =
|
||||
C.new(contract.address, signer)
|
||||
|
||||
func provider*(contract: Contract): Provider =
|
||||
contract.provider
|
||||
|
||||
func signer*(contract: Contract): ?Signer =
|
||||
contract.signer
|
||||
|
||||
func address*(contract: Contract): Address =
|
||||
contract.address
|
||||
|
||||
35
ethers/contracts/contractcall.nim
Normal file
35
ethers/contracts/contractcall.nim
Normal file
@ -0,0 +1,35 @@
|
||||
import ../basics
|
||||
import ./contract
|
||||
import ./overrides
|
||||
|
||||
type ContractCall*[Arguments: tuple] = object
|
||||
contract: Contract
|
||||
function: string
|
||||
arguments: Arguments
|
||||
overrides: TransactionOverrides
|
||||
|
||||
func init*[Arguments: tuple](
|
||||
_: type ContractCall,
|
||||
contract: Contract,
|
||||
function: string,
|
||||
arguments: Arguments,
|
||||
overrides: TransactionOverrides
|
||||
): ContractCall[arguments] =
|
||||
ContractCall[Arguments](
|
||||
contract: contract,
|
||||
function: function,
|
||||
arguments: arguments,
|
||||
overrides: overrides
|
||||
)
|
||||
|
||||
func contract*(call: ContractCall): Contract =
|
||||
call.contract
|
||||
|
||||
func function*(call: ContractCall): string =
|
||||
call.function
|
||||
|
||||
func arguments*(call: ContractCall): auto =
|
||||
call.arguments
|
||||
|
||||
func overrides*(call: ContractCall): TransactionOverrides =
|
||||
call.overrides
|
||||
29
ethers/contracts/errors.nim
Normal file
29
ethers/contracts/errors.nim
Normal file
@ -0,0 +1,29 @@
|
||||
import std/macros
|
||||
import ./errors/conversion
|
||||
|
||||
func getErrorTypes*(procedure: NimNode): NimNode =
|
||||
let pragmas = procedure[4]
|
||||
var tupl = newNimNode(nnkTupleConstr)
|
||||
for pragma in pragmas:
|
||||
if pragma.kind == nnkExprColonExpr:
|
||||
if pragma[0].eqIdent "errors":
|
||||
pragma[1].expectKind(nnkBracket)
|
||||
for error in pragma[1]:
|
||||
tupl.add error
|
||||
if tupl.len == 0:
|
||||
quote do: tuple[]
|
||||
else:
|
||||
tupl
|
||||
|
||||
func addErrorHandling*(procedure: var NimNode) =
|
||||
let body = procedure[6]
|
||||
let errors = getErrorTypes(procedure)
|
||||
procedure.body = quote do:
|
||||
try:
|
||||
`body`
|
||||
except ProviderError as error:
|
||||
if data =? error.data:
|
||||
let convert = customErrorConversion(`errors`)
|
||||
raise convert(error)
|
||||
else:
|
||||
raise error
|
||||
@ -1,5 +1,5 @@
|
||||
import ../basics
|
||||
import ../provider
|
||||
import ../../basics
|
||||
import ../../provider
|
||||
import ./encoding
|
||||
|
||||
type ConvertCustomErrors* =
|
||||
@ -1,7 +1,7 @@
|
||||
import pkg/contractabi
|
||||
import pkg/contractabi/selector
|
||||
import ../basics
|
||||
import ../errors
|
||||
import ../../basics
|
||||
import ../../errors
|
||||
|
||||
func selector(E: type): FunctionSelector =
|
||||
when compiles(E.arguments):
|
||||
@ -1,7 +1,7 @@
|
||||
import std/macros
|
||||
import pkg/contractabi
|
||||
import ./basics
|
||||
import ./provider
|
||||
import ../basics
|
||||
import ../provider
|
||||
|
||||
type
|
||||
Event* = object of RootObj
|
||||
78
ethers/contracts/filters.nim
Normal file
78
ethers/contracts/filters.nim
Normal file
@ -0,0 +1,78 @@
|
||||
import std/sequtils
|
||||
import pkg/contractabi
|
||||
import ../basics
|
||||
import ../provider
|
||||
import ./contract
|
||||
import ./events
|
||||
import ./fields
|
||||
|
||||
type EventHandler*[E: Event] = proc(event: ?!E) {.gcsafe, raises:[].}
|
||||
|
||||
proc subscribe*[E: Event](contract: Contract,
|
||||
_: type E,
|
||||
handler: EventHandler[E]):
|
||||
Future[Subscription] =
|
||||
|
||||
let topic = topic($E, E.fieldTypes).toArray
|
||||
let filter = EventFilter(address: contract.address, topics: @[topic])
|
||||
|
||||
proc logHandler(logResult: ?!Log) {.raises: [].} =
|
||||
without log =? logResult, error:
|
||||
handler(failure(E, error))
|
||||
return
|
||||
|
||||
if event =? E.decode(log.data, log.topics):
|
||||
handler(success(event))
|
||||
|
||||
contract.provider.subscribe(filter, logHandler)
|
||||
|
||||
proc queryFilter[E: Event](contract: Contract,
|
||||
_: type E,
|
||||
filter: EventFilter):
|
||||
Future[seq[E]] {.async.} =
|
||||
|
||||
var logs = await contract.provider.getLogs(filter)
|
||||
logs.keepItIf(not it.removed)
|
||||
|
||||
var events: seq[E] = @[]
|
||||
for log in logs:
|
||||
if event =? E.decode(log.data, log.topics):
|
||||
events.add event
|
||||
|
||||
return events
|
||||
|
||||
proc queryFilter*[E: Event](contract: Contract,
|
||||
_: type E):
|
||||
Future[seq[E]] =
|
||||
|
||||
let topic = topic($E, E.fieldTypes).toArray
|
||||
let filter = EventFilter(address: contract.address,
|
||||
topics: @[topic])
|
||||
|
||||
contract.queryFilter(E, filter)
|
||||
|
||||
proc queryFilter*[E: Event](contract: Contract,
|
||||
_: type E,
|
||||
blockHash: BlockHash):
|
||||
Future[seq[E]] =
|
||||
|
||||
let topic = topic($E, E.fieldTypes).toArray
|
||||
let filter = FilterByBlockHash(address: contract.address,
|
||||
topics: @[topic],
|
||||
blockHash: blockHash)
|
||||
|
||||
contract.queryFilter(E, filter)
|
||||
|
||||
proc queryFilter*[E: Event](contract: Contract,
|
||||
_: type E,
|
||||
fromBlock: BlockTag,
|
||||
toBlock: BlockTag):
|
||||
Future[seq[E]] =
|
||||
|
||||
let topic = topic($E, E.fieldTypes).toArray
|
||||
let filter = Filter(address: contract.address,
|
||||
topics: @[topic],
|
||||
fromBlock: fromBlock,
|
||||
toBlock: toBlock)
|
||||
|
||||
contract.queryFilter(E, filter)
|
||||
60
ethers/contracts/function.nim
Normal file
60
ethers/contracts/function.nim
Normal file
@ -0,0 +1,60 @@
|
||||
import std/macros
|
||||
import ./errors/conversion
|
||||
import ./syntax
|
||||
import ./transactions
|
||||
import ./errors
|
||||
|
||||
func addContractCall(procedure: var NimNode) =
|
||||
let contractCall = getContractCall(procedure)
|
||||
let returnType = procedure.params[0]
|
||||
let isGetter = procedure.isGetter
|
||||
|
||||
let errors = getErrorTypes(procedure)
|
||||
|
||||
func call: NimNode =
|
||||
if returnType.kind == nnkEmpty:
|
||||
quote:
|
||||
await callTransaction(`contractCall`)
|
||||
elif returnType.isMultipleReturn or isGetter:
|
||||
quote:
|
||||
return await callTransaction(`contractCall`, `returnType`)
|
||||
else:
|
||||
quote:
|
||||
# solidity functions return a tuple, so wrap return type in a tuple
|
||||
let tupl = await callTransaction(`contractCall`, (`returnType`,))
|
||||
return tupl[0]
|
||||
|
||||
func send: NimNode =
|
||||
if returnType.kind == nnkEmpty:
|
||||
quote:
|
||||
discard await sendTransaction(`contractCall`)
|
||||
else:
|
||||
quote:
|
||||
when typeof(result) isnot Confirmable:
|
||||
{.error:
|
||||
"unexpected return type, " &
|
||||
"missing {.view.}, {.pure.} or {.getter.} ?"
|
||||
.}
|
||||
let response = await sendTransaction(`contractCall`)
|
||||
let convert = customErrorConversion(`errors`)
|
||||
Confirmable(response: response, convert: convert)
|
||||
|
||||
procedure.body =
|
||||
if procedure.isConstant:
|
||||
call()
|
||||
else:
|
||||
send()
|
||||
|
||||
func addFuture(procedure: var NimNode) =
|
||||
let returntype = procedure[3][0]
|
||||
if returntype.kind != nnkEmpty:
|
||||
procedure[3][0] = quote: Future[`returntype`]
|
||||
|
||||
func createContractFunction*(procedure: NimNode): NimNode =
|
||||
result = copyNimTree(procedure)
|
||||
result.addOverridesParameter()
|
||||
result.addContractCall()
|
||||
result.addErrorHandling()
|
||||
result.addFuture()
|
||||
result.addAsyncPragma()
|
||||
|
||||
51
ethers/contracts/gas.nim
Normal file
51
ethers/contracts/gas.nim
Normal file
@ -0,0 +1,51 @@
|
||||
import std/macros
|
||||
import ../basics
|
||||
import ../provider
|
||||
import ../signer
|
||||
import ./contract
|
||||
import ./contractcall
|
||||
import ./transactions
|
||||
import ./overrides
|
||||
import ./errors
|
||||
import ./syntax
|
||||
|
||||
type ContractGasEstimations[C] = distinct C
|
||||
|
||||
func estimateGas*[C: Contract](contract: C): ContractGasEstimations[C] =
|
||||
ContractGasEstimations[C](contract)
|
||||
|
||||
proc estimateGas(
|
||||
call: ContractCall
|
||||
): Future[UInt256] {.async: (raises: [CancelledError, ProviderError, EthersError]).} =
|
||||
let transaction = createTransaction(call)
|
||||
var blockTag = BlockTag.pending
|
||||
if call.overrides of CallOverrides:
|
||||
if tag =? CallOverrides(call.overrides).blockTag:
|
||||
blockTag = tag
|
||||
if signer =? call.contract.signer:
|
||||
await signer.estimateGas(transaction, blockTag)
|
||||
else:
|
||||
await call.contract.provider.estimateGas(transaction, blockTag)
|
||||
|
||||
func wrapFirstParameter(procedure: var NimNode) =
|
||||
let contractType = procedure.params[1][1]
|
||||
let gasEstimationsType = quote do: ContractGasEstimations[`contractType`]
|
||||
procedure.params[1][1] = gasEstimationsType
|
||||
|
||||
func setReturnType(procedure: var NimNode) =
|
||||
procedure.params[0] = quote do: Future[UInt256]
|
||||
|
||||
func addEstimateCall(procedure: var NimNode) =
|
||||
let contractCall = getContractCall(procedure)
|
||||
procedure.body = quote do:
|
||||
return await estimateGas(`contractCall`)
|
||||
|
||||
func createGasEstimationCall*(procedure: NimNode): NimNode =
|
||||
result = copyNimTree(procedure)
|
||||
result.wrapFirstParameter()
|
||||
result.addOverridesParameter()
|
||||
result.setReturnType()
|
||||
result.addAsyncPragma()
|
||||
result.addUsedPragma()
|
||||
result.addEstimateCall()
|
||||
result.addErrorHandling()
|
||||
13
ethers/contracts/overrides.nim
Normal file
13
ethers/contracts/overrides.nim
Normal file
@ -0,0 +1,13 @@
|
||||
import ../basics
|
||||
import ../blocktag
|
||||
|
||||
type
|
||||
TransactionOverrides* = ref object of RootObj
|
||||
nonce*: ?UInt256
|
||||
chainId*: ?UInt256
|
||||
gasPrice*: ?UInt256
|
||||
maxFeePerGas*: ?UInt256
|
||||
maxPriorityFeePerGas*: ?UInt256
|
||||
gasLimit*: ?UInt256
|
||||
CallOverrides* = ref object of TransactionOverrides
|
||||
blockTag*: ?BlockTag
|
||||
76
ethers/contracts/syntax.nim
Normal file
76
ethers/contracts/syntax.nim
Normal file
@ -0,0 +1,76 @@
|
||||
import std/macros
|
||||
import ./contractcall
|
||||
|
||||
template view* {.pragma.}
|
||||
template pure* {.pragma.}
|
||||
template getter* {.pragma.}
|
||||
template errors*(types) {.pragma.}
|
||||
|
||||
func isGetter*(procedure: NimNode): bool =
|
||||
let pragmas = procedure[4]
|
||||
for pragma in pragmas:
|
||||
if pragma.eqIdent "getter":
|
||||
return true
|
||||
false
|
||||
|
||||
func isConstant*(procedure: NimNode): bool =
|
||||
let pragmas = procedure[4]
|
||||
for pragma in pragmas:
|
||||
if pragma.eqIdent "view":
|
||||
return true
|
||||
elif pragma.eqIdent "pure":
|
||||
return true
|
||||
elif pragma.eqIdent "getter":
|
||||
return true
|
||||
false
|
||||
|
||||
func isMultipleReturn*(returnType: NimNode): bool =
|
||||
(returnType.kind == nnkPar and returnType.len > 1) or
|
||||
(returnType.kind == nnkTupleConstr) or
|
||||
(returnType.kind == nnkTupleTy)
|
||||
|
||||
func getContract(procedure: NimNode): NimNode =
|
||||
let firstArgument = procedure.params[1][0]
|
||||
quote do:
|
||||
Contract(`firstArgument`)
|
||||
|
||||
func getFunctionName(procedure: NimNode): string =
|
||||
$basename(procedure[0])
|
||||
|
||||
func getArgumentTuple(procedure: NimNode): NimNode =
|
||||
let parameters = procedure.params
|
||||
var arguments = newNimNode(nnkTupleConstr, parameters)
|
||||
for parameter in parameters[2..^2]:
|
||||
for name in parameter[0..^3]:
|
||||
arguments.add name
|
||||
return arguments
|
||||
|
||||
func getOverrides(procedure: NimNode): NimNode =
|
||||
procedure.params.last[^3]
|
||||
|
||||
func getContractCall*(procedure: NimNode): NimNode =
|
||||
let contract = getContract(procedure)
|
||||
let function = getFunctionName(procedure)
|
||||
let arguments = getArgumentTuple(procedure)
|
||||
let overrides = getOverrides(procedure)
|
||||
quote do:
|
||||
ContractCall.init(`contract`, `function`, `arguments`, `overrides`)
|
||||
|
||||
func addOverridesParameter*(procedure: var NimNode) =
|
||||
let overrides = genSym(nskParam, "overrides")
|
||||
procedure.params.add(
|
||||
newIdentDefs(
|
||||
overrides,
|
||||
newEmptyNode(),
|
||||
quote do: TransactionOverrides()
|
||||
)
|
||||
)
|
||||
|
||||
func addAsyncPragma*(procedure: var NimNode) =
|
||||
procedure.addPragma nnkExprColonExpr.newTree(
|
||||
quote do: async,
|
||||
quote do: (raises: [CancelledError, ProviderError, EthersError])
|
||||
)
|
||||
|
||||
func addUsedPragma*(procedure: var NimNode) =
|
||||
procedure.addPragma(quote do: used)
|
||||
71
ethers/contracts/transactions.nim
Normal file
71
ethers/contracts/transactions.nim
Normal file
@ -0,0 +1,71 @@
|
||||
import pkg/contractabi
|
||||
import pkg/chronicles
|
||||
import ../basics
|
||||
import ../provider
|
||||
import ../signer
|
||||
import ../transaction
|
||||
import ./contract
|
||||
import ./contractcall
|
||||
import ./overrides
|
||||
|
||||
{.push raises: [].}
|
||||
|
||||
logScope:
|
||||
topics = "ethers contract"
|
||||
|
||||
proc createTransaction*(call: ContractCall): Transaction =
|
||||
let selector = selector(call.function, typeof call.arguments).toArray
|
||||
let data = @selector & AbiEncoder.encode(call.arguments)
|
||||
Transaction(
|
||||
to: call.contract.address,
|
||||
data: data,
|
||||
nonce: call.overrides.nonce,
|
||||
chainId: call.overrides.chainId,
|
||||
gasPrice: call.overrides.gasPrice,
|
||||
maxFeePerGas: call.overrides.maxFeePerGas,
|
||||
maxPriorityFeePerGas: call.overrides.maxPriorityFeePerGas,
|
||||
gasLimit: call.overrides.gasLimit,
|
||||
)
|
||||
|
||||
proc decodeResponse(T: type, bytes: seq[byte]): T {.raises: [ContractError].} =
|
||||
without decoded =? AbiDecoder.decode(bytes, T):
|
||||
raise newException(ContractError, "unable to decode return value as " & $T)
|
||||
return decoded
|
||||
|
||||
proc call(
|
||||
provider: Provider, transaction: Transaction, overrides: TransactionOverrides
|
||||
): Future[seq[byte]] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
if overrides of CallOverrides and blockTag =? CallOverrides(overrides).blockTag:
|
||||
await provider.call(transaction, blockTag)
|
||||
else:
|
||||
await provider.call(transaction)
|
||||
|
||||
proc callTransaction*(call: ContractCall) {.async: (raises: [ProviderError, SignerError, CancelledError]).} =
|
||||
var transaction = createTransaction(call)
|
||||
|
||||
if signer =? call.contract.signer and transaction.sender.isNone:
|
||||
transaction.sender = some(await signer.getAddress())
|
||||
|
||||
discard await call.contract.provider.call(transaction, call.overrides)
|
||||
|
||||
proc callTransaction*(call: ContractCall, ReturnType: type): Future[ReturnType] {.async: (raises: [ProviderError, SignerError, ContractError, CancelledError]).} =
|
||||
var transaction = createTransaction(call)
|
||||
|
||||
if signer =? call.contract.signer and transaction.sender.isNone:
|
||||
transaction.sender = some(await signer.getAddress())
|
||||
|
||||
let response = await call.contract.provider.call(transaction, call.overrides)
|
||||
return decodeResponse(ReturnType, response)
|
||||
|
||||
proc sendTransaction*(call: ContractCall): Future[?TransactionResponse] {.async: (raises: [SignerError, ProviderError, CancelledError]).} =
|
||||
if signer =? call.contract.signer:
|
||||
withLock(signer):
|
||||
let transaction = createTransaction(call)
|
||||
let populated = await signer.populateTransaction(transaction)
|
||||
trace "sending contract transaction", function = call.function, params = $call.arguments
|
||||
let txResp = await signer.sendTransaction(populated)
|
||||
return txResp.some
|
||||
else:
|
||||
await callTransaction(call)
|
||||
return TransactionResponse.none
|
||||
|
||||
@ -1,7 +1,18 @@
|
||||
import ./basics
|
||||
|
||||
type SolidityError* = object of EthersError
|
||||
type
|
||||
SolidityError* = object of EthersError
|
||||
ContractError* = object of EthersError
|
||||
SignerError* = object of EthersError
|
||||
SubscriptionError* = object of EthersError
|
||||
ProviderError* = object of EthersError
|
||||
data*: ?seq[byte]
|
||||
|
||||
{.push raises:[].}
|
||||
|
||||
template errors*(types) {.pragma.}
|
||||
proc toErr*[E1: ref CatchableError, E2: EthersError](
|
||||
e1: E1,
|
||||
_: type E2,
|
||||
msg: string = e1.msg): ref E2 =
|
||||
|
||||
return newException(E2, msg, e1)
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import pkg/chronicles
|
||||
import pkg/serde
|
||||
import pkg/questionable
|
||||
import ./basics
|
||||
import ./transaction
|
||||
import ./blocktag
|
||||
@ -8,13 +9,12 @@ import ./errors
|
||||
export basics
|
||||
export transaction
|
||||
export blocktag
|
||||
export errors
|
||||
|
||||
{.push raises: [].}
|
||||
|
||||
type
|
||||
Provider* = ref object of RootObj
|
||||
ProviderError* = object of EthersError
|
||||
data*: ?seq[byte]
|
||||
EstimateGasError* = object of ProviderError
|
||||
transaction*: Transaction
|
||||
Subscription* = ref object of RootObj
|
||||
@ -56,13 +56,14 @@ type
|
||||
effectiveGasPrice*: ?UInt256
|
||||
status*: TransactionStatus
|
||||
transactionType* {.serialize("type"), deserialize("type").}: TransactionType
|
||||
LogHandler* = proc(log: Log) {.gcsafe, raises:[].}
|
||||
BlockHandler* = proc(blck: Block) {.gcsafe, raises:[].}
|
||||
LogHandler* = proc(log: ?!Log) {.gcsafe, raises:[].}
|
||||
BlockHandler* = proc(blck: ?!Block) {.gcsafe, raises:[].}
|
||||
Topic* = array[32, byte]
|
||||
Block* {.serialize.} = object
|
||||
number*: ?UInt256
|
||||
timestamp*: UInt256
|
||||
hash*: ?BlockHash
|
||||
baseFeePerGas* : ?UInt256
|
||||
PastTransaction* {.serialize.} = object
|
||||
blockHash*: BlockHash
|
||||
blockNumber*: UInt256
|
||||
@ -102,96 +103,90 @@ func toTransaction*(past: PastTransaction): Transaction =
|
||||
)
|
||||
|
||||
method getBlockNumber*(
|
||||
provider: Provider): Future[UInt256] {.base, async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: Provider
|
||||
): Future[UInt256] {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method getBlock*(
|
||||
provider: Provider,
|
||||
tag: BlockTag): Future[?Block] {.base, async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: Provider, tag: BlockTag
|
||||
): Future[?Block] {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method call*(
|
||||
provider: Provider,
|
||||
tx: Transaction,
|
||||
blockTag = BlockTag.latest): Future[seq[byte]] {.base, async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: Provider, tx: Transaction, blockTag = BlockTag.latest
|
||||
): Future[seq[byte]] {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method getGasPrice*(
|
||||
provider: Provider): Future[UInt256] {.base, async: (raises:[ProviderError]).} =
|
||||
provider: Provider
|
||||
): Future[UInt256] {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method getMaxPriorityFeePerGas*(
|
||||
provider: Provider
|
||||
): Future[UInt256] {.base, async: (raises: [CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method getTransactionCount*(
|
||||
provider: Provider,
|
||||
address: Address,
|
||||
blockTag = BlockTag.latest): Future[UInt256] {.base, async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: Provider, address: Address, blockTag = BlockTag.latest
|
||||
): Future[UInt256] {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method getTransaction*(
|
||||
provider: Provider,
|
||||
txHash: TransactionHash): Future[?PastTransaction] {.base, async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: Provider, txHash: TransactionHash
|
||||
): Future[?PastTransaction] {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method getTransactionReceipt*(
|
||||
provider: Provider,
|
||||
txHash: TransactionHash): Future[?TransactionReceipt] {.base, async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: Provider, txHash: TransactionHash
|
||||
): Future[?TransactionReceipt] {.
|
||||
base, async: (raises: [ProviderError, CancelledError])
|
||||
.} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method sendTransaction*(
|
||||
provider: Provider,
|
||||
rawTransaction: seq[byte]): Future[TransactionResponse] {.base, async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: Provider, rawTransaction: seq[byte]
|
||||
): Future[TransactionResponse] {.
|
||||
base, async: (raises: [ProviderError, CancelledError])
|
||||
.} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method getLogs*(
|
||||
provider: Provider,
|
||||
filter: EventFilter): Future[seq[Log]] {.base, async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: Provider, filter: EventFilter
|
||||
): Future[seq[Log]] {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method estimateGas*(
|
||||
provider: Provider,
|
||||
transaction: Transaction,
|
||||
blockTag = BlockTag.latest): Future[UInt256] {.base, async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: Provider, transaction: Transaction, blockTag = BlockTag.latest
|
||||
): Future[UInt256] {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method getChainId*(
|
||||
provider: Provider): Future[UInt256] {.base, async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: Provider
|
||||
): Future[UInt256] {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method subscribe*(
|
||||
provider: Provider,
|
||||
filter: EventFilter,
|
||||
callback: LogHandler): Future[Subscription] {.base, async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: Provider, filter: EventFilter, callback: LogHandler
|
||||
): Future[Subscription] {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method subscribe*(
|
||||
provider: Provider,
|
||||
callback: BlockHandler): Future[Subscription] {.base, async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: Provider, callback: BlockHandler
|
||||
): Future[Subscription] {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method unsubscribe*(
|
||||
subscription: Subscription) {.base, async: (raises:[ProviderError]).} =
|
||||
|
||||
subscription: Subscription
|
||||
) {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method isSyncing*(provider: Provider): Future[bool] {.base, async.} =
|
||||
method isSyncing*(provider: Provider): Future[bool] {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
proc replay*(
|
||||
provider: Provider,
|
||||
tx: Transaction,
|
||||
blockNumber: UInt256) {.async: (raises:[ProviderError]).} =
|
||||
provider: Provider, tx: Transaction, blockNumber: UInt256
|
||||
) {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
# Replay transaction at block. Useful for fetching revert reasons, which will
|
||||
# be present in the raised error message. The replayed block number should
|
||||
# include the state of the chain in the block previous to the block in which
|
||||
@ -203,8 +198,8 @@ proc replay*(
|
||||
discard await provider.call(tx, BlockTag.init(blockNumber))
|
||||
|
||||
proc ensureSuccess(
|
||||
provider: Provider,
|
||||
receipt: TransactionReceipt) {.async: (raises: [ProviderError]).} =
|
||||
provider: Provider, receipt: TransactionReceipt
|
||||
) {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
## If the receipt.status is Failed, the tx is replayed to obtain a revert
|
||||
## reason, after which a ProviderError with the revert reason is raised.
|
||||
## If no revert reason was obtained
|
||||
@ -227,7 +222,7 @@ proc confirm*(
|
||||
tx: TransactionResponse,
|
||||
confirmations = EthersDefaultConfirmations,
|
||||
timeout = EthersReceiptTimeoutBlks): Future[TransactionReceipt]
|
||||
{.async: (raises: [CancelledError, ProviderError, EthersError]).} =
|
||||
{.async: (raises: [CancelledError, ProviderError, SubscriptionError, EthersError]).} =
|
||||
|
||||
## Waits for a transaction to be mined and for the specified number of blocks
|
||||
## to pass since it was mined (confirmations). The number of confirmations
|
||||
@ -238,6 +233,12 @@ proc confirm*(
|
||||
assert confirmations > 0
|
||||
|
||||
var blockNumber: UInt256
|
||||
|
||||
## We need initialized succesfull Result, because the first iteration of the `while` loop
|
||||
## bellow is triggered "manually" by calling `await updateBlockNumber` and not by block
|
||||
## subscription. If left uninitialized then the Result is in error state and error is raised.
|
||||
## This result is not used for block value, but for block subscription errors.
|
||||
var blockSubscriptionResult: ?!Block = success(Block(number: UInt256.none, timestamp: 0.u256, hash: BlockHash.none))
|
||||
let blockEvent = newAsyncEvent()
|
||||
|
||||
proc updateBlockNumber {.async: (raises: []).} =
|
||||
@ -246,11 +247,17 @@ proc confirm*(
|
||||
if number > blockNumber:
|
||||
blockNumber = number
|
||||
blockEvent.fire()
|
||||
except ProviderError:
|
||||
except ProviderError, CancelledError:
|
||||
# there's nothing we can do here
|
||||
discard
|
||||
|
||||
proc onBlock(_: Block) =
|
||||
proc onBlock(blckResult: ?!Block) =
|
||||
blockSubscriptionResult = blckResult
|
||||
|
||||
if blckResult.isErr:
|
||||
blockEvent.fire()
|
||||
return
|
||||
|
||||
# ignore block parameter; hardhat may call this with pending blocks
|
||||
asyncSpawn updateBlockNumber()
|
||||
|
||||
@ -264,6 +271,16 @@ proc confirm*(
|
||||
await blockEvent.wait()
|
||||
blockEvent.clear()
|
||||
|
||||
if blockSubscriptionResult.isErr:
|
||||
let error = blockSubscriptionResult.error()
|
||||
|
||||
if error of SubscriptionError:
|
||||
raise (ref SubscriptionError)(error)
|
||||
elif error of CancelledError:
|
||||
raise (ref CancelledError)(error)
|
||||
else:
|
||||
raise error.toErr(ProviderError)
|
||||
|
||||
if blockNumber >= finish:
|
||||
await subscription.unsubscribe()
|
||||
raise newException(EthersError, "tx not mined before timeout")
|
||||
@ -282,13 +299,24 @@ proc confirm*(
|
||||
proc confirm*(
|
||||
tx: Future[TransactionResponse],
|
||||
confirmations: int = EthersDefaultConfirmations,
|
||||
timeout: int = EthersReceiptTimeoutBlks): Future[TransactionReceipt] {.async.} =
|
||||
timeout: int = EthersReceiptTimeoutBlks): Future[TransactionReceipt] {.async: (raises: [CancelledError, EthersError]).} =
|
||||
## Convenience method that allows wait to be chained to a sendTransaction
|
||||
## call, eg:
|
||||
## `await signer.sendTransaction(populated).confirm(3)`
|
||||
try:
|
||||
let txResp = await tx
|
||||
return await txResp.confirm(confirmations, timeout)
|
||||
except CancelledError as e:
|
||||
raise e
|
||||
except EthersError as e:
|
||||
raise e
|
||||
except CatchableError as e:
|
||||
raise newException(
|
||||
EthersError,
|
||||
"Error when trying to confirm the provider transaction: " & e.msg
|
||||
)
|
||||
|
||||
let txResp = await tx
|
||||
return await txResp.confirm(confirmations, timeout)
|
||||
|
||||
method close*(provider: Provider) {.base, async: (raises:[ProviderError]).} =
|
||||
method close*(
|
||||
provider: Provider
|
||||
) {.base, async: (raises: [ProviderError, CancelledError]).} =
|
||||
discard
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import std/tables
|
||||
import std/uri
|
||||
import pkg/chronicles
|
||||
import pkg/eth/common/eth_types_json_serialization
|
||||
import pkg/eth/common/eth_types except Block, Log, Address, Transaction
|
||||
import pkg/json_rpc/rpcclient
|
||||
import pkg/json_rpc/errors
|
||||
import pkg/serde
|
||||
@ -28,6 +28,7 @@ type
|
||||
JsonRpcProvider* = ref object of Provider
|
||||
client: Future[RpcClient]
|
||||
subscriptions: Future[JsonRpcSubscriptions]
|
||||
maxPriorityFeePerGas: UInt256
|
||||
|
||||
JsonRpcSubscription* = ref object of Subscription
|
||||
subscriptions: JsonRpcSubscriptions
|
||||
@ -43,6 +44,7 @@ type
|
||||
|
||||
const defaultUrl = "http://localhost:8545"
|
||||
const defaultPollingInterval = 4.seconds
|
||||
const defaultMaxPriorityFeePerGas = 1_000_000_000.u256
|
||||
|
||||
proc jsonHeaders: seq[(string, string)] =
|
||||
@[("Content-Type", "application/json")]
|
||||
@ -50,13 +52,14 @@ proc jsonHeaders: seq[(string, string)] =
|
||||
proc new*(
|
||||
_: type JsonRpcProvider,
|
||||
url=defaultUrl,
|
||||
pollingInterval=defaultPollingInterval): JsonRpcProvider {.raises: [JsonRpcProviderError].} =
|
||||
pollingInterval=defaultPollingInterval,
|
||||
maxPriorityFeePerGas=defaultMaxPriorityFeePerGas): JsonRpcProvider {.raises: [JsonRpcProviderError].} =
|
||||
|
||||
var initialized: Future[void]
|
||||
var client: RpcClient
|
||||
var subscriptions: JsonRpcSubscriptions
|
||||
|
||||
proc initialize {.async: (raises:[JsonRpcProviderError]).} =
|
||||
proc initialize() {.async: (raises: [JsonRpcProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
case parseUri(url).scheme
|
||||
of "ws", "wss":
|
||||
@ -72,43 +75,47 @@ proc new*(
|
||||
pollingInterval = pollingInterval)
|
||||
subscriptions.start()
|
||||
|
||||
proc awaitClient: Future[RpcClient] {.async:(raises:[JsonRpcProviderError]).} =
|
||||
proc awaitClient(): Future[RpcClient] {.
|
||||
async: (raises: [JsonRpcProviderError, CancelledError])
|
||||
.} =
|
||||
convertError:
|
||||
await initialized
|
||||
return client
|
||||
|
||||
proc awaitSubscriptions: Future[JsonRpcSubscriptions] {.async:(raises:[JsonRpcProviderError]).} =
|
||||
proc awaitSubscriptions(): Future[JsonRpcSubscriptions] {.
|
||||
async: (raises: [JsonRpcProviderError, CancelledError])
|
||||
.} =
|
||||
convertError:
|
||||
await initialized
|
||||
return subscriptions
|
||||
|
||||
initialized = initialize()
|
||||
return JsonRpcProvider(client: awaitClient(), subscriptions: awaitSubscriptions())
|
||||
return JsonRpcProvider(client: awaitClient(), subscriptions: awaitSubscriptions(), maxPriorityFeePerGas: maxPriorityFeePerGas)
|
||||
|
||||
proc callImpl(
|
||||
client: RpcClient,
|
||||
call: string,
|
||||
args: JsonNode): Future[JsonNode] {.async: (raises: [JsonRpcProviderError]).} =
|
||||
|
||||
without response =? (await client.call(call, %args)).catch, error:
|
||||
client: RpcClient, call: string, args: JsonNode
|
||||
): Future[JsonNode] {.async: (raises: [JsonRpcProviderError, CancelledError]).} =
|
||||
try:
|
||||
let response = await client.call(call, %args)
|
||||
without json =? JsonNode.fromJson(response.string), error:
|
||||
raiseJsonRpcProviderError "Failed to parse response '" & response.string & "': " &
|
||||
error.msg
|
||||
return json
|
||||
except CancelledError as error:
|
||||
raise error
|
||||
except CatchableError as error:
|
||||
raiseJsonRpcProviderError error.msg
|
||||
without json =? JsonNode.fromJson(response.string), error:
|
||||
raiseJsonRpcProviderError "Failed to parse response: " & error.msg
|
||||
json
|
||||
|
||||
proc send*(
|
||||
provider: JsonRpcProvider,
|
||||
call: string,
|
||||
arguments: seq[JsonNode] = @[]): Future[JsonNode]
|
||||
{.async: (raises: [JsonRpcProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider, call: string, arguments: seq[JsonNode] = @[]
|
||||
): Future[JsonNode] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
return await client.callImpl(call, %arguments)
|
||||
|
||||
proc listAccounts*(provider: JsonRpcProvider): Future[seq[Address]]
|
||||
{.async: (raises: [JsonRpcProviderError]).} =
|
||||
|
||||
proc listAccounts*(
|
||||
provider: JsonRpcProvider
|
||||
): Future[seq[Address]] {.async: (raises: [JsonRpcProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
return await client.eth_accounts()
|
||||
@ -120,73 +127,78 @@ proc getSigner*(provider: JsonRpcProvider, address: Address): JsonRpcSigner =
|
||||
JsonRpcSigner(provider: provider, address: some address)
|
||||
|
||||
method getBlockNumber*(
|
||||
provider: JsonRpcProvider): Future[UInt256] {.async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider
|
||||
): Future[UInt256] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
return await client.eth_blockNumber()
|
||||
|
||||
method getBlock*(
|
||||
provider: JsonRpcProvider,
|
||||
tag: BlockTag): Future[?Block] {.async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider, tag: BlockTag
|
||||
): Future[?Block] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
return await client.eth_getBlockByNumber(tag, false)
|
||||
|
||||
method call*(
|
||||
provider: JsonRpcProvider,
|
||||
tx: Transaction,
|
||||
blockTag = BlockTag.latest): Future[seq[byte]] {.async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider, tx: Transaction, blockTag = BlockTag.latest
|
||||
): Future[seq[byte]] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
return await client.eth_call(tx, blockTag)
|
||||
|
||||
method getGasPrice*(
|
||||
provider: JsonRpcProvider): Future[UInt256] {.async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider
|
||||
): Future[UInt256] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
return await client.eth_gasPrice()
|
||||
|
||||
method getTransactionCount*(
|
||||
provider: JsonRpcProvider,
|
||||
address: Address,
|
||||
blockTag = BlockTag.latest): Future[UInt256] {.async: (raises:[ProviderError]).} =
|
||||
method getMaxPriorityFeePerGas*(
|
||||
provider: JsonRpcProvider
|
||||
): Future[UInt256] {.async: (raises: [CancelledError]).} =
|
||||
try:
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
return await client.eth_maxPriorityFeePerGas()
|
||||
except JsonRpcProviderError:
|
||||
# If the provider does not provide the implementation
|
||||
# let's just remove the manual value
|
||||
return provider.maxPriorityFeePerGas
|
||||
|
||||
method getTransactionCount*(
|
||||
provider: JsonRpcProvider, address: Address, blockTag = BlockTag.latest
|
||||
): Future[UInt256] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
return await client.eth_getTransactionCount(address, blockTag)
|
||||
|
||||
method getTransaction*(
|
||||
provider: JsonRpcProvider,
|
||||
txHash: TransactionHash): Future[?PastTransaction] {.async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider, txHash: TransactionHash
|
||||
): Future[?PastTransaction] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
return await client.eth_getTransactionByHash(txHash)
|
||||
|
||||
method getTransactionReceipt*(
|
||||
provider: JsonRpcProvider,
|
||||
txHash: TransactionHash): Future[?TransactionReceipt] {.async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider, txHash: TransactionHash
|
||||
): Future[?TransactionReceipt] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
return await client.eth_getTransactionReceipt(txHash)
|
||||
|
||||
method getLogs*(
|
||||
provider: JsonRpcProvider,
|
||||
filter: EventFilter): Future[seq[Log]] {.async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider, filter: EventFilter
|
||||
): Future[seq[Log]] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
let logsJson = if filter of Filter:
|
||||
await client.eth_getLogs(Filter(filter))
|
||||
elif filter of FilterByBlockHash:
|
||||
await client.eth_getLogs(FilterByBlockHash(filter))
|
||||
else:
|
||||
await client.eth_getLogs(filter)
|
||||
let logsJson =
|
||||
if filter of Filter:
|
||||
await client.eth_getLogs(Filter(filter))
|
||||
elif filter of FilterByBlockHash:
|
||||
await client.eth_getLogs(FilterByBlockHash(filter))
|
||||
else:
|
||||
await client.eth_getLogs(filter)
|
||||
|
||||
var logs: seq[Log] = @[]
|
||||
for logJson in logsJson.getElems:
|
||||
@ -196,10 +208,10 @@ method getLogs*(
|
||||
return logs
|
||||
|
||||
method estimateGas*(
|
||||
provider: JsonRpcProvider,
|
||||
transaction: Transaction,
|
||||
blockTag = BlockTag.latest): Future[UInt256] {.async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider,
|
||||
transaction: Transaction,
|
||||
blockTag = BlockTag.latest,
|
||||
): Future[UInt256] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
try:
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
@ -209,24 +221,24 @@ method estimateGas*(
|
||||
msg: "Estimate gas failed: " & error.msg,
|
||||
data: error.data,
|
||||
transaction: transaction,
|
||||
parent: error
|
||||
parent: error,
|
||||
)
|
||||
|
||||
method getChainId*(
|
||||
provider: JsonRpcProvider): Future[UInt256] {.async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider
|
||||
): Future[UInt256] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
try:
|
||||
return await client.eth_chainId()
|
||||
except CancelledError as error:
|
||||
raise error
|
||||
except CatchableError:
|
||||
return parse(await client.net_version(), UInt256)
|
||||
|
||||
method sendTransaction*(
|
||||
provider: JsonRpcProvider,
|
||||
rawTransaction: seq[byte]): Future[TransactionResponse]
|
||||
{.async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider, rawTransaction: seq[byte]
|
||||
): Future[TransactionResponse] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let
|
||||
client = await provider.client
|
||||
@ -235,41 +247,40 @@ method sendTransaction*(
|
||||
return TransactionResponse(hash: hash, provider: provider)
|
||||
|
||||
method subscribe*(
|
||||
provider: JsonRpcProvider,
|
||||
filter: EventFilter,
|
||||
onLog: LogHandler): Future[Subscription] {.async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider, filter: EventFilter, onLog: LogHandler
|
||||
): Future[Subscription] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let subscriptions = await provider.subscriptions
|
||||
let id = await subscriptions.subscribeLogs(filter, onLog)
|
||||
return JsonRpcSubscription(subscriptions: subscriptions, id: id)
|
||||
|
||||
method subscribe*(
|
||||
provider: JsonRpcProvider,
|
||||
onBlock: BlockHandler): Future[Subscription] {.async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider, onBlock: BlockHandler
|
||||
): Future[Subscription] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let subscriptions = await provider.subscriptions
|
||||
let id = await subscriptions.subscribeBlocks(onBlock)
|
||||
return JsonRpcSubscription(subscriptions: subscriptions, id: id)
|
||||
|
||||
method unsubscribe*(
|
||||
subscription: JsonRpcSubscription) {.async: (raises:[ProviderError]).} =
|
||||
|
||||
subscription: JsonRpcSubscription
|
||||
) {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let subscriptions = subscription.subscriptions
|
||||
let id = subscription.id
|
||||
await subscriptions.unsubscribe(id)
|
||||
|
||||
method isSyncing*(provider: JsonRpcProvider): Future[bool] {.async.} =
|
||||
method isSyncing*(
|
||||
provider: JsonRpcProvider
|
||||
): Future[bool] {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
let response = await provider.send("eth_syncing")
|
||||
if response.kind == JsonNodeKind.JObject:
|
||||
return true
|
||||
return response.getBool()
|
||||
|
||||
method close*(
|
||||
provider: JsonRpcProvider) {.async: (raises:[ProviderError]).} =
|
||||
|
||||
provider: JsonRpcProvider
|
||||
) {.async: (raises: [ProviderError, CancelledError]).} =
|
||||
convertError:
|
||||
let client = await provider.client
|
||||
let subscriptions = await provider.subscriptions
|
||||
@ -290,6 +301,8 @@ proc raiseJsonRpcSignerError(
|
||||
template convertSignerError(body) =
|
||||
try:
|
||||
body
|
||||
except CancelledError as error:
|
||||
raise error
|
||||
except JsonRpcError as error:
|
||||
raiseJsonRpcSignerError(error.msg)
|
||||
except CatchableError as error:
|
||||
@ -301,9 +314,8 @@ method provider*(signer: JsonRpcSigner): Provider
|
||||
signer.provider
|
||||
|
||||
method getAddress*(
|
||||
signer: JsonRpcSigner): Future[Address]
|
||||
{.async: (raises:[ProviderError, SignerError]).} =
|
||||
|
||||
signer: JsonRpcSigner
|
||||
): Future[Address] {.async: (raises: [ProviderError, SignerError, CancelledError]).} =
|
||||
if address =? signer.address:
|
||||
return address
|
||||
|
||||
@ -314,19 +326,18 @@ method getAddress*(
|
||||
raiseJsonRpcSignerError "no address found"
|
||||
|
||||
method signMessage*(
|
||||
signer: JsonRpcSigner,
|
||||
message: seq[byte]): Future[seq[byte]] {.async: (raises:[SignerError]).} =
|
||||
|
||||
signer: JsonRpcSigner, message: seq[byte]
|
||||
): Future[seq[byte]] {.async: (raises: [SignerError, CancelledError]).} =
|
||||
convertSignerError:
|
||||
let client = await signer.provider.client
|
||||
let address = await signer.getAddress()
|
||||
return await client.personal_sign(message, address)
|
||||
|
||||
method sendTransaction*(
|
||||
signer: JsonRpcSigner,
|
||||
transaction: Transaction): Future[TransactionResponse]
|
||||
{.async: (raises:[SignerError, ProviderError]).} =
|
||||
|
||||
signer: JsonRpcSigner, transaction: Transaction
|
||||
): Future[TransactionResponse] {.
|
||||
async: (raises: [SignerError, ProviderError, CancelledError])
|
||||
.} =
|
||||
convertError:
|
||||
let
|
||||
client = await signer.provider.client
|
||||
|
||||
@ -1,9 +1,12 @@
|
||||
import std/strutils
|
||||
import pkg/stew/byteutils
|
||||
import ../../basics
|
||||
import ../../errors
|
||||
import ../../provider
|
||||
import ./conversions
|
||||
|
||||
export errors
|
||||
|
||||
{.push raises:[].}
|
||||
|
||||
type JsonRpcProviderError* = object of ProviderError
|
||||
@ -37,6 +40,8 @@ proc raiseJsonRpcProviderError*(
|
||||
template convertError*(body) =
|
||||
try:
|
||||
body
|
||||
except CancelledError as error:
|
||||
raise error
|
||||
except JsonRpcError as error:
|
||||
raiseJsonRpcProviderError(error.msg)
|
||||
except CatchableError as error:
|
||||
|
||||
@ -21,3 +21,4 @@ proc eth_newBlockFilter(): JsonNode
|
||||
proc eth_newFilter(filter: EventFilter): JsonNode
|
||||
proc eth_getFilterChanges(id: JsonNode): JsonNode
|
||||
proc eth_uninstallFilter(id: JsonNode): bool
|
||||
proc eth_maxPriorityFeePerGas(): UInt256
|
||||
|
||||
@ -1,9 +1,12 @@
|
||||
import std/tables
|
||||
import std/sequtils
|
||||
import std/strutils
|
||||
import pkg/chronos
|
||||
import pkg/questionable
|
||||
import pkg/json_rpc/rpcclient
|
||||
import pkg/serde
|
||||
import ../../basics
|
||||
import ../../errors
|
||||
import ../../provider
|
||||
include ../../nimshims/hashes
|
||||
import ./rpccalls
|
||||
@ -16,12 +19,25 @@ type
|
||||
client: RpcClient
|
||||
callbacks: Table[JsonNode, SubscriptionCallback]
|
||||
methodHandlers: Table[string, MethodHandler]
|
||||
# Used by both PollingSubscriptions and WebsocketSubscriptions to store
|
||||
# subscription filters so the subscriptions can be recreated. With
|
||||
# PollingSubscriptions, the RPC node might prune/forget about them, and with
|
||||
# WebsocketSubscriptions, when using hardhat, subscriptions are dropped after 5
|
||||
# minutes.
|
||||
logFilters: Table[JsonNode, EventFilter]
|
||||
MethodHandler* = proc (j: JsonNode) {.gcsafe, raises: [].}
|
||||
SubscriptionCallback = proc(id, arguments: JsonNode) {.gcsafe, raises:[].}
|
||||
SubscriptionError* = object of EthersError
|
||||
SubscriptionCallback = proc(id: JsonNode, arguments: ?!JsonNode) {.gcsafe, raises:[].}
|
||||
|
||||
{.push raises:[].}
|
||||
|
||||
template convertErrorsToSubscriptionError(body) =
|
||||
try:
|
||||
body
|
||||
except CancelledError as error:
|
||||
raise error
|
||||
except CatchableError as error:
|
||||
raise error.toErr(SubscriptionError)
|
||||
|
||||
template `or`(a: JsonNode, b: typed): JsonNode =
|
||||
if a.isNil: b else: a
|
||||
|
||||
@ -43,7 +59,6 @@ func start*(subscriptions: JsonRpcSubscriptions) =
|
||||
# true = continue processing message using json_rpc's default message handler
|
||||
return ok true
|
||||
|
||||
|
||||
proc setMethodHandler(
|
||||
subscriptions: JsonRpcSubscriptions,
|
||||
`method`: string,
|
||||
@ -54,80 +69,157 @@ proc setMethodHandler(
|
||||
method subscribeBlocks*(subscriptions: JsonRpcSubscriptions,
|
||||
onBlock: BlockHandler):
|
||||
Future[JsonNode]
|
||||
{.async, base.} =
|
||||
{.async: (raises: [SubscriptionError, CancelledError]), base,.} =
|
||||
raiseAssert "not implemented"
|
||||
|
||||
method subscribeLogs*(subscriptions: JsonRpcSubscriptions,
|
||||
filter: EventFilter,
|
||||
onLog: LogHandler):
|
||||
Future[JsonNode]
|
||||
{.async, base.} =
|
||||
{.async: (raises: [SubscriptionError, CancelledError]), base.} =
|
||||
raiseAssert "not implemented"
|
||||
|
||||
method unsubscribe*(subscriptions: JsonRpcSubscriptions,
|
||||
id: JsonNode)
|
||||
{.async, base.} =
|
||||
raiseAssert "not implemented"
|
||||
{.async: (raises: [CancelledError]), base.} =
|
||||
raiseAssert "not implemented "
|
||||
|
||||
method close*(subscriptions: JsonRpcSubscriptions) {.async, base.} =
|
||||
method close*(subscriptions: JsonRpcSubscriptions) {.async: (raises: []), base.} =
|
||||
let ids = toSeq subscriptions.callbacks.keys
|
||||
for id in ids:
|
||||
await subscriptions.unsubscribe(id)
|
||||
try:
|
||||
await subscriptions.unsubscribe(id)
|
||||
except CatchableError as e:
|
||||
error "JsonRpc unsubscription failed", error = e.msg, id = id
|
||||
|
||||
proc getCallback(subscriptions: JsonRpcSubscriptions,
|
||||
id: JsonNode): ?SubscriptionCallback =
|
||||
id: JsonNode): ?SubscriptionCallback {. raises:[].} =
|
||||
try:
|
||||
if not id.isNil and id in subscriptions.callbacks:
|
||||
subscriptions.callbacks[id].some
|
||||
else:
|
||||
SubscriptionCallback.none
|
||||
except KeyError:
|
||||
SubscriptionCallback.none
|
||||
return subscriptions.callbacks[id].some
|
||||
except: discard
|
||||
|
||||
# Web sockets
|
||||
|
||||
# Default re-subscription period is seconds
|
||||
const WsResubscribe {.intdefine.}: int = 0
|
||||
|
||||
type
|
||||
WebSocketSubscriptions = ref object of JsonRpcSubscriptions
|
||||
logFiltersLock: AsyncLock
|
||||
resubscribeFut: Future[void]
|
||||
resubscribeInterval: int
|
||||
|
||||
template withLock*(subscriptions: WebSocketSubscriptions, body: untyped) =
|
||||
if subscriptions.logFiltersLock.isNil:
|
||||
subscriptions.logFiltersLock = newAsyncLock()
|
||||
|
||||
await subscriptions.logFiltersLock.acquire()
|
||||
try:
|
||||
body
|
||||
finally:
|
||||
subscriptions.logFiltersLock.release()
|
||||
|
||||
# This is a workaround to manage the 5 minutes limit due to hardhat.
|
||||
# See https://github.com/NomicFoundation/hardhat/issues/2053#issuecomment-1061374064
|
||||
proc resubscribeWebsocketEventsOnTimeout*(subscriptions: WebsocketSubscriptions) {.async: (raises: [CancelledError]).} =
|
||||
while true:
|
||||
await sleepAsync(subscriptions.resubscribeInterval.seconds)
|
||||
try:
|
||||
withLock(subscriptions):
|
||||
for id, callback in subscriptions.callbacks:
|
||||
|
||||
var newId: JsonNode
|
||||
if id in subscriptions.logFilters:
|
||||
let filter = subscriptions.logFilters[id]
|
||||
newId = await subscriptions.client.eth_subscribe("logs", filter)
|
||||
subscriptions.logFilters[newId] = filter
|
||||
subscriptions.logFilters.del(id)
|
||||
else:
|
||||
newId = await subscriptions.client.eth_subscribe("newHeads")
|
||||
|
||||
subscriptions.callbacks[newId] = callback
|
||||
subscriptions.callbacks.del(id)
|
||||
discard await subscriptions.client.eth_unsubscribe(id)
|
||||
except CancelledError as e:
|
||||
raise e
|
||||
except CatchableError as e:
|
||||
error "WS resubscription failed" , error = e.msg
|
||||
|
||||
proc new*(_: type JsonRpcSubscriptions,
|
||||
client: RpcWebSocketClient): JsonRpcSubscriptions =
|
||||
client: RpcWebSocketClient,
|
||||
resubscribeInterval = WsResubscribe): JsonRpcSubscriptions =
|
||||
let subscriptions = WebSocketSubscriptions(client: client, resubscribeInterval: resubscribeInterval)
|
||||
|
||||
let subscriptions = WebSocketSubscriptions(client: client)
|
||||
proc subscriptionHandler(arguments: JsonNode) {.raises:[].} =
|
||||
let id = arguments{"subscription"} or newJString("")
|
||||
if callback =? subscriptions.getCallback(id):
|
||||
callback(id, arguments)
|
||||
callback(id, success(arguments))
|
||||
subscriptions.setMethodHandler("eth_subscription", subscriptionHandler)
|
||||
|
||||
if resubscribeInterval > 0:
|
||||
if resubscribeInterval >= 300:
|
||||
warn "Resubscription interval greater than 300 seconds is useless for hardhat workaround", resubscribeInterval = resubscribeInterval
|
||||
|
||||
subscriptions.resubscribeFut = resubscribeWebsocketEventsOnTimeout(subscriptions)
|
||||
|
||||
subscriptions
|
||||
|
||||
method subscribeBlocks(subscriptions: WebSocketSubscriptions,
|
||||
onBlock: BlockHandler):
|
||||
Future[JsonNode]
|
||||
{.async.} =
|
||||
proc callback(id, arguments: JsonNode) {.raises: [].} =
|
||||
if blck =? Block.fromJson(arguments{"result"}):
|
||||
onBlock(blck)
|
||||
let id = await subscriptions.client.eth_subscribe("newHeads")
|
||||
subscriptions.callbacks[id] = callback
|
||||
return id
|
||||
{.async: (raises: [SubscriptionError, CancelledError]).} =
|
||||
proc callback(id: JsonNode, argumentsResult: ?!JsonNode) {.raises: [].} =
|
||||
without arguments =? argumentsResult, error:
|
||||
onBlock(failure(Block, error.toErr(SubscriptionError)))
|
||||
return
|
||||
|
||||
let res = Block.fromJson(arguments{"result"}).mapFailure(SubscriptionError)
|
||||
onBlock(res)
|
||||
|
||||
convertErrorsToSubscriptionError:
|
||||
withLock(subscriptions):
|
||||
let id = await subscriptions.client.eth_subscribe("newHeads")
|
||||
subscriptions.callbacks[id] = callback
|
||||
return id
|
||||
|
||||
method subscribeLogs(subscriptions: WebSocketSubscriptions,
|
||||
filter: EventFilter,
|
||||
onLog: LogHandler):
|
||||
Future[JsonNode]
|
||||
{.async.} =
|
||||
proc callback(id, arguments: JsonNode) =
|
||||
if log =? Log.fromJson(arguments{"result"}):
|
||||
onLog(log)
|
||||
let id = await subscriptions.client.eth_subscribe("logs", filter)
|
||||
subscriptions.callbacks[id] = callback
|
||||
return id
|
||||
{.async: (raises: [SubscriptionError, CancelledError]).} =
|
||||
proc callback(id: JsonNode, argumentsResult: ?!JsonNode) =
|
||||
without arguments =? argumentsResult, error:
|
||||
onLog(failure(Log, error.toErr(SubscriptionError)))
|
||||
return
|
||||
|
||||
let res = Log.fromJson(arguments{"result"}).mapFailure(SubscriptionError)
|
||||
onLog(res)
|
||||
|
||||
convertErrorsToSubscriptionError:
|
||||
withLock(subscriptions):
|
||||
let id = await subscriptions.client.eth_subscribe("logs", filter)
|
||||
subscriptions.callbacks[id] = callback
|
||||
subscriptions.logFilters[id] = filter
|
||||
return id
|
||||
|
||||
method unsubscribe*(subscriptions: WebSocketSubscriptions,
|
||||
id: JsonNode)
|
||||
{.async.} =
|
||||
subscriptions.callbacks.del(id)
|
||||
discard await subscriptions.client.eth_unsubscribe(id)
|
||||
{.async: (raises: [CancelledError]).} =
|
||||
try:
|
||||
withLock(subscriptions):
|
||||
subscriptions.callbacks.del(id)
|
||||
discard await subscriptions.client.eth_unsubscribe(id)
|
||||
except CancelledError as e:
|
||||
raise e
|
||||
except CatchableError:
|
||||
# Ignore if uninstallation of the subscribiton fails.
|
||||
discard
|
||||
|
||||
method close*(subscriptions: WebSocketSubscriptions) {.async: (raises: []).} =
|
||||
await procCall JsonRpcSubscriptions(subscriptions).close()
|
||||
if not subscriptions.resubscribeFut.isNil:
|
||||
await subscriptions.resubscribeFut.cancelAndWait()
|
||||
|
||||
# Polling
|
||||
|
||||
@ -135,11 +227,6 @@ type
|
||||
PollingSubscriptions* = ref object of JsonRpcSubscriptions
|
||||
polling: Future[void]
|
||||
|
||||
# We need to keep around the filters that are used to create log filters on the RPC node
|
||||
# as there might be a time when they need to be recreated as RPC node might prune/forget
|
||||
# about them
|
||||
logFilters: Table[JsonNode, EventFilter]
|
||||
|
||||
# Used when filters are recreated to translate from the id that user
|
||||
# originally got returned to new filter id
|
||||
subscriptionMapping: Table[JsonNode, JsonNode]
|
||||
@ -150,7 +237,7 @@ proc new*(_: type JsonRpcSubscriptions,
|
||||
|
||||
let subscriptions = PollingSubscriptions(client: client)
|
||||
|
||||
proc resubscribe(id: JsonNode) {.async: (raises: [CancelledError]).} =
|
||||
proc resubscribe(id: JsonNode): Future[?!void] {.async: (raises: [CancelledError]).} =
|
||||
try:
|
||||
var newId: JsonNode
|
||||
# Log filters are stored in logFilters, block filters are not persisted
|
||||
@ -162,36 +249,49 @@ proc new*(_: type JsonRpcSubscriptions,
|
||||
else:
|
||||
newId = await subscriptions.client.eth_newBlockFilter()
|
||||
subscriptions.subscriptionMapping[id] = newId
|
||||
except CancelledError as error:
|
||||
raise error
|
||||
except CatchableError:
|
||||
# there's nothing further we can do here
|
||||
discard
|
||||
except CancelledError as e:
|
||||
raise e
|
||||
except CatchableError as e:
|
||||
return failure(void, e.toErr(SubscriptionError, "HTTP polling: There was an exception while getting subscription changes: " & e.msg))
|
||||
|
||||
proc getChanges(id: JsonNode): Future[JsonNode] {.async: (raises: [CancelledError]).} =
|
||||
return success()
|
||||
|
||||
proc getChanges(id: JsonNode): Future[?!JsonNode] {.async: (raises: [CancelledError]).} =
|
||||
if mappedId =? subscriptions.subscriptionMapping.?[id]:
|
||||
try:
|
||||
let changes = await subscriptions.client.eth_getFilterChanges(mappedId)
|
||||
if changes.kind == JArray:
|
||||
return changes
|
||||
except JsonRpcError:
|
||||
await resubscribe(id)
|
||||
return success(changes)
|
||||
except JsonRpcError as e:
|
||||
if error =? (await resubscribe(id)).errorOption:
|
||||
return failure(JsonNode, error)
|
||||
|
||||
# TODO: we could still miss some events between losing the subscription
|
||||
# and resubscribing. We should probably adopt a strategy like ethers.js,
|
||||
# whereby we keep track of the latest block number that we've seen
|
||||
# filter changes for:
|
||||
# https://github.com/ethers-io/ethers.js/blob/f97b92bbb1bde22fcc44100af78d7f31602863ab/packages/providers/src.ts/base-provider.ts#L977
|
||||
except CancelledError as error:
|
||||
raise error
|
||||
except CatchableError:
|
||||
# there's nothing we can do here
|
||||
discard
|
||||
return newJArray()
|
||||
|
||||
if not ("filter not found" in e.msg):
|
||||
return failure(JsonNode, e.toErr(SubscriptionError, "HTTP polling: There was an exception while getting subscription changes: " & e.msg))
|
||||
except CancelledError as e:
|
||||
raise e
|
||||
except SubscriptionError as e:
|
||||
return failure(JsonNode, e)
|
||||
except CatchableError as e:
|
||||
return failure(JsonNode, e.toErr(SubscriptionError, "HTTP polling: There was an exception while getting subscription changes: " & e.msg))
|
||||
return success(newJArray())
|
||||
|
||||
proc poll(id: JsonNode) {.async: (raises: [CancelledError]).} =
|
||||
for change in await getChanges(id):
|
||||
if callback =? subscriptions.getCallback(id):
|
||||
callback(id, change)
|
||||
without callback =? subscriptions.getCallback(id):
|
||||
return
|
||||
|
||||
without changes =? (await getChanges(id)), error:
|
||||
callback(id, failure(JsonNode, error))
|
||||
return
|
||||
|
||||
for change in changes:
|
||||
callback(id, success(change))
|
||||
|
||||
proc poll {.async: (raises: []).} =
|
||||
try:
|
||||
@ -206,56 +306,69 @@ proc new*(_: type JsonRpcSubscriptions,
|
||||
asyncSpawn subscriptions.polling
|
||||
subscriptions
|
||||
|
||||
method close*(subscriptions: PollingSubscriptions) {.async.} =
|
||||
method close*(subscriptions: PollingSubscriptions) {.async: (raises: []).} =
|
||||
await subscriptions.polling.cancelAndWait()
|
||||
await procCall JsonRpcSubscriptions(subscriptions).close()
|
||||
|
||||
method subscribeBlocks(subscriptions: PollingSubscriptions,
|
||||
onBlock: BlockHandler):
|
||||
Future[JsonNode]
|
||||
{.async.} =
|
||||
{.async: (raises: [SubscriptionError, CancelledError]).} =
|
||||
|
||||
proc getBlock(hash: BlockHash) {.async.} =
|
||||
proc getBlock(hash: BlockHash) {.async: (raises:[]).} =
|
||||
try:
|
||||
if blck =? (await subscriptions.client.eth_getBlockByHash(hash, false)):
|
||||
onBlock(blck)
|
||||
except CatchableError:
|
||||
onBlock(success(blck))
|
||||
except CancelledError:
|
||||
discard
|
||||
except CatchableError as e:
|
||||
let error = e.toErr(SubscriptionError, "HTTP polling: There was an exception while getting subscription's block: " & e.msg)
|
||||
onBlock(failure(Block, error))
|
||||
|
||||
proc callback(id: JsonNode, changeResult: ?!JsonNode) {.raises:[].} =
|
||||
without change =? changeResult, e:
|
||||
onBlock(failure(Block, e.toErr(SubscriptionError)))
|
||||
return
|
||||
|
||||
proc callback(id, change: JsonNode) =
|
||||
if hash =? BlockHash.fromJson(change):
|
||||
asyncSpawn getBlock(hash)
|
||||
|
||||
let id = await subscriptions.client.eth_newBlockFilter()
|
||||
subscriptions.callbacks[id] = callback
|
||||
subscriptions.subscriptionMapping[id] = id
|
||||
return id
|
||||
convertErrorsToSubscriptionError:
|
||||
let id = await subscriptions.client.eth_newBlockFilter()
|
||||
subscriptions.callbacks[id] = callback
|
||||
subscriptions.subscriptionMapping[id] = id
|
||||
return id
|
||||
|
||||
method subscribeLogs(subscriptions: PollingSubscriptions,
|
||||
filter: EventFilter,
|
||||
onLog: LogHandler):
|
||||
Future[JsonNode]
|
||||
{.async.} =
|
||||
{.async: (raises: [SubscriptionError, CancelledError]).} =
|
||||
|
||||
proc callback(id, change: JsonNode) =
|
||||
if log =? Log.fromJson(change):
|
||||
onLog(log)
|
||||
proc callback(id: JsonNode, argumentsResult: ?!JsonNode) =
|
||||
without arguments =? argumentsResult, error:
|
||||
onLog(failure(Log, error.toErr(SubscriptionError)))
|
||||
return
|
||||
|
||||
let id = await subscriptions.client.eth_newFilter(filter)
|
||||
subscriptions.callbacks[id] = callback
|
||||
subscriptions.logFilters[id] = filter
|
||||
subscriptions.subscriptionMapping[id] = id
|
||||
return id
|
||||
let res = Log.fromJson(arguments).mapFailure(SubscriptionError)
|
||||
onLog(res)
|
||||
|
||||
convertErrorsToSubscriptionError:
|
||||
let id = await subscriptions.client.eth_newFilter(filter)
|
||||
subscriptions.callbacks[id] = callback
|
||||
subscriptions.logFilters[id] = filter
|
||||
subscriptions.subscriptionMapping[id] = id
|
||||
return id
|
||||
|
||||
method unsubscribe*(subscriptions: PollingSubscriptions,
|
||||
id: JsonNode)
|
||||
{.async.} =
|
||||
subscriptions.logFilters.del(id)
|
||||
subscriptions.callbacks.del(id)
|
||||
let sub = subscriptions.subscriptionMapping[id]
|
||||
subscriptions.subscriptionMapping.del(id)
|
||||
{.async: (raises: [CancelledError]).} =
|
||||
try:
|
||||
discard await subscriptions.client.eth_uninstallFilter(sub)
|
||||
subscriptions.logFilters.del(id)
|
||||
subscriptions.callbacks.del(id)
|
||||
if sub =? subscriptions.subscriptionMapping.?[id]:
|
||||
subscriptions.subscriptionMapping.del(id)
|
||||
discard await subscriptions.client.eth_uninstallFilter(sub)
|
||||
except CancelledError as e:
|
||||
raise e
|
||||
except CatchableError:
|
||||
|
||||
@ -1,22 +1,26 @@
|
||||
import pkg/questionable
|
||||
import pkg/chronicles
|
||||
import ./basics
|
||||
import ./errors
|
||||
import ./provider
|
||||
|
||||
export basics
|
||||
export errors
|
||||
|
||||
{.push raises: [].}
|
||||
|
||||
type
|
||||
Signer* = ref object of RootObj
|
||||
populateLock: AsyncLock
|
||||
SignerError* = object of EthersError
|
||||
|
||||
template raiseSignerError(message: string, parent: ref ProviderError = nil) =
|
||||
template raiseSignerError*(message: string, parent: ref CatchableError = nil) =
|
||||
raise newException(SignerError, message, parent)
|
||||
|
||||
template convertError(body) =
|
||||
try:
|
||||
body
|
||||
except CancelledError as error:
|
||||
raise error
|
||||
except ProviderError as error:
|
||||
raise error # do not convert provider errors
|
||||
except CatchableError as error:
|
||||
@ -27,59 +31,66 @@ method provider*(
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method getAddress*(
|
||||
signer: Signer): Future[Address]
|
||||
{.base, async: (raises:[ProviderError, SignerError]).} =
|
||||
|
||||
signer: Signer
|
||||
): Future[Address] {.
|
||||
base, async: (raises: [ProviderError, SignerError, CancelledError])
|
||||
.} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method signMessage*(
|
||||
signer: Signer,
|
||||
message: seq[byte]): Future[seq[byte]]
|
||||
{.base, async: (raises: [SignerError]).} =
|
||||
|
||||
signer: Signer, message: seq[byte]
|
||||
): Future[seq[byte]] {.base, async: (raises: [SignerError, CancelledError]).} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method sendTransaction*(
|
||||
signer: Signer,
|
||||
transaction: Transaction): Future[TransactionResponse]
|
||||
{.base, async: (raises:[SignerError, ProviderError]).} =
|
||||
|
||||
signer: Signer, transaction: Transaction
|
||||
): Future[TransactionResponse] {.
|
||||
base, async: (raises: [SignerError, ProviderError, CancelledError])
|
||||
.} =
|
||||
doAssert false, "not implemented"
|
||||
|
||||
method getGasPrice*(
|
||||
signer: Signer): Future[UInt256]
|
||||
{.base, async: (raises: [ProviderError, SignerError]).} =
|
||||
|
||||
signer: Signer
|
||||
): Future[UInt256] {.
|
||||
base, async: (raises: [ProviderError, SignerError, CancelledError])
|
||||
.} =
|
||||
return await signer.provider.getGasPrice()
|
||||
|
||||
method getTransactionCount*(
|
||||
signer: Signer,
|
||||
blockTag = BlockTag.latest): Future[UInt256]
|
||||
{.base, async: (raises:[SignerError, ProviderError]).} =
|
||||
method getMaxPriorityFeePerGas*(
|
||||
signer: Signer
|
||||
): Future[UInt256] {.async: (raises: [SignerError, CancelledError]).} =
|
||||
return await signer.provider.getMaxPriorityFeePerGas()
|
||||
|
||||
method getTransactionCount*(
|
||||
signer: Signer, blockTag = BlockTag.latest
|
||||
): Future[UInt256] {.
|
||||
base, async: (raises: [SignerError, ProviderError, CancelledError])
|
||||
.} =
|
||||
convertError:
|
||||
let address = await signer.getAddress()
|
||||
return await signer.provider.getTransactionCount(address, blockTag)
|
||||
|
||||
method estimateGas*(
|
||||
signer: Signer,
|
||||
transaction: Transaction,
|
||||
blockTag = BlockTag.latest): Future[UInt256]
|
||||
{.base, async: (raises:[SignerError, ProviderError]).} =
|
||||
|
||||
signer: Signer, transaction: Transaction, blockTag = BlockTag.latest
|
||||
): Future[UInt256] {.
|
||||
base, async: (raises: [SignerError, ProviderError, CancelledError])
|
||||
.} =
|
||||
var transaction = transaction
|
||||
transaction.sender = some(await signer.getAddress())
|
||||
return await signer.provider.estimateGas(transaction, blockTag)
|
||||
|
||||
method getChainId*(
|
||||
signer: Signer): Future[UInt256]
|
||||
{.base, async: (raises: [ProviderError, SignerError]).} =
|
||||
|
||||
signer: Signer
|
||||
): Future[UInt256] {.
|
||||
base, async: (raises: [SignerError, ProviderError, CancelledError])
|
||||
.} =
|
||||
return await signer.provider.getChainId()
|
||||
|
||||
method getNonce(
|
||||
signer: Signer): Future[UInt256] {.base, async: (raises: [SignerError, ProviderError]).} =
|
||||
|
||||
signer: Signer
|
||||
): Future[UInt256] {.
|
||||
base, async: (raises: [SignerError, ProviderError, CancelledError])
|
||||
.} =
|
||||
return await signer.getTransactionCount(BlockTag.pending)
|
||||
|
||||
template withLock*(signer: Signer, body: untyped) =
|
||||
@ -90,7 +101,10 @@ template withLock*(signer: Signer, body: untyped) =
|
||||
try:
|
||||
body
|
||||
finally:
|
||||
signer.populateLock.release()
|
||||
try:
|
||||
signer.populateLock.release()
|
||||
except AsyncLockError as e:
|
||||
raiseSignerError e.msg, e
|
||||
|
||||
method populateTransaction*(
|
||||
signer: Signer,
|
||||
@ -116,8 +130,26 @@ method populateTransaction*(
|
||||
populated.sender = some(address)
|
||||
if transaction.chainId.isNone:
|
||||
populated.chainId = some(await signer.getChainId())
|
||||
if transaction.gasPrice.isNone and (transaction.maxFee.isNone or transaction.maxPriorityFee.isNone):
|
||||
populated.gasPrice = some(await signer.getGasPrice())
|
||||
|
||||
let blk = await signer.provider.getBlock(BlockTag.latest)
|
||||
|
||||
if baseFeePerGas =? blk.?baseFeePerGas:
|
||||
let maxPriorityFeePerGas = transaction.maxPriorityFeePerGas |? (await signer.provider.getMaxPriorityFeePerGas())
|
||||
populated.maxPriorityFeePerGas = some(maxPriorityFeePerGas)
|
||||
|
||||
# Multiply by 2 because during times of congestion, baseFeePerGas can increase by 12.5% per block.
|
||||
# https://github.com/ethers-io/ethers.js/discussions/3601#discussioncomment-4461273
|
||||
let maxFeePerGas = transaction.maxFeePerGas |? (baseFeePerGas * 2 + maxPriorityFeePerGas)
|
||||
populated.maxFeePerGas = some(maxFeePerGas)
|
||||
|
||||
populated.gasPrice = none(UInt256)
|
||||
|
||||
trace "EIP-1559 is supported", maxPriorityFeePerGas = maxPriorityFeePerGas, maxFeePerGas = maxFeePerGas
|
||||
else:
|
||||
populated.gasPrice = some(transaction.gasPrice |? (await signer.getGasPrice()))
|
||||
populated.maxFeePerGas = none(UInt256)
|
||||
populated.maxPriorityFeePerGas = none(UInt256)
|
||||
trace "EIP-1559 is not supported", gasPrice = populated.gasPrice
|
||||
|
||||
if transaction.nonce.isNone and transaction.gasLimit.isNone:
|
||||
# when both nonce and gasLimit are not populated, we must ensure getNonce is
|
||||
@ -146,7 +178,7 @@ method populateTransaction*(
|
||||
method cancelTransaction*(
|
||||
signer: Signer,
|
||||
tx: Transaction
|
||||
): Future[TransactionResponse] {.base, async: (raises: [SignerError, CancelledError, AsyncLockError, ProviderError]).} =
|
||||
): Future[TransactionResponse] {.base, async: (raises: [SignerError, CancelledError, ProviderError]).} =
|
||||
# cancels a transaction by sending with a 0-valued transaction to ourselves
|
||||
# with the failed tx's nonce
|
||||
|
||||
|
||||
@ -27,7 +27,7 @@ type Wallet* = ref object of Signer
|
||||
|
||||
proc new*(_: type Wallet, privateKey: PrivateKey): Wallet =
|
||||
let publicKey = privateKey.toPublicKey()
|
||||
let address = Address.init(publicKey.toCanonicalAddress())
|
||||
let address = Address(publicKey.toCanonicalAddress())
|
||||
Wallet(privateKey: privateKey, publicKey: publicKey, address: address)
|
||||
|
||||
proc new*(_: type Wallet, privateKey: PrivateKey, provider: Provider): Wallet =
|
||||
@ -53,13 +53,13 @@ proc createRandom*(_: type Wallet): Wallet =
|
||||
result = Wallet()
|
||||
result.privateKey = PrivateKey.random(getRng()[])
|
||||
result.publicKey = result.privateKey.toPublicKey()
|
||||
result.address = Address.init(result.publicKey.toCanonicalAddress())
|
||||
result.address = Address(result.publicKey.toCanonicalAddress())
|
||||
|
||||
proc createRandom*(_: type Wallet, provider: Provider): Wallet =
|
||||
result = Wallet()
|
||||
result.privateKey = PrivateKey.random(getRng()[])
|
||||
result.publicKey = result.privateKey.toPublicKey()
|
||||
result.address = Address.init(result.publicKey.toCanonicalAddress())
|
||||
result.address = Address(result.publicKey.toCanonicalAddress())
|
||||
result.provider = some provider
|
||||
|
||||
method provider*(wallet: Wallet): Provider {.gcsafe, raises: [SignerError].} =
|
||||
@ -69,7 +69,7 @@ method provider*(wallet: Wallet): Provider {.gcsafe, raises: [SignerError].} =
|
||||
|
||||
method getAddress*(
|
||||
wallet: Wallet): Future[Address]
|
||||
{.async: (raises:[ProviderError, SignerError]).} =
|
||||
{.async: (raises:[ProviderError, SignerError, CancelledError]).} =
|
||||
|
||||
return wallet.address
|
||||
|
||||
@ -83,7 +83,7 @@ proc signTransaction*(wallet: Wallet,
|
||||
method sendTransaction*(
|
||||
wallet: Wallet,
|
||||
transaction: Transaction): Future[TransactionResponse]
|
||||
{.async: (raises:[SignerError, ProviderError]).} =
|
||||
{.async: (raises:[SignerError, ProviderError, CancelledError]).} =
|
||||
|
||||
let signed = await signTransaction(wallet, transaction)
|
||||
return await provider(wallet).sendTransaction(signed)
|
||||
|
||||
@ -9,5 +9,7 @@ func raiseWalletError*(message: string) {.raises: [WalletError].}=
|
||||
template convertError*(body) =
|
||||
try:
|
||||
body
|
||||
except CancelledError as error:
|
||||
raise error
|
||||
except CatchableError as error:
|
||||
raiseWalletError(error.msg)
|
||||
|
||||
@ -1,11 +1,13 @@
|
||||
import pkg/eth/keys
|
||||
import pkg/eth/rlp
|
||||
import pkg/eth/common/transaction as eth
|
||||
import pkg/eth/common/transaction_utils
|
||||
import pkg/eth/common/eth_hash
|
||||
import ../../basics
|
||||
import ../../transaction as ethers
|
||||
import ../../provider
|
||||
import ./error
|
||||
from pkg/eth/common/eth_types import EthAddress
|
||||
|
||||
type
|
||||
Transaction = ethers.Transaction
|
||||
@ -24,17 +26,18 @@ func toSignableTransaction(transaction: Transaction): SignableTransaction =
|
||||
raiseWalletError "missing gas limit"
|
||||
|
||||
signable.nonce = nonce.truncate(uint64)
|
||||
signable.chainId = ChainId(chainId.truncate(uint64))
|
||||
signable.chainId = chainId
|
||||
signable.gasLimit = GasInt(gasLimit.truncate(uint64))
|
||||
signable.to = some EthAddress(transaction.to)
|
||||
|
||||
signable.to = Opt.some(EthAddress(transaction.to))
|
||||
signable.value = transaction.value
|
||||
signable.payload = transaction.data
|
||||
|
||||
if maxFee =? transaction.maxFee and
|
||||
maxPriorityFee =? transaction.maxPriorityFee:
|
||||
if maxFeePerGas =? transaction.maxFeePerGas and
|
||||
maxPriorityFeePerGas =? transaction.maxPriorityFeePerGas:
|
||||
signable.txType = TxEip1559
|
||||
signable.maxFee = GasInt(maxFee.truncate(uint64))
|
||||
signable.maxPriorityFee = GasInt(maxPriorityFee.truncate(uint64))
|
||||
signable.maxFeePerGas = GasInt(maxFeePerGas.truncate(uint64))
|
||||
signable.maxPriorityFeePerGas = GasInt(maxPriorityFeePerGas.truncate(uint64))
|
||||
elif gasPrice =? transaction.gasPrice:
|
||||
signable.txType = TxLegacy
|
||||
signable.gasPrice = GasInt(gasPrice.truncate(uint64))
|
||||
@ -45,21 +48,7 @@ func toSignableTransaction(transaction: Transaction): SignableTransaction =
|
||||
|
||||
func sign(key: PrivateKey, transaction: SignableTransaction): seq[byte] =
|
||||
var transaction = transaction
|
||||
|
||||
# Temporary V value, used to signal to the hashing function
|
||||
# that we'd like to use an EIP-155 signature
|
||||
transaction.V = int64(uint64(transaction.chainId)) * 2 + 35
|
||||
|
||||
let hash = transaction.txHashNoSignature().data
|
||||
let signature = key.sign(SkMessage(hash)).toRaw()
|
||||
|
||||
transaction.R = UInt256.fromBytesBE(signature[0..<32])
|
||||
transaction.S = UInt256.fromBytesBE(signature[32..<64])
|
||||
transaction.V = int64(signature[64])
|
||||
|
||||
if transaction.txType == TxLegacy:
|
||||
transaction.V += int64(uint64(transaction.chainId)) * 2 + 35
|
||||
|
||||
transaction.signature = transaction.sign(key, true)
|
||||
rlp.encode(transaction)
|
||||
|
||||
func sign*(key: PrivateKey, transaction: Transaction): seq[byte] =
|
||||
|
||||
@ -15,8 +15,8 @@ type
|
||||
nonce*: ?UInt256
|
||||
chainId*: ?UInt256
|
||||
gasPrice*: ?UInt256
|
||||
maxFee*: ?UInt256
|
||||
maxPriorityFee*: ?UInt256
|
||||
maxPriorityFeePerGas*: ?UInt256
|
||||
maxFeePerGas*: ?UInt256
|
||||
gasLimit*: ?UInt256
|
||||
transactionType* {.serialize("type").}: ?TransactionType
|
||||
|
||||
|
||||
@ -13,13 +13,13 @@ method provider*(signer: MockSigner): Provider =
|
||||
|
||||
method getAddress*(
|
||||
signer: MockSigner): Future[Address]
|
||||
{.async: (raises:[ProviderError, SignerError]).} =
|
||||
{.async: (raises:[ProviderError, SignerError, CancelledError]).} =
|
||||
|
||||
return signer.address
|
||||
|
||||
method sendTransaction*(
|
||||
signer: MockSigner,
|
||||
transaction: Transaction): Future[TransactionResponse]
|
||||
{.async: (raises:[SignerError, ProviderError]).} =
|
||||
{.async: (raises:[SignerError, ProviderError, CancelledError]).} =
|
||||
|
||||
signer.transactions.add(transaction)
|
||||
|
||||
@ -9,11 +9,12 @@ import pkg/json_rpc/errors
|
||||
|
||||
type MockRpcHttpServer* = ref object
|
||||
filters*: seq[string]
|
||||
nextGetChangesReturnsError*: bool
|
||||
srv: RpcHttpServer
|
||||
|
||||
proc new*(_: type MockRpcHttpServer): MockRpcHttpServer =
|
||||
let srv = newRpcHttpServer(["127.0.0.1:0"])
|
||||
MockRpcHttpServer(filters: @[], srv: srv)
|
||||
MockRpcHttpServer(filters: @[], srv: srv, nextGetChangesReturnsError: false)
|
||||
|
||||
proc invalidateFilter*(server: MockRpcHttpServer, jsonId: JsonNode) =
|
||||
server.filters.keepItIf it != jsonId.getStr
|
||||
@ -30,6 +31,9 @@ proc start*(server: MockRpcHttpServer) =
|
||||
return filterId
|
||||
|
||||
server.srv.router.rpc("eth_getFilterChanges") do(id: string) -> seq[string]:
|
||||
if server.nextGetChangesReturnsError:
|
||||
raise (ref ApplicationError)(code: -32000, msg: "unknown error")
|
||||
|
||||
if id notin server.filters:
|
||||
raise (ref ApplicationError)(code: -32000, msg: "filter not found")
|
||||
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import std/os
|
||||
import pkg/asynctest
|
||||
import pkg/asynctest/chronos/unittest
|
||||
import pkg/chronos
|
||||
import pkg/ethers
|
||||
import pkg/ethers/providers/jsonrpc/conversions
|
||||
@ -49,7 +49,7 @@ for url in ["ws://" & providerUrl, "http://" & providerUrl]:
|
||||
let oldBlock = !await provider.getBlock(BlockTag.latest)
|
||||
discard await provider.send("evm_mine")
|
||||
var newBlock: Block
|
||||
let blockHandler = proc(blck: Block) = newBlock = blck
|
||||
let blockHandler = proc(blck: ?!Block) {.raises:[].}= newBlock = blck.value
|
||||
let subscription = await provider.subscribe(blockHandler)
|
||||
discard await provider.send("evm_mine")
|
||||
check eventually newBlock.number.isSome
|
||||
@ -98,7 +98,7 @@ for url in ["ws://" & providerUrl, "http://" & providerUrl]:
|
||||
expect JsonRpcProviderError:
|
||||
discard await provider.getBlock(BlockTag.latest)
|
||||
expect JsonRpcProviderError:
|
||||
discard await provider.subscribe(proc(_: Block) = discard)
|
||||
discard await provider.subscribe(proc(_: ?!Block) = discard)
|
||||
expect JsonRpcProviderError:
|
||||
discard await provider.getSigner().sendTransaction(Transaction.example)
|
||||
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import std/os
|
||||
import pkg/asynctest
|
||||
import pkg/asynctest/chronos/unittest
|
||||
import pkg/ethers
|
||||
import pkg/stew/byteutils
|
||||
import ../../examples
|
||||
@ -55,20 +55,27 @@ suite "JsonRpcSigner":
|
||||
let transaction = Transaction.example
|
||||
let populated = await signer.populateTransaction(transaction)
|
||||
check !populated.sender == await signer.getAddress()
|
||||
check !populated.gasPrice == await signer.getGasPrice()
|
||||
check !populated.nonce == await signer.getTransactionCount(BlockTag.pending)
|
||||
check !populated.gasLimit == await signer.estimateGas(transaction)
|
||||
check !populated.chainId == await signer.getChainId()
|
||||
|
||||
let blk = !(await signer.provider.getBlock(BlockTag.latest))
|
||||
check !populated.maxPriorityFeePerGas == await signer.getMaxPriorityFeePerGas()
|
||||
check !populated.maxFeePerGas == !blk.baseFeePerGas * 2.u256 + !populated.maxPriorityFeePerGas
|
||||
|
||||
test "populate does not overwrite existing fields":
|
||||
let signer = provider.getSigner()
|
||||
var transaction = Transaction.example
|
||||
transaction.sender = some await signer.getAddress()
|
||||
transaction.nonce = some UInt256.example
|
||||
transaction.chainId = some await signer.getChainId()
|
||||
transaction.gasPrice = some UInt256.example
|
||||
transaction.maxPriorityFeePerGas = some UInt256.example
|
||||
transaction.gasLimit = some UInt256.example
|
||||
let populated = await signer.populateTransaction(transaction)
|
||||
|
||||
let blk = !(await signer.provider.getBlock(BlockTag.latest))
|
||||
transaction.maxFeePerGas = some(!blk.baseFeePerGas * 2.u256 + !populated.maxPriorityFeePerGas)
|
||||
|
||||
check populated == transaction
|
||||
|
||||
test "populate fails when sender does not match signer address":
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
import std/os
|
||||
import std/sequtils
|
||||
import std/importutils
|
||||
import pkg/asynctest
|
||||
import pkg/asynctest/chronos/unittest
|
||||
import pkg/serde
|
||||
import pkg/json_rpc/rpcclient
|
||||
import pkg/json_rpc/rpcserver
|
||||
@ -27,8 +26,8 @@ template subscriptionTests(subscriptions, client) =
|
||||
|
||||
test "subscribes to new blocks":
|
||||
var latestBlock: Block
|
||||
proc callback(blck: Block) =
|
||||
latestBlock = blck
|
||||
proc callback(blck: ?!Block) =
|
||||
latestBlock = blck.value
|
||||
let subscription = await subscriptions.subscribeBlocks(callback)
|
||||
discard await client.call("evm_mine", newJArray())
|
||||
check eventually latestBlock.number.isSome
|
||||
@ -38,8 +37,9 @@ template subscriptionTests(subscriptions, client) =
|
||||
|
||||
test "stops listening to new blocks when unsubscribed":
|
||||
var count = 0
|
||||
proc callback(blck: Block) =
|
||||
inc count
|
||||
proc callback(blck: ?!Block) =
|
||||
if blck.isOk:
|
||||
inc count
|
||||
let subscription = await subscriptions.subscribeBlocks(callback)
|
||||
discard await client.call("evm_mine", newJArray())
|
||||
check eventually count > 0
|
||||
@ -49,10 +49,20 @@ template subscriptionTests(subscriptions, client) =
|
||||
await sleepAsync(100.millis)
|
||||
check count == 0
|
||||
|
||||
test "unsubscribing from a non-existent subscription does not do any harm":
|
||||
await subscriptions.unsubscribe(newJInt(0))
|
||||
|
||||
test "duplicate unsubscribe is harmless":
|
||||
proc callback(blck: ?!Block) = discard
|
||||
let subscription = await subscriptions.subscribeBlocks(callback)
|
||||
await subscriptions.unsubscribe(subscription)
|
||||
await subscriptions.unsubscribe(subscription)
|
||||
|
||||
test "stops listening to new blocks when provider is closed":
|
||||
var count = 0
|
||||
proc callback(blck: Block) =
|
||||
inc count
|
||||
proc callback(blck: ?!Block) =
|
||||
if blck.isOk:
|
||||
inc count
|
||||
discard await subscriptions.subscribeBlocks(callback)
|
||||
discard await client.call("evm_mine", newJArray())
|
||||
check eventually count > 0
|
||||
@ -97,13 +107,14 @@ suite "HTTP polling subscriptions":
|
||||
|
||||
subscriptionTests(subscriptions, client)
|
||||
|
||||
suite "HTTP polling subscriptions - filter not found":
|
||||
suite "HTTP polling subscriptions - mock tests":
|
||||
|
||||
var subscriptions: PollingSubscriptions
|
||||
var client: RpcHttpClient
|
||||
var mockServer: MockRpcHttpServer
|
||||
|
||||
privateAccess(PollingSubscriptions)
|
||||
privateAccess(JsonRpcSubscriptions)
|
||||
|
||||
proc startServer() {.async.} =
|
||||
mockServer = MockRpcHttpServer.new()
|
||||
@ -130,7 +141,7 @@ suite "HTTP polling subscriptions - filter not found":
|
||||
|
||||
test "filter not found error recreates log filter":
|
||||
let filter = EventFilter(address: Address.example, topics: @[array[32, byte].example])
|
||||
let emptyHandler = proc(log: Log) = discard
|
||||
let emptyHandler = proc(log: ?!Log) = discard
|
||||
|
||||
check subscriptions.logFilters.len == 0
|
||||
check subscriptions.subscriptionMapping.len == 0
|
||||
@ -148,7 +159,7 @@ suite "HTTP polling subscriptions - filter not found":
|
||||
|
||||
test "recreated log filter can be still unsubscribed using the original id":
|
||||
let filter = EventFilter(address: Address.example, topics: @[array[32, byte].example])
|
||||
let emptyHandler = proc(log: Log) = discard
|
||||
let emptyHandler = proc(log: ?!Log) = discard
|
||||
let id = await subscriptions.subscribeLogs(filter, emptyHandler)
|
||||
mockServer.invalidateFilter(id)
|
||||
check eventually subscriptions.subscriptionMapping[id] != id
|
||||
@ -159,7 +170,7 @@ suite "HTTP polling subscriptions - filter not found":
|
||||
check not subscriptions.subscriptionMapping.hasKey id
|
||||
|
||||
test "filter not found error recreates block filter":
|
||||
let emptyHandler = proc(blck: Block) = discard
|
||||
let emptyHandler = proc(blck: ?!Block) = discard
|
||||
|
||||
check subscriptions.subscriptionMapping.len == 0
|
||||
let id = await subscriptions.subscribeBlocks(emptyHandler)
|
||||
@ -170,7 +181,7 @@ suite "HTTP polling subscriptions - filter not found":
|
||||
check eventually subscriptions.subscriptionMapping[id] != id
|
||||
|
||||
test "recreated block filter can be still unsubscribed using the original id":
|
||||
let emptyHandler = proc(blck: Block) = discard
|
||||
let emptyHandler = proc(blck: ?!Block) = discard
|
||||
let id = await subscriptions.subscribeBlocks(emptyHandler)
|
||||
mockServer.invalidateFilter(id)
|
||||
check eventually subscriptions.subscriptionMapping[id] != id
|
||||
@ -181,7 +192,7 @@ suite "HTTP polling subscriptions - filter not found":
|
||||
|
||||
test "polling continues with new filter after temporary error":
|
||||
let filter = EventFilter(address: Address.example, topics: @[array[32, byte].example])
|
||||
let emptyHandler = proc(log: Log) = discard
|
||||
let emptyHandler = proc(log: ?!Log) = discard
|
||||
|
||||
let id = await subscriptions.subscribeLogs(filter, emptyHandler)
|
||||
|
||||
@ -191,3 +202,17 @@ suite "HTTP polling subscriptions - filter not found":
|
||||
await startServer()
|
||||
|
||||
check eventually subscriptions.subscriptionMapping[id] != id
|
||||
|
||||
test "calls callback with failed result on error":
|
||||
let filter = EventFilter(address: Address.example, topics: @[array[32, byte].example])
|
||||
var failedResultReceived = false
|
||||
|
||||
proc handler(log: ?!Log) =
|
||||
if log.isErr:
|
||||
failedResultReceived = true
|
||||
|
||||
let id = await subscriptions.subscribeLogs(filter, handler)
|
||||
|
||||
await sleepAsync(50.milliseconds)
|
||||
mockServer.nextGetChangesReturnsError = true
|
||||
check eventually failedResultReceived
|
||||
|
||||
56
testmodule/providers/jsonrpc/testWsResubscription.nim
Normal file
56
testmodule/providers/jsonrpc/testWsResubscription.nim
Normal file
@ -0,0 +1,56 @@
|
||||
import std/os
|
||||
import std/importutils
|
||||
import pkg/asynctest/chronos/unittest
|
||||
import pkg/json_rpc/rpcclient
|
||||
import ethers/provider
|
||||
import ethers/providers/jsonrpc/subscriptions
|
||||
|
||||
import ../../examples
|
||||
|
||||
suite "Websocket re-subscriptions":
|
||||
privateAccess(JsonRpcSubscriptions)
|
||||
|
||||
var subscriptions: JsonRpcSubscriptions
|
||||
var client: RpcWebSocketClient
|
||||
var resubscribeInterval: int
|
||||
|
||||
setup:
|
||||
resubscribeInterval = 3
|
||||
client = newRpcWebSocketClient()
|
||||
await client.connect("ws://" & getEnv("ETHERS_TEST_PROVIDER", "localhost:8545"))
|
||||
subscriptions = JsonRpcSubscriptions.new(client, resubscribeInterval = resubscribeInterval)
|
||||
subscriptions.start()
|
||||
|
||||
teardown:
|
||||
await subscriptions.close()
|
||||
await client.close()
|
||||
|
||||
test "unsubscribing from a log filter while subscriptions are being resubscribed does not cause a concurrency error":
|
||||
let filter = EventFilter(address: Address.example, topics: @[array[32, byte].example])
|
||||
let emptyHandler = proc(log: ?!Log) = discard
|
||||
|
||||
for i in 1..10:
|
||||
discard await subscriptions.subscribeLogs(filter, emptyHandler)
|
||||
|
||||
# Wait until the re-subscription starts
|
||||
await sleepAsync(resubscribeInterval.seconds)
|
||||
|
||||
# Attempt to modify callbacks while its being iterated
|
||||
discard await subscriptions.subscribeLogs(filter, emptyHandler)
|
||||
|
||||
test "resubscribe events take effect with new subscription IDs in the log filters":
|
||||
let filter = EventFilter(address: Address.example, topics: @[array[32, byte].example])
|
||||
let emptyHandler = proc(log: ?!Log) = discard
|
||||
let id = await subscriptions.subscribeLogs(filter, emptyHandler)
|
||||
|
||||
check id in subscriptions.logFilters
|
||||
check subscriptions.logFilters.len == 1
|
||||
|
||||
# Make sure the subscription is done
|
||||
await sleepAsync((resubscribeInterval + 1).seconds)
|
||||
|
||||
# The previous subscription should not be in the log filters
|
||||
check id notin subscriptions.logFilters
|
||||
|
||||
# There is still one subscription which is the new one
|
||||
check subscriptions.logFilters.len == 1
|
||||
@ -1,6 +1,7 @@
|
||||
import ./jsonrpc/testJsonRpcProvider
|
||||
import ./jsonrpc/testJsonRpcSigner
|
||||
import ./jsonrpc/testJsonRpcSubscriptions
|
||||
import ./jsonrpc/testWsResubscription
|
||||
import ./jsonrpc/testConversions
|
||||
import ./jsonrpc/testErrors
|
||||
|
||||
|
||||
@ -9,5 +9,6 @@ import ./testErc20
|
||||
import ./testGasEstimation
|
||||
import ./testErrorDecoding
|
||||
import ./testCustomErrors
|
||||
import ./testBlockTag
|
||||
|
||||
{.warning[UnusedImport]:off.}
|
||||
|
||||
@ -3,7 +3,7 @@ author = "Nim Ethers Authors"
|
||||
description = "Tests for Nim Ethers library"
|
||||
license = "MIT"
|
||||
|
||||
requires "asynctest >= 0.4.0 & < 0.5.0"
|
||||
requires "asynctest >= 0.5.4 & < 0.6.0"
|
||||
|
||||
task test, "Run the test suite":
|
||||
exec "nimble install -d -y"
|
||||
|
||||
56
testmodule/testBlockTag.nim
Normal file
56
testmodule/testBlockTag.nim
Normal file
@ -0,0 +1,56 @@
|
||||
import std/unittest
|
||||
import std/strformat
|
||||
|
||||
import pkg/stint
|
||||
import pkg/questionable
|
||||
|
||||
import ethers/blocktag
|
||||
|
||||
|
||||
type
|
||||
PredefinedTags = enum earliest, latest, pending
|
||||
|
||||
suite "BlockTag":
|
||||
for predefinedTag in PredefinedTags:
|
||||
test fmt"can be created with predefined special type: {predefinedTag}":
|
||||
var blockTag: BlockTag
|
||||
case predefinedTag:
|
||||
of earliest: blockTag = BlockTag.earliest
|
||||
of latest: blockTag = BlockTag.latest
|
||||
of pending: blockTag = BlockTag.pending
|
||||
check $blockTag == $predefinedTag
|
||||
|
||||
test "can be created with a number":
|
||||
let blockTag = BlockTag.init(42.u256)
|
||||
check blockTag.number == 42.u256.some
|
||||
|
||||
test "can be converted to string in hex format for BlockTags with number":
|
||||
let blockTag = BlockTag.init(42.u256)
|
||||
check $blockTag == "0x2a"
|
||||
|
||||
test "can be compared for equality when BlockTag with number":
|
||||
let blockTag1 = BlockTag.init(42.u256)
|
||||
let blockTag2 = BlockTag.init(42.u256)
|
||||
let blockTag3 = BlockTag.init(43.u256)
|
||||
check blockTag1 == blockTag2
|
||||
check blockTag1 != blockTag3
|
||||
|
||||
for predefinedTag in [BlockTag.earliest, BlockTag.latest, BlockTag.pending]:
|
||||
test fmt"can be compared for equality when predefined tag: {predefinedTag}":
|
||||
case $predefinedTag:
|
||||
of "earliest":
|
||||
check predefinedTag == BlockTag.earliest
|
||||
check predefinedTag != BlockTag.latest
|
||||
check predefinedTag != BlockTag.pending
|
||||
of "latest":
|
||||
check predefinedTag != BlockTag.earliest
|
||||
check predefinedTag == BlockTag.latest
|
||||
check predefinedTag != BlockTag.pending
|
||||
of "pending":
|
||||
check predefinedTag != BlockTag.earliest
|
||||
check predefinedTag != BlockTag.latest
|
||||
check predefinedTag == BlockTag.pending
|
||||
|
||||
for predefinedTag in [BlockTag.earliest, BlockTag.latest, BlockTag.pending]:
|
||||
test fmt"number accessor returns None for BlockTags with string: {predefinedTag}":
|
||||
check predefinedTag.number == UInt256.none
|
||||
@ -1,7 +1,7 @@
|
||||
import pkg/serde
|
||||
import std/os
|
||||
import std/options
|
||||
import pkg/asynctest
|
||||
import pkg/asynctest/chronos/unittest
|
||||
import pkg/questionable
|
||||
import pkg/stint
|
||||
import pkg/ethers
|
||||
@ -64,7 +64,7 @@ for url in ["ws://" & providerUrl, "http://" & providerUrl]:
|
||||
test "can call constant functions without a return type":
|
||||
token = TestToken.new(token.address, provider.getSigner())
|
||||
proc mint(token: TestToken, holder: Address, amount: UInt256) {.contract, view.}
|
||||
await mint(token, accounts[1], 100.u256)
|
||||
await token.mint(accounts[1], 100.u256)
|
||||
check (await balanceOf(token, accounts[1])) == 0.u256
|
||||
|
||||
test "can call non-constant functions without a return type":
|
||||
@ -74,7 +74,6 @@ for url in ["ws://" & providerUrl, "http://" & providerUrl]:
|
||||
check (await balanceOf(token, accounts[1])) == 100.u256
|
||||
|
||||
test "can call non-constant functions with a Confirmable return type":
|
||||
|
||||
token = TestToken.new(token.address, provider.getSigner())
|
||||
proc mint(token: TestToken,
|
||||
holder: Address,
|
||||
@ -108,17 +107,17 @@ for url in ["ws://" & providerUrl, "http://" & providerUrl]:
|
||||
check (await token.connect(provider).balanceOf(accounts[1])) == 25.u256
|
||||
check (await token.connect(provider).balanceOf(accounts[2])) == 25.u256
|
||||
|
||||
test "takes custom values for nonce, gasprice and gaslimit":
|
||||
test "takes custom values for nonce, gasprice and maxPriorityFeePerGas":
|
||||
let overrides = TransactionOverrides(
|
||||
nonce: some 100.u256,
|
||||
gasPrice: some 200.u256,
|
||||
maxPriorityFeePerGas: some 200.u256,
|
||||
gasLimit: some 300.u256
|
||||
)
|
||||
let signer = MockSigner.new(provider)
|
||||
discard await token.connect(signer).mint(accounts[0], 42.u256, overrides)
|
||||
check signer.transactions.len == 1
|
||||
check signer.transactions[0].nonce == overrides.nonce
|
||||
check signer.transactions[0].gasPrice == overrides.gasPrice
|
||||
check signer.transactions[0].maxPriorityFeePerGas == overrides.maxPriorityFeePerGas
|
||||
check signer.transactions[0].gasLimit == overrides.gasLimit
|
||||
|
||||
test "can call functions for different block heights":
|
||||
@ -146,10 +145,22 @@ for url in ["ws://" & providerUrl, "http://" & providerUrl]:
|
||||
discard await token.transfer(accounts[1], 50.u256, beforeMint)
|
||||
discard await token.transfer(accounts[1], 50.u256, afterMint)
|
||||
|
||||
test "can estimate gas of a function call":
|
||||
proc mint(token: TestToken, holder: Address, amount: UInt256) {.contract.}
|
||||
let estimate = await token.estimateGas.mint(accounts[1], 100.u256)
|
||||
let correctGas = TransactionOverrides(gasLimit: some estimate)
|
||||
await token.mint(accounts[1], 100.u256, correctGas)
|
||||
let invalidGas = TransactionOverrides(gasLimit: some (estimate - 1))
|
||||
expect ProviderError:
|
||||
await token.mint(accounts[1], 100.u256, invalidGas)
|
||||
|
||||
test "receives events when subscribed":
|
||||
var transfers: seq[Transfer]
|
||||
|
||||
proc handleTransfer(transfer: Transfer) =
|
||||
proc handleTransfer(transferRes: ?!Transfer) =
|
||||
without transfer =? transferRes, error:
|
||||
echo error.msg
|
||||
|
||||
transfers.add(transfer)
|
||||
|
||||
let signer0 = provider.getSigner(accounts[0])
|
||||
@ -171,8 +182,9 @@ for url in ["ws://" & providerUrl, "http://" & providerUrl]:
|
||||
test "stops receiving events when unsubscribed":
|
||||
var transfers: seq[Transfer]
|
||||
|
||||
proc handleTransfer(transfer: Transfer) =
|
||||
transfers.add(transfer)
|
||||
proc handleTransfer(transferRes: ?!Transfer) =
|
||||
if transfer =? transferRes:
|
||||
transfers.add(transfer)
|
||||
|
||||
let signer0 = provider.getSigner(accounts[0])
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import std/os
|
||||
import pkg/serde
|
||||
import pkg/asynctest
|
||||
import pkg/asynctest/chronos/unittest
|
||||
import pkg/ethers
|
||||
import ./hardhat
|
||||
|
||||
@ -97,7 +97,7 @@ suite "Contract custom errors":
|
||||
expect ErrorWithArguments:
|
||||
await contract.revertsMultipleErrors(simple = false)
|
||||
|
||||
test "handles gas estimation errors":
|
||||
test "handles gas estimation errors when calling a contract function":
|
||||
proc revertsTransaction(contract: TestCustomErrors)
|
||||
{.contract, errors:[ErrorWithArguments].}
|
||||
|
||||
@ -109,6 +109,18 @@ suite "Contract custom errors":
|
||||
check error.arguments.one == 1.u256
|
||||
check error.arguments.two == true
|
||||
|
||||
test "handles errors when only doing gas estimation":
|
||||
proc revertsTransaction(contract: TestCustomErrors)
|
||||
{.contract, errors:[ErrorWithArguments], used.}
|
||||
|
||||
let contract = contract.connect(provider.getSigner())
|
||||
try:
|
||||
discard await contract.estimateGas.revertsTransaction()
|
||||
fail()
|
||||
except ErrorWithArguments as error:
|
||||
check error.arguments.one == 1.u256
|
||||
check error.arguments.two == true
|
||||
|
||||
test "handles transaction submission errors":
|
||||
proc revertsTransaction(contract: TestCustomErrors)
|
||||
{.contract, errors:[ErrorWithArguments].}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import std/os
|
||||
import pkg/asynctest
|
||||
import pkg/asynctest/chronos/unittest
|
||||
import pkg/ethers
|
||||
import pkg/serde
|
||||
import ./hardhat
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import std/os
|
||||
import pkg/serde
|
||||
import pkg/asynctest
|
||||
import pkg/asynctest/chronos/unittest
|
||||
import pkg/questionable
|
||||
import pkg/stint
|
||||
import pkg/ethers
|
||||
|
||||
@ -3,7 +3,7 @@ import std/strutils
|
||||
import pkg/questionable/results
|
||||
import pkg/contractabi
|
||||
import pkg/ethers/errors
|
||||
import pkg/ethers/errors/encoding
|
||||
import pkg/ethers/contracts/errors/encoding
|
||||
|
||||
suite "Decoding of custom errors":
|
||||
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import pkg/asynctest
|
||||
import pkg/asynctest/chronos/unittest
|
||||
import pkg/ethers
|
||||
import pkg/contractabi
|
||||
import ./examples
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import std/os
|
||||
import pkg/asynctest
|
||||
import pkg/asynctest/chronos/unittest
|
||||
import pkg/ethers
|
||||
import pkg/serde
|
||||
import ./hardhat
|
||||
@ -28,7 +28,7 @@ suite "gas estimation":
|
||||
discard await provider.send("evm_revert", @[snapshot])
|
||||
await provider.close()
|
||||
|
||||
test "uses pending block for gas estimations":
|
||||
test "contract function calls use pending block for gas estimations":
|
||||
let latest = CallOverrides(blockTag: some BlockTag.latest)
|
||||
let pending = CallOverrides(blockTag: some BlockTag.pending)
|
||||
|
||||
@ -38,6 +38,40 @@ suite "gas estimation":
|
||||
# ensure that time of latest block and pending block differ
|
||||
check (await contract.getTime(overrides=latest)) != time
|
||||
|
||||
# fails with "Transaction ran out of gas" when gas estimation
|
||||
# is not done using the pending block
|
||||
# only succeeds when gas estimation is done using the pending block,
|
||||
# otherwise it will fail with "Transaction ran out of gas"
|
||||
await contract.checkTimeEquals(time)
|
||||
|
||||
test "contract gas estimation uses pending block":
|
||||
let latest = CallOverrides(blockTag: some BlockTag.latest)
|
||||
let pending = CallOverrides(blockTag: some BlockTag.pending)
|
||||
|
||||
# retrieve time of pending block
|
||||
let time = await contract.getTime(overrides=pending)
|
||||
|
||||
# ensure that time of latest block and pending block differ
|
||||
check (await contract.getTime(overrides=latest)) != time
|
||||
|
||||
# estimate gas
|
||||
let gas = await contract.estimateGas.checkTimeEquals(time)
|
||||
let overrides = TransactionOverrides(gasLimit: some gas)
|
||||
|
||||
# only succeeds when gas estimation is done using the pending block,
|
||||
# otherwise it will fail with "Transaction ran out of gas"
|
||||
await contract.checkTimeEquals(time, overrides)
|
||||
|
||||
test "contract gas estimation honors a block tag override":
|
||||
let latest = CallOverrides(blockTag: some BlockTag.latest)
|
||||
let pending = CallOverrides(blockTag: some BlockTag.pending)
|
||||
|
||||
# retrieve time of pending block
|
||||
let time = await contract.getTime(overrides=pending)
|
||||
|
||||
# ensure that time of latest block and pending block differ
|
||||
check (await contract.getTime(overrides=latest)) != time
|
||||
|
||||
# estimate gas
|
||||
let gasLatest = await contract.estimateGas.checkTimeEquals(time, latest)
|
||||
let gasPending = await contract.estimateGas.checkTimeEquals(time, pending)
|
||||
|
||||
check gasLatest != gasPending
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import std/os
|
||||
import pkg/asynctest
|
||||
import pkg/asynctest/chronos/unittest
|
||||
import pkg/ethers
|
||||
import pkg/serde
|
||||
import ./hardhat
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import std/os
|
||||
import std/strformat
|
||||
import pkg/asynctest
|
||||
import pkg/asynctest/chronos/unittest
|
||||
import pkg/chronos
|
||||
import pkg/ethers
|
||||
import pkg/ethers/testing
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import std/os
|
||||
import pkg/asynctest
|
||||
import pkg/asynctest/chronos/unittest
|
||||
import pkg/serde
|
||||
import pkg/stew/byteutils
|
||||
import ../ethers
|
||||
@ -80,8 +80,8 @@ suite "Wallet":
|
||||
to: wallet.address,
|
||||
nonce: some 0.u256,
|
||||
chainId: some 31337.u256,
|
||||
maxFee: some 2_000_000_000.u256,
|
||||
maxPriorityFee: some 1_000_000_000.u256,
|
||||
maxFeePerGas: some 2_000_000_000.u256,
|
||||
maxPriorityFeePerGas: some 1_000_000_000.u256,
|
||||
gasLimit: some 21_000.u256
|
||||
)
|
||||
let signedTx = await wallet.signTransaction(tx)
|
||||
@ -115,8 +115,8 @@ suite "Wallet":
|
||||
let wallet = !Wallet.new(pk_with_funds, provider)
|
||||
let overrides = TransactionOverrides(
|
||||
nonce: some 0.u256,
|
||||
maxFee: some 1_000_000_000.u256,
|
||||
maxPriorityFee: some 1_000_000_000.u256,
|
||||
maxFeePerGas: some 1_000_000_000.u256,
|
||||
maxPriorityFeePerGas: some 1_000_000_000.u256,
|
||||
gasLimit: some 22_000.u256)
|
||||
let testToken = Erc20.new(wallet.address, wallet)
|
||||
await testToken.transfer(wallet.address, 24.u256, overrides)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user