flash-sdk 1.0.108 → 1.0.109

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,27 @@ 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
+ console.log("swapOut", swapAmountOut.toString());
1152
+ finalCollateralAmount = swapAmountOut;
1153
+ }
1154
+ var collateralMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1155
+ var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(finalCollateralAmount, collateralTokenCustodyAccount.decimals);
1156
+ var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd);
1157
+ if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
1158
+ return sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
1159
+ }
1160
+ else {
1161
+ return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
1162
+ }
1163
+ };
1142
1164
  this.getEntryPriceAndFeeSync = function (positionAccount, collateralDeltaAmount, sizeDeltaAmount, side, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp) {
1143
1165
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
1144
1166
  throw new Error("Delta Amounts cannot be negative.");
@@ -1231,6 +1253,29 @@ var PerpetualsClient = (function () {
1231
1253
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUi);
1232
1254
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(marketToken.decimals, bignumber_js_1.default.ROUND_DOWN), marketToken.decimals);
1233
1255
  };
1256
+ this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount, poolAumUsdMax, poolConfig) {
1257
+ var finalCollateralAmount = constants_1.BN_ZERO;
1258
+ if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
1259
+ finalCollateralAmount = amountIn;
1260
+ console.log("no swap needed");
1261
+ }
1262
+ else {
1263
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, poolAumUsdMax, poolConfig).minAmountOut;
1264
+ console.log("swapOut", swapAmountOut.toString());
1265
+ finalCollateralAmount = swapAmountOut;
1266
+ }
1267
+ var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1268
+ var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1269
+ var entryPriceBN = _this.getEntryPriceSync(side, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount);
1270
+ var entryPriceUi = new bignumber_js_1.default(entryPriceBN.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1271
+ var collateralAmtMinUsdUi = new bignumber_js_1.default(finalCollateralAmount.toString()).dividedBy(Math.pow(10, collateralTokenCustodyAccount.decimals))
1272
+ .multipliedBy(collateralTokenMinPriceUi);
1273
+ var openPosFeeRateUi = new bignumber_js_1.default(marketTokenCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
1274
+ var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
1275
+ .dividedBy(new bignumber_js_1.default(1).plus(openPosFeeRateUi.multipliedBy(leverage)));
1276
+ var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUi);
1277
+ return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(marketTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), marketTokenCustodyAccount.decimals);
1278
+ };
1234
1279
  this.getCollateralAmountWithFeeFromLeverageAndSize = function (sizeAmount, leverage, marketToken, collateralToken, side, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount) {
1235
1280
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
1236
1281
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
@@ -1243,6 +1288,27 @@ var PerpetualsClient = (function () {
1243
1288
  var collateralAmtWithFeeUi = collateralWithFeeUsdUi.dividedBy(collateralTokenMinPriceUi);
1244
1289
  return (0, utils_1.uiDecimalsToNative)(collateralAmtWithFeeUi.toFixed(collateralToken.decimals, bignumber_js_1.default.ROUND_DOWN), collateralToken.decimals);
1245
1290
  };
1291
+ this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount, poolAumUsdMax, poolConfig) {
1292
+ var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1293
+ var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1294
+ var entryPriceBN = _this.getEntryPriceSync(side, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount);
1295
+ var entryPriceUi = new bignumber_js_1.default(entryPriceBN.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1296
+ var openPosFeeRateUi = new bignumber_js_1.default(marketTokenCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
1297
+ var sizeAmountUi = new bignumber_js_1.default(sizeAmount.toString()).dividedBy(Math.pow(10, marketTokenCustodyAccount.decimals));
1298
+ var sizeUsdUi = entryPriceUi.multipliedBy(sizeAmountUi);
1299
+ var collateralWithFeeUsdUi = sizeUsdUi.multipliedBy(new bignumber_js_1.default(1).plus(openPosFeeRateUi.multipliedBy(leverage))).dividedBy(leverage);
1300
+ var collateralAmtWithFeeUi = collateralWithFeeUsdUi.dividedBy(collateralTokenMinPriceUi);
1301
+ var collateralAmountWithFee = (0, utils_1.uiDecimalsToNative)(collateralAmtWithFeeUi.toFixed(collateralTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), collateralTokenCustodyAccount.decimals);
1302
+ var collateralInInputToken;
1303
+ if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
1304
+ console.log("no swap needed");
1305
+ collateralInInputToken = collateralAmountWithFee;
1306
+ }
1307
+ else {
1308
+ collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, poolAumUsdMax, poolConfig).minAmountIn;
1309
+ }
1310
+ return collateralInInputToken;
1311
+ };
1246
1312
  this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, sizeDeltaUsd, keepLevSame, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp) {
1247
1313
  if (!marketCustodyAccount.publicKey.equals(positionAccount.custody)) {
1248
1314
  throw new Error("marketCustodyAccount mismatch");
@@ -1723,6 +1789,151 @@ var PerpetualsClient = (function () {
1723
1789
  });
1724
1790
  });
