@drift-labs/sdk 0.1.12 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +2 -2
  2. package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts +1 -0
  3. package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts.map +1 -1
  4. package/lib/accounts/defaultClearingHouseAccountSubscriber.js +17 -0
  5. package/lib/accounts/defaultUserAccountSubscriber.d.ts +2 -0
  6. package/lib/accounts/defaultUserAccountSubscriber.d.ts.map +1 -1
  7. package/lib/accounts/defaultUserAccountSubscriber.js +16 -0
  8. package/lib/accounts/types.d.ts +3 -21
  9. package/lib/accounts/types.d.ts.map +1 -1
  10. package/lib/accounts/webSocketAccountSubscriber.d.ts +2 -0
  11. package/lib/accounts/webSocketAccountSubscriber.d.ts.map +1 -1
  12. package/lib/accounts/webSocketAccountSubscriber.js +13 -3
  13. package/lib/clearingHouse.d.ts +4 -0
  14. package/lib/clearingHouse.d.ts.map +1 -1
  15. package/lib/clearingHouse.js +8 -0
  16. package/lib/clearingHouseUser.d.ts +31 -3
  17. package/lib/clearingHouseUser.d.ts.map +1 -1
  18. package/lib/clearingHouseUser.js +213 -47
  19. package/lib/constants/markets.d.ts.map +1 -1
  20. package/lib/constants/markets.js +21 -0
  21. package/lib/constants/numericConstants.d.ts +1 -0
  22. package/lib/constants/numericConstants.d.ts.map +1 -1
  23. package/lib/constants/numericConstants.js +2 -1
  24. package/lib/examples/makeTradeExample.d.ts.map +1 -1
  25. package/lib/examples/makeTradeExample.js +14 -13
  26. package/lib/idl/clearing_house.json +94 -42
  27. package/lib/index.d.ts +4 -1
  28. package/lib/index.d.ts.map +1 -1
  29. package/lib/index.js +4 -1
  30. package/lib/math/amm.d.ts +26 -1
  31. package/lib/math/amm.d.ts.map +1 -1
  32. package/lib/math/amm.js +85 -10
  33. package/lib/math/funding.d.ts +6 -6
  34. package/lib/math/funding.d.ts.map +1 -1
  35. package/lib/math/funding.js +41 -22
  36. package/lib/math/insuranceFund.d.ts +15 -0
  37. package/lib/math/insuranceFund.d.ts.map +1 -0
  38. package/lib/math/insuranceFund.js +36 -0
  39. package/lib/math/position.d.ts +1 -1
  40. package/lib/math/position.d.ts.map +1 -1
  41. package/lib/math/position.js +15 -23
  42. package/lib/math/trade.d.ts +1 -1
  43. package/lib/math/trade.d.ts.map +1 -1
  44. package/lib/math/trade.js +9 -4
  45. package/lib/types.d.ts +0 -13
  46. package/lib/types.d.ts.map +1 -1
  47. package/lib/util/computeUnits.d.ts +3 -0
  48. package/lib/util/computeUnits.d.ts.map +1 -0
  49. package/lib/util/computeUnits.js +27 -0
  50. package/lib/util/tps.d.ts +3 -0
  51. package/lib/util/tps.d.ts.map +1 -0
  52. package/lib/util/tps.js +27 -0
  53. package/lib/wallet.d.ts +10 -0
  54. package/lib/wallet.d.ts.map +1 -0
  55. package/lib/wallet.js +35 -0
  56. package/package.json +3 -13
  57. package/src/accounts/defaultClearingHouseAccountSubscriber.ts +18 -0
  58. package/src/accounts/defaultUserAccountSubscriber.ts +18 -0
  59. package/src/accounts/types.ts +3 -28
  60. package/src/accounts/webSocketAccountSubscriber.ts +16 -6
  61. package/src/clearingHouse.ts +9 -3
  62. package/src/clearingHouseUser.ts +306 -65
  63. package/src/constants/markets.ts +21 -0
  64. package/src/constants/numericConstants.ts +2 -0
  65. package/src/examples/makeTradeExample.ts +2 -1
  66. package/src/idl/clearing_house.json +94 -42
  67. package/src/index.ts +4 -1
  68. package/src/math/amm.ts +120 -13
  69. package/src/math/funding.ts +47 -25
  70. package/src/math/insuranceFund.ts +29 -0
  71. package/src/math/position.ts +16 -28
  72. package/src/math/trade.ts +9 -5
  73. package/src/types.ts +0 -14
  74. package/src/util/computeUnits.ts +21 -0
  75. package/src/util/tps.ts +27 -0
  76. package/src/wallet.ts +22 -0
  77. package/.eslintrc.json +0 -36
  78. package/.prettierignore +0 -1
  79. package/.prettierrc.js +0 -9
  80. package/lib/accounts/defaultHistoryAccountSubscriber.d.ts +0 -29
  81. package/lib/accounts/defaultHistoryAccountSubscriber.d.ts.map +0 -1
  82. package/lib/accounts/defaultHistoryAccountSubscriber.js +0 -110
  83. package/src/accounts/defaultHistoryAccountSubscriber.ts +0 -179
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.0.0",
2
+ "version": "1.0.0",
3
3
  "name": "clearing_house",
