-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathethereum.go
499 lines (416 loc) · 12.5 KB
/
ethereum.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
package ethereum
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math/big"
"strings"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts"
"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/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/signer/core/apitypes"
hdwallet "github.com/miguelmota/go-ethereum-hdwallet"
"golang.org/x/crypto/sha3"
)
const DefaultDerivationPath = "m/44'/60'/0'/0/0"
type Wallet struct {
chainID *big.Int
wallet *hdwallet.Wallet
account accounts.Account
rpcClient *ethclient.Client
}
// NewWallet creates a wallet from a given seed
func NewWallet(seed []byte, network, rpcURL string) (*Wallet, error) {
chainID := params.SepoliaChainConfig.ChainID
if network == "livenet" {
chainID = params.MainnetChainConfig.ChainID
}
wallet, err := hdwallet.NewFromSeed(seed)
if err != nil {
return nil, err
}
path := hdwallet.MustParseDerivationPath(DefaultDerivationPath)
account, err := wallet.Derive(path, true)
if err != nil {
return nil, err
}
rpcClient, err := ethclient.Dial(rpcURL)
if err != nil {
return nil, err
}
return &Wallet{
chainID: chainID,
wallet: wallet,
account: account,
rpcClient: rpcClient,
}, nil
}
// NewWallet creates a wallet from a given mnemonic phrases
func NewWalletFromMnemonic(words, network, rpcURL string) (*Wallet, error) {
chainID := params.SepoliaChainConfig.ChainID
if network == "livenet" {
chainID = params.MainnetChainConfig.ChainID
}
wallet, err := hdwallet.NewFromMnemonic(words)
if err != nil {
return nil, err
}
path := hdwallet.MustParseDerivationPath(DefaultDerivationPath)
account, err := wallet.Derive(path, true)
if err != nil {
return nil, err
}
rpcClient, err := ethclient.Dial(rpcURL)
if err != nil {
return nil, err
}
return &Wallet{
chainID: chainID,
wallet: wallet,
account: account,
rpcClient: rpcClient,
}, nil
}
// RPCClient returns the RPC client which is bound to the wallet
func (w *Wallet) RPCClient() *ethclient.Client {
return w.rpcClient
}
// Account returns the ethereum account address
func (w *Wallet) Account() string {
return w.account.Address.Hex()
}
// SignABIParameters sign packed function parameters and returns (r|v|s) in forms of hex string
func (w *Wallet) SignABIParameters(ctx context.Context, types []interface{}, arguments ...interface{}) (string, string, string, error) {
abiTypes, abiTypesArguments, parsedValue, err := parseABIParams(types, arguments)
if err != nil {
return "", "", "", err
}
args := abi.Arguments{}
for i, t := range abiTypes {
var am []abi.ArgumentMarshaling
if abiTypesArguments[i] != nil {
am = *abiTypesArguments[i]
}
ty, err := abi.NewType(t, "", am)
if err != nil {
return "", "", "", err
}
args = append(args, abi.Argument{Type: ty})
}
argBytes, err := args.Pack(parsedValue...)
if err != nil {
return "", "", "", err
}
h := sha3.NewLegacyKeccak256()
h.Write(argBytes)
hash := h.Sum(nil)
validationMessage := append([]byte("\x19Ethereum Signed Message:\n32"), hash...)
h2 := sha3.NewLegacyKeccak256()
h2.Write(validationMessage)
hash2 := h2.Sum(nil)
privateKey, err := w.wallet.PrivateKey(w.account)
if err != nil {
return "", "", "", err
}
signature, err := crypto.Sign(hash2, privateKey)
if err != nil {
return "", "", "", err
}
r, s, v :=
fmt.Sprintf("%#x", signature[0:32]),
fmt.Sprintf("%#x", signature[32:64]),
fmt.Sprintf("%#x", signature[64]+27)
return r, s, v, nil
}
// SignETHTypedDataV4 sign packed function parameters and returns signature
func (w *Wallet) SignETHTypedDataV4(typedDataJson json.RawMessage) (string, error) {
var typedData apitypes.TypedData
if err := json.Unmarshal(typedDataJson, &typedData); err != nil {
return "", fmt.Errorf("unmarshal typed data: %w", err)
}
// EIP-712 typed data marshalling
domainSeparator, err := typedData.HashStruct("EIP712Domain", typedData.Domain.Map())
if err != nil {
return "", fmt.Errorf("eip712domain hash struct: %w", err)
}
typedDataHash, err := typedData.HashStruct(typedData.PrimaryType, typedData.Message)
if err != nil {
return "", fmt.Errorf("primary type hash struct: %w", err)
}
// add magic string prefix
rawData := []byte(fmt.Sprintf("\x19\x01%s%s", string(domainSeparator), string(typedDataHash)))
sigHash := crypto.Keccak256(rawData)
privateKey, err := w.wallet.PrivateKey(w.account)
if err != nil {
return "", err
}
signature, err := crypto.Sign(sigHash, privateKey)
if err != nil {
return "", err
}
sgn := fmt.Sprintf("%#x", signature)
return sgn, nil
}
// TransferETH performs regular ethereum transferring
func (w *Wallet) TransferETH(ctx context.Context, to string, amount string, customizeGasPriceInWei *int64, customizedNonce *uint64) (string, error) {
account := w.account
var nonce uint64
if customizedNonce == nil {
n, err := w.rpcClient.PendingNonceAt(ctx, account.Address)
if err != nil {
return "", err
}
nonce = n
} else {
nonce = *customizedNonce
}
value, ok := big.NewInt(0).SetString(amount, 0)
if !ok {
return "", fmt.Errorf("can not set amount")
}
fromAddress := account.Address
toAddress := common.HexToAddress(to)
var gasPrice *big.Int
if customizeGasPriceInWei != nil && *customizeGasPriceInWei != 0 {
gasPrice = big.NewInt(*customizeGasPriceInWei * params.Wei)
} else {
var err error
gasPrice, err = w.rpcClient.SuggestGasPrice(ctx)
if err != nil {
return "", err
}
}
egl, err := w.rpcClient.EstimateGas(ctx, ethereum.CallMsg{
From: fromAddress,
To: &toAddress,
Value: value,
})
if err != nil {
return "", err
}
tx := types.NewTransaction(nonce, toAddress, value, egl, gasPrice, nil)
signedTx, err := w.wallet.SignTx(account, tx, nil)
if err != nil {
return "", err
}
if err := w.rpcClient.SendTransaction(ctx, signedTx); err != nil {
return "", err
}
return signedTx.Hash().String(), nil
}
// SendTransaction performs regular ethereum transaction
func (w *Wallet) SendTransaction(
ctx context.Context,
to string,
amount *string,
data *string,
customizeGasPriceInWei *int64,
customizedNonce *uint64,
) (string, error) {
account := w.account
// Calculate nonce
var nonce uint64
if customizedNonce == nil {
n, err := w.rpcClient.PendingNonceAt(ctx, account.Address)
if err != nil {
return "", err
}
nonce = n
} else {
nonce = *customizedNonce
}
// Calculate gas price
var gasPrice *big.Int
if customizeGasPriceInWei != nil && *customizeGasPriceInWei != 0 {
gasPrice = big.NewInt(*customizeGasPriceInWei * params.Wei)
} else {
var err error
gasPrice, err = w.rpcClient.SuggestGasPrice(ctx)
if err != nil {
return "", err
}
}
// Parse value
value := big.NewInt(0)
if nil != amount {
val, ok := big.NewInt(0).SetString(*amount, 0)
if !ok {
return "", fmt.Errorf("can not set amount")
}
value = val
}
// Parse data
var dataBytes []byte
if nil != data {
bytes, err := hex.DecodeString(strings.TrimPrefix(*data, "0x"))
if err != nil {
return "", err
}
dataBytes = bytes
}
toAddress := common.HexToAddress(to)
estimatedGas, err := w.rpcClient.EstimateGas(ctx, ethereum.CallMsg{
From: account.Address,
To: &toAddress,
Value: value,
Data: dataBytes,
})
if err != nil {
return "", err
}
tx := types.NewTransaction(nonce, toAddress, value, estimatedGas, gasPrice, dataBytes)
signedTx, err := w.wallet.SignTx(account, tx, nil)
if err != nil {
return "", err
}
if err := w.rpcClient.SendTransaction(ctx, signedTx); err != nil {
return "", err
}
return signedTx.Hash().String(), nil
}
// GetEthereumBalance return ethereum balance at address
func (w *Wallet) GetEthereumBalance(ctx context.Context) (string, error) {
balance, err := w.rpcClient.BalanceAt(ctx, w.account.Address, nil)
if err != nil {
return "", err
}
return balance.String(), nil
}
// GetERC20Balance return ERC20 Token balance at address
func (w *Wallet) GetERC20Balance(ctx context.Context, tokenAddr string) (string, error) {
if tokenAddr == "" {
return "", errors.New("invalid address")
}
erc20TokenContract, err := NewERC20Token(common.HexToAddress(tokenAddr), w.RPCClient())
if err != nil {
return "", err
}
balance, err := erc20TokenContract.BalanceOf(&bind.CallOpts{}, w.account.Address)
if err != nil {
return "", err
}
return balance.String(), nil
}
// GetERC20Allowance return ERC20 token allowance amount at address
func (w *Wallet) GetERC20Allowance(ctx context.Context, tokenAddr, spenderAddr string) (string, error) {
if tokenAddr == "" {
return "", errors.New("invalid address")
}
erc20TokenContract, err := NewERC20Token(common.HexToAddress(tokenAddr), w.RPCClient())
if err != nil {
return "", err
}
balance, err := erc20TokenContract.Allowance(&bind.CallOpts{}, w.account.Address, common.HexToAddress(spenderAddr))
if err != nil {
return "", err
}
return balance.String(), nil
}
// ApproveERC20Token performs approval ERC20 token for spender address
func (w *Wallet) ApproveERC20Token(ctx context.Context, tokenAddr, spender, amount string, customizeGasPriceInWei *int64, customizedNonce *uint64) (*types.Transaction, error) {
if spender == "" || amount == "" {
return nil, errors.New("invalid parameter")
}
erc20TokenContract, err := NewERC20Token(common.HexToAddress(tokenAddr), w.RPCClient())
if err != nil {
return nil, err
}
t, err := w.Transactor()
if err != nil {
return nil, err
}
if customizeGasPriceInWei != nil && *customizeGasPriceInWei != 0 {
t.GasPrice = big.NewInt(*customizeGasPriceInWei * params.Wei)
}
if customizedNonce != nil {
t.Nonce = big.NewInt(int64(*customizedNonce))
}
value, ok := big.NewInt(0).SetString(amount, 0)
if !ok {
return nil, fmt.Errorf("can not set amount")
}
return erc20TokenContract.Approve(t, common.HexToAddress(spender), value)
}
func (w *Wallet) Transactor() (*bind.TransactOpts, error) {
k, err := w.wallet.PrivateKey(w.account)
if err != nil {
return nil, err
}
return bind.NewKeyedTransactorWithChainID(k, w.chainID)
}
// TransferBatchToken performs regular ERC20 Token transferring
func (w *Wallet) TransferBatchToken(ctx context.Context, contractAddress string, arguments json.RawMessage, noSend bool, customizeGasPriceInWei *int64, customizedNonce *uint64) (*types.Transaction, error) {
transferContract, err := NewTokenBatchTransfer(common.HexToAddress(contractAddress), w.RPCClient())
if err != nil {
return nil, err
}
t, err := w.Transactor()
if err != nil {
return nil, err
}
t.NoSend = noSend
if customizeGasPriceInWei != nil && *customizeGasPriceInWei != 0 {
t.GasPrice = big.NewInt(*customizeGasPriceInWei * params.Wei)
}
if customizedNonce != nil {
t.Nonce = big.NewInt(int64(*customizedNonce))
}
var param struct {
TokenOwner string `json:"token_owner"`
Recipients []struct {
Address string `json:"address"`
Amount uint64 `json:"amount"`
} `json:"recipients"`
}
if err := json.Unmarshal(arguments, ¶m); err != nil {
return nil, err
}
emptyOpts := &bind.CallOpts{}
// Checking allowance
tokenAddr, err := transferContract.Token(emptyOpts)
if err != nil {
return nil, err
}
tokenContract, err := NewERC20Token(tokenAddr, w.RPCClient())
if err != nil {
return nil, err
}
balance, err := tokenContract.BalanceOf(emptyOpts, common.HexToAddress(param.TokenOwner))
if err != nil {
return nil, err
}
allowance, err := tokenContract.Allowance(emptyOpts, common.HexToAddress(param.TokenOwner), common.HexToAddress(contractAddress))
if err != nil {
return nil, err
}
amountParams := make([]*big.Int, 0)
tokenHolderParams := make([]common.Address, 0)
totalSendingAmount := uint64(0)
for _, v := range param.Recipients {
if v.Amount == 0 || v.Address == "" {
return nil, errors.New("empty amount or empty address parameter")
}
tokenHolderParams = append(tokenHolderParams, common.HexToAddress(v.Address))
amountParams = append(amountParams, big.NewInt(int64(v.Amount)))
totalSendingAmount += v.Amount
}
if balance.Uint64() < totalSendingAmount {
return nil, errors.New("token balance does not enough for transfer")
}
if allowance.Uint64() < totalSendingAmount {
return nil, errors.New("token allowance does not enough for transfer")
}
tx, err := transferContract.BatchTransferFrom(t, common.HexToAddress(param.TokenOwner), tokenHolderParams, amountParams)
if err != nil {
return nil, err
}
return tx, err
}