-
Notifications
You must be signed in to change notification settings - Fork 1
/
token.go
79 lines (68 loc) · 1.97 KB
/
token.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
package model
import (
"context"
"errors"
"github.com/bitxx/evm-utils/model/types"
"github.com/bitxx/evm-utils/util"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"time"
)
type Token struct {
chain *Chain
}
func NewToken(chain *Chain) *Token {
return &Token{
chain: chain,
}
}
func (t *Token) BalanceOf(address string) (balance string, err error) {
if t.chain == nil {
return "", errors.New("the chain node is empty")
}
if !util.IsValidAddress(address) {
return "", errors.New("invalid hex address")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(t.chain.Timeout)*time.Second)
defer cancel()
balanceResult, err := t.chain.RemoteRpcClient.BalanceAt(ctx, common.HexToAddress(address), nil)
if err != nil {
return "", err
}
return balanceResult.String(), nil
}
func (t *Token) Transfer(privateKey, nonce, gasPrice, gasLimit, maxPriorityFeePerGas, value, to, data string) (hash string, err error) {
if gasPrice == "" || gasLimit == "" || to == "" || value == "" {
return "", errors.New("param is error")
}
tx := types.NewTransaction(nonce, gasPrice, gasLimit, maxPriorityFeePerGas, to, value, data)
priData, err := util.HexDecodeString(privateKey)
if err != nil {
return "", err
}
privateKeyECDSA, err := crypto.ToECDSA(priData)
address := crypto.PubkeyToAddress(privateKeyECDSA.PublicKey).Hex()
//get no sign tx
txUnSign, err := t.chain.BuildTxUnSign(address, tx)
if err != nil {
return "", err
}
//tx sign
txSign, err := t.chain.BuildTxSign(privateKeyECDSA, txUnSign)
if err != nil {
return "", err
}
//send tx
return txSign.TxHex, t.chain.SendTx(txSign.SignedTx)
}
func (t *Token) EstimateGasLimit(fromAddress, receiverAddress, gasPrice, amount string, data []byte) (string, error) {
msg := types.NewCallMsg()
msg.SetFrom(fromAddress)
msg.SetTo(receiverAddress)
msg.SetGasPrice(gasPrice)
msg.SetValue(amount)
if data != nil {
msg.SetData(data)
}
return t.chain.EstimateGasLimit(msg)
}