4
4
  "instructions": [
5
5
  {
@@ -156,11 +156,11 @@
156
156
  "type": "u64"
157
157
  },
158
158
  {
159
- "name": "ammBaseAssetAmount",
159
+ "name": "ammBaseAssetReserve",
160
160
  "type": "u128"
161
161
  },
162
162
  {
163
- "name": "ammQuoteAssetAmount",
163
+ "name": "ammQuoteAssetReserve",
164
164
  "type": "u128"
165
165
  },
166
166
  {
@@ -759,7 +759,59 @@
759
759
  },
760
760
  {
761
761
  "name": "authority",
762
+ "isMut": true,
763
+ "isSigner": true
764
+ },
765
+ {
766
+ "name": "rent",
767
+ "isMut": false,
768
+ "isSigner": false
769
+ },
770
+ {
771
+ "name": "systemProgram",
772
+ "isMut": false,
773
+ "isSigner": false
774
+ }
775
+ ],
776
+ "args": [
777
+ {
778
+ "name": "userNonce",
779
+ "type": "u8"
780
+ },
781
+ {
782
+ "name": "optionalAccounts",
783
+ "type": {
784
+ "defined": "InitializeUserOptionalAccounts"
785
+ }
786
+ }
787
+ ]
788
+ },
789
+ {
790
+ "name": "initializeUserWithExplicitPayer",
791
+ "accounts": [
792
+ {
793
+ "name": "user",
794
+ "isMut": true,
795
+ "isSigner": false
796
+ },
797
+ {
798
+ "name": "state",
762
799
  "isMut": false,
800
+ "isSigner": false
801
+ },
802
+ {
803
+ "name": "userPositions",
804
+ "isMut": true,
805
+ "isSigner": true
806
+ },
807
+ {
808
+ "name": "authority",
809
+ "isMut": false,
810
+ "isSigner": true
811
+ },
812
+ {
813
+ "name": "payer",
814
+ "isMut": true,
763
815
  "isSigner": true
764
816
  },
765
817
  {
@@ -2573,197 +2625,197 @@
2573
2625
  ],
2574
2626
  "errors": [
2575
2627
  {
2576
- "code": 300,
2628
+ "code": 6000,
2577
2629
  "name": "InvalidCollateralAccountAuthority",
2578
2630
  "msg": "Clearing house not collateral account owner"
2579
2631
  },
2580
2632
  {
2581
- "code": 301,
2633
+ "code": 6001,
2582
2634
  "name": "InvalidInsuranceAccountAuthority",
2583
2635
  "msg": "Clearing house not insurance account owner"
2584
2636
  },
2585
2637
  {
2586
- "code": 302,
2638
+ "code": 6002,
2587
2639
  "name": "InsufficientDeposit",
2588
2640
  "msg": "Insufficient deposit"
2589
2641
  },
2590
2642
  {
2591
- "code": 303,
2643
+ "code": 6003,
2592
2644
  "name": "InsufficientCollateral",
2593
2645
  "msg": "Insufficient collateral"
2594
2646
  },
2595
2647
  {
2596
- "code": 304,
2648
+ "code": 6004,
2597
2649
  "name": "SufficientCollateral",
2598
2650
  "msg": "Sufficient collateral"
2599
2651
  },
2600
2652
  {
2601
- "code": 305,
2653
+ "code": 6005,
2602
2654
  "name": "MaxNumberOfPositions",
2603
2655
  "msg": "Max number of positions taken"
2604
2656
  },
2605
2657
  {
2606
- "code": 306,
2658
+ "code": 6006,
2607
2659
  "name": "AdminControlsPricesDisabled",
2608
2660
  "msg": "Admin Controls Prices Disabled"
2609
2661
  },
2610
2662
  {
2611
- "code": 307,
2663
+ "code": 6007,
2612
2664
  "name": "MarketIndexNotInitialized",
2613
2665
  "msg": "Market Index Not Initialized"
2614
2666
  },
2615
2667
  {
2616
- "code": 308,
2668
+ "code": 6008,
2617
2669
  "name": "MarketIndexAlreadyInitialized",
2618
2670
  "msg": "Market Index Already Initialized"
2619
2671
  },
2620
2672
  {
2621
- "code": 309,
2673
+ "code": 6009,
2622
2674
  "name": "UserAccountAndUserPositionsAccountMismatch",
2623
2675
  "msg": "User Account And User Positions Account Mismatch"
2624
2676
  },
2625
2677
  {
2626
- "code": 310,
2678
+ "code": 6010,
2627
2679
  "name": "UserHasNoPositionInMarket",
2628
2680
  "msg": "User Has No Position In Market"
2629
2681
  },
2630
2682
  {
2631
- "code": 311,
2683
+ "code": 6011,
2632
2684
  "name": "InvalidInitialPeg",
2633
2685
  "msg": "Invalid Initial Peg"
2634
2686
  },
2635
2687
  {
2636
- "code": 312,
2688
+ "code": 6012,
2637
2689
  "name": "InvalidRepegRedundant",
2638
2690
  "msg": "AMM repeg already configured with amt given"
2639
2691
  },
2640
2692
  {
2641
- "code": 313,
2693
+ "code": 6013,
2642
2694
  "name": "InvalidRepegDirection",
2643
2695
  "msg": "AMM repeg incorrect repeg direction"
2644
2696
  },
2645
2697
  {
2646
- "code": 314,
2698
+ "code": 6014,
2647
2699
  "name": "InvalidRepegProfitability",
2648
2700
  "msg": "AMM repeg out of bounds pnl"
2649
2701
  },
2650
2702
  {
2651
- "code": 315,
2703
+ "code": 6015,
2652
2704
  "name": "SlippageOutsideLimit",
2653
2705
  "msg": "Slippage Outside Limit Price"
2654
2706
  },
2655
2707
  {
2656
- "code": 316,
2708
+ "code": 6016,
2657
2709
  "name": "TradeSizeTooSmall",
2658
2710
  "msg": "Trade Size Too Small"
2659
2711
  },
2660
2712
  {
2661
- "code": 317,
2713
+ "code": 6017,
2662
2714
  "name": "InvalidUpdateK",
2663
2715
  "msg": "Price change too large when updating K"
2664
2716
  },
2665
2717
  {
2666
- "code": 318,
2718
+ "code": 6018,
2667
2719
  "name": "AdminWithdrawTooLarge",
2668
2720
  "msg": "Admin tried to withdraw amount larger than fees collected"
2669
2721
  },
2670
2722
  {
2671
- "code": 319,
2723
+ "code": 6019,
2672
2724
  "name": "MathError",
2673
2725
  "msg": "Math Error"
2674
2726
  },
2675
2727
  {
2676
- "code": 320,
2728
+ "code": 6020,
2677
2729
  "name": "BnConversionError",
2678
2730
  "msg": "Conversion to u128/u64 failed with an overflow or underflow"
2679
2731
  },
2680
2732
  {
2681
- "code": 321,
2733
+ "code": 6021,
2682
2734
  "name": "ClockUnavailable",
2683
2735
  "msg": "Clock unavailable"
2684
2736
  },
2685
2737
  {
2686
- "code": 322,
2738
+ "code": 6022,
2687
2739
  "name": "UnableToLoadOracle",
2688
2740
  "msg": "Unable To Load Oracles"
2689
2741
  },
2690
2742
  {
2691
- "code": 323,
2743
+ "code": 6023,
2692
2744
  "name": "OracleMarkSpreadLimit",
2693
2745
  "msg": "Oracle/Mark Spread Too Large"
2694
2746
  },
2695
2747
  {
2696
- "code": 324,
2748
+ "code": 6024,
2697
2749
  "name": "HistoryAlreadyInitialized",
2698
2750
  "msg": "Clearing House history already initialized"
2699
2751
  },
2700
2752
  {
2701
- "code": 325,
2753
+ "code": 6025,
2702
2754
  "name": "ExchangePaused",
2703
2755
  "msg": "Exchange is paused"
2704
2756
  },
2705
2757
  {
2706
- "code": 326,
2758
+ "code": 6026,
2707
2759
  "name": "InvalidWhitelistToken",
2708
2760
  "msg": "Invalid whitelist token"
2709
2761
  },
2710
2762
  {
2711
- "code": 327,
2763
+ "code": 6027,
2712
2764
  "name": "WhitelistTokenNotFound",
2713
2765
  "msg": "Whitelist token not found"
2714
2766
  },
2715
2767
  {
2716
- "code": 328,
2768
+ "code": 6028,
2717
2769
  "name": "InvalidDiscountToken",
2718
2770
  "msg": "Invalid discount token"
2719
2771
  },
2720
2772
  {
2721
- "code": 329,
2773
+ "code": 6029,
2722
2774
  "name": "DiscountTokenNotFound",
2723
2775
  "msg": "Discount token not found"
2724
2776
  },
2725
2777
  {
2726
- "code": 330,
2778
+ "code": 6030,
2727
2779
  "name": "InvalidReferrer",
2728
2780
  "msg": "Invalid referrer"
2729
2781
  },
2730
2782
  {
2731
- "code": 331,
2783
+ "code": 6031,
2732
2784
  "name": "ReferrerNotFound",
2733
2785
  "msg": "Referrer not found"
2734
2786
  },
2735
2787
  {
2736
- "code": 332,
2788
+ "code": 6032,
2737
2789
  "name": "InvalidOracle",
2738
2790
  "msg": "InvalidOracle"
2739
2791
  },
2740
2792
  {
2741
- "code": 333,
2793
+ "code": 6033,
2742
2794
  "name": "OracleNotFound",
2743
2795
  "msg": "OracleNotFound"
2744
2796
  },
2745
2797
  {
2746
- "code": 334,
2798
+ "code": 6034,
2747
2799
  "name": "LiquidationsBlockedByOracle",
2748
2800
  "msg": "Liquidations Blocked By Oracle"
2749
2801
  },
2750
2802
  {
2751
- "code": 335,
2803
+ "code": 6035,
2752
2804
  "name": "UserMaxDeposit",
2753
2805
  "msg": "Can not deposit more than max deposit"
2754
2806
  },
2755
2807
  {
2756
- "code": 336,
2808
+ "code": 6036,
2757
2809
  "name": "CantDeleteUserWithCollateral",
2758
2810
  "msg": "Can not delete user that still has collateral"
2759
2811
  },
2760
2812
  {
2761
- "code": 337,
2813
+ "code": 6037,
2762
2814
  "name": "InvalidFundingProfitability",
2763
2815
  "msg": "AMM funding out of bounds pnl"
2764
2816
  },
2765
2817
  {
2766
- "code": 338,
2818
+ "code": 6038,
2767
2819
  "name": "CastingFailure",
2768
2820
  "msg": "Casting Failure"
2769
2821
  }
package/lib/index.d.ts CHANGED
@@ -3,7 +3,6 @@ export * from './mockUSDCFaucet';
3
3
  export * from './pythClient';
4
4
  export * from './types';
5
5
  export * from './constants/markets';
6
- export * from './accounts/defaultHistoryAccountSubscriber';
7
6
  export * from './accounts/defaultClearingHouseAccountSubscriber';
8
7
  export * from './accounts/types';
9
8
  export * from './addresses';
@@ -12,13 +11,17 @@ export * from './clearingHouseUser';
12
11
  export * from './clearingHouse';
13
12
  export * from './math/conversion';
14
13
  export * from './math/funding';
14
+ export * from './math/insuranceFund';
15
15
  export * from './math/market';
16
16
  export * from './math/position';
17
17
  export * from './math/amm';
18
18
  export * from './math/trade';
19
+ export * from './wallet';
19
20
  export * from './types';
20
21
  export * from './math/utils';
21
22
  export * from './config';
22
23
  export * from './constants/numericConstants';
24
+ export * from './util/computeUnits';
25
+ export * from './util/tps';
23
26
  export { BN };
24
27
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,E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AAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC;AACzB,cAAc,8BAA8B,CAAC;AAC7C,cAAc,qBAAqB,CAAC;AACpC,cAAc,YAAY,CAAC;AAE3B,OAAO,EAAE,EAAE,EAAE,CAAC"}
package/lib/index.js CHANGED
@@ -17,7 +17,6 @@ __exportStar(require("./mockUSDCFaucet"), exports);
17
17
  __exportStar(require("./pythClient"), exports);
18
18
  __exportStar(require("./types"), exports);
19
19
  __exportStar(require("./constants/markets"), exports);
20
- __exportStar(require("./accounts/defaultHistoryAccountSubscriber"), exports);
21
20
  __exportStar(require("./accounts/defaultClearingHouseAccountSubscriber"), exports);
22
21
  __exportStar(require("./accounts/types"), exports);
23
22
  __exportStar(require("./addresses"), exports);
@@ -26,11 +25,15 @@ __exportStar(require("./clearingHouseUser"), exports);
26
25
  __exportStar(require("./clearingHouse"), exports);
27
26
  __exportStar(require("./math/conversion"), exports);
28
27
  __exportStar(require("./math/funding"), exports);
28
+ __exportStar(require("./math/insuranceFund"), exports);
29
29
  __exportStar(require("./math/market"), exports);
30
30
  __exportStar(require("./math/position"), exports);
31
31
  __exportStar(require("./math/amm"), exports);
32
32
  __exportStar(require("./math/trade"), exports);
33
+ __exportStar(require("./wallet"), exports);
33
34
  __exportStar(require("./types"), exports);
34
35
  __exportStar(require("./math/utils"), exports);
35
36
  __exportStar(require("./config"), exports);
36
37
  __exportStar(require("./constants/numericConstants"), exports);
38
+ __exportStar(require("./util/computeUnits"), exports);
39
+ __exportStar(require("./util/tps"), exports);
package/lib/math/amm.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /// <reference types="bn.js" />
2
2
  import { BN } from '@project-serum/anchor';
3
- import { AMM, PositionDirection, SwapDirection } from '../types';
3
+ import { AMM, PositionDirection, SwapDirection, Market } from '../types';
4
4
  /**
5
5
  * Calculates a price given an arbitrary base and quote amount (they must have the same precision)
6
6
  *
@@ -38,4 +38,29 @@ export declare function calculateSwapOutput(inputAssetReserve: BN, swapAmount: B
38
38
  * @param positionDirection
39
39
  */
40
40
  export declare function getSwapDirection(inputAssetType: AssetType, positionDirection: PositionDirection): SwapDirection;
41
+ /**
42
+ * Helper function calculating adjust k cost
43
+ * @param market
44
+ * @param marketIndex
45
+ * @param numerator
46
+ * @param denomenator
47
+ * @returns cost : Precision QUOTE_ASSET_PRECISION
48
+ */
49
+ export declare function calculateAdjustKCost(market: Market, marketIndex: BN, numerator: BN, denomenator: BN): BN;
50
+ /**
51
+ * Helper function calculating adjust pegMultiplier (repeg) cost
52
+ *
53
+ * @param market
54
+ * @param marketIndex
55
+ * @param newPeg
56
+ * @returns cost : Precision QUOTE_ASSET_PRECISION
57
+ */
58
+ export declare function calculateRepegCost(market: Market, marketIndex: BN, newPeg: BN): BN;
59
+ /**
60
+ * Helper function calculating terminal price of amm
61
+ *
62
+ * @param market
63
+ * @returns cost : Precision MARK_PRICE_PRECISION
64
+ */
65
+ export declare function calculateTerminalPrice(market: Market): BN;
41
66
  //# sourceMappingURL=amm.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"amm.d.ts","sourceRoot":"","sources":["../../src/math/amm.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,uBAAuB,CAAC;AAO3C,OAAO,EAAE,GAAG,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAGjE;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC7B,eAAe,EAAE,EAAE,EACnB,gBAAgB,EAAE,EAAE,EACpB,cAAc,EAAE,EAAE,GAChB,EAAE,CAUJ;AAED,oBAAY,SAAS,GAAG,OAAO,GAAG,MAAM,CAAC;AAEzC;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAC5C,GAAG,EAAE,GAAG,EACR,cAAc,EAAE,SAAS,EACzB,UAAU,EAAE,EAAE,EACd,aAAa,EAAE,aAAa,GAC1B,CAAC,EAAE,EAAE,EAAE,CAAC,CAmCV;AAED;;;;;;;;GAQG;AACH,wBAAgB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AAE,EACb,WAAW,EAAE,EAAE,GACb,EAAE,CA0BJ;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CACjC,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,EAAE,EACf,MAAM,EAAE,EAAE,GACR,EAAE,CA2BJ;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,MAuBpD"}
package/lib/math/amm.js CHANGED
@@ -1,10 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getSwapDirection = exports.calculateSwapOutput = exports.calculateAmmReservesAfterSwap = exports.calculatePrice = void 0;
3
+ exports.calculateTerminalPrice = exports.calculateRepegCost = exports.calculateAdjustKCost = exports.getSwapDirection = exports.calculateSwapOutput = exports.calculateAmmReservesAfterSwap = exports.calculatePrice = void 0;
4
4
  const anchor_1 = require("@project-serum/anchor");
5
5
  const numericConstants_1 = require("../constants/numericConstants");
6
+ const position_1 = require("./position");
6
7
  const types_1 = require("../types");
7
8
  const assert_1 = require("../assert/assert");
9
+ const __1 = require("..");
8
10
  /**
9
11
  * Calculates a price given an arbitrary base and quote amount (they must have the same precision)
10
12
  *
@@ -38,15 +40,9 @@ function calculateAmmReservesAfterSwap(amm, inputAssetType, swapAmount, swapDire
38
40
  let newQuoteAssetReserve;
39
41
  let newBaseAssetReserve;
40
42
  if (inputAssetType === 'quote') {
41
- const swapAmountIntermediate = swapAmount.mul(numericConstants_1.MARK_PRICE_PRECISION);
42
- swapAmount = swapAmountIntermediate.div(amm.pegMultiplier);
43
- // Because ints round down by default, we need to add 1 back when removing from
44
- // AMM to avoid giving users extra pnl when they short
45
- const roundUp = swapDirection === types_1.SwapDirection.REMOVE &&
46
- !swapAmountIntermediate.mod(amm.pegMultiplier).eq(numericConstants_1.ZERO);
47
- if (roundUp) {
48
- swapAmount = swapAmount.add(numericConstants_1.ONE);
49
- }
43
+ swapAmount = swapAmount
44
+ .mul(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
45
+ .div(amm.pegMultiplier);
50
46
  [newQuoteAssetReserve, newBaseAssetReserve] = calculateSwapOutput(amm.quoteAssetReserve, swapAmount, swapDirection, amm.sqrtK.mul(amm.sqrtK));
51
47
  }
52
48
  else {
@@ -94,3 +90,82 @@ function getSwapDirection(inputAssetType, positionDirection) {
94
90
  return types_1.SwapDirection.ADD;
95
91
  }
96
92
  exports.getSwapDirection = getSwapDirection;
93
+ /**
94
+ * Helper function calculating adjust k cost
95
+ * @param market
96
+ * @param marketIndex
97
+ * @param numerator
98
+ * @param denomenator
99
+ * @returns cost : Precision QUOTE_ASSET_PRECISION
100
+ */
101
+ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
102
+ const netUserPosition = {
103
+ baseAssetAmount: market.baseAssetAmount,
104
+ lastCumulativeFundingRate: market.amm.cumulativeFundingRate,
105
+ marketIndex: new anchor_1.BN(marketIndex),
106
+ quoteAssetAmount: new anchor_1.BN(0),
107
+ };
108
+ const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
109
+ const marketNewK = Object.assign({}, market);
110
+ marketNewK.amm = Object.assign({}, market.amm);
111
+ marketNewK.amm.baseAssetReserve = market.amm.baseAssetReserve
112
+ .mul(numerator)
113
+ .div(denomenator);
114
+ marketNewK.amm.quoteAssetReserve = market.amm.quoteAssetReserve
115
+ .mul(numerator)
116
+ .div(denomenator);
117
+ marketNewK.amm.sqrtK = market.amm.sqrtK.mul(numerator).div(denomenator);
118
+ netUserPosition.quoteAssetAmount = currentValue;
119
+ const cost = __1.calculatePositionPNL(marketNewK, netUserPosition);
120
+ return cost;
121
+ }
122
+ exports.calculateAdjustKCost = calculateAdjustKCost;
123
+ /**
124
+ * Helper function calculating adjust pegMultiplier (repeg) cost
125
+ *
126
+ * @param market
127
+ * @param marketIndex
128
+ * @param newPeg
129
+ * @returns cost : Precision QUOTE_ASSET_PRECISION
130
+ */
131
+ function calculateRepegCost(market, marketIndex, newPeg) {
132
+ const netUserPosition = {
133
+ baseAssetAmount: market.baseAssetAmount,
134
+ lastCumulativeFundingRate: market.amm.cumulativeFundingRate,
135
+ marketIndex: new anchor_1.BN(marketIndex),
136
+ quoteAssetAmount: new anchor_1.BN(0),
137
+ };
138
+ const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
139
+ netUserPosition.quoteAssetAmount = currentValue;
140
+ const prevMarketPrice = __1.calculateMarkPrice(market);
141
+ const marketNewPeg = Object.assign({}, market);
142
+ marketNewPeg.amm = Object.assign({}, market.amm);
143
+ // const marketNewPeg = JSON.parse(JSON.stringify(market));
144
+ marketNewPeg.amm.pegMultiplier = newPeg;
145
+ console.log('Price moves from', __1.convertToNumber(prevMarketPrice), 'to', __1.convertToNumber(__1.calculateMarkPrice(marketNewPeg)));
146
+ const cost = __1.calculatePositionPNL(marketNewPeg, netUserPosition);
147
+ return cost;
148
+ }
149
+ exports.calculateRepegCost = calculateRepegCost;
150
+ /**
151
+ * Helper function calculating terminal price of amm
152
+ *
153
+ * @param market
154
+ * @returns cost : Precision MARK_PRICE_PRECISION
155
+ */
156
+ function calculateTerminalPrice(market) {
157
+ if (!market.initialized) {
158
+ return new anchor_1.BN(0);
159
+ }
160
+ const directionToClose = market.baseAssetAmount.gt(numericConstants_1.ZERO)
161
+ ? types_1.PositionDirection.SHORT
162
+ : types_1.PositionDirection.LONG;
163
+ const [newQuoteAssetReserve, newBaseAssetReserve] = calculateAmmReservesAfterSwap(market.amm, 'base', market.baseAssetAmount.abs(), getSwapDirection('base', directionToClose));
164
+ const terminalPrice = newQuoteAssetReserve
165
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
166
+ .mul(market.amm.pegMultiplier)
167
+ .div(numericConstants_1.PEG_PRECISION)
168
+ .div(newBaseAssetReserve);
169
+ return terminalPrice;
170
+ }
171
+ exports.calculateTerminalPrice = calculateTerminalPrice;
@@ -1,6 +1,6 @@
1
1
  /// <reference types="bn.js" />
2
2
  import { BN } from '@project-serum/anchor';
3
- import { PythClient } from '../pythClient';
3
+ import { PriceData } from '@pythnetwork/client';
4
4
  import { Market } from '../types';
5
5
  /**
6
6
  *
@@ -9,16 +9,16 @@ import { Market } from '../types';
9
9
  * @param periodAdjustment
10
10
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
11
11
  */
12
- export declare function calculateAllEstimatedFundingRate(market: Market, pythClient: PythClient, periodAdjustment?: BN): Promise<[BN, BN, BN, BN, BN]>;
12
+ export declare function calculateAllEstimatedFundingRate(market: Market, oraclePriceData: PriceData, periodAdjustment?: BN): Promise<[BN, BN, BN, BN, BN]>;
13
13
  /**
14
14
  *
15
15
  * @param market
16
- * @param pythClient
16
+ * @param oraclePriceData
17
17
  * @param periodAdjustment
18
18
  * @param estimationMethod
19
19
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
20
20
  */
21
- export declare function calculateEstimatedFundingRate(market: Market, pythClient: PythClient, periodAdjustment: BN, estimationMethod: 'interpolated' | 'lowerbound' | 'capped'): Promise<BN>;
21
+ export declare function calculateEstimatedFundingRate(market: Market, oraclePriceData: PriceData, periodAdjustment: BN, estimationMethod: 'interpolated' | 'lowerbound' | 'capped'): Promise<BN>;
22
22
  /**
23
23
  *
24
24
  * @param market
@@ -27,7 +27,7 @@ export declare function calculateEstimatedFundingRate(market: Market, pythClient
27
27
  * @param estimationMethod
28
28
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
29
29
  */
30
- export declare function calculateLongShortFundingRate(market: Market, pythClient: PythClient, periodAdjustment?: BN): Promise<[BN, BN]>;
30
+ export declare function calculateLongShortFundingRate(market: Market, oraclePriceData: PriceData, periodAdjustment?: BN): Promise<[BN, BN]>;
31
31
  /**
32
32
  *
33
33
  * @param market
@@ -36,7 +36,7 @@ export declare function calculateLongShortFundingRate(market: Market, pythClient
36
36
  * @param estimationMethod
37
37
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
38
38
  */
39
- export declare function calculateLongShortFundingRateAndLiveTwaps(market: Market, pythClient: PythClient, periodAdjustment?: BN): Promise<[BN, BN, BN, BN]>;
39
+ export declare function calculateLongShortFundingRateAndLiveTwaps(market: Market, oraclePriceData: PriceData, periodAdjustment?: BN): Promise<[BN, BN, BN, BN]>;
40
40
  /**
41
41
  *
42
42
  * @param market
@@ -1 +1 @@
1
- {"version":3,"file":"funding.d.ts","sourceRoot":"","sources":["../../src/math/funding.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,uBAAuB,CAAC;AAO3C,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAGlC;;;;;;GAMG;AACH,wBAAsB,gCAAgC,CACrD,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,UAAU,EACtB,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAoJ/B;AAED;;;;;;;GAOG;AACH,wBAAsB,6BAA6B,CAClD,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,UAAU,EACtB,gBAAgB,EAAE,EAAc,EAChC,gBAAgB,EAAE,cAAc,GAAG,YAAY,GAAG,QAAQ,GACxD,OAAO,CAAC,EAAE,CAAC,CAgBb;AAED;;;;;;;GAOG;AACH,wBAAsB,6BAA6B,CAClD,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,UAAU,EACtB,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAenB;AAED;;;;;;;GAOG;AACH,wBAAsB,yCAAyC,CAC9D,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,UAAU,EACtB,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAe3B;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,MA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