-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathflyover.test.ts
More file actions
759 lines (660 loc) · 34.2 KB
/
flyover.test.ts
File metadata and controls
759 lines (660 loc) · 34.2 KB
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
import { describe, test, expect, beforeEach, jest } from '@jest/globals'
import { Flyover } from './flyover'
import { getQuote } from './getQuote'
import { getProviders } from './getProviders'
import { acceptQuote } from './acceptQuote'
import { getPegoutQuote } from './getPegoutQuote'
import { acceptPegoutQuote } from './acceptPegoutQuote'
import { depositPegout } from './depositPegout'
import { type Quote, type PeginQuoteRequest, type LiquidityProvider, type PegoutQuote, type PegoutQuoteRequest } from '../api'
import { LiquidityBridgeContract } from '../blockchain/lbc'
import { refundPegout } from './refundPegout'
import { registerPegin, type RegisterPeginParams } from './registerPegin'
import { type BlockchainConnection } from '@rsksmart/bridges-core-sdk'
import { FlyoverError } from '../client/httpClient'
import { supportsConversion } from './supportsConversion'
import { getMetadata } from './getMetadata'
import { getPeginStatus } from './getPeginStatus'
import { getPegoutStatus } from './getPegoutStatus'
import { getAvailableLiquidity } from './getAvailableLiquidity'
import { validatePeginTransaction, type ValidatePeginTransactionOptions, type ValidatePeginTransactionParams } from './validatePeginTransaction'
import { RskBridge } from '../blockchain/bridge'
import { isPeginQuotePaid } from './isPeginQuotePaid'
import { isPegoutQuotePaid } from './isPegoutQuotePaid'
import { type BitcoinDataSource } from '../bitcoin/BitcoinDataSource'
jest.mock('ethers')
jest.mock('./getProviders')
jest.mock('./getQuote')
jest.mock('./acceptQuote')
jest.mock('./getPegoutQuote')
jest.mock('./acceptPegoutQuote')
jest.mock('./depositPegout')
jest.mock('./refundPegout')
jest.mock('./registerPegin')
jest.mock('./supportsConversion')
jest.mock('./getMetadata')
jest.mock('./getPeginStatus')
jest.mock('./getPegoutStatus')
jest.mock('./getAvailableLiquidity')
jest.mock('./validatePeginTransaction')
jest.mock('./isPeginQuotePaid')
jest.mock('./isPegoutQuotePaid')
const mockedGetQuote = getQuote as jest.Mock<typeof getQuote>
const mockedGetPegoutQuote = getPegoutQuote as jest.Mock<typeof getPegoutQuote>
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const rskConnectionMock = jest.mocked({
getChainHeight: async () => Promise.resolve(1),
getAbstraction: () => {
return jest.mocked({})
}
} as BlockchainConnection)
const signatureMock = 'fa751697c71da60568814c1c18161a4be6af252177e6483b66ee554d6ff141a72879c152ac436ae07816dd69984d9440f9651e47ac24e7216825093f13f9147b1c'
const quoteMock: Quote = {
quoteHash: 'any hash',
quote: {
fedBTCAddr: 'any address',
lbcAddr: 'any address',
lpRSKAddr: 'any address',
btcRefundAddr: 'any address',
rskRefundAddr: 'any address',
lpBTCAddr: 'any address',
contractAddr: 'any address',
callFee: BigInt(1),
penaltyFee: BigInt(1),
data: 'any data',
gasLimit: 1,
nonce: BigInt(1),
value: BigInt('9007199254740993'),
timeForDeposit: 1,
lpCallTime: 1,
agreementTimestamp: 1,
confirmations: 1,
callOnRegister: true,
gasFee: BigInt('1'),
productFeeAmount: BigInt(50000000000000)
}
}
const pegoutQuoteMock: PegoutQuote = {
quote: {
agreementTimestamp: 1,
btcRefundAddress: 'any address',
callFee: BigInt(1),
depositAddr: 'any address',
depositConfirmations: 1,
depositDateLimit: 1,
expireBlocks: 1,
expireDate: 1,
gasFee: BigInt('1'),
lbcAddress: 'any address',
liquidityProviderRskAddress: 'any address',
lpBtcAddr: 'any address',
nonce: BigInt(1),
penaltyFee: BigInt(1),
rskRefundAddress: 'any address',
transferConfirmations: 1,
transferTime: 1,
value: BigInt('9007199254740993'),
productFeeAmount: BigInt(50000000000000)
},
quoteHash: 'any hash'
}
const providerMock: LiquidityProvider = {
apiBaseUrl: 'http://localhost',
id: 1,
provider: 'any address',
name: 'any name',
status: true,
providerType: 'pegin',
siteKey: 'any key',
liquidityCheckEnabled: true,
pegin: {
minTransactionValue: BigInt(1),
maxTransactionValue: BigInt(100),
fee: BigInt(1),
fixedFee: BigInt(3),
feePercentage: 1.25,
requiredConfirmations: 5
},
pegout: {
minTransactionValue: BigInt(1),
maxTransactionValue: BigInt(100),
fee: BigInt(1),
fixedFee: BigInt(3),
feePercentage: 1.25,
requiredConfirmations: 5
}
}
const quoteRequestMock: PeginQuoteRequest = {
callEoaOrContractAddress: 'any address',
callContractArguments: 'any address',
valueToTransfer: BigInt('9007199254740993'),
rskRefundAddress: 'any address'
}
const pegoutQuoteRequestMock: PegoutQuoteRequest = {
to: 'any address',
valueToTransfer: BigInt('9007199254740993'),
rskRefundAddress: 'any address'
}
const registerPeginParamsMock: RegisterPeginParams = {
quote: quoteMock,
signature: 'any signature',
partialMerkleTree: 'any pmt',
btcRawTransaction: 'any tx',
height: 1
}
mockedGetQuote.mockImplementation(async () => Promise.resolve([quoteMock]))
mockedGetPegoutQuote.mockImplementation(async () => Promise.resolve([pegoutQuoteMock]))
describe('Flyover object should', () => {
let flyover: Flyover
const FAKE_NETWORK = 'Regtest'
beforeEach(() => {
flyover = new Flyover({
network: FAKE_NETWORK,
allowInsecureConnections: true,
captchaTokenResolver: async () => Promise.resolve('')
})
})
test('fail to get quotes if liquidity provider has not been selected', async () => {
await flyover.connectToRsk(rskConnectionMock)
await expect(flyover.getQuotes({
callEoaOrContractAddress: '0xa2193A393aa0c94A4d52893496F02B56C61c36A1',
callContractArguments: '',
valueToTransfer: BigInt(500000000000000000),
rskRefundAddress: '0xa2193A393aa0c94A4d52893496F02B56C61c36A1'
})).rejects.toThrow('You need to select a provider to do this operation')
})
test('fail to get pegout quotes if liquidity provider has not been selected', async () => {
await flyover.connectToRsk(rskConnectionMock)
await expect(flyover.getPegoutQuotes({
to: 'mxqk28jvEtvjxRN8k7W9hFEJfWz5VcUgHW',
valueToTransfer: BigInt(500000000000000000),
rskRefundAddress: '0xa2193A393aa0c94A4d52893496F02B56C61c36A1'
})).rejects.toThrow('You need to select a provider to do this operation')
})
test('fail to accept quote if liquidity provider has not been selected', async () => {
await expect(flyover.acceptQuote(quoteMock)).rejects.toThrow('You need to select a provider to do this operation')
})
test('fail to accept pegout quote if liquidity provider has not been selected', async () => {
await expect(flyover.acceptPegoutQuote(pegoutQuoteMock)).rejects.toThrow('You need to select a provider to do this operation')
})
test('be able to set selected provider', () => {
flyover.useLiquidityProvider(providerMock)
expect(flyover).not.toHaveProperty('liquidityProvider', undefined)
})
test('invoke correctly getProviders', async () => {
await flyover.connectToRsk(rskConnectionMock)
await flyover.getLiquidityProviders()
expect(getProviders).toBeCalledTimes(1)
})
test('throw error if getLiquidityProviders is executed without a RSK connection', async () => {
await expect(flyover.getLiquidityProviders()).rejects.toThrow('Not connected to RSK')
})
test('invoke correctly getQuotes', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.connectToRsk(rskConnectionMock)
await flyover.getQuotes(quoteRequestMock)
expect(getQuote).toBeCalledTimes(1)
})
test('invoke correctly getPegoutQuotes', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.connectToRsk(rskConnectionMock)
await flyover.getPegoutQuotes(pegoutQuoteRequestMock)
expect(getPegoutQuote).toBeCalledTimes(1)
})
test('invoke correctly acceptQuote', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.connectToRsk(rskConnectionMock)
await flyover.acceptQuote(quoteMock)
expect(acceptQuote).toBeCalledTimes(1)
})
test('invoke correctly acceptPegoutQuote', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.acceptPegoutQuote(pegoutQuoteMock)
expect(acceptPegoutQuote).toBeCalledTimes(1)
})
test('change network correctly', () => {
const previousNetwork: string = (flyover as any).config.network
flyover.setNetwork('Testnet')
let actualNetwork: string = (flyover as any).config.network
expect(previousNetwork).not.toEqual(actualNetwork)
expect(actualNetwork).toBe('Testnet')
flyover.setNetwork('Regtest')
actualNetwork = (flyover as any).config.network
expect(actualNetwork).not.toBe('Testnet')
expect(actualNetwork).toBe('Regtest')
})
test('not allow insecure connections by default', () => {
const mainnet = new Flyover({ network: 'Mainnet', captchaTokenResolver: async () => Promise.resolve('') })
const testnet = new Flyover({ network: 'Testnet', captchaTokenResolver: async () => Promise.resolve('') })
const regtest = new Flyover({ network: 'Regtest', captchaTokenResolver: async () => Promise.resolve('') })
expect((mainnet as any).config.allowInsecureConnections).not.toBe(true)
expect((testnet as any).config.allowInsecureConnections).not.toBe(true)
expect((regtest as any).config.allowInsecureConnections).not.toBe(true)
})
test('ask for addresses checksum by default', () => {
const mainnet = new Flyover({ network: 'Mainnet', captchaTokenResolver: async () => Promise.resolve('') })
const testnet = new Flyover({ network: 'Testnet', captchaTokenResolver: async () => Promise.resolve('') })
const regtest = new Flyover({ network: 'Regtest', captchaTokenResolver: async () => Promise.resolve('') })
expect((mainnet as any).config.disableChecksum).not.toBe(true)
expect((testnet as any).config.disableChecksum).not.toBe(true)
expect((regtest as any).config.disableChecksum).not.toBe(true)
})
test('fail to get quotes when allowInsecureConnections is false and Provider apiBaseUrl is insecure', async () => {
(flyover as any).config.allowInsecureConnections = false
const provider = { ...providerMock }
provider.apiBaseUrl = 'http://localhost:1234'
flyover.useLiquidityProvider(provider)
await flyover.connectToRsk(rskConnectionMock)
await expect(flyover.getQuotes(quoteRequestMock)).rejects
.toThrow('Provider API base URL is not secure. Please enable insecure connections on Flyover configuration')
})
test('fail to get pegout quotes when allowInsecureConnections is false and Provider apiBaseUrl is insecure', async () => {
(flyover as any).config.allowInsecureConnections = false
const provider = { ...providerMock }
provider.apiBaseUrl = 'http://localhost:1234'
flyover.useLiquidityProvider(provider)
await flyover.connectToRsk(rskConnectionMock)
await expect(flyover.getPegoutQuotes(pegoutQuoteRequestMock)).rejects
.toThrow('Provider API base URL is not secure. Please enable insecure connections on Flyover configuration')
})
test('fail to accept quote when allowInsecureConnections is false and Provider apiBaseUrl is insecure', async () => {
(flyover as any).config.allowInsecureConnections = false
const provider = { ...providerMock }
provider.apiBaseUrl = 'http://localhost:1234'
flyover.useLiquidityProvider(provider)
await expect(flyover.acceptQuote(quoteMock)).rejects.toThrow('Provider API base URL is not secure. Please enable insecure connections on Flyover configuration')
})
test('fail to accept pegout quote when allowInsecureConnections is false and Provider apiBaseUrl is insecure', async () => {
(flyover as any).config.allowInsecureConnections = false
const provider = { ...providerMock }
provider.apiBaseUrl = 'http://localhost:1234'
flyover.useLiquidityProvider(provider)
await expect(flyover.acceptPegoutQuote(pegoutQuoteMock)).rejects.toThrow('Provider API base URL is not secure. Please enable insecure connections on Flyover configuration')
})
test('generate QR code from Bitcoin address', async () => {
const qrCode = await flyover.generateQrCode(
'mq4kBDAL4yDJBdd1qJk5jEffkJxvNdLxeF',
'1.4455',
'rsk'
)
expect(qrCode).toBe(
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKQAAACkCAYAAAAZtYVBAAAAAklEQVR4AewaftIAAAYwSURBVO3BQY4cy5LAQDLQ978yR0tfJZCoaineHzezP1jrEoe1LnJY6yKHtS5yWOsih7UucljrIoe1LnJY6yKHtS5yWOsih7UucljrIoe1LnJY6yKHtS7yw4dU/qaKSWWqeKLypGJSmSomlU9UPFF5UvFE5W+q+MRhrYsc1rrIYa2L/PBlFd+k8qTiiconKj5RMal8omJSmSqeVH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TypeKIyVTxRmSomlScVTyomlaniicq/dFjrIoe1LnJY6yI/fEjlExVPKiaVJypTxW+qeKIyVUwqb6hMFZPKVDGpTBWfqPimw1oXOax1kcNaF7E/+ItUpoonKlPFpDJVTCpTxaQyVUwqTyomlU9UTCpvVLyh8qRiUpkqvumw1kUOa13ksNZFfvhlKp+omFQ+oTJVTCpvqLxR8UTlScWk8kRlqnhS8aTiNx3WushhrYsc1rqI/cEHVP6mijdUnlRMKlPFGypTxaTypGJS+ZcqJpUnFZ84rHWRw1oXOax1kR8+VPEvqbxRMam8ofKkYlKZKp6oTBVPVKaKN1SmiicVv+mw1kUOa13ksNZFfviQyt9U8UbFpDJVPFF5UjGpTBVvVDxReUNlqnii8kbFNx3WushhrYsc1rrID19W8U0qTyomlUnlicpU8U0qU8Wk8kbFpPKk4o2Kf+mw1kUOa13ksNZFfvhlKm9UvKHyiYpJZap4o2JSmVSmim9S+U0qU8U3Hda6yGGtixzWusgP/3EVT1TeqJhUpopJ5UnFpDKpTBWTylTxpGJS+aaK33RY6yKHtS5yWOsiP/yPUZkqJpUnKp+oeFLxTRVPKp6oTCpTxd90WOsih7UucljrIj/8sop/SeWJyicqJpWp4g2VJyqfqHhS8S8d1rrIYa2LHNa6yA9fpvI3qTyp+CaVqWKqeKLymyomlUnlm1Smik8c1rrIYa2LHNa6iP3BWpc4rHWRw1oXOax1kcNaFzmsdZHDWhc5rHWRw1oXOax1kcNaFzmsdZHDWhc5rHWRw1oXOax1kf8DPf4GaSKydeEAAAAASUVORK5CYII='
)
})
test('generate QR code from RSK address', async () => {
const qrCode = await flyover.generateQrCode(
'0x9D93929A9099be4355fC2389FbF253982F9dF47c',
'10000',
'bitcoin'
)
expect(qrCode).toBe(
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKQAAACkCAYAAAAZtYVBAAAAAklEQVR4AewaftIAAAYBSURBVO3BQY4kRxLAQDLQ//8yd45+SiBR1aOQ1s3sD9a6xGGtixzWushhrYsc1rrIYa2LHN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ushhrYsc1rrIDx+qeKIyVUwVb6j8TSpTxaQyVTxRmSomlanijYpJZVL5hMqTik8c1rrIYa2LHNa6yA8fUnlS8QmVN1SmiknlScWkMqlMFZPKk4pJ5Z9U8YbKVPFNh7UucljrIoe1LvLDX6bypGKq+KaK31TxRGWqeKLyhsonVKaKqWJSmSo+cVjrIoe1LnJY6yI/fFnFpDJVvKEyVTypeKIyVXyTylTxROUTFW+oTCpTxaTypOKbDmtd5LDWRQ5rXeSHy6hMFU9UpopJZap4ovJNKm9UPFH5popJ5UnFpDJVfOKw1kUOa13ksNZFfvhlFZPKGypTxROVqWJSeVLxiYpJ5Q2VJxWTyidUpopJ5W86rHWRw1oXOax1kR8+VPFGxd+kMlW8oTJVPFF5UjGpTBWfqHhD5SaHtS5yWOsih7Uu8sOHVP6miqniDZWp4t9E5Q2VqeKJylQxqUwV33RY6yKHtS5yWOsiP3xZxTepPFF5o2JS+YTKVDGpPKl4ojJVTCpPKj6hMlVMKlPFJw5rXeSw1kUOa13kh1+m8kbFJyreqJhUnqhMFW+oPKmYKt5Q+UTFE5Wp4psOa13ksNZFDmtd5If/cypTxaTyiYpPqEwVb1RMKp+o+E2HtS5yWOsih7Uu8sN/jMonVKaKN1SmiknlScUbFZPKpDJVvKEyVfymw1oXOax1kcNaF/nhl1X8popJZar4hMpUMalMFZPKVPFNKlPFGypPKv6mw1oXOax1kcNaF/nhy1T+JpVPqDypeFIxqUwVT1SeVHxCZap4UjGpPKn4psNaFzmsdZHDWhexP1jrEoe1LnJY6yKHtS5yWOsih7UucljrIoe1LnJY6yKHtS5yWOsih7UucljrIoe1LnJY6yKHtS7yP31d3Ga+N5OzAAAAAElFTkSuQmCC'
)
})
test('throw error when generating code from invalid address', async () => {
await expect(
flyover.generateQrCode('ricardomilos<3', '1000000000', 'rsk')
).rejects.toThrow('Only Bitcoin and RSK addresses are supported')
})
test('validate correclty if its connected to network', async () => {
const connected = new Flyover({
network: 'Regtest',
rskConnection: rskConnectionMock,
captchaTokenResolver: async () => Promise.resolve('')
})
const notConnected = new Flyover({
network: 'Regtest',
captchaTokenResolver: async () => Promise.resolve('')
})
const connectedResult = await connected.isConnected()
const notConnectedResult = await notConnected.isConnected()
expect(connectedResult).toBe(true)
expect(notConnectedResult).toBe(false)
})
test('throw error when trying to connect with an existing connection', async () => {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const otherConenction = jest.mocked({} as BlockchainConnection)
const connected = new Flyover({
network: 'Regtest',
rskConnection: rskConnectionMock,
captchaTokenResolver: async () => Promise.resolve('')
})
await expect(connected.connectToRsk(otherConenction)).rejects.toThrow('already connected to Rsk network')
})
test('connect successfully to RSK', async () => {
expect(flyover).toEqual(expect.objectContaining(
{
config: expect.not.objectContaining({ rskConnection: expect.anything() })
}
))
await flyover.connectToRsk(rskConnectionMock)
expect(flyover).toEqual(expect.objectContaining(
{
config: expect.objectContaining({ rskConnection: expect.anything() })
}
))
})
test('throw error if depositPegout is executed without a RSK connection', async () => {
await expect(flyover.depositPegout(pegoutQuoteMock, '0x1234', BigInt(800))).rejects.toThrow('Not connected to RSK')
})
test('execute deposit pegout successfully', async () => {
await flyover.connectToRsk(rskConnectionMock)
const amount = BigInt(500)
await flyover.depositPegout(pegoutQuoteMock, signatureMock, amount)
expect(depositPegout).toBeCalledTimes(1)
expect(depositPegout).toBeCalledWith(pegoutQuoteMock, signatureMock, amount, expect.any(LiquidityBridgeContract))
})
test('create LBC instance during depositPegout if not created before', async () => {
await flyover.connectToRsk(rskConnectionMock)
const amount = BigInt(500)
expect(flyover).not.toHaveProperty('liquidityBridgeContract')
await flyover.depositPegout(pegoutQuoteMock, signatureMock, amount)
expect(flyover).not.toHaveProperty('liquidityBridgeContract', undefined)
})
test('throw error if refundPegout is executed without a RSK connection', async () => {
await expect(flyover.refundPegout(pegoutQuoteMock)).rejects.toThrow('Not connected to RSK')
})
test('execute refund pegout successfully', async () => {
await flyover.connectToRsk(rskConnectionMock)
await flyover.refundPegout(pegoutQuoteMock)
expect(refundPegout).toBeCalledTimes(1)
expect(refundPegout).toBeCalledWith(pegoutQuoteMock, expect.any(LiquidityBridgeContract))
})
test('create LBC instance during refundPegout if not created before', async () => {
await flyover.connectToRsk(rskConnectionMock)
expect(flyover).not.toHaveProperty('liquidityBridgeContract')
await flyover.refundPegout(pegoutQuoteMock)
expect(flyover).not.toHaveProperty('liquidityBridgeContract', undefined)
})
test('throw error if registerPegin is executed without a RSK connection', async () => {
await expect(flyover.registerPegin(registerPeginParamsMock)).rejects.toThrow('Not connected to RSK')
})
test('execute register pegin successfully', async () => {
await flyover.connectToRsk(rskConnectionMock)
await flyover.registerPegin(registerPeginParamsMock)
expect(registerPegin).toBeCalledTimes(1)
expect(registerPegin).toBeCalledWith(registerPeginParamsMock, expect.any(LiquidityBridgeContract))
})
test('create LBC instance during registerPegin if not created before', async () => {
await flyover.connectToRsk(rskConnectionMock)
expect(flyover).not.toHaveProperty('liquidityBridgeContract')
await flyover.registerPegin(registerPeginParamsMock)
expect(flyover).not.toHaveProperty('liquidityBridgeContract', undefined)
})
test('throw error if getQuotes is executed without a RSK connection', async () => {
flyover.useLiquidityProvider(providerMock)
await expect(flyover.getQuotes(quoteRequestMock)).rejects.toThrow('Not connected to RSK')
})
test('throw error if acceptQuote is executed without a RSK connection', async () => {
flyover.useLiquidityProvider(providerMock)
await expect(flyover.acceptQuote(quoteMock)).rejects.toThrow('Not connected to RSK')
})
test('throw error if unsupported network is used', async () => {
expect.assertions(2)
try {
flyover.setNetwork('MyNetwork' as any)
} catch (e: any) {
expect(e).toBeInstanceOf(FlyoverError)
expect(e.details).toBe('unsupported network')
}
})
test('invoke correctly supportsConversion', () => {
flyover.supportsConversion('rBTC', 'BTC')
expect(supportsConversion).toBeCalledTimes(1)
})
test('invoke correctly getMetadata', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.connectToRsk(rskConnectionMock)
await flyover.getMetadata()
expect(getMetadata).toBeCalledTimes(1)
})
test('invoke delete last quotes when provider changes', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.connectToRsk(rskConnectionMock)
await flyover.getQuotes(quoteRequestMock)
await flyover.getPegoutQuotes(pegoutQuoteRequestMock)
expect((flyover as any).lastPeginQuote).not.toBeNull()
expect((flyover as any).lastPegoutQuote).not.toBeNull()
const otherProvider = { ...providerMock }
flyover.useLiquidityProvider(otherProvider)
expect((flyover as any).lastPeginQuote).toBeNull()
expect((flyover as any).lastPegoutQuote).toBeNull()
})
test('save last pegin quote', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.connectToRsk(rskConnectionMock)
await flyover.getQuotes(quoteRequestMock)
expect((flyover as any).lastPeginQuote).not.toBeNull()
})
test('save last pegout quote', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.connectToRsk(rskConnectionMock)
await flyover.getPegoutQuotes(pegoutQuoteRequestMock)
expect((flyover as any).lastPegoutQuote).not.toBeNull()
})
test('fail to get metadata if liquidity provider has not been selected', async () => {
expect.assertions(2)
try {
await flyover.connectToRsk(rskConnectionMock)
await flyover.getMetadata()
} catch (e: any) {
expect(e).toBeInstanceOf(FlyoverError)
expect(e.details).toBe('You need to select a provider to fetch the metadata')
}
})
test('fail to get metadata if is not connected to the network', async () => {
expect.assertions(2)
try {
flyover.useLiquidityProvider(providerMock)
await flyover.getMetadata()
} catch (e: any) {
expect(e).toBeInstanceOf(Error)
expect(e.message).toBe('Not connected to RSK')
}
})
test('invoke correctly getPeginStatus', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.connectToRsk(rskConnectionMock)
await flyover.getPeginStatus('1234')
expect(getPeginStatus).toBeCalledTimes(1)
})
test('fail to get pegin status if liquidity provider has not been selected', async () => {
await expect(flyover.getPegoutStatus('1234')).rejects.toThrow('You need to select a provider to do this operation')
})
test('fail to get pegin status when allowInsecureConnections is false and Provider apiBaseUrl is insecure', async () => {
(flyover as any).config.allowInsecureConnections = false
const provider = { ...providerMock }
provider.apiBaseUrl = 'http://localhost:1234'
flyover.useLiquidityProvider(provider)
await flyover.connectToRsk(rskConnectionMock)
await expect(flyover.getPeginStatus('1234')).rejects
.toThrow('Provider API base URL is not secure. Please enable insecure connections on Flyover configuration')
})
test('invoke correctly getPegoutStatus', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.connectToRsk(rskConnectionMock)
await flyover.getPegoutStatus('5678')
expect(getPegoutStatus).toBeCalledTimes(1)
})
test('fail to get pegout status if liquidity provider has not been selected', async () => {
await expect(flyover.getPegoutStatus('5678')).rejects.toThrow('You need to select a provider to do this operation')
})
test('fail to get pegout status when allowInsecureConnections is false and Provider apiBaseUrl is insecure', async () => {
(flyover as any).config.allowInsecureConnections = false
const provider = { ...providerMock }
provider.apiBaseUrl = 'http://localhost:1234'
flyover.useLiquidityProvider(provider)
await flyover.connectToRsk(rskConnectionMock)
await expect(flyover.getPegoutStatus('5678')).rejects
.toThrow('Provider API base URL is not secure. Please enable insecure connections on Flyover configuration')
})
describe('getAvailableLiquidity', () => {
test('invoke correctly', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.getAvailableLiquidity()
expect(getAvailableLiquidity).toBeCalledTimes(1)
})
test('fail to get available liquidity if LP has not been selected', async () => {
await expect(flyover.getAvailableLiquidity()).rejects.toThrow('You need to select a provider to do this operation')
})
test('fail to get available liquidity when allowInsecureConnections is false and Provider apiBaseUrl is insecure', async () => {
(flyover as any).config.allowInsecureConnections = false
const provider = { ...providerMock }
provider.apiBaseUrl = 'http://localhost:1234'
flyover.useLiquidityProvider(provider)
await expect(flyover.getAvailableLiquidity()).rejects
.toThrow('Provider API base URL is not secure. Please enable insecure connections on Flyover configuration')
})
})
describe('validatePeginTransaction method should', () => {
const params: ValidatePeginTransactionParams = {
quoteInfo: quoteMock,
acceptInfo: {
signature: signatureMock,
bitcoinDepositAddressHash: '2MvkytopbHAGgTwrpQjpGVM5WZYvujPqf9u'
},
btcTx: '010203'
}
const options: ValidatePeginTransactionOptions = { throwError: true }
test('invoke correctly validatePeginTransaction', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.connectToRsk(rskConnectionMock)
await flyover.validatePeginTransaction(params, options)
expect(validatePeginTransaction).toBeCalledTimes(1)
expect(validatePeginTransaction).toBeCalledWith(
{
config: expect.objectContaining({
network: 'Regtest',
allowInsecureConnections: true
}),
bridge: expect.any(RskBridge),
lbc: expect.any(LiquidityBridgeContract),
provider: providerMock
},
params,
options
)
})
test('fail if LP has not been selected', async () => {
await flyover.connectToRsk(rskConnectionMock)
await expect(flyover.validatePeginTransaction(params)).rejects.toThrow('You need to select a provider to do this operation')
})
test('create LBC instance if not created before', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.connectToRsk(rskConnectionMock)
expect(flyover).not.toHaveProperty('liquidityBridgeContract')
await flyover.validatePeginTransaction(params)
expect(flyover).not.toHaveProperty('liquidityBridgeContract', undefined)
})
test('create RskBridge instance if not created before', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.connectToRsk(rskConnectionMock)
expect(flyover).not.toHaveProperty('rskBridge')
await flyover.validatePeginTransaction(params)
expect(flyover).not.toHaveProperty('rskBridge', undefined)
})
})
describe('isQuotePaid method should', () => {
test('fail if liquidity provider has not been selected', async () => {
await flyover.connectToRsk(rskConnectionMock)
await expect(flyover.isQuotePaid('testQuoteHash', 'pegin'))
.rejects.toThrow('You need to select a provider to do this operation')
})
describe('pegin quotes', () => {
test('invoke correctly isQuotePaid external function', async () => {
flyover.useLiquidityProvider(providerMock)
await flyover.connectToRsk(rskConnectionMock)
await flyover.isQuotePaid('testQuoteHash', 'pegin')
expect(isPeginQuotePaid).toBeCalledTimes(1)
expect(isPeginQuotePaid).toBeCalledWith(
(flyover as any).httpClient, // httpClient
providerMock, // liquidityProvider
'testQuoteHash', // quoteHash
rskConnectionMock // rskConnection
)
})
test('fail when allowInsecureConnections is false and Provider apiBaseUrl is insecure', async () => {
(flyover as any).config.allowInsecureConnections = false
const provider = { ...providerMock }
provider.apiBaseUrl = 'http://localhost:1234'
flyover.useLiquidityProvider(provider)
await flyover.connectToRsk(rskConnectionMock)
await expect(flyover.isQuotePaid('testQuoteHash', 'pegin'))
.rejects.toThrow('Provider API base URL is not secure. Please enable insecure connections on Flyover configuration')
})
test('fail if not connected to RSK', async () => {
// Create a new Flyover instance without RSK connection
const disconnectedFlyover = new Flyover({
network: FAKE_NETWORK,
allowInsecureConnections: true,
captchaTokenResolver: async () => Promise.resolve('')
})
// Set a liquidity provider
disconnectedFlyover.useLiquidityProvider(providerMock)
// Connect to RSK with a connection that returns undefined for chain height
const mockConnectionWithNoHeight = {
...rskConnectionMock,
getChainHeight: jest.fn().mockImplementation(async () => Promise.resolve(undefined))
} as unknown as BlockchainConnection
await disconnectedFlyover.connectToRsk(mockConnectionWithNoHeight)
// Expect the method to throw an error about needing to connect to RSK
await expect(disconnectedFlyover.isQuotePaid('testQuoteHash', 'pegin'))
.rejects.toThrow('Before calling isQuotePaid for pegin quotes, you need to connect to RSK using Flyover.connectToRsk')
})
})
describe('pegout quotes', () => {
const bitcoinDataSourceMock: BitcoinDataSource = { getTransactionAsHex: jest.fn() } as unknown as BitcoinDataSource
beforeEach(() => {
(isPegoutQuotePaid as jest.Mock).mockImplementation(async () => Promise.resolve({ isPaid: true }))
})
test('invoke correctly isPegoutQuotePaid external function', async () => {
flyover.useLiquidityProvider(providerMock)
flyover.connectToBitcoin(bitcoinDataSourceMock)
const result = await flyover.isQuotePaid('testQuoteHash', 'pegout')
expect(result).toEqual({ isPaid: true })
expect(isPegoutQuotePaid).toBeCalledTimes(1)
expect(isPegoutQuotePaid).toBeCalledWith(
(flyover as any).httpClient, // httpClient
providerMock, // liquidityProvider
'testQuoteHash', // quoteHash
bitcoinDataSourceMock // bitcoinDataSource
)
})
test('fail when bitcoinDataSource is not connected', async () => {
flyover.useLiquidityProvider(providerMock)
await expect(flyover.isQuotePaid('testQuoteHash', 'pegout'))
.rejects
.toThrow('Before calling isQuotePaid for pegout quotes, you need to connect to Bitcoin using Flyover.connectToBitcoin')
})
test('return isPaid true when quote is paid', async () => {
flyover.useLiquidityProvider(providerMock)
flyover.connectToBitcoin(bitcoinDataSourceMock)
; (isPegoutQuotePaid as jest.Mock).mockImplementation(async () => Promise.resolve({ isPaid: true }))
const result = await flyover.isQuotePaid('testQuoteHash', 'pegout')
expect(result).toEqual({ isPaid: true })
})
test('return isPaid false when quote is not paid', async () => {
flyover.useLiquidityProvider(providerMock)
flyover.connectToBitcoin(bitcoinDataSourceMock)
; (isPegoutQuotePaid as jest.Mock).mockImplementation(async () => Promise.resolve({ isPaid: false }))
const result = await flyover.isQuotePaid('testQuoteHash', 'pegout')
expect(result).toEqual({ isPaid: false })
})
test('handle errors from isPegoutQuotePaid function', async () => {
flyover.useLiquidityProvider(providerMock)
flyover.connectToBitcoin(bitcoinDataSourceMock)
const errorMessage = 'Failed to check quote payment status'
; (isPegoutQuotePaid as jest.Mock).mockImplementation(async () => Promise.reject(new Error(errorMessage)))
await expect(flyover.isQuotePaid('testQuoteHash', 'pegout'))
.rejects
.toThrow(errorMessage)
})
test('fail when invalid type of operation is provided', async () => {
flyover.useLiquidityProvider(providerMock)
await expect(flyover.isQuotePaid('testQuoteHash', 'notPeginNotPegoutOperation' as any))
.rejects
.toThrow('Invalid type of operation')
})
})
})
})