@drift-labs/sdk 2.30.0-beta.0 → 2.30.0

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 (55) hide show
  1. package/lib/accounts/pollingTokenAccountSubscriber.d.ts +3 -3
  2. package/lib/accounts/pollingTokenAccountSubscriber.js +5 -2
  3. package/lib/accounts/types.d.ts +3 -3
  4. package/lib/constants/spotMarkets.js +10 -0
  5. package/lib/dlob/DLOB.d.ts +20 -1
  6. package/lib/dlob/DLOB.js +39 -0
  7. package/lib/driftClient.d.ts +51 -2
  8. package/lib/driftClient.js +162 -13
  9. package/lib/events/types.d.ts +3 -2
  10. package/lib/events/types.js +1 -0
  11. package/lib/examples/makeTradeExample.js +1 -1
  12. package/lib/idl/drift.json +279 -2
  13. package/lib/index.d.ts +1 -0
  14. package/lib/index.js +1 -0
  15. package/lib/jupiter/jupiterClient.d.ts +86 -0
  16. package/lib/jupiter/jupiterClient.js +109 -0
  17. package/lib/math/spotBalance.d.ts +41 -0
  18. package/lib/math/spotBalance.js +41 -0
  19. package/lib/token/index.d.ts +3 -2
  20. package/lib/token/index.js +9 -32
  21. package/lib/tokenFaucet.d.ts +3 -3
  22. package/lib/tokenFaucet.js +4 -9
  23. package/lib/tx/retryTxSender.js +3 -0
  24. package/lib/types.d.ts +29 -1
  25. package/lib/types.js +6 -1
  26. package/lib/wallet.d.ts +5 -3
  27. package/lib/wallet.js +19 -7
  28. package/package.json +2 -2
  29. package/src/accounts/pollingTokenAccountSubscriber.ts +8 -5
  30. package/src/accounts/types.ts +3 -3
  31. package/src/assert/assert.js +9 -0
  32. package/src/constants/spotMarkets.ts +11 -0
  33. package/src/dlob/DLOB.ts +75 -0
  34. package/src/driftClient.ts +288 -37
  35. package/src/events/types.ts +5 -1
  36. package/src/examples/makeTradeExample.ts +2 -4
  37. package/src/idl/drift.json +279 -2
  38. package/src/index.ts +1 -0
  39. package/src/jupiter/jupiterClient.ts +214 -0
  40. package/src/math/spotBalance.ts +41 -0
  41. package/src/token/index.js +38 -0
  42. package/src/token/index.ts +12 -36
  43. package/src/tokenFaucet.ts +15 -34
  44. package/src/tx/retryTxSender.ts +4 -0
  45. package/src/types.ts +32 -1
  46. package/src/util/computeUnits.js +27 -0
  47. package/src/util/promiseTimeout.js +14 -0
  48. package/src/util/tps.js +27 -0
  49. package/src/wallet.ts +34 -12
  50. package/tests/dlob/helpers.ts +9 -0
  51. package/tests/dlob/test.ts +218 -40
  52. package/dlob_read.ts +0 -155
  53. package/lib/util/getTokenAddress.d.ts +0 -2
  54. package/lib/util/getTokenAddress.js +0 -9
  55. package/src/util/getTokenAddress.ts +0 -18
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.30.0-beta.0",
2
+ "version": "2.30.0",
3
3
  "name": "drift",
4
4
  "instructions": [
5
5
  {
@@ -710,6 +710,170 @@
710
710
  }
711
711
  ]
712
712
  },
