@0dotxyz/p0-ts-sdk 1.2.0 → 1.2.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.
package/dist/index.cjs CHANGED
@@ -43353,8 +43353,22 @@ async function buildSwapCollateralFlashloanTx({
43353
43353
  overrideInferAccounts,
43354
43354
  blockhash
43355
43355
  }) {
43356
- const { withdrawBank, tokenProgram: withdrawTokenProgram, totalPositionAmount } = withdrawOpts;
43356
+ const {
43357
+ withdrawBank,
43358
+ tokenProgram: withdrawTokenProgram,
43359
+ totalPositionAmount,
43360
+ withdrawAmount
43361
+ } = withdrawOpts;
43357
43362
  const { depositBank, tokenProgram: depositTokenProgram } = depositOpts;
43363
+ if (withdrawAmount !== void 0 && withdrawAmount <= 0) {
43364
+ throw new Error("withdrawAmount must be greater than 0");
43365
+ }
43366
+ const actualWithdrawAmount = Math.min(withdrawAmount ?? totalPositionAmount, totalPositionAmount);
43367
+ const isFullWithdraw = isWholePosition(
43368
+ { amount: totalPositionAmount, isLending: true },
43369
+ actualWithdrawAmount,
43370
+ withdrawBank.mintDecimals
43371
+ );
43358
43372
  const swapResult = [];
43359
43373
  const cuRequestIxs = [
43360
43374
  web3_js.ComputeBudgetProgram.setComputeUnitLimit({ units: 12e5 }),
@@ -43371,7 +43385,7 @@ async function buildSwapCollateralFlashloanTx({
43371
43385
  withdrawOpts.withdrawBank.tokenSymbol
43372
43386
  );
43373
43387
  }
43374
- const adjustedAmount = new BigNumber10.BigNumber(totalPositionAmount).div(withdrawOpts.withdrawBank.assetShareValue).times(1.0001).toNumber();
43388
+ const adjustedAmount = new BigNumber10.BigNumber(actualWithdrawAmount).div(withdrawOpts.withdrawBank.assetShareValue).times(1.0001).toNumber();
43375
43389
  withdrawIxs = await makeKaminoWithdrawIx3({
43376
43390
  program,
43377
43391
  bank: withdrawBank,
@@ -43381,7 +43395,7 @@ async function buildSwapCollateralFlashloanTx({
43381
43395
  marginfiAccount,
43382
43396
  authority: marginfiAccount.authority,
43383
43397
  reserve,
43384
- withdrawAll: true,
43398
+ withdrawAll: isFullWithdraw,
43385
43399
  isSync: true,
43386
43400
  opts: {
43387
43401
  createAtas: false,
@@ -43405,12 +43419,12 @@ async function buildSwapCollateralFlashloanTx({
43405
43419
  bank: withdrawOpts.withdrawBank,
43406
43420
  bankMap,
43407
43421
  tokenProgram: withdrawOpts.tokenProgram,
43408
- amount: totalPositionAmount,
43422
+ amount: actualWithdrawAmount,
43409
43423
  marginfiAccount,
43410
43424
  authority: marginfiAccount.authority,
43411
43425
  driftSpotMarket: driftState.spotMarketState,
43412
43426
  userRewards: driftState.userRewards,
43413
- withdrawAll: true,
43427
+ withdrawAll: isFullWithdraw,
43414
43428
  isSync: false,
43415
43429
  opts: {
43416
43430
  createAtas: false,
@@ -43426,10 +43440,10 @@ async function buildSwapCollateralFlashloanTx({
43426
43440
  bank: withdrawBank,
43427
43441
  bankMap,
43428
43442
  tokenProgram: withdrawTokenProgram,
43429
- amount: totalPositionAmount,
43443
+ amount: actualWithdrawAmount,
43430
43444
  marginfiAccount,
43431
43445
  authority: marginfiAccount.authority,
43432
- withdrawAll: true,
43446
+ withdrawAll: isFullWithdraw,
43433
43447
  isSync: true,
43434
43448
  opts: {
43435
43449
  createAtas: false,
@@ -43442,7 +43456,7 @@ async function buildSwapCollateralFlashloanTx({
43442
43456
  }
43443
43457
  if (depositBank.mint.equals(withdrawBank.mint)) {
43444
43458
  swapResult.push({
43445
- amountToDeposit: totalPositionAmount,
43459
+ amountToDeposit: actualWithdrawAmount,
43446
43460
  swapInstructions: [],
43447
43461
  setupInstructions: [],
43448
43462
  swapLookupTables: []
@@ -43458,7 +43472,7 @@ async function buildSwapCollateralFlashloanTx({
43458
43472
  quoteParams: {
43459
43473
  inputMint: withdrawBank.mint.toBase58(),
43460
43474
  outputMint: depositBank.mint.toBase58(),
43461
- amount: uiToNative(totalPositionAmount, withdrawBank.mintDecimals).toNumber(),
43475
+ amount: uiToNative(actualWithdrawAmount, withdrawBank.mintDecimals).toNumber(),
43462
43476
  dynamicSlippage: swapOpts.jupiterOptions ? swapOpts.jupiterOptions.slippageMode === "DYNAMIC" : true,
43463
43477
  slippageBps: swapOpts.jupiterOptions?.slippageBps,
43464
43478
  swapMode: "ExactIn",
@@ -43725,56 +43739,74 @@ async function buildSwapDebtFlashloanTx({
43725
43739
  overrideInferAccounts,
43726
43740
  blockhash
43727
43741
  }) {
43728
- const { repayBank, tokenProgram: repayTokenProgram, totalPositionAmount } = repayOpts;
43742
+ const {
43743
+ repayBank,
43744
+ tokenProgram: repayTokenProgram,
43745
+ totalPositionAmount,
43746
+ repayAmount
43747
+ } = repayOpts;
43729
43748
  const { borrowBank, tokenProgram: borrowTokenProgram } = borrowOpts;
43749
+ if (repayAmount !== void 0 && repayAmount <= 0) {
43750
+ throw new Error("repayAmount must be greater than 0");
43751
+ }
43752
+ const actualRepayAmount = Math.min(repayAmount ?? totalPositionAmount, totalPositionAmount);
43730
43753
  const swapResult = [];
43731
43754
  const cuRequestIxs = [
43732
43755
  web3_js.ComputeBudgetProgram.setComputeUnitLimit({ units: 12e5 }),
43733
43756
  web3_js.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 })
43734
43757
  ];
43735
- if (borrowBank.mint.equals(repayBank.mint)) {
43736
- swapResult.push({
43737
- amountToRepay: totalPositionAmount,
43738
- borrowAmount: totalPositionAmount,
43739
- swapInstructions: [],
43740
- setupInstructions: [],
43741
- swapLookupTables: []
43742
- });
43743
- } else {
43744
- const destinationTokenAccount = getAssociatedTokenAddressSync(
43745
- repayBank.mint,
43746
- marginfiAccount.authority,
43747
- true,
43748
- repayTokenProgram.equals(TOKEN_2022_PROGRAM_ID) ? TOKEN_2022_PROGRAM_ID : void 0
43758
+ const destinationTokenAccount = getAssociatedTokenAddressSync(
43759
+ repayBank.mint,
43760
+ marginfiAccount.authority,
43761
+ true,
43762
+ repayTokenProgram.equals(TOKEN_2022_PROGRAM_ID) ? TOKEN_2022_PROGRAM_ID : void 0
43763
+ );
43764
+ const jupiterApiClient = swapOpts.jupiterOptions?.configParams?.basePath ? new api.SwapApi(new api.Configuration(swapOpts.jupiterOptions.configParams)) : api.createJupiterApiClient(swapOpts.jupiterOptions?.configParams);
43765
+ const estimateQuote = await jupiterApiClient.quoteGet({
43766
+ inputMint: borrowBank.mint.toBase58(),
43767
+ outputMint: repayBank.mint.toBase58(),
43768
+ amount: uiToNative(actualRepayAmount, repayBank.mintDecimals).toNumber(),
43769
+ swapMode: "ExactOut",
43770
+ dynamicSlippage: swapOpts.jupiterOptions ? swapOpts.jupiterOptions.slippageMode === "DYNAMIC" : true,
43771
+ slippageBps: swapOpts.jupiterOptions?.slippageBps
43772
+ });
43773
+ const estimatedBorrowAmount = nativeToUi(
43774
+ estimateQuote.otherAmountThreshold,
43775
+ borrowBank.mintDecimals
43776
+ );
43777
+ const swapResponses = await getJupiterSwapIxsForFlashloan({
43778
+ quoteParams: {
43779
+ inputMint: borrowBank.mint.toBase58(),
43780
+ outputMint: repayBank.mint.toBase58(),
43781
+ amount: uiToNative(estimatedBorrowAmount, borrowBank.mintDecimals).toNumber(),
43782
+ dynamicSlippage: swapOpts.jupiterOptions ? swapOpts.jupiterOptions.slippageMode === "DYNAMIC" : true,
43783
+ slippageBps: swapOpts.jupiterOptions?.slippageBps,
43784
+ swapMode: "ExactIn",
43785
+ platformFeeBps: swapOpts.jupiterOptions?.platformFeeBps,
43786
+ onlyDirectRoutes: swapOpts.jupiterOptions?.directRoutesOnly ?? false
43787
+ },
43788
+ authority: marginfiAccount.authority,
43789
+ connection,
43790
+ destinationTokenAccount,
43791
+ configParams: swapOpts.jupiterOptions?.configParams
43792
+ });
43793
+ swapResponses.forEach((response) => {
43794
+ const outAmount = nativeToUi(response.quoteResponse.outAmount, repayBank.mintDecimals);
43795
+ const outAmountThreshold = nativeToUi(
43796
+ response.quoteResponse.otherAmountThreshold,
43797
+ repayBank.mintDecimals
43749
43798
  );
43750
- const swapResponses = await getJupiterSwapIxsForFlashloan({
43751
- quoteParams: {
43752
- inputMint: borrowBank.mint.toBase58(),
43753
- outputMint: repayBank.mint.toBase58(),
43754
- amount: uiToNative(totalPositionAmount, repayBank.mintDecimals).toNumber(),
43755
- dynamicSlippage: swapOpts.jupiterOptions ? swapOpts.jupiterOptions.slippageMode === "DYNAMIC" : true,
43756
- slippageBps: swapOpts.jupiterOptions?.slippageBps,
43757
- swapMode: "ExactOut",
43758
- platformFeeBps: swapOpts.jupiterOptions?.platformFeeBps,
43759
- onlyDirectRoutes: swapOpts.jupiterOptions?.directRoutesOnly ?? false
43760
- },
43761
- authority: marginfiAccount.authority,
43762
- connection,
43763
- destinationTokenAccount,
43764
- configParams: swapOpts.jupiterOptions?.configParams
43765
- });
43766
- swapResponses.forEach((response) => {
43767
- const borrowAmount = nativeToUi(response.quoteResponse.inAmount, borrowBank.mintDecimals);
43768
- swapResult.push({
43769
- amountToRepay: totalPositionAmount,
43770
- borrowAmount,
43771
- swapInstructions: [response.swapInstruction],
43772
- setupInstructions: response.setupInstructions,
43773
- swapLookupTables: response.addressLookupTableAddresses,
43774
- quoteResponse: response.quoteResponse
43775
- });
43799
+ const amountToRepay = outAmount > totalPositionAmount ? totalPositionAmount : outAmountThreshold;
43800
+ const borrowAmount = nativeToUi(response.quoteResponse.inAmount, borrowBank.mintDecimals);
43801
+ swapResult.push({
43802
+ amountToRepay,
43803
+ borrowAmount,
43804
+ swapInstructions: [response.swapInstruction],
43805
+ setupInstructions: response.setupInstructions,
43806
+ swapLookupTables: response.addressLookupTableAddresses,
43807
+ quoteResponse: response.quoteResponse
43776
43808
  });
43777
- }
43809
+ });
43778
43810
  if (swapResult.length === 0) {
43779
43811
  throw new Error(
43780
43812
  `No swap routes found for ${borrowBank.mint.toBase58()} -> ${repayBank.mint.toBase58()}`
@@ -44748,7 +44780,9 @@ async function computeSmartCrank({
44748
44780
  };
44749
44781
  }
44750
44782
  async function makeSmartCrankSwbFeedIx(params) {
44783
+ console.log("[makeSmartCrankSwbFeedIx] Called");
44751
44784
  const crankResult = await computeSmartCrank(params);
44785
+ console.log("[makeSmartCrankSwbFeedIx] Crank result:", crankResult);
44752
44786
  if (crankResult.uncrankableLiabilities.length > 0) {
44753
44787
  console.log(
44754
44788
  "Uncrankable liability details:",
@@ -44784,6 +44818,7 @@ async function makeSmartCrankSwbFeedIx(params) {
44784
44818
  );
44785
44819
  }
44786
44820
  const oraclesToCrank = crankResult.requiredOracles;
44821
+ console.log("[makeSmartCrankSwbFeedIx] Oracles to crank:", oraclesToCrank);
44787
44822
  const { instructions: instructions2, luts } = await makeUpdateSwbFeedIx({
44788
44823
  swbPullOracles: oraclesToCrank,
44789
44824
  feePayer: params.marginfiAccount.authority,
@@ -44820,6 +44855,9 @@ async function makeCrankSwbFeedIx(marginfiAccount, bankMap, newBanksPk, provider
44820
44855
  }
44821
44856
  }
44822
44857
  async function makeUpdateSwbFeedIx(props) {
44858
+ console.log(
44859
+ `[makeUpdateSwbFeedIx] Called with ${props.swbPullOracles.length} oracles, feePayer: ${props.feePayer.toBase58()}`
44860
+ );
44823
44861
  const seen = /* @__PURE__ */ new Set();
44824
44862
  const uniqueOracles = props.swbPullOracles.filter((oracle) => {
44825
44863
  const key = oracle.key.toBase58();
@@ -44827,6 +44865,14 @@ async function makeUpdateSwbFeedIx(props) {
44827
44865
  seen.add(key);
44828
44866
  return true;
44829
44867
  });
44868
+ console.log(
44869
+ `[makeUpdateSwbFeedIx] ${uniqueOracles.length} unique oracles after dedup (removed ${props.swbPullOracles.length - uniqueOracles.length})`
44870
+ );
44871
+ uniqueOracles.forEach(
44872
+ (o) => console.log(
44873
+ `[makeUpdateSwbFeedIx] - ${o.key.toBase58()} (hasSwitchboardData: ${!!o.price?.switchboardData})`
44874
+ )
44875
+ );
44830
44876
  const swbProgram = await onDemand.AnchorUtils.loadProgramFromConnection(props.connection);
44831
44877
  const pullFeedInstances = uniqueOracles.map((oracle) => {
44832
44878
  const pullFeed = new onDemand.PullFeed(swbProgram, oracle.key);
@@ -44842,6 +44888,7 @@ async function makeUpdateSwbFeedIx(props) {
44842
44888
  return pullFeed;
44843
44889
  });
44844
44890
  if (pullFeedInstances.length === 0) {
44891
+ console.log(`[makeUpdateSwbFeedIx] No pull feed instances, returning early`);
44845
44892
  return { instructions: [], luts: [] };
44846
44893
  }
44847
44894
  const crossbarClient = new common.CrossbarClient(
@@ -44851,11 +44898,19 @@ async function makeUpdateSwbFeedIx(props) {
44851
44898
  if (!gatewayUrls || gatewayUrls.length === 0) {
44852
44899
  throw new Error(`No gateways available for mainnet`);
44853
44900
  }
44901
+ console.log(`[makeUpdateSwbFeedIx] Fetched ${gatewayUrls.length} gateways`);
44854
44902
  const gatewayUrl = gatewayUrls[0];
44855
44903
  if (!gatewayUrl) {
44856
44904
  throw new Error(`Invalid gateway URL received formainnet`);
44857
44905
  }
44858
44906
  const gateway = new onDemand.Gateway(swbProgram, gatewayUrl);
44907
+ console.log(
44908
+ `[makeUpdateSwbFeedIx] Fetching update ix for ${pullFeedInstances.length} feeds via gateway: ${gateway.gatewayUrl}`
44909
+ );
44910
+ console.log(
44911
+ `[makeUpdateSwbFeedIx] pullFeedInstances:`,
44912
+ pullFeedInstances.map((f) => ({ key: f.pubkey.toBase58(), hasData: !!f.data }))
44913
+ );
44859
44914
  const [pullIx, luts] = await onDemand.PullFeed.fetchUpdateManyIx(swbProgram, {
44860
44915
  feeds: pullFeedInstances,
44861
44916
  gateway: gateway.gatewayUrl,
@@ -44863,6 +44918,7 @@ async function makeUpdateSwbFeedIx(props) {
44863
44918
  payer: props.feePayer,
44864
44919
  crossbarClient
44865
44920
  });
44921
+ console.log(`[makeUpdateSwbFeedIx] Got ${pullIx.length} instructions, ${luts.length} LUTs`);
44866
44922
  return { instructions: pullIx, luts };
44867
44923
  }
44868
44924