forked from ExWeb3/elixir_ethers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathethers.ex
807 lines (645 loc) · 27 KB
/
ethers.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
defmodule Ethers do
@moduledoc """
high-level module providing a convenient and efficient interface for interacting
with the Ethereum blockchain using Elixir.
This module offers a simple API for common Ethereum operations such as deploying contracts,
fetching current gas prices, and querying event logs.
## Batching Requests
Often you would find yourself executing different actions without dependency. These actions can
be combined together in one JSON RPC call. This will save on the number of round trips and
improves latency.
Before continuing, please note that batching JSON RPC requests and using `Ethers.Multicall` are
two different things. As a rule of thumb:
- Use `Ethers.Multicall` if you need to make multiple contract calls and get the result
*on the same block*.
- Use `Ethers.batch/2` if you need to make multiple JSON RPC operations which may or may not run
on the same block (or even be related to any specific block e.g. eth_gas_price)
### Make batch requests
`Ethers.batch/2` supports all operations which the RPC module (`Ethereumex` by default)
implements. Although some actions support pre and post processing and some are just forwarded
to the RPC module.
Every request passed to `Ethers.batch/2` can be in one of the following formats
- `action_name_atom`: This only works with requests which do not require any additional data.
e.g. `:current_gas_price` or `:net_version`.
- `{action_name_atom, data}`: This works with all other actions which accept input data.
e.g. `:call`, `:send` or `:get_logs`.
- `{action_name_atom, data, overrides_keyword_list}`: Use this to override or add attributes
to the action data. This is only accepted for these actions and will through error on others.
- `:call`: data should be a Ethers.TxData struct and overrides are accepted.
- `:estimate_gas`: data should be a Ethers.TxData struct or a map and overrides are accepted.
- `:get_logs`: data should be a Ethers.EventFilter struct and overrides are accepted.
- `:send`: data should be a Ethers.TxData struct and overrides are accepted.
### Example
```elixir
Ethers.batch([
:current_block_number,
:current_gas_price,
{:call, Ethers.Contracts.ERC20.name(), to: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"},
{:send, MyContract.ping(), from: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"},
{:get_logs, Ethers.Contracts.ERC20.EventFilters.approval(nil, nil)} # <- can have add overrides
])
{:ok, [
{:ok, 18539069},
{:ok, 21221},
{:ok, "Wrapped Ether"},
{:ok, "0xed67b1aafdc823077166c8ee9da13c6a621d19f4d7a24a80353219c09bdac87f"},
{:ok, [%Ethers.EventFilter{}]}
]}
```
"""
alias Ethers.Event
alias Ethers.EventFilter
alias Ethers.ExecutionError
alias Ethers.Transaction
alias Ethers.TxData
alias Ethers.Types
alias Ethers.Utils
@option_keys [:rpc_client, :rpc_opts, :signer, :signer_opts, :tx_type]
@hex_decode_post_process [
:estimate_gas,
:current_gas_price,
:current_block_number,
:get_balance
]
@rpc_actions_map %{
call: :eth_call,
chain_id: :eth_chain_id,
current_block_number: :eth_block_number,
current_gas_price: :eth_gas_price,
estimate_gas: :eth_estimate_gas,
gas_price: :eth_gas_price,
get_logs: :eth_get_logs,
get_transaction_count: :eth_get_transaction_count,
get_transaction: :eth_get_transaction_by_hash,
send: :eth_send_transaction
}
@type t_batch_request :: atom() | {atom, term()} | {atom, term(), Keyword.t()}
defguardp valid_result(bin) when bin != "0x"
@doc """
Returns the current gas price from the RPC API
"""
@spec current_gas_price(Keyword.t()) :: {:ok, non_neg_integer()}
def current_gas_price(opts \\ []) do
{rpc_client, rpc_opts} = get_rpc_client(opts)
rpc_client.eth_gas_price(rpc_opts)
|> post_process(nil, :current_gas_price)
end
@doc """
Returns the current block number of the blockchain.
"""
@spec current_block_number(Keyword.t()) :: {:ok, non_neg_integer()} | {:error, term()}
def current_block_number(opts \\ []) do
{rpc_client, rpc_opts} = get_rpc_client(opts)
rpc_client.eth_block_number(rpc_opts)
|> post_process(nil, :current_block_number)
end
@doc """
Returns the native token (ETH) balance of an account in wei.
## Parameters
- account: Account which the balance is queried for.
- overrides:
- block: The block you want to query the balance of account in (defaults to `latest`).
- rpc_client: The RPC module to use for this request (overrides default).
- rpc_opts: Specific RPC options to specify for this request.
"""
@spec get_balance(Types.t_address(), Keyword.t()) ::
{:ok, non_neg_integer()} | {:error, term()}
def get_balance(account, overrides \\ []) do
{opts, overrides} = Keyword.split(overrides, @option_keys)
{rpc_client, rpc_opts} = get_rpc_client(opts)
with {:ok, account, block} <- pre_process(account, overrides, :get_balance, opts) do
rpc_client.eth_get_balance(account, block, rpc_opts)
|> post_process(nil, :get_balance)
end
end
@doc """
Returns the native transaction (ETH) by transaction hash.
## Parameters
- tx_hash: Transaction hash which the transaction is queried for.
- overrides:
- rpc_client: The RPC module to use for this request (overrides default).
- rpc_opts: Specific RPC options to specify for this request.
"""
@spec get_transaction(Types.t_hash(), Keyword.t()) ::
{:ok, Transaction.t()} | {:error, term()}
def get_transaction(tx_hash, opts \\ []) when is_binary(tx_hash) do
{rpc_client, rpc_opts} = get_rpc_client(opts)
rpc_client.eth_get_transaction_by_hash(tx_hash, rpc_opts)
|> post_process(nil, :get_transaction)
end
@doc """
Returns the receipt of a transaction by it's hash.
## Parameters
- tx_hash: Transaction hash which the transaction receipt is queried for.
- overrides:
- rpc_client: The RPC module to use for this request (overrides default).
- rpc_opts: Specific RPC options to specify for this request.
"""
@spec get_transaction_receipt(Types.t_hash(), Keyword.t()) ::
{:ok, map()} | {:error, term()}
def get_transaction_receipt(tx_hash, opts \\ []) when is_binary(tx_hash) do
{rpc_client, rpc_opts} = get_rpc_client(opts)
rpc_client.eth_get_transaction_receipt(tx_hash, rpc_opts)
|> post_process(nil, :get_transaction_receipt)
end
@doc """
Deploys a contract to the blockchain.
This will return the transaction hash for the deployment transaction.
To get the address of your deployed contract, use `Ethers.deployed_address/2`.
To deploy a cotract you must have the binary related to it. It can either be a part of the ABI
File you have or as a separate file.
## Parameters
- contract_module_or_binary: Either the contract module which was already loaded or the compiled
binary of the contract. The binary MUST be hex encoded.
- overrides: A keyword list containing options and overrides.
- `:encoded_constructor`: Hex encoded value for constructor parameters. (See `constructor`
function of the contract module)
- All other options from `Ethers.send/2`
"""
@spec deploy(atom() | binary(), Keyword.t()) ::
{:ok, Types.t_hash()} | {:error, term()}
def deploy(contract_module_or_binary, overrides \\ [])
def deploy(contract_module, overrides) when is_atom(contract_module) do
with true <- function_exported?(contract_module, :__contract_binary__, 0),
bin when not is_nil(bin) <- contract_module.__contract_binary__() do
deploy(bin, overrides)
else
_error ->
{:error, :binary_not_found}
end
end
def deploy("0x" <> contract_binary, overrides) do
deploy(contract_binary, overrides)
end
def deploy(contract_binary, overrides) when is_binary(contract_binary) do
{opts, overrides} = Keyword.split(overrides, @option_keys)
{rpc_client, rpc_opts} = get_rpc_client(opts)
with {:ok, tx_params, action} <- pre_process(contract_binary, overrides, :deploy, opts) do
apply(rpc_client, action, [tx_params, rpc_opts])
|> post_process(tx_params, :deploy)
end
end
@doc """
Returns the address of the deployed contract if the deployment is finished and successful
## Parameters
- tx_hash: Hash of the Transaction which created a contract.
- opts: RPC and account options.
"""
@spec deployed_address(binary, Keyword.t()) ::
{:ok, Types.t_address()}
| {:error, :no_contract_address | :transaction_not_found | term()}
def deployed_address(tx_hash, opts \\ []) when is_binary(tx_hash) do
{rpc_client, rpc_opts} = get_rpc_client(opts)
rpc_client.eth_get_transaction_receipt(tx_hash, rpc_opts)
|> post_process(tx_hash, :deployed_address)
end
@doc """
Makes an eth_call to with the given `Ethers.TxData` struct and overrides. It then parses
the response using the selector in the TxData struct.
## Overrides and Options
Other than what stated below, any other option given in the overrides keyword list will be merged
with the map that the RPC client will receive.
- `:to`: Indicates recepient address. (Contract address in this case)
- `:block`: The block number or block alias. Defaults to `latest`
- `:rpc_client`: The RPC Client to use. It should implement ethereum jsonRPC API. default: Ethereumex.HttpClient
- `:rpc_opts`: Extra options to pass to rpc_client. (Like timeout, Server URL, etc.)
## Return structure
For contract functions which return a single value (e.g. `function test() returns (uint)`) this
returns `{:ok, value}` and for the functions which return multiple values it will return
`{:ok, [value0, value1]}` (A list).
## Examples
```elixir
Ethers.Contract.ERC20.total_supply() |> Ethers.call(to: "0xa0b...ef6")
{:ok, 100000000000000}
```
"""
@spec call(TxData.t(), Keyword.t()) :: {:ok, [term()]} | {:ok, term()} | {:error, term()}
def call(params, overrides \\ [])
def call(tx_data, overrides) do
{opts, overrides} = Keyword.split(overrides, @option_keys)
{rpc_client, rpc_opts} = get_rpc_client(opts)
with {:ok, tx_params, block} <- pre_process(tx_data, overrides, :call, opts) do
rpc_client.eth_call(tx_params, block, rpc_opts)
|> post_process(tx_data, :call)
end
end
@doc """
Same as `Ethers.call/2` but raises on error.
"""
@spec call!(TxData.t(), Keyword.t()) :: term() | no_return()
def call!(params, overrides \\ []) do
case call(params, overrides) do
{:ok, result} -> result
{:error, reason} -> raise ExecutionError, reason
end
end
@doc """
Makes an eth_send rpc call to with the given data and overrides, Then returns the
transaction hash.
## Overrides and Options
Other than what stated below, any other option given in the overrides keyword list will be merged
with the map that the RPC client will receive.
### Required Options
- `:from`: The address of the account to sign the transaction with.
### Optional Options
- `:access_list`: List of storage slots that this transaction accesses (optional)
- `:chain_id`: Chain id for the transaction (defaults to chain id from RPC server).
- `:gas_price`: (legacy only) max price willing to pay for each gas.
- `:gas`: Gas limit for execution of this transaction.
- `:max_fee_per_gas`: (EIP-1559 only) max fee per gas (defaults to 120% current gas price estimate).
- `:max_priority_fee_per_gas`: (EIP-1559 only) max priority fee per gas or validator tip. (defaults to zero)
- `:nonce`: Nonce of the transaction. (defaults to number of transactions of from address)
- `:rpc_client`: The RPC Client to use. It should implement ethereum jsonRPC API. default: Ethereumex.HttpClient
- `:rpc_opts`: Extra options to pass to rpc_client. (Like timeout, Server URL, etc.)
- `:signer`: The signer module to use for signing transaction. Default is nil and will rely on the RPC server for signing.
- `:signer_opts`: Options for signer module. See your signer docs for more details.
- `:tx_type`: Transaction type. Either `:eip1559` (default) or `:legacy`.
- `:to`: Address of the contract or a receiver of this transaction. (required if TxData does not have default_address)
- `:value`: Ether value to send with the transaction to the receiver (`from => to`).
## Examples
```elixir
Ethers.Contract.ERC20.transfer("0xff0...ea2", 1000) |> Ethers.send(to: "0xa0b...ef6")
{:ok, _tx_hash}
```
"""
@spec send(map() | TxData.t(), Keyword.t()) :: {:ok, String.t()} | {:error, term()}
def send(tx_data, overrides \\ []) do
{opts, overrides} = Keyword.split(overrides, @option_keys)
{rpc_client, rpc_opts} = get_rpc_client(opts)
with {:ok, tx_params, action} <- pre_process(tx_data, overrides, :send, opts) do
apply(rpc_client, action, [tx_params, rpc_opts])
|> post_process(tx_data, :send)
end
end
@doc """
Same as `Ethers.send/2` but raises on error.
"""
@spec send!(map() | TxData.t(), Keyword.t()) :: String.t() | no_return()
def send!(tx_data, overrides \\ []) do
case Ethers.send(tx_data, overrides) do
{:ok, tx_hash} -> tx_hash
{:error, reason} -> raise ExecutionError, reason
end
end
@doc """
Signs a transaction and returns the encoded signed transaction hex.
## Parameters
Accepts same parameters as `Ethers.send/2`.
"""
@spec sign_transaction(map(), Keyword.t()) :: {:ok, binary()} | {:error, term()}
def sign_transaction(tx_data, overrides \\ []) do
{opts, overrides} = Keyword.split(overrides, @option_keys)
default_signer = default_signer() || Ethers.Signer.JsonRPC
with {:ok, tx_params} <- pre_process(tx_data, overrides, :sign_transaction, opts),
{:ok, signer} <- get_signer(opts, default_signer),
{:ok, signed_transaction, _action} <- use_signer(tx_params, signer, opts) do
{:ok, signed_transaction}
end
end
@doc """
Same as `Ethers.sign_transaction/2` but raises on error.
"""
@spec sign_transaction!(map(), Keyword.t()) :: binary() | no_return()
def sign_transaction!(tx_data, overrides \\ []) do
case sign_transaction(tx_data, overrides) do
{:ok, signed_transaction} -> signed_transaction
{:error, reason} -> raise ExecutionError, reason
end
end
@doc """
Makes an eth_estimate_gas rpc call with the given parameters and overrides.
## Overrides and Options
- `:to`: Indicates recepient address. (Contract address in this case)
- `:rpc_client`: The RPC Client to use. It should implement ethereum jsonRPC API. default: Ethereumex.HttpClient
- `:rpc_opts`: Extra options to pass to rpc_client. (Like timeout, Server URL, etc.)
```elixir
Ethers.Contract.ERC20.transfer("0xff0...ea2", 1000) |> Ethers.estimate_gas(to: "0xa0b...ef6")
{:ok, 12345}
```
"""
@spec estimate_gas(map(), Keyword.t()) :: {:ok, non_neg_integer()} | {:error, term()}
def estimate_gas(tx_data, overrides \\ []) do
{opts, overrides} = Keyword.split(overrides, @option_keys)
{rpc_client, rpc_opts} = get_rpc_client(opts)
with {:ok, tx_params} <- pre_process(tx_data, overrides, :estimate_gas, opts) do
rpc_client.eth_estimate_gas(tx_params, rpc_opts)
|> post_process(tx_data, :estimate_gas)
end
end
@doc """
Same as `Ethers.estimate_gas/2` but raises on error.
"""
@spec estimate_gas!(map(), Keyword.t()) :: non_neg_integer() | no_return()
def estimate_gas!(tx_data, overrides \\ []) do
case estimate_gas(tx_data, overrides) do
{:ok, gas} -> gas
{:error, reason} -> raise ExecutionError, reason
end
end
@doc """
Fetches the event logs with the given filter.
## Overrides and Options
- `:address`: Indicates event emitter contract address. (nil means all contracts)
- `:rpc_client`: The RPC Client to use. It should implement ethereum jsonRPC API. default: Ethereumex.HttpClient
- `:rpc_opts`: Extra options to pass to rpc_client. (Like timeout, Server URL, etc.)
- `:fromBlock`: Minimum block number of logs to filter.
- `:toBlock`: Maximum block number of logs to filter.
"""
@spec get_logs(map(), Keyword.t()) :: {:ok, [Event.t()]} | {:error, atom()}
def get_logs(event_filter, overrides \\ []) do
{opts, overrides} = Keyword.split(overrides, @option_keys)
{rpc_client, rpc_opts} = get_rpc_client(opts)
with {:ok, log_params} <- pre_process(event_filter, overrides, :get_logs, opts) do
rpc_client.eth_get_logs(log_params, rpc_opts)
|> post_process(event_filter, :get_logs)
end
end
@doc """
Same as `Ethers.get_logs/2` but raises on error.
"""
@spec get_logs!(map(), Keyword.t()) :: [Event.t()] | no_return
def get_logs!(params, overrides \\ []) do
case get_logs(params, overrides) do
{:ok, logs} -> logs
{:error, reason} -> raise ExecutionError, reason
end
end
@doc """
Combines multiple requests and make a batch json RPC request.
It returns `{:ok, results}` in case of success or `{:error, reason}` in case of RPC failure.
Each action will have an entry in the results. Each entry is again a tuple and either
`{:ok, result}` or `{:error, reason}` in case of action failure.
Checkout `Batching Requests` sections in `Ethers` module for more examples.
## Parameters
- requests: A list of requests to execute.
- opts: RPC related options. (No account and block options are accepted in batch)
### Action
An action can be in either of the following formats.
- `{action_name_atom, action_data, action_overrides}`
- `{action_name_atom, action_data}`
- `action_name_atom`
## Examples
```elixir
Ethers.batch([
{:call, WETH.name()},
{:call, WETH.symbol(), to: "[WETH ADDRESS]"},
{:send, WETH.transfer("[RECEIVER]", 1000), from: "[SENDER]"},
:current_block_number
])
{:ok, [ok: "Weapped Ethereum", ok: "WETH", ok: "0xhash...", ok: 182394532]}
```
"""
@spec batch([t_batch_request()], Keyword.t()) ::
{:ok, [{:ok, term()} | {:error, term()}]} | {:error, term()}
def batch(requests, opts \\ []) do
{rpc_client, rpc_opts} = get_rpc_client(opts)
requests = prepare_requests(requests)
with rpc_requests when is_list(rpc_requests) <- prepare_batch_requests(requests, opts),
{:ok, responses} <- rpc_client.batch_request(rpc_requests, rpc_opts) do
results =
responses
|> Stream.zip(requests)
|> Stream.map(fn {result, {action, data, _overrides}} ->
post_process(result, data, action)
end)
|> Enum.to_list()
{:ok, results}
end
end
@doc """
Same as `Ethers.batch/2` but raises on error.
"""
@spec batch!([t_batch_request()], Keyword.t()) :: [{:ok, term()} | {:error, term()}]
def batch!(actions, opts \\ []) do
case batch(actions, opts) do
{:ok, results} -> results
{:error, reason} -> raise ExecutionError, reason
end
end
@doc false
@spec keccak_module() :: atom()
def keccak_module, do: Application.get_env(:ethers, :keccak_module, ExKeccak)
@doc false
@spec json_module() :: atom()
def json_module, do: Application.get_env(:ethers, :json_module, Jason)
@doc false
@spec secp256k1_module() :: atom()
def secp256k1_module, do: Application.get_env(:ethers, :secp256k1_module, ExSecp256k1)
@doc false
@spec rpc_client() :: atom()
def rpc_client, do: Application.get_env(:ethers, :rpc_client, Ethereumex.HttpClient)
@doc false
@spec get_rpc_client(Keyword.t()) :: {atom(), Keyword.t()}
def get_rpc_client(opts) do
module =
case Keyword.fetch(opts, :rpc_client) do
{:ok, module} when is_atom(module) -> module
:error -> Ethers.rpc_client()
end
{module, Keyword.get(opts, :rpc_opts, [])}
end
defp pre_process(tx_data, overrides, :call = _action, _opts) do
{block, overrides} = Keyword.pop(overrides, :block, "latest")
block =
case block do
number when is_integer(number) -> Utils.integer_to_hex(number)
v -> v
end
tx_params = TxData.to_map(tx_data, overrides)
case check_params(tx_params, :call) do
:ok -> {:ok, tx_params, block}
err -> err
end
end
defp pre_process(account, overrides, :get_balance = _action, _opts) do
block =
case Keyword.get(overrides, :block, "latest") do
number when is_integer(number) -> Utils.integer_to_hex(number)
v -> v
end
case account do
"0x" <> _ -> {:ok, account, block}
<<_::binary-20>> -> {:ok, Utils.hex_encode(account), block}
_ -> {:error, :invalid_account}
end
end
defp pre_process(contract_binary, overrides, :deploy = _action, opts) do
{encoded_constructor, overrides} = Keyword.pop(overrides, :encoded_constructor)
tx_params =
Enum.into(overrides, %{
data: "0x#{contract_binary}#{encoded_constructor}",
to: nil
})
with {:ok, tx_params} <- Utils.maybe_add_gas_limit(tx_params, opts) do
maybe_use_signer(tx_params, opts)
end
end
defp pre_process(tx_data, overrides, :send = action, opts) do
tx_params = TxData.to_map(tx_data, overrides)
with :ok <- check_params(tx_params, action),
{:ok, tx_params} <- Utils.maybe_add_gas_limit(tx_params, opts) do
maybe_use_signer(tx_params, opts)
end
end
defp pre_process(tx_data, overrides, :sign_transaction = action, opts) do
tx_params = TxData.to_map(tx_data, overrides)
with :ok <- check_params(tx_params, action) do
Utils.maybe_add_gas_limit(tx_params, opts)
end
end
defp pre_process(tx_data, overrides, :estimate_gas = action, _opts) do
tx_params = TxData.to_map(tx_data, overrides)
with :ok <- check_params(tx_params, action) do
{:ok, tx_params}
end
end
defp pre_process(event_filter, overrides, :get_logs, _opts) do
log_params =
event_filter
|> EventFilter.to_map(overrides)
|> ensure_hex_value(:fromBlock)
|> ensure_hex_value(:toBlock)
{:ok, log_params}
end
defp pre_process([], [], _action, _opts), do: :ok
defp pre_process(data, [], _action, _opts), do: {:ok, data}
defp post_process({:ok, resp}, tx_data, :call) when valid_result(resp) do
tx_data.selector
|> ABI.decode(Ethers.Utils.hex_decode!(resp), :output)
|> Enum.zip(tx_data.selector.returns)
|> Enum.map(fn {return, type} -> Utils.human_arg(return, type) end)
|> case do
[element] -> {:ok, element}
elements -> {:ok, elements}
end
end
defp post_process({:ok, tx_hash}, _tx_data, _action = :send) when valid_result(tx_hash),
do: {:ok, tx_hash}
defp post_process({:ok, tx_hash}, _tx_params, _action = :deploy) when valid_result(tx_hash),
do: {:ok, tx_hash}
defp post_process({:ok, gas_hex}, _tx_data, action)
when valid_result(gas_hex) and action in @hex_decode_post_process do
Utils.hex_to_integer(gas_hex)
end
defp post_process({:ok, resp}, event_filter, :get_logs) when is_list(resp) do
logs = Enum.map(resp, &Event.decode(&1, event_filter.selector))
{:ok, logs}
end
defp post_process({:ok, resp}, _event_filter, :get_logs) do
{:ok, resp}
end
defp post_process({:ok, %{"contractAddress" => contract_address}}, _tx_hash, :deployed_address)
when not is_nil(contract_address),
do: {:ok, contract_address}
defp post_process({:ok, nil}, _tx_hash, :deployed_address),
do: {:error, :transaction_not_found}
defp post_process({:ok, _}, _tx_hash, :deployed_address),
do: {:error, :no_contract_address}
defp post_process({:ok, nil}, _tx_hash, :get_transaction),
do: {:error, :transaction_not_found}
defp post_process({:ok, tx_data}, _tx_hash, :get_transaction) do
Transaction.from_map(tx_data)
end
defp post_process({:ok, nil}, _tx_hash, :get_transaction_receipt),
do: {:error, :transaction_receipt_not_found}
defp post_process({:ok, result}, _tx_data, _action),
do: {:ok, result}
defp post_process(
{:error, %{"data" => "0x" <> error_data} = full_error},
%{base_module: module},
_action
)
when is_atom(module) do
error_data = Utils.hex_decode!(error_data)
errors_module = Module.concat(module, Errors)
case errors_module.find_and_decode(error_data) do
{:ok, error} -> {:error, error}
{:error, :undefined_error} -> {:error, full_error}
e -> e
end
end
defp post_process({:error, cause}, _tx_data, _action),
do: {:error, cause}
defp ensure_hex_value(params, key) do
case Map.get(params, key) do
v when is_integer(v) -> %{params | key => Utils.integer_to_hex(v)}
_ -> params
end
end
defp prepare_requests(requests) do
Enum.map(requests, fn
{action, data} -> {action, data, []}
{action, data, overrides} -> {action, data, overrides}
action when is_atom(action) -> {action, [], []}
end)
end
defp prepare_batch_requests(requests, opts) do
requests
|> Enum.reduce_while([], fn {action, data, overrides}, acc ->
rpc_action = Map.get(@rpc_actions_map, action, action)
{sub_opts, overrides} = Keyword.split(overrides, @option_keys)
opts = Keyword.merge(opts, sub_opts)
case pre_process(data, overrides, action, opts) do
:ok ->
{:cont, [{rpc_action, []} | acc]}
{:ok, params} ->
{:cont, [{rpc_action, List.wrap(params)} | acc]}
{:ok, params, action} when action in [:eth_send_transaction, :eth_send_raw_transaction] ->
{:cont, [{action, [params]} | acc]}
{:ok, params, block} ->
{:cont, [{rpc_action, [params, block]} | acc]}
{:error, err} ->
{:halt, {:error, err}}
end
end)
|> case do
{:error, err} -> {:error, err}
list -> Enum.reverse(list)
end
end
defp maybe_use_signer(tx_params, opts) do
case get_signer(opts) do
{:ok, signer} ->
use_signer(tx_params, signer, opts)
{:error, :no_signer} ->
{:ok, tx_params, :eth_send_transaction}
end
end
defp get_signer(opts, default \\ default_signer()) do
case Keyword.get(opts, :signer, default) do
nil -> {:error, :no_signer}
signer -> {:ok, signer}
end
end
defp default_signer do
Application.get_env(:ethers, :default_signer)
end
defp default_signer_opts do
Application.get_env(:ethers, :default_signer_opts, [])
end
defp use_signer(tx_params, signer, opts) do
signer_opts = Keyword.get(opts, :signer_opts) || default_signer_opts()
tx_type = Keyword.get(opts, :tx_type, :eip1559)
with {:ok, tx} <-
Transaction.new(tx_params, tx_type) |> Transaction.fill_with_defaults(opts),
{:ok, signed_tx} <-
signer.sign_transaction(tx, signer_opts) do
{:ok, signed_tx, :eth_send_raw_transaction}
end
end
defp check_to_address(%{to: to_address}, _action) when is_binary(to_address), do: :ok
defp check_to_address(%{to: nil}, action)
when action in [:send, :sign_transaction, :estimate_gas],
do: :ok
defp check_to_address(_params, _action), do: {:error, :no_to_address}
defp check_from_address(%{from: from}, _action) when not is_nil(from), do: :ok
defp check_from_address(_tx_params, action)
when action in [:send, :sign_transaction],
do: {:error, :no_from_address}
defp check_from_address(_tx_params, _action), do: :ok
defp check_params(params, action) do
with :ok <- check_to_address(params, action) do
check_from_address(params, action)
end
end
end