713
+ {
714
+ "name": "beginSwap",
715
+ "accounts": [
716
+ {
717
+ "name": "state",
718
+ "isMut": false,
719
+ "isSigner": false
720
+ },
721
+ {
722
+ "name": "user",
723
+ "isMut": true,
724
+ "isSigner": false
725
+ },
726
+ {
727
+ "name": "userStats",
728
+ "isMut": true,
729
+ "isSigner": false
730
+ },
731
+ {
732
+ "name": "authority",
733
+ "isMut": false,
734
+ "isSigner": true
735
+ },
736
+ {
737
+ "name": "outSpotMarketVault",
738
+ "isMut": true,
739
+ "isSigner": false
740
+ },
741
+ {
742
+ "name": "inSpotMarketVault",
743
+ "isMut": true,
744
+ "isSigner": false
745
+ },
746
+ {
747
+ "name": "outTokenAccount",
748
+ "isMut": true,
749
+ "isSigner": false
750
+ },
751
+ {
752
+ "name": "inTokenAccount",
753
+ "isMut": true,
754
+ "isSigner": false
755
+ },
756
+ {
757
+ "name": "tokenProgram",
758
+ "isMut": false,
759
+ "isSigner": false
760
+ },
761
+ {
762
+ "name": "driftSigner",
763
+ "isMut": false,
764
+ "isSigner": false
765
+ },
766
+ {
767
+ "name": "instructions",
768
+ "isMut": false,
769
+ "isSigner": false,
770
+ "docs": [
771
+ "Instructions Sysvar for instruction introspection"
772
+ ]
773
+ }
774
+ ],
775
+ "args": [
776
+ {
777
+ "name": "inMarketIndex",
778
+ "type": "u16"
779
+ },
780
+ {
781
+ "name": "outMarketIndex",
782
+ "type": "u16"
783
+ },
784
+ {
785
+ "name": "amountIn",
786
+ "type": "u64"
787
+ }
788
+ ]
789
+ },
790
+ {
791
+ "name": "endSwap",
792
+ "accounts": [
793
+ {
794
+ "name": "state",
795
+ "isMut": false,
796
+ "isSigner": false
797
+ },
798
+ {
799
+ "name": "user",
800
+ "isMut": true,
801
+ "isSigner": false
802
+ },
803
+ {
804
+ "name": "userStats",
805
+ "isMut": true,
806
+ "isSigner": false
807
+ },
808
+ {
809
+ "name": "authority",
810
+ "isMut": false,
811
+ "isSigner": true
812
+ },
813
+ {
814
+ "name": "outSpotMarketVault",
815
+ "isMut": true,
816
+ "isSigner": false
817
+ },
818
+ {
819
+ "name": "inSpotMarketVault",
820
+ "isMut": true,
821
+ "isSigner": false
822
+ },
823
+ {
824
+ "name": "outTokenAccount",
825
+ "isMut": true,
826
+ "isSigner": false
827
+ },
828
+ {
829
+ "name": "inTokenAccount",
830
+ "isMut": true,
831
+ "isSigner": false
832
+ },
833
+ {
834
+ "name": "tokenProgram",
835
+ "isMut": false,
836
+ "isSigner": false
837
+ },
838
+ {
839
+ "name": "driftSigner",
840
+ "isMut": false,
841
+ "isSigner": false
842
+ },
843
+ {
844
+ "name": "instructions",
845
+ "isMut": false,
846
+ "isSigner": false,
847
+ "docs": [
848
+ "Instructions Sysvar for instruction introspection"
849
+ ]
850
+ }
851
+ ],
852
+ "args": [
853
+ {
854
+ "name": "inMarketIndex",
855
+ "type": "u16"
856
+ },
857
+ {
858
+ "name": "outMarketIndex",
859
+ "type": "u16"
860
+ },
861
+ {
862
+ "name": "limitPrice",
863
+ "type": {
864
+ "option": "u64"
865
+ }
866
+ },
867
+ {
868
+ "name": "reduceOnly",
869
+ "type": {
870
+ "option": {
871
+ "defined": "SwapReduceOnly"
872
+ }
873
+ }
874
+ }
875
+ ]
876
+ },
713
877
  {
714
878
  "name": "addPerpLpShares",
715
879
  "accounts": [
@@ -4895,12 +5059,46 @@
4895
5059
  "defined": "AssetTier"
4896
5060
  }
4897
5061
  },
5062
+ {
5063
+ "name": "padding1",
5064
+ "type": {
5065
+ "array": [
5066
+ "u8",
5067
+ 6
5068
+ ]
5069
+ }
5070
+ },
5071
+ {
5072
+ "name": "flashLoanAmount",
5073
+ "docs": [
5074
+ "For swaps, the amount of token loaned out in the begin_swap ix",
5075
+ "precision: token mint precision"
5076
+ ],
5077
+ "type": "u64"
5078
+ },
5079
+ {
5080
+ "name": "flashLoanInitialTokenAmount",
5081
+ "docs": [
5082
+ "For swaps, the amount in the users token account in the begin_swap ix",
5083
+ "Used to calculate how much of the token left the system in end_swap ix",
5084
+ "precision: token mint precision"
5085
+ ],
5086
+ "type": "u64"
5087
+ },
5088
+ {
5089
+ "name": "totalSwapFee",
5090
+ "docs": [
5091
+ "The total fees received from swaps",
5092
+ "precision: token mint precision"
5093
+ ],
5094
+ "type": "u64"
5095
+ },
4898
5096
  {
4899
5097
  "name": "padding",
4900
5098
  "type": {
4901
5099
  "array": [
4902
5100
  "u8",
4903
- 86
5101
+ 56
4904
5102
  ]
4905
5103
  }
4906
5104
  }
