forked from ChainSafe/ChainBridge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
105 lines (90 loc) 路 2.29 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
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: LGPL-3.0-only
package utils
import (
"context"
"errors"
"fmt"
"math/big"
"sync"
"time"
"github.com/ethereum/go-ethereum"
"github.com/egorgripasov/chainbridge-utils/crypto/secp256k1"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
)
const DefaultGasLimit = 6721975
const DefaultMaxGasPrice = 20000000000
const DefaultGasMultiplier = 1
var ExpectedBlockTime = time.Second
type Client struct {
Client *ethclient.Client
Opts *bind.TransactOpts
CallOpts *bind.CallOpts
nonceLock sync.Mutex
}
func NewClient(endpoint string, kp *secp256k1.Keypair) (*Client, error) {
ctx := context.Background()
rpcClient, err := rpc.DialWebsocket(ctx, endpoint, "/ws")
if err != nil {
return nil, err
}
client := ethclient.NewClient(rpcClient)
id, err := client.ChainID(ctx)
if err != nil {
return nil, err
}
opts, err := bind.NewKeyedTransactorWithChainID(kp.PrivateKey(), id)
if err != nil {
return nil, err
}
opts.Nonce = big.NewInt(0)
opts.Value = big.NewInt(0) // in wei
opts.GasLimit = uint64(DefaultGasLimit) // in units
opts.GasPrice = big.NewInt(DefaultMaxGasPrice)
opts.Context = ctx
return &Client{
Client: client,
Opts: opts,
CallOpts: &bind.CallOpts{
From: opts.From,
},
}, nil
}
func (c *Client) LockNonceAndUpdate() error {
c.nonceLock.Lock()
nonce, err := c.Client.PendingNonceAt(context.Background(), c.Opts.From)
if err != nil {
c.nonceLock.Unlock()
return err
}
c.Opts.Nonce.SetUint64(nonce)
return nil
}
func (c *Client) UnlockNonce() {
c.nonceLock.Unlock()
}
// WaitForTx will query the chain at ExpectedBlockTime intervals, until a receipt is returned.
// Returns an error if the tx failed.
func WaitForTx(client *Client, tx *ethtypes.Transaction) error {
retry := 10
for retry > 0 {
receipt, err := client.Client.TransactionReceipt(context.Background(), tx.Hash())
if err != nil {
if errors.Is(err, ethereum.NotFound) {
retry--
time.Sleep(ExpectedBlockTime)
continue
} else {
return err
}
}
if receipt.Status != 1 {
return fmt.Errorf("transaction failed on chain")
}
return nil
}
return nil
}