flash-sdk 1.0.4 → 1.0.5

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 (100) hide show
  1. package/lib/CustodyAccount.js +9 -19
  2. package/lib/OraclePrice.d.ts +2 -0
  3. package/lib/OraclePrice.js +4 -0
  4. package/lib/PerpetualsClient.d.ts +26 -5
  5. package/lib/PerpetualsClient.js +586 -24
  6. package/lib/PoolAccount.d.ts +2 -1
  7. package/lib/PoolAccount.js +16 -29
  8. package/lib/PoolConfig.d.ts +7 -2
  9. package/lib/PoolConfig.js +15 -7
  10. package/lib/PoolConfig.json +4 -0
  11. package/lib/{PoolDisplayData.d.ts → PoolDataClient.d.ts} +3 -2
  12. package/lib/{PoolDisplayData.js → PoolDataClient.js} +13 -13
  13. package/lib/PositionAccount.d.ts +1 -0
  14. package/lib/Token.js +1 -0
  15. package/lib/constants/index.d.ts +1 -0
  16. package/lib/idl/perpetuals.d.ts +3675 -0
  17. package/{src/target/types → lib/idl}/perpetuals.js +140 -3
  18. package/lib/index.d.ts +3 -0
  19. package/lib/index.js +5 -0
  20. package/lib/tsconfig.tsbuildinfo +1 -1
  21. package/lib/types/index.d.ts +5 -3
  22. package/lib/types/index.js +21 -1
  23. package/lib/utils/index.d.ts +2 -0
  24. package/lib/utils/index.js +57 -1
  25. package/lib/utils/rpc.d.ts +13 -0
  26. package/lib/utils/rpc.js +217 -0
  27. package/package.json +1 -1
  28. package/src/CustodyAccount.ts +24 -23
  29. package/src/OraclePrice.ts +4 -4
  30. package/src/PerpetualsClient.ts +737 -96
  31. package/src/PoolAccount.ts +34 -32
  32. package/src/PoolConfig.json +4 -0
  33. package/src/PoolConfig.ts +21 -6
  34. package/src/{PoolDisplayData.ts → PoolDataClient.ts} +2 -2
  35. package/src/Token.ts +1 -0
  36. package/src/{target/types → idl}/perpetuals.ts +280 -6
  37. package/src/index.ts +3 -0
  38. package/src/types/index.ts +26 -3
  39. package/src/utils/index.ts +14 -0
  40. package/src/utils/rpc.ts +162 -0
  41. package/lib/CustodyAccount.d.ts.map +0 -1
  42. package/lib/CustodyAccount.js.map +0 -1
  43. package/lib/OraclePrice.d.ts.map +0 -1
  44. package/lib/OraclePrice.js.map +0 -1
  45. package/lib/PerpetualsClient.d.ts.map +0 -1
  46. package/lib/PerpetualsClient.js.map +0 -1
  47. package/lib/PoolAccount.d.ts.map +0 -1
  48. package/lib/PoolAccount.js.map +0 -1
  49. package/lib/PositionAccount.d.ts.map +0 -1
  50. package/lib/PositionAccount.js.map +0 -1
  51. package/lib/client/src/CustodyAccount.d.ts +0 -30
  52. package/lib/client/src/CustodyAccount.d.ts.map +0 -1
  53. package/lib/client/src/CustodyAccount.js +0 -64
  54. package/lib/client/src/CustodyAccount.js.map +0 -1
  55. package/lib/client/src/OraclePrice.d.ts +0 -19
  56. package/lib/client/src/OraclePrice.d.ts.map +0 -1
  57. package/lib/client/src/OraclePrice.js +0 -84
  58. package/lib/client/src/OraclePrice.js.map +0 -1
  59. package/lib/client/src/PerpetualsClient.d.ts +0 -1938
  60. package/lib/client/src/PerpetualsClient.d.ts.map +0 -1
  61. package/lib/client/src/PerpetualsClient.js +0 -1043
  62. package/lib/client/src/PerpetualsClient.js.map +0 -1
  63. package/lib/client/src/PoolAccount.d.ts +0 -35
  64. package/lib/client/src/PoolAccount.d.ts.map +0 -1
  65. package/lib/client/src/PoolAccount.js +0 -307
  66. package/lib/client/src/PoolAccount.js.map +0 -1
  67. package/lib/client/src/PositionAccount.d.ts +0 -27
  68. package/lib/client/src/PositionAccount.d.ts.map +0 -1
  69. package/lib/client/src/PositionAccount.js +0 -91
  70. package/lib/client/src/PositionAccount.js.map +0 -1
  71. package/lib/client/src/constants/index.d.ts +0 -12
  72. package/lib/client/src/constants/index.d.ts.map +0 -1
  73. package/lib/client/src/constants/index.js +0 -15
  74. package/lib/client/src/constants/index.js.map +0 -1
  75. package/lib/client/src/index.d.ts +0 -9
  76. package/lib/client/src/index.d.ts.map +0 -1
  77. package/lib/client/src/index.js +0 -26
  78. package/lib/client/src/index.js.map +0 -1
  79. package/lib/client/src/types/index.d.ts +0 -188
  80. package/lib/client/src/types/index.d.ts.map +0 -1
  81. package/lib/client/src/types/index.js +0 -57
  82. package/lib/client/src/types/index.js.map +0 -1
  83. package/lib/client/src/utils/helpers.d.ts +0 -8
  84. package/lib/client/src/utils/helpers.d.ts.map +0 -1
  85. package/lib/client/src/utils/helpers.js +0 -152
  86. package/lib/client/src/utils/helpers.js.map +0 -1
  87. package/lib/constants/index.d.ts.map +0 -1
  88. package/lib/constants/index.js.map +0 -1
  89. package/lib/index.d.ts.map +0 -1
  90. package/lib/index.js.map +0 -1
  91. package/lib/types/index.d.ts.map +0 -1
  92. package/lib/types/index.js.map +0 -1
  93. package/lib/utils/helpers.d.ts +0 -7
  94. package/lib/utils/helpers.d.ts.map +0 -1
  95. package/lib/utils/helpers.js +0 -151
  96. package/lib/utils/helpers.js.map +0 -1
  97. package/src/target/types/limit_order_cpi.js +0 -132
  98. package/src/target/types/limit_order_cpi.ts +0 -259
  99. /package/{src/target/idl/perpetuals.json → lib/Token.d.ts} +0 -0
  100. /package/src/{readme.md → type-rules.md} +0 -0