@@ -7259,6 +7457,20 @@
7259
7457
  ]
7260
7458
  }
7261
7459
  },
7460
+ {
7461
+ "name": "SwapReduceOnly",
7462
+ "type": {
7463
+ "kind": "enum",
7464
+ "variants": [
7465
+ {
7466
+ "name": "In"
7467
+ },
7468
+ {
7469
+ "name": "Out"
7470
+ }
7471
+ ]
7472
+ }
7473
+ },
7262
7474
  {
7263
7475
  "name": "TwapPeriod",
7264
7476
  "type": {
@@ -8845,6 +9057,56 @@
8845
9057
  "index": false
8846
9058
  }
8847
9059
  ]
9060
+ },
9061
+ {
9062
+ "name": "SwapRecord",
9063
+ "fields": [
9064
+ {
9065
+ "name": "ts",
9066
+ "type": "i64",
9067
+ "index": false
9068
+ },
9069
+ {
9070
+ "name": "user",
9071
+ "type": "publicKey",
9072
+ "index": false
9073
+ },
9074
+ {
9075
+ "name": "amountOut",
9076
+ "type": "u64",
9077
+ "index": false
9078
+ },
9079
+ {
9080
+ "name": "amountIn",
9081
+ "type": "u64",
9082
+ "index": false
9083
+ },
9084
+ {
9085
+ "name": "outMarketIndex",
9086
+ "type": "u16",
9087
+ "index": false
9088
+ },
9089
+ {
9090
+ "name": "inMarketIndex",
9091
+ "type": "u16",
9092
+ "index": false
9093
+ },
9094
+ {
9095
+ "name": "outOraclePrice",
9096
+ "type": "i64",
9097
+ "index": false
9098
+ },
9099
+ {
9100
+ "name": "inOraclePrice",
9101
+ "type": "i64",
9102
+ "index": false
9103
+ },
9104
+ {
9105
+ "name": "fee",
9106
+ "type": "u64",
9107
+ "index": false
9108
+ }
9109
+ ]
8848
9110
  }
8849
9111
  ],
8850
9112
  "errors": [
@@ -10087,6 +10349,21 @@
10087
10349
  "code": 6247,
10088
10350
  "name": "InvalidPhoenixMarket",
10089
10351
  "msg": "InvalidPhoenixMarket"
10352
+ },
10353
+ {
10354
+ "code": 6248,
10355
+ "name": "InvalidSwap",
10356
+ "msg": "InvalidSwap"
10357
+ },
10358
+ {
10359
+ "code": 6249,
10360
+ "name": "SwapLimitPriceBreached",
10361
+ "msg": "SwapLimitPriceBreached"
10362
+ },
10363
+ {
10364
+ "code": 6250,
10365
+ "name": "SpotMarketReduceOnly",
10366
+ "msg": "SpotMarketReduceOnly"
10090
10367
  }
10091
10368
  ]
10092
10369
  }
package/lib/index.d.ts CHANGED
@@ -30,6 +30,7 @@ export * from './factory/bigNum';
30
30
  export * from './events/types';
31
31
  export * from './events/eventSubscriber';
32
32
  export * from './events/fetchLogs';
33
+ export * from './jupiter/jupiterClient';
33
34
  export * from './math/auction';
34
35
  export * from './math/spotMarket';
35
36
  export * from './math/conversion';
package/lib/index.js CHANGED
@@ -54,6 +54,7 @@ __exportStar(require("./factory/bigNum"), exports);
54
54
  __exportStar(require("./events/types"), exports);
55
55
  __exportStar(require("./events/eventSubscriber"), exports);
56
56
  __exportStar(require("./events/fetchLogs"), exports);
57
+ __exportStar(require("./jupiter/jupiterClient"), exports);
57
58
  __exportStar(require("./math/auction"), exports);
58
59
  __exportStar(require("./math/spotMarket"), exports);
59
60
  __exportStar(require("./math/conversion"), exports);
