flash-sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/lib/CustodyAccount.d.ts +29 -0
  2. package/lib/CustodyAccount.d.ts.map +1 -0
  3. package/lib/CustodyAccount.js +64 -0
  4. package/lib/CustodyAccount.js.map +1 -0
  5. package/lib/OraclePrice.d.ts +18 -0
  6. package/lib/OraclePrice.d.ts.map +1 -0
  7. package/lib/OraclePrice.js +83 -0
  8. package/lib/OraclePrice.js.map +1 -0
  9. package/lib/PerpetualsClient.d.ts +1937 -0
  10. package/lib/PerpetualsClient.d.ts.map +1 -0
  11. package/lib/PerpetualsClient.js +1013 -0
  12. package/lib/PerpetualsClient.js.map +1 -0
  13. package/lib/PoolAccount.d.ts +34 -0
  14. package/lib/PoolAccount.d.ts.map +1 -0
  15. package/lib/PoolAccount.js +306 -0
  16. package/lib/PoolAccount.js.map +1 -0
  17. package/lib/PositionAccount.d.ts +26 -0
  18. package/lib/PositionAccount.d.ts.map +1 -0
  19. package/lib/PositionAccount.js +90 -0
  20. package/lib/PositionAccount.js.map +1 -0
  21. package/lib/client/src/CustodyAccount.d.ts +30 -0
  22. package/lib/client/src/CustodyAccount.d.ts.map +1 -0
  23. package/lib/client/src/CustodyAccount.js +64 -0
  24. package/lib/client/src/CustodyAccount.js.map +1 -0
  25. package/lib/client/src/OraclePrice.d.ts +19 -0
  26. package/lib/client/src/OraclePrice.d.ts.map +1 -0
  27. package/lib/client/src/OraclePrice.js +84 -0
  28. package/lib/client/src/OraclePrice.js.map +1 -0
  29. package/lib/client/src/PerpetualsClient.d.ts +1940 -0
  30. package/lib/client/src/PerpetualsClient.d.ts.map +1 -0
  31. package/lib/client/src/PerpetualsClient.js +1013 -0
  32. package/lib/client/src/PerpetualsClient.js.map +1 -0
  33. package/lib/client/src/PoolAccount.d.ts +35 -0
  34. package/lib/client/src/PoolAccount.d.ts.map +1 -0
  35. package/lib/client/src/PoolAccount.js +307 -0
  36. package/lib/client/src/PoolAccount.js.map +1 -0
  37. package/lib/client/src/PositionAccount.d.ts +27 -0
  38. package/lib/client/src/PositionAccount.d.ts.map +1 -0
  39. package/lib/client/src/PositionAccount.js +91 -0
  40. package/lib/client/src/PositionAccount.js.map +1 -0
  41. package/lib/client/src/constants/index.d.ts +12 -0
  42. package/lib/client/src/constants/index.d.ts.map +1 -0
  43. package/lib/client/src/constants/index.js +15 -0
  44. package/lib/client/src/constants/index.js.map +1 -0
  45. package/lib/client/src/index.d.ts +8 -0
  46. package/lib/client/src/index.d.ts.map +1 -0
  47. package/lib/client/src/index.js +24 -0
  48. package/lib/client/src/index.js.map +1 -0
  49. package/lib/client/src/target/types/perpetuals.d.ts +3539 -0
  50. package/lib/client/src/target/types/perpetuals.d.ts.map +1 -0
  51. package/lib/client/src/target/types/perpetuals.js +3541 -0
  52. package/lib/client/src/target/types/perpetuals.js.map +1 -0
  53. package/lib/client/src/types/index.d.ts +188 -0
  54. package/lib/client/src/types/index.d.ts.map +1 -0
  55. package/lib/client/src/types/index.js +57 -0
  56. package/lib/client/src/types/index.js.map +1 -0
  57. package/lib/client/src/utils/helpers.d.ts +8 -0
  58. package/lib/client/src/utils/helpers.d.ts.map +1 -0
  59. package/lib/client/src/utils/helpers.js +152 -0
  60. package/lib/client/src/utils/helpers.js.map +1 -0
  61. package/lib/constants/index.d.ts +11 -0
  62. package/lib/constants/index.d.ts.map +1 -0
  63. package/lib/constants/index.js +14 -0
  64. package/lib/constants/index.js.map +1 -0
  65. package/lib/index.d.ts +8 -0
  66. package/lib/index.d.ts.map +1 -0
  67. package/lib/index.js +24 -0
  68. package/lib/index.js.map +1 -0
  69. package/lib/target/types/perpetuals.d.ts +3538 -0
  70. package/lib/target/types/perpetuals.d.ts.map +1 -0
  71. package/lib/target/types/perpetuals.js +3540 -0
  72. package/lib/target/types/perpetuals.js.map +1 -0
  73. package/lib/tsconfig.tsbuildinfo +1 -0
  74. package/lib/types/index.d.ts +187 -0
  75. package/lib/types/index.d.ts.map +1 -0
  76. package/lib/types/index.js +56 -0
  77. package/lib/types/index.js.map +1 -0
  78. package/lib/utils/helpers.d.ts +7 -0
  79. package/lib/utils/helpers.d.ts.map +1 -0
  80. package/lib/utils/helpers.js +151 -0
  81. package/lib/utils/helpers.js.map +1 -0
  82. package/lib/utils/index.d.ts +7 -0
  83. package/lib/utils/index.js +151 -0
  84. package/package.json +35 -0
  85. package/readme.md +4 -0
  86. package/src/CustodyAccount.ts +90 -0
  87. package/src/OraclePrice.ts +108 -0
  88. package/src/PerpetualsClient.ts +983 -0
  89. package/src/PoolAccount.ts +434 -0
  90. package/src/PositionAccount.ts +57 -0
  91. package/src/constants/index.ts +17 -0
  92. package/src/index.ts +14 -0
  93. package/src/readme.md +4 -0
  94. package/src/target/types/perpetuals.js +3540 -0
  95. package/src/target/types/perpetuals.ts +7075 -0
  96. package/src/types/index.ts +260 -0
  97. package/src/utils/index.ts +169 -0
  98. package/tsconfig.json +23 -0
