forked from kewka/give-me-bnb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockchain.go
64 lines (52 loc) · 1.42 KB
/
blockchain.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
package main
import (
"context"
"crypto/ecdsa"
"math/big"
"time"
"github.com/ethereum/go-ethereum"
"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"
)
var (
GasLimit uint64 = 21000
// 1 BNB
BnbAmount = big.NewInt(1e18)
)
func WaitTx(ctx context.Context, client *ethclient.Client, tx string) error {
hash := common.HexToHash(tx)
for {
receipt, err := client.TransactionReceipt(ctx, hash)
if receipt != nil {
return nil
}
if err != nil && err != ethereum.NotFound {
return err
}
time.Sleep(time.Second)
}
}
func SendBnb(ctx context.Context, client *ethclient.Client, from *ecdsa.PrivateKey, to string) (string, error) {
nonce, err := client.PendingNonceAt(ctx, crypto.PubkeyToAddress(from.PublicKey))
if err != nil {
return "", err
}
gasPrice, err := client.SuggestGasPrice(ctx)
if err != nil {
return "", err
}
gasAmount := new(big.Int).Mul(big.NewInt(int64(GasLimit)), gasPrice)
amount := new(big.Int).Sub(BnbAmount, gasAmount)
tx := types.NewTransaction(nonce, common.HexToAddress(to), amount, GasLimit, gasPrice, nil)
chainId, err := client.NetworkID(ctx)
if err != nil {
return "", err
}
signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainId), from)
if err != nil {
return "", err
}
return signedTx.Hash().Hex(), client.SendTransaction(ctx, signedTx)
}