@@ -0,0 +1,86 @@
1
+ import { AddressLookupTableAccount, Connection, PublicKey, TransactionInstruction, TransactionMessage, VersionedTransaction } from '@solana/web3.js';
2
+ import { BN } from '@coral-xyz/anchor';
3
+ export type SwapMode = 'ExactIn' | 'ExactOut';
4
+ export interface MarketInfo {
5
+ id: string;
6
+ inAmount: number;
7
+ inputMint: string;
8
+ label: string;
9
+ lpFee: Fee;
10
+ notEnoughLiquidity: boolean;
11
+ outAmount: number;
12
+ outputMint: string;
13
+ platformFee: Fee;
14
+ priceImpactPct: number;
15
+ }
16
+ export interface Fee {
17
+ amount: number;
18
+ mint: string;
19
+ pct: number;
20
+ }
21
+ export interface Route {
22
+ amount: number;
23
+ inAmount: number;
24
+ marketInfos: MarketInfo[];
25
+ otherAmountThreshold: number;
26
+ outAmount: number;
27
+ priceImpactPct: number;
28
+ slippageBps: number;
29
+ swapMode: SwapMode;
30
+ }
31
+ export declare class JupiterClient {
32
+ url: string;
33
+ connection: Connection;
34
+ lookupTableCahce: Map<string, AddressLookupTableAccount>;
35
+ constructor({ connection }: {
36
+ connection: Connection;
37
+ });
38
+ /**
39
+ * Get routes for a swap
40
+ * @param inputMint the mint of the input token
41
+ * @param outputMint the mint of the output token
42
+ * @param amount the amount of the input token
43
+ * @param slippageBps the slippage tolerance in basis points
44
+ * @param swapMode the swap mode (ExactIn or ExactOut)
45
+ */
46
+ getRoutes({ inputMint, outputMint, amount, slippageBps, swapMode, }: {
47
+ inputMint: PublicKey;
48
+ outputMint: PublicKey;
49
+ amount: BN;
50
+ slippageBps?: number;
51
+ swapMode?: SwapMode;
52
+ }): Promise<Route[]>;
53
+ /**
54
+ * Get a swap transaction for a route
55
+ * @param route the route to perform swap
56
+ * @param userPublicKey the signer's wallet public key
57
+ * @param slippageBps the slippage tolerance in basis points
58
+ */
59
+ getSwapTransaction({ route, userPublicKey, slippageBps, }: {
60
+ route: Route;
61
+ userPublicKey: PublicKey;
62
+ slippageBps?: number;
63
+ }): Promise<VersionedTransaction>;
64
+ /**
65
+ * Get the transaction message and lookup tables for a transaction
66
+ * @param transaction
67
+ */
68
+ getTransactionMessageAndLookupTables({ transaction, }: {
69
+ transaction: VersionedTransaction;
70
+ }): Promise<{
71
+ transactionMessage: TransactionMessage;
72
+ lookupTables: AddressLookupTableAccount[];
73
+ }>;
74
+ getLookupTable(accountKey: PublicKey): Promise<AddressLookupTableAccount>;
75
+ /**
76
+ * Get the jupiter instructions from transaction by filtering out instructions to compute budget and associated token programs
77
+ * @param transactionMessage the transaction message
78
+ * @param inputMint the input mint
79
+ * @param outputMint the output mint
80
+ */
81
+ getJupiterInstructions({ transactionMessage, inputMint, outputMint, }: {
82
+ transactionMessage: TransactionMessage;
83
+ inputMint: PublicKey;
84
+ outputMint: PublicKey;
85
+ }): TransactionInstruction[];
86
+ }
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.JupiterClient = void 0;
7
+ const web3_js_1 = require("@solana/web3.js");
8
+ const node_fetch_1 = __importDefault(require("node-fetch"));
9
+ class JupiterClient {
10
+ constructor({ connection }) {
11
+ this.url = 'https://quote-api.jup.ag/v4';
12
+ this.lookupTableCahce = new Map();
13
+ this.connection = connection;
14
+ }
15
+ /**
16
+ * Get routes for a swap
17
+ * @param inputMint the mint of the input token
18
+ * @param outputMint the mint of the output token
19
+ * @param amount the amount of the input token
20
+ * @param slippageBps the slippage tolerance in basis points
21
+ * @param swapMode the swap mode (ExactIn or ExactOut)
22
+ */
23
+ async getRoutes({ inputMint, outputMint, amount, slippageBps = 50, swapMode = 'ExactIn', }) {
24
+ const params = new URLSearchParams({
25
+ inputMint: inputMint.toString(),
26
+ outputMint: outputMint.toString(),
27
+ amount: amount.toString(),
28
+ slippageBps: slippageBps.toString(),
29
+ swapMode,
30
+ }).toString();
31
+ const { data: routes } = await (await (0, node_fetch_1.default)(`https://quote-api.jup.ag/v4/quote?${params}`)).json();
32
+ return routes;
33
+ }
34
+ /**
35
+ * Get a swap transaction for a route
36
+ * @param route the route to perform swap
37
+ * @param userPublicKey the signer's wallet public key
38
+ * @param slippageBps the slippage tolerance in basis points
39
+ */
40
+ async getSwapTransaction({ route, userPublicKey, slippageBps = 50, }) {
41
+ const resp = await (await (0, node_fetch_1.default)(`${this.url}/swap`, {
42
+ method: 'POST',
43
+ headers: {
44
+ 'Content-Type': 'application/json',
45
+ },
46
+ body: JSON.stringify({
47
+ route,
48
+ userPublicKey,
49
+ slippageBps,
50
+ }),
51
+ })).json();
52
+ const { swapTransaction } = resp;
53
+ const swapTransactionBuf = Buffer.from(swapTransaction, 'base64');
54
+ return web3_js_1.VersionedTransaction.deserialize(swapTransactionBuf);
55
+ }
56
+ /**
57
+ * Get the transaction message and lookup tables for a transaction
58
+ * @param transaction
59
+ */
60
+ async getTransactionMessageAndLookupTables({ transaction, }) {
61
+ const message = transaction.message;
62
+ const lookupTables = (await Promise.all(message.addressTableLookups.map(async (lookup) => {
63
+ return await this.getLookupTable(lookup.accountKey);
64
+ }))).filter((lookup) => lookup);
65
+ const transactionMessage = web3_js_1.TransactionMessage.decompile(message, {
66
+ addressLookupTableAccounts: lookupTables,
67
+ });
68
+ return {
69
+ transactionMessage,
70
+ lookupTables,
71
+ };
72
+ }
73
+ async getLookupTable(accountKey) {
74
+ if (this.lookupTableCahce.has(accountKey.toString())) {
75
+ return this.lookupTableCahce.get(accountKey.toString());
76
+ }
77
+ return (await this.connection.getAddressLookupTable(accountKey)).value;
78
+ }
79
+ /**
80
+ * Get the jupiter instructions from transaction by filtering out instructions to compute budget and associated token programs
81
+ * @param transactionMessage the transaction message
82
+ * @param inputMint the input mint
83
+ * @param outputMint the output mint
84
+ */
85
+ getJupiterInstructions({ transactionMessage, inputMint, outputMint, }) {
86
+ return transactionMessage.instructions.filter((instruction) => {
87
+ if (instruction.programId.toString() ===
88
+ 'ComputeBudget111111111111111111111111111111') {
89
+ return false;
90
+ }
91
+ if (instruction.programId.toString() ===
92
+ 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA') {
93
+ return false;
94
+ }
95
+ if (instruction.programId.toString() === '11111111111111111111111111111111') {
96
+ return false;
97
+ }
98
+ if (instruction.programId.toString() ===
99
+ 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL') {
100
+ const mint = instruction.keys[3].pubkey;
101
+ if (mint.equals(inputMint) || mint.equals(outputMint)) {
102
+ return false;
103
+ }
104
+ }
105
+ return true;
106
+ });
107
+ }
108
+ }
109
+ exports.JupiterClient = JupiterClient;
@@ -1,10 +1,51 @@
1
1
  import { SpotMarketAccount, SpotBalanceType, MarginCategory } from '../types';