@@ -0,0 +1,983 @@
1
+ import {
2
+ setProvider,
3
+ Program,
4
+ AnchorProvider,
5
+ workspace,
6
+ utils,
7
+ BN,
8
+ } from "@coral-xyz/anchor";
9
+ import {
10
+ PublicKey,
11
+ TransactionInstruction,
12
+ Transaction,
13
+ SystemProgram,
14
+ AccountMeta,
15
+ Keypair,
16
+ SYSVAR_RENT_PUBKEY,
17
+ } from "@solana/web3.js";
18
+ import {
19
+ getAccount,
20
+ getAssociatedTokenAddress,
21
+ createAssociatedTokenAccountInstruction,
22
+ createCloseAccountInstruction,
23
+ createSyncNativeInstruction,
24
+ TOKEN_PROGRAM_ID,
25
+ } from "@solana/spl-token";
26
+
27
+ import fetch from "node-fetch";
28
+ import { sha256 } from "js-sha256";
29
+ import { encode } from "bs58";
30
+ import { readFileSync } from "fs";
31
+
32
+ import { PoolAccount } from "./PoolAccount";
33
+ import { PositionAccount } from "./PositionAccount";
34
+ import { BorrowRateParams, Custody, Fees, OracleParams, Permissions, Position, PositionSide, PricingParams, TokenRatios, isVariant } from "./types";
35
+ import { OraclePrice } from "./OraclePrice";
36
+ import { CustodyAccount } from "./CustodyAccount";
37
+ import { Perpetuals } from "./target/types/perpetuals"
38
+ // import { Perpetuals } from "../../target/types/perpetuals"
39
+
40
+
41
+ export class PerpetualsClient {
42
+ provider: AnchorProvider;
43
+ program: Program<Perpetuals>;
44
+ admin: Keypair;
45
+
46
+ // pdas
47
+ multisig: { publicKey: PublicKey; bump: number };
48
+ authority: { publicKey: PublicKey; bump: number };
49
+ perpetuals: { publicKey: PublicKey; bump: number };
50
+
51
+ constructor(clusterUrl: string, adminKey: string) {
52
+ this.provider = AnchorProvider.local(clusterUrl, {
53
+ commitment: "confirmed",
54
+ preflightCommitment: "confirmed",
55
+ skipPreflight: true
56
+ });
57
+ setProvider(this.provider);
58
+ this.program = workspace.Perpetuals as Program<Perpetuals>;
59
+
60
+ this.admin = Keypair.fromSecretKey(
61
+ new Uint8Array(JSON.parse(readFileSync(adminKey).toString()))
62
+ );
63
+
64
+ this.multisig = this.findProgramAddress("multisig");
65
+ this.authority = this.findProgramAddress("transfer_authority");
66
+ this.perpetuals = this.findProgramAddress("perpetuals");
67
+
68
+ BN.prototype.toJSON = function () {
69
+ return this.toString(10);
70
+ };
71
+ }
72
+
73
+ findProgramAddress = (label: string, extraSeeds :any = null) => {
74
+ let seeds = [Buffer.from(utils.bytes.utf8.encode(label))];
75
+ if (extraSeeds) {
76
+ for (let extraSeed of extraSeeds) {
77
+ if (typeof extraSeed === "string") {
78
+ seeds.push(Buffer.from(utils.bytes.utf8.encode(extraSeed)));
79
+ } else if (Array.isArray(extraSeed)) {
80
+ seeds.push(Buffer.from(extraSeed));
81
+ } else {
82
+ seeds.push(extraSeed.toBuffer());
83
+ }
84
+ }
85
+ }
86
+ let res = PublicKey.findProgramAddressSync(seeds, this.program.programId);
87
+ return { publicKey: res[0], bump: res[1] };
88
+ };
89
+
90
+ adjustTokenRatios = (ratios : TokenRatios[]) => {
91
+ if (ratios.length == 0) {
92
+ return ratios;
93
+ }
94
+ let target = Math.floor(10000 / ratios.length);
95
+
96
+ for (let ratio of ratios) {
97
+ ratio.target = new BN(target);
98
+ }
99
+
100
+ if (10000 % ratios.length !== 0) {
101
+ ratios[ratios.length - 1].target = new BN(
102
+ target + (10000 % ratios.length)
103
+ );
104
+ }
105
+
106
+ return ratios;
107
+ };
108
+
109
+ getPerpetuals = async () => {
110
+ return this.program.account.perpetuals.fetch(this.perpetuals.publicKey);
111
+ };
112
+
113
+ getPoolKey = (name: string) => {
114
+ return this.findProgramAddress("pool", name).publicKey;
115
+ };
116
+
117
+ getPool = async (name: string) => {
118
+ console.log("pool:",this.getPoolKey(name).toBase58())
119
+ return this.program.account.pool.fetch(this.getPoolKey(name));
120
+ };
121
+
122
+ getPools = async () => {
123
+ //return this.program.account.pool.all();
124
+ let perpetuals = await this.getPerpetuals();
125
+ return this.program.account.pool.fetchMultiple(perpetuals.pools);
126
+ };
127
+
128
+ getPoolLpTokenKey = (name: string) => {
129
+ return this.findProgramAddress("lp_token_mint", [this.getPoolKey(name)])
130
+ .publicKey;
131
+ };
132
+
133
+ getCustodyKey = (poolName: string, tokenMint: PublicKey) => {
134
+ return this.findProgramAddress("custody", [
135
+ this.getPoolKey(poolName),
136
+ tokenMint,
137
+ ]).publicKey;
138
+ };
139
+
140
+ getCustodyTokenAccountKey = (poolName: string, tokenMint: PublicKey) => {
141
+ return this.findProgramAddress("custody_token_account", [
142
+ this.getPoolKey(poolName),
143
+ tokenMint,
144
+ ]).publicKey;
145
+ };
146
+
147
+ getCustodyOracleAccountKey = async (
148
+ poolName: string,
149
+ tokenMint: PublicKey
150
+ ) => {
151
+ return (await this.getCustody(poolName, tokenMint)).oracle.oracleAccount;
152
+ };
153
+
154
+ getCustodyTestOracleAccountKey = (poolName: string, tokenMint: PublicKey) => {
155
+ return this.findProgramAddress("oracle_account", [
156
+ this.getPoolKey(poolName),
157
+ tokenMint,
158
+ ]).publicKey;
159
+ };
160
+
161
+ getCustody = async (poolName: string, tokenMint: PublicKey) => {
162
+ console.log("custody key :",this.getCustodyKey(poolName, tokenMint).toBase58());
163
+ return this.program.account.custody.fetch(
164
+ this.getCustodyKey(poolName, tokenMint)
165
+ );
166
+ };
167
+
168
+ getCustodies = async (poolName: string) => {
169
+ //return this.program.account.custody.all();
170
+ let pool = await this.getPool(poolName);
171
+ return this.program.account.custody.fetchMultiple(
172
+ pool.custodies
173
+ );
174
+ };
175
+
176
+ getCustodyMetas = async (poolName: string) => {
177
+ let pool = await this.getPool(poolName);
178
+ let custodies :any = await this.program.account.custody.fetchMultiple(
179
+ pool.custodies
180
+ );
181
+ let custodyMetas = [];
182
+ for (const custody of pool.custodies) {
183
+ custodyMetas.push({
184
+ isSigner: false,
185
+ isWritable: false,
186
+ pubkey: custody,
187
+ });
188
+ }
189
+ for (const custody of custodies) {
190
+ custodyMetas.push({
191
+ isSigner: false,
192
+ isWritable: false,
193
+ pubkey: custody?.oracle.oracleAccount,
194
+ });
195
+ }
196
+ return custodyMetas;
197
+ };
198
+
199
+ getMultisig = async () => {
200
+ return this.program.account.multisig.fetch(this.multisig.publicKey);
201
+ };
202
+
203
+ getPositionKey = (
204
+ wallet: PublicKey,
205
+ poolName: string,
206
+ tokenMint: PublicKey,
207
+ side: PositionSide
208
+ ) => {
209
+ let pool = this.getPoolKey(poolName);
210
+ let custody = this.getCustodyKey(poolName, tokenMint);
211
+ return this.findProgramAddress("position", [
212
+ wallet,
213
+ pool,
214
+ custody,
215
+ side === "long" ? [1] : [0],
216
+ ]).publicKey;
217
+ };
218
+
219
+ getPosition = async (postionKey : PublicKey) => {
220
+ return this.program.account.position.fetch(postionKey);
221
+ };
222
+
223
+ getUserPosition = async (
224
+ wallet: PublicKey,
225
+ poolName: string,
226
+ tokenMint: PublicKey,
227
+ side: PositionSide
228
+ ) => {
229
+ return this.program.account.position.fetch(
230
+ this.getPositionKey(wallet, poolName, tokenMint, side)
231
+ );
232
+ };
233
+
234
+ getUserPositions = async (wallet: PublicKey) => {
235
+ let data = encode(
236
+ Buffer.concat([
237
+ this.getAccountDiscriminator("Position"),
238
+ wallet.toBuffer(),
239
+ ])
240
+ );
241
+ let positions = await this.provider.connection.getProgramAccounts(
242
+ this.program.programId,
243
+ {
244
+ filters: [{ dataSize: 200 }, { memcmp: { bytes: data, offset: 0 } }],
245
+ }
246
+ );
247
+ return Promise.all(
248
+ positions.map((position) => {
249
+ return this.program.account.position.fetch(position.pubkey);
250
+ })
251
+ );
252
+ };
253
+
254
+ getPoolTokenPositions = async (poolName: string, tokenMint: PublicKey) => {
255
+ let poolKey = this.getPoolKey(poolName);
256
+ let custodyKey = this.getCustodyKey(poolName, tokenMint);
257
+ let data = encode(
258
+ Buffer.concat([poolKey.toBuffer(), custodyKey.toBuffer()])
259
+ );
260
+ let positions = await this.provider.connection.getProgramAccounts(
261
+ this.program.programId,
262
+ {
263
+ filters: [{ dataSize: 200 }, { memcmp: { bytes: data, offset: 40 } }],
264
+ }
265
+ );
266
+ return Promise.all(
267
+ positions.map((position) => {
268
+ return this.program.account.position.fetch(position.pubkey);
269
+ })
270
+ );
271
+ };
272
+
273
+ getAllPositions = async () => {
274
+ return this.program.account.position.all();
275
+ };
276
+
277
+ getAccountDiscriminator = (name: string) => {
278
+ return Buffer.from(sha256.digest(`account:${name}`)).slice(0, 8);
279
+ };
280
+
281
+
282
+ log = (...message: string[]) => {
283
+ let date = new Date();
284
+ let date_str = date.toDateString();
285
+ let time = date.toLocaleTimeString();
286
+ console.log(`[${date_str} ${time}] ${message}`);
287
+ };
288
+
289
+ prettyPrint = (object: object) => {
290
+ console.log(JSON.stringify(object, null, 2));
291
+ };
292
+
293
+ ///////
294
+ // instructions
295
+
296
+ init = async (admins: PublicKey[], config: any) => {
297
+ let perpetualsProgramData = PublicKey.findProgramAddressSync(
298
+ [this.program.programId.toBuffer()],
299
+ new PublicKey("BPFLoaderUpgradeab1e11111111111111111111111")
300
+ )[0];
301
+
302
+ let adminMetas = [];
303
+ for (const admin of admins) {
304
+ adminMetas.push({
305
+ isSigner: false,
306
+ isWritable: false,
307
+ pubkey: admin,
308
+ });
309
+ }
310
+
311
+ await this.program.methods
312
+ .init(config)
313
+ .accounts({
314
+ upgradeAuthority: this.provider.wallet.publicKey,
315
+ multisig: this.multisig.publicKey,
316
+ transferAuthority: this.authority.publicKey,
317
+ perpetuals: this.perpetuals.publicKey,
318
+ perpetualsProgram: this.program.programId,
319
+ perpetualsProgramData,
320
+ systemProgram: SystemProgram.programId,
321
+ tokenProgram: TOKEN_PROGRAM_ID,
322
+ })
323
+ .remainingAccounts(adminMetas)
324
+ .rpc()
325
+ .catch((err) => {
326
+ console.error(err);
327
+ throw err;
328
+ });
329
+ };
330
+
331
+ setAdminSigners = async (admins: PublicKey[], minSignatures: number) => {
332
+ let adminMetas = [];
333
+ for (const admin of admins) {
334
+ adminMetas.push({
335
+ isSigner: false,
336
+ isWritable: false,
337
+ pubkey: admin,
338
+ });
339
+ }
340
+ try {
341
+ await this.program.methods
342
+ .setAdminSigners({
343
+ minSignatures,
344
+ })
345
+ .accounts({
346
+ admin: this.admin.publicKey,
347
+ multisig: this.multisig.publicKey,
348
+ })
349
+ .remainingAccounts(adminMetas)
350
+ .signers([this.admin])
351
+ .rpc();
352
+ } catch (err) {
353
+ // @ts-ignore
354
+ if (this.printErrors) {
355
+ console.log(err);
356
+ }
357
+ throw err;
358
+ }
359
+ };
360
+
361
+ addPool = async (name: string) => {
362
+ await this.program.methods
363
+ .addPool({ name })
364
+ .accounts({
365
+ admin: this.admin.publicKey,
366
+ multisig: this.multisig.publicKey,
367
+ transferAuthority: this.authority.publicKey,
368
+ perpetuals: this.perpetuals.publicKey,
369
+ pool: this.getPoolKey(name),
370
+ lpTokenMint: this.getPoolLpTokenKey(name),
371
+ systemProgram: SystemProgram.programId,
372
+ tokenProgram: TOKEN_PROGRAM_ID,
373
+ rent: SYSVAR_RENT_PUBKEY,
374
+ })
375
+ .signers([this.admin])
376
+ .rpc()
377
+ .catch((err) => {
378
+ console.error(err);
379
+ throw err;
380
+ });
381
+ };
382
+
383
+ removePool = async (name: string) => {
384
+ await this.program.methods
385
+ .removePool({})
386
+ .accounts({
387
+ admin: this.admin.publicKey,
388
+ multisig: this.multisig.publicKey,
389
+ transferAuthority: this.authority.publicKey,
390
+ perpetuals: this.perpetuals.publicKey,
391
+ pool: this.getPoolKey(name),
392
+ systemProgram: SystemProgram.programId,
393
+ })
394
+ .signers([this.admin])
395
+ .rpc()
396
+ .catch((err) => {
397
+ console.error(err);
398
+ throw err;
399
+ });
400
+ };
401
+
402
+ addCustody = async (
403
+ poolName: string,
404
+ tokenMint: PublicKey,
405
+ isStable: boolean,
406
+ oracle : OracleParams,
407
+ pricing: PricingParams,
408
+ permissions : Permissions,
409
+ fees : Fees,
410
+ borrowRate : BorrowRateParams,
411
+ ratios : TokenRatios[]
412
+ ) => {
413
+ console.log("CustodyKey", this.getCustodyKey(poolName, tokenMint).toBase58())
414
+ console.log("getCustodyTokenAccountKey", this.getCustodyTokenAccountKey(poolName, tokenMint).toBase58())
415
+ try {
416
+ const trx_id = await this.program.methods
417
+ // @ts-ignore
418
+ .addCustody({
419
+ isStable,
420
+ oracle,
421
+ pricing,
422
+ permissions,
423
+ fees,
424
+ borrowRate,
425
+ ratios,
426
+ })
427
+ .accounts({
428
+ admin: this.admin.publicKey,
429
+ multisig: this.multisig.publicKey,
430
+ transferAuthority: this.authority.publicKey,
431
+ perpetuals: this.perpetuals.publicKey,
432
+ pool: this.getPoolKey(poolName),
433
+ custody: this.getCustodyKey(poolName, tokenMint),
434
+ custodyTokenAccount: this.getCustodyTokenAccountKey(
435
+ poolName,
436
+ tokenMint
437
+ ),
438
+ custodyTokenMint: tokenMint,
439
+ systemProgram: SystemProgram.programId,
440
+ tokenProgram: TOKEN_PROGRAM_ID,
441
+ rent: SYSVAR_RENT_PUBKEY,
442
+ })
443
+ .signers([this.admin])
444
+ .rpc()
445
+ .catch((err) => {
446
+ console.error(err);
447
+ throw err;
448
+ });
449
+
450
+ console.log("trx_id:", `https://explorer.solana.com/tx/${trx_id}?cluster=devnet`)
451
+ } catch (error) {
452
+ console.log("cli error :",error);
453
+ }
454
+
455
+
456
+ };
457
+
458
+ editCustody = async (
459
+ poolName: string,
460
+ tokenMint: PublicKey,
461
+ isStable: boolean,
462
+ oracle : OracleParams,
463
+ pricing: PricingParams,
464
+ permissions : Permissions,
465
+ fees : Fees,
466
+ borrowRate : BorrowRateParams,
467
+ ratios : TokenRatios[]
468
+ ) => {
469
+ console.log("CustodyKey", this.getCustodyKey(poolName, tokenMint).toBase58())
470
+ console.log("getCustodyTokenAccountKey", this.getCustodyTokenAccountKey(poolName, tokenMint).toBase58())
471
+
472
+ const trx_id = await this.program.methods
473
+ //@ts-ignore
474
+ .testingEditCustody({
475
+ isStable,
476
+ oracle,
477
+ pricing,
478
+ permissions,
479
+ fees,
480
+ borrowRate,
481
+ ratios,
482
+ })
483
+ .accounts({
484
+ admin: this.admin.publicKey,
485
+ multisig: this.multisig.publicKey,
486
+ transferAuthority: this.authority.publicKey,
487
+ perpetuals: this.perpetuals.publicKey,
488
+ pool: this.getPoolKey(poolName),
489
+ custody: this.getCustodyKey(poolName, tokenMint),
490
+ custodyTokenAccount: this.getCustodyTokenAccountKey(
491
+ poolName,
492
+ tokenMint
493
+ ),
494
+ custodyTokenMint: tokenMint,
495
+ systemProgram: SystemProgram.programId,
496
+ tokenProgram: TOKEN_PROGRAM_ID,
497
+ rent: SYSVAR_RENT_PUBKEY,
498
+ })
499
+ .signers([this.admin])
500
+ .rpc()
501
+ .catch((err) => {
502
+ console.error(err);
503
+ throw err;
504
+ });
505
+ console.log("trx_id:", `https://explorer.solana.com/tx/${trx_id}?cluster=devnet`)
506
+ };
507
+
508
+ removeCustody = async (poolName: string, tokenMint: PublicKey, ratios:TokenRatios[]) => {
509
+ await this.program.methods
510
+ .removeCustody({ ratios })
511
+ .accounts({
512
+ admin: this.admin.publicKey,
513
+ multisig: this.multisig.publicKey,
514
+ transferAuthority: this.authority.publicKey,
515
+ perpetuals: this.perpetuals.publicKey,
516
+ pool: this.getPoolKey(poolName),
517
+ custody: this.getCustodyKey(poolName, tokenMint),
518
+ custodyTokenAccount: this.getCustodyTokenAccountKey(
519
+ poolName,
520
+ tokenMint
521
+ ),
522
+ systemProgram: SystemProgram.programId,
523
+ tokenProgram: TOKEN_PROGRAM_ID,
524
+ })
525
+ .signers([this.admin])
526
+ .rpc()
527
+ .catch((err) => {
528
+ console.error(err);
529
+ throw err;
530
+ });
531
+ };
532
+
533
+ upgradeCustody = async (poolName: string, tokenMint: PublicKey) => {
534
+ await this.program.methods
535
+ .upgradeCustody({})
536
+ .accounts({
537
+ admin: this.admin.publicKey,
538
+ multisig: this.multisig.publicKey,
539
+ pool: this.getPoolKey(poolName),
540
+ custody: this.getCustodyKey(poolName, tokenMint),
541
+ systemProgram: SystemProgram.programId,
542
+ })
543
+ .signers([this.admin])
544
+ .rpc()
545
+ .catch((err) => {
546
+ console.error(err);
547
+ throw err;
548
+ });
549
+ };
550
+
551
+ liquidate = async (
552
+ wallet: PublicKey,
553
+ poolName: string,
554
+ tokenMint: PublicKey,
555
+ side: PositionSide,
556
+ receivingAccount: PublicKey,
557
+ rewardsReceivingAccount: PublicKey
558
+ ) => {
559
+ return await this.program.methods
560
+ .liquidate({})
561
+ .accounts({
562
+ signer: this.provider.wallet.publicKey,
563
+ receivingAccount,
564
+ rewardsReceivingAccount,
565
+ transferAuthority: this.authority.publicKey,
566
+ perpetuals: this.perpetuals.publicKey,
567
+ pool: this.getPoolKey(poolName),
568
+ position: this.getPositionKey(wallet, poolName, tokenMint, side),
569
+ custody: this.getCustodyKey(poolName, tokenMint),
570
+ custodyOracleAccount: await this.getCustodyOracleAccountKey(
571
+ poolName,
572
+ tokenMint
573
+ ),
574
+ custodyTokenAccount: this.getCustodyTokenAccountKey(
575
+ poolName,
576
+ tokenMint
577
+ ),
578
+ tokenProgram: TOKEN_PROGRAM_ID,
579
+ })
580
+ .rpc()
581
+ .catch((err) => {
582
+ console.error(err);
583
+ throw err;
584
+ });
585
+ };
586
+
587
+ getOraclePrice = async (
588
+ poolName: string,
589
+ tokenMint: PublicKey,
590
+ ema: boolean
591
+ ) => {
592
+ return await this.program.methods
593
+ .getOraclePrice({
594
+ ema,
595
+ })
596
+ .accounts({
597
+ // signer: this.provider.wallet.publicKey,
598
+ perpetuals: this.perpetuals.publicKey,
599
+ pool: this.getPoolKey(poolName),
600
+ custody: this.getCustodyKey(poolName, tokenMint),
601
+ custodyOracleAccount: await this.getCustodyOracleAccountKey(
602
+ poolName,
603
+ tokenMint
604
+ ),
605
+ })
606
+ .view()
607
+ .catch((err) => {
608
+ console.error(err);
609
+ throw err;
610
+ });
611
+ };
612
+
613
+ getAddLiquidityAmountAndFee = async (
614
+ poolName: string,
615
+ tokenMint: PublicKey,
616
+ amount: BN
617
+ ) => {
618
+ return await this.program.methods
619
+ .getAddLiquidityAmountAndFee({
620
+ amountIn: amount,
621
+ })
622
+ .accounts({
623
+ perpetuals: this.perpetuals.publicKey,
624
+ pool: this.getPoolKey(poolName),
625
+ custody: this.getCustodyKey(poolName, tokenMint),
626
+ custodyOracleAccount: await this.getCustodyOracleAccountKey(
627
+ poolName,
628
+ tokenMint
629
+ ),
630
+ lpTokenMint: this.getPoolLpTokenKey(poolName),
631
+ })
632
+ .remainingAccounts(await this.getCustodyMetas(poolName))
633
+ .view()
634
+ .catch((err) => {
635
+ console.error(err);
636
+ throw err;
637
+ });
638
+ };
639
+
640
+
641
+
642
+ getRemoveLiquidityAmountAndFee = async (
643
+ poolName: string,
644
+ tokenMint: PublicKey,
645
+ lpAmount: BN
646
+ ) => {
647
+ return await this.program.methods
648
+ .getRemoveLiquidityAmountAndFee({
649
+ lpAmountIn: lpAmount,
650
+ })
651
+ .accounts({
652
+ perpetuals: this.perpetuals.publicKey,
653
+ pool: this.getPoolKey(poolName),
654
+ custody: this.getCustodyKey(poolName, tokenMint),
655
+ custodyOracleAccount: await this.getCustodyOracleAccountKey(
656
+ poolName,
657
+ tokenMint
658
+ ),
659
+ lpTokenMint: this.getPoolLpTokenKey(poolName),
660
+ })
661
+ .remainingAccounts(await this.getCustodyMetas(poolName))
662
+ .view()
663
+ .catch((err) => {
664
+ console.error(err);
665
+ throw err;
666
+ });
667
+ };
668
+
669
+ getEntryPriceAndFee = async (
670
+ poolName: string,
671
+ tokenMint: PublicKey,
672
+ collateral: BN,
673
+ size: BN,
674
+ side: PositionSide
675
+ ) => {
676
+ console.log("perps: ", this.perpetuals.publicKey.toBase58())
677
+
678
+ console.log("poolKey: ", this.getPoolKey(poolName).toBase58())
679
+ console.log("custody key : ",this.getCustodyKey(poolName, tokenMint).toBase58());
680
+ console.log("orcalve: ", (await this.getCustodyOracleAccountKey(poolName,tokenMint)).toBase58())
681
+
682
+ //@ts-ignore
683
+ return await this.program.methods
684
+ //@ts-ignore
685
+ .getEntryPriceAndFee({
686
+ collateral,
687
+ size,
688
+ side: side == "long" ? { long: {} } : { short: {} },
689
+ })
690
+ .accounts({
691
+ // signer: this.provider.wallet.publicKey,
692
+ perpetuals: this.perpetuals.publicKey,
693
+ pool: this.getPoolKey(poolName),
694
+ custody: this.getCustodyKey(poolName, tokenMint),
695
+ custodyOracleAccount: await this.getCustodyOracleAccountKey(
696
+ poolName,
697
+ tokenMint
698
+ ),
699
+ // lockCustody: this.getCustodyKey(poolName, tokenMint),
700
+ // lockCustodyOracleAccount: await this.getCustodyOracleAccountKey(
701
+ // poolName,
702
+ // tokenMint
703
+ // ),
704
+ })
705
+ .view()
706
+ .catch((err) => {
707
+ console.error(err);
708
+ throw err;
709
+ });
710
+ };
711
+
712
+ getExitPriceAndFee = async (
713
+ wallet: PublicKey,
714
+ poolName: string,
715
+ tokenMint: PublicKey,
716
+ side: PositionSide
717
+ ) => {
718
+ return await this.program.methods
719
+ .getExitPriceAndFee({})
720
+ .accounts({
721
+ perpetuals: this.perpetuals.publicKey,
722
+ pool: this.getPoolKey(poolName),
723
+ position: this.getPositionKey(wallet, poolName, tokenMint, side),
724
+ custody: this.getCustodyKey(poolName, tokenMint),
725
+ custodyOracleAccount: await this.getCustodyOracleAccountKey(
726
+ poolName,
727
+ tokenMint
728
+ ),
729
+ })
730
+ .view()
731
+ .catch((err) => {
732
+ console.error(err);
733
+ throw err;
734
+ });
735
+ };
736
+
737
+ getLiquidationPrice = async (
738
+ wallet: PublicKey,
739
+ poolName: string,
740
+ tokenMint: PublicKey,
741
+ side: PositionSide,
742
+ addCollateral: BN,
743
+ removeCollateral: BN
744
+ ) => {
745
+ return await this.program.methods
746
+ .getLiquidationPrice({
747
+ addCollateral,
748
+ removeCollateral,
749
+ })
750
+ .accounts({
751
+ perpetuals: this.perpetuals.publicKey,
752
+ pool: this.getPoolKey(poolName),
753
+ position: this.getPositionKey(wallet, poolName, tokenMint, side),
754
+ custody: this.getCustodyKey(poolName, tokenMint),
755
+ custodyOracleAccount: await this.getCustodyOracleAccountKey(
756
+ poolName,
757
+ tokenMint
758
+ ),
759
+ })
760
+ .view()
761
+ .catch((err) => {
762
+ console.error(err);
763
+ throw err;
764
+ });
765
+ };
766
+
767
+ getLiquidationPriceTrx = async (
768
+ wallet: PublicKey,
769
+ poolName: string,
770
+ tokenMint: PublicKey,
771
+ side: PositionSide,
772
+ addCollateral: BN,
773
+ removeCollateral: BN
774
+ ) => {
775
+ return await this.program.methods
776
+ .getLiquidationPrice({
777
+ addCollateral,
778
+ removeCollateral,
779
+ })
780
+ .accounts({
781
+ perpetuals: this.perpetuals.publicKey,
782
+ pool: this.getPoolKey(poolName),
783
+ position: this.getPositionKey(wallet, poolName, tokenMint, side),
784
+ custody: this.getCustodyKey(poolName, tokenMint),
785
+ custodyOracleAccount: await this.getCustodyOracleAccountKey(
786
+ poolName,
787
+ tokenMint
788
+ ),
789
+ })
790
+ .rpc()
791
+ .catch((err) => {
792
+ console.error(err);
793
+ throw err;
794
+ });
795
+ };
796
+
797
+ getLiquidationPrice2 = async (
798
+ wallet: PublicKey,
799
+ poolName: string,
800
+ tokenMint: PublicKey,
801
+ side: PositionSide,
802
+ addCollateral: BN,
803
+ removeCollateral: BN
804
+ ) => {
805
+ return await this.program.methods
806
+ .getLiquidationPrice({
807
+ addCollateral,
808
+ removeCollateral,
809
+ })
810
+ .accounts({
811
+ perpetuals: this.perpetuals.publicKey,
812
+ pool: this.getPoolKey(poolName),
813
+ position: this.getPositionKey(wallet, poolName, tokenMint, side),
814
+ custody: this.getCustodyKey(poolName, tokenMint),
815
+ custodyOracleAccount: await this.getCustodyOracleAccountKey(
816
+ poolName,
817
+ tokenMint
818
+ ),
819
+ })
820
+ .view()
821
+ .catch((err) => {
822
+ console.error(err);
823
+ throw err;
824
+ });
825
+ };
826
+
827
+ getLiquidationState = async (
828
+ wallet: PublicKey,
829
+ poolName: string,
830
+ tokenMint: PublicKey,
831
+ side: PositionSide
832
+ ) => {
833
+ return await this.program.methods
834
+ .getLiquidationState({})
835
+ .accounts({
836
+ perpetuals: this.perpetuals.publicKey,
837
+ pool: this.getPoolKey(poolName),
838
+ position: this.getPositionKey(wallet, poolName, tokenMint, side),
839
+ custody: this.getCustodyKey(poolName, tokenMint),
840
+ custodyOracleAccount: await this.getCustodyOracleAccountKey(
841
+ poolName,
842
+ tokenMint
843
+ ),
844
+ })
845
+ .view()
846
+ .catch((err) => {
847
+ console.error(err);
848
+ throw err;
849
+ });
850
+ };
851
+
852
+ getPnl = async (
853
+ wallet: PublicKey,
854
+ poolName: string,
855
+ tokenMint: PublicKey,
856
+ side: PositionSide
857
+ ) => {
858
+ const pos = this.getPositionKey(wallet, poolName, tokenMint, side);
859
+ console.log("pos:",pos.toBase58())
860
+ return await this.program.methods
861
+ .getPnl({})
862
+ .accounts({
863
+ perpetuals: this.perpetuals.publicKey,
864
+ pool: this.getPoolKey(poolName),
865
+ position: pos,
866
+ custody: this.getCustodyKey(poolName, tokenMint),
867
+ custodyOracleAccount: await this.getCustodyOracleAccountKey(
868
+ poolName,
869
+ tokenMint
870
+ ),
871
+ })
872
+ .view()
873
+ .catch((err) => {
874
+ console.error(err);
875
+ throw err;
876
+ });
877
+ };
878
+
879
+
880
+ getPnlTrx = async (
881
+ wallet: PublicKey,
882
+ poolName: string,
883
+ tokenMint: PublicKey,
884
+ side: PositionSide
885
+ ) => {
886
+ const pos = this.getPositionKey(wallet, poolName, tokenMint, side);
887
+ console.log("pos:",pos.toBase58())
888
+ return await this.program.methods
889
+ .getPnl({})
890
+ .accounts({
891
+ perpetuals: this.perpetuals.publicKey,
892
+ pool: this.getPoolKey(poolName),
893
+ position: pos,
894
+ custody: this.getCustodyKey(poolName, tokenMint),
895
+ custodyOracleAccount: await this.getCustodyOracleAccountKey(
896
+ poolName,
897
+ tokenMint
898
+ ),
899
+ })
900
+ .rpc()
901
+ .catch((err) => {
902
+ console.error(err);
903
+ throw err;
904
+ });
905
+ };
906
+
907
+
908
+ getPnl2 = (
909
+ postionKey : PublicKey,
910
+ postionData: Position,
911
+ tokenPrice : OraclePrice,
912
+ tokenEmaPrice : OraclePrice,
913
+ custodyAccount : CustodyAccount,
914
+ poolAccount : PoolAccount,
915
+ currentTime : BN
916
+ ) => {
917
+
918
+ const positionAccount = PositionAccount.from(postionKey, postionData);
919
+ // console.log("positionAccount:",positionAccount);
920
+ // console.log("side :", postionData.side, (isVariant(postionData.side, 'long')))
921
+
922
+ let {profit, loss, exitFee} = poolAccount.getPnlUsd(
923
+ positionAccount,
924
+ tokenPrice,
925
+ tokenEmaPrice,
926
+ custodyAccount,
927
+ currentTime,
928
+ false,
929
+ );
930
+
931
+ return {
932
+ profit,
933
+ loss
934
+ }
935
+
936
+ }
937
+
938
+ getSwapAmountAndFees = async (
939
+ poolName: string,
940
+ tokenMintIn: PublicKey,
941
+ tokenMintOut: PublicKey,
942
+ amountIn: BN
943
+ ) => {
944
+ return await this.program.methods
945
+ .getSwapAmountAndFees({
946
+ amountIn,
947
+ })
948
+ .accounts({
949
+ perpetuals: this.perpetuals.publicKey,
950
+ pool: this.getPoolKey(poolName),
951
+ receivingCustody: this.getCustodyKey(poolName, tokenMintIn),
952
+ receivingCustodyOracleAccount: await this.getCustodyOracleAccountKey(
953
+ poolName,
954
+ tokenMintIn
955
+ ),
956
+ dispensingCustody: this.getCustodyKey(poolName, tokenMintOut),
957
+ dispensingCustodyOracleAccount: await this.getCustodyOracleAccountKey(
958
+ poolName,
959
+ tokenMintOut
960
+ ),
961
+ })
962
+ .view()
963
+ .catch((err) => {
964
+ console.error(err);
965
+ throw err;
966
+ });
967
+ };
968
+
969
+ getAum = async (poolName: string) => {
970
+ return await this.program.methods
971
+ .getAssetsUnderManagement({})
972
+ .accounts({
973
+ perpetuals: this.perpetuals.publicKey,
974
+ pool: this.getPoolKey(poolName),
975
+ })
976
+ .remainingAccounts(await this.getCustodyMetas(poolName))
977
+ .view()
978
+ .catch((err) => {
979
+ console.error(err);
980
+ throw err;
981
+ });
982
+ };
983
+ }