Skip to content

Commit

Permalink
prettify/lint
Browse files Browse the repository at this point in the history
  • Loading branch information
crispheaney committed Jan 2, 2025
1 parent 98cd907 commit aabf9c7
Show file tree
Hide file tree
Showing 2 changed files with 130 additions and 162 deletions.
182 changes: 94 additions & 88 deletions sdk/src/driftClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7363,70 +7363,76 @@ export class DriftClient {
* @param userAccountPublicKey
* @param userStatsAccountPublicKey
*/
public async getLiquidateSpotWithSwapIx({
liabilityMarketIndex,
assetMarketIndex,
swapAmount: swapAmount,
assetTokenAccount,
liabilityTokenAccount,
userAccount,
userAccountPublicKey,
userStatsAccountPublicKey,
liquidatorSubAccountId,
}: {
liabilityMarketIndex: number;
assetMarketIndex: number;
swapAmount: BN;
assetTokenAccount: PublicKey;
liabilityTokenAccount: PublicKey;
userAccount: UserAccount;
userAccountPublicKey: PublicKey;
userStatsAccountPublicKey: PublicKey;
liquidatorSubAccountId?: number;
}): Promise<{
beginSwapIx: TransactionInstruction;
endSwapIx: TransactionInstruction;
}> {
const liquidatorAccountPublicKey = await this.getUserAccountPublicKey(
liquidatorSubAccountId
);
const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
public async getLiquidateSpotWithSwapIx({
liabilityMarketIndex,
assetMarketIndex,
swapAmount: swapAmount,
assetTokenAccount,
liabilityTokenAccount,
userAccount,
userAccountPublicKey,
userStatsAccountPublicKey,
liquidatorSubAccountId,
}: {
liabilityMarketIndex: number;
assetMarketIndex: number;
swapAmount: BN;
assetTokenAccount: PublicKey;
liabilityTokenAccount: PublicKey;
userAccount: UserAccount;
userAccountPublicKey: PublicKey;
userStatsAccountPublicKey: PublicKey;
liquidatorSubAccountId?: number;
}): Promise<{
beginSwapIx: TransactionInstruction;
endSwapIx: TransactionInstruction;
}> {
const liquidatorAccountPublicKey = await this.getUserAccountPublicKey(
liquidatorSubAccountId
);
const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();

const userAccounts = [userAccount];
const remainingAccounts = this.getRemainingAccounts({
userAccounts,
writableSpotMarketIndexes: [liabilityMarketIndex, assetMarketIndex],
readableSpotMarketIndexes: [QUOTE_SPOT_MARKET_INDEX],
});

const userAccounts = [userAccount];
const remainingAccounts = this.getRemainingAccounts({
userAccounts,
writableSpotMarketIndexes: [liabilityMarketIndex, assetMarketIndex],
readableSpotMarketIndexes: [QUOTE_SPOT_MARKET_INDEX],
const liabilitySpotMarket = this.getSpotMarketAccount(liabilityMarketIndex);
const assetSpotMarket = this.getSpotMarketAccount(assetMarketIndex);

const liabilityTokenProgram =
this.getTokenProgramForSpotMarket(liabilitySpotMarket);
const assetTokenProgram =
this.getTokenProgramForSpotMarket(assetSpotMarket);

if (!liabilityTokenProgram.equals(assetTokenProgram)) {
remainingAccounts.push({
pubkey: liabilityTokenProgram,
isWritable: false,
isSigner: false,
});

const liabilitySpotMarket = this.getSpotMarketAccount(liabilityMarketIndex);
const assetSpotMarket = this.getSpotMarketAccount(assetMarketIndex);

const liabilityTokenProgram = this.getTokenProgramForSpotMarket(liabilitySpotMarket);
const assetTokenProgram = this.getTokenProgramForSpotMarket(assetSpotMarket);

if (!liabilityTokenProgram.equals(assetTokenProgram)) {
remainingAccounts.push({
pubkey: liabilityTokenProgram,
isWritable: false,
isSigner: false,
});
}

if (liabilitySpotMarket.tokenProgram === 1 || assetSpotMarket.tokenProgram === 1) {
remainingAccounts.push({
pubkey: assetSpotMarket.mint,
isWritable: false,
isSigner: false,
});
remainingAccounts.push({
pubkey: liabilitySpotMarket.mint,
isWritable: false,
isSigner: false,
});
}

const beginSwapIx = await this.program.instruction.liquidateSpotWithSwapBegin(
}

if (
liabilitySpotMarket.tokenProgram === 1 ||
assetSpotMarket.tokenProgram === 1
) {
remainingAccounts.push({
pubkey: assetSpotMarket.mint,
isWritable: false,
isSigner: false,
});
remainingAccounts.push({
pubkey: liabilitySpotMarket.mint,
isWritable: false,
isSigner: false,
});
}

const beginSwapIx =
await this.program.instruction.liquidateSpotWithSwapBegin(
assetMarketIndex,
liabilityMarketIndex,
swapAmount,
Expand All @@ -7449,32 +7455,32 @@ export class DriftClient {
remainingAccounts,
}
);
const endSwapIx = await this.program.instruction.liquidateSpotWithSwapEnd(
assetMarketIndex,
liabilityMarketIndex,
{
accounts: {
state: await this.getStatePublicKey(),
user: userAccountPublicKey,
userStats: userStatsAccountPublicKey,
liquidator: liquidatorAccountPublicKey,
liquidatorStats: liquidatorStatsPublicKey,
authority: this.wallet.publicKey,
liabilitySpotMarketVault: liabilitySpotMarket.vault,
assetSpotMarketVault: assetSpotMarket.vault,
assetTokenAccount: assetTokenAccount,
liabilityTokenAccount: liabilityTokenAccount,
tokenProgram: assetTokenProgram,
driftSigner: this.getStateAccount().signer,
instructions: anchor.web3.SYSVAR_INSTRUCTIONS_PUBKEY,
},
remainingAccounts,
}
);
return { beginSwapIx, endSwapIx };
}

const endSwapIx = await this.program.instruction.liquidateSpotWithSwapEnd(
assetMarketIndex,
liabilityMarketIndex,
{
accounts: {
state: await this.getStatePublicKey(),
user: userAccountPublicKey,
userStats: userStatsAccountPublicKey,
liquidator: liquidatorAccountPublicKey,
liquidatorStats: liquidatorStatsPublicKey,
authority: this.wallet.publicKey,
liabilitySpotMarketVault: liabilitySpotMarket.vault,
assetSpotMarketVault: assetSpotMarket.vault,
assetTokenAccount: assetTokenAccount,
liabilityTokenAccount: liabilityTokenAccount,
tokenProgram: assetTokenProgram,
driftSigner: this.getStateAccount().signer,
instructions: anchor.web3.SYSVAR_INSTRUCTIONS_PUBKEY,
},
remainingAccounts,
}
);

return { beginSwapIx, endSwapIx };
}

public async liquidateBorrowForPerpPnl(
userAccountPublicKey: PublicKey,
Expand Down
110 changes: 36 additions & 74 deletions tests/liquidateSpotWithSwap.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as anchor from '@coral-xyz/anchor';
import { assert } from 'chai';

import { Program } from '@coral-xyz/anchor';

Expand All @@ -18,14 +17,8 @@ import {
EventSubscriber,
OracleSource,
OracleInfo,
getTokenAmount,
SpotBalanceType,
ZERO,
getSerumSignerPublicKey,
QUOTE_PRECISION,
UserStatsAccount,
getUserStatsAccountPublicKey,
PERCENTAGE_PRECISION,
PERCENTAGE_PRECISION,
} from '../sdk/src';

import {
Expand All @@ -36,14 +29,13 @@ import {
mockOracleNoProgram,
mockUSDCMint,
mockUserUSDCAccount,
setFeedPriceNoProgram
setFeedPriceNoProgram,
} from './testHelpers';
import { NATIVE_MINT } from '@solana/spl-token';
import { DexInstructions, Market, OpenOrders } from '@project-serum/serum';
import { startAnchor } from 'solana-bankrun';
import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader';
import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection';
import { DRIFT_PROGRAM_ID } from '../sdk/src';

describe('spot swap', () => {
const chProgram = anchor.workspace.Drift as Program;
Expand Down Expand Up @@ -71,19 +63,17 @@ describe('spot swap', () => {
const usdcAmount = new BN(200 * 10 ** 6).muln(10);
const solAmount = new BN(10 * 10 ** 9).muln(10);

const takerUsdcDepositAmount = new BN(10 ** 6).muln(200);
const takerSolDepositAmount = new BN(10 ** 9).muln(2);
const makerUsdcDepositAmount = new BN(10 ** 6).muln(200);
const makerSolWithdrawAmount = new BN(10 ** 9).muln(1);
const takerUsdcDepositAmount = new BN(10 ** 6).muln(200);
const takerSolDepositAmount = new BN(10 ** 9).muln(2);
const makerUsdcDepositAmount = new BN(10 ** 6).muln(200);
const makerSolWithdrawAmount = new BN(10 ** 9).muln(1);

let marketIndexes: number[];
let spotMarketIndexes: number[];
let oracleInfos: OracleInfo[];

const solSpotMarketIndex = 1;

let openOrdersAccount: PublicKey;

let takerKeypair: Keypair;

before(async () => {
Expand Down Expand Up @@ -156,8 +146,9 @@ describe('spot swap', () => {
await makerDriftClient.subscribe();
await makerDriftClient.initializeUserAccount();

const oracleGuardrails = await makerDriftClient.getStateAccount().oracleGuardRails;
oracleGuardrails.validity.tooVolatileRatio = new BN(10000);
const oracleGuardrails = await makerDriftClient.getStateAccount()
.oracleGuardRails;
oracleGuardrails.validity.tooVolatileRatio = new BN(10000);
oracleGuardrails.priceDivergence.oracleTwap5MinPercentDivergence = new BN(
100
).mul(PERCENTAGE_PRECISION);
Expand Down Expand Up @@ -197,13 +188,17 @@ describe('spot swap', () => {
);
await takerDriftClient.deposit(takerUsdcDepositAmount, 0, takerUSDC);

await takerDriftClient.deposit(takerSolDepositAmount, 1, takerWSOL);
await takerDriftClient.deposit(takerSolDepositAmount, 1, takerWSOL);

await makerDriftClient.deposit(makerUsdcDepositAmount, 0, makerUSDC.publicKey);
await makerDriftClient.deposit(
makerUsdcDepositAmount,
0,
makerUSDC.publicKey
);

await makerDriftClient.withdraw(makerSolWithdrawAmount, 1, makerWSOL);
await makerDriftClient.withdraw(makerSolWithdrawAmount, 1, makerWSOL);

await setFeedPriceNoProgram(bankrunContextWrapper, 200, solOracle);
await setFeedPriceNoProgram(bankrunContextWrapper, 200, solOracle);
});

after(async () => {
Expand Down Expand Up @@ -270,43 +265,6 @@ describe('spot swap', () => {
takerOpenOrders = openOrdersAccount.publicKey;
});

const crankMarkets = async () => {
const openOrdersAccounts = [];

const market = await Market.load(
bankrunContextWrapper.connection.toConnection(),
serumMarketPublicKey,
{ commitment: 'processed' },
SERUM
);

openOrdersAccounts.push(openOrdersAccount);

const serumFulfillmentConfigAccount =
await makerDriftClient.getSerumV3FulfillmentConfig(serumMarketPublicKey);
openOrdersAccounts.push(serumFulfillmentConfigAccount.serumOpenOrders);

const consumeEventsIx = await market.makeConsumeEventsInstruction(
openOrdersAccounts,
10
);

const consumeEventsTx = new Transaction().add(consumeEventsIx);
await bankrunContextWrapper.sendTransaction(consumeEventsTx);
// await provider.sendAndConfirm(consumeEventsTx, []);

// Open orders need to be sorted correctly but not sure how to do it in js, so will run this
// ix sorted in both direction
const consumeEventsIx2 = await market.makeConsumeEventsInstruction(
openOrdersAccounts.reverse(),
10
);

const consumeEventsTx2 = new Transaction().add(consumeEventsIx2);
await bankrunContextWrapper.sendTransaction(consumeEventsTx2);
// await provider.sendAndConfirm(consumeEventsTx2, []);
};

it('swap usdc for sol', async () => {
const market = await Market.load(
bankrunContextWrapper.connection.toConnection(),
Expand Down Expand Up @@ -336,25 +294,25 @@ describe('spot swap', () => {
}
);

openOrdersAccount = signers[0].publicKey;

const signerKeypairs = signers.map((signer) => {
return Keypair.fromSecretKey(signer.secretKey);
});

await bankrunContextWrapper.sendTransaction(transaction, signerKeypairs);

const amountIn = makerUsdcDepositAmount;
const { beginSwapIx, endSwapIx } = await takerDriftClient.getLiquidateSpotWithSwapIx({
swapAmount: amountIn,
assetMarketIndex: 0,
liabilityMarketIndex: 1,
assetTokenAccount: takerUSDC,
liabilityTokenAccount: takerWSOL,
userAccount: makerDriftClient.getUserAccount(),
userAccountPublicKey: await makerDriftClient.getUserAccountPublicKey(),
userStatsAccountPublicKey: makerDriftClient.getUserStatsAccountPublicKey(),
});
const { beginSwapIx, endSwapIx } =
await takerDriftClient.getLiquidateSpotWithSwapIx({
swapAmount: amountIn,
assetMarketIndex: 0,
liabilityMarketIndex: 1,
assetTokenAccount: takerUSDC,
liabilityTokenAccount: takerWSOL,
userAccount: makerDriftClient.getUserAccount(),
userAccountPublicKey: await makerDriftClient.getUserAccountPublicKey(),
userStatsAccountPublicKey:
makerDriftClient.getUserStatsAccountPublicKey(),
});

// @ts-ignore
const serumBidIx = await market.makePlaceOrderInstruction(
Expand Down Expand Up @@ -401,10 +359,14 @@ describe('spot swap', () => {
.add(settleFundsIx)
.add(endSwapIx);

const { txSig } = await takerDriftClient.sendTransaction(tx);
await takerDriftClient.sendTransaction(tx);

await makerDriftClient.fetchAccounts();
await makerDriftClient.fetchAccounts();

console.log('maker is being liquidated', makerDriftClient.getUser().isBeingLiquidated(), makerDriftClient.getUserAccount().status);
console.log(
'maker is being liquidated',
makerDriftClient.getUser().isBeingLiquidated(),
makerDriftClient.getUserAccount().status
);
});
});

0 comments on commit aabf9c7

Please sign in to comment.