-
Notifications
You must be signed in to change notification settings - Fork 1
/
EthMultiCall_RPC.go.patch
208 lines (206 loc) · 6.59 KB
/
EthMultiCall_RPC.go.patch
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
From 7a70eb6ccb99eb242b066e23026de41f3bf70561 Mon Sep 17 00:00:00 2001
From: Levi Aul <levi@leviaul.com>
Date: Sat, 2 Oct 2021 13:45:42 -0700
Subject: [PATCH] Add eth_multicall API endpoint
---
cmd/rpcdaemon/commands/eth_multicall.go | 174 ++++++++++++++++++++++++
internal/web3ext/web3ext.go | 6 +
2 files changed, 180 insertions(+)
create mode 100644 cmd/rpcdaemon/commands/eth_multicall.go
diff --git a/cmd/rpcdaemon/commands/eth_multicall.go b/cmd/rpcdaemon/commands/eth_multicall.go
new file mode 100644
index 0000000000..d62159f562
--- /dev/null
+++ b/cmd/rpcdaemon/commands/eth_multicall.go
@@ -0,0 +1,174 @@
+package commands
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/holiman/uint256"
+ common2 "github.com/ledgerwatch/erigon-lib/common"
+ "github.com/ledgerwatch/erigon/common"
+ "github.com/ledgerwatch/erigon/common/hexutil"
+ "github.com/ledgerwatch/erigon/common/math"
+ "github.com/ledgerwatch/erigon/core"
+ "github.com/ledgerwatch/erigon/core/rawdb"
+ "github.com/ledgerwatch/erigon/core/state"
+ "github.com/ledgerwatch/erigon/core/vm"
+ "github.com/ledgerwatch/erigon/ethdb"
+ "github.com/ledgerwatch/erigon/internal/ethapi"
+ "github.com/ledgerwatch/erigon/rpc"
+ "github.com/ledgerwatch/erigon/turbo/rpchelper"
+ "github.com/ledgerwatch/erigon/turbo/shards"
+ "github.com/ledgerwatch/erigon/turbo/transactions"
+ "github.com/ledgerwatch/log/v3"
+)
+
+type MulticallRunlist map[common.Address][]hexutil.Bytes
+
+type MulticallResult map[common.Address][]*MulticallExecutionResult
+
+type MulticallExecutionResult struct {
+ UsedGas uint64
+ ReturnData hexutil.Bytes `json:",omitempty"`
+ Err string `json:",omitempty"`
+}
+
+// Call implements eth_call. Executes a new message call immediately without creating a transaction on the block chain.
+func (api *APIImpl) Multicall(ctx context.Context, commonCallArgs ethapi.CallArgs, contractsWithPayloads MulticallRunlist, blockNrOrHash *rpc.BlockNumberOrHash, overrides *map[common.Address]ethapi.Account) (MulticallResult, error) {
+ startTime := time.Now()
+
+ // result stores
+ execResults := make(MulticallResult)
+
+ dbtx, err := api.db.BeginRo(ctx)
+ if err != nil {
+ return nil, err
+ }
+ defer dbtx.Rollback()
+
+ chainConfig, err := api.chainConfig(dbtx)
+ if err != nil {
+ return nil, err
+ }
+
+ var baseFee *uint256.Int
+ if blockNrOrHash == nil {
+ var num = rpc.LatestBlockNumber
+ blockNrOrHash = &rpc.BlockNumberOrHash{BlockNumber: &num}
+ }
+ blockNumber, hash, err := rpchelper.GetBlockNumber(*blockNrOrHash, dbtx, api.filters)
+ if err != nil {
+ return nil, err
+ }
+ blockHeader := rawdb.ReadHeader(dbtx, hash, blockNumber)
+ if blockHeader == nil {
+ return nil, fmt.Errorf("block header %d(%x) not found", blockNumber, hash)
+ }
+ if blockHeader != nil && blockHeader.BaseFee != nil {
+ var overflow bool
+ baseFee, overflow = uint256.FromBig(blockHeader.BaseFee)
+ if overflow {
+ return nil, fmt.Errorf("header.BaseFee uint256 overflow")
+ }
+ }
+
+ var stateReader state.StateReader
+ if num, ok := blockNrOrHash.Number(); ok && num == rpc.LatestBlockNumber {
+ stateReader = state.NewPlainStateReader(dbtx)
+ } else {
+ stateReader = state.NewPlainState(dbtx, blockNumber)
+ }
+ stateCache := shards.NewStateCache(32, 0 /* no limit */)
+ cachedReader := state.NewCachedReader(stateReader, stateCache)
+ noop := state.NewNoopWriter()
+ cachedWriter := state.NewCachedWriter(noop, stateCache)
+ vmConfig := vm.Config{}
+
+ // Setup context so it may be cancelled the call has completed
+ // or, in case of unmetered gas, setup a context with a timeout.
+ var cancel context.CancelFunc
+ if callTimeout > 0 {
+ ctx, cancel = context.WithTimeout(ctx, callTimeout)
+ } else {
+ ctx, cancel = context.WithCancel(ctx)
+ }
+
+ // Make sure the context is cancelled when the call has completed
+ // this makes sure resources are cleaned up.
+ defer cancel()
+
+ callArgsBuf := commonCallArgs
+ callArgsBuf.MaxFeePerGas = (*hexutil.Big)(blockHeader.BaseFee)
+
+ if callArgsBuf.Gas == nil || uint64(*callArgsBuf.Gas) == 0 {
+ callArgsBuf.Gas = (*hexutil.Uint64)(&api.GasCap)
+ }
+
+ ibs := state.New(cachedReader)
+ var execSeq int
+
+ contractHasTEVM := ethdb.GetHasTEVM(dbtx)
+
+ for contractAddr, payloads := range contractsWithPayloads {
+ callArgsBuf.To = &contractAddr
+
+ execResultsForContract := make([]*MulticallExecutionResult, 0, len(payloads))
+
+ for _, payload := range payloads {
+ if err := common2.Stopped(ctx.Done()); err != nil {
+ return nil, err
+ }
+
+ callArgsBuf.Data = (*hexutil.Bytes)(&payload)
+
+ msg, err := callArgsBuf.ToMessage(api.GasCap, baseFee)
+ if err != nil {
+ return nil, err
+ }
+
+ blockCtx, txCtx := transactions.GetEvmContext(msg, blockHeader, blockNrOrHash.RequireCanonical, dbtx, contractHasTEVM)
+ blockCtx.GasLimit = math.MaxUint64
+ blockCtx.MaxGasLimit = true
+
+ evm := vm.NewEVM(blockCtx, txCtx, ibs, chainConfig, vmConfig)
+ gp := new(core.GasPool).AddGas(msg.Gas())
+
+ // Clone the state cache before applying the changes, clone is discarded
+ ibs.Prepare(common.Hash{}, blockHeader.Hash(), execSeq)
+
+ execResult, applyMsgErr := core.ApplyMessage(evm, msg, gp, true /* refunds */, true /* gasBailout */)
+
+ var effectiveErrDesc string
+ if applyMsgErr != nil {
+ effectiveErrDesc = applyMsgErr.Error()
+ } else if execResult.Err != nil {
+ effectiveErrDesc = ethapi.NewRevertError(execResult).Error()
+ }
+
+ if err = ibs.FinalizeTx(evm.ChainRules, noop); err != nil {
+ return nil, err
+ }
+ if err = ibs.CommitBlock(evm.ChainRules, cachedWriter); err != nil {
+ return nil, err
+ }
+
+ mcExecResult := &MulticallExecutionResult{
+ UsedGas: execResult.UsedGas,
+ Err: effectiveErrDesc,
+ }
+
+ if len(execResult.ReturnData) > 0 {
+ mcExecResult.ReturnData = common.CopyBytes(execResult.ReturnData)
+ }
+
+ execResultsForContract = append(execResultsForContract, mcExecResult)
+ execSeq++
+ }
+
+ execResults[contractAddr] = execResultsForContract
+ }
+
+ log.Info("Executed eth_multicall", "runtime_usec", time.Since(startTime).Microseconds())
+
+ return execResults, nil
+}
diff --git a/internal/web3ext/web3ext.go b/internal/web3ext/web3ext.go
index a47e1ee074..ea33afae62 100644
--- a/internal/web3ext/web3ext.go
+++ b/internal/web3ext/web3ext.go
@@ -478,6 +478,12 @@ const EthJs = `
web3._extend({
property: 'eth',
methods: [
+ new web3._extend.Method({
+ name: 'multicall',
+ call: 'eth_multicall',
+ params: 3,
+ inputFormatter: [web3._extend.formatters.inputCallFormatter, null, web3._extend.formatters.inputDefaultBlockNumberFormatter]
+ }),
new web3._extend.Method({
name: 'chainId',
call: 'eth_chainId',