-
Notifications
You must be signed in to change notification settings - Fork 60
/
OceanPool.ts
1027 lines (961 loc) 路 30.3 KB
/
OceanPool.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
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Web3 from 'web3'
import { AbiItem } from 'web3-utils/types'
import { TransactionReceipt } from 'web3-core'
import { Pool } from './Pool'
import { EventData, Filter } from 'web3-eth-contract'
import BigNumber from 'bignumber.js'
import { SubscribablePromise, Logger } from '../utils'
declare type PoolTransactionType = 'swap' | 'join' | 'exit'
const POOL_MAX_AMOUNT_IN_LIMIT = 0.25 // maximum 1/4 of the pool reserve
const POOL_MAX_AMOUNT_OUT_LIMIT = 0.25 // maximum 1/4 of the pool reserve
export interface PoolDetails {
poolAddress: string
tokens: string[]
}
export interface TokensReceived {
dtAmount: string
oceanAmount: string
}
export interface PoolTransaction {
poolAddress: string
dtAddress: string
caller: string
transactionHash: string
blockNumber: number
timestamp: number
tokenIn?: string
tokenOut?: string
tokenAmountIn?: string
tokenAmountOut?: string
type: PoolTransactionType
}
export enum PoolCreateProgressStep {
CreatingPool,
ApprovingDatatoken,
ApprovingOcean,
SetupPool
}
/**
* Ocean Pools submodule exposed under ocean.pool
*/
export class OceanPool extends Pool {
public oceanAddress: string = null
public dtAddress: string = null
constructor(
web3: Web3,
logger: Logger,
factoryABI: AbiItem | AbiItem[] = null,
poolABI: AbiItem | AbiItem[] = null,
factoryAddress: string = null,
oceanAddress: string = null,
gaslimit?: number
) {
super(web3, logger, factoryABI, poolABI, factoryAddress, gaslimit)
if (oceanAddress) {
this.oceanAddress = oceanAddress
}
}
/**
* Create DataToken pool
@param {String} account
* @param {String} dtAddress DataToken address
* @param {String} dtAmount DataToken amount
* @param {String} dtWeight DataToken weight
* @param {String} oceanAmount Ocean amount
* @param {String} fee Swap fee. E.g. to get a 0.1% swapFee use `0.001`. The maximum allowed swapFee is `0.1` (10%).
* @return {String}
*/
public create(
account: string,
dtAddress: string,
dtAmount: string,
dtWeight: string,
oceanAmount: string,
fee: string
): SubscribablePromise<PoolCreateProgressStep, TransactionReceipt> {
if (this.oceanAddress == null) {
this.logger.error('ERROR: oceanAddress is not defined')
return null
}
if (parseFloat(fee) > 0.1) {
this.logger.error('ERROR: Swap fee too high. The maximum allowed swapFee is 10%')
return null
}
if (parseFloat(dtAmount) < 2) {
this.logger.error('ERROR: Amount of DT is too low')
return null
}
if (parseFloat(dtWeight) > 9 || parseFloat(dtWeight) < 1) {
this.logger.error('ERROR: Weight out of bounds (min 1, max9)')
return null
}
return new SubscribablePromise(async (observer) => {
observer.next(PoolCreateProgressStep.CreatingPool)
const createTxid = await super.createPool(account)
if (!createTxid) {
this.logger.error('ERROR: Failed to call approve DT token')
return null
}
const address = createTxid.events.BPoolRegistered.returnValues[0]
const oceanWeight = 10 - parseFloat(dtWeight)
this.dtAddress = dtAddress
observer.next(PoolCreateProgressStep.ApprovingDatatoken)
let txid
txid = await this.approve(
account,
dtAddress,
address,
this.web3.utils.toWei(String(dtAmount))
)
if (!txid) {
this.logger.error('ERROR: Failed to call approve DT token')
return null
}
observer.next(PoolCreateProgressStep.ApprovingOcean)
txid = await this.approve(
account,
this.oceanAddress,
address,
this.web3.utils.toWei(String(oceanAmount))
)
if (!txid) {
this.logger.error('ERROR: Failed to call approve OCEAN token')
return null
}
observer.next(PoolCreateProgressStep.SetupPool)
txid = await super.setup(
account,
address,
dtAddress,
this.web3.utils.toWei(String(dtAmount)),
this.web3.utils.toWei(String(dtWeight)),
this.oceanAddress,
this.web3.utils.toWei(String(oceanAmount)),
this.web3.utils.toWei(String(oceanWeight)),
this.web3.utils.toWei(fee)
)
if (!txid) {
this.logger.error('ERROR: Failed to create a new pool')
return null
}
return createTxid
})
}
/**
* Get DataToken address of token in this pool
* @param {String} account
* @param {String} poolAddress
* @return {string}
*/
public async getDTAddress(poolAddress: string): Promise<string> {
this.dtAddress = null
const tokens = await this.getCurrentTokens(poolAddress)
let token: string
for (token of tokens) {
// TODO: Potential timing attack, left side: true
if (token !== this.oceanAddress) this.dtAddress = token
}
return this.dtAddress
}
/**
* Get Ocean Token balance of a pool
* @param {String} poolAddress
* @return {String}
*/
public async getOceanReserve(poolAddress: string): Promise<string> {
if (this.oceanAddress == null) {
this.logger.error('ERROR: oceanAddress is not defined')
return null
}
return super.getReserve(poolAddress, this.oceanAddress)
}
/**
* Get datatoken balance of a pool
* @param {String} poolAddress
* @return {String}
*/
public async getDTReserve(poolAddress: string): Promise<string> {
const dtAddress = await this.getDTAddress(poolAddress)
return super.getReserve(poolAddress, dtAddress)
}
/**
* Returns max amount that you can buy.
* @param poolAddress
* @param tokenAddress
*/
public async getMaxBuyQuantity(
poolAddress: string,
tokenAddress: string
): Promise<string> {
const balance = await super.getReserve(poolAddress, tokenAddress)
return String(parseFloat(balance) / 3)
}
/**
* Returns max amount of OCEAN that you can buy.
* @param poolAddress
* @param tokenAddress
*/
public async getOceanMaxBuyQuantity(poolAddress: string): Promise<string> {
return this.getMaxBuyQuantity(poolAddress, this.oceanAddress)
}
/**
* Returns max amount of DT that you can buy.
* @param poolAddress
* @param tokenAddress
*/
public async getDTMaxBuyQuantity(poolAddress: string): Promise<string> {
return this.getMaxBuyQuantity(poolAddress, await this.getDTAddress(poolAddress))
}
/**
* Returns tokenInAmount required to get tokenOutAmount
* @param poolAddress
* @param tokenInAddress
* @param tokenOutAddress
* @param tokenOutAmount
*/
public async calcInGivenOut(
poolAddress: string,
tokenInAddress: string,
tokenOutAddress: string,
tokenOutAmount: string
): Promise<string> {
const result = await super.calcInGivenOut(
poolAddress,
await super.getReserve(poolAddress, tokenInAddress),
await super.getDenormalizedWeight(poolAddress, tokenInAddress),
await super.getReserve(poolAddress, tokenOutAddress),
await super.getDenormalizedWeight(poolAddress, tokenOutAddress),
tokenOutAmount,
await this.getSwapFee(poolAddress)
)
return result
}
/**
* Returns tokenOutAmount given tokenInAmount
* @param poolAddress
* @param tokenInAddress
* @param tokenOutAddress
* @param tokenInAmount
*/
public async calcOutGivenIn(
poolAddress: string,
tokenInAddress: string,
tokenOutAddress: string,
tokenInAmount: string
): Promise<string> {
const result = await super.calcOutGivenIn(
poolAddress,
await super.getReserve(poolAddress, tokenInAddress),
await super.getDenormalizedWeight(poolAddress, tokenInAddress),
await super.getReserve(poolAddress, tokenOutAddress),
await super.getDenormalizedWeight(poolAddress, tokenOutAddress),
tokenInAmount,
await super.getSwapFee(poolAddress)
)
return result
}
/**
* Returns no of shares receved for adding a token to the pool
* @param poolAddress
* @param tokenInAddress
* @param tokenInAmount
*/
public async calcPoolOutGivenSingleIn(
poolAddress: string,
tokenInAddress: string,
tokenInAmount: string
): Promise<string> {
const result = super.calcPoolOutGivenSingleIn(
poolAddress,
await super.getReserve(poolAddress, tokenInAddress),
await super.getDenormalizedWeight(poolAddress, tokenInAddress),
await super.getPoolSharesTotalSupply(poolAddress),
await super.getTotalDenormalizedWeight(poolAddress),
tokenInAmount,
await super.getSwapFee(poolAddress)
)
return result
}
/**
* Returns no of tokens required to get a specific no of poolShares
* @param poolAddress
* @param tokenInAddress
* @param poolShares
*/
public async calcSingleInGivenPoolOut(
poolAddress: string,
tokenInAddress: string,
poolShares: string
): Promise<string> {
const result = super.calcSingleInGivenPoolOut(
poolAddress,
await super.getReserve(poolAddress, tokenInAddress),
await super.getDenormalizedWeight(poolAddress, tokenInAddress),
await super.getPoolSharesTotalSupply(poolAddress),
await super.getTotalDenormalizedWeight(poolAddress),
poolShares,
await super.getSwapFee(poolAddress)
)
return result
}
/**
* Returns no of tokens received for spending a specific no of poolShares
* @param poolAddress
* @param tokenOutAddress
* @param poolShares
*/
public async calcSingleOutGivenPoolIn(
poolAddress: string,
tokenOutAddress: string,
poolShares: string
): Promise<string> {
const result = super.calcSingleOutGivenPoolIn(
poolAddress,
await super.getReserve(poolAddress, tokenOutAddress),
await super.getDenormalizedWeight(poolAddress, tokenOutAddress),
await super.getPoolSharesTotalSupply(poolAddress),
await super.getTotalDenormalizedWeight(poolAddress),
poolShares,
await super.getSwapFee(poolAddress)
)
return result
}
/**
* Returns no of pool shares required to receive a specified amount of tokens
* @param poolAddress
* @param tokenOutAddress
* @param tokenOutAmount
*/
public async calcPoolInGivenSingleOut(
poolAddress: string,
tokenOutAddress: string,
tokenOutAmount: string
): Promise<string> {
const result = super.calcPoolInGivenSingleOut(
poolAddress,
await super.getReserve(poolAddress, tokenOutAddress),
await super.getDenormalizedWeight(poolAddress, tokenOutAddress),
await super.getPoolSharesTotalSupply(poolAddress),
await super.getTotalDenormalizedWeight(poolAddress),
tokenOutAmount,
await super.getSwapFee(poolAddress)
)
return result
}
/**
* Returns no of pool shares required to receive specified amount of DT
* @param poolAddress
* @param dtAmount
*/
public async getPoolSharesRequiredToRemoveDT(
poolAddress: string,
dtAmount: string
): Promise<string> {
const dtAddress = await this.getDTAddress(poolAddress)
return this.calcPoolInGivenSingleOut(poolAddress, dtAddress, dtAmount)
}
/**
* Returns DT amnount received after spending poolShares
* @param poolAddress
* @param poolShares
*/
public async getDTRemovedforPoolShares(
poolAddress: string,
poolShares: string
): Promise<string> {
const dtAddress = await this.getDTAddress(poolAddress)
return this.calcSingleOutGivenPoolIn(poolAddress, dtAddress, poolShares)
}
/**
* Returns no of pool shares required to receive specified amount of DT
* @param poolAddress
* @param dtAmount
*/
public async getPoolSharesRequiredToRemoveOcean(
poolAddress: string,
oceanAmount: string
): Promise<string> {
return this.calcPoolInGivenSingleOut(poolAddress, this.oceanAddress, oceanAmount)
}
/**
* Returns Ocean amnount received after spending poolShares
* @param poolAddress
* @param poolShares
*/
public async getOceanRemovedforPoolShares(
poolAddress: string,
poolShares: string
): Promise<string> {
return this.calcSingleOutGivenPoolIn(poolAddress, this.oceanAddress, poolShares)
}
/**
* Returns Datatoken & Ocean amounts received after spending poolShares
* @param {String} poolAddress
* @param {String} poolShares
* @return {TokensReceived}
*/
public async getTokensRemovedforPoolShares(
poolAddress: string,
poolShares: string
): Promise<TokensReceived> {
try {
const totalPoolTokens = await this.getPoolSharesTotalSupply(poolAddress)
const dtReserve = await this.getDTReserve(poolAddress)
const oceanReserve = await this.getOceanReserve(poolAddress)
const dtAmount = `${
(Number(poolShares) / Number(totalPoolTokens)) * Number(dtReserve)
}`
const oceanAmount = `${
(Number(poolShares) / Number(totalPoolTokens)) * Number(oceanReserve)
}`
return { dtAmount, oceanAmount }
} catch (e) {
this.logger.error(`ERROR: Unable to get token info. ${e.message}`)
}
}
/**
* Returns max DT amount that you can add to the pool
* @param poolAddress
*/
public async getDTMaxAddLiquidity(poolAddress: string): Promise<string> {
const dtAddress = await this.getDTAddress(poolAddress)
return this.getMaxAddLiquidity(poolAddress, dtAddress)
}
/**
* Returns max Ocean amount that you can add to the pool
* @param poolAddress
*/
public async getOceanMaxAddLiquidity(poolAddress: string): Promise<string> {
return this.getMaxAddLiquidity(poolAddress, this.oceanAddress)
}
/**
* Returns max amount of tokens that you can add to the pool
* @param poolAddress
* @param tokenAddress
*/
public async getMaxAddLiquidity(
poolAddress: string,
tokenAddress: string
): Promise<string> {
const balance = await super.getReserve(poolAddress, tokenAddress)
if (parseFloat(balance) > 0) {
const result = new BigNumber(this.web3.utils.toWei(balance))
.multipliedBy(POOL_MAX_AMOUNT_IN_LIMIT)
.integerValue(BigNumber.ROUND_DOWN)
.minus(1)
return this.web3.utils.fromWei(result.toString(10))
} else return '0'
}
/**
* Returns max amount of tokens that you can withdraw from the pool
* @param poolAddress
* @param tokenAddress
*/
public async getMaxRemoveLiquidity(
poolAddress: string,
tokenAddress: string
): Promise<string> {
const balance = await super.getReserve(poolAddress, tokenAddress)
if (parseFloat(balance) > 0) {
const result = new BigNumber(this.web3.utils.toWei(balance))
.multipliedBy(POOL_MAX_AMOUNT_OUT_LIMIT)
.integerValue(BigNumber.ROUND_DOWN)
.minus(1)
return this.web3.utils.fromWei(result.toString(10))
} else return '0'
}
/**
* Returns max amount of DT that you can withdraw from the pool
* @param poolAddress
* @param tokenAddress
*/
public async getDTMaxRemoveLiquidity(poolAddress: string): Promise<string> {
const dtAddress = await this.getDTAddress(poolAddress)
return this.getMaxRemoveLiquidity(poolAddress, dtAddress)
}
/**
* Returns max amount of Ocean that you can withdraw from the pool
* @param poolAddress
* @param tokenAddress
*/
public async getOceanMaxRemoveLiquidity(poolAddress: string): Promise<string> {
return this.getMaxRemoveLiquidity(poolAddress, this.oceanAddress)
}
/**
* Buy datatoken from a pool
* @param {String} account
* @param {String} poolAddress
* @param {String} amount datatoken amount
* @param {String} oceanAmount Ocean Token amount payed
* @param {String} maxPrice Maximum price to pay
* @return {TransactionReceipt}
*/
public async buyDT(
account: string,
poolAddress: string,
dtAmountWanted: string,
maxOceanAmount: string,
maxPrice?: string
): Promise<TransactionReceipt> {
if (this.oceanAddress == null) {
this.logger.error('ERROR: undefined ocean token contract address')
return null
}
const dtAddress = await this.getDTAddress(poolAddress)
if (
parseFloat(dtAmountWanted) > parseFloat(await this.getDTMaxBuyQuantity(poolAddress))
) {
this.logger.error('ERROR: Buy quantity exceeds quantity allowed')
return null
}
const calcInGivenOut = await this.getOceanNeeded(poolAddress, dtAmountWanted)
if (parseFloat(calcInGivenOut) > parseFloat(maxOceanAmount)) {
this.logger.error('ERROR: Not enough Ocean Tokens')
return null
}
// TODO - check balances first
const txid = await super.approve(
account,
this.oceanAddress,
poolAddress,
this.web3.utils.toWei(maxOceanAmount)
)
if (!txid) {
this.logger.error('ERROR: OCEAN approve failed')
return null
}
return this.swapExactAmountOut(
account,
poolAddress,
this.oceanAddress,
maxOceanAmount,
dtAddress,
dtAmountWanted,
maxPrice
)
}
/**
* Sell datatoken
* @param {String} account
* @param {String} poolAddress
* @param {String} amount datatoken amount to be sold
* @param {String} oceanAmount Ocean Token amount expected
* @param {String} maxPrice Minimum price to sell
* @return {TransactionReceipt}
*/
public async sellDT(
account: string,
poolAddress: string,
dtAmount: string,
oceanAmountWanted: string,
maxPrice?: string
): Promise<TransactionReceipt> {
if (this.oceanAddress == null) {
this.logger.error('ERROR: oceanAddress is not defined')
return null
}
const dtAddress = await this.getDTAddress(poolAddress)
if (
parseFloat(oceanAmountWanted) >
parseFloat(await this.getOceanMaxBuyQuantity(poolAddress))
) {
this.logger.error('ERROR: Buy quantity exceeds quantity allowed')
return null
}
const calcOutGivenIn = await this.getOceanReceived(poolAddress, dtAmount)
if (parseFloat(calcOutGivenIn) < parseFloat(oceanAmountWanted)) {
this.logger.error('ERROR: Not enough datatokens')
return null
}
const txid = await super.approve(
account,
dtAddress,
poolAddress,
this.web3.utils.toWei(dtAmount)
)
if (!txid) {
this.logger.error('ERROR: DT approve failed')
return null
}
return this.swapExactAmountIn(
account,
poolAddress,
dtAddress,
dtAmount,
this.oceanAddress,
oceanAmountWanted,
maxPrice
)
}
/**
* Add datatoken amount to pool liquidity
* @param {String} account
* @param {String} poolAddress
* @param {String} amount datatoken amount
* @return {TransactionReceipt}
*/
public async addDTLiquidity(
account: string,
poolAddress: string,
amount: string
): Promise<TransactionReceipt> {
const dtAddress = await this.getDTAddress(poolAddress)
const maxAmount = await this.getMaxAddLiquidity(poolAddress, dtAddress)
if (parseFloat(amount) > parseFloat(maxAmount)) {
this.logger.error('ERROR: Too much reserve to add')
return null
}
const txid = await super.approve(
account,
dtAddress,
poolAddress,
this.web3.utils.toWei(amount)
)
if (!txid) {
this.logger.error('ERROR: DT approve failed')
return null
}
const result = await super.joinswapExternAmountIn(
account,
poolAddress,
dtAddress,
amount,
'0'
)
return result
}
/**
* Remove datatoken amount from pool liquidity
* @param {String} account
* @param {String} poolAddress
* @param {String} amount datatoken amount
* @return {TransactionReceipt}
*/
public async removeDTLiquidity(
account: string,
poolAddress: string,
amount: string,
maximumPoolShares: string
): Promise<TransactionReceipt> {
const dtAddress = await this.getDTAddress(poolAddress)
const maxAmount = await this.getDTMaxRemoveLiquidity(poolAddress)
if (parseFloat(amount) > parseFloat(maxAmount)) {
this.logger.error('ERROR: Too much reserve to remove')
return null
}
const usershares = await this.sharesBalance(account, poolAddress)
if (parseFloat(usershares) < parseFloat(maximumPoolShares)) {
this.logger.error('ERROR: Not enough poolShares')
return null
}
const sharesRequired = await this.getPoolSharesRequiredToRemoveDT(poolAddress, amount)
if (parseFloat(maximumPoolShares) < parseFloat(sharesRequired)) {
this.logger.error('ERROR: Not enough poolShares')
return null
}
// Balancer bug fix
if (parseFloat(maximumPoolShares) < parseFloat(sharesRequired))
maximumPoolShares = String(parseFloat(maximumPoolShares) * 0.9999)
// Balance bug fix
return this.exitswapExternAmountOut(
account,
poolAddress,
dtAddress,
amount,
maximumPoolShares
)
}
/**
* Add Ocean Token amount to pool liquidity
* @param {String} account
* @param {String} poolAddress
* @param {String} amount Ocean Token amount in OCEAN
* @return {TransactionReceipt}
*/
public async addOceanLiquidity(
account: string,
poolAddress: string,
amount: string
): Promise<TransactionReceipt> {
if (this.oceanAddress == null) {
this.logger.error('ERROR: oceanAddress is not defined')
return null
}
const maxAmount = await this.getOceanMaxAddLiquidity(poolAddress)
if (parseFloat(amount) > parseFloat(maxAmount)) {
this.logger.error('ERROR: Too much reserve to add')
return null
}
const txid = await super.approve(
account,
this.oceanAddress,
poolAddress,
this.web3.utils.toWei(amount)
)
if (!txid) {
this.logger.error('ERROR: OCEAN approve failed')
return null
}
const result = await super.joinswapExternAmountIn(
account,
poolAddress,
this.oceanAddress,
amount,
'0'
)
return result
}
/**
* Remove Ocean Token amount from pool liquidity
* @param {String} account
* @param {String} poolAddress
* @param {String} amount Ocean Token amount in OCEAN
* @return {TransactionReceipt}
*/
public async removeOceanLiquidity(
account: string,
poolAddress: string,
amount: string,
maximumPoolShares: string
): Promise<TransactionReceipt> {
if (this.oceanAddress == null) {
this.logger.error('ERROR: oceanAddress is not defined')
return null
}
const maxAmount = await this.getOceanMaxRemoveLiquidity(poolAddress)
if (parseFloat(amount) > parseFloat(maxAmount)) {
this.logger.error('ERROR: Too much reserve to remove')
return null
}
const usershares = await this.sharesBalance(account, poolAddress)
if (parseFloat(usershares) < parseFloat(maximumPoolShares)) {
this.logger.error('ERROR: Not enough poolShares')
return null
}
const sharesRequired = await this.getPoolSharesRequiredToRemoveOcean(
poolAddress,
amount
)
if (parseFloat(maximumPoolShares) < parseFloat(sharesRequired)) {
this.logger.error('ERROR: Not enough poolShares')
return null
}
// Balancer bug fix
if (parseFloat(maximumPoolShares) < parseFloat(sharesRequired))
maximumPoolShares = String(parseFloat(maximumPoolShares) * 0.9999)
// Balance bug fix
return super.exitswapExternAmountOut(
account,
poolAddress,
this.oceanAddress,
amount,
maximumPoolShares
)
}
/**
* Remove pool liquidity
* @param {String} account
* @param {String} poolAddress
* @param {String} poolShares
* @param {String} minDT Minimum DT expected (defaults 0)
* @param {String} poolShares Minim Ocean expected (defaults 0)
* @return {TransactionReceipt}
*/
public async removePoolLiquidity(
account: string,
poolAddress: string,
poolShares: string,
minDT = '0',
minOcean = '0'
): Promise<TransactionReceipt> {
const usershares = await this.sharesBalance(account, poolAddress)
if (parseFloat(usershares) < parseFloat(poolShares)) {
this.logger.error('ERROR: Not enough poolShares')
return null
}
// Balancer bug fix
if (parseFloat(usershares) === parseFloat(poolShares))
poolShares = String(parseFloat(poolShares) * 0.9999)
// Balance bug fix
return this.exitPool(account, poolAddress, poolShares, [minDT, minOcean])
}
/**
* Get datatoken price from pool
* @param {String} poolAddress
* @return {String}
*/
public async getDTPrice(poolAddress: string): Promise<string> {
if (this.oceanAddress == null) {
this.logger.error('ERROR: oceanAddress is not defined')
return null
}
return this.getOceanNeeded(poolAddress, '1')
}
/**
* Search all pools that have datatoken in their composition
* @param {String} dtAddress
* @return {String[]}
*/
public async searchPoolforDT(dtAddress: string): Promise<string[]> {
const result: string[] = []
const factory = new this.web3.eth.Contract(this.factoryABI, this.factoryAddress)
const events = await factory.getPastEvents('BPoolRegistered', {
filter: {},
fromBlock: 0,
toBlock: 'latest'
})
events.sort((a, b) => (a.blockNumber > b.blockNumber ? 1 : -1))
for (let i = 0; i < events.length; i++) {
const constituents = await super.getCurrentTokens(events[i].returnValues[0])
if (constituents.includes(dtAddress)) result.push(events[i].returnValues[0])
}
return result
}
public async getOceanNeeded(poolAddress: string, dtRequired: string): Promise<string> {
const dtAddress = await this.getDTAddress(poolAddress)
return this.calcInGivenOut(poolAddress, this.oceanAddress, dtAddress, dtRequired)
}
public async getOceanReceived(poolAddress: string, dtSold: string): Promise<string> {
const dtAddress = await this.getDTAddress(poolAddress)
return this.calcOutGivenIn(poolAddress, dtAddress, this.oceanAddress, dtSold)
}
public async getDTNeeded(poolAddress: string, OceanRequired: string): Promise<string> {
const dtAddress = await this.getDTAddress(poolAddress)
return this.calcInGivenOut(poolAddress, dtAddress, this.oceanAddress, OceanRequired)
}
/**
* Search all pools created by an address
* @param {String} account If empty, will return all pools ever created by anybody
* @return {PoolDetails[]}
*/
public async getPoolsbyCreator(account?: string): Promise<PoolDetails[]> {
const result: PoolDetails[] = []
const factory = new this.web3.eth.Contract(this.factoryABI, this.factoryAddress)
const events = await factory.getPastEvents('BPoolRegistered', {
filter: account ? { registeredBy: account } : {},
fromBlock: 0,
toBlock: 'latest'
})
for (let i = 0; i < events.length; i++) {
if (!account || events[i].returnValues[1].toLowerCase() === account.toLowerCase())
result.push(await this.getPoolDetails(events[i].returnValues[0]))
}
return result
}
/**
* Get pool details
* @param {String} poolAddress Pool address
* @return {PoolDetails}
*/
public async getPoolDetails(poolAddress: string): Promise<PoolDetails> {
const tokens = await super.getFinalTokens(poolAddress)
const details: PoolDetails = { poolAddress, tokens }
return details
}
/**
* Get all actions from a pool (join,exit,swap)
* @param {String} poolAddress Pool address
* @param {String} account Optional, filter for this address
* @return {PoolTransaction[]}
*/
public async getPoolLogs(
poolAddress: string,
account?: string
): Promise<PoolTransaction[]> {
const results: PoolTransaction[] = []
const pool = new this.web3.eth.Contract(this.poolABI, poolAddress)
const dtAddress = await this.getDTAddress(poolAddress)
const filter: Filter = account ? { caller: account } : {}
let events: EventData[]
events = await pool.getPastEvents('LOG_SWAP', {
filter,
fromBlock: 0,
toBlock: 'latest'
})
for (let i = 0; i < events.length; i++) {
if (!account || events[i].returnValues[0].toLowerCase() === account.toLowerCase())
results.push(await this.getEventData('swap', poolAddress, dtAddress, events[i]))
}
events = await pool.getPastEvents('LOG_JOIN', {
filter,
fromBlock: 0,
toBlock: 'latest'
})
for (let i = 0; i < events.length; i++) {
if (!account || events[i].returnValues[0].toLowerCase() === account.toLowerCase())
results.push(await this.getEventData('join', poolAddress, dtAddress, events[i]))
}
events = await pool.getPastEvents('LOG_EXIT', {
filter,
fromBlock: 0,
toBlock: 'latest'
})
for (let i = 0; i < events.length; i++) {
if (!account || events[i].returnValues[0].toLowerCase() === account.toLowerCase())
results.push(await this.getEventData('exit', poolAddress, dtAddress, events[i]))
}
return results
}
/**
* Get all logs on all pools for a specific address
* @param {String} account
* @return {PoolTransaction[]}
*/
public async getAllPoolLogs(account: string): Promise<PoolTransaction[]> {
const results: PoolTransaction[] = []
const factory = new this.web3.eth.Contract(this.factoryABI, this.factoryAddress)
const events = await factory.getPastEvents('BPoolRegistered', {
filter: {},
fromBlock: 0,
toBlock: 'latest'
})
for (let i = 0; i < events.length; i++) {
const logs = await this.getPoolLogs(events[i].returnValues[0], account)
for (let j = 0; j < logs.length; j++) results.push(logs[j])
}
return results
}
private async getEventData(
type: PoolTransactionType,
poolAddress: string,
dtAddress: string,
data: EventData
): Promise<PoolTransaction> {
const blockDetails = await this.web3.eth.getBlock(data.blockNumber)
let result: PoolTransaction = {
poolAddress,
dtAddress,
caller: data.returnValues[0],
transactionHash: data.transactionHash,
blockNumber: data.blockNumber,
timestamp: parseInt(String(blockDetails.timestamp)),
type
}
switch (type) {