-
Notifications
You must be signed in to change notification settings - Fork 5
/
init.go
321 lines (284 loc) · 9.61 KB
/
init.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
// Copyright 2020 The Penguin Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package chequebook
import (
"context"
"encoding/hex"
"fmt"
"github.com/penguintop/penguin/pkg/property"
"github.com/penguintop/penguin/pkg/xwcfmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/penguintop/penguin/pkg/logging"
"github.com/penguintop/penguin/pkg/settlement/swap/erc20"
"github.com/penguintop/penguin/pkg/storage"
"github.com/penguintop/penguin/pkg/transaction"
)
const (
chequebookKey = "swap_chequebook"
ChequebookDeploymentKey = "swap_chequebook_transaction_deployment"
balanceCheckBackoffDuration = 20 * time.Second
balanceCheckMaxRetries = 10
CHECK_BALANCE_INTERVAL = 60 * time.Second
chequeBookDeployedCheckBackoffDuration = 10 * time.Second
)
func checkBalance(
ctx context.Context,
logger logging.Logger,
swapInitialDeposit *big.Int,
swapBackend transaction.Backend,
chainId int64,
overlayXwcAddress common.Address,
erc20Token erc20.Service,
) error {
timeoutCtx, cancel := context.WithTimeout(ctx, balanceCheckBackoffDuration*time.Duration(balanceCheckMaxRetries))
defer cancel()
for {
erc20Balance, err := erc20Token.BalanceOf(timeoutCtx, overlayXwcAddress)
if err != nil {
return err
}
logger.Info("pen token balance:", erc20Balance)
xwcBalance, err := swapBackend.BalanceAt(timeoutCtx, overlayXwcAddress, nil)
if err != nil {
return err
}
logger.Info("xwc balance:", xwcBalance)
minimumXwc := big.NewInt(1).Mul(big.NewInt(1), big.NewInt(property.XWC_ASSET_PRCISION))
insufficientERC20 := erc20Balance.Cmp(swapInitialDeposit) < 0
insufficientXWC := xwcBalance.Cmp(minimumXwc) < 0
if insufficientERC20 || insufficientXWC {
neededERC20, mod := new(big.Int).DivMod(swapInitialDeposit, big.NewInt(property.PEN_ERC20_PRCISION), new(big.Int))
if mod.Cmp(big.NewInt(0)) > 0 {
// always round up the division as the bzzaar cannot handle decimals
neededERC20.Add(neededERC20, big.NewInt(1))
}
overlayXwcAddr, _ := xwcfmt.HexAddrToXwcAddr(hex.EncodeToString(overlayXwcAddress[:]))
if insufficientXWC && insufficientERC20 {
logger.Warningf("cannot continue until there is sufficient XWC (for Gas) and at least %d PEN available on %s", neededERC20, overlayXwcAddr)
} else if insufficientXWC {
logger.Warningf("cannot continue until there is sufficient XWC (for Gas) available on %s", overlayXwcAddr)
} else {
logger.Warningf("cannot continue until there is at least %d PEN available on %s", neededERC20, overlayXwcAddr)
}
select {
case <-time.After(balanceCheckBackoffDuration):
case <-timeoutCtx.Done():
if insufficientERC20 {
return fmt.Errorf("insufficient PEN for initial deposit")
} else {
return fmt.Errorf("insufficient ETH for initial deposit")
}
}
continue
}
return nil
}
}
// Function Init will initialize the chequebook service.
func Init(
ctx context.Context,
chequebookFactory Factory,
stateStore storage.StateStorer,
logger logging.Logger,
swapInitialDeposit *big.Int,
transactionService transaction.Service,
swapBackend transaction.Backend,
chainId int64,
overlayXwcAddress common.Address,
chequeSigner ChequeSigner,
) (chequebookService Service, err error) {
// verify that the supplied factory is valid
err = chequebookFactory.VerifyBytecode(ctx)
if err != nil {
return nil, err
}
erc20Address, err := chequebookFactory.ERC20Address(ctx)
if err != nil {
return nil, err
}
conAddr, _ := xwcfmt.HexAddrToXwcConAddr(hex.EncodeToString(erc20Address[:]))
logger.Info("pen token contract: ", conAddr)
erc20Service := erc20.New(swapBackend, transactionService, erc20Address)
/////////////////////////////////////////////////////////////
//var chequebookAddress common.Address
//err = stateStore.Get(chequebookKey, &chequebookAddress)
//if err != nil {
// if err != storage.ErrNotFound {
// return nil, err
// }
//
// var txHash common.Hash
// err = stateStore.Get(ChequebookDeploymentKey, &txHash)
// if err != nil && err != storage.ErrNotFound {
// return nil, err
// }
// if err == storage.ErrNotFound {
// logger.Info("no chequebook found, deploying new one.")
// if swapInitialDeposit.Cmp(big.NewInt(0)) != 0 {
// err = checkBalance(ctx, logger, swapInitialDeposit, swapBackend, chainId, overlayXwcAddress, erc20Service)
// if err != nil {
// return nil, err
// }
// }
//
// nonce := make([]byte, 32)
// _, err = rand.Read(nonce)
// if err != nil {
// return nil, err
// }
//
// // if we don't yet have a chequebook, deploy a new one
// txHash, err = chequebookFactory.Deploy(ctx, overlayXwcAddress, big.NewInt(0), common.BytesToHash(nonce))
// if err != nil {
// return nil, err
// }
//
// logger.Infof("deploying new chequebook in transaction %x", txHash)
//
// err = stateStore.Put(ChequebookDeploymentKey, txHash)
// if err != nil {
// return nil, err
// }
// } else {
// logger.Infof("waiting for chequebook deployment in transaction %x", txHash)
// }
//
// chequebookAddress, err = chequebookFactory.WaitDeployed(ctx, txHash)
// if err != nil {
// return nil, err
// }
//
// logger.Infof("deployed chequebook at address %x", chequebookAddress)
//
// // save the address for later use
// err = stateStore.Put(chequebookKey, chequebookAddress)
// if err != nil {
// return nil, err
// }
//
// chequebookService, err = New(transactionService, chequebookAddress, overlayXwcAddress, stateStore, chequeSigner, erc20Service)
// if err != nil {
// return nil, err
// }
//
// if swapInitialDeposit.Cmp(big.NewInt(0)) != 0 {
// logger.Infof("depositing %d token into new chequebook", swapInitialDeposit)
// depositHash, err := chequebookService.Deposit(ctx, swapInitialDeposit)
// if err != nil {
// return nil, err
// }
//
// logger.Infof("sent deposit transaction %x", depositHash)
// err = chequebookService.WaitForDeposit(ctx, depositHash)
// if err != nil {
// return nil, err
// }
//
// logger.Info("successfully deposited to chequebook")
// }
//} else {
// chequebookService, err = New(transactionService, chequebookAddress, overlayXwcAddress, stateStore, chequeSigner, erc20Service)
// if err != nil {
// return nil, err
// }
//
// logger.Infof("using existing chequebook %x", chequebookAddress)
//}
//
//// regardless of how the chequebook service was initialized make sure that the chequebook is valid
//err = chequebookFactory.VerifyChequebook(ctx, chequebookService.Address())
//if err != nil {
// return nil, err
//}
///////////////////////////////////////////////////////////////
p, err := chequebookFactory.QueryUserChequeBook(ctx, overlayXwcAddress)
if err != nil {
return nil, err
}
if p == nil {
// chequebook contract not exist
var txHash common.Hash
err = stateStore.Get(ChequebookDeploymentKey, &txHash)
if err != nil && err != storage.ErrNotFound {
return nil, err
}
if err == storage.ErrNotFound {
logger.Info("no chequebook found, deploying new one.")
if swapInitialDeposit.Cmp(big.NewInt(0)) != 0 {
for {
err = checkBalance(ctx, logger, swapInitialDeposit, swapBackend, chainId, overlayXwcAddress, erc20Service)
if err != nil {
// Never skip the process and retry it until the account balance is available.
logger.Errorf("Failed to check balance: %s", err.Error())
logger.Info("Wait a moment to retry the checking balance.")
time.Sleep(CHECK_BALANCE_INTERVAL)
continue
}
break
}
// transfer token
EntranceAddressHex, _ := xwcfmt.XwcAddrToHexAddr(property.EntranceAddress)
EntranceAddressBytes, _ := hex.DecodeString(EntranceAddressHex)
var toAddr common.Address
toAddr.SetBytes(EntranceAddressBytes)
txHash, err = erc20Service.Transfer(ctx, toAddr, swapInitialDeposit)
if err != nil {
return nil, err
}
logger.Infof("deploying new chequebook in transaction %x", txHash[12:])
err = stateStore.Put(ChequebookDeploymentKey, txHash)
if err != nil {
return nil, err
}
}
} else {
logger.Infof("waiting for chequebook deployment in transaction %x", txHash[12:])
}
// wait deploy
for {
p, err = chequebookFactory.QueryUserChequeBook(ctx, overlayXwcAddress)
if err != nil {
return nil, err
}
if p == nil {
logger.Infof("waiting for cheque book contract deployed...")
// wait 10 seconds
select {
case <-time.After(chequeBookDeployedCheckBackoffDuration):
continue
}
} else {
chequebookAddress := *p
chequebookService, err = New(transactionService, chequebookAddress, overlayXwcAddress, stateStore, chequeSigner, erc20Service)
if err != nil {
return nil, err
}
chequebookXwcAddr, _ := xwcfmt.HexAddrToXwcConAddr(hex.EncodeToString(chequebookAddress[:]))
logger.Infof("chequebook deployed %s", chequebookXwcAddr)
break
}
}
} else {
// chequebook contract exist
chequebookAddress := *p
chequebookService, err = New(transactionService, chequebookAddress, overlayXwcAddress, stateStore, chequeSigner, erc20Service)
if err != nil {
return nil, err
}
chequebookXwcAddr, _ := xwcfmt.HexAddrToXwcConAddr(hex.EncodeToString(chequebookAddress[:]))
logger.Infof("using existing chequebook %s", chequebookXwcAddr)
}
// regardless of how the chequebook service was initialized make sure that the chequebook is valid
err = chequebookFactory.VerifyChequebook(ctx, chequebookService.Address())
if err != nil {
return nil, err
}
err = chequebookFactory.VerifyChequebookOwner(ctx, chequebookService.Address(), overlayXwcAddress)
if err != nil {
return nil, err
}
return chequebookService, nil
}