2
2
  import { BN } from '@coral-xyz/anchor';
3
3
  import { OraclePriceData } from '../oracles/types';
4
+ /**
5
+ * Calculates the balance of a given token amount including any accumulated interest. This
6
+ * is the same as `SpotPosition.scaledBalance`.
7
+ *
8
+ * @param {BN} tokenAmount - the amount of tokens
9
+ * @param {SpotMarketAccount} spotMarket - the spot market account
10
+ * @param {SpotBalanceType} balanceType - the balance type ('deposit' or 'borrow')
11
+ * @return {BN} the calculated balance, scaled by `SPOT_MARKET_BALANCE_PRECISION`
12
+ */
4
13
  export declare function getBalance(tokenAmount: BN, spotMarket: SpotMarketAccount, balanceType: SpotBalanceType): BN;
14
+ /**
15
+ * Calculates the spot token amount including any accumulated interest.
16
+ *
17
+ * @param {BN} balanceAmount - The balance amount, typically from `SpotPosition.scaledBalance`
18
+ * @param {SpotMarketAccount} spotMarket - The spot market account details
19
+ * @param {SpotBalanceType} balanceType - The balance type to be used for calculation
20
+ * @returns {BN} The calculated token amount, scaled by `SpotMarketConfig.precision`
21
+ */
5
22
  export declare function getTokenAmount(balanceAmount: BN, spotMarket: SpotMarketAccount, balanceType: SpotBalanceType): BN;
