flash-sdk 1.0.4 → 1.0.6

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 +24 -5
  5. package/lib/PerpetualsClient.js +604 -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 +763 -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,567 @@ 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
+ // TODO : if out token WSOL -> unwrap to SOL - DONE
1166
+ this.closePosition = function (receivingTokenSymbol, price, side, slippagePercentage, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
1167
+ var slippageMultiplier, priceAfterSlippage, publicKey, userReceivingTokenAccount, instructions, receivingTokenCustody, positionAccount, params, instruction, closeWsolATAIns, error_3;
1168
+ return __generator(this, function (_a) {
1169
+ switch (_a.label) {
1170
+ case 0:
1171
+ console.log("close position :::", receivingTokenSymbol, poolConfig.getTokenFromSymbol(receivingTokenSymbol).mintKey.toBase58());
1172
+ slippageMultiplier = (0, types_1.isVariant)(side, 'long') ? -1 : 1;
1173
+ priceAfterSlippage = price.mul(new anchor_1.BN((100 - (slippagePercentage * slippageMultiplier)) * 100)).div(new anchor_1.BN(100 * 100));
1174
+ publicKey = this.provider.wallet.publicKey;
1175
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.getTokenFromSymbol(receivingTokenSymbol).mintKey, publicKey)];
1176
+ case 1:
1177
+ userReceivingTokenAccount = _a.sent();
1178
+ instructions = [];
1179
+ _a.label = 2;
1180
+ case 2:
1181
+ _a.trys.push([2, 5, , 6]);
1182
+ return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(userReceivingTokenAccount, this.provider.connection)];
1183
+ case 3:
1184
+ if (!(_a.sent())) {
1185
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userReceivingTokenAccount, publicKey, poolConfig.getTokenFromSymbol(receivingTokenSymbol).mintKey));
1186
+ }
1187
+ receivingTokenCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(receivingTokenSymbol).mintKey); });
1188
+ positionAccount = web3_js_1.PublicKey.findProgramAddressSync([
1189
+ Buffer.from("position"),
1190
+ publicKey.toBuffer(),
1191
+ poolConfig.poolAddress.toBuffer(),
1192
+ receivingTokenCustody.custodyAccount.toBuffer(),
1193
+ (0, types_1.isVariant)(side, 'long') ? Buffer.from([1]) : Buffer.from([2]),
1194
+ ], this.programId)[0];
1195
+ console.log("positionAccount:", positionAccount.toBase58());
1196
+ params = {
1197
+ price: priceAfterSlippage,
1198
+ };
1199
+ return [4 /*yield*/, this.program.methods
1200
+ .closePosition(params)
1201
+ .accounts({
1202
+ owner: publicKey,
1203
+ receivingAccount: userReceivingTokenAccount,
1204
+ transferAuthority: poolConfig.transferAuthority,
1205
+ perpetuals: poolConfig.perpetuals,
1206
+ pool: poolConfig.poolAddress,
1207
+ position: positionAccount,
1208
+ custody: receivingTokenCustody.custodyAccount,
1209
+ custodyOracleAccount: receivingTokenCustody.oracleAddress,
1210
+ custodyTokenAccount: receivingTokenCustody.tokenAccount,
1211
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1212
+ }).instruction()];
1213
+ case 4:
1214
+ instruction = _a.sent();
1215
+ instructions.push(instruction);
1216
+ // SOL is only retrievable by closing the token account and choosing the desired address to send the token account's lamports.
1217
+ if (receivingTokenSymbol == 'SOL') {
1218
+ closeWsolATAIns = (0, spl_token_1.createCloseAccountInstruction)(userReceivingTokenAccount, publicKey, publicKey);
1219
+ instructions.push(closeWsolATAIns);
1220
+ }
1221
+ return [3 /*break*/, 6];
1222
+ case 5:
1223
+ error_3 = _a.sent();
1224
+ console.error("perpclient closePosition error:", error_3);
1225
+ return [3 /*break*/, 6];
1226
+ case 6: return [2 /*return*/, instructions];
1227
+ }
1228
+ });
1229
+ }); };
1230
+ // TODO: ATA check - else create - DONE
1231
+ // TODO: handle SOL wrapping to WSOL and create a ATA - DONE
1232
+ // TODO : Balance checks - NOT NEEDED
1233
+ // TODO: for close Accounts - DONE BY ANCHOR
1234
+ // TODO : if out token WSOL -> unwrap to SOL - DONE
1235
+ this.swap = function (receivingTokenSymbol, dispensingTokenSymbol, amountIn, minAmountOut, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
1236
+ var receivingTokenCustody, dispensingTokenCustody, publicKey, instructions, receivingTokenAccount, dispensingCustodyTokenAccount, wsolAssociatedTokenAccount, wsolATAExist, wsolBalance, _a, _b, unWrappedSolBalance, _c, totalSolBal, conversionAmt, tokenAccountBalance, _d, params, inx, closeWsolATAIns, err_2;
1237
+ return __generator(this, function (_e) {
1238
+ switch (_e.label) {
1239
+ case 0:
1240
+ receivingTokenCustody = poolConfig.custodies.find(function (i) { return i.mintKey.toBase58() === poolConfig.getTokenFromSymbol(receivingTokenSymbol).mintKey.toBase58(); });
1241
+ if (!receivingTokenCustody) {
1242
+ throw "receivingTokenCustody not found";
1243
+ }
1244
+ dispensingTokenCustody = poolConfig.custodies.find(function (i) { return i.mintKey.toBase58() === poolConfig.getTokenFromSymbol(dispensingTokenSymbol).mintKey.toBase58(); });
1245
+ if (!dispensingTokenCustody) {
1246
+ throw "dispensingTokenCustody not found";
1247
+ }
1248
+ publicKey = this.provider.wallet.publicKey;
1249
+ instructions = [];
1250
+ _e.label = 1;
1251
+ case 1:
1252
+ _e.trys.push([1, 17, , 18]);
1253
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(receivingTokenCustody.mintKey, publicKey)];
1254
+ case 2:
1255
+ receivingTokenAccount = _e.sent();
1256
+ return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
1257
+ case 3:
1258
+ if (!(_e.sent())) {
1259
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, receivingTokenCustody.mintKey));
1260
+ }
1261
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(dispensingTokenCustody.mintKey, publicKey)];
1262
+ case 4:
1263
+ dispensingCustodyTokenAccount = _e.sent();
1264
+ if (!(dispensingTokenSymbol == 'SOL')) return [3 /*break*/, 12];
1265
+ console.log("dispensingTokenSymbol === sol", dispensingTokenSymbol);
1266
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(spl_token_1.NATIVE_MINT, publicKey)];
1267
+ case 5:
1268
+ wsolAssociatedTokenAccount = _e.sent();
1269
+ return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(wsolAssociatedTokenAccount, this.provider.connection)];
1270
+ case 6:
1271
+ wsolATAExist = _e.sent();
1272
+ if (!wsolATAExist) {
1273
+ console.log("wsol ata does not exist");
1274
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, wsolAssociatedTokenAccount, publicKey, spl_token_1.NATIVE_MINT));
1275
+ }
1276
+ _a = anchor_1.BN.bind;
1277
+ if (!wsolATAExist) return [3 /*break*/, 8];
1278
+ return [4 /*yield*/, this.provider.connection.getTokenAccountBalance(wsolAssociatedTokenAccount)];
1279
+ case 7:
1280
+ _b = (_e.sent()).value.amount;
1281
+ return [3 /*break*/, 9];
1282
+ case 8:
1283
+ _b = 0;
1284
+ _e.label = 9;
1285
+ case 9:
1286
+ wsolBalance = new (_a.apply(anchor_1.BN, [void 0, _b]))();
1287
+ if (!wsolBalance.lt(amountIn)) return [3 /*break*/, 11];
1288
+ _c = anchor_1.BN.bind;
1289
+ return [4 /*yield*/, this.provider.connection.getBalance(publicKey)];
1290
+ case 10:
1291
+ unWrappedSolBalance = new (_c.apply(anchor_1.BN, [void 0, _e.sent()]))();
1292
+ totalSolBal = unWrappedSolBalance.add(wsolBalance);
1293
+ if (totalSolBal.lt(amountIn)) {
1294
+ throw "Insufficient SOL Funds";
1295
+ }
1296
+ conversionAmt = amountIn.sub(wsolBalance);
1297
+ instructions.push(web3_js_1.SystemProgram.transfer({
1298
+ fromPubkey: publicKey,
1299
+ toPubkey: wsolAssociatedTokenAccount,
1300
+ lamports: conversionAmt.toNumber(), // IS IT SAFE TO PUT AS NUMBER ?
1301
+ }), (0, spl_token_1.createSyncNativeInstruction)(wsolAssociatedTokenAccount));
1302
+ _e.label = 11;
1303
+ case 11: return [3 /*break*/, 15];
1304
+ case 12: return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(dispensingCustodyTokenAccount, this.provider.connection)];
1305
+ case 13:
1306
+ if (!(_e.sent())) {
1307
+ throw "Insufficient Funds , Token Account doesn't exist";
1308
+ }
1309
+ _d = anchor_1.BN.bind;
1310
+ return [4 /*yield*/, this.provider.connection.getTokenAccountBalance(dispensingCustodyTokenAccount)];
1311
+ case 14:
1312
+ tokenAccountBalance = new (_d.apply(anchor_1.BN, [void 0, (_e.sent()).value.amount]))();
1313
+ if (tokenAccountBalance.lt(amountIn)) {
1314
+ throw "Insufficient Funds";
1315
+ }
1316
+ _e.label = 15;
1317
+ case 15:
1318
+ params = {
1319
+ amountIn: amountIn,
1320
+ minAmountOut: minAmountOut,
1321
+ };
1322
+ return [4 /*yield*/, this.program.methods
1323
+ .swap(params)
1324
+ .accounts({
1325
+ owner: publicKey,
1326
+ fundingAccount: dispensingCustodyTokenAccount,
1327
+ receivingAccount: receivingTokenAccount,
1328
+ transferAuthority: poolConfig.transferAuthority,
1329
+ perpetuals: poolConfig.perpetuals,
1330
+ pool: poolConfig.poolAddress,
1331
+ receivingCustody: dispensingTokenCustody.custodyAccount,
1332
+ receivingCustodyOracleAccount: dispensingTokenCustody.oracleAddress,
1333
+ receivingCustodyTokenAccount: dispensingTokenCustody.tokenAccount,
1334
+ dispensingCustody: receivingTokenCustody.custodyAccount,
1335
+ dispensingCustodyOracleAccount: receivingTokenCustody.oracleAddress,
1336
+ dispensingCustodyTokenAccount: receivingTokenCustody.tokenAccount,
1337
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1338
+ })
1339
+ .instruction()];
1340
+ case 16:
1341
+ inx = _e.sent();
1342
+ instructions.push(inx);
1343
+ // SOL is only retrievable by closing the token account and choosing the desired address to send the token account's lamports.
1344
+ if (receivingTokenSymbol == 'SOL') {
1345
+ closeWsolATAIns = (0, spl_token_1.createCloseAccountInstruction)(receivingTokenAccount, publicKey, publicKey);
1346
+ instructions.push(closeWsolATAIns);
1347
+ }
1348
+ return [3 /*break*/, 18];
1349
+ case 17:
1350
+ err_2 = _e.sent();
1351
+ console.log("perpClient Swap error:: ", err_2);
1352
+ throw err_2;
1353
+ case 18: return [2 /*return*/, instructions];
1354
+ }
1355
+ });
1356
+ }); };
1357
+ // TODO: handle SOL wrapping to WSOL and create a ATA - DONE
1358
+ // TODO :Balance checks - DONE
1359
+ // TODO: ATA check - else create - DONE
1360
+ // TODO: for close Accounts - NOT NEEDED
1361
+ this.addLiquidity = function (payTokenSymbol, tokenAmountIn, minLpAmountOut, // give this value based on slippage
1362
+ poolConfig) { return __awaiter(_this, void 0, void 0, function () {
1363
+ 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;
1364
+ return __generator(this, function (_f) {
1365
+ switch (_f.label) {
1366
+ case 0:
1367
+ payTokenCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(payTokenSymbol).mintKey); });
1368
+ if (!payTokenCustody) {
1369
+ throw "payTokenCustody not found";
1370
+ }
1371
+ publicKey = this.provider.wallet.publicKey;
1372
+ instructions = [];
1373
+ _f.label = 1;
1374
+ case 1:
1375
+ _f.trys.push([1, 17, , 18]);
1376
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(payTokenCustody.mintKey, publicKey)];
1377
+ case 2:
1378
+ userPayingTokenAccount = _f.sent();
1379
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.lpTokenMint, publicKey)];
1380
+ case 3:
1381
+ lpTokenAccount = _f.sent();
1382
+ custodyAccountMetas = [];
1383
+ custodyOracleAccountMetas = [];
1384
+ for (_i = 0, _a = poolConfig.custodies; _i < _a.length; _i++) {
1385
+ custody = _a[_i];
1386
+ custodyAccountMetas.push({
1387
+ pubkey: custody.custodyAccount,
1388
+ isSigner: false,
1389
+ isWritable: false,
1390
+ });
1391
+ custodyOracleAccountMetas.push({
1392
+ pubkey: custody.oracleAddress,
1393
+ isSigner: false,
1394
+ isWritable: false,
1395
+ });
1396
+ }
1397
+ return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(lpTokenAccount, this.provider.connection)];
1398
+ case 4:
1399
+ if (!(_f.sent())) {
1400
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, lpTokenAccount, publicKey, poolConfig.lpTokenMint));
1401
+ }
1402
+ if (!(payTokenSymbol == 'SOL')) return [3 /*break*/, 12];
1403
+ console.log("payTokenSymbol === sol", payTokenSymbol);
1404
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(spl_token_1.NATIVE_MINT, publicKey)];
1405
+ case 5:
1406
+ wsolAssociatedTokenAccount = _f.sent();
1407
+ return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(wsolAssociatedTokenAccount, this.provider.connection)];
1408
+ case 6:
1409
+ wsolATAExist = _f.sent();
1410
+ if (!wsolATAExist) {
1411
+ console.log("wsol ata does not exist");
1412
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, wsolAssociatedTokenAccount, publicKey, spl_token_1.NATIVE_MINT));
1413
+ }
1414
+ _b = anchor_1.BN.bind;
1415
+ if (!wsolATAExist) return [3 /*break*/, 8];
1416
+ return [4 /*yield*/, this.provider.connection.getTokenAccountBalance(wsolAssociatedTokenAccount)];
1417
+ case 7:
1418
+ _c = (_f.sent()).value.amount;
1419
+ return [3 /*break*/, 9];
1420
+ case 8:
1421
+ _c = 0;
1422
+ _f.label = 9;
1423
+ case 9:
1424
+ wsolBalance = new (_b.apply(anchor_1.BN, [void 0, _c]))();
1425
+ if (!wsolBalance.lt(tokenAmountIn)) return [3 /*break*/, 11];
1426
+ _d = anchor_1.BN.bind;
1427
+ return [4 /*yield*/, this.provider.connection.getBalance(publicKey)];
1428
+ case 10:
1429
+ unWrappedSolBalance = new (_d.apply(anchor_1.BN, [void 0, _f.sent()]))();
1430
+ totalSolBal = unWrappedSolBalance.add(wsolBalance);
1431
+ if (totalSolBal.lt(tokenAmountIn)) {
1432
+ throw "Insufficient SOL Funds";
1433
+ }
1434
+ conversionAmt = tokenAmountIn.sub(wsolBalance);
1435
+ instructions.push(web3_js_1.SystemProgram.transfer({
1436
+ fromPubkey: publicKey,
1437
+ toPubkey: wsolAssociatedTokenAccount,
1438
+ lamports: conversionAmt.toNumber(), // IS IT SAFE TO PUT AS NUMBER
1439
+ }), (0, spl_token_1.createSyncNativeInstruction)(wsolAssociatedTokenAccount));
1440
+ _f.label = 11;
1441
+ case 11: return [3 /*break*/, 15];
1442
+ case 12: return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(userPayingTokenAccount, this.provider.connection)];
1443
+ case 13:
1444
+ if (!(_f.sent())) {
1445
+ throw "Insufficient Funds , token Account doesn't exist";
1446
+ }
1447
+ _e = anchor_1.BN.bind;
1448
+ return [4 /*yield*/, this.provider.connection.getTokenAccountBalance(userPayingTokenAccount)];
1449
+ case 14:
1450
+ tokenAccountBalance = new (_e.apply(anchor_1.BN, [void 0, (_f.sent()).value.amount]))();
1451
+ if (tokenAccountBalance.lt(tokenAmountIn)) {
1452
+ throw "Insufficient Funds";
1453
+ }
1454
+ _f.label = 15;
1455
+ case 15:
1456
+ console.log("in add liq", tokenAmountIn);
1457
+ return [4 /*yield*/, this.program.methods
1458
+ .addLiquidity({
1459
+ amountIn: tokenAmountIn,
1460
+ minLpAmountOut: minLpAmountOut
1461
+ })
1462
+ .accounts({
1463
+ owner: publicKey,
1464
+ fundingAccount: userPayingTokenAccount,
1465
+ lpTokenAccount: lpTokenAccount,
1466
+ transferAuthority: poolConfig.transferAuthority,
1467
+ perpetuals: poolConfig.perpetuals,
1468
+ pool: poolConfig.poolAddress,
1469
+ custody: payTokenCustody.custodyAccount,
1470
+ custodyOracleAccount: payTokenCustody.oracleAddress,
1471
+ custodyTokenAccount: payTokenCustody.tokenAccount,
1472
+ lpTokenMint: poolConfig.lpTokenMint,
1473
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1474
+ })
1475
+ .remainingAccounts(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true))
1476
+ .instruction()];
1477
+ case 16:
1478
+ inx = _f.sent();
1479
+ instructions.push(inx);
1480
+ return [3 /*break*/, 18];
1481
+ case 17:
1482
+ err_3 = _f.sent();
1483
+ console.log("perpClient addLiquidity error:: ", err_3);
1484
+ throw err_3;
1485
+ case 18: return [2 /*return*/, instructions];
1486
+ }
1487
+ });
1488
+ }); };
1489
+ // TODO: handle SOL wrapping to WSOL and create a ATA - NOT NEEDED
1490
+ // TODO :Balance checks - DONE
1491
+ // TODO: ATA check - else create - DONE
1492
+ // TODO: for LP close Accounts - DONE
1493
+ // TODO : if out token WSOL -> unwrap to SOL - DONE
1494
+ this.removeLiquidity = function (recieveTokenSymbol, liquidityAmountIn, minTokenAmountOut, // give this value based on slippage
1495
+ poolConfig, closeLpATA) {
1496
+ if (closeLpATA === void 0) { closeLpATA = false; }
1497
+ return __awaiter(_this, void 0, void 0, function () {
1498
+ var recieveTokenCustody, publicKey, instructions, userRecievingTokenAccount, lpTokenAccount, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody, removeLiquidityTx, closeInx, closeWsolATAIns, err_4;
1499
+ return __generator(this, function (_b) {
1500
+ switch (_b.label) {
1501
+ case 0:
1502
+ recieveTokenCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(recieveTokenSymbol).mintKey); });
1503
+ if (!recieveTokenCustody) {
1504
+ throw "recieveTokenCustody not found";
1505
+ }
1506
+ publicKey = this.provider.wallet.publicKey;
1507
+ instructions = [];
1508
+ _b.label = 1;
1509
+ case 1:
1510
+ _b.trys.push([1, 6, , 7]);
1511
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(recieveTokenCustody.mintKey, publicKey)];
1512
+ case 2:
1513
+ userRecievingTokenAccount = _b.sent();
1514
+ return [4 /*yield*/, (0, utils_1.checkIfAccountExists)(userRecievingTokenAccount, this.provider.connection)];
1515
+ case 3:
1516
+ if (!(_b.sent())) {
1517
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userRecievingTokenAccount, publicKey, recieveTokenCustody.mintKey));
1518
+ }
1519
+ return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.lpTokenMint, publicKey)];
1520
+ case 4:
1521
+ lpTokenAccount = _b.sent();
1522
+ custodyAccountMetas = [];
1523
+ custodyOracleAccountMetas = [];
1524
+ for (_i = 0, _a = poolConfig.custodies; _i < _a.length; _i++) {
1525
+ custody = _a[_i];
1526
+ custodyAccountMetas.push({
1527
+ pubkey: custody.custodyAccount,
1528
+ isSigner: false,
1529
+ isWritable: false,
1530
+ });
1531
+ custodyOracleAccountMetas.push({
1532
+ pubkey: custody.oracleAddress,
1533
+ isSigner: false,
1534
+ isWritable: false,
1535
+ });
1536
+ }
1537
+ console.log("liquidityAmountIn", liquidityAmountIn.toString());
1538
+ return [4 /*yield*/, this.program.methods
1539
+ .removeLiquidity({
1540
+ lpAmountIn: liquidityAmountIn,
1541
+ minAmountOut: minTokenAmountOut
1542
+ })
1543
+ .accounts({
1544
+ owner: publicKey,
1545
+ receivingAccount: userRecievingTokenAccount,
1546
+ lpTokenAccount: lpTokenAccount,
1547
+ transferAuthority: poolConfig.transferAuthority,
1548
+ perpetuals: poolConfig.perpetuals,
1549
+ pool: poolConfig.poolAddress,
1550
+ custody: recieveTokenCustody.custodyAccount,
1551
+ custodyOracleAccount: recieveTokenCustody.oracleAddress,
1552
+ custodyTokenAccount: recieveTokenCustody.tokenAccount,
1553
+ lpTokenMint: poolConfig.lpTokenMint,
1554
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1555
+ })
1556
+ .remainingAccounts(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true))
1557
+ .instruction()];
1558
+ case 5:
1559
+ removeLiquidityTx = _b.sent();
1560
+ instructions.push(removeLiquidityTx);
1561
+ if (closeLpATA) {
1562
+ closeInx = (0, spl_token_1.createCloseAccountInstruction)(lpTokenAccount, publicKey, publicKey);
1563
+ instructions.push(closeInx);
1564
+ }
1565
+ // SOL is only retrievable by closing the token account and choosing the desired address to send the token account's lamports.
1566
+ if (recieveTokenSymbol == 'SOL') {
1567
+ closeWsolATAIns = (0, spl_token_1.createCloseAccountInstruction)(userRecievingTokenAccount, publicKey, publicKey);
1568
+ instructions.push(closeWsolATAIns);
1569
+ }
1570
+ return [3 /*break*/, 7];
1571
+ case 6:
1572
+ err_4 = _b.sent();
1573
+ console.log("perpClient removeLiquidity error:: ", err_4);
1574
+ throw err_4;
1575
+ case 7: return [2 /*return*/, instructions];
1576
+ }
1577
+ });
1578
+ });
1579
+ };
1016
1580
  // this.provider = AnchorProvider.local(clusterUrl, {
