-
Notifications
You must be signed in to change notification settings - Fork 486
/
NEXT2BTC.ts
460 lines (365 loc) · 11 KB
/
NEXT2BTC.ts
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import debug from 'debug'
import crypto from 'bitcoinjs-lib/src/crypto' // move to BtcSwap
import SwapApp, { constants } from 'swap.app'
import COIN_DATA from 'swap.app/constants'
import { Flow, stepsForCoins } from 'swap.swap'
const fromCoin = constants.COIN_DATA.NEXT
const toCoin = constants.COIN_DATA.BTC
class NEXT2BTC extends Flow {
_flowName: string
nextSwap: any
btcSwap: any
state: any
static getName() {
return `${this.getFromName()}2${this.getToName()}`
}
static getFromName() {
return fromCoin.ticker
}
static getToName() {
return toCoin.ticker
}
constructor(swap) {
super(swap)
this._flowName = NEXT2BTC.getName()
// todo: remove for all flows
/*
this.stepNumbers = {
'sign': 1,
'wait-lock-btc': 2,
'verify-script': 3,
'sync-balance': 4,
'lock-utxo': 5,
'wait-withdraw-next': 6, // aka getSecret
'withdraw-btc': 7,
'finish': 8,
'end': 9
}
*/
this.stepNumbers = stepsForCoins(fromCoin, toCoin)
this.nextSwap = swap.participantSwap
this.btcSwap = swap.ownerSwap
if (!this.nextSwap) {
throw new Error('BTC2NEXT: "nextSwap" of type object required')
}
if (!this.btcSwap) {
throw new Error('BTC2NEXT: "btcSwap" of type object required')
}
this.state = {
step: 0,
signTransactionHash: null,
isSignFetching: false,
isMeSigned: false,
secretHash: null,
btcScriptValues: null,
nextScriptValues: null,
btcScriptVerified: false,
isBalanceFetching: false,
isBalanceEnough: false,
balance: null,
btcScriptCreatingTransactionHash: null,
nextSwapCreationTransactionHash: null,
isNextScriptFunded: false,
secret: null,
isNextWithdrawn: false,
isbtcWithdrawn: false,
refundTransactionHash: null,
isRefunded: false,
isFinished: false,
isSwapExist: false,
}
this._persistState()
super._persistSteps()
}
_persistState() {
super._persistState()
}
//@ts-ignore: strictNullChecks
_getSteps() {
const flow = this
return [
// 1. Sign swap to start
() => {
// this.sign()
},
// 2. Wait participant create, fund BTC Script
() => {
flow.swap.room.once('create btc script', ({ scriptValues, btcScriptCreatingTransactionHash }) => {
flow.finishStep({
secretHash: scriptValues.secretHash,
btcScriptValues: scriptValues,
btcScriptCreatingTransactionHash,
}, { step: 'wait-lock-btc', silentError: true })
})
flow.swap.room.sendMessage({
event: 'request btc script',
})
},
// 3. Verify BTC Script
() => {
debug('swap.core:flow')(`waiting verify btc script`)
// this.verifyBtcScript()
},
// 4. Check balance
() => {
this.syncBalance()
debug('swap.core:flow')(this)
},
// 5. Create Next Script
async () => {
const { participant, buyAmount, sellAmount } = flow.swap
let nextSwapCreationTransactionHash
// TODO move this somewhere!
const utcNow = () => Math.floor(Date.now() / 1000)
const getLockTime = () => utcNow() + 3600 * 1 // 1 hour from now
const scriptCheckResult = await flow.btcSwap.checkScript(flow.state.btcScriptValues, {
value: buyAmount,
//@ts-ignore: strictNullChecks
recipientPublicKey: this.app.services.auth.accounts.btc.getPublicKey(),
lockTime: getLockTime(),
})
if (scriptCheckResult) {
console.error(`Btc script check error:`, scriptCheckResult)
flow.swap.events.dispatch('btc script check error', scriptCheckResult)
return
}
const scriptValues = {
secretHash: flow.state.secretHash,
//@ts-ignore: strictNullChecks
ownerPublicKey: this.app.services.auth.accounts.next.getPublicKey(),
recipientPublicKey: participant.next.publicKey,
lockTime: getLockTime(),
}
try {
await flow.nextSwap.fundScript({
scriptValues,
amount: sellAmount,
}, (hash) => {
nextSwapCreationTransactionHash = hash
flow.setState({
nextSwapCreationTransactionHash: hash,
})
})
} catch (err) {
// TODO user can stuck here after page reload...
if ( /known transaction/.test(err.message) )
return console.error(`known tx: ${err.message}`)
else if ( /out of gas/.test(err.message) )
return console.error(`tx failed (wrong secret?): ${err.message}`)
else
return console.error(err)
}
flow.swap.room.on('request next script', () => {
flow.swap.room.sendMessage({
event: 'create next script',
data: {
scriptValues,
nextSwapCreationTransactionHash,
}
})
})
flow.swap.room.sendMessage({
event: 'create next script',
data: {
scriptValues,
nextSwapCreationTransactionHash,
}
})
flow.finishStep({
isNextScriptFunded: true,
nextScriptValues: scriptValues,
}, { step: 'lock-utxo' })
},
// 6. Wait participant withdraw
() => {
flow.swap.room.once('nextWithdrawTxHash', async ({ nextSwapWithdrawTransactionHash }) => {
flow.setState({
nextSwapWithdrawTransactionHash,
})
const secret = await flow.nextSwap.getSecretFromTxhash(nextSwapWithdrawTransactionHash)
if (!flow.state.isNextWithdrawn && secret) {
flow.finishStep({
isNextWithdrawn: true,
secret,
}, { step: 'wait-withdraw-next' })
}
})
flow.swap.room.sendMessage({
event: 'request nextWithdrawTxHash',
})
},
// 7. Withdraw
async () => {
let { secret, btcScriptValues } = flow.state
if (!btcScriptValues) {
console.error('There is no "btcScriptValues" in state. No way to continue swap...')
return
}
await flow.btcSwap.withdraw({
scriptValues: flow.state.btcScriptValues,
secret,
}, (hash) => {
flow.setState({
btcSwapWithdrawTransactionHash: hash,
})
})
flow.finishStep({
isbtcWithdrawn: true,
}, { step: 'withdraw-btc' })
},
// 8. Finish
() => {
flow.swap.room.sendMessage({
event: 'swap finished',
})
flow.finishStep({
isFinished: true,
}, { step: 'finish' })
},
// 9. Finished!
() => {
}
]
}
_checkSwapAlreadyExists() {
const { participant } = this.swap
const swapData = {
//@ts-ignore: strictNullChecks
ownerAddress: this.app.services.auth.accounts.next.address,
participantAddress: participant.next.address
}
return false//this.nextSwap.checkSwapExists(swapData)
}
async sign() {
const swapExists = await this._checkSwapAlreadyExists()
if (swapExists) {
this.swap.room.sendMessage({
event: 'swap exists',
})
this.setState({
isSwapExist: true,
})
} else {
this.setState({
isSignFetching: true,
})
this.swap.room.on('request sign', () => {
this.swap.room.sendMessage({
event: 'swap sign',
})
})
this.swap.room.sendMessage({
event: 'swap sign',
})
this.finishStep({
isMeSigned: true,
}, { step: 'sign', silentError: true })
return true
}
}
verifyBtcScript() {
if (this.state.btcScriptVerified) {
return true
}
if (!this.state.btcScriptValues) {
throw new Error(`No script, cannot verify`)
}
this.finishStep({
btcScriptVerified: true,
}, { step: 'verify-script' })
return true
}
async syncBalance() {
const { sellAmount } = this.swap
this.setState({
isBalanceFetching: true,
})
//@ts-ignore: strictNullChecks
const balance = await this.nextSwap.fetchBalance(this.app.services.auth.accounts.next.getAddress())
const isEnoughMoney = sellAmount.isLessThanOrEqualTo(balance)
if (isEnoughMoney) {
this.finishStep({
balance,
isBalanceFetching: false,
isBalanceEnough: true,
}, { step: 'sync-balance' })
} else {
this.setState({
balance,
isBalanceFetching: false,
isBalanceEnough: false,
})
}
}
getRefundTxHex = () => {
this.nextSwap.getRefundHexTransaction({
scriptValues: this.state.nextScriptValues,
secret: this.state.secret,
})
.then((txHex) => {
this.setState({
refundTxHex: txHex,
})
})
}
tryRefund() {
return this.nextSwap.refund({
scriptValues: this.state.nextScriptValues,
secret: this.state.secret,
}, (hash) => {
this.setState({
refundTransactionHash: hash,
isRefunded: true,
})
})
.then(() => {
this.swap.room.sendMessage({
event: 'refund completed',
})
this.setState({
isSwapExist: false,
})
})
}
async isRefundSuccess() {
return true
}
async tryWithdraw(_secret) {
const { secret, secretHash, isNextWithdrawn, isbtcWithdrawn, btcScriptValues } = this.state
if (!_secret)
throw new Error(`Withdrawal is automatic. For manual withdrawal, provide a secret`)
if (!btcScriptValues)
throw new Error(`Cannot withdraw without script values`)
if (secret && secret != _secret)
console.warn(`Secret already known and is different. Are you sure?`)
if (isbtcWithdrawn)
console.warn(`Looks like money were already withdrawn, are you sure?`)
debug('swap.core:flow')(`WITHDRAW using secret = ${_secret}`)
const _secretHash = crypto.ripemd160(Buffer.from(_secret, 'hex')).toString('hex')
if (secretHash != _secretHash)
console.warn(`Hash does not match!`)
const { scriptAddress } = this.btcSwap.createScript(btcScriptValues)
const balance = await this.btcSwap.getBalance(scriptAddress)
debug('swap.core:flow')(`address=${scriptAddress}, balance=${balance}`)
if (balance === 0) {
this.finishStep({
isbtcWithdrawn: true,
}, { step: 'withdraw-btc' })
throw new Error(`Already withdrawn: address=${scriptAddress},balance=${balance}`)
}
await this.btcSwap.withdraw({
scriptValues: btcScriptValues,
secret: _secret,
}, (hash) => {
debug('swap.core:flow')(`TX hash=${hash}`)
this.setState({
btcSwapWithdrawTransactionHash: hash,
})
})
debug('swap.core:flow')(`TX withdraw sent: ${this.state.btcSwapWithdrawTransactionHash}`)
this.finishStep({
isbtcWithdrawn: true,
}, { step: 'withdraw-btc' })
}
}
export default NEXT2BTC