23
+ /**
24
+ * Returns the signed (positive for deposit,negative for borrow) token amount based on the balance type.
25
+ *
26
+ * @param {BN} tokenAmount - The token amount to convert (from `getTokenAmount`)
27
+ * @param {SpotBalanceType} balanceType - The balance type to determine the sign of the token amount.
28
+ * @returns {BN} - The signed token amount, scaled by `SpotMarketConfig.precision`
29
+ */
6
30
  export declare function getSignedTokenAmount(tokenAmount: BN, balanceType: SpotBalanceType): BN;
31
+ /**
32
+ * Calculates the value of a given token amount using the worst of the provided oracle price and its TWAP.
33
+ *
34
+ * @param {BN} tokenAmount - The amount of tokens to calculate the value for (from `getTokenAmount`)
35
+ * @param {number} spotDecimals - The number of decimals in the token.
36
+ * @param {OraclePriceData} oraclePriceData - The oracle price data (typically a token/USD oracle).
37
+ * @param {BN} oraclePriceTwap - The Time-Weighted Average Price of the oracle.
38
+ * @return {BN} The calculated value of the given token amount, scaled by `PRICE_PRECISION`
39
+ */
7
40
  export declare function getStrictTokenValue(tokenAmount: BN, spotDecimals: number, oraclePriceData: OraclePriceData, oraclePriceTwap: BN): BN;
41
+ /**
42
+ * Calculates the value of a given token amount in relation to an oracle price data
43
+ *
44
+ * @param {BN} tokenAmount - The amount of tokens to calculate the value for (from `getTokenAmount`)
45
+ * @param {number} spotDecimals - The number of decimal places of the token.
46
+ * @param {OraclePriceData} oraclePriceData - The oracle price data (typically a token/USD oracle).
47
+ * @return {BN} The value of the token based on the oracle, scaled by `PRICE_PRECISION`
48
+ */
8
49
  export declare function getTokenValue(tokenAmount: BN, spotDecimals: number, oraclePriceData: OraclePriceData): BN;
9
50
  export declare function calculateAssetWeight(balanceAmount: BN, spotMarket: SpotMarketAccount, marginCategory: MarginCategory): BN;
10
51
  export declare function calculateLiabilityWeight(size: BN, spotMarket: SpotMarketAccount, marginCategory: MarginCategory): BN;
@@ -7,6 +7,15 @@ const numericConstants_1 = require("../constants/numericConstants");
7
7
  const margin_1 = require("./margin");
8
8
  const numericConstants_2 = require("../constants/numericConstants");
9
9
  const utils_1 = require("./utils");
