/
client.go
192 lines (170 loc) · 4.82 KB
/
client.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
package client
import (
"context"
"crypto/ecdsa"
"fmt"
balance_op "github.com/b1uem0nday/transfer_service/internal/client/balance_operations"
"github.com/b1uem0nday/transfer_service/internal/client/logs"
"github.com/b1uem0nday/transfer_service/internal/repository"
"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"
"io/ioutil"
"log"
"math/big"
"time"
)
type (
Config struct {
IP string `yaml:"ip"`
HttpPort string `yaml:"http_port"`
WsPort string `yaml:"ws_port"`
AddressPath string `yaml:"address_path"`
PrivateKeyPath string `yaml:"private_key_path"`
}
Api interface {
Deposit(amount *big.Int) error
Withdraw(amount *big.Int) error
Transfer(receiver string, amount *big.Int) error
GetBalance(accountAddress *string) (*big.Int, error)
}
Client struct {
chainId *big.Int
cfg *Config
ctx context.Context
log logs.Logger
owner ownerData
contract *balance_op.BalanceOp
ethCli *ethclient.Client
Api
}
txOpts struct {
gasPrice *big.Int
gasLimit uint64
value *big.Int
}
ownerData struct {
pk *ecdsa.PrivateKey
address common.Address
}
)
var DefaultConfig = Config{
IP: "localhost",
HttpPort: "22000",
WsPort: "32000",
AddressPath: "",
PrivateKeyPath: "",
}
func NewClient(db repository.Repo, ctx context.Context) *Client {
return &Client{log: logs.NewLogger(db, make(chan *types.Transaction)), ctx: ctx}
}
func (c *Client) Prepare(cfg *Config) (err error) {
if c.owner.pk, err = readKeyFromFile(cfg.PrivateKeyPath); err != nil {
return err
}
c.ethCli, err = connect(fmt.Sprintf("http://%s:%s", cfg.IP, cfg.HttpPort)) //json-rpc
if err != nil {
return err
}
c.chainId, err = c.ethCli.ChainID(c.ctx)
if err != nil {
return err
}
auth, err := bind.NewKeyedTransactorWithChainID(c.owner.pk, c.chainId)
if err != nil {
return err
}
var contractAddress common.Address
if b, err := ioutil.ReadFile(cfg.AddressPath); b == nil || err != nil {
contractAddress, err = c.deploy(cfg.AddressPath, auth)
if err != nil {
return err
}
} else {
contractAddress = common.BytesToAddress(b)
log.Println("using existent contract", contractAddress)
}
if err = c.setInstance(contractAddress, auth); err != nil {
return err
}
if c.owner.address, err = c.contract.Owner(nil); err != nil {
return err
}
go c.log.Run(fmt.Sprintf("ws://%s:%s", cfg.IP, cfg.WsPort), contractAddress)
return nil
}
func (c *Client) deploy(path string, opts *bind.TransactOpts) (address common.Address, err error) {
if nonce, err := c.getNonce(); err != nil {
return common.Address{}, err
} else {
opts.Nonce = nonce
}
addr, _, _, err := balance_op.DeployBalanceOp(opts, c.ethCli)
if err != nil {
return common.Address{}, err
}
log.Println("contract deployed")
if err = ioutil.WriteFile(path, addr.Bytes(), 0777); err != nil {
log.Println("contract deployed, but address wasn't saved")
}
return addr, nil
}
func (c *Client) getNonce() (*big.Int, error) {
nonce, err := c.ethCli.PendingNonceAt(context.Background(), c.owner.address)
if err != nil {
return nil, err
}
return big.NewInt(int64(nonce)), err
}
func (c *Client) setInstance(contractAddress common.Address, opts *bind.TransactOpts) (err error) {
if c.contract, err = balance_op.NewBalanceOp(contractAddress, c.ethCli); err != nil || c.contract == nil {
log.Printf("contract %s was not deployed, deploy again", contractAddress)
contractAddress, err = c.deploy(c.cfg.AddressPath, opts)
if err != nil {
return err
}
c.contract, err = balance_op.NewBalanceOp(contractAddress, c.ethCli)
if err != nil {
return err
}
}
return nil
}
func connect(rawurl string) (c *ethclient.Client, err error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
return ethclient.DialContext(ctx, rawurl)
}
func (c *Client) newTxOpts(opts ...txOpts) (*bind.TransactOpts, error) {
txOpts, err := bind.NewKeyedTransactorWithChainID(c.owner.pk, c.chainId)
if err != nil {
return nil, err
}
if txOpts.Nonce, err = c.getNonce(); err != nil {
return nil, err
}
if len(opts) > 0 {
if opts[0].gasPrice == nil {
txOpts.GasPrice, err = c.ethCli.SuggestGasPrice(c.ctx)
if err != nil {
log.Printf("Cannot calculate suggested gas price due the transaction")
txOpts.GasPrice = big.NewInt(0)
}
}
txOpts.GasLimit = opts[0].gasLimit
txOpts.Value = opts[0].value
}
return txOpts, nil
}
func (c *Client) NewTxOpts() (*bind.TransactOpts, error) {
return c.newTxOpts()
}
func readKeyFromFile(path string) (key *ecdsa.PrivateKey, err error) {
pk, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return crypto.HexToECDSA(string(pk))
}