/
client_sbch.go
303 lines (261 loc) · 7.73 KB
/
client_sbch.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
package bot
import (
"context"
"crypto/ecdsa"
"fmt"
"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/ethclient"
log "github.com/sirupsen/logrus"
"github.com/smartbch/atomic-swap-bot/htlcsbch"
)
const (
getReceiptRetryCount = 30
getReceiptWaitTime = 2 * time.Second
)
const (
SwapInvalid = iota
SwapLocked
SwapUnlocked
SwapRefunded
)
var _ ISbchClient = (*SbchClient)(nil)
type ISbchClient interface {
getBlockNumber() (uint64, error)
getBlockTimeLatest() (uint64, error)
getTxTime(txHash common.Hash) (uint64, error)
getHtlcLogs(fromBlock, toBlock uint64) ([]types.Log, error)
lockSbchToHtlc(userEvmAddr common.Address, hashLock common.Hash, timeLock uint32, amt *big.Int) (*common.Hash, error)
unlockSbchFromHtlc(hashLock common.Hash, secret common.Hash) (*common.Hash, error)
refundSbchFromHtlc(hashLock common.Hash) (*common.Hash, error)
getSwapState(hashLock common.Hash) (uint8, error)
getMarketMakerInfo(addr common.Address) (*htlcsbch.MarketMakerInfo, error)
}
type SbchClient struct {
client *ethclient.Client
timeout time.Duration
privKey *ecdsa.PrivateKey
botAddr common.Address
htlcAddr common.Address
chainId *big.Int
gasPrice *big.Int
lockGasLimit uint64
unlockGasLimit uint64
refundGasLimit uint64
}
func newSbchClient(
rawUrl string, timeout time.Duration,
privKey *ecdsa.PrivateKey, botAddr common.Address,
htlcAddr common.Address,
gasPrice *big.Int,
lockGasLimit, unlockGasLimit, refundGasLimit uint64,
) (*SbchClient, error) {
client, err := ethclient.Dial(rawUrl)
if err != nil {
return nil, err
}
return &SbchClient{
client: client,
timeout: timeout,
privKey: privKey,
botAddr: botAddr,
htlcAddr: htlcAddr,
gasPrice: gasPrice,
lockGasLimit: lockGasLimit,
unlockGasLimit: unlockGasLimit,
refundGasLimit: refundGasLimit,
}, nil
}
func (c *SbchClient) getBlockNumber() (uint64, error) {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
return c.client.BlockNumber(ctx)
}
func (c *SbchClient) getBlockTimeLatest() (uint64, error) {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
header, err := c.client.HeaderByNumber(ctx, nil)
if err != nil {
return 0, err
}
return header.Time, nil
}
func (c *SbchClient) getTxTime(txHash common.Hash) (uint64, error) {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
tr, err := c.client.TransactionReceipt(ctx, txHash)
if err != nil {
return 0, err
}
header, err := c.client.HeaderByHash(ctx, tr.BlockHash)
if err != nil {
return 0, err
}
return header.Time, nil
}
func (c *SbchClient) getHtlcLogs(fromBlock, toBlock uint64) ([]types.Log, error) {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
return c.client.FilterLogs(ctx, ethereum.FilterQuery{
FromBlock: big.NewInt(int64(fromBlock)),
ToBlock: big.NewInt(int64(toBlock)),
Addresses: []common.Address{c.htlcAddr},
})
}
func (c *SbchClient) getSwapState(hashLock common.Hash) (uint8, error) {
callData, err := htlcsbch.PackGetSwapState(hashLock)
if err != nil {
return 0, err
}
msg := ethereum.CallMsg{
From: c.botAddr,
To: &c.htlcAddr,
Gas: c.lockGasLimit,
Data: callData,
}
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
result, err := c.client.CallContract(ctx, msg, nil)
if err != nil {
return 0, err
}
return htlcsbch.UnpackGetSwapState(result)
}
func (c *SbchClient) getMarketMakerInfo(addr common.Address) (*htlcsbch.MarketMakerInfo, error) {
callData, err := htlcsbch.PackGetMarketMaker(addr)
if err != nil {
return nil, err
}
msg := ethereum.CallMsg{
From: c.botAddr,
To: &c.htlcAddr,
Gas: c.lockGasLimit,
Data: callData,
}
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
result, err := c.client.CallContract(ctx, msg, nil)
if err != nil {
return nil, err
}
return htlcsbch.UnpackGetMarketMaker(result)
}
// call lock()
func (c *SbchClient) lockSbchToHtlc(
userEvmAddr common.Address,
hashLock common.Hash,
timeLock uint32,
amt *big.Int,
) (*common.Hash, error) {
bchAddr := common.Address{}
log.Info("lock sBCH to HTLC",
", userEvmAddr: ", userEvmAddr.String(),
", hashLock: ", hashLock.String(),
", timeLock: ", timeLock,
", amt :", amt.String(),
", bchAddr: ", bchAddr.String())
data, err := htlcsbch.PackOpen(userEvmAddr, hashLock, timeLock, bchAddr)
if err != nil {
return nil, fmt.Errorf("failed to pack calldata: %w", err)
}
return c.callHtlc(amt, data, c.lockGasLimit)
}
// call unlock()
func (c *SbchClient) unlockSbchFromHtlc(
hashLock common.Hash,
secret common.Hash,
) (*common.Hash, error) {
log.Info("unlock sBCH from HTLC",
", hashLock: ", hashLock.String(),
", secret: ", secret.String())
data, err := htlcsbch.PackUnlock(hashLock, secret)
if err != nil {
return nil, fmt.Errorf("failed to pack calldata: %w", err)
}
return c.callHtlc(big.NewInt(0), data, c.unlockGasLimit)
}
// call refund()
func (c *SbchClient) refundSbchFromHtlc(hashLock common.Hash) (*common.Hash, error) {
log.Info("refund sBCH from HTLC",
", hashLock: ", hashLock.String())
data, err := htlcsbch.PackRefund(hashLock)
if err != nil {
return nil, fmt.Errorf("failed to pack calldata: %w", err)
}
return c.callHtlc(big.NewInt(0), data, c.refundGasLimit)
}
func (c *SbchClient) callHtlc(val *big.Int, data []byte, gasLimit uint64) (*common.Hash, error) {
chainID, err := c.getChainId()
if err != nil {
return nil, fmt.Errorf("failed to get chain ID: %w", err)
}
nonce, err := c.getNonce()
if err != nil {
return nil, fmt.Errorf("failed to get nonce: %w", err)
}
signer := types.NewEIP155Signer(chainID)
tx, err := types.SignNewTx(c.privKey, signer, &types.LegacyTx{
Nonce: nonce,
To: &c.htlcAddr,
Value: val,
Gas: gasLimit,
GasPrice: c.gasPrice,
Data: data,
})
if err != nil {
return nil, fmt.Errorf("failed to sign tx: %w", err)
}
err = c.sendTx(tx)
if err != nil {
return nil, fmt.Errorf("failed to send tx: %w", err)
}
txHash := tx.Hash()
log.Info("tx sent, hash: ", txHash.String())
receipt, err := c.waitTxReceipt(txHash)
if err != nil {
return nil, fmt.Errorf("failed to get receipt: %w", err)
}
if receipt.Status != types.ReceiptStatusSuccessful {
return nil, fmt.Errorf("tx failed! tx hash: %s", txHash.String())
}
return &txHash, nil
}
func (c *SbchClient) getChainId() (*big.Int, error) {
if c.chainId != nil {
return c.chainId, nil
}
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
return c.client.ChainID(ctx)
}
func (c *SbchClient) getNonce() (uint64, error) {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
return c.client.NonceAt(ctx, c.botAddr, nil)
}
func (c *SbchClient) sendTx(tx *types.Transaction) error {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
return c.client.SendTransaction(ctx, tx)
}
func (c *SbchClient) getTxReceipt(txHash common.Hash) (*types.Receipt, error) {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
return c.client.TransactionReceipt(ctx, txHash)
}
func (c *SbchClient) waitTxReceipt(txHash common.Hash) (receipt *types.Receipt, err error) {
log.Info("get tx receipt, hash: ", txHash.String())
for i := 0; i < getReceiptRetryCount; i++ {
receipt, err = c.getTxReceipt(txHash)
if err == ethereum.NotFound {
log.Info("tx receipt not ready, wait 2 seconds ...")
time.Sleep(getReceiptWaitTime)
continue
}
return
}
return
}