@@ -1,4 +1,15 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
14
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
15
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -35,6 +46,15 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
35
46
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
47
  }
37
48
  };
49
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
50
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
51
+ if (ar || !(i in from)) {
52
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
53
+ ar[i] = from[i];
54
+ }
55
+ }
56
+ return to.concat(ar || Array.prototype.slice.call(from));
57
+ };
38
58
  Object.defineProperty(exports, "__esModule", { value: true });
39
59
  exports.PerpetualsClient = void 0;
40
60
  var anchor_1 = require("@coral-xyz/anchor");
@@ -43,31 +63,14 @@ var spl_token_1 = require("@solana/spl-token");
43
63
  var js_sha256_1 = require("js-sha256");
44
64
  var bs58_1 = require("bs58");
45
65
  var PositionAccount_1 = require("./PositionAccount");
46
- var perpetuals_1 = require("./target/types/perpetuals");
47
- /* USEAGE
48
-
49
- UI ---
50
- provider = from phatom
51
-
52
- client = new PerpetualsClient(provider, user.pubkey , programId);
53
-
54
- BOT cli --------
55
-
56
- provider = await getProvider(new DefaultWallet(DEFAULT_PERPS_USER));
57
-
58
- AnchorProvider.local(clusterUrl, {
59
- commitment: "confirmed",
60
- preflightCommitment: "confirmed",
61
- skipPreflight: true
62
- });
63
- process.env["ANCHOR_WALLET"] = adminKeyPath;
64
-
65
- client = new PerpetualsClient(provider, DEFAULT_PERPS_USER.pubkey , programId);
66
-
67
- */
66
+ var types_1 = require("./types");
67
+ var perpetuals_1 = require("./idl/perpetuals");
68
+ var rpc_1 = require("./utils/rpc");
69
+ var utils_1 = require("./utils");
68
70
  var PerpetualsClient = /** @class */ (function () {
69
- function PerpetualsClient(provider, programId) {
71
+ function PerpetualsClient(provider, programId, opts) {
70
72
  var _this = this;
73
+ var _a;
71
74
  this.findProgramAddress = function (label, extraSeeds) {
72
75
  if (extraSeeds === void 0) { extraSeeds = null; }
73
76
  var seeds = [Buffer.from(anchor_1.utils.bytes.utf8.encode(label))];
@@ -990,7 +993,7 @@ var PerpetualsClient = /** @class */ (function () {
990
993
  }
991
994
  });
992
995
  }); };
993
- this.getAum = function (poolName) { return __awaiter(_this, void 0, void 0, function () {
996
+ this.getAumView = function (poolName) { return __awaiter(_this, void 0, void 0, function () {
994
997
  var _a, _b;
995
998
  return __generator(this, function (_c) {
996
999
  switch (_c.label) {
@@ -1013,6 +1016,549 @@ var PerpetualsClient = /** @class */ (function () {
1013
1016
  }
1014
1017
  });
1015
1018
  }); };
1019
+ this.getAumTrx = function (poolName) { return __awaiter(_this, void 0, void 0, function () {
1020
+ var _a, _b;
1021
+ return __generator(this, function (_c) {
1022
+ switch (_c.label) {
1023
+ case 0:
1024
+ _b = (_a = this.program.methods
1025
+ .getAssetsUnderManagement({})
1026
+ .accounts({
1027
+ perpetuals: this.perpetuals.publicKey,
1028
+ pool: this.getPoolKey(poolName),
1029
+ }))
1030
+ .remainingAccounts;
1031
+ return [4 /*yield*/, this.getCustodyMetas(poolName)];
1032
+ case 1: return [4 /*yield*/, _b.apply(_a, [_c.sent()])
1033
+ .rpc()
1034
+ .catch(function (err) {
1035
+ console.error(err);
1036
+ throw err;
1037
+ })];
1038
+ case 2: return [2 /*return*/, _c.sent()];
1039
+ }
1040
+ });
1041
+ }); };
1042
+ this.getAumSdk = function (poolAccount, token_prices, token_ema_prices, custodies, aum_calc_mode, currentTime) {
1043
+ // console.log("poolAccount:",poolAccount);
1044
+ return poolAccount.getAssetsUnderManagementUsd(token_prices, token_ema_prices, custodies, aum_calc_mode, currentTime);
1045
+ };
1046
+ // TODO: handle SOL wrapping to WSOL and create a ATA - DONE
1047
+ // TODO: Balance checks - DONE
1048
+ // TODO: ATA check - else create - DONE
1049
+ // TODO: for close Accounts - NOT NEEDED
1050
+ this.openPosition = function (payTokenSymbol, price, collateral, size, side, slippagePercentage, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
1051
+ var slippageMultiplier, priceAfterSlippage, publicKey, payTokenCustody, userCustodyTokenAccount, instructions, wsolAssociatedTokenAccount, wsolATAExist, wsolBalance, _a, _b, unWrappedSolBalance, _c, totalSolBal, conversionAmt, tokenAccountBalance, _d, positionAccount, params, instruction, error_2;
1052
+ return __generator(this, function (_e) {
1053
+ switch (_e.label) {
1054
+ case 0:
1055
+ console.log("open position :::", payTokenSymbol, poolConfig.getTokenFromSymbol(payTokenSymbol).mintKey.toBase58());
1056
+ slippageMultiplier = (0, types_1.isVariant)(side, 'long') ? -1 : 1;
1057
+ priceAfterSlippage = price.mul(new anchor_1.BN((100 - (slippagePercentage * slippageMultiplier)) * 100)).div(new anchor_1.BN(100 * 100));
1058
+ publicKey = this.provider.wallet.publicKey;
1059
+ payTokenCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(payTokenSymbol).mintKey); });
1060
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.getTokenFromSymbol(payTokenSymbol).mintKey, publicKey)];
1061
+ case 1:
1062
+ userCustodyTokenAccount = _e.sent();
1063
+ instructions = [];
1064
+ _e.label = 2;
1065
+ case 2:
1066
+ _e.trys.push([2, 15, , 16]);
1067
+ if (!(payTokenSymbol == 'SOL')) return [3 /*break*/, 10];
1068
+ console.log("payTokenSymbol === sol", payTokenSymbol);
1069
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(spl_token_1.NATIVE_MINT, publicKey)];
1070
+ case 3:
1071
+ wsolAssociatedTokenAccount = _e.sent();
1072
+ return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(wsolAssociatedTokenAccount, this.provider.connection)];
1073
+ case 4:
1074
+ wsolATAExist = _e.sent();
1075
+ if (!wsolATAExist) {
1076
+ console.log("wsol ata does not exist");
1077
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, wsolAssociatedTokenAccount, publicKey, spl_token_1.NATIVE_MINT));
1078
+ }
1079
+ _a = anchor_1.BN.bind;
1080
+ if (!wsolATAExist) return [3 /*break*/, 6];
1081
+ return [4 /*yield*/, this.provider.connection.getTokenAccountBalance(wsolAssociatedTokenAccount)];
1082
+ case 5:
1083
+ _b = (_e.sent()).value.amount;
1084
+ return [3 /*break*/, 7];
1085
+ case 6:
1086
+ _b = 0;
1087
+ _e.label = 7;
1088
+ case 7:
1089
+ wsolBalance = new (_a.apply(anchor_1.BN, [void 0, _b]))();
1090
+ if (!wsolBalance.lt(collateral)) return [3 /*break*/, 9];
1091
+ _c = anchor_1.BN.bind;
1092
+ return [4 /*yield*/, this.provider.connection.getBalance(publicKey)];
1093
+ case 8:
1094
+ unWrappedSolBalance = new (_c.apply(anchor_1.BN, [void 0, _e.sent()]))();
1095
+ totalSolBal = unWrappedSolBalance.add(wsolBalance);
1096
+ if (totalSolBal.lt(collateral)) {
1097
+ throw "Insufficient SOL Funds";
1098
+ }
1099
+ conversionAmt = collateral.sub(wsolBalance);
1100
+ instructions.push(web3_js_1.SystemProgram.transfer({
1101
+ fromPubkey: publicKey,
1102
+ toPubkey: wsolAssociatedTokenAccount,
1103
+ lamports: conversionAmt.toNumber(), // IS IT SAFE TO PUT AS NUMBER
1104
+ }), (0, spl_token_1.createSyncNativeInstruction)(wsolAssociatedTokenAccount));
1105
+ _e.label = 9;
1106
+ case 9: return [3 /*break*/, 13];
1107
+ case 10: return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(userCustodyTokenAccount, this.provider.connection)];
1108
+ case 11:
1109
+ if (!(_e.sent())) {
1110
+ throw "Insufficient Funds , token Account doesn't exist";
1111
+ }
1112
+ _d = anchor_1.BN.bind;
1113
+ return [4 /*yield*/, this.provider.connection.getTokenAccountBalance(userCustodyTokenAccount)];
1114
+ case 12:
1115
+ tokenAccountBalance = new (_d.apply(anchor_1.BN, [void 0, (_e.sent()).value.amount]))();
1116
+ if (tokenAccountBalance.lt(collateral)) {
1117
+ throw "Insufficient Funds";
1118
+ }
1119
+ _e.label = 13;
1120
+ case 13:
1121
+ positionAccount = web3_js_1.PublicKey.findProgramAddressSync([
1122
+ Buffer.from("position"),
1123
+ publicKey.toBuffer(),
1124
+ poolConfig.poolAddress.toBuffer(),
1125
+ payTokenCustody.custodyAccount.toBuffer(),
1126
+ (0, types_1.isVariant)(side, 'long') ? Buffer.from([1]) : Buffer.from([2]),
1127
+ ], this.programId)[0];
1128
+ params = {
1129
+ price: priceAfterSlippage,
1130
+ collateral: collateral,
1131
+ size: size,
1132
+ side: side,
1133
+ };
1134
+ return [4 /*yield*/, this.program.methods
1135
+ .openPosition(params)
1136
+ .accounts({
1137
+ owner: publicKey,
1138
+ fundingAccount: userCustodyTokenAccount,
1139
+ transferAuthority: poolConfig.transferAuthority,
1140
+ perpetuals: poolConfig.perpetuals,
1141
+ pool: poolConfig.poolAddress,
1142
+ position: positionAccount,
1143
+ custody: payTokenCustody.custodyAccount,
1144
+ custodyOracleAccount: payTokenCustody.oracleAddress,
1145
+ custodyTokenAccount: payTokenCustody.tokenAccount,
1146
+ systemProgram: web3_js_1.SystemProgram.programId,
1147
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1148
+ }).instruction()];
1149
+ case 14:
1150
+ instruction = _e.sent();
1151
+ instructions.push(instruction);
1152
+ return [3 /*break*/, 16];
1153
+ case 15:
1154
+ error_2 = _e.sent();
1155
+ console.log("perpClient openPosition error:", error_2);
1156
+ return [3 /*break*/, 16];
1157
+ case 16: return [2 /*return*/, instructions];
1158
+ }
1159
+ });
1160
+ }); };
1161
+ // TODO: handle SOL wrapping to WSOL and create a ATA - NOT NEEDED
1162
+ // TODO : Balance checks - NOT NEEDED
1163
+ // TODO: ATA check - else create - DONE
1164
+ // TODO: for close Accounts - DONE BY ANCHOR
1165
+ this.closePosition = function (receivingTokenSymbol, price, side, slippagePercentage, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
1166
+ var slippageMultiplier, priceAfterSlippage, publicKey, userReceivingTokenAccount, instructions, receivingTokenCustody, positionAccount, params, instruction, error_3;
1167
+ return __generator(this, function (_a) {
1168
+ switch (_a.label) {
1169
+ case 0:
1170
+ console.log("close position :::", receivingTokenSymbol, poolConfig.getTokenFromSymbol(receivingTokenSymbol).mintKey.toBase58());
1171
+ slippageMultiplier = (0, types_1.isVariant)(side, 'long') ? -1 : 1;
1172
+ priceAfterSlippage = price.mul(new anchor_1.BN((100 - (slippagePercentage * slippageMultiplier)) * 100)).div(new anchor_1.BN(100 * 100));
1173
+ publicKey = this.provider.wallet.publicKey;
1174
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.getTokenFromSymbol(receivingTokenSymbol).mintKey, publicKey)];
1175
+ case 1:
1176
+ userReceivingTokenAccount = _a.sent();
1177
+ instructions = [];
1178
+ _a.label = 2;
1179
+ case 2:
1180
+ _a.trys.push([2, 5, , 6]);
1181
+ return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(userReceivingTokenAccount, this.provider.connection)];
1182
+ case 3:
1183
+ if (!(_a.sent())) {
1184
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userReceivingTokenAccount, publicKey, poolConfig.getTokenFromSymbol(receivingTokenSymbol).mintKey));
1185
+ }
1186
+ receivingTokenCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(receivingTokenSymbol).mintKey); });
1187
+ positionAccount = web3_js_1.PublicKey.findProgramAddressSync([
1188
+ Buffer.from("position"),
1189
+ publicKey.toBuffer(),
1190
+ poolConfig.poolAddress.toBuffer(),
1191
+ receivingTokenCustody.custodyAccount.toBuffer(),
1192
+ (0, types_1.isVariant)(side, 'long') ? Buffer.from([1]) : Buffer.from([2]),
1193
+ ], this.programId)[0];
1194
+ console.log("positionAccount:", positionAccount.toBase58());
1195
+ params = {
1196
+ price: priceAfterSlippage,
1197
+ };
1198
+ return [4 /*yield*/, this.program.methods
1199
+ .closePosition(params)
1200
+ .accounts({
1201
+ owner: publicKey,
1202
+ receivingAccount: userReceivingTokenAccount,
1203
+ transferAuthority: poolConfig.transferAuthority,
1204
+ perpetuals: poolConfig.perpetuals,
1205
+ pool: poolConfig.poolAddress,
1206
+ position: positionAccount,
1207
+ custody: receivingTokenCustody.custodyAccount,
1208
+ custodyOracleAccount: receivingTokenCustody.oracleAddress,
1209
+ custodyTokenAccount: receivingTokenCustody.tokenAccount,
1210
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1211
+ }).instruction()];
1212
+ case 4:
1213
+ instruction = _a.sent();
1214
+ instructions.push(instruction);
1215
+ return [3 /*break*/, 6];
1216
+ case 5:
1217
+ error_3 = _a.sent();
1218
+ console.error("perpclient closePosition error:", error_3);
1219
+ return [3 /*break*/, 6];
1220
+ case 6: return [2 /*return*/, instructions];
1221
+ }
1222
+ });
1223
+ }); };
1224
+ // TODO: ATA check - else create - DONE
1225
+ // TODO: handle SOL wrapping to WSOL and create a ATA - DONE
1226
+ // TODO : Balance checks - NOT NEEDED
1227
+ // TODO: for close Accounts - DONE BY ANCHOR
1228
+ this.swap = function (receivingTokenSymbol, dispensingTokenSymbol, amountIn, minAmountOut, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
1229
+ var receivingTokenCustody, dispensingTokenCustody, publicKey, instructions, receivingTokenAccount, dispensingCustodyTokenAccount, wsolAssociatedTokenAccount, wsolATAExist, wsolBalance, _a, _b, unWrappedSolBalance, _c, totalSolBal, conversionAmt, tokenAccountBalance, _d, params, inx, err_2;
1230
+ return __generator(this, function (_e) {
1231
+ switch (_e.label) {
1232
+ case 0:
1233
+ receivingTokenCustody = poolConfig.custodies.find(function (i) { return i.mintKey.toBase58() === poolConfig.getTokenFromSymbol(receivingTokenSymbol).mintKey.toBase58(); });
1234
+ if (!receivingTokenCustody) {
1235
+ throw "receivingTokenCustody not found";
1236
+ }
1237
+ dispensingTokenCustody = poolConfig.custodies.find(function (i) { return i.mintKey.toBase58() === poolConfig.getTokenFromSymbol(dispensingTokenSymbol).mintKey.toBase58(); });
1238
+ if (!dispensingTokenCustody) {
1239
+ throw "dispensingTokenCustody not found";
1240
+ }
1241
+ publicKey = this.provider.wallet.publicKey;
1242
+ instructions = [];
1243
+ _e.label = 1;
1244
+ case 1:
1245
+ _e.trys.push([1, 17, , 18]);
1246
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(receivingTokenCustody.mintKey, publicKey)];
1247
+ case 2:
1248
+ receivingTokenAccount = _e.sent();
1249
+ return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
1250
+ case 3:
1251
+ if (!(_e.sent())) {
1252
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, receivingTokenCustody.mintKey));
1253
+ }
1254
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(dispensingTokenCustody.mintKey, publicKey)];
1255
+ case 4:
1256
+ dispensingCustodyTokenAccount = _e.sent();
1257
+ if (!(dispensingTokenSymbol == 'SOL')) return [3 /*break*/, 12];
1258
+ console.log("dispensingTokenSymbol === sol", dispensingTokenSymbol);
1259
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(spl_token_1.NATIVE_MINT, publicKey)];
1260
+ case 5:
1261
+ wsolAssociatedTokenAccount = _e.sent();
1262
+ return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(wsolAssociatedTokenAccount, this.provider.connection)];
1263
+ case 6:
1264
+ wsolATAExist = _e.sent();
1265
+ if (!wsolATAExist) {
1266
+ console.log("wsol ata does not exist");
1267
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, wsolAssociatedTokenAccount, publicKey, spl_token_1.NATIVE_MINT));
1268
+ }
1269
+ _a = anchor_1.BN.bind;
1270
+ if (!wsolATAExist) return [3 /*break*/, 8];
1271
+ return [4 /*yield*/, this.provider.connection.getTokenAccountBalance(wsolAssociatedTokenAccount)];
1272
+ case 7:
1273
+ _b = (_e.sent()).value.amount;
1274
+ return [3 /*break*/, 9];
1275
+ case 8:
1276
+ _b = 0;
1277
+ _e.label = 9;
1278
+ case 9:
1279
+ wsolBalance = new (_a.apply(anchor_1.BN, [void 0, _b]))();
1280
+ if (!wsolBalance.lt(amountIn)) return [3 /*break*/, 11];
1281
+ _c = anchor_1.BN.bind;
1282
+ return [4 /*yield*/, this.provider.connection.getBalance(publicKey)];
1283
+ case 10:
1284
+ unWrappedSolBalance = new (_c.apply(anchor_1.BN, [void 0, _e.sent()]))();
1285
+ totalSolBal = unWrappedSolBalance.add(wsolBalance);
1286
+ if (totalSolBal.lt(amountIn)) {
1287
+ throw "Insufficient SOL Funds";
1288
+ }
1289
+ conversionAmt = amountIn.sub(wsolBalance);
1290
+ instructions.push(web3_js_1.SystemProgram.transfer({
1291
+ fromPubkey: publicKey,
1292
+ toPubkey: wsolAssociatedTokenAccount,
1293
+ lamports: conversionAmt.toNumber(), // IS IT SAFE TO PUT AS NUMBER ?
1294
+ }), (0, spl_token_1.createSyncNativeInstruction)(wsolAssociatedTokenAccount));
1295
+ _e.label = 11;
1296
+ case 11: return [3 /*break*/, 15];
1297
+ case 12: return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(dispensingCustodyTokenAccount, this.provider.connection)];
1298
+ case 13:
1299
+ if (!(_e.sent())) {
1300
+ throw "Insufficient Funds , Token Account doesn't exist";
1301
+ }
1302
+ _d = anchor_1.BN.bind;
1303
+ return [4 /*yield*/, this.provider.connection.getTokenAccountBalance(dispensingCustodyTokenAccount)];
1304
+ case 14:
1305
+ tokenAccountBalance = new (_d.apply(anchor_1.BN, [void 0, (_e.sent()).value.amount]))();
1306
+ if (tokenAccountBalance.lt(amountIn)) {
1307
+ throw "Insufficient Funds";
1308
+ }
1309
+ _e.label = 15;
1310
+ case 15:
1311
+ params = {
1312
+ amountIn: amountIn,
1313
+ minAmountOut: minAmountOut,
1314
+ };
1315
+ return [4 /*yield*/, this.program.methods
1316
+ .swap(params)
1317
+ .accounts({
1318
+ owner: publicKey,
1319
+ fundingAccount: dispensingCustodyTokenAccount,
1320
+ receivingAccount: receivingTokenAccount,
1321
+ transferAuthority: poolConfig.transferAuthority,
1322
+ perpetuals: poolConfig.perpetuals,
1323
+ pool: poolConfig.poolAddress,
1324
+ receivingCustody: dispensingTokenCustody.custodyAccount,
1325
+ receivingCustodyOracleAccount: dispensingTokenCustody.oracleAddress,
1326
+ receivingCustodyTokenAccount: dispensingTokenCustody.tokenAccount,
1327
+ dispensingCustody: receivingTokenCustody.custodyAccount,
1328
+ dispensingCustodyOracleAccount: receivingTokenCustody.oracleAddress,
1329
+ dispensingCustodyTokenAccount: receivingTokenCustody.tokenAccount,
1330
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1331
+ })
1332
+ .instruction()];
1333
+ case 16:
1334
+ inx = _e.sent();
1335
+ instructions.push(inx);
1336
+ return [3 /*break*/, 18];
1337
+ case 17:
1338
+ err_2 = _e.sent();
1339
+ console.log("perpClient Swap error:: ", err_2);
1340
+ throw err_2;
1341
+ case 18: return [2 /*return*/, instructions];
1342
+ }
1343
+ });
1344
+ }); };
1345
+ // TODO: handle SOL wrapping to WSOL and create a ATA - DONE
1346
+ // TODO :Balance checks - DONE
1347
+ // TODO: ATA check - else create - DONE
1348
+ // TODO: for close Accounts - NOT NEEDED
1349
+ this.addLiquidity = function (payTokenSymbol, tokenAmountIn, minLpAmountOut, // give this value based on slippage
1350
+ poolConfig) { return __awaiter(_this, void 0, void 0, function () {
1351
+ var payTokenCustody, publicKey, instructions, userPayingTokenAccount, lpTokenAccount, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody, wsolAssociatedTokenAccount, wsolATAExist, wsolBalance, _b, _c, unWrappedSolBalance, _d, totalSolBal, conversionAmt, tokenAccountBalance, _e, inx, err_3;
1352
+ return __generator(this, function (_f) {
1353
+ switch (_f.label) {
1354
+ case 0:
1355
+ payTokenCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(payTokenSymbol).mintKey); });
1356
+ if (!payTokenCustody) {
1357
+ throw "payTokenCustody not found";
1358
+ }
1359
+ publicKey = this.provider.wallet.publicKey;
1360
+ instructions = [];
1361
+ _f.label = 1;
1362
+ case 1:
1363
+ _f.trys.push([1, 17, , 18]);
1364
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(payTokenCustody.mintKey, publicKey)];
1365
+ case 2:
1366
+ userPayingTokenAccount = _f.sent();
1367
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.lpTokenMint, publicKey)];
1368
+ case 3:
1369
+ lpTokenAccount = _f.sent();
1370
+ custodyAccountMetas = [];
1371
+ custodyOracleAccountMetas = [];
1372
+ for (_i = 0, _a = poolConfig.custodies; _i < _a.length; _i++) {
1373
+ custody = _a[_i];
1374
+ custodyAccountMetas.push({
1375
+ pubkey: custody.custodyAccount,
1376
+ isSigner: false,
1377
+ isWritable: false,
1378
+ });
1379
+ custodyOracleAccountMetas.push({
1380
+ pubkey: custody.oracleAddress,
1381
+ isSigner: false,
1382
+ isWritable: false,
1383
+ });
1384
+ }
1385
+ return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(lpTokenAccount, this.provider.connection)];
1386
+ case 4:
1387
+ if (!(_f.sent())) {
1388
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, lpTokenAccount, publicKey, poolConfig.lpTokenMint));
1389
+ }
1390
+ if (!(payTokenSymbol == 'SOL')) return [3 /*break*/, 12];
1391
+ console.log("payTokenSymbol === sol", payTokenSymbol);
1392
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(spl_token_1.NATIVE_MINT, publicKey)];
1393
+ case 5:
1394
+ wsolAssociatedTokenAccount = _f.sent();
1395
+ return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(wsolAssociatedTokenAccount, this.provider.connection)];
1396
+ case 6:
1397
+ wsolATAExist = _f.sent();
1398
+ if (!wsolATAExist) {
1399
+ console.log("wsol ata does not exist");
1400
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, wsolAssociatedTokenAccount, publicKey, spl_token_1.NATIVE_MINT));
1401
+ }
1402
+ _b = anchor_1.BN.bind;
1403
+ if (!wsolATAExist) return [3 /*break*/, 8];
1404
+ return [4 /*yield*/, this.provider.connection.getTokenAccountBalance(wsolAssociatedTokenAccount)];
1405
+ case 7:
1406
+ _c = (_f.sent()).value.amount;
1407
+ return [3 /*break*/, 9];
1408
+ case 8:
1409
+ _c = 0;
1410
+ _f.label = 9;
1411
+ case 9:
1412
+ wsolBalance = new (_b.apply(anchor_1.BN, [void 0, _c]))();
1413
+ if (!wsolBalance.lt(tokenAmountIn)) return [3 /*break*/, 11];
1414
+ _d = anchor_1.BN.bind;
1415
+ return [4 /*yield*/, this.provider.connection.getBalance(publicKey)];
1416
+ case 10:
1417
+ unWrappedSolBalance = new (_d.apply(anchor_1.BN, [void 0, _f.sent()]))();
1418
+ totalSolBal = unWrappedSolBalance.add(wsolBalance);
1419
+ if (totalSolBal.lt(tokenAmountIn)) {
1420
+ throw "Insufficient SOL Funds";
1421
+ }
1422
+ conversionAmt = tokenAmountIn.sub(wsolBalance);
1423
+ instructions.push(web3_js_1.SystemProgram.transfer({
1424
+ fromPubkey: publicKey,
1425
+ toPubkey: wsolAssociatedTokenAccount,
1426
+ lamports: conversionAmt.toNumber(), // IS IT SAFE TO PUT AS NUMBER
1427
+ }), (0, spl_token_1.createSyncNativeInstruction)(wsolAssociatedTokenAccount));
1428
+ _f.label = 11;
1429
+ case 11: return [3 /*break*/, 15];
1430
+ case 12: return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(userPayingTokenAccount, this.provider.connection)];
1431
+ case 13:
1432
+ if (!(_f.sent())) {
1433
+ throw "Insufficient Funds , token Account doesn't exist";
1434
+ }
1435
+ _e = anchor_1.BN.bind;
1436
+ return [4 /*yield*/, this.provider.connection.getTokenAccountBalance(userPayingTokenAccount)];
1437
+ case 14:
1438
+ tokenAccountBalance = new (_e.apply(anchor_1.BN, [void 0, (_f.sent()).value.amount]))();
1439
+ if (tokenAccountBalance.lt(tokenAmountIn)) {
1440
+ throw "Insufficient Funds";
1441
+ }
1442
+ _f.label = 15;
1443
+ case 15:
1444
+ console.log("in add liq", tokenAmountIn);
1445
+ return [4 /*yield*/, this.program.methods
1446
+ .addLiquidity({
1447
+ amountIn: tokenAmountIn,
1448
+ minLpAmountOut: minLpAmountOut
1449
+ })
1450
+ .accounts({
1451
+ owner: publicKey,
1452
+ fundingAccount: userPayingTokenAccount,
1453
+ lpTokenAccount: lpTokenAccount,
1454
+ transferAuthority: poolConfig.transferAuthority,
1455
+ perpetuals: poolConfig.perpetuals,
1456
+ pool: poolConfig.poolAddress,
1457
+ custody: payTokenCustody.custodyAccount,
1458
+ custodyOracleAccount: payTokenCustody.oracleAddress,
1459
+ custodyTokenAccount: payTokenCustody.tokenAccount,
1460
+ lpTokenMint: poolConfig.lpTokenMint,
1461
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1462
+ })
1463
+ .remainingAccounts(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true))
1464
+ .instruction()];
1465
+ case 16:
1466
+ inx = _f.sent();
1467
+ instructions.push(inx);
1468
+ return [3 /*break*/, 18];
1469
+ case 17:
1470
+ err_3 = _f.sent();
1471
+ console.log("perpClient addLiquidity error:: ", err_3);
1472
+ throw err_3;
1473
+ case 18: return [2 /*return*/, instructions];
1474
+ }
1475
+ });
1476
+ }); };
1477
+ // TODO: handle SOL wrapping to WSOL and create a ATA - NOT NEEDED
1478
+ // TODO :Balance checks - DONE
1479
+ // TODO: ATA check - else create - DONE
1480
+ // TODO: for LP close Accounts - DONE
1481
+ this.removeLiquidity = function (recieveTokenSymbol, liquidityAmountIn, minTokenAmountOut, // give this value based on slippage
1482
+ poolConfig, closeLpATA) {
1483
+ if (closeLpATA === void 0) { closeLpATA = false; }
1484
+ return __awaiter(_this, void 0, void 0, function () {
1485
+ var recieveTokenCustody, publicKey, instructions, userRecievingTokenAccount, lpTokenAccount, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody, removeLiquidityTx, closeInx, err_4;
1486
+ return __generator(this, function (_b) {
1487
+ switch (_b.label) {
1488
+ case 0:
1489
+ recieveTokenCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(recieveTokenSymbol).mintKey); });
1490
+ if (!recieveTokenCustody) {
1491
+ throw "recieveTokenCustody not found";
1492
+ }
1493
+ publicKey = this.provider.wallet.publicKey;
1494
+ instructions = [];
1495
+ _b.label = 1;
1496
+ case 1:
1497
+ _b.trys.push([1, 6, , 7]);
1498
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(recieveTokenCustody.mintKey, publicKey)];
1499
+ case 2:
1500
+ userRecievingTokenAccount = _b.sent();
1501
+ return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(userRecievingTokenAccount, this.provider.connection)];
1502
+ case 3:
1503
+ if (!(_b.sent())) {
1504
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userRecievingTokenAccount, publicKey, recieveTokenCustody.mintKey));
1505
+ }
1506
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.lpTokenMint, publicKey)];
1507
+ case 4:
1508
+ lpTokenAccount = _b.sent();
1509
+ custodyAccountMetas = [];
1510
+ custodyOracleAccountMetas = [];
1511
+ for (_i = 0, _a = poolConfig.custodies; _i < _a.length; _i++) {
1512
+ custody = _a[_i];
1513
+ custodyAccountMetas.push({
1514
+ pubkey: custody.custodyAccount,
1515
+ isSigner: false,
1516
+ isWritable: false,
1517
+ });
1518
+ custodyOracleAccountMetas.push({
1519
+ pubkey: custody.oracleAddress,
1520
+ isSigner: false,
1521
+ isWritable: false,
1522
+ });
1523
+ }
1524
+ console.log("liquidityAmountIn", liquidityAmountIn.toString());
1525
+ return [4 /*yield*/, this.program.methods
1526
+ .removeLiquidity({
1527
+ lpAmountIn: liquidityAmountIn,
1528
+ minAmountOut: minTokenAmountOut
1529
+ })
1530
+ .accounts({
1531
+ owner: publicKey,
1532
+ receivingAccount: userRecievingTokenAccount,
1533
+ lpTokenAccount: lpTokenAccount,
1534
+ transferAuthority: poolConfig.transferAuthority,
1535
+ perpetuals: poolConfig.perpetuals,
1536
+ pool: poolConfig.poolAddress,
1537
+ custody: recieveTokenCustody.custodyAccount,
1538
+ custodyOracleAccount: recieveTokenCustody.oracleAddress,
1539
+ custodyTokenAccount: recieveTokenCustody.tokenAccount,
1540
+ lpTokenMint: poolConfig.lpTokenMint,
1541
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1542
+ })
1543
+ .remainingAccounts(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true))
1544
+ .instruction()];
1545
+ case 5:
1546
+ removeLiquidityTx = _b.sent();
1547
+ instructions.push(removeLiquidityTx);
1548
+ if (closeLpATA) {
1549
+ closeInx = (0, spl_token_1.createCloseAccountInstruction)(lpTokenAccount, publicKey, publicKey);
1550
+ instructions.push(closeInx);
1551
+ }
1552
+ return [3 /*break*/, 7];
1553
+ case 6:
1554
+ err_4 = _b.sent();
1555
+ console.log("perpClient removeLiquidity error:: ", err_4);
1556
+ throw err_4;
1557
+ case 7: return [2 /*return*/, instructions];
1558
+ }
1559
+ });
1560
+ });
1561
+ };
1016
1562
  // this.provider = AnchorProvider.local(clusterUrl, {
