flash-sdk 1.0.108 → 1.0.110

Sign up to get free protection for your applications and to get access to all the features.
@@ -7,6 +7,7 @@ import { AddLiquidityAmountAndFee, AumCalcMode, BorrowRateParams, EntryPriceAndF
7
7
  import { OraclePrice } from "./OraclePrice";
8
8
  import { CustodyAccount } from "./CustodyAccount";
9
9
  import { Perpetuals } from "./idl/perpetuals";
10
+ import { PerpComposability } from "./idl/perp_composability";
10
11
  import { SendTransactionOpts } from "./utils/rpc";
11
12
  import { PoolConfig, Token } from "./PoolConfig";
12
13
  import { max } from "bn.js";
@@ -20,8 +21,10 @@ export type PerpClientOptions = {
20
21
  export declare class PerpetualsClient {
21
22
  provider: AnchorProvider;
22
23
  program: Program<Perpetuals>;
24
+ programPerpComposability: Program<PerpComposability>;
23
25
  admin: PublicKey;
24
26
  programId: PublicKey;
27
+ composabilityProgramId: PublicKey;
25
28
  multisig: {
26
29
  publicKey: PublicKey;
27
30
  bump: number;
@@ -42,7 +45,7 @@ export declare class PerpetualsClient {
42
45
  private postSendTxCallback?;
43
46
  private prioritizationFee;
44
47
  private txConfirmationCommitment;
45
- constructor(provider: AnchorProvider, programId: PublicKey, opts: PerpClientOptions);
48
+ constructor(provider: AnchorProvider, programId: PublicKey, composabilityProgramId: PublicKey, opts: PerpClientOptions);
46
49
  setPrioritizationFee: (fee: number) => void;
47
50
  loadAddressLookupTable: (poolConfig: PoolConfig) => Promise<void>;
48
51
  findProgramAddress: (label: string, extraSeeds?: any) => {
@@ -2198,12 +2201,15 @@ export declare class PerpetualsClient {
2198
2201
  checkIfPriceStaleOrCustom: (price: OraclePrice, emaPrice: OraclePrice, custodyAccount: CustodyAccount, timestampInSeconds: BN) => boolean;
2199
2202
  getAveragePriceSync: (price1: BN, size1: BN, price2: BN, size2: BN) => BN;
2200
2203
  getLeverageSync: (sizeUsd: BN, collateralAmount: BN, collateralMinOraclePrice: OraclePrice, collateralTokenDecimals: number, pnlUsd: BN) => BN;
2204
+ getLeverageAtAmountEntryWithSwapSync: (positionAccount: PositionAccount | null, collateralDeltaAmount: BN, sizeDeltaAmount: BN, sizeUsd: BN, inputAmount: BN, poolAccount: PoolAccount, inputTokenPrice: OraclePrice, inputTokenEmaPrice: OraclePrice, inputTokenCustodyAccount: CustodyAccount, collateralTokenPrice: OraclePrice, collateralTokenEmaPrice: OraclePrice, collateralTokenCustodyAccount: CustodyAccount, marketTokenPrice: OraclePrice, marketTokenEmaPrice: OraclePrice, marketTokenCustodyAccount: CustodyAccount, poolAumUsdMax: BN, poolConfig: PoolConfig, pnlUsd: BN) => BN;
2201
2205
  getEntryPriceAndFeeSync: (positionAccount: PositionAccount | null, collateralDeltaAmount: BN, sizeDeltaAmount: BN, side: Side, marketPrice: OraclePrice, marketEmaPrice: OraclePrice, marketCustodyAccount: CustodyAccount, collateralPrice: OraclePrice, collateralEmaPrice: OraclePrice, collateralCustodyAccount: CustodyAccount, currentTimestamp: BN) => EntryPriceAndFee;
2202
2206
  getEntryPriceSync: (side: Side, marketPrice: OraclePrice, marketEmaPrice: OraclePrice, marketCustodyAccount: CustodyAccount) => BN;
2203
2207
  getExitPriceAndFeeSync: (positionAccount: PositionAccount, collateralDeltaAmount: BN, sizeDeltaAmount: BN, side: Side, marketPrice: OraclePrice, marketEmaPrice: OraclePrice, marketCustodyAccount: CustodyAccount, collateralPrice: OraclePrice, collateralEmaPrice: OraclePrice, collateralCustodyAccount: CustodyAccount, currentTimestamp: BN) => ExitPriceAndFee;
2204
2208
  getExitPriceSync: (side: Side, marketPrice: OraclePrice, marketEmaPrice: OraclePrice, marketCustodyAccount: CustodyAccount) => BN;
2205
2209
  getSizeAmountFromLeverageAndCollateral: (collateralAmtWithFee: BN, leverage: string, marketToken: Token, collateralToken: Token, side: Side, marketPrice: OraclePrice, marketEmaPrice: OraclePrice, marketCustodyAccount: CustodyAccount, collateralPrice: OraclePrice, collateralEmaPrice: OraclePrice, collateralCustodyAccount: CustodyAccount) => BN;
2210
+ getSizeAmountWithSwapSync: (amountIn: BN, leverage: string, side: Side, poolAccount: PoolAccount, inputTokenPrice: OraclePrice, inputTokenEmaPrice: OraclePrice, inputTokenCustodyAccount: CustodyAccount, collateralTokenPrice: OraclePrice, collateralTokenEmaPrice: OraclePrice, collateralTokenCustodyAccount: CustodyAccount, marketTokenPrice: OraclePrice, marketTokenEmaPrice: OraclePrice, marketTokenCustodyAccount: CustodyAccount, poolAumUsdMax: BN, poolConfig: PoolConfig) => BN;
2206
2211
  getCollateralAmountWithFeeFromLeverageAndSize: (sizeAmount: BN, leverage: string, marketToken: Token, collateralToken: Token, side: Side, marketPrice: OraclePrice, marketEmaPrice: OraclePrice, marketCustodyAccount: CustodyAccount, collateralPrice: OraclePrice, collateralEmaPrice: OraclePrice, collateralCustodyAccount: CustodyAccount) => BN;
2212
+ getCollateralAmountWithSwapSync: (sizeAmount: BN, leverage: string, side: Side, poolAccount: PoolAccount, inputTokenPrice: OraclePrice, inputTokenEmaPrice: OraclePrice, inputTokenCustodyAccount: CustodyAccount, collateralTokenPrice: OraclePrice, collateralTokenEmaPrice: OraclePrice, collateralTokenCustodyAccount: CustodyAccount, marketTokenPrice: OraclePrice, marketTokenEmaPrice: OraclePrice, marketTokenCustodyAccount: CustodyAccount, poolAumUsdMax: BN, poolConfig: PoolConfig) => BN;
2207
2213
  getDecreaseSizeCollateralAndFeeSync: (positionAccount: PositionAccount, sizeDeltaUsd: BN, keepLevSame: boolean, marketPrice: OraclePrice, marketEmaPrice: OraclePrice, marketCustodyAccount: CustodyAccount, collateralPrice: OraclePrice, collateralEmaPrice: OraclePrice, collateralCustodyAccount: CustodyAccount, currentTimestamp: BN) => RemoveCollateralData;
2208
2214
  getFinalCloseAmountSync: (positionAccount: PositionAccount, marketPrice: OraclePrice, marketEmaPrice: OraclePrice, marketCustodyAccount: CustodyAccount, collateralPrice: OraclePrice, collateralEmaPrice: OraclePrice, collateralCustodyAccount: CustodyAccount, currentTimestamp: BN) => {
2209
2215
  finalAmount: BN;
@@ -2232,6 +2238,10 @@ export declare class PerpetualsClient {
2232
2238
  instructions: TransactionInstruction[];
2233
2239
  additionalSigners: Signer[];
2234
2240
  }>;
2241
+ openPositionWithSwap: (marketSymbol: string, inputSymbol: string, collateralSymbol: string, amountIn: BN, minAmountOut: BN, priceAfterSlippage: BN, size: BN, side: Side, poolConfig: PoolConfig, skipBalanceChecks?: boolean) => Promise<{
2242
+ instructions: TransactionInstruction[];
2243
+ additionalSigners: Signer[];
2244
+ }>;
2235
2245
  closePosition: (marketSymbol: string, collateralSymbol: string, priceAfterSlippage: BN, side: Side, poolConfig: PoolConfig, createUserATA?: boolean, closeUsersWSOLATA?: boolean) => Promise<{
2236
2246
  instructions: TransactionInstruction[];
2237
2247
  additionalSigners: Signer[];
@@ -2244,6 +2254,10 @@ export declare class PerpetualsClient {
2244
2254
  instructions: TransactionInstruction[];
2245
2255
  additionalSigners: Signer[];
2246
2256
  }>;
2257
+ addCollateralWithSwap: (marketSymbol: string, inputSymbol: string, collateralSymbol: string, amountIn: BN, minAmountOut: BN, positionPubKey: PublicKey, poolConfig: PoolConfig, skipBalanceChecks?: boolean) => Promise<{
2258
+ instructions: TransactionInstruction[];
2259
+ additionalSigners: Signer[];
2260
+ }>;
2247
2261
  removeCollateral: (collateralWithFee: BN, marketSymbol: string, collateralSymbol: string, positionPubKey: PublicKey, poolConfig: PoolConfig, createUserATA?: boolean, closeUsersWSOLATA?: boolean) => Promise<{
2248
2262
  instructions: TransactionInstruction[];
2249
2263
  additionalSigners: Signer[];
@@ -69,12 +69,13 @@ var PositionAccount_1 = require("./PositionAccount");
69
69
  var types_1 = require("./types");
70
70
  var OraclePrice_1 = require("./OraclePrice");
71
71
  var perpetuals_1 = require("./idl/perpetuals");
72
+ var perp_composability_1 = require("./idl/perp_composability");
72
73
  var rpc_1 = require("./utils/rpc");
73
74
  var utils_1 = require("./utils");
74
75
  var constants_1 = require("./constants");
75
76
  var bignumber_js_1 = __importDefault(require("bignumber.js"));
76
77
  var PerpetualsClient = (function () {
77
- function PerpetualsClient(provider, programId, opts) {
78
+ function PerpetualsClient(provider, programId, composabilityProgramId, opts) {
78
79
  var _this = this;
79
80
  var _a;
80
81
  this.addressLookupTables = [];
@@ -1139,6 +1140,26 @@ var PerpetualsClient = (function () {
1139
1140
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
1140
1141
  }
1141
1142
  };
1143
+ this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, collateralDeltaAmount, sizeDeltaAmount, sizeUsd, inputAmount, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount, poolAumUsdMax, poolConfig, pnlUsd) {
1144
+ var finalCollateralAmount;
1145
+ if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
1146
+ finalCollateralAmount = inputAmount;
1147
+ console.log("no swap needed");
1148
+ }
1149
+ else {
1150
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(inputAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, poolAumUsdMax, poolConfig).minAmountOut;
1151
+ finalCollateralAmount = swapAmountOut;
1152
+ }
1153
+ var collateralMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1154
+ var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(finalCollateralAmount, collateralTokenCustodyAccount.decimals);
1155
+ var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd);
1156
+ if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
1157
+ return sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
1158
+ }
1159
+ else {
1160
+ return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
1161
+ }
1162
+ };
1142
1163
  this.getEntryPriceAndFeeSync = function (positionAccount, collateralDeltaAmount, sizeDeltaAmount, side, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp) {
1143
1164
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
1144
1165
  throw new Error("Delta Amounts cannot be negative.");
@@ -1231,6 +1252,28 @@ var PerpetualsClient = (function () {
1231
1252
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUi);
1232
1253
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(marketToken.decimals, bignumber_js_1.default.ROUND_DOWN), marketToken.decimals);
1233
1254
  };
1255
+ this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount, poolAumUsdMax, poolConfig) {
1256
+ var finalCollateralAmount = constants_1.BN_ZERO;
1257
+ if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
1258
+ finalCollateralAmount = amountIn;
1259
+ console.log("no swap needed");
1260
+ }
1261
+ else {
1262
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, poolAumUsdMax, poolConfig).minAmountOut;
1263
+ finalCollateralAmount = swapAmountOut;
1264
+ }
1265
+ var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1266
+ var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1267
+ var entryPriceBN = _this.getEntryPriceSync(side, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount);
1268
+ var entryPriceUi = new bignumber_js_1.default(entryPriceBN.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1269
+ var collateralAmtMinUsdUi = new bignumber_js_1.default(finalCollateralAmount.toString()).dividedBy(Math.pow(10, collateralTokenCustodyAccount.decimals))
1270
+ .multipliedBy(collateralTokenMinPriceUi);
1271
+ var openPosFeeRateUi = new bignumber_js_1.default(marketTokenCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
1272
+ var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
1273
+ .dividedBy(new bignumber_js_1.default(1).plus(openPosFeeRateUi.multipliedBy(leverage)));
1274
+ var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUi);
1275
+ return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(marketTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), marketTokenCustodyAccount.decimals);
1276
+ };
1234
1277
  this.getCollateralAmountWithFeeFromLeverageAndSize = function (sizeAmount, leverage, marketToken, collateralToken, side, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount) {
1235
1278
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
1236
1279
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
@@ -1243,6 +1286,27 @@ var PerpetualsClient = (function () {
1243
1286
  var collateralAmtWithFeeUi = collateralWithFeeUsdUi.dividedBy(collateralTokenMinPriceUi);
1244
1287
  return (0, utils_1.uiDecimalsToNative)(collateralAmtWithFeeUi.toFixed(collateralToken.decimals, bignumber_js_1.default.ROUND_DOWN), collateralToken.decimals);
1245
1288
  };
1289
+ this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount, poolAumUsdMax, poolConfig) {
1290
+ var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1291
+ var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1292
+ var entryPriceBN = _this.getEntryPriceSync(side, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount);
1293
+ var entryPriceUi = new bignumber_js_1.default(entryPriceBN.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1294
+ var openPosFeeRateUi = new bignumber_js_1.default(marketTokenCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
1295
+ var sizeAmountUi = new bignumber_js_1.default(sizeAmount.toString()).dividedBy(Math.pow(10, marketTokenCustodyAccount.decimals));
1296
+ var sizeUsdUi = entryPriceUi.multipliedBy(sizeAmountUi);
1297
+ var collateralWithFeeUsdUi = sizeUsdUi.multipliedBy(new bignumber_js_1.default(1).plus(openPosFeeRateUi.multipliedBy(leverage))).dividedBy(leverage);
1298
+ var collateralAmtWithFeeUi = collateralWithFeeUsdUi.dividedBy(collateralTokenMinPriceUi);
1299
+ var collateralAmountWithFee = (0, utils_1.uiDecimalsToNative)(collateralAmtWithFeeUi.toFixed(collateralTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), collateralTokenCustodyAccount.decimals);
1300
+ var collateralInInputToken;
1301
+ if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
1302
+ console.log("no swap needed");
1303
+ collateralInInputToken = collateralAmountWithFee;
1304
+ }
1305
+ else {
1306
+ collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, poolAumUsdMax, poolConfig).minAmountIn;
1307
+ }
1308
+ return collateralInInputToken;
1309
+ };
1246
1310
  this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, sizeDeltaUsd, keepLevSame, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp) {
1247
1311
  if (!marketCustodyAccount.publicKey.equals(positionAccount.custody)) {
1248
1312
  throw new Error("marketCustodyAccount mismatch");
@@ -1723,6 +1787,151 @@ var PerpetualsClient = (function () {
1723
1787
  });
1724
1788
  });
1725
1789
  };
1790
+ this.openPositionWithSwap = function (marketSymbol, inputSymbol, collateralSymbol, amountIn, minAmountOut, priceAfterSlippage, size, side, poolConfig, skipBalanceChecks) {
1791
+ if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
1792
+ return __awaiter(_this, void 0, void 0, function () {
1793
+ var publicKey, marketCustodyConfig, collateralCustodyConfig, inputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userInputTokenAccount, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, userCollateralTokenAccount, positionAccount, custodyAccountMetas, custodyOracleAccountMetas, custodyCustomOracles, _i, _c, custody, instruction;
1794
+ return __generator(this, function (_d) {
1795
+ switch (_d.label) {
1796
+ case 0:
1797
+ publicKey = this.provider.wallet.publicKey;
1798
+ marketCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey); });
1799
+ collateralCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
1800
+ inputCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(inputSymbol).mintKey); });
1801
+ if (inputCustodyConfig.mintKey.equals(collateralCustodyConfig.mintKey)) {
1802
+ throw "Use Simple Swap";
1803
+ }
1804
+ preInstructions = [];
1805
+ instructions = [];
1806
+ postInstructions = [];
1807
+ additionalSigners = [];
1808
+ if (!(inputSymbol == 'SOL')) return [3, 3];
1809
+ console.log("inputSymbol === SOL", inputSymbol);
1810
+ wrappedSolAccount = new web3_js_1.Keypair();
1811
+ return [4, (0, spl_token_1.getMinimumBalanceForRentExemptAccount)(this.provider.connection)];
1812
+ case 1:
1813
+ accCreationLamports = (_d.sent());
1814
+ console.log("accCreationLamports:", accCreationLamports);
1815
+ lamports = amountIn.add(new anchor_1.BN(accCreationLamports));
1816
+ _a = anchor_1.BN.bind;
1817
+ return [4, this.provider.connection.getBalance(publicKey)];
1818
+ case 2:
1819
+ unWrappedSolBalance = new (_a.apply(anchor_1.BN, [void 0, _d.sent()]))();
1820
+ if (unWrappedSolBalance.lt(lamports)) {
1821
+ throw "Insufficient SOL Funds";
1822
+ }
1823
+ preInstructions = [
1824
+ web3_js_1.SystemProgram.createAccount({
1825
+ fromPubkey: publicKey,
1826
+ newAccountPubkey: wrappedSolAccount.publicKey,
1827
+ lamports: lamports.toNumber(),
1828
+ space: 165,
1829
+ programId: spl_token_1.TOKEN_PROGRAM_ID,
1830
+ }),
1831
+ (0, spl_token_1.createInitializeAccount3Instruction)(wrappedSolAccount.publicKey, spl_token_1.NATIVE_MINT, publicKey),
1832
+ ];
1833
+ postInstructions = [
1834
+ (0, spl_token_1.createCloseAccountInstruction)(wrappedSolAccount.publicKey, publicKey, publicKey),
1835
+ ];
1836
+ additionalSigners.push(wrappedSolAccount);
1837
+ return [3, 6];
1838
+ case 3:
1839
+ userInputTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(poolConfig.getTokenFromSymbol(inputSymbol).mintKey, publicKey);
1840
+ return [4, (0, utils_1.checkIfAccountExists)(userInputTokenAccount, this.provider.connection)];
1841
+ case 4:
1842
+ if (!(_d.sent())) {
1843
+ throw "Insufficient Funds , Token Account doesn't exist";
1844
+ }
1845
+ if (!!skipBalanceChecks) return [3, 6];
1846
+ _b = anchor_1.BN.bind;
1847
+ return [4, this.provider.connection.getTokenAccountBalance(userInputTokenAccount)];
1848
+ case 5:
1849
+ tokenAccountBalance = new (_b.apply(anchor_1.BN, [void 0, (_d.sent()).value.amount]))();
1850
+ if (tokenAccountBalance.lt(amountIn)) {
1851
+ throw "Insufficient Funds need more ".concat(amountIn.sub(tokenAccountBalance), " tokens");
1852
+ }
1853
+ _d.label = 6;
1854
+ case 6:
1855
+ userCollateralTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey, publicKey);
1856
+ return [4, (0, utils_1.checkIfAccountExists)(userCollateralTokenAccount, this.provider.connection)];
1857
+ case 7:
1858
+ if (!(_d.sent())) {
1859
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userCollateralTokenAccount, publicKey, poolConfig.getTokenFromSymbol(collateralSymbol).mintKey));
1860
+ }
1861
+ positionAccount = web3_js_1.PublicKey.findProgramAddressSync([
1862
+ Buffer.from("position"),
1863
+ publicKey.toBuffer(),
1864
+ poolConfig.poolAddress.toBuffer(),
1865
+ marketCustodyConfig.custodyAccount.toBuffer(),
1866
+ (0, types_1.isVariant)(side, 'long') ? Buffer.from([1]) : Buffer.from([2]),
1867
+ ], this.programId)[0];
1868
+ custodyAccountMetas = [];
1869
+ custodyOracleAccountMetas = [];
1870
+ custodyCustomOracles = [];
1871
+ for (_i = 0, _c = poolConfig.custodies; _i < _c.length; _i++) {
1872
+ custody = _c[_i];
1873
+ custodyAccountMetas.push({
1874
+ pubkey: custody.custodyAccount,
1875
+ isSigner: false,
1876
+ isWritable: false,
1877
+ });
1878
+ custodyOracleAccountMetas.push({
1879
+ pubkey: custody.oracleAddress,
1880
+ isSigner: false,
1881
+ isWritable: false,
1882
+ });
1883
+ custodyCustomOracles.push({
1884
+ pubkey: web3_js_1.SystemProgram.programId,
1885
+ isSigner: false,
1886
+ isWritable: false,
1887
+ });
1888
+ }
1889
+ return [4, this.programPerpComposability.methods
1890
+ .swapAndOpen({
1891
+ amountIn: amountIn,
1892
+ minAmountOut: minAmountOut,
1893
+ openPrice: priceAfterSlippage,
1894
+ openSize: size,
1895
+ side: side,
1896
+ })
1897
+ .accounts({
1898
+ delegate: publicKey,
1899
+ owner: publicKey,
1900
+ fundingAccount: inputSymbol == 'SOL' ? wrappedSolAccount.publicKey : userInputTokenAccount,
1901
+ receivingAccount: userCollateralTokenAccount,
1902
+ transferAuthority: poolConfig.transferAuthority,
1903
+ perpetuals: poolConfig.perpetuals,
1904
+ pool: poolConfig.poolAddress,
1905
+ receivingCustody: inputCustodyConfig.custodyAccount,
1906
+ receivingCustodyOracleAccount: inputCustodyConfig.oracleAddress,
1907
+ receivingCustodyCustomOracleAccount: web3_js_1.SystemProgram.programId,
1908
+ receivingCustodyTokenAccount: inputCustodyConfig.tokenAccount,
1909
+ dispensingCustody: collateralCustodyConfig.custodyAccount,
1910
+ dispensingCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
1911
+ dispensingCustodyCustomOracleAccount: web3_js_1.SystemProgram.programId,
1912
+ dispensingCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
1913
+ position: positionAccount,
1914
+ custody: marketCustodyConfig.custodyAccount,
1915
+ custodyOracleAccount: marketCustodyConfig.oracleAddress,
1916
+ custodyCustomOracleAccount: web3_js_1.SystemProgram.programId,
1917
+ eventAuthority: this.eventAuthority.publicKey,
1918
+ systemProgram: web3_js_1.SystemProgram.programId,
1919
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1920
+ perpProgram: this.programId,
1921
+ })
1922
+ .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true), custodyCustomOracles, true))
1923
+ .instruction()];
1924
+ case 8:
1925
+ instruction = _d.sent();
1926
+ instructions.push(instruction);
1927
+ return [2, {
1928
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
1929
+ additionalSigners: additionalSigners
1930
+ }];
1931
+ }
1932
+ });
1933
+ });
1934
+ };
1726
1935
  this.closePosition = function (marketSymbol, collateralSymbol, priceAfterSlippage, side, poolConfig, createUserATA, closeUsersWSOLATA) {
1727
1936
  if (createUserATA === void 0) { createUserATA = true; }
1728
1937
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
@@ -2142,6 +2351,142 @@ var PerpetualsClient = (function () {
2142
2351
  });
2143
2352
  });
