Skip to content

Commit

Permalink
everything but one local val test
Browse files Browse the repository at this point in the history
  • Loading branch information
NourAlharithi committed Dec 26, 2024
1 parent 8c2bc38 commit 4d07edd
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 195 deletions.
2 changes: 1 addition & 1 deletion Anchor.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ exclude = ["programs/openbook_v2"]

[scripts]
# to run local validator tests, use "./test-scripts/run-ts-mocha" in "test"
test = "echo" # need to call anchor test to update metadata field in idl before running tests, so just do a noop
test = "./test-scripts/run-ts-mocha" # need to call anchor test to update metadata field in idl before running tests, so just do a noop
lint = "yarn prettify:fix && cargo fmt"
fulltest = 'cargo test && bash ./test-scripts/run-anchor-tests.sh'
watch_ts = 'find ./programs/clearing_house/src/* ./tests ./sdk/src | entr -c bash ./test-scripts/single-anchor-test.sh'
Expand Down
6 changes: 1 addition & 5 deletions sdk/src/driftClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,6 @@ import pythSolanaReceiverIdl from './idl/pyth_solana_receiver.json';
import { asV0Tx, PullFeed } from '@switchboard-xyz/on-demand';
import { gprcDriftClientAccountSubscriber } from './accounts/grpcDriftClientAccountSubscriber';
import nacl from 'tweetnacl';
import { digest } from './util/digest';
import { Slothash } from './slot/SlothashSubscriber';
import { getOracleId } from './oracles/oracleId';

Expand Down Expand Up @@ -5886,9 +5885,7 @@ export class DriftClient {
): Buffer {
const takerOrderParamsMessage =
this.encodeSwiftOrderParamsMessage(orderParamsMessage);
return this.signMessage(
new TextEncoder().encode(digest(takerOrderParamsMessage).toString('hex'))
);
return this.signMessage(takerOrderParamsMessage);
}