1017
1563
  // commitment: "confirmed",
1018
1564
  // preflightCommitment: "confirmed",
@@ -1025,6 +1571,7 @@ var PerpetualsClient = /** @class */ (function () {
1025
1571
  // const idl = JSON.parse(IDL);
1026
1572
  // const program = new anchor.Program(idl, programId, provider);
1027
1573
  this.program = new anchor_1.Program(perpetuals_1.IDL, programId);
1574
+ this.programId = programId;
1028
1575
  //this.program = workspace.Perpetuals as Program<Perpetuals>;
1029
1576
  console.log("client constructor programID : ", this.program.programId.toBase58());
1030
1577
  // this.admin = Keypair.fromSecretKey(
@@ -1035,10 +1582,25 @@ var PerpetualsClient = /** @class */ (function () {
1035
1582
  this.multisig = this.findProgramAddress("multisig");
1036
1583
  this.authority = this.findProgramAddress("transfer_authority");
1037
1584
  this.perpetuals = this.findProgramAddress("perpetuals");
1585
+ this.prioritizationFee = (opts === null || opts === void 0 ? void 0 : opts.prioritizationFee) || 0;
1586
+ this.postSendTxCallback = opts === null || opts === void 0 ? void 0 : opts.postSendTxCallback;
1587
+ this.txConfirmationCommitment = (_a = opts === null || opts === void 0 ? void 0 : opts.txConfirmationCommitment) !== null && _a !== void 0 ? _a : 'processed';
1038
1588
  anchor_1.BN.prototype.toJSON = function () {
1039
1589
  return this.toString(10);
1040
1590
  };
1041
1591
  }
1592
+ PerpetualsClient.prototype.sendTransaction = function (ixs, opts) {
1593
+ var _a;
1594
+ if (opts === void 0) { opts = {}; }
1595
+ return __awaiter(this, void 0, void 0, function () {
1596
+ return __generator(this, function (_b) {
1597
+ switch (_b.label) {
1598
+ case 0: return [4 /*yield*/, (0, rpc_1.sendTransaction)(this.program.provider, ixs, (_a = opts.alts) !== null && _a !== void 0 ? _a : [], __assign({ postSendTxCallback: this.postSendTxCallback, prioritizationFee: this.prioritizationFee, txConfirmationCommitment: this.txConfirmationCommitment }, opts))];
1599
+ case 1: return [2 /*return*/, _b.sent()];
1600
+ }
1601
+ });
1602
+ });
1603
+ };
1042
1604
  return PerpetualsClient;
1043
1605
  }());
1044
1606
  exports.PerpetualsClient = PerpetualsClient;