This repository has been archived by the owner on Jan 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
420 lines (369 loc) · 11.3 KB
/
client.go
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
package evm
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"log"
"math/big"
"net/http"
"strings"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
xc "github.com/jumpcrypto/crosschain"
"github.com/jumpcrypto/crosschain/chain/evm/erc20"
)
const DEFAULT_GAS_PRICE = 20_000_000_000
const DEFAULT_GAS_TIP = 3_000_000_000
var ERC20 abi.ABI
func init() {
var err error
ERC20, err = abi.JSON(strings.NewReader(erc20.Erc20ABI))
if err != nil {
panic(err)
}
}
// Client for EVM
type Client struct {
Asset *xc.AssetConfig
EthClient *ethclient.Client
RpcClient *rpc.Client
ChainId *big.Int
Interceptor *HttpInterceptor
EstimateGasFunc xc.EstimateGasFunc
Legacy bool
}
var _ xc.FullClientWithGas = &Client{}
// TxInput for EVM
type TxInput struct {
xc.TxInputEnvelope
Nonce uint64
GasLimit uint64
// DynamicFeeTx
GasTipCap xc.AmountBlockchain // maxPriorityFeePerGas
GasFeeCap xc.AmountBlockchain // maxFeePerGas
// LegacyTx
GasPrice xc.AmountBlockchain // wei per gas
}
func NewTxInput() *TxInput {
return &TxInput{
TxInputEnvelope: xc.TxInputEnvelope{
Type: xc.DriverEVM,
},
}
}
// Interceptor
type HttpInterceptor struct {
core http.RoundTripper
enabled bool
}
func (i *HttpInterceptor) Enable() {
i.enabled = true
}
func (i *HttpInterceptor) Disable() {
i.enabled = false
}
func (i HttpInterceptor) RoundTrip(req *http.Request) (*http.Response, error) {
defer func() {
_ = req.Body.Close()
}()
// log.Printf("[EVM] req: %+v", req)
res, err := i.core.RoundTrip(req)
if err != nil {
return nil, err
}
if i.enabled {
defer func() {
_ = res.Body.Close()
}()
body, _ := ioutil.ReadAll(res.Body)
bodyStr := string(body)
newStr := ""
// KLAY issue
if strings.Contains(bodyStr, "type\":\"TxTypeLegacyTransaction") {
log.Print("Replacing KLAY TxTypeLegacyTransaction")
newStr = strings.Replace(bodyStr, "TxTypeLegacyTransaction", "0x0", 1)
newStr = strings.Replace(newStr, "\"V\"", "\"v\"", 1)
newStr = strings.Replace(newStr, "\"R\"", "\"r\"", 1)
newStr = strings.Replace(newStr, "\"S\"", "\"s\"", 1)
newStr = strings.Replace(newStr, "\"signatures\":[{", "", 1)
newStr = strings.Replace(newStr, "}]", ",\"cumulativeGasUsed\":\"0x0\"", 1)
}
if strings.Contains(bodyStr, "parentHash") {
log.Print("Adding KLAY/CELO sha3Uncles")
newStr = strings.Replace(bodyStr, "parentHash", "gasLimit\":\"0x0\",\"difficulty\":\"0x0\",\"miner\":\"0x0000000000000000000000000000000000000000\",\"sha3Uncles\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\"parentHash", 1)
}
if newStr != "" {
newBody := []byte(newStr)
res.Body = io.NopCloser(bytes.NewReader(newBody))
res.ContentLength = int64(len(newBody))
res.Header.Set("Content-Length", fmt.Sprintf("%d", res.ContentLength))
}
}
newRes := res
return newRes, nil
}
func configToEVMClientURL(cfgI xc.ITask) string {
cfg := cfgI.GetNativeAsset()
if cfg.Provider == "infura" {
return cfg.URL + "/" + cfg.AuthSecret
}
return cfg.URL
}
// NewClient returns a new EVM Client
func NewClient(cfgI xc.ITask) (*Client, error) {
asset := cfgI.GetAssetConfig()
cfg := cfgI.GetNativeAsset()
url := configToEVMClientURL(cfgI)
// c, err := rpc.DialContext(context.Background(), url)
interceptor := &HttpInterceptor{http.DefaultTransport, false}
httpClient := &http.Client{
Transport: interceptor,
}
c, err := rpc.DialHTTPWithClient(url, httpClient)
if err != nil {
return nil, fmt.Errorf(fmt.Sprintf("dialing url: %v", cfg.URL))
}
client := ethclient.NewClient(c)
return &Client{
Asset: asset,
EthClient: client,
RpcClient: c,
ChainId: nil,
Interceptor: interceptor,
EstimateGasFunc: nil,
Legacy: false,
}, nil
}
// ChainID returns the ChainID
func (client *Client) ChainID() (*big.Int, error) {
var err error
if client.ChainId == nil {
client.ChainId, err = client.EthClient.ChainID(context.Background())
}
return client.ChainId, err
}
// NewLegacyClient returns a new EVM Client for legacy tx
func NewLegacyClient(cfg xc.ITask) (*Client, error) {
client, err := NewClient(cfg)
if err != nil {
return nil, err
}
client.Legacy = true
return client, nil
}
// FetchTxInput returns tx input for a EVM tx
func (client *Client) FetchTxInput(ctx context.Context, from xc.Address, _ xc.Address) (xc.TxInput, error) {
zero := xc.NewAmountBlockchainFromUint64(0)
result := NewTxInput()
result.GasTipCap = xc.NewAmountBlockchainFromUint64(DEFAULT_GAS_TIP)
result.GasFeeCap = zero
result.GasPrice = zero
// Nonce
targetAddr, err := HexToAddress(from)
if err != nil {
return zero, fmt.Errorf("bad to address '%v': %v", from, err)
}
nonce, err := client.EthClient.NonceAt(ctx, targetAddr, nil)
if err != nil {
return result, err
}
result.Nonce = nonce
// Gas
gas, err := client.EstimateGas(ctx)
if err != nil {
// pass, return err later
}
result.GasPrice = gas // legacy
result.GasFeeCap = gas // new
return result, err
}
// SubmitTx submits a EVM tx
func (client *Client) SubmitTx(ctx context.Context, tx xc.Tx) error {
switch tx := tx.(type) {
case *Tx:
err := client.EthClient.SendTransaction(ctx, tx.EthTx)
if err != nil {
return fmt.Errorf(fmt.Sprintf("sending transaction '%v': %v", tx.Hash(), err))
}
return nil
default:
bz, err := tx.Serialize()
if err != nil {
return err
}
return client.RpcClient.CallContext(ctx, nil, "eth_sendRawTransaction", hexutil.Encode(bz))
}
}
// FetchTxInfo returns tx info for a EVM tx
func (client *Client) FetchTxInfo(ctx context.Context, txHashStr xc.TxHash) (xc.TxInfo, error) {
txHashHex := TrimPrefixes(string(txHashStr))
txHash := common.HexToHash(txHashHex)
result := xc.TxInfo{
TxID: txHashHex,
ExplorerURL: client.Asset.ExplorerURL + "/tx/0x" + txHashHex,
}
tx, pending, err := client.EthClient.TransactionByHash(ctx, txHash)
if err != nil {
// TODO retry only for KLAY
client.Interceptor.Enable()
tx, pending, err = client.EthClient.TransactionByHash(ctx, txHash)
client.Interceptor.Disable()
if err != nil {
return result, fmt.Errorf(fmt.Sprintf("fetching tx by hash '%s': %v", txHashStr, err))
}
}
chainID := new(big.Int).SetInt64(client.Asset.ChainID)
// chainID, err := client.EthClient.ChainID(ctx)
// if err != nil {
// return result, fmt.Errorf("fetching chain ID: %v", err)
// }
// If the transaction is still pending, return an empty txInfo.
if pending {
return result, nil
}
receipt, err := client.EthClient.TransactionReceipt(ctx, txHash)
if err != nil {
// TODO retry only for KLAY
client.Interceptor.Enable()
receipt, err = client.EthClient.TransactionReceipt(ctx, txHash)
client.Interceptor.Disable()
if err != nil {
return result, fmt.Errorf("fetching receipt for tx %v : %v", txHashStr, err)
}
}
// if no receipt, tx has 0 confirmations
if receipt == nil {
return result, nil
}
// reverted tx
result.BlockIndex = receipt.BlockNumber.Int64()
result.BlockHash = receipt.BlockHash.Hex()
gasUsed := receipt.GasUsed
if receipt.Status == 0 {
result.Status = xc.TxStatusFailure
}
// tx confirmed
currentHeader, err := client.EthClient.HeaderByNumber(ctx, receipt.BlockNumber)
if err != nil {
client.Interceptor.Enable()
currentHeader, err = client.EthClient.HeaderByNumber(ctx, receipt.BlockNumber)
client.Interceptor.Disable()
if err != nil {
return result, fmt.Errorf("fetching current header: (%T) %v", err, err)
}
}
result.BlockTime = int64(currentHeader.Time)
var baseFee uint64
if currentHeader.BaseFee != nil {
baseFee = currentHeader.BaseFee.Uint64()
}
latestHeader, err := client.EthClient.HeaderByNumber(ctx, nil)
if err != nil {
client.Interceptor.Enable()
latestHeader, err = client.EthClient.HeaderByNumber(ctx, nil)
client.Interceptor.Disable()
if err != nil {
return result, fmt.Errorf("fetching latest header: %v", err)
}
}
result.Confirmations = latestHeader.Number.Int64() - receipt.BlockNumber.Int64()
// // tx confirmed
confirmedTx := Tx{
EthTx: tx,
Signer: types.LatestSignerForChainID(chainID),
}
info := confirmedTx.ParseTransfer(receipt, client.Asset.NativeAsset)
result.From = confirmedTx.From()
result.To = confirmedTx.To()
result.ContractAddress = confirmedTx.ContractAddress()
result.Amount = confirmedTx.Amount()
result.Fee = confirmedTx.Fee(baseFee, gasUsed)
result.Sources = info.Sources
result.Destinations = info.Destinations
return result, nil
}
// EstimateGas estimates gas price for a Cosmos chain
func (client *Client) EstimateGas(ctx context.Context) (xc.AmountBlockchain, error) {
// invoke EstimateGasFunc callback, if registered
if client.EstimateGasFunc != nil {
nativeAsset := client.Asset.NativeAsset
res, err := client.EstimateGasFunc(nativeAsset)
if err != nil {
// continue with default implementation as fallback
} else {
return res, err
}
}
// KLAY has fixed gas price of 250 ston
if client.Asset.NativeAsset == xc.KLAY {
return xc.NewAmountBlockchainFromUint64(250_000_000_000), nil
}
// legacy gas estimation via SuggestGasPrice
var baseFee uint64
if client.Legacy {
baseFeeInt, err := client.EthClient.SuggestGasPrice(ctx)
if err != nil {
// pass
} else {
baseFee = baseFeeInt.Uint64()
}
} else {
latest, err := client.EthClient.HeaderByNumber(ctx, nil)
if err != nil {
// pass
} else {
baseFee = latest.BaseFee.Uint64()
}
}
if baseFee < DEFAULT_GAS_PRICE {
baseFee = DEFAULT_GAS_PRICE
}
multiplier := 2.0
if client.Asset.ChainGasMultiplier > 0.0 {
multiplier = client.Asset.ChainGasMultiplier
}
gasPrice := (uint64)((float64)(baseFee+DEFAULT_GAS_TIP) * multiplier)
return xc.NewAmountBlockchainFromUint64(gasPrice), nil
}
// RegisterEstimateGasCallback registers a callback to get gas price
func (client *Client) RegisterEstimateGasCallback(fn xc.EstimateGasFunc) {
client.EstimateGasFunc = fn
}
// Fetch the balance of the native asset that this client is configured for
func (client *Client) FetchNativeBalance(ctx context.Context, address xc.Address) (xc.AmountBlockchain, error) {
zero := xc.NewAmountBlockchainFromUint64(0)
targetAddr, err := HexToAddress(address)
if err != nil {
return zero, fmt.Errorf("bad to address '%v': %v", address, err)
}
balance, err := client.EthClient.BalanceAt(ctx, targetAddr, nil)
if err != nil {
return zero, fmt.Errorf("failed to get balance for '%v': %v", address, err)
}
return xc.AmountBlockchain(*balance), nil
}
// Fetch the balance of the asset that this client is configured for
func (client *Client) FetchBalance(ctx context.Context, address xc.Address) (xc.AmountBlockchain, error) {
if client.Asset.Type == xc.AssetTypeNative {
return client.FetchNativeBalance(ctx, address)
}
zero := xc.NewAmountBlockchainFromUint64(0)
tokenAddress, _ := HexToAddress(xc.Address(client.Asset.Contract))
instance, err := erc20.NewErc20(tokenAddress, client.EthClient)
if err != nil {
return zero, err
}
dstAddress, _ := HexToAddress(address)
balance, err := instance.BalanceOf(&bind.CallOpts{}, dstAddress)
if err != nil {
return zero, err
}
return xc.AmountBlockchain(*balance), nil
}