public encodeSwiftOrderParamsMessage(
Expand Down Expand Up @@ -8974,7 +8971,6 @@ export class DriftClient {
preSigned?: boolean
): Promise<TxSigAndSlot> {
const isVersionedTx = this.isVersionedTransaction(tx);

if (isVersionedTx) {
return this.txSender.sendVersionedTransaction(
tx as VersionedTransaction,
Expand Down
2 changes: 1 addition & 1 deletion test-scripts/run-anchor-local-validator-tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ fi
export ANCHOR_WALLET=~/.config/solana/id.json

test_files=(
pythLazer.ts
# pythLazer.ts
placeAndMakeSwiftPerp.ts
)

Expand Down
223 changes: 41 additions & 182 deletions tests/placeAndMakeSwiftPerp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { Program } from '@coral-xyz/anchor';
import {
ComputeBudgetProgram,
Keypair,
SendTransactionError,
Transaction,
TransactionMessage,
VersionedTransaction,
Expand Down Expand Up @@ -102,10 +101,11 @@ describe('place and make swift order', () => {
spotMarketIndexes = [0, 1];
oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }];

const wallet = new Wallet(loadKeypair(process.env.ANCHOR_WALLET));
makerDriftClient = new TestClient({
connection,
//@ts-ignore
wallet: new Wallet(loadKeypair(process.env.ANCHOR_WALLET)),
wallet,
programID: chProgram.programId,
opts: {
commitment: 'confirmed',
Expand All @@ -118,6 +118,7 @@ describe('place and make swift order', () => {
type: 'polling',
accountLoader: bulkAccountLoader,
},
txVersion: 'legacy',
});
await makerDriftClient.initialize(usdcMint.publicKey, true);
await makerDriftClient.subscribe();
Expand Down Expand Up @@ -244,23 +245,27 @@ describe('place and make swift order', () => {
takerOrderParamsMessage
);

let ixs = await makerDriftClient.getPlaceAndMakeSwiftPerpOrderIxs(
takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage),
takerOrderParamsSig,
uuid,
{
taker: await takerDriftClient.getUserAccountPublicKey(),
takerUserAccount: takerDriftClient.getUserAccount(),
takerStats: takerDriftClient.getUserStatsAccountPublicKey(),
},
makerOrderParams
);
ixs = [
const ixs = [
ComputeBudgetProgram.setComputeUnitLimit({
units: 10_000_000,
}),
...ixs,
];
ixs.push(
...(await makerDriftClient.getPlaceAndMakeSwiftPerpOrderIxs(
takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage),
takerOrderParamsSig,
uuid,
{
taker: await takerDriftClient.getUserAccountPublicKey(),
takerUserAccount: takerDriftClient.getUserAccount(),
takerStats: takerDriftClient.getUserStatsAccountPublicKey(),
},
makerOrderParams,
undefined,
undefined,
ixs
))
);

const message = new TransactionMessage({
instructions: ixs,
Expand Down Expand Up @@ -363,24 +368,31 @@ describe('place and make swift order', () => {
);

try {
let ixs = await makerDriftClient.getPlaceAndMakeSwiftPerpOrderIxs(
takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage),
takerOrderParamsSig,
uuid,
{
taker: await takerDriftClient.getUserAccountPublicKey(),
takerUserAccount: takerDriftClient.getUserAccount(),
takerStats: takerDriftClient.getUserStatsAccountPublicKey(),
},
makerOrderParams
);
ixs = [
const ixs = [
ComputeBudgetProgram.setComputeUnitLimit({
units: 10_000_000,
}),
...ixs,
];
await makerDriftClient.sendTransaction(new Transaction().add(...ixs));
ixs.push(
...(await makerDriftClient.getPlaceAndMakeSwiftPerpOrderIxs(
takerDriftClient.encodeSwiftOrderParamsMessage(
takerOrderParamsMessage
),
takerOrderParamsSig,
uuid,
{
taker: await takerDriftClient.getUserAccountPublicKey(),
takerUserAccount: takerDriftClient.getUserAccount(),
takerStats: takerDriftClient.getUserStatsAccountPublicKey(),
},
makerOrderParams,
undefined,
undefined,
ixs
))
);
const tx = new Transaction().add(...ixs);
await makerDriftClient.sendTransaction(tx);
assert.fail('Should have failed');
} catch (error) {
assert.equal(
Expand All @@ -389,157 +401,4 @@ describe('place and make swift order', () => {
);
}
});

it('should fail if diff signed message to verify ixs vs drift ixs', async () => {
const keypair = new Keypair();
await provider.connection.requestAirdrop(keypair.publicKey, 10 ** 9);
await sleep(1000);
const wallet = new Wallet(keypair);
const userUSDCAccount = await mockUserUSDCAccount(
usdcMint,
usdcAmount,
provider,
keypair.publicKey
);
const takerDriftClient = new TestClient({
connection,
wallet,
programID: chProgram.programId,
opts: {
commitment: 'confirmed',
},
activeSubAccountId: 0,
perpMarketIndexes: marketIndexes,
spotMarketIndexes: spotMarketIndexes,
oracleInfos,
userStats: true,
accountSubscription: {
type: 'polling',
accountLoader: bulkAccountLoader,
},
});

await takerDriftClient.subscribe();
await takerDriftClient.initializeUserAccountAndDepositCollateral(
usdcAmount,
userUSDCAccount.publicKey
);

const takerDriftClientUser = new User({
driftClient: takerDriftClient,
userAccountPublicKey: await takerDriftClient.getUserAccountPublicKey(),
accountSubscription: {
type: 'polling',
accountLoader: bulkAccountLoader,
},
});
await takerDriftClientUser.subscribe();
await takerDriftClient.initializeSwiftUserOrders(
takerDriftClientUser.userAccountPublicKey,
32
);

const marketIndex = 0;
const baseAssetAmount = BASE_PRECISION;
const takerOrderParams = getMarketOrderParams({
marketIndex,
direction: PositionDirection.LONG,
baseAssetAmount: baseAssetAmount.muln(2),
price: new BN(34).mul(PRICE_PRECISION),
auctionStartPrice: new BN(33).mul(PRICE_PRECISION),
auctionEndPrice: new BN(34).mul(PRICE_PRECISION),
auctionDuration: 10,
userOrderId: 1,
postOnly: PostOnlyParams.NONE,
marketType: MarketType.PERP,
});
const takerOrderParamsMessage: SwiftOrderParamsMessage = {
swiftOrderParams: takerOrderParams,
subAccountId: 0,
uuid: Uint8Array.from(Buffer.from(nanoid(8))),
slot: new BN(await connection.getSlot()),
takeProfitOrderParams: null,
stopLossOrderParams: null,
};

await takerDriftClientUser.fetchAccounts();

// Auth for legit order
const takerOrderParamsSig = takerDriftClient.signSwiftOrderParamsMessage(
takerOrderParamsMessage
);

// Auth for non-legit order
const takerOrderParamsMessage2: SwiftOrderParamsMessage = {
swiftOrderParams: Object.assign({}, takerOrderParams, {
direction: PositionDirection.SHORT,
auctionStartPrice: new BN(34).mul(PRICE_PRECISION),
auctionEndPrice: new BN(33).mul(PRICE_PRECISION),
price: new BN(33).mul(PRICE_PRECISION),
}),
subAccountId: 0,
takeProfitOrderParams: null,
stopLossOrderParams: null,
uuid: Uint8Array.from(Buffer.from(nanoid(8))),
slot: new BN(await connection.getSlot()),
};

const takerOrderParamsSig2 = takerDriftClient.signSwiftOrderParamsMessage(
takerOrderParamsMessage2
);

const computeBudgetIx = ComputeBudgetProgram.setComputeUnitLimit({
units: 10_000_000,
});

const ixs = await makerDriftClient.getPlaceSwiftTakerPerpOrderIxs(
takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage),
takerOrderParamsSig,
0,
{
taker: await takerDriftClient.getUserAccountPublicKey(),
takerUserAccount: takerDriftClient.getUserAccount(),
takerStats: takerDriftClient.getUserStatsAccountPublicKey(),
}
);

const ixsForOrder2 = await makerDriftClient.getPlaceSwiftTakerPerpOrderIxs(
takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage2),
takerOrderParamsSig2,
0,
{
taker: await takerDriftClient.getUserAccountPublicKey(),
takerUserAccount: takerDriftClient.getUserAccount(),
takerStats: takerDriftClient.getUserStatsAccountPublicKey(),
}
);

const badOrderTx = new Transaction();
badOrderTx.add(...[computeBudgetIx, ixs[0], ixsForOrder2[1]]);
try {
await makerDriftClient.sendTransaction(badOrderTx);
assert.fail('Should have failed');
} catch (error) {
console.log((error as SendTransactionError).logs);
assert(
(error as SendTransactionError).logs.some((log) =>
log.includes('SigVerificationFailed')
)
);
}

const badSwiftTx = new Transaction();
badSwiftTx.add(...[computeBudgetIx, ixsForOrder2[0], ixs[1]]);
try {
await makerDriftClient.sendTransaction(badSwiftTx);
assert.fail('Should have failed');
} catch (error) {
console.log((error as SendTransactionError).logs);
assert(
(error as SendTransactionError).logs.some((log) =>
log.includes('SigVerificationFailed')
)
);
}
});
});
32 changes: 26 additions & 6 deletions tests/placeAndMakeSwiftPerpBankrun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,11 @@ describe('place and make swift order', () => {
takerUserAccount: takerDriftClient.getUserAccount(),
takerStats: takerDriftClient.getUserStatsAccountPublicKey(),
},
makerOrderParams
makerOrderParams,
undefined,
undefined,
undefined,
2
);

/*
Expand Down Expand Up @@ -715,7 +719,12 @@ describe('place and make swift order', () => {
takerUserAccount: takerDriftClient.getUserAccount(),
takerStats: takerDriftClient.getUserStatsAccountPublicKey(),
},
makerOrderParams
makerOrderParams,
undefined,
undefined,
undefined,
undefined,
2
);
} catch (e) {
assert(e);
Expand Down Expand Up @@ -780,7 +789,9 @@ describe('place and make swift order', () => {
taker: await takerDriftClient.getUserAccountPublicKey(),
takerUserAccount: takerDriftClient.getUserAccount(),
takerStats: takerDriftClient.getUserStatsAccountPublicKey(),
}
},
undefined,
2
);

assert(takerDriftClient.getOrderByUserId(1) !== undefined);
Expand All @@ -803,7 +814,12 @@ describe('place and make swift order', () => {
takerUserAccount: takerDriftClient.getUserAccount(),
takerStats: takerDriftClient.getUserStatsAccountPublicKey(),
},
makerOrderParams
makerOrderParams,
undefined,
undefined,
undefined,
undefined,
2
);

const takerPosition = takerDriftClient.getUser().getPerpPosition(0);
Expand Down Expand Up @@ -863,7 +879,9 @@ describe('place and make swift order', () => {
taker: await takerDriftClient.getUserAccountPublicKey(),
takerUserAccount: takerDriftClient.getUserAccount(),
takerStats: takerDriftClient.getUserStatsAccountPublicKey(),
}
},
undefined,
2
);
assert.fail('Should have failed');
} catch (error) {
Expand Down Expand Up @@ -925,7 +943,9 @@ describe('place and make swift order', () => {
taker: await takerDriftClient.getUserAccountPublicKey(),
takerUserAccount: takerDriftClient.getUserAccount(),
takerStats: takerDriftClient.getUserStatsAccountPublicKey(),
}
},
undefined,
2
);

assert(
Expand Down

0 comments on commit 4d07edd

Please sign in to comment.