1017
1581
  // commitment: "confirmed",
1018
1582
  // preflightCommitment: "confirmed",
@@ -1025,6 +1589,7 @@ var PerpetualsClient = /** @class */ (function () {
1025
1589
  // const idl = JSON.parse(IDL);
1026
1590
  // const program = new anchor.Program(idl, programId, provider);
1027
1591
  this.program = new anchor_1.Program(perpetuals_1.IDL, programId);
1592
+ this.programId = programId;
1028
1593
  //this.program = workspace.Perpetuals as Program<Perpetuals>;
1029
1594
  console.log("client constructor programID : ", this.program.programId.toBase58());
1030
1595
  // this.admin = Keypair.fromSecretKey(
@@ -1035,10 +1600,25 @@ var PerpetualsClient = /** @class */ (function () {
1035
1600
  this.multisig = this.findProgramAddress("multisig");
1036
1601
  this.authority = this.findProgramAddress("transfer_authority");
1037
1602
  this.perpetuals = this.findProgramAddress("perpetuals");
1603
+ this.prioritizationFee = (opts === null || opts === void 0 ? void 0 : opts.prioritizationFee) || 0;
1604
+ this.postSendTxCallback = opts === null || opts === void 0 ? void 0 : opts.postSendTxCallback;
1605
+ this.txConfirmationCommitment = (_a = opts === null || opts === void 0 ? void 0 : opts.txConfirmationCommitment) !== null && _a !== void 0 ? _a : 'processed';
1038
1606
  anchor_1.BN.prototype.toJSON = function () {
1039
1607
  return this.toString(10);
1040
1608
  };
1041
1609
  }
1610
+ PerpetualsClient.prototype.sendTransaction = function (ixs, opts) {
1611
+ var _a;
1612
+ if (opts === void 0) { opts = {}; }
1613
+ return __awaiter(this, void 0, void 0, function () {
1614
+ return __generator(this, function (_b) {
1615
+ switch (_b.label) {
1616
+ 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))];
1617
+ case 1: return [2 /*return*/, _b.sent()];
1618
+ }
1619
+ });
1620
+ });
1621
+ };
1042
1622
  return PerpetualsClient;
1043
1623
  }());
1044
1624
  exports.PerpetualsClient = PerpetualsClient;