10
+ /**
11
+ * Calculates the balance of a given token amount including any accumulated interest. This
12
+ * is the same as `SpotPosition.scaledBalance`.
13
+ *
14
+ * @param {BN} tokenAmount - the amount of tokens
15
+ * @param {SpotMarketAccount} spotMarket - the spot market account
16
+ * @param {SpotBalanceType} balanceType - the balance type ('deposit' or 'borrow')
17
+ * @return {BN} the calculated balance, scaled by `SPOT_MARKET_BALANCE_PRECISION`
18
+ */
10
19
  function getBalance(tokenAmount, spotMarket, balanceType) {
11
20
  const precisionIncrease = numericConstants_1.TEN.pow(new anchor_1.BN(19 - spotMarket.decimals));
12
21
  const cumulativeInterest = (0, types_1.isVariant)(balanceType, 'deposit')
@@ -19,6 +28,14 @@ function getBalance(tokenAmount, spotMarket, balanceType) {
19
28
  return balance;
20
29
  }
21
30
  exports.getBalance = getBalance;
31
+ /**
32
+ * Calculates the spot token amount including any accumulated interest.
33
+ *
34
+ * @param {BN} balanceAmount - The balance amount, typically from `SpotPosition.scaledBalance`
35
+ * @param {SpotMarketAccount} spotMarket - The spot market account details
36
+ * @param {SpotBalanceType} balanceType - The balance type to be used for calculation
37
+ * @returns {BN} The calculated token amount, scaled by `SpotMarketConfig.precision`
38
+ */
22
39
  function getTokenAmount(balanceAmount, spotMarket, balanceType) {
23
40
  const precisionDecrease = numericConstants_1.TEN.pow(new anchor_1.BN(19 - spotMarket.decimals));
24
41
  if ((0, types_1.isVariant)(balanceType, 'deposit')) {
@@ -31,6 +48,13 @@ function getTokenAmount(balanceAmount, spotMarket, balanceType) {
31
48
  }
32
49
  }
33
50
  exports.getTokenAmount = getTokenAmount;
51
+ /**
52
+ * Returns the signed (positive for deposit,negative for borrow) token amount based on the balance type.
53
+ *
54
+ * @param {BN} tokenAmount - The token amount to convert (from `getTokenAmount`)
55
+ * @param {SpotBalanceType} balanceType - The balance type to determine the sign of the token amount.
56
+ * @returns {BN} - The signed token amount, scaled by `SpotMarketConfig.precision`
57
+ */
34
58
  function getSignedTokenAmount(tokenAmount, balanceType) {
35
59
  if ((0, types_1.isVariant)(balanceType, 'deposit')) {
36
60
  return tokenAmount;
@@ -40,6 +64,15 @@ function getSignedTokenAmount(tokenAmount, balanceType) {
40
64
  }
41
65
  }
42
66
  exports.getSignedTokenAmount = getSignedTokenAmount;
67
+ /**
68
+ * Calculates the value of a given token amount using the worst of the provided oracle price and its TWAP.
69
+ *
70
+ * @param {BN} tokenAmount - The amount of tokens to calculate the value for (from `getTokenAmount`)
71
+ * @param {number} spotDecimals - The number of decimals in the token.
72
+ * @param {OraclePriceData} oraclePriceData - The oracle price data (typically a token/USD oracle).
73
+ * @param {BN} oraclePriceTwap - The Time-Weighted Average Price of the oracle.
74
+ * @return {BN} The calculated value of the given token amount, scaled by `PRICE_PRECISION`
75
+ */
43
76
  function getStrictTokenValue(tokenAmount, spotDecimals, oraclePriceData, oraclePriceTwap) {
44
77
  if (tokenAmount.eq(numericConstants_1.ZERO)) {
45
78
  return numericConstants_1.ZERO;
@@ -55,6 +88,14 @@ function getStrictTokenValue(tokenAmount, spotDecimals, oraclePriceData, oracleP
55
88
  return tokenAmount.mul(price).div(precisionDecrease);
56
89
  }
57
90
  exports.getStrictTokenValue = getStrictTokenValue;
91
+ /**
92
+ * Calculates the value of a given token amount in relation to an oracle price data
93
+ *
94
+ * @param {BN} tokenAmount - The amount of tokens to calculate the value for (from `getTokenAmount`)
95
+ * @param {number} spotDecimals - The number of decimal places of the token.
96
+ * @param {OraclePriceData} oraclePriceData - The oracle price data (typically a token/USD oracle).
97
+ * @return {BN} The value of the token based on the oracle, scaled by `PRICE_PRECISION`
98
+ */
58
99
  function getTokenValue(tokenAmount, spotDecimals, oraclePriceData) {
59
100
  if (tokenAmount.eq(numericConstants_1.ZERO)) {
60
101
  return numericConstants_1.ZERO;
@@ -1,3 +1,4 @@
1
1
  /// <reference types="node" />
2
- import { AccountInfo } from '@solana/spl-token';
3
- export declare function parseTokenAccount(data: Buffer): AccountInfo;
2
+ import { Account } from '@solana/spl-token';
3
+ import { PublicKey } from '@solana/web3.js';
4
+ export declare function parseTokenAccount(data: Buffer, pubkey: PublicKey): Account;