@jup-ag/lend 0.1.10 → 0.2.0-beta.2

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.
@@ -1,9 +1,8 @@
1
- import { PublicKey, Transaction, SYSVAR_RENT_PUBKEY, SYSVAR_INSTRUCTIONS_PUBKEY, SystemProgram } from '@solana/web3.js';
2
- import BN from 'bn.js';
3
1
  import { Program, AnchorProvider } from '@coral-xyz/anchor';
4
- import { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID, getAssociatedTokenAddressSync, NATIVE_MINT } from '@solana/spl-token';
5
- import { a as getTickHasDebt, c as getPosition, d as getTick, e as getTickIdLiquidation, f as getVaultConfig, h as getBranch, i as getVaultState, j as getPositionMetadata, k as getPositionTokenAccount, l as getPositionMint, g as getVaultAdmin, m as getVaultMetadata, n as getLiquidity, o as getClaimAccount, p as getRateModel, q as getUserBorrowPosition, r as getUserSupplyPosition, s as getLiquidityReserve } from './lend.ByiEG4eI.mjs';
6
- import { e as getReserve } from './lend.BhQGaP3o.mjs';
2
+ import BN from 'bn.js';
3
+ import { p as getTickHasDebt, e as getPosition, q as getTick, s as getTickIdLiquidation, h as getVaultConfig, r as getBranch, f as getVaultState } from './lend.a53XYkl5.mjs';
4
+ import { PublicKey, Transaction } from '@solana/web3.js';
5
+ import { e as getReserve } from './lend.C3XdrR6R.mjs';
7
6
 
8
7
  const address$1 = "jupnw4B6Eqs7ft6rxpzYLJZYSnrpRgPcr589n5Kv4oc";
