-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.go
executable file
·206 lines (175 loc) · 6.07 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
// Copyright 2020 The Swarm 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"
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/yanhuangpai/ifi-bee/pkg/logging"
"github.com/yanhuangpai/ifi-bee/pkg/settlement/swap/erc20"
"github.com/yanhuangpai/ifi-bee/pkg/settlement/swap/transaction"
"github.com/yanhuangpai/ifi-bee/pkg/storage"
)
const (
chequebookKey = "swap_chequebook"
chequebookDeploymentKey = "swap_chequebook_transaction_deployment"
balanceCheckBackoffDuration = 20 * time.Second
balanceCheckMaxRetries = 10
)
func checkBalance(
ctx context.Context,
logger logging.Logger,
swapInitialDeposit *big.Int,
swapBackend transaction.Backend,
chainId int64,
overlayEthAddress common.Address,
erc20Token erc20.Service,
) error {
timeoutCtx, cancel := context.WithTimeout(ctx, balanceCheckBackoffDuration*time.Duration(balanceCheckMaxRetries))
defer cancel()
for {
erc20Balance, err := erc20Token.BalanceOf(timeoutCtx, overlayEthAddress)
if err != nil {
return err
}
ethBalance, err := swapBackend.BalanceAt(timeoutCtx, overlayEthAddress, nil)
if err != nil {
return err
}
gasPrice, err := swapBackend.SuggestGasPrice(timeoutCtx)
if err != nil {
return err
}
minimumEth := gasPrice.Mul(gasPrice, big.NewInt(2000000))
insufficientERC20 := erc20Balance.Cmp(swapInitialDeposit) < 0
insufficientETH := ethBalance.Cmp(minimumEth) < 0
if insufficientERC20 || insufficientETH {
neededERC20, mod := new(big.Int).DivMod(swapInitialDeposit, big.NewInt(10000000000000000), 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))
}
if insufficientETH && insufficientERC20 {
logger.Warningf("cannot continue until there is sufficient ETH (for Gas) and at least %d BZZ available on %x", neededERC20, overlayEthAddress)
} else if insufficientETH {
logger.Warningf("cannot continue until there is sufficient ETH (for Gas) available on %x", overlayEthAddress)
} else {
logger.Warningf("cannot continue until there is at least %d BZZ available on %x", neededERC20, overlayEthAddress)
}
if chainId == 5 {
logger.Warningf("get your Goerli ETH and Goerli BZZ now via the bzzaar at https://bzz.ethswarm.org/?transaction=buy&amount=%d&slippage=30&receiver=0x%x", neededERC20, overlayEthAddress)
}
select {
case <-time.After(balanceCheckBackoffDuration):
case <-timeoutCtx.Done():
if insufficientERC20 {
return fmt.Errorf("insufficient BZZ for initial deposit")
} else {
return fmt.Errorf("insufficient ETH for initial deposit")
}
}
continue
}
return nil
}
}
// Init initialises 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,
overlayEthAddress common.Address,
chequeSigner ChequeSigner,
simpleSwapBindingFunc SimpleSwapBindingFunc,
) (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
}
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, overlayEthAddress, erc20Service)
if err != nil {
return nil, err
}
}
// if we don't yet have a chequebook, deploy a new one
txHash, err = chequebookFactory.Deploy(ctx, overlayEthAddress, big.NewInt(0))
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(swapBackend, transactionService, chequebookAddress, overlayEthAddress, stateStore, chequeSigner, erc20Service, simpleSwapBindingFunc)
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(swapBackend, transactionService, chequebookAddress, overlayEthAddress, stateStore, chequeSigner, erc20Service, simpleSwapBindingFunc)
if err != nil {
return nil, err
}
logger.Infof("using existing chequebook %x", chequebookAddress)
}
// regardless of how the chequebook service was initialised make sure that the chequebook is valid
err = chequebookFactory.VerifyChequebook(ctx, chequebookService.Address())
if err != nil {
return nil, err
}
return chequebookService, nil
}