1725
1791
  };
1792
+ this.openPositionWithSwap = function (marketSymbol, inputSymbol, collateralSymbol, amountIn, minAmountOut, priceAfterSlippage, size, side, poolConfig, skipBalanceChecks) {
1793
+ if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
1794
+ return __awaiter(_this, void 0, void 0, function () {
1795
+ 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;
1796
+ return __generator(this, function (_d) {
1797
+ switch (_d.label) {
1798
+ case 0:
1799
+ publicKey = this.provider.wallet.publicKey;
1800
+ marketCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey); });
1801
+ collateralCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
1802
+ inputCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(inputSymbol).mintKey); });
1803
+ if (inputCustodyConfig.mintKey.equals(collateralCustodyConfig.mintKey)) {
1804
+ throw "Use Simple Swap";
1805
+ }
1806
+ preInstructions = [];
1807
+ instructions = [];
1808
+ postInstructions = [];
1809
+ additionalSigners = [];
1810
+ if (!(inputSymbol == 'SOL')) return [3, 3];
1811
+ console.log("inputSymbol === SOL", inputSymbol);
1812
+ wrappedSolAccount = new web3_js_1.Keypair();
1813
+ return [4, (0, spl_token_1.getMinimumBalanceForRentExemptAccount)(this.provider.connection)];
1814
+ case 1:
1815
+ accCreationLamports = (_d.sent());
1816
+ console.log("accCreationLamports:", accCreationLamports);
1817
+ lamports = amountIn.add(new anchor_1.BN(accCreationLamports));
1818
+ _a = anchor_1.BN.bind;
1819
+ return [4, this.provider.connection.getBalance(publicKey)];
1820
+ case 2:
1821
+ unWrappedSolBalance = new (_a.apply(anchor_1.BN, [void 0, _d.sent()]))();
1822
+ if (unWrappedSolBalance.lt(lamports)) {
1823
+ throw "Insufficient SOL Funds";
1824
+ }
1825
+ preInstructions = [
1826
+ web3_js_1.SystemProgram.createAccount({
1827
+ fromPubkey: publicKey,
1828
+ newAccountPubkey: wrappedSolAccount.publicKey,
1829
+ lamports: lamports.toNumber(),
1830
+ space: 165,
1831
+ programId: spl_token_1.TOKEN_PROGRAM_ID,
1832
+ }),
1833
+ (0, spl_token_1.createInitializeAccount3Instruction)(wrappedSolAccount.publicKey, spl_token_1.NATIVE_MINT, publicKey),
1834
+ ];
1835
+ postInstructions = [
1836
+ (0, spl_token_1.createCloseAccountInstruction)(wrappedSolAccount.publicKey, publicKey, publicKey),
1837
+ ];
1838
+ additionalSigners.push(wrappedSolAccount);
1839
+ return [3, 6];
1840
+ case 3:
1841
+ userInputTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(poolConfig.getTokenFromSymbol(inputSymbol).mintKey, publicKey);
1842
+ return [4, (0, utils_1.checkIfAccountExists)(userInputTokenAccount, this.provider.connection)];
1843
+ case 4:
1844
+ if (!(_d.sent())) {
1845
+ throw "Insufficient Funds , Token Account doesn't exist";
1846
+ }
1847
+ if (!!skipBalanceChecks) return [3, 6];
1848
+ _b = anchor_1.BN.bind;
1849
+ return [4, this.provider.connection.getTokenAccountBalance(userInputTokenAccount)];
1850
+ case 5:
1851
+ tokenAccountBalance = new (_b.apply(anchor_1.BN, [void 0, (_d.sent()).value.amount]))();
1852
+ if (tokenAccountBalance.lt(amountIn)) {
1853
+ throw "Insufficient Funds need more ".concat(amountIn.sub(tokenAccountBalance), " tokens");
1854
+ }
1855
+ _d.label = 6;
1856
+ case 6:
1857
+ userCollateralTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey, publicKey);
1858
+ return [4, (0, utils_1.checkIfAccountExists)(userCollateralTokenAccount, this.provider.connection)];
1859
+ case 7:
1860
+ if (!(_d.sent())) {
1861
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userCollateralTokenAccount, publicKey, poolConfig.getTokenFromSymbol(collateralSymbol).mintKey));
1862
+ }
1863
+ positionAccount = web3_js_1.PublicKey.findProgramAddressSync([
1864
+ Buffer.from("position"),
1865
+ publicKey.toBuffer(),
1866
+ poolConfig.poolAddress.toBuffer(),
1867
+ marketCustodyConfig.custodyAccount.toBuffer(),
1868
+ (0, types_1.isVariant)(side, 'long') ? Buffer.from([1]) : Buffer.from([2]),
1869
+ ], this.programId)[0];
1870
+ custodyAccountMetas = [];
1871
+ custodyOracleAccountMetas = [];
1872
+ custodyCustomOracles = [];
1873
+ for (_i = 0, _c = poolConfig.custodies; _i < _c.length; _i++) {
1874
+ custody = _c[_i];
1875
+ custodyAccountMetas.push({
1876
+ pubkey: custody.custodyAccount,
1877
+ isSigner: false,
1878
+ isWritable: false,
1879
+ });
1880
+ custodyOracleAccountMetas.push({
1881
+ pubkey: custody.oracleAddress,
1882
+ isSigner: false,
1883
+ isWritable: false,
1884
+ });
1885
+ custodyCustomOracles.push({
1886
+ pubkey: web3_js_1.SystemProgram.programId,
1887
+ isSigner: false,
1888
+ isWritable: false,
1889
+ });
1890
+ }
1891
+ return [4, this.programPerpComposability.methods
1892
+ .swapAndOpen({
1893
+ amountIn: amountIn,
1894
+ minAmountOut: minAmountOut,
1895
+ openPrice: priceAfterSlippage,
1896
+ openSize: size,
1897
+ side: side,
1898
+ })
1899
+ .accounts({
1900
+ delegate: publicKey,
1901
+ owner: publicKey,
1902
+ fundingAccount: inputSymbol == 'SOL' ? wrappedSolAccount.publicKey : userInputTokenAccount,
1903
+ receivingAccount: userCollateralTokenAccount,
1904
+ transferAuthority: poolConfig.transferAuthority,
1905
+ perpetuals: poolConfig.perpetuals,
1906
+ pool: poolConfig.poolAddress,
1907
+ receivingCustody: inputCustodyConfig.custodyAccount,
1908
+ receivingCustodyOracleAccount: inputCustodyConfig.oracleAddress,
1909
+ receivingCustodyCustomOracleAccount: web3_js_1.SystemProgram.programId,
1910
+ receivingCustodyTokenAccount: inputCustodyConfig.tokenAccount,
1911
+ dispensingCustody: collateralCustodyConfig.custodyAccount,
1912
+ dispensingCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
1913
+ dispensingCustodyCustomOracleAccount: web3_js_1.SystemProgram.programId,
1914
+ dispensingCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
1915
+ position: positionAccount,
1916
+ custody: marketCustodyConfig.custodyAccount,
1917
+ custodyOracleAccount: marketCustodyConfig.oracleAddress,
1918
+ custodyCustomOracleAccount: web3_js_1.SystemProgram.programId,
1919
+ eventAuthority: this.eventAuthority.publicKey,
1920
+ systemProgram: web3_js_1.SystemProgram.programId,
1921
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1922
+ perpProgram: this.programId,
1923
+ })
1924
+ .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true), custodyCustomOracles, true))
1925
+ .instruction()];
1926
+ case 8:
1927
+ instruction = _d.sent();
1928
+ instructions.push(instruction);
1929
+ return [2, {
1930
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
1931
+ additionalSigners: additionalSigners
1932
+ }];
1933
+ }
1934
+ });
1935
+ });
1936
+ };
1726
1937
  this.closePosition = function (marketSymbol, collateralSymbol, priceAfterSlippage, side, poolConfig, createUserATA, closeUsersWSOLATA) {
1727
1938
  if (createUserATA === void 0) { createUserATA = true; }
1728
1939
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
@@ -2142,6 +2353,142 @@ var PerpetualsClient = (function () {
2142
2353
  });
2143
2354
  });