9
8
  const metadata$1 = {
@@ -7055,6 +7054,26 @@ async function loadRelevantBranchesForLiquidate(vaultId, vaultState, program, ma
7055
7054
  if (!doesBranchExist(0)) branches.push({ branchId: 0 });
7056
7055
  return branches;
7057
7056
  }
7057
+ async function getOracleSources({
7058
+ connection,
7059
+ signer,
7060
+ oracle: oracle$1
7061
+ }) {
7062
+ const program = new Program(
7063
+ oracle,
7064
+ new AnchorProvider(connection, {
7065
+ signTransaction() {
7066
+ throw new Error("Not implemented");
7067
+ },
7068
+ signAllTransactions() {
7069
+ throw new Error("Not implemented");
7070
+ },
7071
+ publicKey: signer ?? new PublicKey("HEyJLdMfZhhQ7FHCtjD5DWDFNFQhaeAVAsHeWqoY6dSD")
7072
+ })
7073
+ );
7074
+ const oracleData = await program.account.oracle.fetch(oracle$1);
7075
+ return oracleData.sources;
7076
+ }
7058
7077
  async function readOraclePrice({
7059
7078
  connection,
7060
7079
  signer,
@@ -7095,841 +7114,4 @@ const getLiquidityProgramId = (market) => {
7095
7114
  return market === "ethena" ? new PublicKey("jup6QF1sNDGpkkcu6F4qaFHcRBmnSS1VgyB4uFbBvNS") : new PublicKey("jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC");
7096
7115
  };
7097
7116
 
7098
- const MPL_TOKEN_METADATA_PROGRAM_ID = new PublicKey(
7099
- "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"
7100
- );
7101
- async function getOtherInstructionsOperate(vaultId, vaultState, currentPosition, finalPosition, currentTick, currentTickId, program, signer, market) {
7102
- const otherIxs = [];
7103
- const tickToRead = [currentTick];
7104
- let finalTickData;
7105
- tickToRead.push(currentPosition.tick);
7106
- tickToRead.push(finalPosition.tick);
7107
- if (tickToRead.length > 0) {
7108
- const tickData = await program.account.tick.fetchMultiple(
7109
- tickToRead.map((tick) => getTick(vaultId, tick, market))
7110
- );
7111
- tickData[0];
7112
- finalTickData = tickData[2];
7113
- for (const [i, tickDatum] of tickData.entries()) {
7114
- if (!tickDatum) {
7115
- const ix = await program.methods.initTick(vaultId, tickToRead[i]).accounts(getInitTickContext(vaultId, tickToRead[i], signer, market)).instruction();
7116
- otherIxs.push(ix);
7117
- }
7118
- }
7119
- }
7120
- let newBranchId;
7121
- if (vaultState.branchLiquidated) {
7122
- newBranchId = vaultState.totalBranchId + 1;
7123
- let newBranchData = null;
7124
- try {
7125
- newBranchData = await program.account.branch.fetch(
7126
- getBranch(vaultId, newBranchId, market)
7127
- );
7128
- } catch {
7129
- }
7130
- if (!newBranchData) {
7131
- const ix = await program.methods.initBranch(vaultId, newBranchId).accounts(getInitBranchContext(vaultId, newBranchId, signer, market)).instruction();
7132
- otherIxs.push(ix);
7133
- }
7134
- } else {
7135
- newBranchId = vaultState.currentBranchId;
7136
- }
7137
- const newBranchPda = getBranch(vaultId, newBranchId, market);
7138
- const currentTickIdDataPda = getTickIdLiquidation(
7139
- vaultId,
7140
- currentTick,
7141
- // Position tick
7142
- currentTickId,
7143
- // Position tick ID
7144
- market
7145
- );
7146
- const tickIdsToRead = [
7147
- {
7148
- tick: currentTick,
7149
- totalIds: currentTickId
7150
- }
7151
- ];
7152
- const finalTickIdDataPda = getTickIdLiquidation(
7153
- vaultId,
7154
- finalPosition.tick,
7155
- finalTickData ? finalTickData.totalIds : 0,
7156
- market
7157
- );
7158
- if (finalPosition.tick !== currentTick)
7159
- if (finalTickData) {
7160
- tickIdsToRead.push({
7161
- tick: finalPosition.tick,
7162
- totalIds: finalTickData.totalIds
7163
- });
7164
- } else {
7165
- const context = await getInitTickIdLiquidationContext(
7166
- vaultId,
7167
- finalPosition.tick,
7168
- signer,
7169
- program,
7170
- market
7171
- );
7172
- const ix = await program.methods.initTickIdLiquidation(vaultId, finalPosition.tick, 0).accounts(context).instruction();
7173
- otherIxs.push(ix);
7174
- }
7175
- const tickIdData = await program.account.tickIdLiquidation.fetchMultiple(
7176
- tickIdsToRead.map(
7177
- ({ tick, totalIds }) => getTickIdLiquidation(vaultId, tick, totalIds, market)
7178
- )
7179
- );
7180
- if (tickIdData.length > 0) {
7181
- for (const [i, tickIdDatum] of tickIdData.entries()) {
7182
- if (!tickIdDatum) {
7183
- const ix = await program.methods.initTickIdLiquidation(
7184
- vaultId,
7185
- tickIdsToRead[i].tick,
7186
- tickIdsToRead[i].totalIds
7187
- ).accounts(
7188
- await getInitTickIdLiquidationContext(
7189
- vaultId,
7190
- tickIdsToRead[i].tick,
7191
- signer,
7192
- program,
7193
- market
7194
- )
7195
- ).instruction();
7196
- otherIxs.push(ix);
7197
- }
7198
- }
7199
- }
7200
- return {
7201
- otherIxs,
7202
- newBranchPda,
7203
- currentTickIdDataPda,
7204
- finalTickIdDataPda
7205
- };
7206
- }
7207
- const tickHelper = (tickValue) => {
7208
- return tickValue === 0 ? INIT_TICK : tickValue;
7209
- };
7210
- async function getRemainingAccountsOperate(vaultId, vaultState, vaultConfig, finalPositionTick, existingPositionTick, liquidationStatus, postLiquidationBranchId, program, market) {
7211
- const remainingAccounts = [];
7212
- const oracleProgram = new Program(oracle, program.provider);
7213
- const [oracleData, branches, tickHasDebt] = await Promise.all([
7214
- oracleProgram.account.oracle.fetch(new PublicKey(vaultConfig.oracle)),
7215
- // Add branch accounts (next 10 remaining accounts)
7216
- loadRelevantBranches(
7217
- vaultId,
7218
- vaultState,
7219
- liquidationStatus,
7220
- postLiquidationBranchId,
7221
- program,
7222
- market
7223
- ),
7224
- loadRelevantTicksHasDebtArrays(
7225
- vaultId,
7226
- tickHelper(vaultState.topmostTick),
7227
- existingPositionTick,
7228
- finalPositionTick,
7229
- program,
7230
- market
7231
- )
7232
- ]);
7233
- const sourceLength = oracleData.sources.length;
7234
- for (const source of oracleData.sources)
7235
- remainingAccounts.push({
7236
- pubkey: new PublicKey(source.source),
7237
- isWritable: false,
7238
- isSigner: false
7239
- });
7240
- const branchLength = branches.length;
7241
- for (const branch of branches) {
7242
- remainingAccounts.push({
7243
- pubkey: getBranch(vaultId, branch, market),
7244
- isWritable: true,
7245
- isSigner: false
7246
- });
7247
- }
7248
- const tickHasDebtLength = tickHasDebt.length;
7249
- for (const tickHasDebtArray of tickHasDebt)
7250
- remainingAccounts.push({
7251
- pubkey: tickHasDebtArray,
7252
- isWritable: true,
7253
- isSigner: false
7254
- });
7255
- const remainingAccountsIndices = [
7256
- sourceLength,
7257
- branchLength,
7258
- tickHasDebtLength
7259
- ];
7260
- return {
7261
- remainingAccounts,
7262
- remainingAccountsIndices
7263
- };
7264
- }
7265
- async function getOperateContext({
7266
- vaultId,
7267
- positionId,
7268
- program,
7269
- connection,
7270
- signer,
7271
- positionOwner = signer,
7272
- colAmount: newCol,
7273
- debtAmount: newDebt,
7274
- recipient,
7275
- market
7276
- }) {
7277
- program = program ?? getVaultsProgram({ connection, signer, market });
7278
- const [vaultState, vaultConfig, vaultMetadata] = await Promise.all([
7279
- program.account.vaultState.fetch(getVaultState(vaultId, market)),
7280
- program.account.vaultConfig.fetch(
7281
- getVaultConfig(vaultId, market)
7282
- ),
7283
- program.account.vaultMetadata.fetch(
7284
- getVaultMetadata(vaultId, market)
7285
- )
7286
- ]);
7287
- const [supplyTokenProgram, borrowTokenProgram] = await Promise.all([
7288
- getAccountOwner(vaultConfig.supplyToken, connection),
7289
- getAccountOwner(vaultConfig.borrowToken, connection)
7290
- ]);
7291
- const vaultSupplyDecimals = vaultMetadata.supplyMintDecimals;
7292
- const vaultBorrowDecimals = vaultMetadata.borrowMintDecimals;
7293
- if (newCol.gt(MIN_I128)) {
7294
- const decimalsDelta = vaultSupplyDecimals < 9 ? 9 - vaultSupplyDecimals : 0;
7295
- newCol = newCol.mul(new BN(10).pow(new BN(decimalsDelta)));
7296
- }
7297
- if (newDebt.gt(MIN_I128)) {
7298
- const decimalsDelta = vaultBorrowDecimals < 9 ? 9 - vaultBorrowDecimals : 0;
7299
- newDebt = newDebt.mul(new BN(10).pow(new BN(decimalsDelta)));
7300
- }
7301
- const positionData = positionId === 0 ? {
7302
- nftId: vaultState.nextPositionId,
7303
- positionMint: new PublicKey(0),
7304
- isSupplyOnlyPosition: 1,
7305
- tick: -2147483648,
7306
- tickId: 0,
7307
- lastUpdateTimestamp: new BN(0),
7308
- supplyAmount: new BN(0),
7309
- dustDebtAmount: new BN(0)} : await program.account.position.fetch(
7310
- getPosition(vaultId, positionId, market)
7311
- );
7312
- let existingPositionTick = positionData.tick;
7313
- let existingPositionTickId = positionData.tickId;
7314
- const currentPosition = await getCurrentPositionState({
7315
- vaultId,
7316
- position: positionData,
7317
- program,
7318
- market
7319
- });
7320
- if (existingPositionTick === -2147483648) {
7321
- existingPositionTick = currentPosition.tick;
7322
- existingPositionTickId = 0;
7323
- }
7324
- const currentPositionTickPda = getTick(
7325
- vaultId,
7326
- existingPositionTick,
7327
- market
7328
- );
7329
- const finalPosition = await getFinalPosition({
7330
- vaultId,
7331
- currentPosition,
7332
- newColAmount: newCol,
7333
- newDebtAmount: newDebt,
7334
- program,
7335
- connection,
7336
- signer,
7337
- market
7338
- });
7339
- const { otherIxs, newBranchPda, currentTickIdDataPda, finalTickIdDataPda } = await getOtherInstructionsOperate(
7340
- vaultId,
7341
- vaultState,
7342
- currentPosition,
7343
- finalPosition,
7344
- existingPositionTick,
7345
- existingPositionTickId,
7346
- program,
7347
- signer,
7348
- market
7349
- );
7350
- const { remainingAccounts, remainingAccountsIndices } = await getRemainingAccountsOperate(
7351
- vaultId,
7352
- vaultState,
7353
- vaultConfig,
7354
- finalPosition.tick,
7355
- existingPositionTick,
7356
- currentPosition.userLiquidationStatus,
7357
- currentPosition.postLiquidationBranchId,
7358
- program,
7359
- market
7360
- );
7361
- const accounts = {
7362
- signer,
7363
- signerSupplyTokenAccount: getAssociatedTokenAddressSync(
7364
- vaultConfig.supplyToken,
7365
- signer,
7366
- true,
7367
- supplyTokenProgram
7368
- ),
7369
- signerBorrowTokenAccount: getAssociatedTokenAddressSync(
7370
- vaultConfig.borrowToken,
7371
- signer,
7372
- true,
7373
- borrowTokenProgram
7374
- ),
7375
- recipient: recipient ?? null,
7376
- recipientSupplyTokenAccount: recipient ? getAssociatedTokenAddressSync(
7377
- vaultConfig.supplyToken,
7378
- recipient,
7379
- true,
7380
- supplyTokenProgram
7381
- ) : null,
7382
- recipientBorrowTokenAccount: recipient ? getAssociatedTokenAddressSync(
7383
- vaultConfig.borrowToken,
7384
- recipient,
7385
- true,
7386
- borrowTokenProgram
7387
- ) : null,
7388
- vaultConfig: getVaultConfig(vaultId, market),
7389
- vaultState: getVaultState(vaultId, market),
7390
- supplyToken: vaultConfig.supplyToken,
7391
- borrowToken: vaultConfig.borrowToken,
7392
- oracle: new PublicKey(vaultConfig.oracle),
7393
- position: getPosition(vaultId, positionData.nftId, market),
7394
- positionTokenAccount: getPositionTokenAccount(
7395
- vaultId,
7396
- positionData.nftId,
7397
- positionOwner,
7398
- market
7399
- ),
7400
- currentPositionTick: currentPositionTickPda,
7401
- finalPositionTick: getTick(vaultId, finalPosition.tick, market),
7402
- currentPositionTickId: currentTickIdDataPda,
7403
- finalPositionTickId: finalTickIdDataPda,
7404
- newBranch: newBranchPda,
7405
- supplyTokenReservesLiquidity: getLiquidityReserve(
7406
- vaultConfig.supplyToken,
7407
- market
7408
- ),
7409
- borrowTokenReservesLiquidity: getLiquidityReserve(
7410
- vaultConfig.borrowToken,
7411
- market
7412
- ),
7413
- vaultSupplyPositionOnLiquidity: getUserSupplyPosition(
7414
- vaultConfig.supplyToken,
7415
- getVaultConfig(vaultId, market),
7416
- market
7417
- ),
7418
- vaultBorrowPositionOnLiquidity: getUserBorrowPosition(
7419
- vaultConfig.borrowToken,
7420
- getVaultConfig(vaultId, market),
7421
- market
7422
- ),
7423
- supplyRateModel: getRateModel(vaultConfig.supplyToken, market),
7424
- borrowRateModel: getRateModel(vaultConfig.borrowToken, market),
7425
- supplyTokenClaimAccount: null,
7426
- borrowTokenClaimAccount: null,
7427
- liquidity: getLiquidity(market),
7428
- liquidityProgram: getLiquidityProgramId(market),
7429
- vaultSupplyTokenAccount: getAssociatedTokenAddressSync(
7430
- vaultConfig.supplyToken,
7431
- getLiquidity(market),
7432
- true,
7433
- supplyTokenProgram
7434
- ),
7435
- vaultBorrowTokenAccount: getAssociatedTokenAddressSync(
7436
- vaultConfig.borrowToken,
7437
- getLiquidity(market),
7438
- true,
7439
- borrowTokenProgram
7440
- ),
7441
- oracleProgram: new PublicKey(vaultConfig.oracleProgram),
7442
- supplyTokenProgram,
7443
- borrowTokenProgram,
7444
- associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
7445
- systemProgram: SystemProgram.programId
7446
- };
7447
- return {
7448
- nftId: positionData.nftId,
7449
- accounts,
7450
- remainingAccounts,
7451
- initPositionIx: positionId === 0 ? await program.methods.initPosition(vaultId, positionData.nftId).accounts(
7452
- getInitPositionContext(
7453
- vaultId,
7454
- positionData.nftId,
7455
- signer,
7456
- market
7457
- )
7458
- ).instruction() : null,
7459
- otherIxs,
7460
- remainingAccountsIndices,
7461
- lookupTable: vaultMetadata.lookupTable
7462
- };
7463
- }
7464
- async function getInitPositionIx({
7465
- vaultId,
7466
- connection,
7467
- signer,
7468
- market = "main"
7469
- }) {
7470
- const program = getVaultsProgram({ connection, signer, market });
7471
- const vaultState = await program.account.vaultState.fetch(
7472
- getVaultState(vaultId, market)
7473
- );
7474
- return {
7475
- ix: await program.methods.initPosition(vaultId, vaultState.nextPositionId).accounts(
7476
- getInitPositionContext(
7477
- vaultId,
7478
- vaultState.nextPositionId,
7479
- signer,
7480
- market
7481
- )
7482
- ).instruction(),
7483
- nftId: vaultState.nextPositionId
7484
- };
7485
- }
7486
- function getInitPositionContext(vaultId, positionId, signer, market) {
7487
- return {
7488
- signer,
7489
- vaultAdmin: getVaultAdmin(market),
7490
- vaultState: getVaultState(vaultId, market),
7491
- position: getPosition(vaultId, positionId, market),
7492
- positionMint: getPositionMint(vaultId, positionId, market),
7493
- positionTokenAccount: getPositionTokenAccount(
7494
- vaultId,
7495
- positionId,
7496
- signer,
7497
- market
7498
- ),
7499
- tokenProgram: TOKEN_PROGRAM_ID,
7500
- metadataAccount: getPositionMetadata(vaultId, positionId, market),
7501
- associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
7502
- systemProgram: SystemProgram.programId,
7503
- sysvarInstruction: SYSVAR_INSTRUCTIONS_PUBKEY,
7504
- metadataProgram: MPL_TOKEN_METADATA_PROGRAM_ID,
7505
- rent: SYSVAR_RENT_PUBKEY
7506
- };
7507
- }
7508
- const getOperateIx = async ({
7509
- vaultId,
7510
- positionId,
7511
- colAmount,
7512
- debtAmount,
7513
- connection,
7514
- signer,
7515
- recipient,
7516
- positionOwner,
7517
- market = "main"
7518
- }) => {
7519
- const program = getVaultsProgram({ connection, signer, market });
7520
- const {
7521
- accounts,
7522
- remainingAccounts,
7523
- remainingAccountsIndices,
7524
- initPositionIx,
7525
- otherIxs,
7526
- lookupTable,
7527
- nftId
7528
- } = await getOperateContext({
7529
- vaultId,
7530
- positionId,
7531
- colAmount,
7532
- debtAmount,
7533
- signer,
7534
- positionOwner,
7535
- connection,
7536
- recipient,
7537
- program,
7538
- market
7539
- });
7540
- if (accounts.borrowToken.toString() !== NATIVE_MINT.toString() && debtAmount.lt(new BN(0))) {
7541
- try {
7542
- const userDebtTokenBalance = await connection.getTokenAccountBalance(
7543
- accounts.signerBorrowTokenAccount
7544
- );
7545
- if (userDebtTokenBalance.value.amount === debtAmount.abs().toString()) {
7546
- debtAmount = debtAmount.add(new BN(1));
7547
- }
7548
- } catch {
7549
- }
7550
- }
7551
- const [operateIx, addressLookupTable] = await Promise.all([
7552
- program.methods.operate(
7553
- colAmount,
7554
- debtAmount,
7555
- { direct: {} },
7556
- Buffer.from(remainingAccountsIndices)
7557
- ).accounts(accounts).remainingAccounts(remainingAccounts).instruction(),
7558
- connection.getAddressLookupTable(lookupTable)
7559
- ]);
7560
- return {
7561
- nftId,
7562
- accounts,
7563
- remainingAccounts,
7564
- remainingAccountsIndices,
7565
- addressLookupTableAddresses: lookupTable ? [lookupTable] : [],
7566
- addressLookupTableAccounts: addressLookupTable.value ? [addressLookupTable.value] : [],
7567
- ixs: initPositionIx ? [initPositionIx, ...otherIxs, operateIx] : [...otherIxs, operateIx]
7568
- };
7569
- };
7570
- function getInitBranchContext(vaultId, branchId, signer, market) {
7571
- return {
7572
- signer,
7573
- vaultConfig: getVaultConfig(vaultId, market),
7574
- branch: getBranch(vaultId, branchId, market),
7575
- systemProgram: SystemProgram.programId
7576
- };
7577
- }
7578
- function getInitTickContext(vaultId, tick, signer, market) {
7579
- return {
7580
- signer,
7581
- vaultConfig: getVaultConfig(vaultId, market),
7582
- tickData: getTick(vaultId, tick, market),
7583
- systemProgram: SystemProgram.programId
7584
- };
7585
- }
7586
- async function getInitTickIdLiquidationContext(vaultId, tick, signer, program, market) {
7587
- const tickData = await program.account.tick.fetch(getTick(vaultId, tick, market)).catch(() => null);
7588
- if (!tickData) {
7589
- return {
7590
- signer,
7591
- vaultConfig: getVaultConfig(vaultId, market),
7592
- tickIdLiquidation: getTickIdLiquidation(
7593
- vaultId,
7594
- tick,
7595
- 0,
7596
- market
7597
- ),
7598
- tickData: getTick(vaultId, tick, market),
7599
- systemProgram: SystemProgram.programId
7600
- };
7601
- }
7602
- return {
7603
- signer,
7604
- vaultConfig: getVaultConfig(vaultId, market),
7605
- tickIdLiquidation: getTickIdLiquidation(
7606
- vaultId,
7607
- tick,
7608
- tickData.totalIds,
7609
- market
7610
- ),
7611
- tickData: getTick(vaultId, tick, market),
7612
- systemProgram: SystemProgram.programId
7613
- };
7614
- }
7615
- async function getLiquidateContext({
7616
- vaultId,
7617
- to,
7618
- program,
7619
- connection,
7620
- signer,
7621
- market
7622
- }) {
7623
- program = program ?? getVaultsProgram({ connection, signer, market });
7624
- const [vaultState, vaultConfig, vaultMetadata] = await Promise.all([
7625
- program.account.vaultState.fetch(getVaultState(vaultId, market)),
7626
- program.account.vaultConfig.fetch(
7627
- getVaultConfig(vaultId, market)
7628
- ),
7629
- program.account.vaultMetadata.fetch(
7630
- getVaultMetadata(vaultId, market)
7631
- )
7632
- ]);
7633
- const [supplyTokenProgram, borrowTokenProgram] = await Promise.all([
7634
- getAccountOwner(vaultConfig.supplyToken, connection),
7635
- getAccountOwner(vaultConfig.borrowToken, connection)
7636
- ]);
7637
- const { arrayIndex } = getTickIndices(vaultState.topmostTick);
7638
- let { otherIxs, newBranchPda } = await getOtherInstructionsLiquidate(
7639
- vaultId,
7640
- vaultState,
7641
- program,
7642
- signer,
7643
- market
7644
- );
7645
- const {
7646
- remainingAccounts,
7647
- remainingAccountsIndices,
7648
- otherIxs: finalOtherIxs
7649
- } = await getRemainingAccountsLiquidate(
7650
- vaultId,
7651
- vaultState,
7652
- vaultConfig,
7653
- otherIxs,
7654
- program,
7655
- connection,
7656
- signer,
7657
- market
7658
- );
7659
- return {
7660
- accounts: {
7661
- signer,
7662
- signerTokenAccount: getAssociatedTokenAddressSync(
7663
- vaultConfig.borrowToken,
7664
- signer,
7665
- false,
7666
- borrowTokenProgram
7667
- ),
7668
- to,
7669
- toTokenAccount: getAssociatedTokenAddressSync(
7670
- vaultConfig.supplyToken,
7671
- to,
7672
- false,
7673
- supplyTokenProgram
7674
- ),
7675
- vaultAdmin: getVaultAdmin(market),
7676
- vaultConfig: getVaultConfig(vaultId, market),
7677
- vaultState: getVaultState(vaultId, market),
7678
- supplyToken: vaultConfig.supplyToken,
7679
- borrowToken: vaultConfig.borrowToken,
7680
- oracle: new PublicKey(vaultConfig.oracle),
7681
- tickHasDebt: getTickHasDebt(vaultId, arrayIndex, market),
7682
- newBranch: newBranchPda,
7683
- supplyTokenReservesLiquidity: getLiquidityReserve(
7684
- vaultConfig.supplyToken,
7685
- market
7686
- ),
7687
- borrowTokenReservesLiquidity: getLiquidityReserve(
7688
- vaultConfig.borrowToken,
7689
- market
7690
- ),
7691
- vaultSupplyPositionOnLiquidity: getUserSupplyPosition(
7692
- vaultConfig.supplyToken,
7693
- getVaultConfig(vaultId, market),
7694
- market
7695
- ),
7696
- vaultBorrowPositionOnLiquidity: getUserBorrowPosition(
7697
- vaultConfig.borrowToken,
7698
- getVaultConfig(vaultId, market),
7699
- market
7700
- ),
7701
- supplyRateModel: getRateModel(vaultConfig.supplyToken, market),
7702
- borrowRateModel: getRateModel(vaultConfig.borrowToken, market),
7703
- supplyTokenClaimAccount: getClaimAccount(
7704
- vaultConfig.supplyToken,
7705
- getVaultConfig(vaultId, market),
7706
- market
7707
- ),
7708
- borrowTokenClaimAccount: getClaimAccount(
7709
- vaultConfig.borrowToken,
7710
- getVaultConfig(vaultId, market),
7711
- market
7712
- ),
7713
- liquidity: getLiquidity(market),
7714
- liquidityProgram: getLiquidityProgramId(market),
7715
- vaultSupplyTokenAccount: getAssociatedTokenAddressSync(
7716
- vaultConfig.supplyToken,
7717
- getLiquidity(market),
7718
- true,
7719
- supplyTokenProgram
7720
- ),
7721
- vaultBorrowTokenAccount: getAssociatedTokenAddressSync(
7722
- vaultConfig.borrowToken,
7723
- getLiquidity(market),
7724
- true,
7725
- borrowTokenProgram
7726
- ),
7727
- oracleProgram: new PublicKey(vaultConfig.oracleProgram),
7728
- supplyTokenProgram,
7729
- borrowTokenProgram,
7730
- systemProgram: SystemProgram.programId,
7731
- associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID
7732
- },
7733
- remainingAccounts,
7734
- otherIxs: finalOtherIxs,
7735
- remainingAccountsIndices,
7736
- lookupTable: vaultMetadata.lookupTable
7737
- };
7738
- }
7739
- const getLiquidateIx = async ({
7740
- vaultId,
7741
- debtAmount,
7742
- colPerUnitDebt = new BN(0),
7743
- absorb = false,
7744
- signer,
7745
- to = signer,
7746
- connection,
7747
- market
7748
- }) => {
7749
- const program = getVaultsProgram({ connection, signer, market });
7750
- const {
7751
- accounts,
7752
- remainingAccounts,
7753
- remainingAccountsIndices,
7754
- otherIxs,
7755
- lookupTable
7756
- } = await getLiquidateContext({
7757
- vaultId,
7758
- to,
7759
- program,
7760
- signer,
7761
- connection,
7762
- market
7763
- });
7764
- const ixs = [];
7765
- if (otherIxs.length > 0) {
7766
- ixs.push(...otherIxs);
7767
- }
7768
- const [ix, addressLookupTable] = await Promise.all([
7769
- program.methods.liquidate(
7770
- debtAmount,
7771
- colPerUnitDebt,
7772
- absorb,
7773
- { direct: {} },
7774
- Buffer.from(remainingAccountsIndices)
7775
- ).accounts(accounts).remainingAccounts(remainingAccounts).instruction(),
7776
- connection.getAddressLookupTable(lookupTable)
7777
- ]);
7778
- ixs.push(ix);
7779
- return {
7780
- accounts,
7781
- remainingAccounts,
7782
- remainingAccountsIndices,
7783
- ixs,
7784
- addressLookupTableAddresses: lookupTable ? [lookupTable] : [],
7785
- addressLookupTableAccounts: addressLookupTable.value ? [addressLookupTable.value] : []
7786
- };
7787
- };
7788
- async function getOtherInstructionsLiquidate(vaultId, vaultState, program, signer, market) {
7789
- const otherIxs = [];
7790
- let newBranchId = vaultState.branchLiquidated === 1 ? vaultState.totalBranchId + 1 : vaultState.currentBranchId;
7791
- let newBranchPda = getBranch(
7792
- vaultId,
7793
- newBranchId,
7794
- market
7795
- );
7796
- const [newBranchData, tickData] = await Promise.all([
7797
- program.account.branch.fetch(newBranchPda).catch(() => null),
7798
- // might be possible that liquidation ends on a tick that is not initialized
7799
- program.account.tick.fetch(getTick(vaultId, vaultState.topmostTick, market)).catch(() => null)
7800
- ]);
7801
- if (!newBranchData) {
7802
- const ix = await program.methods.initBranch(vaultId, newBranchId).accounts(getInitBranchContext(vaultId, newBranchId, signer, market)).instruction();
7803
- otherIxs.push(ix);
7804
- }
7805
- if (!tickData) {
7806
- const ix = await program.methods.initTick(vaultId, vaultState.topmostTick).accounts(
7807
- getInitTickContext(vaultId, vaultState.topmostTick, signer, market)
7808
- ).instruction();
7809
- otherIxs.push(ix);
7810
- }
7811
- return {
7812
- otherIxs,
7813
- newBranchPda
7814
- };
7815
- }
7816
- async function loadRelevantTicksForLiquidate(vaultId, vaultState, liquidationTick, program, market) {
7817
- const ticks = [];
7818
- let topTick = vaultState.topmostTick;
7819
- if (topTick > liquidationTick)
7820
- try {
7821
- const topTickData = await program.account.tick.fetch(
7822
- getTick(vaultId, topTick, market)
7823
- );
7824
- if (topTickData) ticks.push({ ...topTickData, tick: topTick });
7825
- } catch {
7826
- }
7827
- let nextTick = MIN_TICK$1;
7828
- try {
7829
- nextTick = await findNextTickWithDebt(vaultId, topTick, program, market);
7830
- } catch {
7831
- }
7832
- const doesTickExist = (tick) => ticks.some((t) => t.tick === tick);
7833
- while (nextTick > liquidationTick && !doesTickExist(nextTick)) {
7834
- try {
7835
- const nextTickData = await program.account.tick.fetch(
7836
- getTick(vaultId, nextTick, market)
7837
- );
7838
- if (nextTickData) ticks.push({ ...nextTickData, tick: nextTick });
7839
- else throw new Error("Tick not found to load");
7840
- nextTick = await findNextTickWithDebt(vaultId, nextTick, program, market);
7841
- } catch {
7842
- }
7843
- }
7844
- return { ticks, nextTick };
7845
- }
7846
- async function getRemainingAccountsLiquidate(vaultId, vaultState, vaultConfig, otherIxs, program, connection, signer, market) {
7847
- const remainingAccounts = [];
7848
- const { oraclePriceLiquidate, oracleSources } = await readOraclePrice({
7849
- oracle: vaultConfig.oracle,
7850
- connection
7851
- // signer,
7852
- });
7853
- const liquidationRatio = new BN(oraclePriceLiquidate).mul(new BN(281474976710656)).div(new BN(10).pow(new BN(15)));
7854
- const liquidationThresholdRatio = liquidationRatio.mul(new BN(vaultConfig.liquidationThreshold)).div(new BN(10).pow(new BN(3)));
7855
- const liquidationTick = getTickAtRatio(liquidationThresholdRatio);
7856
- for (const source of oracleSources) {
7857
- remainingAccounts.push({
7858
- pubkey: source.source,
7859
- isWritable: false,
7860
- isSigner: false
7861
- });
7862
- }
7863
- const [branches, { ticks: tickAccounts, nextTick }] = await Promise.all([
7864
- loadRelevantBranchesForLiquidate(vaultId, vaultState, program, market),
7865
- loadRelevantTicksForLiquidate(
7866
- vaultId,
7867
- vaultState,
7868
- liquidationTick,
7869
- program,
7870
- market
7871
- )
7872
- ]);
7873
- const tickHasDebt = await loadRelevantTicksHasDebtArraysLiquidate(
7874
- vaultId,
7875
- vaultState.topmostTick,
7876
- nextTick,
7877
- program,
7878
- market
7879
- );
7880
- for (const branch of branches) {
7881
- remainingAccounts.push({
7882
- pubkey: getBranch(vaultId, branch.branchId, market),
7883
- isWritable: true,
7884
- isSigner: false
7885
- });
7886
- }
7887
- const tickToInit = [];
7888
- const existingTicks = await Promise.all(
7889
- tickAccounts.map(
7890
- (tickData) => program.account.tick.fetch(getTick(vaultId, tickData.tick, market)).catch(() => null)
7891
- )
7892
- );
7893
- const initInstructions = await Promise.all(
7894
- tickAccounts.map(async (tickData, index) => {
7895
- const existingTick = existingTicks[index];
7896
- if (!existingTick && !tickToInit.includes(tickData.tick)) {
7897
- tickToInit.push(tickData.tick);
7898
- return program.methods.initTick(vaultId, tickData.tick).accounts(getInitTickContext(vaultId, tickData.tick, signer, market)).instruction();
7899
- }
7900
- return null;
7901
- })
7902
- );
7903
- for (const ix of initInstructions) {
7904
- if (ix) {
7905
- otherIxs.push(ix);
7906
- }
7907
- }
7908
- for (const tickData of tickAccounts) {
7909
- remainingAccounts.push({
7910
- pubkey: getTick(vaultId, tickData.tick, market),
7911
- isWritable: true,
7912
- isSigner: false
7913
- });
7914
- }
7915
- for (const tickHasDebtArray of tickHasDebt) {
7916
- remainingAccounts.push({
7917
- pubkey: getTickHasDebt(vaultId, tickHasDebtArray.index, market),
7918
- isWritable: true,
7919
- isSigner: false
7920
- });
7921
- }
7922
- const remainingAccountsIndices = [
7923
- oracleSources.length,
7924
- branches.length,
7925
- tickAccounts.length,
7926
- tickHasDebt.length
7927
- ];
7928
- return {
7929
- remainingAccounts,
7930
- otherIxs,
7931
- remainingAccountsIndices
7932
- };
7933
- }
7934
-
7935
- export { loadRelevantBranchesForLiquidate as A, loadRelevantTicksHasDebtArrays as B, loadRelevantTicksHasDebtArraysLiquidate as C, readOraclePrice as D, readTickHasDebtArray as E, vaultsIdl as F, INIT_TICK as I, MAX_REPAY_AMOUNT as M, TICKS_PER_TICK_HAS_DEBT as T, ZERO_TICK_SCALED_RATIO$1 as Z, getLiquidateIx as a, MAX_TICK$1 as b, MAX_WITHDRAW_AMOUNT as c, MIN_I128 as d, MIN_TICK$1 as e, TICK_HAS_DEBT_ARRAY_SIZE as f, getVaultsProgram as g, TICK_HAS_DEBT_CHILDREN_SIZE as h, TICK_HAS_DEBT_CHILDREN_SIZE_IN_BITS as i, TOTAL_INDICES_NEEDED as j, findNextTickWithDebt as k, getAccountOwner as l, getCurrentPosition as m, getCurrentPositionState as n, getFinalPosition as o, getFirstTickForIndex as p, getInitPositionContext as q, getInitPositionIx as r, getLiquidateContext as s, getLiquidityProgramId as t, getOperateContext as u, getOperateIx as v, getRatioAtTick as w, getTickAtRatio as x, getTickIndices as y, loadRelevantBranches as z };
7117
+ export { vaultsIdl as A, oracle as B, INIT_TICK as I, MAX_REPAY_AMOUNT as M, TICKS_PER_TICK_HAS_DEBT as T, ZERO_TICK_SCALED_RATIO$1 as Z, MAX_TICK$1 as a, MAX_WITHDRAW_AMOUNT as b, MIN_I128 as c, MIN_TICK$1 as d, TICK_HAS_DEBT_ARRAY_SIZE as e, TICK_HAS_DEBT_CHILDREN_SIZE as f, getVaultsProgram as g, TICK_HAS_DEBT_CHILDREN_SIZE_IN_BITS as h, TOTAL_INDICES_NEEDED as i, findNextTickWithDebt as j, getAccountOwner as k, getCurrentPosition as l, getCurrentPositionState as m, getFinalPosition as n, getFirstTickForIndex as o, getLiquidityProgramId as p, getOracleSources as q, getRatioAtTick as r, getTickAtRatio as s, getTickIndices as t, loadRelevantBranches as u, loadRelevantBranchesForLiquidate as v, loadRelevantTicksHasDebtArrays as w, loadRelevantTicksHasDebtArraysLiquidate as x, readOraclePrice as y, readTickHasDebtArray as z };