hermez-node/eth/client.go
eth/client.goRaw
1package eth
2
3import (
4 "context"
5 "fmt"
6 "math/big"
7 "time"
8
9 "github.com/ethereum/go-ethereum/accounts"
10 "github.com/ethereum/go-ethereum/accounts/abi/bind"
11 ethKeystore "github.com/ethereum/go-ethereum/accounts/keystore"
12 ethCommon "github.com/ethereum/go-ethereum/common"
13 "github.com/ethereum/go-ethereum/core/types"
14 "github.com/ethereum/go-ethereum/ethclient"
15 "github.com/hermeznetwork/hermez-node/common"
16 "github.com/hermeznetwork/hermez-node/log"
17)
18
19var (
20 // ErrAccountNil is used when the calls can not be made because the account is nil
21 ErrAccountNil = fmt.Errorf("Authorized calls can't be made when the account is nil")
22 // ErrReceiptStatusFailed is used when receiving a failed transaction
23 ErrReceiptStatusFailed = fmt.Errorf("receipt status is failed")
24 // ErrReceiptNotReceived is used when unable to retrieve a transaction
25 ErrReceiptNotReceived = fmt.Errorf("receipt not available")
26)
27
28const (
29 errStrDeploy = "deployment of %s failed: %w"
30 errStrWaitReceipt = "wait receipt of %s deploy failed: %w"
31
32 // default values
33 defaultCallGasLimit = 300000
34 defaultDeployGasLimit = 1000000
35 defaultGasPriceDiv = 100
36 defaultReceiptTimeout = 60
37 defaultIntervalReceiptLoop = 200
38)
39
40// Config defines the configuration parameters of the Client
41type Config struct {
42 CallGasLimit uint64
43 DeployGasLimit uint64
44 GasPriceDiv uint64
45 ReceiptTimeout time.Duration // in seconds
46 IntervalReceiptLoop time.Duration // in milliseconds
47}
48
49// Client is an ethereum client to call Smart Contract methods.
50type Client struct {
51 client *ethclient.Client
52 account *accounts.Account
53 ks *ethKeystore.KeyStore
54 ReceiptTimeout time.Duration
55 config *Config
56}
57
58// NewClient creates a Client instance. The account is not mandatory (it can
59// be nil). If the account is nil, CallAuth will fail with ErrAccountNil.
60func NewClient(client *ethclient.Client, account *accounts.Account, ks *ethKeystore.KeyStore, config *Config) *Client {
61 if config == nil {
62 config = &Config{
63 CallGasLimit: defaultCallGasLimit,
64 DeployGasLimit: defaultDeployGasLimit,
65 GasPriceDiv: defaultGasPriceDiv,
66 ReceiptTimeout: defaultReceiptTimeout,
67 IntervalReceiptLoop: defaultIntervalReceiptLoop,
68 }
69 }
70 return &Client{client: client, account: account, ks: ks, ReceiptTimeout: config.ReceiptTimeout * time.Second, config: config}
71}
72
73// BalanceAt retieves information about the default account
74func (c *Client) BalanceAt(addr ethCommon.Address) (*big.Int, error) {
75 return c.client.BalanceAt(context.TODO(), addr, nil)
76}
77
78// Account returns the underlying ethereum account
79func (c *Client) Account() *accounts.Account {
80 return c.account
81}
82
83// CallAuth performs a Smart Contract method call that requires authorization.
84// This call requires a valid account with Ether that can be spend during the
85// call.
86func (c *Client) CallAuth(gasLimit uint64,
87 fn func(*ethclient.Client, *bind.TransactOpts) (*types.Transaction, error)) (*types.Transaction, error) {
88 if c.account == nil {
89 return nil, ErrAccountNil
90 }
91
92 gasPrice, err := c.client.SuggestGasPrice(context.Background())
93 if err != nil {
94 return nil, err
95 }
96 inc := new(big.Int).Set(gasPrice)
97 inc.Div(inc, new(big.Int).SetUint64(c.config.GasPriceDiv))
98 gasPrice.Add(gasPrice, inc)
99 log.Debug("Transaction metadata", "gasPrice", gasPrice)
100
101 auth, err := bind.NewKeyStoreTransactor(c.ks, *c.account)
102 if err != nil {
103 return nil, err
104 }
105 auth.Value = big.NewInt(0) // in wei
106 if gasLimit == 0 {
107 auth.GasLimit = c.config.CallGasLimit // in units
108 } else {
109 auth.GasLimit = gasLimit // in units
110 }
111 auth.GasPrice = gasPrice
112
113 tx, err := fn(c.client, auth)
114 if tx != nil {
115 log.Debug("Transaction", "tx", tx.Hash().Hex(), "nonce", tx.Nonce())
116 }
117 return tx, err
118}
119
120// ContractData contains the contract data
121type ContractData struct {
122 Address ethCommon.Address
123 Tx *types.Transaction
124 Receipt *types.Receipt
125}
126
127// Deploy a smart contract. `name` is used to log deployment information. fn
128// is a wrapper to the deploy function generated by abigen. In case of error,
129// the returned `ContractData` may have some parameters filled depending on the
130// kind of error that occurred.
131func (c *Client) Deploy(name string,
132 fn func(c *ethclient.Client, auth *bind.TransactOpts) (ethCommon.Address, *types.Transaction, interface{}, error)) (ContractData, error) {
133 var contractData ContractData
134 log.Info("Deploying", "contract", name)
135 tx, err := c.CallAuth(
136 c.config.DeployGasLimit,
137 func(client *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
138 addr, tx, _, err := fn(client, auth)
139 if err != nil {
140 return nil, err
141 }
142 contractData.Address = addr
143 return tx, nil
144 },
145 )
146 if err != nil {
147 return contractData, fmt.Errorf(errStrDeploy, name, err)
148 }
149 log.Info("Waiting receipt", "tx", tx.Hash().Hex(), "contract", name)
150 contractData.Tx = tx
151 receipt, err := c.WaitReceipt(tx)
152 if err != nil {
153 return contractData, fmt.Errorf(errStrWaitReceipt, name, err)
154 }
155 contractData.Receipt = receipt
156 return contractData, nil
157}
158
159// Call performs a read only Smart Contract method call.
160func (c *Client) Call(fn func(*ethclient.Client) error) error {
161 return fn(c.client)
162}
163
164// WaitReceipt will block until a transaction is confirmed. Internally it
165// polls the state every 200 milliseconds.
166func (c *Client) WaitReceipt(tx *types.Transaction) (*types.Receipt, error) {
167 return c.waitReceipt(context.TODO(), tx, c.ReceiptTimeout)
168}
169
170// GetReceipt will check if a transaction is confirmed and return
171// immediately, waiting at most 1 second and returning error if the transaction
172// is still pending.
173func (c *Client) GetReceipt(tx *types.Transaction) (*types.Receipt, error) {
174 ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
175 defer cancel()
176 return c.waitReceipt(ctx, tx, 0)
177}
178
179func (c *Client) waitReceipt(ctx context.Context, tx *types.Transaction, timeout time.Duration) (*types.Receipt, error) {
180 var err error
181 var receipt *types.Receipt
182
183 txid := tx.Hash()
184 log.Debug("Waiting for receipt", "tx", txid.Hex())
185
186 start := time.Now()
187 for {
188 receipt, err = c.client.TransactionReceipt(ctx, txid)
189 if receipt != nil || time.Since(start) >= timeout {
190 break
191 }
192 time.Sleep(c.config.IntervalReceiptLoop * time.Millisecond)
193 }
194
195 if receipt != nil && receipt.Status == types.ReceiptStatusFailed {
196 log.Error("Failed transaction", "tx", txid.Hex())
197 return receipt, ErrReceiptStatusFailed
198 }
199
200 if receipt == nil {
201 log.Debug("Pendingtransaction / Wait receipt timeout", "tx", txid.Hex(), "lasterr", err)
202 return receipt, ErrReceiptNotReceived
203 }
204 log.Debug("Successful transaction", "tx", txid.Hex())
205
206 return receipt, err
207}
208
209// CurrentBlock returns the current block number in the blockchain
210func (c *Client) CurrentBlock() (*big.Int, error) {
211 ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
212 defer cancel()
213 header, err := c.client.HeaderByNumber(ctx, nil)
214 if err != nil {
215 return nil, err
216 }
217 return header.Number, nil
218}
219
220// HeaderByNumber internally calls ethclient.Client HeaderByNumber
221func (c *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
222 return c.client.HeaderByNumber(ctx, number)
223}
224
225// BlockByNumber internally calls ethclient.Client BlockByNumber and returns *common.Block
226func (c *Client) BlockByNumber(ctx context.Context, number *big.Int) (*common.Block, error) {
227 block, err := c.client.BlockByNumber(ctx, number)
228 if err != nil {
229 return nil, err
230 }
231 b := &common.Block{
232 EthBlockNum: block.Number().Uint64(),
233 Timestamp: time.Unix(int64(block.Time()), 0),
234 Hash: block.Hash(),
235 }
236 return b, nil
237}
238
239// ForgeCall send the *common.CallDataForge to the Forge method of the smart contract
240func (c *Client) ForgeCall(callData *common.CallDataForge) ([]byte, error) {
241 // TODO this depends on the smart contracts, once are ready this will be updated
242 return nil, nil
243}