/
tx.go
71 lines (65 loc) · 1.45 KB
/
tx.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
package eth_utils
import (
"context"
"crypto/ecdsa"
"errors"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"math/big"
"time"
)
func SignTx(
signer *ecdsa.PrivateKey, chainId *big.Int, nonce uint64,
to *common.Address, value *big.Int, data []byte,
maxPriorityFeePerGas, maxFeePerGas *big.Int, gasLimit uint64,
) (*types.Transaction, error) {
baseTx := &types.DynamicFeeTx{
ChainID: chainId,
To: to,
Nonce: nonce,
Value: value,
Data: data,
GasTipCap: maxPriorityFeePerGas,
GasFeeCap: maxFeePerGas,
Gas: gasLimit,
}
tx, err := types.SignNewTx(
signer,
types.LatestSignerForChainID(chainId),
baseTx,
)
if err != nil {
return nil, err
}
return tx, nil
}
func WaitConfirm(ctx context.Context, ec *ethclient.Client, txHash common.Hash, timeout time.Duration) error {
pending := true
for pending {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(timeout):
return errors.New("timeout")
case <-time.After(time.Second):
_, isPending, err := ec.TransactionByHash(ctx, txHash)
if err != nil {
return err
}
if !isPending {
pending = false // break `for`
}
}
}
receipt, err := ec.TransactionReceipt(ctx, txHash)
if err != nil {
return err
}
if receipt.Status == 0 {
msg := fmt.Sprintf("transaction reverted, hash %s", receipt.TxHash.String())
return errors.New(msg)
}
return nil
}