2144
2353
  };
2354
+ this.addCollateralWithSwap = function (marketSymbol, inputSymbol, collateralSymbol, amountIn, minAmountOut, positionPubKey, poolConfig, skipBalanceChecks) {
2355
+ if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2356
+ return __awaiter(_this, void 0, void 0, function () {
2357
+ var publicKey, collateralCustodyConfig, marketCustodyConfig, inputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userInputTokenAccount, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, userCollateralTokenAccount, custodyAccountMetas, custodyOracleAccountMetas, custodyCustomOracles, _i, _c, custody, instruction;
2358
+ return __generator(this, function (_d) {
2359
+ switch (_d.label) {
2360
+ case 0:
2361
+ publicKey = this.provider.wallet.publicKey;
2362
+ collateralCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
2363
+ marketCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey); });
2364
+ inputCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(inputSymbol).mintKey); });
2365
+ if (!collateralCustodyConfig || !marketCustodyConfig || !inputCustodyConfig) {
2366
+ throw "payTokenCustody not found";
2367
+ }
2368
+ if (inputCustodyConfig.mintKey.equals(collateralCustodyConfig.mintKey)) {
2369
+ throw "Use Simple Swap";
2370
+ }
2371
+ preInstructions = [];
2372
+ instructions = [];
2373
+ postInstructions = [];
2374
+ additionalSigners = [];
2375
+ if (!(inputSymbol == 'SOL')) return [3, 3];
2376
+ console.log("inputSymbol === SOL", inputSymbol);
2377
+ wrappedSolAccount = new web3_js_1.Keypair();
2378
+ return [4, (0, spl_token_1.getMinimumBalanceForRentExemptAccount)(this.provider.connection)];
2379
+ case 1:
2380
+ accCreationLamports = (_d.sent());
2381
+ console.log("accCreationLamports:", accCreationLamports);
2382
+ lamports = amountIn.add(new anchor_1.BN(accCreationLamports));
2383
+ console.log("lamports:", lamports.toNumber());
2384
+ _a = anchor_1.BN.bind;
2385
+ return [4, this.provider.connection.getBalance(publicKey)];
2386
+ case 2:
2387
+ unWrappedSolBalance = new (_a.apply(anchor_1.BN, [void 0, _d.sent()]))();
2388
+ if (unWrappedSolBalance.lt(lamports)) {
2389
+ throw "Insufficient SOL Funds";
2390
+ }
2391
+ preInstructions = [
2392
+ web3_js_1.SystemProgram.createAccount({
2393
+ fromPubkey: publicKey,
2394
+ newAccountPubkey: wrappedSolAccount.publicKey,
2395
+ lamports: lamports.toNumber(),
2396
+ space: 165,
2397
+ programId: spl_token_1.TOKEN_PROGRAM_ID,
2398
+ }),
2399
+ (0, spl_token_1.createInitializeAccount3Instruction)(wrappedSolAccount.publicKey, spl_token_1.NATIVE_MINT, publicKey),
2400
+ ];
2401
+ postInstructions = [
2402
+ (0, spl_token_1.createCloseAccountInstruction)(wrappedSolAccount.publicKey, publicKey, publicKey),
2403
+ ];
2404
+ additionalSigners.push(wrappedSolAccount);
2405
+ return [3, 6];
2406
+ case 3:
2407
+ userInputTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(inputCustodyConfig.mintKey, publicKey);
2408
+ return [4, (0, utils_1.checkIfAccountExists)(userInputTokenAccount, this.provider.connection)];
2409
+ case 4:
2410
+ if (!(_d.sent())) {
2411
+ throw "Insufficient Funds , token Account doesn't exist";
2412
+ }
2413
+ if (!!skipBalanceChecks) return [3, 6];
2414
+ _b = anchor_1.BN.bind;
2415
+ return [4, this.provider.connection.getTokenAccountBalance(userInputTokenAccount)];
2416
+ case 5:
2417
+ tokenAccountBalance = new (_b.apply(anchor_1.BN, [void 0, (_d.sent()).value.amount]))();
2418
+ if (tokenAccountBalance.lt(amountIn)) {
2419
+ throw "Insufficient Funds need more ".concat(amountIn.sub(tokenAccountBalance), " tokens");
2420
+ }
2421
+ _d.label = 6;
2422
+ case 6:
2423
+ userCollateralTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(collateralCustodyConfig.mintKey, publicKey);
2424
+ return [4, (0, utils_1.checkIfAccountExists)(userCollateralTokenAccount, this.provider.connection)];
2425
+ case 7:
2426
+ if (!(_d.sent())) {
2427
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userCollateralTokenAccount, publicKey, collateralCustodyConfig.mintKey));
2428
+ }
2429
+ custodyAccountMetas = [];
2430
+ custodyOracleAccountMetas = [];
2431
+ custodyCustomOracles = [];
2432
+ for (_i = 0, _c = poolConfig.custodies; _i < _c.length; _i++) {
2433
+ custody = _c[_i];
2434
+ custodyAccountMetas.push({
2435
+ pubkey: custody.custodyAccount,
2436
+ isSigner: false,
2437
+ isWritable: false,
2438
+ });
2439
+ custodyOracleAccountMetas.push({
2440
+ pubkey: custody.oracleAddress,
2441
+ isSigner: false,
2442
+ isWritable: false,
2443
+ });
2444
+ custodyCustomOracles.push({
2445
+ pubkey: web3_js_1.SystemProgram.programId,
2446
+ isSigner: false,
2447
+ isWritable: false,
2448
+ });
2449
+ }
2450
+ return [4, this.programPerpComposability.methods.swapAndAddCollateral({
2451
+ amountIn: amountIn,
2452
+ minAmountOut: minAmountOut,
2453
+ }).accounts({
2454
+ delegate: publicKey,
2455
+ owner: publicKey,
2456
+ position: positionPubKey,
2457
+ fundingAccount: inputSymbol == 'SOL' ? wrappedSolAccount.publicKey : userInputTokenAccount,
2458
+ receivingAccount: userCollateralTokenAccount,
2459
+ transferAuthority: poolConfig.transferAuthority,
2460
+ perpetuals: poolConfig.perpetuals,
2461
+ pool: poolConfig.poolAddress,
2462
+ receivingCustody: inputCustodyConfig.custodyAccount,
2463
+ receivingCustodyOracleAccount: inputCustodyConfig.oracleAddress,
2464
+ receivingCustodyCustomOracleAccount: web3_js_1.SystemProgram.programId,
2465
+ receivingCustodyTokenAccount: inputCustodyConfig.tokenAccount,
2466
+ dispensingCustody: collateralCustodyConfig.custodyAccount,
2467
+ dispensingCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
2468
+ dispensingCustodyCustomOracleAccount: web3_js_1.SystemProgram.programId,
2469
+ dispensingCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2470
+ custody: marketCustodyConfig.custodyAccount,
2471
+ custodyOracleAccount: marketCustodyConfig.oracleAddress,
2472
+ custodyCustomOracleAccount: web3_js_1.SystemProgram.programId,
2473
+ eventAuthority: this.eventAuthority.publicKey,
2474
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
2475
+ perpProgram: this.programId,
2476
+ })
2477
+ .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true), custodyCustomOracles, true))
2478
+ .instruction()];
2479
+ case 8:
2480
+ instruction = _d.sent();
2481
+ instructions.push(instruction);
2482
+ return [2, {
2483
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
2484
+ additionalSigners: additionalSigners
2485
+ }];
2486
+ }
2487
+ });
2488
+ });
2489
+ };
2145
2490
  this.removeCollateral = function (collateralWithFee, marketSymbol, collateralSymbol, positionPubKey, poolConfig, createUserATA, closeUsersWSOLATA) {
2146
2491
  if (createUserATA === void 0) { createUserATA = true; }
2147
2492
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
@@ -2619,7 +2964,9 @@ var PerpetualsClient = (function () {
2619
2964
  this.provider = provider;
2620
2965
  (0, anchor_1.setProvider)(provider);
2621
2966
  this.program = new anchor_1.Program(perpetuals_1.IDL, programId);
2967
+ this.programPerpComposability = new anchor_1.Program(perp_composability_1.IDL, composabilityProgramId);
2622
2968
  this.programId = programId;
2969
+ this.composabilityProgramId = composabilityProgramId;
2623
2970
  this.admin = this.provider.wallet.publicKey;
2624
2971
  this.multisig = this.findProgramAddress("multisig");
2625
2972
  this.authority = this.findProgramAddress("transfer_authority");
@@ -18,6 +18,10 @@ export interface LpStats {
18
18
  export interface CustodyStats {
19
19
  symbol: string;
20
20
  priceUi: string;
21
+ minRatio: BN;
22
+ minRatioUi: string;
23
+ maxRatio: BN;
24
+ maxRatioUi: string;
21
25
  targetRatio: BN;
22
26
  targetRatioUi: string;
23
27
  currentRatio: BN;
@@ -91,8 +91,8 @@ var PoolDataClient = (function () {
91
91
  var utilizationBnUi = (custodyAccount.assets.locked.isZero() || custodyAccount.assets.owned.isZero()) ? new bignumber_js_1.default(0) :
92
92
  lockedBnUi.dividedBy(ownedBnUi).multipliedBy(100);
93
93
  var currentRatioBnUi = totalPoolValueUsd.isZero() ? new bignumber_js_1.default(0) : ownedBnUi.multipliedBy(priceBnUi).dividedBy(totalPoolValueUsdUi).multipliedBy(100);
94
- var minRatioBnUi = new bignumber_js_1.default(20);
95
- var maxRatioBnUi = new bignumber_js_1.default(30);
94
+ var minRatioBnUi = tokenRatio.min.isZero() ? new bignumber_js_1.default(5) : new bignumber_js_1.default(tokenRatio.min.toString()).div(100);
95
+ var maxRatioBnUi = tokenRatio.max.toString() === '10000' ? new bignumber_js_1.default(95) : new bignumber_js_1.default(tokenRatio.max.toString()).div(100);
96
96
  var availableToAddUsdBnUi = currentRatioBnUi.isGreaterThanOrEqualTo(maxRatioBnUi) ?
97
97
  new bignumber_js_1.default(0) :
98
98
  maxRatioBnUi.minus(currentRatioBnUi).multipliedBy(totalPoolValueUsdUi).div(100);
@@ -109,6 +109,10 @@ var PoolDataClient = (function () {
109
109
  custodyDetails.push({
110
110
  symbol: custodyConfig.symbol,
111
111
  priceUi: pricesMap.get(custodyConfig.symbol).price.toUiPrice(2),
112
+ minRatio: tokenRatio.min,
113
+ minRatioUi: (0, utils_1.nativeToUiDecimals)(tokenRatio.min, 2, 2),
114
+ maxRatio: tokenRatio.max,
115
+ maxRatioUi: (0, utils_1.nativeToUiDecimals)(tokenRatio.max, 2, 2),
112
116
  targetRatio: tokenRatio.target,
113
117
  targetRatioUi: (0, utils_1.nativeToUiDecimals)(tokenRatio.target, 2, 2),
114
118
  currentRatio: (0, utils_1.uiDecimalsToNative)(currentRatioBnUi.toString(), 2),