2144
2355
  };
2356
+ this.addCollateralWithSwap = function (marketSymbol, inputSymbol, collateralSymbol, amountIn, minAmountOut, positionPubKey, poolConfig, skipBalanceChecks) {
2357
+ if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2358
+ return __awaiter(_this, void 0, void 0, function () {
2359
+ 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;
2360
+ return __generator(this, function (_d) {
2361
+ switch (_d.label) {
2362
+ case 0:
2363
+ publicKey = this.provider.wallet.publicKey;
2364
+ collateralCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
2365
+ marketCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey); });
2366
+ inputCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(inputSymbol).mintKey); });
2367
+ if (!collateralCustodyConfig || !marketCustodyConfig || !inputCustodyConfig) {
2368
+ throw "payTokenCustody not found";
2369
+ }
2370
+ if (inputCustodyConfig.mintKey.equals(collateralCustodyConfig.mintKey)) {
2371
+ throw "Use Simple Swap";
2372
+ }
2373
+ preInstructions = [];
2374
+ instructions = [];
2375
+ postInstructions = [];
2376
+ additionalSigners = [];
2377
+ if (!(inputSymbol == 'SOL')) return [3, 3];
2378
+ console.log("inputSymbol === SOL", inputSymbol);
2379
+ wrappedSolAccount = new web3_js_1.Keypair();
2380
+ return [4, (0, spl_token_1.getMinimumBalanceForRentExemptAccount)(this.provider.connection)];
2381
+ case 1:
2382
+ accCreationLamports = (_d.sent());
2383
+ console.log("accCreationLamports:", accCreationLamports);
2384
+ lamports = amountIn.add(new anchor_1.BN(accCreationLamports));
2385
+ console.log("lamports:", lamports.toNumber());
2386
+ _a = anchor_1.BN.bind;
2387
+ return [4, this.provider.connection.getBalance(publicKey)];
2388
+ case 2:
2389
+ unWrappedSolBalance = new (_a.apply(anchor_1.BN, [void 0, _d.sent()]))();
2390
+ if (unWrappedSolBalance.lt(lamports)) {
2391
+ throw "Insufficient SOL Funds";
2392
+ }
2393
+ preInstructions = [
2394
+ web3_js_1.SystemProgram.createAccount({
2395
+ fromPubkey: publicKey,
2396
+ newAccountPubkey: wrappedSolAccount.publicKey,
2397
+ lamports: lamports.toNumber(),
2398
+ space: 165,
2399
+ programId: spl_token_1.TOKEN_PROGRAM_ID,
2400
+ }),
2401
+ (0, spl_token_1.createInitializeAccount3Instruction)(wrappedSolAccount.publicKey, spl_token_1.NATIVE_MINT, publicKey),
2402
+ ];
2403
+ postInstructions = [
2404
+ (0, spl_token_1.createCloseAccountInstruction)(wrappedSolAccount.publicKey, publicKey, publicKey),
2405
+ ];
2406
+ additionalSigners.push(wrappedSolAccount);
2407
+ return [3, 6];
2408
+ case 3:
2409
+ userInputTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(inputCustodyConfig.mintKey, publicKey);
2410
+ return [4, (0, utils_1.checkIfAccountExists)(userInputTokenAccount, this.provider.connection)];
2411
+ case 4:
2412
+ if (!(_d.sent())) {
2413
+ throw "Insufficient Funds , token Account doesn't exist";
2414
+ }
2415
+ if (!!skipBalanceChecks) return [3, 6];
2416
+ _b = anchor_1.BN.bind;
2417
+ return [4, this.provider.connection.getTokenAccountBalance(userInputTokenAccount)];
2418
+ case 5:
2419
+ tokenAccountBalance = new (_b.apply(anchor_1.BN, [void 0, (_d.sent()).value.amount]))();
2420
+ if (tokenAccountBalance.lt(amountIn)) {
2421
+ throw "Insufficient Funds need more ".concat(amountIn.sub(tokenAccountBalance), " tokens");
2422
+ }
2423
+ _d.label = 6;
2424
+ case 6:
2425
+ userCollateralTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(collateralCustodyConfig.mintKey, publicKey);
2426
+ return [4, (0, utils_1.checkIfAccountExists)(userCollateralTokenAccount, this.provider.connection)];
2427
+ case 7:
2428
+ if (!(_d.sent())) {
2429
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userCollateralTokenAccount, publicKey, collateralCustodyConfig.mintKey));
2430
+ }
2431
+ custodyAccountMetas = [];
2432
+ custodyOracleAccountMetas = [];
2433
+ custodyCustomOracles = [];
2434
+ for (_i = 0, _c = poolConfig.custodies; _i < _c.length; _i++) {
2435
+ custody = _c[_i];
2436
+ custodyAccountMetas.push({
2437
+ pubkey: custody.custodyAccount,
2438
+ isSigner: false,
2439
+ isWritable: false,
2440
+ });
2441
+ custodyOracleAccountMetas.push({
2442
+ pubkey: custody.oracleAddress,
2443
+ isSigner: false,
2444
+ isWritable: false,
2445
+ });
2446
+ custodyCustomOracles.push({
2447
+ pubkey: web3_js_1.SystemProgram.programId,
2448
+ isSigner: false,
2449
+ isWritable: false,
2450
+ });
2451
+ }
2452
+ return [4, this.programPerpComposability.methods.swapAndAddCollateral({
2453
+ amountIn: amountIn,
2454
+ minAmountOut: minAmountOut,
2455
+ }).accounts({
2456
+ delegate: publicKey,
2457
+ owner: publicKey,
2458
+ position: positionPubKey,
2459
+ fundingAccount: inputSymbol == 'SOL' ? wrappedSolAccount.publicKey : userInputTokenAccount,
2460
+ receivingAccount: userCollateralTokenAccount,
2461
+ transferAuthority: poolConfig.transferAuthority,
2462
+ perpetuals: poolConfig.perpetuals,
2463
+ pool: poolConfig.poolAddress,
2464
+ receivingCustody: inputCustodyConfig.custodyAccount,
2465
+ receivingCustodyOracleAccount: inputCustodyConfig.oracleAddress,
2466
+ receivingCustodyCustomOracleAccount: web3_js_1.SystemProgram.programId,
2467
+ receivingCustodyTokenAccount: inputCustodyConfig.tokenAccount,
2468
+ dispensingCustody: collateralCustodyConfig.custodyAccount,
2469
+ dispensingCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
2470
+ dispensingCustodyCustomOracleAccount: web3_js_1.SystemProgram.programId,
2471
+ dispensingCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2472
+ custody: marketCustodyConfig.custodyAccount,
2473
+ custodyOracleAccount: marketCustodyConfig.oracleAddress,
2474
+ custodyCustomOracleAccount: web3_js_1.SystemProgram.programId,
2475
+ eventAuthority: this.eventAuthority.publicKey,
2476
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
2477
+ perpProgram: this.programId,
2478
+ })
2479
+ .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true), custodyCustomOracles, true))
2480
+ .instruction()];
2481
+ case 8:
2482
+ instruction = _d.sent();
2483
+ instructions.push(instruction);
2484
+ return [2, {
2485
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
2486
+ additionalSigners: additionalSigners
2487
+ }];
2488
+ }
2489
+ });
2490
+ });
2491
+ };
2145
2492
  this.removeCollateral = function (collateralWithFee, marketSymbol, collateralSymbol, positionPubKey, poolConfig, createUserATA, closeUsersWSOLATA) {
2146
2493
  if (createUserATA === void 0) { createUserATA = true; }
2147
2494
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
@@ -2619,7 +2966,9 @@ var PerpetualsClient = (function () {
2619
2966
  this.provider = provider;
2620
2967
  (0, anchor_1.setProvider)(provider);
2621
2968
  this.program = new anchor_1.Program(perpetuals_1.IDL, programId);
2969
+ this.programPerpComposability = new anchor_1.Program(perp_composability_1.IDL, composabilityProgramId);
2622
2970
  this.programId = programId;
2971
+ this.composabilityProgramId = composabilityProgramId;
2623
2972
  this.admin = this.provider.wallet.publicKey;
2624
2973
  this.multisig = this.findProgramAddress("multisig");
2625
2974
  this.authority = this.findProgramAddress("transfer_authority");