repo_id
stringclasses
563 values
file_path
stringlengths
40
166
content
stringlengths
1
2.94M
__index_level_0__
int64
0
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/tokenFaucet.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { TestClient, TokenFaucet } from '../sdk/src'; import { BN } from '../sdk'; import { Keypair, PublicKey } from '@solana/web3.js'; import { initializeQuoteSpotMarket, mockUSDCMint } from './testHelpers'; import { createAssociatedTokenAccountIdempotentInstruction, getAssociatedTokenAddressSync, unpackAccount, unpackMint, } from '@solana/spl-token'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('token faucet', () => { const program = anchor.workspace.TokenFaucet as Program; let tokenFaucet: TokenFaucet; let usdcMint: Keypair; const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; const amount = new BN(10 * 10 ** 6); before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, spotMarketIndexes: [], perpMarketIndexes: [], subAccountIds: [], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); usdcMint = await mockUSDCMint(bankrunContextWrapper); tokenFaucet = new TokenFaucet( bankrunContextWrapper.connection.toConnection(), bankrunContextWrapper.provider.wallet, program.programId, usdcMint.publicKey, undefined, bankrunContextWrapper ); }); after(async () => { await driftClient.unsubscribe(); }); it('Initialize State', async () => { await tokenFaucet.initialize(); const state: any = await tokenFaucet.fetchState(); assert.ok( state.admin.equals(bankrunContextWrapper.provider.wallet.publicKey) ); const [mintAuthority, mintAuthorityNonce] = await PublicKey.findProgramAddress( [ Buffer.from(anchor.utils.bytes.utf8.encode('mint_authority')), state.mint.toBuffer(), ], tokenFaucet.program.programId ); assert.ok(state.mintAuthority.equals(mintAuthority)); assert.ok(mintAuthorityNonce === state.mintAuthorityNonce); const mintInfoRaw = await bankrunContextWrapper.connection.getAccountInfo( tokenFaucet.mint ); const mintInfo = unpackMint(tokenFaucet.mint, mintInfoRaw); assert.ok(state.mintAuthority.equals(mintInfo.mintAuthority)); }); it('mint to user', async () => { const keyPair = new Keypair(); const ata = getAssociatedTokenAddressSync( tokenFaucet.mint, keyPair.publicKey ); const userTokenAccountIx = await createAssociatedTokenAccountIdempotentInstruction( bankrunContextWrapper.provider.wallet.publicKey, ata, keyPair.publicKey, tokenFaucet.mint ); await bankrunContextWrapper.sendTransaction( new anchor.web3.Transaction().add(userTokenAccountIx) ); let userTokenAccountInfoRaw = await bankrunContextWrapper.connection.getAccountInfo(ata); let userTokenAccountInfo = unpackAccount(ata, userTokenAccountInfoRaw); try { await tokenFaucet.mintToUser(userTokenAccountInfo.address, amount); } catch (e) { console.error(e); } userTokenAccountInfoRaw = await bankrunContextWrapper.connection.getAccountInfo(ata); userTokenAccountInfo = unpackAccount(ata, userTokenAccountInfoRaw); assert.ok(new BN(userTokenAccountInfo.amount.toString()).eq(amount)); }); it('initialize user for dev net', async () => { const state: any = await tokenFaucet.fetchState(); await driftClient.initialize(state.mint, false); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.initializeUserAccountForDevnet( 0, 'crisp', 0, tokenFaucet, amount ); assert(driftClient.getQuoteAssetTokenAmount().eq(amount)); }); it('transfer mint authority back', async () => { await tokenFaucet.transferMintAuthority(); const mintInfoRaw = await bankrunContextWrapper.connection.getAccountInfo( tokenFaucet.mint ); const mintInfo = unpackMint(tokenFaucet.mint, mintInfoRaw); assert.ok( bankrunContextWrapper.provider.wallet.publicKey.equals( mintInfo.mintAuthority ) ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/switchboardOnDemandData.ts
import { PublicKey } from '@solana/web3.js'; export const SB_ON_DEMAND_ACCOUNT_DATA = ''; export const PULL_FEED_ADDRESS = new PublicKey( 'EZLBfnznMYKjFmaWYMEdhwnkiQF1WiP9jjTY6M8HpmGE' ); export const PULL_FEED_ACCOUNT_DATA = 'xBtsxArX2yhvXnVmrAAKlTDlax20lYV3Jxmuqu6ttNm9jCNXuI6eeBTDmRAAAAAAAAAAAAAAAAAAjEqO4Us2LgkAAAAAAAAA4+UTCQLD6cJ5F3iXafGuBd4Vz1BGWL6v7tLFmKlJs7cUw5kQAAAAAAAAAAAAAAAAAIxKjuFLNi4JAAAAAAAAAOfvAk6nVvi+7C6qQCNAcNo1Z1So7rKsahfDLRfD6Z+NFMOZEAAAAAAAAAAAAAAAAACMSo7hSzYuCQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMvk0dDyZCl4A8z9IXIepPHoxrb5Yaa6GykmRSAPvuFthoBwaEMvGGoUfPCxOjAGfThiBOqdbIsEdDrC7wELB1JapKD9jPBdSUumh0cofC10oJxPpaEB37JhI68koBidk6q6mmYAAAAAAAAAAAAAAAAA8gUqAQAAAAEAAABTT0wvVVNEIFB5dGgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMA3JpmAAAAAKx5mRAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjEqO4Us2LgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACMSo7hSzYuCQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIxKjuFLNi4JAAAAAAAAAACMSo7hSzYuCQAAAAAAAAADAAAAAAAAABTDmRAAAAAAFMOZEAAAAAAUw5kQAAAAADIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=='; export const QUEUE_ADDRESS = new PublicKey( 'A43DyUGA7s8eXPxqEjJY6EBu1KKbNgfxF8h17VAHn13w' ); export const QUEUE_ACCOUNT_DATA = '2cI3f7hTigEd1I0O4f5wWbKGZQe4T19CWddAjIEuiL1iYKSRT3omBQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADn7wJOp1b4vuwuqkAjQHDaNWdUqO6yrGoXwy0Xw'; export const ORACLE_ADDRESS_1 = new PublicKey( 'GcNZRMqGSEyEULZnLDD3ParcHTgFBrNfUdUCDtThP55e' ); export const ORACLE_ADDRESS_1_DATA = 'gB4Q8apJNzZSJ8+YzqzzDQltMkvXMc1BRAVe8xbt0Fa1XZoDikelEdM0sOs9p20Km/h/mcwayuv8Awb+I3APCLyZ26R7czzxBAAAAAAAAACOzZ9mAAAAAA4IqWYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANPDEZCzq22PF75L9qKR//v912S3QZpzdEEbRbPgb/cwayk8UWxRwk7TAe5X+YfUvSbzXlW+4zew59sM/facDHwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4UWV1VcXnNiMVBlkCndUkwOdalX0GZw+FyEv6PvZCPkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAFInz5jOrPMNCW0yS9cxzUFEBV7zFu3QVrVdmgOKR6URNPDEZCzq22PF75L9qKR//v912S3QZpzdEEbRbPgb/cwayk8UWxRwk7TAe5X+YfUvSbzXlW+4zew59sM/facDHwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPZZ+gKsPwrYGgZkKtk9C1DhrYIdhYwo+uUZjXLPlALIaAcGhDLxhqFHzwsTowBn04YgTqnWyLBHQ6wu8BCwdSWyxWZgAAAABKFaBmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABodHRwczovLzk1LjE3OS4xMzQuMTAzLnhpcC5zd2l0Y2hib2FyZC1vcmFjbGVzLnh5ei9tYWlubmV0AAAAAAAAAQAAAAAAAAABAAAAAAAAABLeABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=='; export const ORACLE_ADDRESS_2 = new PublicKey( 'BuZBFufhjGn1HDUCukJYognbeoQQW8ACZJq5sWoQPnGe' ); export const ORACLE_ADDRESS_2_DATA = 'gB4Q8apJNzZRJet6Ou1Z3ahP/9cdV9ykdZ2RKUQ3PPGhmbFS44NSNNM0sOs9p20Km/h/mcwayuv8Awb+I3APCLyZ26R7czzxBAAAAAAAAADPxJ9mAAAAAE//qGYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArzaUk36ELwXp+Ea4qJCa0+NRpnAfb72Uj0pPKfkzPXqt+eT+Z7L6JkVT58yAcZXFCqvEpIHTTAdHlvFi5WnHzgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWOzkz4ZGbPT0UQ/MX6PWYdv5BXdUAc9ppTDTxXv5HY4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAFEl63o67VndqE//1x1X3KR1nZEpRDc88aGZsVLjg1I0rzaUk36ELwXp+Ea4qJCa0+NRpnAfb72Uj0pPKfkzPXqt+eT+Z7L6JkVT58yAcZXFCqvEpIHTTAdHlvFi5WnHzgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAd1I0O4f5wWbKGZQe4T19CWddAjIEuiL1iYKSRT3omBYaAcGhDLxhqFHzwsTowBn04YgTqnWyLBHQ6wu8BCwdSLQxGZgAAAABtFaBmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABodHRwczovLzIwOS4yNTAuMjUzLjE4OC54aXAuc3dpdGNoYm9hcmQtb3JhY2xlcy54eXovbWFpbm5ldAAAAAAAAQAAAAAAAAABAAAAAAAAABLY3A8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=='; export const ORACLE_ADDRESS_3 = new PublicKey( '3DNK48NH6jvay2nHBiW3wk5yWegD9C2crk2vd9aznRz6' ); export const ORACLE_ADDRESS_3_DATA = 'gB4Q8apJNzbbRyjE0DCSZU4nDrlOkzBC5nqJa6SPkw1yfUj5OSgsF9M0sOs9p20Km/h/mcwayuv8Awb+I3APCLyZ26R7czzxBAAAAAAAAACw1Z9mAAAAADAQqWYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD+8A0lL5O/Ict++8kW+lbi0Hj1Z6zlGxOvO2XsaEUMrAKLdC95ssBvr6y6Y+gAeUKxaQVbt803iHRcenezMXtQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWOzkz4ZGbPT0UQ/MX6PWYdv5BXdUAc9ppTDTxXv5HY4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAANtHKMTQMJJlTicOuU6TMELmeolrpI+TDXJ9SPk5KCwXD+8A0lL5O/Ict++8kW+lbi0Hj1Z6zlGxOvO2XsaEUMrAKLdC95ssBvr6y6Y+gAeUKxaQVbt803iHRcenezMXtQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPeswwW+Ek5vPz+ybmZLtGRcin/ty9MOOnEAHX5z8GqIaAcGhDLxhqFHzwsTowBn04YgTqnWyLBHQ6wu8BCwdSJNpMZgAAAAD1FKBmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABodHRwczovLzU3LjEyOS4zNy42Ni54aXAuc3dpdGNoYm9hcmQtb3JhY2xlcy54eXovbWFpbm5ldAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAHZF7A8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=='; export const ORACLE_ADDRESS_4 = new PublicKey( '8Vjo4QEbmB9QhhBu6QiTy66G1tw8WomtFVWECMi3a71y' ); export const ORACLE_ADDRESS_4_DATA = 'gB4Q8apJNzbvHthU78LGdxVNKt0hJSQCVi3ceM0ArbSEjK6Tin/IXbEs+luycPcvAo9yB3cA1VWa5nFYyKm+p7Pb7QeUa8y4BAAAAAAAAADmLJ9mAAAAAGZnqGYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAeB4yxFiG7RyJ7BOLVdCck1fAB0HAf0ew/Dy0txy8jy+mnpPqtO9bWgjDAPxXgt7qK8bQ7BJWdDe0ppPi1M+PlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWOzkz4ZGbPT0UQ/MX6PWYdv5BXdUAc9ppTDTxXv5HY4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAO8e2FTvwsZ3FU0q3SElJAJWLdx4zQCttISMrpOKf8hdeB4yxFiG7RyJ7BOLVdCck1fAB0HAf0ew/Dy0txy8jy+mnpPqtO9bWgjDAPxXgt7qK8bQ7BJWdDe0ppPi1M+PlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAd1I0O4f5wWbKGZQe4T19CWddAjIEuiL1iYKSRT3omBYaAcGhDLxhqFHzwsTowBn04YgTqnWyLBHQ6wu8BCwdSRT5fZgAAAAC2FaBmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABodHRwczovL3hvcmFjbGUtMy1tbi5zd2l0Y2hib2FyZC54eXoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAFPBFRAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=='; export const ORACLE_ADDRESS_5 = new PublicKey( 'CXyurDdbo9JR5Xh9QuknMJSsuGM3aQdsa38ZVrKSjp1c' ); export const ORACLE_ADDRESS_5_DATA = 'gB4Q8apJNzaiWYTibvKmtE5apvU6wyY/XnS9miPOux8n7v4jUaUHC9M0sOs9p20Km/h/mcwayuv8Awb+I3APCLyZ26R7czzxBAAAAAAAAAD8yZ9mAAAAAHwEqWYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAdT3+DuOrlObfhM3zyU+csa4dhc68UVj5O3xrXtd233QaiZrFwDr3oHYibN1VOYpeR2nOTbspTpLI59T1lw/MnAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWOzkz4ZGbPT0UQ/MX6PWYdv5BXdUAc9ppTDTxXv5HY4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAKJZhOJu8qa0Tlqm9TrDJj9edL2aI867Hyfu/iNRpQcLdT3+DuOrlObfhM3zyU+csa4dhc68UVj5O3xrXtd233QaiZrFwDr3oHYibN1VOYpeR2nOTbspTpLI59T1lw/MnAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACs5tcdxX0o1RTrEPrwq6TcbKqpFpLLzuCtLoSZT0aX1IaAcGhDLxhqFHzwsTowBn04YgTqnWyLBHQ6wu8BCwdSOehYZgAAAABDFaBmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABodHRwczovLzEzNi4yNDQuODcuMTM2LnhpcC5zd2l0Y2hib2FyZC1vcmFjbGVzLnh5ei9tYWlubmV0AAAAAAAAAQAAAAAAAAABAAAAAAAAAJoxBxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=='; export const ORACLE_ADDRESS_6 = new PublicKey( 'GLc9EQ5ARgnBJvM59wU6eNjaeAEeBa1Gj7jp8rT5NJ8v' ); export const ORACLE_ADDRESS_6_DATA = 'gB4Q8apJNzbzsYZXOCuTpboFcKXE/sMkdNG2KBov/94xETKSVwL//bEs+luycPcvAo9yB3cA1VWa5nFYyKm+p7Pb7QeUa8y4BAAAAAAAAAAVLZ9mAAAAAJVnqGYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAet9eBXIaS0gy56IQTGIQt0jnFFiXpEqQR432dpzNqHB3Z8VuoNflHGblq6gGt+5bD0NOVASDieVZLvP7MXRHOQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWOzkz4ZGbPT0UQ/MX6PWYdv5BXdUAc9ppTDTxXv5HY4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAPOxhlc4K5OlugVwpcT+wyR00bYoGi//3jERMpJXAv/9et9eBXIaS0gy56IQTGIQt0jnFFiXpEqQR432dpzNqHB3Z8VuoNflHGblq6gGt+5bD0NOVASDieVZLvP7MXRHOQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAd1I0O4f5wWbKGZQe4T19CWddAjIEuiL1iYKSRT3omBYaAcGhDLxhqFHzwsTowBn04YgTqnWyLBHQ6wu8BCwdSpj1fZgAAAACKFaBmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABodHRwczovL3hvcmFjbGUtMi1tbi5zd2l0Y2hib2FyZC54eXoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAA3AFRAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=='; export const ORACLE_ADDRESS_7 = new PublicKey( '7EyXLrFUtoRoYKhPBnRpjyo2nGTsfGgo2d7XcPb4TwPF' ); export const ORACLE_ADDRESS_7_DATA = 'gB4Q8apJNzbiF/kJGSrVJEo7TYcohdRJNxfsO8BHXGU+CF+r+f9UobEs+luycPcvAo9yB3cA1VWa5nFYyKm+p7Pb7QeUa8y4BAAAAAAAAADmLJ9mAAAAAGZnqGYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgRV5VcxlQ1XcyerrpHSXC5WiDDaMhadb/W87/DEz4G7I4GJxtF3Ne7zApderYcuReksCnlPROrT/g7DU1oktgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWOzkz4ZGbPT0UQ/MX6PWYdv5BXdUAc9ppTDTxXv5HY4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAOIX+QkZKtUkSjtNhyiF1Ek3F+w7wEdcZT4IX6v5/1ShDgRV5VcxlQ1XcyerrpHSXC5WiDDaMhadb/W87/DEz4G7I4GJxtF3Ne7zApderYcuReksCnlPROrT/g7DU1oktgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAd1I0O4f5wWbKGZQe4T19CWddAjIEuiL1iYKSRT3omBYaAcGhDLxhqFHzwsTowBn04YgTqnWyLBHQ6wu8BCwdSNztfZgAAAABjFaBmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABodHRwczovL3hvcmFjbGUtMS1tbi5zd2l0Y2hib2FyZC54eXoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAJu6FRAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==';
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/assetTier.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { PublicKey, Keypair } from '@solana/web3.js'; import { TestClient, BN, ZERO, // SPOT_MARKET_RATE_PRECISION, // SpotBalanceType, isVariant, OracleSource, // SPOT_MARKET_WEIGHT_PRECISION, // SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION, // OracleInfo, AMM_RESERVE_PRECISION, PEG_PRECISION, QUOTE_SPOT_MARKET_INDEX, AssetTier, SPOT_MARKET_WEIGHT_PRECISION, QUOTE_PRECISION, } from '../sdk/src'; import { mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, // setFeedPrice, initializeQuoteSpotMarket, createUserWithUSDCAndWSOLAccount, initializeSolSpotMarket, createUSDCAccountForUser, // getFeedData, // sleep, } from './testHelpers'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; import { ContractTier } from '../sdk'; describe('asset tiers', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let bulkAccountLoader: TestBulkAccountLoader; let usdcMint; let dogeMint; let userUSDCAccount: Keypair; let solOracle: PublicKey; let dogeOracle: PublicKey; const usdcAmount = new BN(1000000 * 10 ** 6); //1M let secondUserDriftClient: TestClient; let secondUserDriftClientWSOLAccount: PublicKey; let secondUserDriftClientUSDCAccount: PublicKey; let secondUserDriftClientDogeAccount: PublicKey; let secondUserKeyPair: Keypair; const solAmount = new BN(10000 * 10 ** 9); before(async () => { const context = await startAnchor('', [], []); const bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); dogeMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount.mul(new BN(2)), // 2x it bankrunContextWrapper ); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 22500); // a future we all need to believe in dogeOracle = await mockOracleNoProgram(bankrunContextWrapper, 0.05); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, // activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0, 1], subAccountIds: [], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], userStats: false, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); // await driftClient.initializeUserAccount(0); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await initializeSolSpotMarket(driftClient, solOracle); await initializeSolSpotMarket(driftClient, dogeOracle, dogeMint.publicKey); const periodicity = new BN(60 * 60); // 1 HOUR await driftClient.initializePerpMarket( 0, solOracle, AMM_RESERVE_PRECISION, AMM_RESERVE_PRECISION, periodicity, new BN(22500 * PEG_PRECISION.toNumber()), undefined, ContractTier.A, 1000, 500, undefined, undefined, undefined, true, 2000, 5000 ); await driftClient.updatePerpMarketCurveUpdateIntensity(0, 100); const subAccountId = 0; const name = 'BIGZ'; await driftClient.initializeUserAccount(subAccountId, name); const depositAmount = driftClient.convertToSpotPrecision( QUOTE_SPOT_MARKET_INDEX, 1 ); console.log(`\n\n\n\n\n\n depositing here: ${depositAmount}`); await driftClient.deposit( // $10k depositAmount, QUOTE_SPOT_MARKET_INDEX, userUSDCAccount.publicKey ); [ secondUserDriftClient, secondUserDriftClientWSOLAccount, secondUserDriftClientUSDCAccount, secondUserKeyPair, ] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount, ZERO, [0], [0, 1, 2], [ { publicKey: solOracle, source: OracleSource.PYTH, }, { publicKey: dogeOracle, source: OracleSource.PYTH, }, ], bulkAccountLoader ); secondUserDriftClientDogeAccount = await createUSDCAccountForUser( bankrunContextWrapper, secondUserKeyPair, dogeMint, usdcAmount ); secondUserDriftClient.subscribe(); const marketIndex = 1; console.log( '\n\n\n\n\n\n\n\n\n\n FIRST depositing for second user: ' + solAmount ); await secondUserDriftClient.deposit( solAmount, marketIndex, secondUserDriftClientWSOLAccount ); // await printTxLogs(connection, txSig); console.log( '\n\n\n\n\n\n\n\n\n\n SECOND depositing for second user: ' + usdcAmount ); await secondUserDriftClient.deposit( usdcAmount, 2, secondUserDriftClientDogeAccount ); // await printTxLogs(connection, txSig2); }); it('fail trying to borrow protected asset', async () => { const usdcBorrowAmount = QUOTE_PRECISION; const quoteMarket = driftClient.getSpotMarketAccount(0); assert(isVariant(quoteMarket.assetTier, 'collateral')); await driftClient.updateSpotMarketAssetTier(0, AssetTier.PROTECTED); await driftClient.fetchAccounts(); const quoteMarketAfter = driftClient.getSpotMarketAccount(0); assert(isVariant(quoteMarketAfter.assetTier, 'protected')); console.log('updateSpotMarketAssetTier for USDC to PROTECTED'); try { await secondUserDriftClient.withdraw( usdcBorrowAmount, 0, secondUserDriftClientUSDCAccount, false ); // await printTxLogs(connection, txSig); // assert(false); } catch (err) { console.error(err); // assert(err.message.includes('0x17e2')); } console.log('updateSpotMarketAssetTier for USDC back to COLLATERAL'); await driftClient.updateSpotMarketAssetTier(0, AssetTier.COLLATERAL); await secondUserDriftClient.fetchAccounts(); const quoteMarketAfterAgain = secondUserDriftClient.getSpotMarketAccount(0); assert(isVariant(quoteMarketAfterAgain.assetTier, 'collateral')); console.log('USDC tier:', quoteMarketAfterAgain.assetTier); // make doge isolated asset try { await driftClient.updateSpotMarketMarginWeights( 2, 0, 1, SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(2)).toNumber(), SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(10)).div(new BN(9)).toNumber() ); await driftClient.updateSpotMarketAssetTier(2, AssetTier.ISOLATED); } catch (e) { console.error(e); } await driftClient.fetchAccounts(); await secondUserDriftClient.fetchAccounts(); console.log('updateSpotMarketAssetTier for DOGE to isolated'); const dogeMarketAfter = secondUserDriftClient.getSpotMarketAccount(2); assert(isVariant(dogeMarketAfter.assetTier, 'isolated')); console.log('DOGE asset tier:', dogeMarketAfter.assetTier); await secondUserDriftClient.withdraw( new BN(1), 2, secondUserDriftClientDogeAccount, false ); // await printTxLogs(connection, txSig); await secondUserDriftClient.fetchAccounts(); try { await secondUserDriftClient.withdraw( usdcBorrowAmount, 0, secondUserDriftClientUSDCAccount, false ); // await printTxLogs(connection, txSig); console.log('usdc borrow succeed (should have fail!)'); assert(false); } catch (err) { console.log('failed!'); // assert(err.message.includes('Transaction simulation failed:')); } // make doge CROSS await driftClient.updateSpotMarketAssetTier(2, AssetTier.CROSS); const dogeMarketAfterAgain = driftClient.getSpotMarketAccount(2); assert(isVariant(dogeMarketAfterAgain.assetTier, 'cross')); await secondUserDriftClient.fetchAccounts(); const scQuoteMarketAfterAgain = secondUserDriftClient.getSpotMarketAccount(0); assert(isVariant(scQuoteMarketAfterAgain.assetTier, 'collateral')); console.log('USDC asset tier:', scQuoteMarketAfterAgain.assetTier); try { await secondUserDriftClient.withdraw( QUOTE_PRECISION.divn(2), 0, secondUserDriftClientUSDCAccount, false ); // await printTxLogs(connection, txSig2); } catch (e) { console.error(e); assert(false); } }); after(async () => { await driftClient.unsubscribe(); await secondUserDriftClient.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/forceUserDelete.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js'; import { TestClient, BN, EventSubscriber, SPOT_MARKET_RATE_PRECISION, OracleSource, SPOT_MARKET_WEIGHT_PRECISION, OracleInfo, } from '../sdk/src'; import { createUserWithUSDCAndWSOLAccount, createWSolTokenAccountForUser, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpers'; import { NATIVE_MINT } from '@solana/spl-token'; import { QUOTE_PRECISION, ZERO } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('spot deposit and withdraw', () => { const chProgram = anchor.workspace.Drift as Program; let admin: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let solOracle: PublicKey; let usdcMint; let firstUserDriftClient: TestClient; let firstUserDriftClientWSOLAccount: PublicKey; let firstUserDriftClientUSDCAccount: PublicKey; let secondUserDriftClient: TestClient; let secondUserDriftClientWSOLAccount: PublicKey; const usdcAmount = new BN(10 ** 6 / 20); const largeUsdcAmount = new BN(10_000 * 10 ** 6); const solAmount = new BN(1 * 10 ** 9); let marketIndexes: number[]; let spotMarketIndexes: number[]; let oracleInfos: OracleInfo[]; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); await mockUserUSDCAccount(usdcMint, largeUsdcAmount, bankrunContextWrapper); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 30); marketIndexes = []; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solOracle, source: OracleSource.PYTH }]; admin = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await admin.initialize(usdcMint.publicKey, true); await admin.subscribe(); }); after(async () => { await admin.unsubscribe(); await eventSubscriber.unsubscribe(); await firstUserDriftClient.unsubscribe(); await secondUserDriftClient.unsubscribe(); }); it('Initialize USDC Market', async () => { const optimalUtilization = SPOT_MARKET_RATE_PRECISION.div( new BN(2) ).toNumber(); // 50% utilization const optimalRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(20)).toNumber(); // 2000% APR const maxRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(50)).toNumber(); // 5000% APR const initialAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const initialLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); await admin.initializeSpotMarket( usdcMint.publicKey, optimalUtilization, optimalRate, maxRate, PublicKey.default, OracleSource.QUOTE_ASSET, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight ); const txSig = await admin.updateWithdrawGuardThreshold( 0, new BN(10 ** 10).mul(QUOTE_PRECISION) ); bankrunContextWrapper.printTxLogs(txSig); await admin.fetchAccounts(); }); it('Initialize SOL Market', async () => { const optimalUtilization = SPOT_MARKET_RATE_PRECISION.div( new BN(2) ).toNumber(); // 50% utilization const optimalRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(20)).toNumber(); // 2000% APR const maxRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(50)).toNumber(); // 5000% APR const initialAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(8)) .div(new BN(10)) .toNumber(); const maintenanceAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(9)) .div(new BN(10)) .toNumber(); const initialLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(12)) .div(new BN(10)) .toNumber(); const maintenanceLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.mul( new BN(11) ) .div(new BN(10)) .toNumber(); await admin.initializeSpotMarket( NATIVE_MINT, optimalUtilization, optimalRate, maxRate, solOracle, OracleSource.PYTH, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight ); const txSig = await admin.updateWithdrawGuardThreshold( 1, new BN(10 ** 10).mul(QUOTE_PRECISION) ); bankrunContextWrapper.printTxLogs(txSig); await admin.fetchAccounts(); }); it('First User Deposit USDC', async () => { [ firstUserDriftClient, firstUserDriftClientWSOLAccount, firstUserDriftClientUSDCAccount, ] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, ZERO, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); const marketIndex = 0; await sleep(100); await firstUserDriftClient.fetchAccounts(); const txSig = await firstUserDriftClient.deposit( usdcAmount, marketIndex, firstUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); }); it('Second User Deposit SOL', async () => { [secondUserDriftClient, secondUserDriftClientWSOLAccount] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount, ZERO, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); const marketIndex = 1; const txSig = await secondUserDriftClient.deposit( solAmount, marketIndex, secondUserDriftClientWSOLAccount ); bankrunContextWrapper.printTxLogs(txSig); }); it('First User Borrow SOL', async () => { const marketIndex = 1; const withdrawAmount = solAmount.div(new BN(1000)); const txSig = await firstUserDriftClient.withdraw( withdrawAmount, marketIndex, firstUserDriftClientWSOLAccount ); bankrunContextWrapper.printTxLogs(txSig); }); it('Force delete', async () => { await firstUserDriftClient.fetchAccounts(); // @ts-ignore await createWSolTokenAccountForUser( bankrunContextWrapper, secondUserDriftClient.wallet, new BN(LAMPORTS_PER_SOL) ); // @ts-ignore await secondUserDriftClient.sendTransaction( await secondUserDriftClient.buildTransaction([ await secondUserDriftClient.createAssociatedTokenAccountIdempotentInstruction( await secondUserDriftClient.getAssociatedTokenAccount(0), secondUserDriftClient.wallet.publicKey, secondUserDriftClient.wallet.publicKey, secondUserDriftClient.getSpotMarketAccount(0).mint ), ]) ); const ixs = []; ixs.push( await secondUserDriftClient.getForceDeleteUserIx( await firstUserDriftClient.getUserAccountPublicKey(), await firstUserDriftClient.getUserAccount() ) ); // @ts-ignore await secondUserDriftClient.sendTransaction( await secondUserDriftClient.buildTransaction(ixs) ); const accountInfo = await bankrunContextWrapper.connection.getAccountInfo( await firstUserDriftClient.getUserAccountPublicKey() ); assert(accountInfo === null); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/spotSwap22.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair, LAMPORTS_PER_SOL, PublicKey, Transaction, } from '@solana/web3.js'; import { BN, TestClient, EventSubscriber, OracleSource, OracleInfo, QUOTE_PRECISION, UserStatsAccount, getUserStatsAccountPublicKey, } from '../sdk/src'; import { createUserWithUSDCAndWSOLAccount, createWSolTokenAccountForUser, initializeQuoteSpotMarket, initializeSolSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } from './testHelpers'; import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, createTransferInstruction, } from '@solana/spl-token'; 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 22', () => { const chProgram = anchor.workspace.Drift as Program; let makerDriftClient: TestClient; let makerWSOL: PublicKey; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let solOracle: PublicKey; let usdcMint; let makerUSDC; let takerDriftClient: TestClient; let takerWSOL: PublicKey; let takerUSDC: PublicKey; const usdcAmount = new BN(200 * 10 ** 6); const solAmount = new BN(2 * 10 ** 9); let marketIndexes: number[]; let spotMarketIndexes: number[]; let oracleInfos: OracleInfo[]; let takerKeypair: Keypair; before(async () => { const context = await startAnchor( '', [ { name: 'serum_dex', programId: new PublicKey( 'srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX' ), }, ], [] ); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper, TOKEN_2022_PROGRAM_ID); makerUSDC = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); makerWSOL = await createWSolTokenAccountForUser( bankrunContextWrapper, // @ts-ignore bankrunContextWrapper.provider.wallet, solAmount ); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 100); marketIndexes = []; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solOracle, source: OracleSource.PYTH }]; makerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClient.initialize(usdcMint.publicKey, true); await makerDriftClient.subscribe(); await makerDriftClient.initializeUserAccount(); await initializeQuoteSpotMarket(makerDriftClient, usdcMint.publicKey); await initializeSolSpotMarket(makerDriftClient, solOracle); await makerDriftClient.updateSpotMarketStepSizeAndTickSize( 1, new BN(100000000), new BN(100) ); await makerDriftClient.updateSpotAuctionDuration(0); [takerDriftClient, takerWSOL, takerUSDC, takerKeypair] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount, usdcAmount, [], [0, 1], [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], bulkAccountLoader ); await bankrunContextWrapper.fundKeypair( takerKeypair, 10 * LAMPORTS_PER_SOL ); await takerDriftClient.deposit(usdcAmount, 0, takerUSDC); }); after(async () => { await takerDriftClient.unsubscribe(); await makerDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('swap usdc for sol', async () => { const amountIn = new BN(200).mul(QUOTE_PRECISION); const { beginSwapIx, endSwapIx } = await takerDriftClient.getSwapIx({ amountIn: amountIn, inMarketIndex: 0, outMarketIndex: 1, inTokenAccount: takerUSDC, outTokenAccount: takerWSOL, }); const transferIn = createTransferInstruction( takerUSDC, makerUSDC.publicKey, takerDriftClient.wallet.publicKey, new BN(100).mul(QUOTE_PRECISION).toNumber(), undefined, TOKEN_2022_PROGRAM_ID ); const transferOut = createTransferInstruction( makerWSOL, takerWSOL, makerDriftClient.wallet.publicKey, LAMPORTS_PER_SOL, undefined, TOKEN_PROGRAM_ID ); const tx = new Transaction() .add(beginSwapIx) .add(transferIn) .add(transferOut) .add(endSwapIx); // @ts-ignore const { txSig } = await takerDriftClient.sendTransaction(tx, [ makerDriftClient.wallet.payer, ]); bankrunContextWrapper.printTxLogs(txSig); const takerSOLAmount = await takerDriftClient.getTokenAmount(1); assert(takerSOLAmount.eq(new BN(1000000000))); const takerUSDCAmount = await takerDriftClient.getTokenAmount(0); assert(takerUSDCAmount.eq(new BN(99999999))); const userStatsPublicKey = getUserStatsAccountPublicKey( new PublicKey(DRIFT_PROGRAM_ID), takerDriftClient.wallet.publicKey ); const accountInfo = await bankrunContextWrapper.connection.getAccountInfo( userStatsPublicKey ); const userStatsAccount = accountInfo ? (takerDriftClient.program.account.user.coder.accounts.decodeUnchecked( 'UserStats', accountInfo.data ) as UserStatsAccount) : undefined; assert(userStatsAccount.takerVolume30D.eq(new BN(0))); const swapRecord = eventSubscriber.getEventsArray('SwapRecord')[0]; assert(swapRecord.amountOut.eq(new BN(1000000000))); assert(swapRecord.outMarketIndex === 1); assert(swapRecord.amountIn.eq(new BN(100000000))); assert(swapRecord.inMarketIndex === 0); assert(swapRecord.fee.eq(new BN(0))); const solSpotMarket = takerDriftClient.getSpotMarketAccount(1); assert(solSpotMarket.totalSwapFee.eq(new BN(0))); }); it('swap usdc for sol', async () => { const amountIn = new BN(1).mul(new BN(LAMPORTS_PER_SOL)); const { beginSwapIx, endSwapIx } = await takerDriftClient.getSwapIx({ amountIn: amountIn, inMarketIndex: 1, outMarketIndex: 0, inTokenAccount: takerWSOL, outTokenAccount: takerUSDC, }); const transferIn = createTransferInstruction( takerWSOL, makerWSOL, takerDriftClient.wallet.publicKey, LAMPORTS_PER_SOL, undefined, TOKEN_PROGRAM_ID ); const transferOut = createTransferInstruction( makerUSDC.publicKey, takerUSDC, makerDriftClient.wallet.publicKey, new BN(100).mul(QUOTE_PRECISION).toNumber(), undefined, TOKEN_2022_PROGRAM_ID ); const tx = new Transaction() .add(beginSwapIx) .add(transferIn) .add(transferOut) .add(endSwapIx); // @ts-ignore const { txSig } = await takerDriftClient.sendTransaction(tx, [ makerDriftClient.wallet.payer, ]); bankrunContextWrapper.printTxLogs(txSig); const takerSOLAmount = await takerDriftClient.getTokenAmount(1); assert(takerSOLAmount.eq(new BN(0))); const takerUSDCAmount = await takerDriftClient.getTokenAmount(0); console.log(takerUSDCAmount.toString()); assert(takerUSDCAmount.eq(new BN(199999999))); const swapRecord = eventSubscriber.getEventsArray('SwapRecord')[0]; assert(swapRecord.amountOut.eq(new BN(100000000))); assert(swapRecord.outMarketIndex === 0); assert(swapRecord.amountIn.eq(new BN(1000000000))); assert(swapRecord.inMarketIndex === 1); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/liquidatePerpAndLp.ts
import * as anchor from '@coral-xyz/anchor'; import { BASE_PRECISION, BN, getLimitOrderParams, isVariant, OracleSource, QUOTE_PRECISION, ZERO, OracleGuardRails, ContractTier, TestClient, EventSubscriber, PRICE_PRECISION, PositionDirection, Wallet, LIQUIDATION_PCT_PRECISION, User, } from '../sdk/src'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair } from '@solana/web3.js'; import { mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, sleep, mockOracleNoProgram, setFeedPriceNoProgram, } from './testHelpers'; import { PERCENTAGE_PRECISION, UserStatus } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('liquidate perp and lp', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bankrunContextWrapper: BankrunContextWrapper; let bulkAccountLoader: TestBulkAccountLoader; let usdcMint; let userUSDCAccount; const liquidatorKeyPair = new Keypair(); let liquidatorUSDCAccount: Keypair; let liquidatorDriftClient: TestClient; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(11.32 * 10 ** 6); const nLpShares = new BN(10000000); before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); const oracle = await mockOracleNoProgram(bankrunContextWrapper, 1); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [ { publicKey: oracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await driftClient.updateInitialPctToLiquidate( LIQUIDATION_PCT_PRECISION.toNumber() ); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: PERCENTAGE_PRECISION, oracleTwap5MinPercentDivergence: PERCENTAGE_PRECISION.muln(100), }, validity: { slotsBeforeStaleForAmm: new BN(100), slotsBeforeStaleForMargin: new BN(100), confidenceIntervalMaxSize: new BN(100000), tooVolatileRatio: new BN(11), // allow 11x change }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); const periodicity = new BN(0); await driftClient.initializePerpMarket( 0, oracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); await driftClient.openPosition( PositionDirection.LONG, new BN(175).mul(BASE_PRECISION).div(new BN(10)), // 17.5 SOL 0, new BN(0) ); await driftClient.addPerpLpShares(nLpShares, 0); for (let i = 0; i < 32; i++) { await driftClient.placePerpOrder( getLimitOrderParams({ baseAssetAmount: BASE_PRECISION, marketIndex: 0, direction: PositionDirection.LONG, price: PRICE_PRECISION, }) ); } eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); bankrunContextWrapper.fundKeypair(liquidatorKeyPair, 10 ** 9); liquidatorUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, liquidatorKeyPair.publicKey ); liquidatorDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(liquidatorKeyPair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [ { publicKey: oracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await liquidatorDriftClient.subscribe(); await liquidatorDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, liquidatorUSDCAccount.publicKey ); }); after(async () => { await driftClient.unsubscribe(); await liquidatorDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('liquidate', async () => { const marketIndex = 0; const lpShares = driftClient.getUserAccount().perpPositions[0].lpShares; assert(lpShares.eq(nLpShares)); const driftClientUser = new User({ driftClient: driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const mtc = driftClientUser.getTotalCollateral('Maintenance'); const mmr = driftClientUser.getMaintenanceMarginRequirement(); const pp = driftClientUser.getPerpPosition(0); const deltaValueToLiq = mtc.sub(mmr); // QUOTE_PRECISION console.log('mtc:', mtc.toString()); console.log('mmr:', mmr.toString()); console.log('deltaValueToLiq:', deltaValueToLiq.toString()); console.log('pp.base:', pp.baseAssetAmount.toString()); // const expectedLiqPrice = 0.521639; const liqPrice = driftClientUser.liquidationPrice(0, ZERO); console.log('liqPrice:', liqPrice.toString()); const expectedLiqPrice2 = new BN('372792'); console.log('expected liqPrice:', expectedLiqPrice2.toString()); assert(liqPrice.eq(expectedLiqPrice2)); const oracle = driftClient.getPerpMarketAccount(0).amm.oracle; await setFeedPriceNoProgram(bankrunContextWrapper, 0.9, oracle); await sleep(2000); await driftClientUser.fetchAccounts(); await driftClient.fetchAccounts(); const liqPriceAfterPxChange = driftClientUser.liquidationPrice(0, ZERO); console.log('liqPriceAfterPxChange:', liqPriceAfterPxChange.toString()); const mtc0 = driftClientUser.getTotalCollateral('Maintenance'); const mmr0 = driftClientUser.getMaintenanceMarginRequirement(); const pp0 = driftClientUser.getPerpPosition(0); const deltaValueToLiq0 = mtc0.sub(mmr0); // QUOTE_PRECISION console.log('mtc0:', mtc0.toString()); console.log('mmr0:', mmr0.toString()); console.log('deltaValueToLiq0:', deltaValueToLiq0.toString()); console.log('pp.base0:', pp0.baseAssetAmount.toString()); assert(liqPriceAfterPxChange.eq(expectedLiqPrice2)); await driftClient.settlePNL( driftClientUser.userAccountPublicKey, driftClientUser.getUserAccount(), 0 ); await sleep(2000); await driftClientUser.fetchAccounts(); await driftClient.fetchAccounts(); const liqPriceAfterSettlePnl = driftClientUser.liquidationPrice(0, ZERO); const mtc2 = driftClientUser.getTotalCollateral('Maintenance'); const mmr2 = driftClientUser.getMaintenanceMarginRequirement(); const pp2 = driftClientUser.getPerpPosition(0); const deltaValueToLiq2 = mtc2.sub(mmr2); // QUOTE_PRECISION console.log('mtc2:', mtc2.toString()); console.log('mmr2:', mmr2.toString()); console.log('deltaValueToLiq2:', deltaValueToLiq2.toString()); console.log('pp.base2:', pp2.baseAssetAmount.toString()); console.log('liqPriceAfterSettlePnl:', liqPriceAfterSettlePnl.toString()); assert(liqPriceAfterSettlePnl.eq(expectedLiqPrice2)); await setFeedPriceNoProgram(bankrunContextWrapper, 1.1, oracle); await driftClient.settlePNL( driftClientUser.userAccountPublicKey, driftClientUser.getUserAccount(), 0 ); const lpEventAfterSettle = eventSubscriber.getEventsArray('LPRecord')[0]; console.log(eventSubscriber.getEventsArray('LPRecord')); assert(lpEventAfterSettle.nShares.eq(new BN(900000))); const liqPriceAfterRallySettlePnl = driftClientUser.liquidationPrice( 0, ZERO ); console.log( 'liqPriceAfterRallySettlePnl:', liqPriceAfterRallySettlePnl.toString() ); assert(liqPriceAfterRallySettlePnl.eq(expectedLiqPrice2)); await driftClientUser.unsubscribe(); await setFeedPriceNoProgram(bankrunContextWrapper, 0.1, oracle); console.log( driftClient.getUserAccount().perpPositions[0].lpShares.toString() ); const txSig = await liquidatorDriftClient.liquidatePerp( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0, new BN(175).mul(BASE_PRECISION).div(new BN(10)) ); bankrunContextWrapper.connection.printTxLogs(txSig); const lpEvent = eventSubscriber.getEventsArray('LPRecord')[0]; assert(lpEvent.nShares.eq(new BN(8100000))); for (let i = 0; i < 32; i++) { assert(isVariant(driftClient.getUserAccount().orders[i].status, 'init')); } assert( liquidatorDriftClient .getUserAccount() .perpPositions[0].baseAssetAmount.eq(new BN(17500000000)) ); assert(driftClient.getUserAccount().status === UserStatus.BEING_LIQUIDATED); assert(driftClient.getUserAccount().nextLiquidationId === 2); // try to add liq when being liquidated -- should fail try { await driftClient.addPerpLpShares(nLpShares, 0); assert(false); } catch (err) { assert(err.message.includes('0x17e5')); } const liquidationRecord = eventSubscriber.getEventsArray('LiquidationRecord')[0]; assert(liquidationRecord.liquidationId === 1); assert(isVariant(liquidationRecord.liquidationType, 'liquidatePerp')); assert(liquidationRecord.liquidatePerp.marketIndex === 0); assert(liquidationRecord.canceledOrderIds.length === 32); assert( liquidationRecord.liquidatePerp.oraclePrice.eq( PRICE_PRECISION.div(new BN(10)) ) ); assert( liquidationRecord.liquidatePerp.baseAssetAmount.eq(new BN(-17500000000)) ); assert( liquidationRecord.liquidatePerp.quoteAssetAmount.eq(new BN(1750000)) ); assert(liquidationRecord.liquidatePerp.lpShares.eq(new BN(8100000))); assert(liquidationRecord.liquidatePerp.ifFee.eq(new BN(0))); assert(liquidationRecord.liquidatePerp.liquidatorFee.eq(new BN(0))); const fillRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert(isVariant(fillRecord.action, 'fill')); assert(fillRecord.marketIndex === 0); assert(isVariant(fillRecord.marketType, 'perp')); assert(fillRecord.baseAssetAmountFilled.eq(new BN(17500000000))); assert(fillRecord.quoteAssetAmountFilled.eq(new BN(1750000))); assert(fillRecord.takerOrderBaseAssetAmount.eq(new BN(17500000000))); assert( fillRecord.takerOrderCumulativeBaseAssetAmountFilled.eq( new BN(17500000000) ) ); assert(fillRecord.takerFee.eq(new BN(0))); assert(isVariant(fillRecord.takerOrderDirection, 'short')); assert(fillRecord.makerOrderBaseAssetAmount.eq(new BN(17500000000))); assert( fillRecord.makerOrderCumulativeBaseAssetAmountFilled.eq( new BN(17500000000) ) ); console.log(fillRecord.makerFee.toString()); assert(fillRecord.makerFee.eq(new BN(ZERO))); assert(isVariant(fillRecord.makerOrderDirection, 'long')); await liquidatorDriftClient.liquidatePerpPnlForDeposit( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0, 0, driftClient.getUserAccount().perpPositions[0].quoteAssetAmount ); await driftClient.fetchAccounts(); assert(driftClient.getUserAccount().status === UserStatus.BANKRUPT); console.log( driftClient.getUserAccount().perpPositions[0].quoteAssetAmount.toString() ); assert( driftClient .getUserAccount() .perpPositions[0].quoteAssetAmount.eq(new BN(-4447653)) ); // try to add liq when bankrupt -- should fail try { await driftClient.addPerpLpShares(nLpShares, 0); assert(false); } catch (err) { // cant add when bankrupt assert(err.message.includes('0x17ed')); } await driftClient.updatePerpMarketContractTier(0, ContractTier.A); const tx1 = await driftClient.updatePerpMarketMaxImbalances( marketIndex, new BN(40000).mul(QUOTE_PRECISION), QUOTE_PRECISION, QUOTE_PRECISION ); bankrunContextWrapper.connection.printTxLogs(tx1); await driftClient.fetchAccounts(); const marketBeforeBankruptcy = driftClient.getPerpMarketAccount(marketIndex); assert( marketBeforeBankruptcy.insuranceClaim.revenueWithdrawSinceLastSettle.eq( ZERO ) ); assert( marketBeforeBankruptcy.insuranceClaim.quoteSettledInsurance.eq(ZERO) ); assert( marketBeforeBankruptcy.insuranceClaim.quoteMaxInsurance.eq( QUOTE_PRECISION ) ); assert(marketBeforeBankruptcy.amm.totalSocialLoss.eq(ZERO)); await liquidatorDriftClient.resolvePerpBankruptcy( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0 ); await driftClient.fetchAccounts(); // all social loss const marketAfterBankruptcy = driftClient.getPerpMarketAccount(marketIndex); assert( marketAfterBankruptcy.insuranceClaim.revenueWithdrawSinceLastSettle.eq( ZERO ) ); assert(marketAfterBankruptcy.insuranceClaim.quoteSettledInsurance.eq(ZERO)); assert( marketAfterBankruptcy.insuranceClaim.quoteMaxInsurance.eq(QUOTE_PRECISION) ); console.log( 'marketAfterBankruptcy.amm.feePool.scaledBalance:', marketAfterBankruptcy.amm.feePool.scaledBalance.toString() ); assert(marketAfterBankruptcy.amm.feePool.scaledBalance.eq(ZERO)); console.log( 'marketAfterBankruptcy.amm.totalSocialLoss:', marketAfterBankruptcy.amm.totalSocialLoss.toString() ); assert(marketAfterBankruptcy.amm.totalSocialLoss.eq(new BN(4430007))); assert( (driftClient.getUserAccount().status & (UserStatus.BANKRUPT | UserStatus.BEING_LIQUIDATED)) === 0 ); const perpBankruptcyRecord = eventSubscriber.getEventsArray('LiquidationRecord')[0]; console.log(eventSubscriber.getEventsArray('LiquidationRecord')); assert(isVariant(perpBankruptcyRecord.liquidationType, 'perpBankruptcy')); // console.log(perpBankruptcyRecord); assert(perpBankruptcyRecord.perpBankruptcy.marketIndex === 0); console.log(perpBankruptcyRecord.perpBankruptcy.pnl.toString()); console.log( perpBankruptcyRecord.perpBankruptcy.cumulativeFundingRateDelta.toString() ); assert(perpBankruptcyRecord.perpBankruptcy.pnl.eq(new BN(-4447653))); console.log( perpBankruptcyRecord.perpBankruptcy.cumulativeFundingRateDelta.toString() ); assert( perpBankruptcyRecord.perpBankruptcy.cumulativeFundingRateDelta.eq( new BN(253144000) ) ); const market = driftClient.getPerpMarketAccount(0); console.log( market.amm.cumulativeFundingRateLong.toString(), market.amm.cumulativeFundingRateShort.toString() ); assert(market.amm.cumulativeFundingRateLong.eq(new BN(253152333))); assert(market.amm.cumulativeFundingRateShort.eq(new BN(-253135667))); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/modifyOrder.ts
import * as anchor from '@coral-xyz/anchor'; import { BASE_PRECISION, BN, OracleSource, TestClient, EventSubscriber, PRICE_PRECISION, PositionDirection, } from '../sdk/src'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, } from './testHelpers'; import { OrderType, TWO } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('modify orders', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); const oracle = await mockOracleNoProgram(bankrunContextWrapper, 1); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [ { publicKey: oracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(0); await driftClient.initializePerpMarket( 0, oracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); }); after(async () => { await driftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('modify order by order id', async () => { await driftClient.placePerpOrder({ marketIndex: 0, baseAssetAmount: BASE_PRECISION, direction: PositionDirection.LONG, orderType: OrderType.LIMIT, price: PRICE_PRECISION, }); await driftClient.modifyOrder({ orderId: 1, newBaseAmount: BASE_PRECISION.mul(TWO), }); assert( driftClient .getUser() .getUserAccount() .orders[0].baseAssetAmount.eq(BASE_PRECISION.mul(TWO)) ); }); it('modify order by user order id', async () => { await driftClient.placePerpOrder({ userOrderId: 1, marketIndex: 0, baseAssetAmount: BASE_PRECISION, direction: PositionDirection.LONG, orderType: OrderType.LIMIT, price: PRICE_PRECISION, }); await driftClient.modifyOrderByUserOrderId({ userOrderId: 1, newBaseAmount: BASE_PRECISION.mul(TWO), }); assert( driftClient .getUser() .getUserAccount() .orders[1].baseAssetAmount.eq(BASE_PRECISION.mul(TWO)) ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/surgePricing.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { PublicKey } from '@solana/web3.js'; import { TestClient, BN, EventSubscriber, SPOT_MARKET_RATE_PRECISION, OracleSource, SPOT_MARKET_WEIGHT_PRECISION, SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION, OracleInfo, } from '../sdk/src'; import { createUserWithUSDCAccount, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpers'; import { QUOTE_PRECISION, getUserAccountPublicKey } from '../sdk/src'; import { calculateInitUserFee } from '../sdk/src/math/state'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('surge pricing', () => { const chProgram = anchor.workspace.Drift as Program; let admin: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let solOracle: PublicKey; let usdcMint; const usdcAmount = new BN(10 * 10 ** 6); const largeUsdcAmount = new BN(10_000 * 10 ** 6); let marketIndexes: number[]; let spotMarketIndexes: number[]; let oracleInfos: OracleInfo[]; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); await mockUserUSDCAccount(usdcMint, largeUsdcAmount, bankrunContextWrapper); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 30); marketIndexes = []; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solOracle, source: OracleSource.PYTH }]; admin = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await admin.initialize(usdcMint.publicKey, true); await admin.subscribe(); }); after(async () => { await admin.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('Initialize USDC Market', async () => { const optimalUtilization = SPOT_MARKET_RATE_PRECISION.div( new BN(2) ).toNumber(); // 50% utilization const optimalRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(20)).toNumber(); // 2000% APR const maxRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(50)).toNumber(); // 5000% APR const initialAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const initialLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); await admin.initializeSpotMarket( usdcMint.publicKey, optimalUtilization, optimalRate, maxRate, PublicKey.default, OracleSource.QUOTE_ASSET, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight ); const txSig = await admin.updateWithdrawGuardThreshold( 0, new BN(10 ** 10).mul(QUOTE_PRECISION) ); bankrunContextWrapper.printTxLogs(txSig); await admin.fetchAccounts(); const spotMarket = await admin.getSpotMarketAccount(0); assert(spotMarket.marketIndex === 0); assert(spotMarket.optimalUtilization === optimalUtilization); assert(spotMarket.optimalBorrowRate === optimalRate); assert(spotMarket.maxBorrowRate === maxRate); assert( spotMarket.cumulativeBorrowInterest.eq( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); assert( spotMarket.cumulativeDepositInterest.eq( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); assert(spotMarket.initialAssetWeight === initialAssetWeight); assert(spotMarket.maintenanceAssetWeight === maintenanceAssetWeight); assert(spotMarket.initialLiabilityWeight === initialLiabilityWeight); assert(spotMarket.maintenanceAssetWeight === maintenanceAssetWeight); assert(admin.getStateAccount().numberOfSpotMarkets === 1); await admin.updateStateMaxNumberOfSubAccounts(5); await admin.updateStateMaxInitializeUserFee(1); }); it('Create users', async () => { for (let i = 0; i < 5; i++) { const expectedFee = calculateInitUserFee(admin.getStateAccount()); const [driftClient, _, keyPair] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); const userAccount = await getUserAccountPublicKey( driftClient.program.programId, keyPair.publicKey, 0 ); const accountInfo = await bankrunContextWrapper.connection.getAccountInfo( userAccount ); const baseLamports = 31347840; console.log('expected fee', expectedFee.toNumber()); if (i === 4) { // assert(expectedFee.toNumber() === LAMPORTS_PER_SOL / 100); } console.log('account info', accountInfo.lamports); assert(accountInfo.lamports === baseLamports + expectedFee.toNumber()); await sleep(1000); if (i === 4) { await admin.updateStateMaxNumberOfSubAccounts(0); await driftClient.reclaimRent(0); const accountInfoAfterReclaim = await bankrunContextWrapper.connection.getAccountInfo(userAccount); console.log( 'account info after reclaim', accountInfoAfterReclaim.lamports ); assert(accountInfoAfterReclaim.lamports === baseLamports); } await driftClient.unsubscribe(); } }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/rfq.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair } from '@solana/web3.js'; import { BN, PRICE_PRECISION, TestClient, User, Wallet, EventSubscriber, OracleSource, RFQMakerOrderParams, PositionDirection, MarketType, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpers'; import { BASE_PRECISION, BN_MAX, PEG_PRECISION, ZERO } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; import { nanoid } from 'nanoid'; describe('place and fill rfq orders', () => { const chProgram = anchor.workspace.Drift as Program; let takerDriftClient: TestClient; let takerDriftClientUser: User; let makerDriftClient: TestClient; let makerDriftClientUser: User; let makerDriftClient1: TestClient; let makerDriftClientUser1: User; let makerDriftClient2: TestClient; let makerDriftClientUser2: User; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); let usdcMint; let userUSDCAccount; const usdcAmount = new BN(100 * 10 ** 6); let solUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 100); marketIndexes = [0]; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; takerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await takerDriftClient.initialize(usdcMint.publicKey, true); await takerDriftClient.subscribe(); await initializeQuoteSpotMarket(takerDriftClient, usdcMint.publicKey); const periodicity = new BN(0); await takerDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(100 * PEG_PRECISION.toNumber()) ); await takerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); takerDriftClientUser = new User({ driftClient: takerDriftClient, userAccountPublicKey: await takerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await takerDriftClientUser.subscribe(); // Create some makers let keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); await sleep(500); let wallet = new Wallet(keypair); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); makerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClient.subscribe(); await makerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); makerDriftClientUser = new User({ driftClient: makerDriftClient, userAccountPublicKey: await makerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClientUser.subscribe(); // Create some makers keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); await sleep(500); wallet = new Wallet(keypair); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); makerDriftClient1 = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClient1.subscribe(); await makerDriftClient1.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); makerDriftClientUser1 = new User({ driftClient: makerDriftClient1, userAccountPublicKey: await makerDriftClient1.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClientUser1.subscribe(); // Create some makers keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); await sleep(500); wallet = new Wallet(keypair); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); makerDriftClient2 = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClient2.subscribe(); await makerDriftClient2.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); makerDriftClientUser2 = new User({ driftClient: makerDriftClient2, userAccountPublicKey: await makerDriftClient2.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClientUser2.subscribe(); // Create the maker's rfq accounts let [txSig, _rfqUserAccountPublicKey] = await makerDriftClient.initializeRFQUser( makerDriftClientUser.userAccountPublicKey ); bankrunContextWrapper.printTxLogs(txSig); [txSig, _rfqUserAccountPublicKey] = await makerDriftClient1.initializeRFQUser( makerDriftClientUser1.userAccountPublicKey ); bankrunContextWrapper.printTxLogs(txSig); [txSig, _rfqUserAccountPublicKey] = await makerDriftClient2.initializeRFQUser( makerDriftClientUser2.userAccountPublicKey ); bankrunContextWrapper.printTxLogs(txSig); }); after(async () => { await makerDriftClientUser.unsubscribe(); await makerDriftClientUser1.unsubscribe(); await makerDriftClientUser2.unsubscribe(); await makerDriftClient.unsubscribe(); await makerDriftClient1.unsubscribe(); await makerDriftClient2.unsubscribe(); await takerDriftClient.unsubscribe(); await takerDriftClientUser.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('should match rfq orders successfully', async () => { // Makers sign a messages to create a limit order const makerOrderMessage: RFQMakerOrderParams = { marketIndex: 0, marketType: MarketType.PERP, direction: PositionDirection.SHORT, authority: makerDriftClientUser.getUserAccount().authority, subAccountId: 0, price: new BN(100).mul(PRICE_PRECISION), baseAssetAmount: BASE_PRECISION, maxTs: BN_MAX, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const signature = makerDriftClient.signMessage( makerDriftClient.encodeRFQMakerOrderParams(makerOrderMessage) ); const _makerOrderMessage1: RFQMakerOrderParams = { marketIndex: 0, marketType: MarketType.PERP, direction: PositionDirection.SHORT, authority: makerDriftClientUser1.getUserAccount().authority, subAccountId: 0, price: new BN(100).mul(PRICE_PRECISION), baseAssetAmount: BASE_PRECISION, maxTs: BN_MAX, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const _signature1 = makerDriftClient1.signMessage( makerDriftClient1.encodeRFQMakerOrderParams(makerOrderMessage) ); await takerDriftClient.placeAndMatchRFQOrders([ { baseAssetAmount: BASE_PRECISION, makerOrderParams: makerOrderMessage, makerSignature: signature, }, // would fail if we included the second order as well bc tx too large // { // baseAssetAmount: BASE_PRECISION, // makerOrderParams: _makerOrderMessage1, // makerSignature: _signature1, // }, ]); assert( makerDriftClientUser .getPerpPosition(0) .baseAssetAmount.eq(BASE_PRECISION.neg()) ); assert( takerDriftClientUser.getPerpPosition(0).baseAssetAmount.eq(BASE_PRECISION) ); }); it('should not match again if order was already used once', async () => { // Makers sign a messages to create a limit order const makerOrderMessage: RFQMakerOrderParams = { marketIndex: 0, marketType: MarketType.PERP, direction: PositionDirection.SHORT, authority: makerDriftClientUser.getUserAccount().authority, subAccountId: 0, price: new BN(100).mul(PRICE_PRECISION), baseAssetAmount: BASE_PRECISION, maxTs: BN_MAX, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const signature = makerDriftClient.signMessage( makerDriftClient.encodeRFQMakerOrderParams(makerOrderMessage) ); await takerDriftClient.placeAndMatchRFQOrders([ { baseAssetAmount: BASE_PRECISION, makerOrderParams: makerOrderMessage, makerSignature: signature, }, ]); const makerPositionBefore = makerDriftClientUser.getPerpPosition(0); const takerPositionBefore = takerDriftClientUser.getPerpPosition(0); await takerDriftClient.placeAndMatchRFQOrders([ { baseAssetAmount: BASE_PRECISION, makerOrderParams: makerOrderMessage, makerSignature: signature, }, ]); const makerPositionAfter = makerDriftClientUser.getPerpPosition(0); const takerPositionAfter = takerDriftClientUser.getPerpPosition(0); assert( makerPositionBefore.baseAssetAmount.eq(makerPositionAfter.baseAssetAmount) ); assert( takerPositionBefore.baseAssetAmount.eq(takerPositionAfter.baseAssetAmount) ); }); it('should not match if maker order is expired', async () => { // Makers sign a messages to create a limit order const makerOrderMessage: RFQMakerOrderParams = { marketIndex: 0, marketType: MarketType.PERP, direction: PositionDirection.SHORT, authority: makerDriftClientUser.getUserAccount().authority, subAccountId: 0, price: new BN(100).mul(PRICE_PRECISION), baseAssetAmount: BASE_PRECISION, maxTs: ZERO, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const signature = makerDriftClient.signMessage( makerDriftClient.encodeRFQMakerOrderParams(makerOrderMessage) ); const makerPositionBefore = makerDriftClientUser.getPerpPosition(0); const takerPositionBefore = takerDriftClientUser.getPerpPosition(0); await takerDriftClient.placeAndMatchRFQOrders([ { baseAssetAmount: BASE_PRECISION, makerOrderParams: makerOrderMessage, makerSignature: signature, }, ]); const makerPositionAfter = makerDriftClientUser.getPerpPosition(0); const takerPositionAfter = takerDriftClientUser.getPerpPosition(0); assert( makerPositionBefore.baseAssetAmount.eq(makerPositionAfter.baseAssetAmount) ); assert( takerPositionBefore.baseAssetAmount.eq(takerPositionAfter.baseAssetAmount) ); assert(makerDriftClientUser.getOpenOrders().length === 0); }); it('should not match if rfq match exceeds maker base asset amount', async () => { // Makers sign a messages to create a limit order const makerOrderMessage: RFQMakerOrderParams = { marketIndex: 0, marketType: MarketType.PERP, direction: PositionDirection.SHORT, authority: makerDriftClientUser.getUserAccount().authority, subAccountId: 0, price: new BN(100).mul(PRICE_PRECISION), baseAssetAmount: BASE_PRECISION, maxTs: ZERO, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const signature = makerDriftClient.signMessage( makerDriftClient.encodeRFQMakerOrderParams(makerOrderMessage) ); const makerPositionBefore = makerDriftClientUser.getPerpPosition(0); const takerPositionBefore = takerDriftClientUser.getPerpPosition(0); // expect error try { await takerDriftClient.placeAndMatchRFQOrders([ { baseAssetAmount: BASE_PRECISION.muln(2), makerOrderParams: makerOrderMessage, makerSignature: signature, }, ]); } catch (e) { console.log(e); } const makerPositionAfter = makerDriftClientUser.getPerpPosition(0); const takerPositionAfter = takerDriftClientUser.getPerpPosition(0); assert( makerPositionBefore.baseAssetAmount.eq(makerPositionAfter.baseAssetAmount) ); assert( takerPositionBefore.baseAssetAmount.eq(takerPositionAfter.baseAssetAmount) ); assert(makerDriftClientUser.getOpenOrders().length === 0); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/imbalancePerpPnl.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { PublicKey, Keypair } from '@solana/web3.js'; import { Wallet, getInsuranceFundStakeAccountPublicKey, InsuranceFundStake, BASE_PRECISION, BN, OracleSource, ZERO, TestClient, convertToNumber, PRICE_PRECISION, PositionDirection, EventSubscriber, QUOTE_PRECISION, User, calculateNetUserPnlImbalance, getMarketOrderParams, calculateUpdatedAMM, oraclePriceBands, InsuranceFundRecord, OracleGuardRails, AMM_RESERVE_PRECISION, BID_ASK_SPREAD_PRECISION, calculateBidAskPrice, ContractTier, isVariant, MARGIN_PRECISION, PerpMarketAccount, OraclePriceData, SPOT_MARKET_BALANCE_PRECISION, QUOTE_SPOT_MARKET_INDEX, } from '../sdk/src'; import { mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, initializeQuoteSpotMarket, createUserWithUSDCAndWSOLAccount, initializeSolSpotMarket, sleep, } from './testHelpers'; import { PERCENTAGE_PRECISION } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; async function depositToFeePoolFromIF( amount: number, driftClient: TestClient, userUSDCAccount: Keypair ) { const ifAmount = new BN(amount * QUOTE_PRECISION.toNumber()); // // send $50 to market from IF const txSig00 = await driftClient.depositIntoPerpMarketFeePool( 0, ifAmount, userUSDCAccount.publicKey ); console.log(txSig00); } function examineSpread( market: PerpMarketAccount, oraclePriceData: OraclePriceData ) { const [bid, ask] = calculateBidAskPrice(market.amm, oraclePriceData, false); console.log( 'bid/ask:', bid.toString(), '/', ask.toString(), 'oracle:', oraclePriceData.price.toString() ); const spread = ask.sub(bid); console.log( 'market spread:', '$', convertToNumber(spread), spread.mul(BID_ASK_SPREAD_PRECISION).div(oraclePriceData.price).toNumber() / BID_ASK_SPREAD_PRECISION.toNumber(), '%', 'and max (', '$', convertToNumber( new BN(market.amm.maxSpread) .mul(oraclePriceData.price) .div(BID_ASK_SPREAD_PRECISION) ), market.amm.maxSpread / BID_ASK_SPREAD_PRECISION.toNumber(), '%', ' margin max=', (market.marginRatioInitial - market.marginRatioMaintenance) / BID_ASK_SPREAD_PRECISION.toNumber(), ')' ); const [minPrice, maxPrice] = oraclePriceBands(market, oraclePriceData); console.log( 'min/max:', minPrice.toString(), '/', maxPrice.toString(), '(oracle bands)' ); assert(bid.lte(oraclePriceData.price)); assert(ask.gte(oraclePriceData.price)); return [bid, ask]; } describe('imbalanced large perp pnl w/ borrow hitting limits', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bankrunContextWrapper: BankrunContextWrapper; let bulkAccountLoader: TestBulkAccountLoader; let usdcMint; let userUSDCAccount; let userUSDCAccount2; let driftClientLoser: TestClient; let driftClientLoserUser: User; let liquidatorDriftClient: TestClient; let liquidatorDriftClientWSOLAccount: PublicKey; let liquidatorDriftClientWUSDCAccount: PublicKey; let solOracle: PublicKey; // ammInvariant == k == x * y const ammInitialQuoteAssetReserve = new anchor.BN( 9 * AMM_RESERVE_PRECISION.toNumber() ).mul(new BN(1000000000)); const ammInitialBaseAssetReserve = new anchor.BN( 9 * AMM_RESERVE_PRECISION.toNumber() ).mul(new BN(1000000000)); const ammInitialQuoteAssetReserve2 = new anchor.BN(9) .mul(AMM_RESERVE_PRECISION) .mul(AMM_RESERVE_PRECISION); const ammInitialBaseAssetReserve2 = new anchor.BN(9) .mul(AMM_RESERVE_PRECISION) .mul(AMM_RESERVE_PRECISION); assert(ammInitialBaseAssetReserve.eq(ammInitialBaseAssetReserve2)); assert(ammInitialQuoteAssetReserve.eq(ammInitialQuoteAssetReserve2)); const usdcAmount = new BN(1000 * 10 ** 6); const userKeypair = new Keypair(); before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount.mul(new BN(10000)), bankrunContextWrapper ); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 43.1337); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0, 1], subAccountIds: [], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); const oracleGuardrails = driftClient.getStateAccount().oracleGuardRails; oracleGuardrails.priceDivergence.oracleTwap5MinPercentDivergence = new BN( 12 ).mul(PERCENTAGE_PRECISION); await driftClient.updateOracleGuardRails(oracleGuardrails); try { await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await initializeSolSpotMarket(driftClient, solOracle); } catch (e) { console.error(e); } await driftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(0); await driftClient.initializePerpMarket( 0, solOracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(42_500_000), undefined, ContractTier.A, 1000, 500, undefined, undefined, undefined, true, 250, 500 ); await driftClient.updatePerpMarketCurveUpdateIntensity(0, 100); await sleep(100); await driftClient.fetchAccounts(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); await bankrunContextWrapper.fundKeypair(userKeypair, 10 ** 9); userUSDCAccount2 = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, userKeypair.publicKey ); driftClientLoser = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(userKeypair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0, 1], subAccountIds: [], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientLoser.subscribe(); await sleep(100); await driftClientLoser.fetchAccounts(); await driftClientLoser.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount2.publicKey ); driftClientLoserUser = new User({ driftClient: driftClientLoser, userAccountPublicKey: await driftClientLoser.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientLoserUser.subscribe(); }); it('update amm', async () => { const marketAccount0 = driftClient.getPerpMarketAccount(0); assert(marketAccount0.amm.totalFee.eq(ZERO)); assert(marketAccount0.amm.pegMultiplier.eq(new BN(42500000))); assert(marketAccount0.amm.totalFeeMinusDistributions.eq(ZERO)); await depositToFeePoolFromIF(1000, driftClient, userUSDCAccount); const newPrice = 42.52; await setFeedPriceNoProgram(bankrunContextWrapper, newPrice, solOracle); console.log('price move to $', newPrice); const txSig1 = await driftClient.updateAMMs([0]); bankrunContextWrapper.connection.printTxLogs(txSig1); const txSig = await driftClient.openPosition( PositionDirection.SHORT, BASE_PRECISION, 0, new BN(0) ); bankrunContextWrapper.connection.printTxLogs(txSig); await driftClient.fetchAccounts(); const userAccount = driftClient.getUserAccount(); assert( userAccount.perpPositions[0].baseAssetAmount.abs().eq(BASE_PRECISION) ); const marketAccount = driftClient.getPerpMarketAccount(0); assert(marketAccount.amm.totalFee.gt(ZERO)); assert(marketAccount.amm.pegMultiplier.eq(new BN(42520000))); assert(marketAccount.amm.totalFeeMinusDistributions.gt(ZERO)); const newPrice2 = 42.5; await setFeedPriceNoProgram(bankrunContextWrapper, newPrice2, solOracle); console.log('price move to $', newPrice2); const txSig2 = await driftClient.updateAMMs([0]); bankrunContextWrapper.connection.printTxLogs(txSig2); }); it('put market in big drawdown and net user negative pnl', async () => { const uL = driftClientLoserUser.getUserAccount(); console.log( 'uL.spotPositions[0].scaledBalance:', uL.spotPositions[0].scaledBalance.toString() ); assert( uL.spotPositions[0].scaledBalance.eq( new BN(1000 * SPOT_MARKET_BALANCE_PRECISION.toNumber()) ) ); const bank0Value = driftClientLoserUser.getSpotMarketAssetValue(0); console.log('uL.bank0Value:', bank0Value.toString()); assert(bank0Value.eq(new BN(1000 * QUOTE_PRECISION.toNumber()))); const driftClientLoserUserValue = convertToNumber( driftClientLoserUser.getTotalCollateral(), QUOTE_PRECISION ); console.log('driftClientLoserUserValue:', driftClientLoserUserValue); assert(driftClientLoserUserValue == 1000); // ?? // todo try { const txSig = await driftClientLoser.openPosition( PositionDirection.LONG, BASE_PRECISION.mul(new BN(205)), 0, new BN(0) ); bankrunContextWrapper.connection.printTxLogs(txSig); } catch (e) { console.log('failed driftClientLoserc.openPosition'); console.error(e); } await driftClientLoser.fetchAccounts(); await driftClientLoserUser.fetchAccounts(); const driftClientLoserUserLeverage = convertToNumber( driftClientLoserUser.getLeverage(), MARGIN_PRECISION ); const driftClientLoserUserLiqPrice = convertToNumber( driftClientLoserUser.liquidationPrice(0), PRICE_PRECISION ); console.log( 'driftClientLoserUser.getLeverage:', driftClientLoserUserLeverage, 'driftClientLoserUserLiqPrice:', driftClientLoserUserLiqPrice ); assert(driftClientLoserUserLeverage < 8.95); assert(driftClientLoserUserLeverage > 8.5); assert(driftClientLoserUserLiqPrice < 42); assert(driftClientLoserUserLiqPrice > 30.5); const bank00 = driftClient.getSpotMarketAccount(0); const market00 = driftClient.getPerpMarketAccount(0); assert(market00.amm.feePool.scaledBalance.eq(new BN(1000000000000))); console.log('market00 oracle string:', market00.amm.oracle.toString()); const oraclePriceData00Test = driftClient.getOraclePriceDataAndSlot( market00.amm.oracle ); console.log(oraclePriceData00Test); const oraclePriceData00 = driftClient.getOracleDataForPerpMarket( market00.marketIndex ); const imbalance00 = calculateNetUserPnlImbalance( market00, bank00, oraclePriceData00, false ); console.log('pnlimbalance00:', imbalance00.toString()); assert(imbalance00.eq(new BN(-1009821952))); const bank0Value1p5 = driftClientLoserUser.getSpotMarketAssetValue(0); console.log('uL.bank0Value1p5:', bank0Value1p5.toString()); const driftClientLoserUserValue1p5 = convertToNumber( driftClientLoserUser.getTotalCollateral(), QUOTE_PRECISION ); console.log('driftClientLoserUserValue1p5:', driftClientLoserUserValue1p5); const [bid0, ask0] = examineSpread(market00, oraclePriceData00); console.log(bid0.toString(), ask0.toString()); assert(bid0.eq(new BN(42494732))); assert(ask0.eq(new BN(42505272))); // sol rallys big // await driftClient.moveAmmToPrice( // new BN(0), // new BN(260.5 * PRICE_PRECISION.toNumber()) // ); await setFeedPriceNoProgram(bankrunContextWrapper, 260.5, solOracle); console.log('price move to $260.5'); await sleep(1000); await driftClient.fetchAccounts(); const oraclePriceData00Again = driftClient.getOracleDataForPerpMarket( market00.marketIndex ); const newAmm00 = calculateUpdatedAMM(market00.amm, oraclePriceData00Again); const [bid0After, ask0After] = calculateBidAskPrice( newAmm00, oraclePriceData00Again ); console.log('bid0After:', bid0After.toString(), ask0After.toString()); assert(bid0After.eq(new BN(254679585))); assert( oraclePriceData00Again.price.eq( new BN(260.5 * PRICE_PRECISION.toNumber()) ) ); assert(ask0After.eq(new BN(585978468))); try { const txSig = await driftClient.updateAMMs([0]); bankrunContextWrapper.connection.printTxLogs(txSig); } catch (e) { console.error(e); } await driftClientLoser.fetchAccounts(); await driftClientLoserUser.fetchAccounts(); const driftClientLoserUserLeverage2 = convertToNumber( driftClientLoserUser.getLeverage(), MARGIN_PRECISION ); const driftClientLoserUserLiqPrice2 = convertToNumber( driftClientLoserUser.liquidationPrice(0), PRICE_PRECISION ); const bank0Value2 = driftClientLoserUser.getSpotMarketAssetValue(0); console.log('uL.bank0Value2:', bank0Value2.toString()); const driftClientLoserUserValue2 = convertToNumber( driftClientLoserUser.getTotalCollateral(), QUOTE_PRECISION ); console.log('driftClientLoserUserValue2:', driftClientLoserUserValue2); console.log( 'driftClientLoserUser.getLeverage2:', driftClientLoserUserLeverage2, 'driftClientLoserUserLiqPrice2:', driftClientLoserUserLiqPrice2, 'bank0Value2:', bank0Value2.toString(), 'driftClientLoserUserValue2:', driftClientLoserUserValue2.toString() ); const solAmount = new BN(1 * 10 ** 9); [ liquidatorDriftClient, liquidatorDriftClientWSOLAccount, liquidatorDriftClientWUSDCAccount, ] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount, usdcAmount.mul(new BN(10)), [0], [0, 1], [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], bulkAccountLoader ); await liquidatorDriftClient.subscribe(); const bankIndex = 1; await liquidatorDriftClient.deposit( solAmount, bankIndex, liquidatorDriftClientWSOLAccount ); await liquidatorDriftClient.deposit( usdcAmount.mul(new BN(10)), 0, liquidatorDriftClientWUSDCAccount ); const bank0 = driftClient.getSpotMarketAccount(0); let market0 = driftClient.getPerpMarketAccount(0); const winnerUser = driftClient.getUserAccount(); const loserUser = driftClientLoser.getUserAccount(); console.log(winnerUser.perpPositions[0].quoteAssetAmount.toString()); console.log(loserUser.perpPositions[0].quoteAssetAmount.toString()); assert( market0.amm.quoteAssetAmount.eq( winnerUser.perpPositions[0].quoteAssetAmount.add( loserUser.perpPositions[0].quoteAssetAmount ) ) ); const oraclePriceData0 = driftClient.getOracleDataForPerpMarket( market0.marketIndex ); const [bid1, ask1] = examineSpread(market0, oraclePriceData0); console.log('DOUBLE CHECK bids:', bid1.toString(), bid0After.toString()); console.log('DOUBLE CHECK asks:', ask1.toString(), ask0After.toString()); // assert(bid1.sub(bid0After).abs().lte(TWO)); // assert(ask1.sub(ask0After).abs().lte(TWO)); while (!market0.amm.lastOracleValid) { const imbalance = calculateNetUserPnlImbalance( market0, bank0, oraclePriceData0, false ); console.log('pnlimbalance:', imbalance.toString()); assert(imbalance.eq(new BN(43462178048))); //44k! :o console.log( 'lastOraclePrice:', market0.amm.historicalOracleData.lastOraclePrice.toString() ); console.log('lastOracleValid:', market0.amm.lastOracleValid.toString()); console.log('lastUpdateSlot:', market0.amm.lastUpdateSlot.toString()); console.log('lastAskPriceTwap:', market0.amm.lastAskPriceTwap.toString()); console.log('lastBidPriceTwap:', market0.amm.lastBidPriceTwap.toString()); console.log( 'lastOraclePriceTwap:', market0.amm.historicalOracleData.lastOraclePriceTwap.toString() ); try { const txSig = await driftClient.updateAMMs([0]); bankrunContextWrapper.connection.printTxLogs(txSig); } catch (e) { console.error(e); } driftClient.fetchAccounts(); market0 = driftClient.getPerpMarketAccount(0); } const oraclePriceData = driftClient.getOracleDataForPerpMarket( market0.marketIndex ); const imbalance = calculateNetUserPnlImbalance( market0, bank0, oraclePriceData, false ); console.log('pnlimbalance:', imbalance.toString()); assert(imbalance.eq(new BN(43462178048))); //44k! :o console.log( 'lastOraclePrice:', market0.amm.historicalOracleData.lastOraclePrice.toString() ); console.log('lastOracleValid:', market0.amm.lastOracleValid.toString()); console.log('lastUpdateSlot:', market0.amm.lastUpdateSlot.toString()); console.log('lastAskPriceTwap:', market0.amm.lastAskPriceTwap.toString()); console.log('lastBidPriceTwap:', market0.amm.lastBidPriceTwap.toString()); console.log( 'lastOraclePriceTwap:', market0.amm.historicalOracleData.lastOraclePriceTwap.toString() ); assert(market0.amm.lastOracleValid == true); }); it('update market imbalance limits', async () => { const marketIndex = 0; try { const txSig = await driftClient.updateAMMs([0]); bankrunContextWrapper.connection.printTxLogs(txSig); } catch (e) { console.error(e); } const market0 = driftClient.getPerpMarketAccount(marketIndex); assert(market0.expiryTs.eq(ZERO)); const oraclePriceData0 = driftClient.getOracleDataForPerpMarket( market0.marketIndex ); const prepegAMM = calculateUpdatedAMM(market0.amm, oraclePriceData0); console.log(prepegAMM.pegMultiplier.toString()); // assert(prepegAMM.pegMultiplier.eq(new BN(248126))); assert(market0.unrealizedPnlMaxImbalance.eq(ZERO)); await driftClient.updatePerpMarketContractTier(0, ContractTier.A); await driftClient.fetchAccounts(); // try { const tx1 = await driftClient.updatePerpMarketMaxImbalances( marketIndex, new BN(40000).mul(QUOTE_PRECISION), QUOTE_PRECISION, QUOTE_PRECISION ); bankrunContextWrapper.connection.printTxLogs(tx1); // } catch (e) { // console.error(e); // } await sleep(1000); driftClient.fetchAccounts(); const perpMarket = driftClient.getPerpMarketAccount(marketIndex); const quoteSpotMarket = driftClient.getSpotMarketAccount( QUOTE_SPOT_MARKET_INDEX ); const oraclePriceData = driftClient.getOracleDataForPerpMarket( market0.marketIndex ); const imbalance = calculateNetUserPnlImbalance( perpMarket, quoteSpotMarket, oraclePriceData, false ); console.log('pnlimbalance:', imbalance.toString()); assert(imbalance.eq(new BN(43462178048))); //44k still :o assert(perpMarket.insuranceClaim.revenueWithdrawSinceLastSettle.eq(ZERO)); console.log('pnlimbalance:', imbalance.toString()); assert( perpMarket.insuranceClaim.maxRevenueWithdrawPerPeriod.eq(QUOTE_PRECISION) ); // assert(perpMarket.insuranceClaim.lastRevenueWithdrawTs.lt(new BN(now))); assert( perpMarket.unrealizedPnlMaxImbalance.eq( new BN(40000).mul(QUOTE_PRECISION) ) ); assert(perpMarket.insuranceClaim.quoteSettledInsurance.eq(ZERO)); assert(perpMarket.insuranceClaim.quoteMaxInsurance.eq(QUOTE_PRECISION)); console.log(perpMarket.status); assert(isVariant(perpMarket.status, 'active')); console.log( 'totalExchangeFee:', perpMarket.amm.totalExchangeFee.toString() ); console.log('totalFee:', perpMarket.amm.totalFee.toString()); console.log('totalMMFee:', perpMarket.amm.totalMmFee.toString()); console.log( 'totalFeeMinusDistributions:', perpMarket.amm.totalFeeMinusDistributions.toString() ); await driftClientLoserUser.fetchAccounts(); const driftClientLoserUserLeverage = convertToNumber( driftClientLoserUser.getLeverage(), MARGIN_PRECISION ); const driftClientLoserUserLiqPrice = convertToNumber( driftClientLoserUser.liquidationPrice(0), PRICE_PRECISION ); console.log( 'driftClientLoserUser.getLeverage:', driftClientLoserUserLeverage, 'driftClientLoserUserLiqPrice:', driftClientLoserUserLiqPrice ); assert(driftClientLoserUserLeverage > 1); }); it('whale takes tiny profit', async () => { const market0 = driftClient.getPerpMarketAccount(0); assert(market0.marginRatioInitial == 1000); assert(market0.marginRatioMaintenance == 500); const oraclePriceData0 = driftClient.getOracleDataForPerpMarket( market0.marketIndex ); oraclePriceData0.confidence = new BN(0); //oraclePriceData0.price.div(new BN(1000)); console.log( 'market0.amm.totalFeeMinusDistributions:', market0.amm.totalFeeMinusDistributions.toString() ); assert(market0.amm.totalFeeMinusDistributions.lt(new BN('0'))); // assert(market0.amm.totalFeeMinusDistributions.eq(new BN('254313115'))); const prepegAMM = calculateUpdatedAMM(market0.amm, oraclePriceData0); const [bid, ask] = examineSpread(market0, oraclePriceData0); console.log( 'prepegAMM.totalFeeMinusDistributions:', prepegAMM.totalFeeMinusDistributions.toString() ); assert( prepegAMM.totalFeeMinusDistributions.eq( market0.amm.totalFeeMinusDistributions ) ); console.log(prepegAMM.pegMultiplier.toString()); console.log(bid.toString()); console.log(ask.toString()); assert(bid.eq(new BN('255252220'))); assert(prepegAMM.pegMultiplier.eq(new BN('260434864'))); // lowered by 1 for funding offset change assert(oraclePriceData0.price.eq(new BN('260500000'))); assert(ask.eq(new BN('585978467'))); const direction = PositionDirection.SHORT; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const price = bid.mul(new BN(1000)).div(new BN(1049)); // dont breach oracle price bands assert( driftClientLoser .getUserAccount() .perpPositions[0].baseAssetAmount.gt(ZERO) ); const orderParams = getMarketOrderParams({ marketIndex: 0, direction, baseAssetAmount, price, }); const txSig = await driftClientLoser.placeAndTakePerpOrder(orderParams); bankrunContextWrapper.connection.printTxLogs(txSig); const market1 = driftClient.getPerpMarketAccount(0); const oraclePriceData1 = driftClient.getOracleDataForPerpMarket( market1.marketIndex ); const prepegAMM1 = calculateUpdatedAMM(market0.amm, oraclePriceData1); console.log(prepegAMM1.pegMultiplier.toString()); assert(prepegAMM1.pegMultiplier.eq(new BN(260434864))); }); it('resolvePerpPnlDeficit', async () => { const bankIndex = 0; const marketIndex = 0; const usdcbalance = ( await bankrunContextWrapper.connection.getTokenAccount( userUSDCAccount.publicKey ) ).amount.toString(); console.log('usdc balance:', usdcbalance); assert(usdcbalance == '9998000000000'); await driftClient.initializeInsuranceFundStake(bankIndex); const ifStakePublicKey = getInsuranceFundStakeAccountPublicKey( driftClient.program.programId, bankrunContextWrapper.provider.wallet.publicKey, bankIndex ); const ifStakeAccount = (await driftClient.program.account.insuranceFundStake.fetch( ifStakePublicKey )) as InsuranceFundStake; assert(ifStakeAccount.marketIndex === bankIndex); assert( ifStakeAccount.authority.equals( bankrunContextWrapper.provider.wallet.publicKey ) ); const txSig = await driftClient.addInsuranceFundStake({ marketIndex: bankIndex, amount: QUOTE_PRECISION.add(QUOTE_PRECISION.div(new BN(100))), // $1.01 collateralAccountPublicKey: userUSDCAccount.publicKey, }); bankrunContextWrapper.connection.printTxLogs(txSig); const market0 = driftClient.getPerpMarketAccount(marketIndex); //will fail try { const txSig2 = await driftClient.resolvePerpPnlDeficit( bankIndex, marketIndex ); bankrunContextWrapper.connection.printTxLogs(txSig2); } catch (e) { console.error(e); } const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: new BN(12).mul(PERCENTAGE_PRECISION), oracleTwap5MinPercentDivergence: new BN(100).mul(PERCENTAGE_PRECISION), }, validity: { slotsBeforeStaleForAmm: new BN(100), slotsBeforeStaleForMargin: new BN(100), confidenceIntervalMaxSize: new BN(100000), tooVolatileRatio: new BN(1000), }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); const txSig2 = await driftClient.resolvePerpPnlDeficit( bankIndex, marketIndex ); bankrunContextWrapper.connection.printTxLogs(txSig2); const ifRecord: InsuranceFundRecord = eventSubscriber.getEventsArray( 'InsuranceFundRecord' )[0]; console.log(ifRecord); assert(ifRecord.vaultAmountBefore.eq(new BN('13000000000'))); assert(ifRecord.insuranceVaultAmountBefore.eq(new BN('1010000'))); assert(ifRecord.amount.eq(new BN('-1000000'))); assert(ifRecord.amount.eq(new BN('-1000000'))); await driftClient.fetchAccounts(); const perpMarket = driftClient.getPerpMarketAccount(marketIndex); const quoteSpotMarket = driftClient.getSpotMarketAccount( QUOTE_SPOT_MARKET_INDEX ); const oraclePriceData = driftClient.getOracleDataForPerpMarket( perpMarket.marketIndex ); const imbalance = calculateNetUserPnlImbalance( perpMarket, quoteSpotMarket, oraclePriceData, false ); console.log('pnlimbalance:', imbalance.toString()); // more volatile now based on runtime const expectedOffset = (43461178048 + 43461050931 + 43461032413) / 3; // 43454489193; // used to be 43454561797 assert(imbalance.lt(new BN(expectedOffset + 300000))); //44k still :o assert(imbalance.gt(new BN(expectedOffset - 300000))); //44k still :o console.log( 'revenueWithdrawSinceLastSettle:', perpMarket.insuranceClaim.revenueWithdrawSinceLastSettle.toString() ); assert( perpMarket.insuranceClaim.revenueWithdrawSinceLastSettle.eq( QUOTE_PRECISION ) ); console.log( 'market.insuranceClaim.maxRevenueWithdrawPerPeriod:', perpMarket.insuranceClaim.maxRevenueWithdrawPerPeriod.toString() ); assert( perpMarket.insuranceClaim.maxRevenueWithdrawPerPeriod.eq(QUOTE_PRECISION) ); assert( perpMarket.insuranceClaim.lastRevenueWithdrawTs.gt( market0.insuranceClaim.lastRevenueWithdrawTs ) ); assert( perpMarket.unrealizedPnlMaxImbalance.eq( new BN(40000).mul(QUOTE_PRECISION) ) ); assert(perpMarket.insuranceClaim.quoteSettledInsurance.eq(QUOTE_PRECISION)); assert(perpMarket.insuranceClaim.quoteMaxInsurance.eq(QUOTE_PRECISION)); console.log( 'market0.pnlPool.scaledBalance:', market0.pnlPool.scaledBalance.toString(), '->', perpMarket.pnlPool.scaledBalance.toString() ); assert(perpMarket.pnlPool.scaledBalance.gt(market0.pnlPool.scaledBalance)); console.log(perpMarket.status); assert(isVariant(perpMarket.status, 'active')); console.log( 'totalExchangeFee:', perpMarket.amm.totalExchangeFee.toString() ); console.log('totalFee:', perpMarket.amm.totalFee.toString()); console.log('totalMMFee:', perpMarket.amm.totalMmFee.toString()); console.log( 'totalFeeMinusDistributions:', perpMarket.amm.totalFeeMinusDistributions.toString() ); }); // it('liq and settle expired market position', async () => { // const marketIndex = 0; // const loserUser0 = driftClientLoser.getUserAccount(); // assert(loserUser0.perpPositions[0].baseAssetAmount.gt(0)); // assert(loserUser0.perpPositions[0].quoteAssetAmount.lt(0)); // // console.log(loserUser0.perpPositions[0]); // const liquidatorDriftClientUser = new User({ // driftClient: liquidatorDriftClient, // userAccountPublicKey: // await liquidatorDriftClient.getUserAccountPublicKey(), // }); // await liquidatorDriftClientUser.subscribe(); // const liquidatorDriftClientValue = convertToNumber( // liquidatorDriftClientUser.getTotalCollateral(), // QUOTE_PRECISION // ); // console.log( // 'liquidatorDriftClientValue:', // liquidatorDriftClientValue.toString() // ); // const txSigLiq = await liquidatorDriftClient.liquidatePerp( // await driftClientLoser.getUserAccountPublicKey(), // driftClientLoser.getUserAccount(), // marketIndex, // BASE_PRECISION.mul(new BN(290)) // ); // console.log(txSigLiq); // const liquidatorDriftClientValueAfter = convertToNumber( // liquidatorDriftClientUser.getTotalCollateral(), // QUOTE_PRECISION // ); // console.log( // 'liquidatorDriftClientValueAfter:', // liquidatorDriftClientValueAfter.toString() // ); // console.log('settle position driftClientLoser'); // const txSig = await driftClientLoser.settleExpiredPosition( // await driftClientLoser.getUserAccountPublicKey(), // driftClientLoser.getUserAccount(), // marketIndex // ); // await printTxLogs(connection, txSig); // console.log('settle pnl driftClientLoser'); // try { // await driftClient.settlePNL( // await driftClient.getUserAccountPublicKey(), // driftClient.getUserAccount(), // marketIndex // ); // } catch (e) { // // if (!e.toString().search('AnchorError occurred')) { // // assert(false); // // } // console.log('Cannot settle pnl under current market status'); // } // // const settleRecord = eventSubscriber.getEventsArray('SettlePnlRecord')[0]; // // console.log(settleRecord); // await driftClientLoser.fetchAccounts(); // const loserUser = driftClientLoser.getUserAccount(); // // console.log(loserUser.perpPositions[0]); // assert(loserUser.perpPositions[0].baseAssetAmount.eq(0)); // assert(loserUser.perpPositions[0].quoteAssetAmount.eq(0)); // const marketAfter0 = driftClient.getPerpMarketAccount(marketIndex); // const finalPnlResultMin0 = new BN(1415296436 - 11090); // const finalPnlResultMax0 = new BN(1415296436 + 111090); // console.log(marketAfter0.pnlPool.scaledBalance.toString()); // assert(marketAfter0.pnlPool.scaledBalance.gt(finalPnlResultMin0)); // assert(marketAfter0.pnlPool.scaledBalance.lt(finalPnlResultMax0)); // // const ammPnlResult = 0; // console.log('feePool:', marketAfter0.amm.feePool.scaledBalance.toString()); // console.log( // 'totalExchangeFee:', // marketAfter0.amm.totalExchangeFee.toString() // ); // assert(marketAfter0.amm.feePool.scaledBalance.eq(new BN(4356250))); // await liquidatorDriftClientUser.unsubscribe(); // }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/switchOracle.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { PublicKey } from '@solana/web3.js'; import { TestClient, BN, EventSubscriber, OracleSource, OracleInfo, } from '../sdk/src'; import { createFundedKeyPair, createUserWithUSDCAccount, initializeQuoteSpotMarket, initializeSolSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpers'; import { PRICE_PRECISION, PEG_PRECISION, Wallet, DriftClient } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('switch oracles', () => { const chProgram = anchor.workspace.Drift as Program; let admin: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let solOracle: PublicKey; let usdcMint; const usdcAmount = new BN(10 * 10 ** 6); const largeUsdcAmount = new BN(10_000 * 10 ** 6); const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); let marketIndexes: number[]; let spotMarketIndexes: number[]; let oracleInfos: OracleInfo[]; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); await mockUserUSDCAccount(usdcMint, largeUsdcAmount, bankrunContextWrapper); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 30); marketIndexes = [0]; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solOracle, source: OracleSource.PYTH }]; admin = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await admin.initialize(usdcMint.publicKey, true); await admin.subscribe(); await initializeQuoteSpotMarket(admin, usdcMint.publicKey); await initializeSolSpotMarket(admin, solOracle); const periodicity = new BN(0); await admin.initializePerpMarket( 0, solOracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(30 * PEG_PRECISION.toNumber()) ); }); beforeEach(async () => { await admin.updateSpotMarketOracle(1, solOracle, OracleSource.PYTH); await admin.updatePerpMarketOracle(0, solOracle, OracleSource.PYTH); }); after(async () => { await admin.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('polling', async () => { const [driftClient, _usdcAccount, _userKeyPair] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); const newSolOracle = await mockOracleNoProgram(bankrunContextWrapper, 100); await admin.updatePerpMarketOracle(0, newSolOracle, OracleSource.PYTH); await admin.fetchAccounts(); const perpOraclePriceBefore = await driftClient.getOracleDataForPerpMarket( 0 ); assert(perpOraclePriceBefore.price.eq(PRICE_PRECISION.muln(30))); await sleep(1000); const perpOraclePriceAfter = await driftClient.getOracleDataForPerpMarket( 0 ); assert(perpOraclePriceAfter.price.eq(PRICE_PRECISION.muln(100))); await admin.updateSpotMarketOracle(1, newSolOracle, OracleSource.PYTH); await driftClient.fetchAccounts(); const spotOraclePriceBefore = await driftClient.getOracleDataForSpotMarket( 1 ); assert(spotOraclePriceBefore.price.eq(PRICE_PRECISION.muln(30))); await sleep(1000); const spotOraclePriceAfter = await driftClient.getOracleDataForSpotMarket( 1 ); console.log(spotOraclePriceAfter.price.toString()); assert(spotOraclePriceAfter.price.eq(PRICE_PRECISION.muln(100))); await driftClient.unsubscribe(); }); it('ws', async () => { const userKeyPair = await createFundedKeyPair(bankrunContextWrapper); const driftClient = new DriftClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(userKeyPair), programID: admin.program.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'websocket', }, }); await driftClient.subscribe(); const newSolOracle = await mockOracleNoProgram(bankrunContextWrapper, 100); await admin.updatePerpMarketOracle(0, newSolOracle, OracleSource.PYTH); const perpOraclePriceBefore = await driftClient.getOracleDataForPerpMarket( 0 ); console.log('oraclePriceBefore', perpOraclePriceBefore.price.toNumber()); assert(perpOraclePriceBefore.price.eq(PRICE_PRECISION.muln(30))); await sleep(5000); const perpOraclePriceAfter = await driftClient.getOracleDataForPerpMarket( 0 ); assert(perpOraclePriceAfter.price.eq(PRICE_PRECISION.muln(100))); await admin.updateSpotMarketOracle(1, newSolOracle, OracleSource.PYTH); const spotOraclePriceBefore = await driftClient.getOracleDataForSpotMarket( 1 ); assert(spotOraclePriceBefore.price.eq(PRICE_PRECISION.muln(30))); await sleep(1000); const spotOraclePriceAfter = await driftClient.getOracleDataForSpotMarket( 1 ); assert(spotOraclePriceAfter.price.eq(PRICE_PRECISION.muln(100))); await driftClient.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/pythLazer.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { BulkAccountLoader, OracleSource, TestClient, assert, getPythLazerOraclePublicKey, } from '../sdk/src'; import { PublicKey, TransactionMessage, VersionedTransaction, } from '@solana/web3.js'; import { initializeQuoteSpotMarket, mockUSDCMint, } from './testHelpersLocalValidator'; import { Wallet, loadKeypair, EventSubscriber } from '../sdk/src'; import { PYTH_LAZER_HEX_STRING_BTC, PYTH_LAZER_HEX_STRING_MULTI, PYTH_LAZER_HEX_STRING_SOL, } from './pythLazerData'; describe('pyth lazer oracles', () => { const provider = anchor.AnchorProvider.local(undefined, { commitment: 'confirmed', preflightCommitment: 'confirmed', }); const connection = provider.connection; anchor.setProvider(provider); const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; const bulkAccountLoader = new BulkAccountLoader(connection, 'confirmed', 0); let usdcMint; const feedId = 3; let solUsd: PublicKey; //@ts-ignore const eventSubscriber = new EventSubscriber(connection, chProgram, { commitment: 'recent', }); eventSubscriber.subscribe(); before(async () => { // use bankrun builtin function to start solana program test await provider.connection.requestAirdrop( provider.wallet.publicKey, 10 ** 9 ); usdcMint = await mockUSDCMint(provider); solUsd = getPythLazerOraclePublicKey(chProgram.programId, feedId); const marketIndexes = [0]; const spotMarketIndexes = [0, 1]; const oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; driftClient = new TestClient({ connection, //@ts-ignore wallet: new Wallet(loadKeypair(process.env.ANCHOR_WALLET)), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); }); after(async () => { await driftClient.unsubscribe(); }); it('init feed', async () => { await driftClient.initializePythLazerOracle(1); await driftClient.initializePythLazerOracle(2); await driftClient.initializePythLazerOracle(6); }); it('crank', async () => { const ixs = await driftClient.getPostPythLazerOracleUpdateIxs( [1], PYTH_LAZER_HEX_STRING_BTC ); const message = new TransactionMessage({ instructions: ixs, payerKey: driftClient.wallet.payer.publicKey, recentBlockhash: (await connection.getLatestBlockhash()).blockhash, }).compileToV0Message(); const tx = new VersionedTransaction(message); const simResult = await provider.connection.simulateTransaction(tx); console.log(simResult.value.logs); assert(simResult.value.err === null); }); it('crank multi', async () => { const ixs = driftClient.getPostPythLazerOracleUpdateIxs( [1, 2, 6], PYTH_LAZER_HEX_STRING_MULTI ); const message = new TransactionMessage({ instructions: ixs, payerKey: driftClient.wallet.payer.publicKey, recentBlockhash: (await connection.getLatestBlockhash()).blockhash, }).compileToV0Message(); const tx = new VersionedTransaction(message); const simResult = await provider.connection.simulateTransaction(tx); console.log(simResult.value.logs); assert(simResult.value.err === null); }); it('fails on wrong message passed', async () => { const ixs = driftClient.getPostPythLazerOracleUpdateIxs( [1], PYTH_LAZER_HEX_STRING_SOL ); const message = new TransactionMessage({ instructions: ixs, payerKey: driftClient.wallet.payer.publicKey, recentBlockhash: (await connection.getLatestBlockhash()).blockhash, }).compileToV0Message(); const tx = new VersionedTransaction(message); const simResult = await provider.connection.simulateTransaction(tx); console.log(simResult.value.logs); assert(simResult.value.err !== null); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/userDelegate.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { QUOTE_SPOT_MARKET_INDEX, TestClient, BN, EventSubscriber, PRICE_PRECISION, OracleSource, PositionDirection, Wallet, MarketStatus, } from '../sdk/src'; import { createFundedKeyPair, initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } from './testHelpers'; import { assert } from 'chai'; import { Keypair } from '@solana/web3.js'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('user delegate', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; const usdcAmount = new BN(10 * 10 ** 6); let delegateKeyPair: Keypair; let delegateDriftClient: TestClient; let delegateUsdcAccount: Keypair; const marketIndexes = [0]; const spotMarketIndexes = [0]; let solUsd; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetAmount = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetAmount = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos: [ { source: OracleSource.PYTH, publicKey: solUsd, }, ], userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(60 * 60); // 1 HOUR await driftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity ); await driftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); const subAccountId = 0; const name = 'CRISP'; await driftClient.initializeUserAccount(subAccountId, name); delegateKeyPair = await createFundedKeyPair(bankrunContextWrapper); }); after(async () => { await driftClient.unsubscribe(); await eventSubscriber.unsubscribe(); await delegateDriftClient.unsubscribe(); }); it('Update delegate', async () => { await driftClient.updateUserDelegate(delegateKeyPair.publicKey); await driftClient.fetchAccounts(); assert( driftClient.getUserAccount().delegate.equals(delegateKeyPair.publicKey) ); delegateDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(delegateKeyPair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, oracleInfos: [ { source: OracleSource.PYTH, publicKey: solUsd, }, ], authority: bankrunContextWrapper.provider.wallet.publicKey, authoritySubAccountMap: new Map().set( bankrunContextWrapper.provider.wallet.publicKey, [0] ), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await delegateDriftClient.subscribe(); }); it('Deposit', async () => { delegateUsdcAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, delegateKeyPair.publicKey ); await delegateDriftClient.deposit( usdcAmount, QUOTE_SPOT_MARKET_INDEX, delegateUsdcAccount.publicKey ); assert(delegateDriftClient.getQuoteAssetTokenAmount().eq(usdcAmount)); }); it('Withdraw', async () => { let caughtError = false; try { await delegateDriftClient.withdraw( usdcAmount, QUOTE_SPOT_MARKET_INDEX, delegateUsdcAccount.publicKey ); } catch (e) { caughtError = true; } assert(caughtError); }); it('Open position', async () => { await delegateDriftClient.openPosition( PositionDirection.LONG, usdcAmount, 0 ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/cappedSymFunding.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { getFeedData, initUserAccounts, mockOracle, mockUserUSDCAccount, mockUSDCMint, setFeedPrice, initializeQuoteSpotMarket, sleep, printTxLogs, } from './testHelpers'; import { TestClient, BN, QUOTE_SPOT_MARKET_INDEX, PRICE_PRECISION, FUNDING_RATE_BUFFER_PRECISION, PEG_PRECISION, User, PositionDirection, QUOTE_PRECISION, AMM_RESERVE_PRECISION, calculateReservePrice, convertToNumber, ExchangeStatus, BASE_PRECISION, OracleSource, isVariant, ContractTier, } from '../sdk/src'; import { Program } from '@coral-xyz/anchor'; import { Keypair, PublicKey } from '@solana/web3.js'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; async function updateFundingRateHelper( driftClient: TestClient, marketIndex: number, priceFeedAddress: PublicKey, prices: Array<number> ) { for (let i = 0; i < prices.length; i++) { await new Promise((r) => setTimeout(r, 1000)); // wait 1 second const newprice = prices[i]; await setFeedPrice(anchor.workspace.Pyth, newprice, priceFeedAddress); // just to update funding trade .1 cent // await driftClient.openPosition( // PositionDirection.LONG, // QUOTE_PRECISION.div(new BN(100)), // marketIndex // ); await driftClient.fetchAccounts(); const marketData0 = driftClient.getPerpMarketAccount(marketIndex); const ammAccountState0 = marketData0.amm; const oraclePx0 = await getFeedData( anchor.workspace.Pyth, ammAccountState0.oracle ); const priceSpread0 = convertToNumber(ammAccountState0.lastMarkPriceTwap) - convertToNumber( ammAccountState0.historicalOracleData.lastOraclePriceTwap ); const frontEndFundingCalc0 = priceSpread0 / oraclePx0.twap / (24 * 3600); console.log( 'funding rate frontend calc0:', frontEndFundingCalc0, 'markTwap0:', ammAccountState0.lastMarkPriceTwap.toNumber() / PRICE_PRECISION.toNumber(), 'oracleTwap0:', ammAccountState0.historicalOracleData.lastOraclePriceTwap.toNumber() / PRICE_PRECISION.toNumber(), 'markTwap0:', ammAccountState0.lastMarkPriceTwap.toNumber(), 'oracleTwapPyth:', oraclePx0.twap, 'priceSpread', priceSpread0 ); const cumulativeFundingRateLongOld = ammAccountState0.cumulativeFundingRateLong; const cumulativeFundingRateShortOld = ammAccountState0.cumulativeFundingRateShort; const state = driftClient.getStateAccount(); assert(state.exchangeStatus === ExchangeStatus.ACTIVE); const market = driftClient.getPerpMarketAccount(marketIndex); assert(isVariant(market.status, 'active')); await driftClient.updateFundingRate(marketIndex, priceFeedAddress); const CONVERSION_SCALE = FUNDING_RATE_BUFFER_PRECISION.mul(PRICE_PRECISION); await driftClient.fetchAccounts(); const marketData = driftClient.getPerpMarketAccount(marketIndex); const ammAccountState = marketData.amm; const peroidicity = marketData.amm.fundingPeriod; const lastFundingRate = convertToNumber( ammAccountState.lastFundingRate, CONVERSION_SCALE ); console.log('last funding rate:', lastFundingRate); console.log( 'cumfunding rate long', convertToNumber( ammAccountState.cumulativeFundingRateLong, CONVERSION_SCALE ), 'cumfunding rate short', convertToNumber( ammAccountState.cumulativeFundingRateShort, CONVERSION_SCALE ) ); const lastFundingLong = ammAccountState.cumulativeFundingRateLong .sub(cumulativeFundingRateLongOld) .abs(); const lastFundingShort = ammAccountState.cumulativeFundingRateShort .sub(cumulativeFundingRateShortOld) .abs(); assert(ammAccountState.lastFundingRate.abs().gte(lastFundingLong.abs())); console.log( convertToNumber(ammAccountState.lastFundingRate.abs()) / FUNDING_RATE_BUFFER_PRECISION.toNumber(), '>=', convertToNumber(lastFundingShort.abs()) / FUNDING_RATE_BUFFER_PRECISION.toNumber() ); assert(ammAccountState.lastFundingRate.abs().gte(lastFundingShort.abs())); const oraclePx = await getFeedData( anchor.workspace.Pyth, ammAccountState.oracle ); await new Promise((r) => setTimeout(r, 1000)); // wait 1 second const priceSpread = ammAccountState.lastMarkPriceTwap.toNumber() / PRICE_PRECISION.toNumber() - ammAccountState.historicalOracleData.lastOraclePriceTwap.toNumber() / PRICE_PRECISION.toNumber(); const frontEndFundingCalc = priceSpread / ((24 * 3600) / Math.max(1, peroidicity.toNumber())); console.log( 'funding rate frontend calc:', frontEndFundingCalc, 'markTwap:', ammAccountState.lastMarkPriceTwap.toNumber() / PRICE_PRECISION.toNumber(), 'oracleTwap:', ammAccountState.historicalOracleData.lastOraclePriceTwap.toNumber() / PRICE_PRECISION.toNumber(), 'markTwap:', ammAccountState.lastMarkPriceTwap.toNumber(), 'oracleTwapPyth:', oraclePx.twap, 'priceSpread:', priceSpread ); const s = new Date(ammAccountState.lastMarkPriceTwapTs.toNumber() * 1000); const sdate = s.toLocaleDateString('en-US'); const stime = s.toLocaleTimeString('en-US'); console.log('funding rate timestamp:', sdate, stime); // assert(Math.abs(frontEndFundingCalc - lastFundingRate) < 9e-6); } } async function cappedSymFundingScenario( rollingMarketNum: number, driftClient: TestClient, userAccount: User, driftClient2: TestClient, userAccount2: User, marketIndex: number, kSqrt: BN, priceAction: Array<number>, longShortSizes: Array<number>, fees = 0 ) { const priceFeedAddress = await mockOracle(priceAction[0], -10); const periodicity = new BN(0); await driftClient.initializePerpMarket( rollingMarketNum, priceFeedAddress, kSqrt, kSqrt, periodicity, new BN(priceAction[0] * PEG_PRECISION.toNumber()) ); await driftClient.updatePerpMarketContractTier( rollingMarketNum, ContractTier.A ); await driftClient.accountSubscriber.addOracle({ source: OracleSource.PYTH, publicKey: priceFeedAddress, }); await driftClient2.accountSubscriber.addOracle({ source: OracleSource.PYTH, publicKey: priceFeedAddress, }); await sleep(2500); if (fees && fees > 0) { await driftClient.updateExchangeStatus(ExchangeStatus.FUNDING_PAUSED); console.log('spawn some fee pool'); await driftClient.openPosition( PositionDirection.LONG, BASE_PRECISION.mul(new BN(100)), marketIndex ); await driftClient.closePosition(marketIndex); await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); await driftClient.updateExchangeStatus(ExchangeStatus.ACTIVE); } await driftClient.fetchAccounts(); const oracleData = driftClient.getOracleDataForPerpMarket(0); console.log( 'PRICE', convertToNumber( calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ) ), 'oracleData:', convertToNumber(oracleData.price), '+/-', convertToNumber(oracleData.confidence) ); console.log(ExchangeStatus.FUNDING_PAUSED); console.log(ExchangeStatus.ACTIVE); await driftClient.updateExchangeStatus(ExchangeStatus.FUNDING_PAUSED); await driftClient.fetchAccounts(); if (longShortSizes[0] !== 0) { console.log('driftClient.openPosition'); const txSig = await driftClient.openPosition( PositionDirection.LONG, BASE_PRECISION.mul(new BN(longShortSizes[0])), marketIndex ); await printTxLogs(driftClient.connection, txSig); } // try{ if (longShortSizes[1] !== 0) { console.log('driftClient2.openPosition'); await driftClient2.openPosition( PositionDirection.SHORT, BASE_PRECISION.mul(new BN(longShortSizes[1])), marketIndex ); } await sleep(1500); await driftClient.fetchAccounts(); await driftClient2.fetchAccounts(); await sleep(1500); console.log(longShortSizes[0], longShortSizes[1]); await userAccount.fetchAccounts(); const uA = userAccount.getUserAccount(); console.log( 'userAccount.getTotalPositionValue():', userAccount.getTotalPerpPositionLiability().toString(), uA.perpPositions[0].marketIndex, ':', uA.perpPositions[0].baseAssetAmount.toString(), '/', uA.perpPositions[0].quoteAssetAmount.toString() ); await userAccount2.fetchAccounts(); const uA2 = userAccount2.getUserAccount(); console.log( 'userAccount2.getTotalPositionValue():', userAccount2.getTotalPerpPositionLiability().toString(), uA2.perpPositions[0].marketIndex, ':', uA2.perpPositions[0].baseAssetAmount.toString(), '/', uA2.perpPositions[0].quoteAssetAmount.toString() ); if (longShortSizes[0] != 0) { assert(!userAccount.getTotalPerpPositionLiability().eq(new BN(0))); } else { assert(userAccount.getTotalPerpPositionLiability().eq(new BN(0))); } if (longShortSizes[1] != 0) { assert(!userAccount2.getTotalPerpPositionLiability().eq(new BN(0))); } else { assert(userAccount2.getTotalPerpPositionLiability().eq(new BN(0))); } await driftClient.fetchAccounts(); const market = driftClient.getPerpMarketAccount(marketIndex); await driftClient.updateExchangeStatus(ExchangeStatus.ACTIVE); console.log('priceAction update', priceAction, priceAction.slice(1)); await updateFundingRateHelper( driftClient, marketIndex, market.amm.oracle, priceAction.slice(1) ); await driftClient.fetchAccounts(); await driftClient2.fetchAccounts(); const marketNew = driftClient.getPerpMarketAccount(marketIndex); const fundingRateLong = marketNew.amm.cumulativeFundingRateLong; //.sub(prevFRL); const fundingRateShort = marketNew.amm.cumulativeFundingRateShort; //.sub(prevFRS); console.log( 'fundingRateLong', convertToNumber( fundingRateLong, PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), 'fundingRateShort', convertToNumber( fundingRateShort, PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ) ); console.log( 'baseAssetAmountLong', convertToNumber(marketNew.amm.baseAssetAmountLong, AMM_RESERVE_PRECISION), 'baseAssetAmountShort', convertToNumber(marketNew.amm.baseAssetAmountShort, AMM_RESERVE_PRECISION), 'totalFee', convertToNumber(marketNew.amm.totalFee, QUOTE_PRECISION), 'totalFeeMinusDistributions', convertToNumber(marketNew.amm.totalFeeMinusDistributions, QUOTE_PRECISION) ); const fundingPnLForLongs = marketNew.amm.baseAssetAmountLong .mul(fundingRateLong) .mul(new BN(-1)); const fundingPnLForShorts = marketNew.amm.baseAssetAmountShort .mul(fundingRateShort) .mul(new BN(-1)); const precisionFundingPay = AMM_RESERVE_PRECISION; console.log( 'fundingPnLForLongs', convertToNumber( fundingPnLForLongs.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ), 'fundingPnLForShorts', convertToNumber( fundingPnLForShorts.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ) ); // more dollars long than short assert(!fundingRateLong.eq(new BN(0))); assert(!fundingRateShort.eq(new BN(0))); // await driftClient.moveAmmToPrice( // marketIndex, // new BN(priceAction[1] * PRICE_PRECISION.toNumber()) // ); setFeedPrice(anchor.workspace.Pyth, priceAction[0], priceFeedAddress); await driftClient.updateExchangeStatus(ExchangeStatus.FUNDING_PAUSED); assert(fundingRateShort.lte(fundingRateLong)); if (longShortSizes[0] !== 0) { await driftClient.closePosition(marketIndex); await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); } if (longShortSizes[1] !== 0) { await driftClient2.closePosition(marketIndex); await driftClient2.settlePNL( await driftClient2.getUserAccountPublicKey(), driftClient2.getUserAccount(), marketIndex ); } await driftClient.updateExchangeStatus(ExchangeStatus.ACTIVE); setFeedPrice(anchor.workspace.Pyth, priceAction[1], priceFeedAddress); await sleep(2000); await driftClient.fetchAccounts(); await driftClient2.fetchAccounts(); await userAccount.fetchAccounts(); await userAccount2.fetchAccounts(); console.log( userAccount.getTotalPerpPositionLiability().toString(), ',', userAccount2.getTotalPerpPositionLiability().toString() ); assert(userAccount.getTotalPerpPositionLiability().eq(new BN(0))); assert(userAccount2.getTotalPerpPositionLiability().eq(new BN(0))); return [ fundingRateLong, fundingRateShort, fundingPnLForLongs, fundingPnLForShorts, marketNew.amm.totalFee, marketNew.amm.totalFeeMinusDistributions, ]; } describe('capped funding', () => { const chProgram = anchor.workspace.Drift as Program; let bulkAccountLoader: TestBulkAccountLoader; let driftClient: TestClient; let driftClient2: TestClient; let usdcMint: Keypair; let userUSDCAccount: Keypair; const ammInitialBaseAssetAmount = new anchor.BN(5 * 10 ** 13).mul( PRICE_PRECISION ); const usdcAmount = new BN(100000 * 10 ** 6); let userAccount: User; let userAccount2: User; let rollingMarketNum = 0; before(async () => { const context = await startAnchor('', [], []); const bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); const spotMarketIndexes = [0]; const marketIndexes = Array.from({ length: 15 }, (_, i) => i); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, subAccountIds: [], perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.fetchAccounts(); await driftClient.updatePerpAuctionDuration(new BN(0)); await driftClient.initializeUserAccount(); userAccount = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await userAccount.subscribe(); await driftClient.fetchAccounts(); await driftClient.fetchAccounts(); await driftClient.deposit( usdcAmount, QUOTE_SPOT_MARKET_INDEX, userUSDCAccount.publicKey ); // create <NUM_USERS> users with 10k that collectively do <NUM_EVENTS> actions const [_userUSDCAccounts, _user_keys, driftClients, userAccountInfos] = await initUserAccounts( 1, usdcMint, usdcAmount, bankrunContextWrapper, marketIndexes, spotMarketIndexes, [], bulkAccountLoader ); driftClient2 = driftClients[0]; userAccount2 = userAccountInfos[0]; }); it('capped sym funding: ($1 long, $200 short, oracle < mark)', async () => { const marketIndex = rollingMarketNum; rollingMarketNum += 1; const [ fundingRateLong, fundingRateShort, fundingPnLForLongs, fundingPnLForShorts, totalFee, cumulativeFee, ] = await cappedSymFundingScenario( rollingMarketNum - 1, driftClient, userAccount, driftClient2, userAccount2, marketIndex, ammInitialBaseAssetAmount, [40, 36.5], [1, 200] ); assert(fundingRateLong.abs().gt(fundingRateShort.abs())); assert(fundingRateLong.gt(new BN(0))); assert(fundingRateShort.gt(new BN(0))); assert(fundingPnLForLongs.abs().lt(fundingPnLForShorts.abs())); const feeAlloced = convertToNumber(totalFee, QUOTE_PRECISION) - convertToNumber(cumulativeFee, QUOTE_PRECISION); const precisionFundingPay = AMM_RESERVE_PRECISION; const fundingPnLForLongsNum = convertToNumber( fundingPnLForLongs.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); const fundingPnLForShortsNum = convertToNumber( fundingPnLForShorts.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); console.log( feeAlloced, '+', Math.abs(fundingPnLForLongsNum), '>=', fundingPnLForShortsNum ); assert( feeAlloced + Math.abs(fundingPnLForLongsNum) >= fundingPnLForShortsNum ); }); it('capped sym funding: ($0 long, $200 short, oracle < mark)', async () => { const marketIndex = rollingMarketNum; rollingMarketNum += 1; const [ fundingRateLong, fundingRateShort, fundingPnLForLongs, fundingPnLForShorts, totalFee, cumulativeFee, ] = await cappedSymFundingScenario( rollingMarketNum - 1, driftClient, userAccount, driftClient2, userAccount2, marketIndex, ammInitialBaseAssetAmount, [40, 36.5], [0, 200] ); assert(fundingRateLong.abs().gt(fundingRateShort.abs())); assert(fundingRateLong.gt(new BN(0))); assert(fundingRateShort.gt(new BN(0))); assert(fundingPnLForLongs.abs().lt(fundingPnLForShorts.abs())); const feeAlloced = convertToNumber(totalFee, QUOTE_PRECISION) - convertToNumber(cumulativeFee, QUOTE_PRECISION); const precisionFundingPay = AMM_RESERVE_PRECISION; const fundingPnLForLongsNum = convertToNumber( fundingPnLForLongs.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); const fundingPnLForShortsNum = convertToNumber( fundingPnLForShorts.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); console.log( feeAlloced, '+', Math.abs(fundingPnLForLongsNum), '>=', fundingPnLForShortsNum ); assert( feeAlloced + Math.abs(fundingPnLForLongsNum) >= fundingPnLForShortsNum ); }); it('capped sym funding: ($1 long, $200 short, oracle > mark)', async () => { // symmetric is taking fees const marketIndex = rollingMarketNum; rollingMarketNum += 1; const [ fundingRateLong, fundingRateShort, fundingPnLForLongs, fundingPnLForShorts, totalFee, cumulativeFee, ] = await cappedSymFundingScenario( rollingMarketNum - 1, driftClient, userAccount, driftClient2, userAccount2, marketIndex, ammInitialBaseAssetAmount, [40, 43.5], [1, 200] ); assert(fundingRateLong.abs().eq(fundingRateShort.abs())); assert(fundingRateLong.lt(new BN(0))); assert(fundingRateShort.lt(new BN(0))); assert(fundingPnLForLongs.abs().lt(fundingPnLForShorts.abs())); const feeAlloced = convertToNumber(totalFee, QUOTE_PRECISION) - convertToNumber(cumulativeFee, QUOTE_PRECISION); const precisionFundingPay = AMM_RESERVE_PRECISION; const fundingPnLForLongsNum = convertToNumber( fundingPnLForLongs.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); const fundingPnLForShortsNum = convertToNumber( fundingPnLForShorts.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); console.log( feeAlloced, '+', Math.abs(fundingPnLForLongsNum), '>=', fundingPnLForShortsNum ); assert( feeAlloced + Math.abs(fundingPnLForLongsNum) >= fundingPnLForShortsNum ); }); it('capped sym funding: ($200 long, $1 short, oracle > mark)', async () => { const marketIndex = rollingMarketNum; rollingMarketNum += 1; const [ fundingRateLong, fundingRateShort, fundingPnLForLongs, fundingPnLForShorts, totalFee, cumulativeFee, ] = await cappedSymFundingScenario( rollingMarketNum - 1, driftClient, userAccount, driftClient2, userAccount2, marketIndex, ammInitialBaseAssetAmount, [41, 42.5], [200, 1] ); assert(fundingRateShort.abs().gt(fundingRateLong.abs())); assert(fundingRateLong.lt(new BN(0))); assert(fundingRateShort.lt(new BN(0))); assert(fundingPnLForLongs.gt(new BN(0))); assert(fundingPnLForShorts.lt(new BN(0))); assert(fundingPnLForShorts.abs().lt(fundingPnLForLongs.abs())); const feeAlloced = convertToNumber(totalFee, QUOTE_PRECISION) - convertToNumber(cumulativeFee, QUOTE_PRECISION); const precisionFundingPay = AMM_RESERVE_PRECISION; const fundingPnLForLongsNum = convertToNumber( fundingPnLForLongs.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); const fundingPnLForShortsNum = convertToNumber( fundingPnLForShorts.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); // amount of money inflow must be greater than or equal to money outflow console.log( feeAlloced, '+', Math.abs(fundingPnLForShortsNum), '>=', fundingPnLForLongsNum ); assert( feeAlloced + Math.abs(fundingPnLForShortsNum) >= fundingPnLForLongsNum ); }); it('capped sym funding: ($2000 long, $1000 short, oracle > mark), clamped to ~3.03% price spread', async () => { const marketIndex = rollingMarketNum; rollingMarketNum += 1; const [ fundingRateLong, fundingRateShort, fundingPnLForLongs, fundingPnLForShorts, totalFee, cumulativeFee, ] = await cappedSymFundingScenario( rollingMarketNum - 1, driftClient, userAccount, driftClient2, userAccount2, marketIndex, ammInitialBaseAssetAmount, [41, 44.5], [50, 25], 10000 ); //ensure it was clamped :) await driftClient.fetchAccounts(); const marketNew = driftClient.getPerpMarketAccount(marketIndex); console.log( 'marketNew.amm.historicalOracleData.lastOraclePriceTwap:', marketNew.amm.historicalOracleData.lastOraclePriceTwap.toString() ); const clampedFundingRatePct = new BN( (0.03 * PRICE_PRECISION.toNumber()) / 24 ).mul(FUNDING_RATE_BUFFER_PRECISION); const clampedFundingRate = new BN(44.5 * PRICE_PRECISION.toNumber()) .mul(FUNDING_RATE_BUFFER_PRECISION) .div(new BN(24)) .div(new BN(33)); console.log( 'clamped funding:', convertToNumber(clampedFundingRate) / FUNDING_RATE_BUFFER_PRECISION.toNumber(), 'hourly pct:', convertToNumber(clampedFundingRatePct) / FUNDING_RATE_BUFFER_PRECISION.toNumber() ); console.log( 'short funding:', convertToNumber(fundingRateShort) / FUNDING_RATE_BUFFER_PRECISION.toNumber() ); assert(fundingRateShort.abs().eq(fundingRateLong.abs())); console.log(fundingRateShort.abs().toString()); console.log(clampedFundingRate.toString()); assert( fundingRateShort.abs().sub(clampedFundingRate).abs().lt(new BN(1000)) ); assert(fundingRateLong.lt(new BN(0))); assert(fundingRateShort.lt(new BN(0))); assert(fundingPnLForLongs.gt(new BN(0))); assert(fundingPnLForShorts.lt(new BN(0))); assert(fundingPnLForShorts.abs().lt(fundingPnLForLongs.abs())); const feeAlloced = convertToNumber(totalFee, QUOTE_PRECISION) - convertToNumber(cumulativeFee, QUOTE_PRECISION); const precisionFundingPay = AMM_RESERVE_PRECISION; const fundingPnLForLongsNum = convertToNumber( fundingPnLForLongs.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); const fundingPnLForShortsNum = convertToNumber( fundingPnLForShorts.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); // amount of money inflow must be greater than or equal to money outflow console.log( feeAlloced, '+', Math.abs(fundingPnLForShortsNum), '>=', fundingPnLForLongsNum ); assert( Math.abs( feeAlloced + Math.abs(fundingPnLForShortsNum) - fundingPnLForLongsNum ) < 1e-6 ); }); it('capped sym funding: ($20000 long, $1000 short, oracle > mark), clamped to ~3.03% price spread, fee pool drain', async () => { const marketIndex = rollingMarketNum; rollingMarketNum += 1; const [ fundingRateLong, fundingRateShort, fundingPnLForLongs, fundingPnLForShorts, totalFee, cumulativeFee, ] = await cappedSymFundingScenario( rollingMarketNum - 1, driftClient, userAccount, driftClient2, userAccount2, marketIndex, ammInitialBaseAssetAmount, [41, 45.1], [50, 25] ); //ensure it was clamped :) await driftClient.fetchAccounts(); const _marketNew = driftClient.getPerpMarketAccount(marketIndex); const clampedFundingRatePct = new BN( (0.03 * PRICE_PRECISION.toNumber()) / 24 ).mul(FUNDING_RATE_BUFFER_PRECISION); const clampedFundingRate = new BN(45.1 * PRICE_PRECISION.toNumber()) .mul(FUNDING_RATE_BUFFER_PRECISION) .div(new BN(24)) .div(new BN(33)); console.log( 'clamped funding:', convertToNumber(clampedFundingRate) / FUNDING_RATE_BUFFER_PRECISION.toNumber(), 'hourly pct:', convertToNumber(clampedFundingRatePct) / FUNDING_RATE_BUFFER_PRECISION.toNumber() ); console.log( 'short funding:', convertToNumber(fundingRateShort) / FUNDING_RATE_BUFFER_PRECISION.toNumber() ); assert(fundingRateShort.abs().gt(fundingRateLong.abs())); // assert(fundingRateShort.abs().gt(clampedFundingRate)); assert( fundingRateShort.abs().sub(clampedFundingRate).abs().lt(new BN(1000)) ); assert(fundingRateLong.lt(new BN(0))); assert(fundingRateShort.lt(new BN(0))); assert(fundingPnLForLongs.gt(new BN(0))); assert(fundingPnLForShorts.lt(new BN(0))); assert(fundingPnLForShorts.abs().lt(fundingPnLForLongs.abs())); const feeAlloced = convertToNumber(totalFee, QUOTE_PRECISION) - convertToNumber(cumulativeFee, QUOTE_PRECISION); assert(cumulativeFee.gt(totalFee.div(new BN(2)))); assert( cumulativeFee.gt(totalFee.mul(new BN(2)).div(new BN(3)).sub(new BN(1))) ); const precisionFundingPay = AMM_RESERVE_PRECISION; const fundingPnLForLongsNum = convertToNumber( fundingPnLForLongs.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); const fundingPnLForShortsNum = convertToNumber( fundingPnLForShorts.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); // amount of money inflow must be greater than or equal to money outflow console.log( feeAlloced, '+', Math.abs(fundingPnLForShortsNum), '>=', fundingPnLForLongsNum ); assert( feeAlloced + Math.abs(fundingPnLForShortsNum) >= fundingPnLForLongsNum + 1e-6 ); }); it('capped sym funding: ($2000 long, $1000 short, oracle > mark)', async () => { const marketIndex = rollingMarketNum; rollingMarketNum += 1; const [ fundingRateLong, fundingRateShort, fundingPnLForLongs, fundingPnLForShorts, totalFee, cumulativeFee, ] = await cappedSymFundingScenario( rollingMarketNum - 1, driftClient, userAccount, driftClient2, userAccount2, marketIndex, ammInitialBaseAssetAmount, [41, 43.8], [2000, 1000] ); assert(fundingRateShort.abs().gt(fundingRateLong.abs())); assert(fundingRateLong.lt(new BN(0))); assert(fundingRateShort.lt(new BN(0))); assert(fundingPnLForLongs.gt(new BN(0))); assert(fundingPnLForShorts.lt(new BN(0))); assert(fundingPnLForShorts.abs().lt(fundingPnLForLongs.abs())); const feeAlloced = convertToNumber(totalFee, QUOTE_PRECISION) - convertToNumber(cumulativeFee, QUOTE_PRECISION); const precisionFundingPay = AMM_RESERVE_PRECISION; const fundingPnLForLongsNum = convertToNumber( fundingPnLForLongs.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); const fundingPnLForShortsNum = convertToNumber( fundingPnLForShorts.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); // amount of money inflow must be greater than or equal to money outflow console.log( feeAlloced, '+', Math.abs(fundingPnLForShortsNum), '>=', fundingPnLForLongsNum ); assert( feeAlloced + Math.abs(fundingPnLForShortsNum) >= fundingPnLForLongsNum ); }); it('capped sym funding: ($200 long, $0 short, oracle > mark)', async () => { const marketIndex = rollingMarketNum; rollingMarketNum += 1; const [ fundingRateLong, fundingRateShort, fundingPnLForLongs, fundingPnLForShorts, totalFee, cumulativeFee, ] = await cappedSymFundingScenario( rollingMarketNum - 1, driftClient, userAccount, driftClient2, userAccount2, marketIndex, ammInitialBaseAssetAmount, [41, 42.5], [200, 0] ); assert(fundingRateShort.abs().gt(fundingRateLong.abs())); assert(fundingRateLong.lt(new BN(0))); assert(fundingRateShort.lt(new BN(0))); assert(fundingPnLForLongs.gt(new BN(0))); assert(fundingPnLForShorts.eq(new BN(0))); assert(fundingPnLForShorts.abs().lt(fundingPnLForLongs.abs())); const feeAlloced = convertToNumber(totalFee, QUOTE_PRECISION) - convertToNumber(cumulativeFee, QUOTE_PRECISION); const precisionFundingPay = AMM_RESERVE_PRECISION; const fundingPnLForLongsNum = convertToNumber( fundingPnLForLongs.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); const fundingPnLForShortsNum = convertToNumber( fundingPnLForShorts.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); // amount of money inflow must be greater than or equal to money outflow console.log( feeAlloced, '+', Math.abs(fundingPnLForShortsNum), '>=', fundingPnLForLongsNum ); assert( feeAlloced + Math.abs(fundingPnLForShortsNum) >= fundingPnLForLongsNum ); }); it('capped sym funding: ($200 long, $1 short, oracle < mark)', async () => { //symmetric is taking fees const marketIndex = rollingMarketNum; rollingMarketNum += 1; const [ fundingRateLong, fundingRateShort, fundingPnLForLongs, fundingPnLForShorts, totalFee, cumulativeFee, ] = await cappedSymFundingScenario( rollingMarketNum - 1, driftClient, userAccount, driftClient2, userAccount2, marketIndex, ammInitialBaseAssetAmount, [41, 38.5], [200, 1] ); assert(fundingRateShort.abs().eq(fundingRateLong.abs())); assert(fundingRateLong.gt(new BN(0))); assert(fundingRateShort.gt(new BN(0))); assert(fundingPnLForLongs.lt(new BN(0))); assert(fundingPnLForShorts.gt(new BN(0))); assert(fundingPnLForShorts.abs().lt(fundingPnLForLongs.abs())); const feeAlloced = convertToNumber(totalFee, QUOTE_PRECISION) - convertToNumber(cumulativeFee, QUOTE_PRECISION); const precisionFundingPay = AMM_RESERVE_PRECISION; const fundingPnLForLongsNum = convertToNumber( fundingPnLForLongs.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); const fundingPnLForShortsNum = convertToNumber( fundingPnLForShorts.div( PRICE_PRECISION.mul(FUNDING_RATE_BUFFER_PRECISION) ), precisionFundingPay ); // amount of money inflow must be greater than or equal to money outflow console.log( feeAlloced, '+', Math.abs(fundingPnLForShortsNum), '>=', fundingPnLForLongsNum ); assert( feeAlloced + Math.abs(fundingPnLForShortsNum) >= fundingPnLForLongsNum ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/serumHelper.ts
// TODO: Modernize all these apis. This is all quite clunky. import { TOKEN_PROGRAM_ID } from '@solana/spl-token'; import { Account, LAMPORTS_PER_SOL, PublicKey, Transaction, SystemProgram, Connection, } from '@solana/web3.js'; import { TokenInstructions, Market, DexInstructions, OpenOrders, } from '@project-serum/serum'; import { BN } from '@coral-xyz/anchor'; import { WRAPPED_SOL_MINT } from '../sdk/src'; export const SERUM = new PublicKey( 'srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX' ); export async function listMarket({ context, wallet, baseMint, quoteMint, baseLotSize, quoteLotSize, dexProgramId, feeRateBps, }) { const market = new Account(); const requestQueue = new Account(); const eventQueue = new Account(); const bids = new Account(); const asks = new Account(); const baseVault = new Account(); const quoteVault = new Account(); const quoteDustThreshold = new BN(100); async function getVaultOwnerAndNonce() { const nonce = new BN(0); while (nonce.lten(255)) { try { const vaultOwner = await PublicKey.createProgramAddress( [market.publicKey.toBuffer(), nonce.toArrayLike(Buffer, 'le', 8)], dexProgramId ); return [vaultOwner, nonce]; } catch (e) { nonce.iaddn(1); } } } const [vaultOwner, vaultSignerNonce] = await getVaultOwnerAndNonce(); const tx1 = new Transaction(); tx1.add( SystemProgram.createAccount({ fromPubkey: wallet.publicKey, newAccountPubkey: baseVault.publicKey, lamports: LAMPORTS_PER_SOL, space: 165, programId: TOKEN_PROGRAM_ID, }), SystemProgram.createAccount({ fromPubkey: wallet.publicKey, newAccountPubkey: quoteVault.publicKey, lamports: LAMPORTS_PER_SOL, space: 165, programId: TOKEN_PROGRAM_ID, }), TokenInstructions.initializeAccount({ account: baseVault.publicKey, mint: baseMint, owner: vaultOwner, }), TokenInstructions.initializeAccount({ account: quoteVault.publicKey, mint: quoteMint, owner: vaultOwner, }) ); const tx2 = new Transaction(); tx2.add( SystemProgram.createAccount({ fromPubkey: wallet.publicKey, newAccountPubkey: market.publicKey, lamports: LAMPORTS_PER_SOL * 100, space: Market.getLayout(dexProgramId).span, programId: dexProgramId, }), SystemProgram.createAccount({ fromPubkey: wallet.publicKey, newAccountPubkey: requestQueue.publicKey, lamports: LAMPORTS_PER_SOL * 100, space: 5120 + 12, programId: dexProgramId, }), SystemProgram.createAccount({ fromPubkey: wallet.publicKey, newAccountPubkey: eventQueue.publicKey, lamports: LAMPORTS_PER_SOL * 100, space: 262144 + 12, programId: dexProgramId, }), SystemProgram.createAccount({ fromPubkey: wallet.publicKey, newAccountPubkey: bids.publicKey, lamports: LAMPORTS_PER_SOL * 100, space: 65536 + 12, programId: dexProgramId, }), SystemProgram.createAccount({ fromPubkey: wallet.publicKey, newAccountPubkey: asks.publicKey, lamports: LAMPORTS_PER_SOL * 100, space: 65536 + 12, programId: dexProgramId, }), DexInstructions.initializeMarket({ market: market.publicKey, requestQueue: requestQueue.publicKey, eventQueue: eventQueue.publicKey, bids: bids.publicKey, asks: asks.publicKey, baseVault: baseVault.publicKey, quoteVault: quoteVault.publicKey, baseMint, quoteMint, baseLotSize: new BN(baseLotSize), quoteLotSize: new BN(quoteLotSize), feeRateBps, vaultSignerNonce, quoteDustThreshold, programId: dexProgramId, }) ); const signedTransactions = await signTransactions({ transactionsAndSigners: [ { transaction: tx1, signers: [baseVault, quoteVault] }, { transaction: tx2, signers: [market, requestQueue, eventQueue, bids, asks], }, ], wallet, connection: context, }); for (const signedTransaction of signedTransactions) { await context.connection.sendTransaction(signedTransaction); } await context.connection.getAccountInfo(market.publicKey); return market.publicKey; } async function signTransactions({ transactionsAndSigners, wallet, connection, }) { const blockhash = await connection.getLatestBlockhash(); transactionsAndSigners.forEach(({ transaction, signers = [] }) => { transaction.recentBlockhash = blockhash; transaction.setSigners( wallet.publicKey, ...signers.map((s) => s.publicKey) ); if (signers.length > 0) { transaction.partialSign(...signers); } }); return await wallet.signAllTransactions( transactionsAndSigners.map(({ transaction }) => transaction) ); } export async function makePlaceOrderTransaction( connection: Connection, market: Market, { owner, payer, side, price, size, orderType = 'limit', clientId, openOrdersAddressKey, openOrdersAccount, feeDiscountPubkey = undefined, selfTradeBehavior = 'decrementTake', maxTs, replaceIfExists = false, openOrdersAccounts = [], }, feeDiscountPubkeyCacheDurationMs = 0 ) { // @ts-ignore const ownerAddress: PublicKey = owner.publicKey ?? owner; // const openOrdersAccounts = await this.findOpenOrdersAccountsForOwner( // connection, // ownerAddress, // cacheDurationMs, // ); const transaction = new Transaction(); const signers: Account[] = []; // Fetch an SRM fee discount key if the market supports discounts and it is not supplied let useFeeDiscountPubkey: PublicKey | null; if (feeDiscountPubkey) { useFeeDiscountPubkey = feeDiscountPubkey; } else if (feeDiscountPubkey === undefined && this.supportsSrmFeeDiscounts) { useFeeDiscountPubkey = ( await market.findBestFeeDiscountKey( connection, ownerAddress, feeDiscountPubkeyCacheDurationMs ) ).pubkey; } else { useFeeDiscountPubkey = null; } let openOrdersAddress: PublicKey; if (openOrdersAccounts.length === 0) { let account; if (openOrdersAccount) { account = openOrdersAccount; } else { account = new Account(); } transaction.add( await OpenOrders.makeCreateAccountTransaction( connection, market.address, ownerAddress, account.publicKey, SERUM ) ); openOrdersAddress = account.publicKey; signers.push(account); // refresh the cache of open order accounts on next fetch // market._openOrdersAccountsCache[ownerAddress.toBase58()].ts = 0; } else if (openOrdersAccount) { openOrdersAddress = openOrdersAccount.publicKey; } else if (openOrdersAddressKey) { openOrdersAddress = openOrdersAddressKey; } else { openOrdersAddress = openOrdersAccounts[0].address; } let wrappedSolAccount: Account | null = null; if (payer.equals(ownerAddress)) { if ( (side === 'buy' && this.quoteMintAddress.equals(WRAPPED_SOL_MINT)) || (side === 'sell' && this.baseMintAddress.equals(WRAPPED_SOL_MINT)) ) { wrappedSolAccount = new Account(); let lamports; if (side === 'buy') { lamports = Math.round(price * size * 1.01 * LAMPORTS_PER_SOL); if (openOrdersAccounts.length > 0) { lamports -= openOrdersAccounts[0].quoteTokenFree.toNumber(); } } else { lamports = Math.round(size * LAMPORTS_PER_SOL); if (openOrdersAccounts.length > 0) { lamports -= openOrdersAccounts[0].baseTokenFree.toNumber(); } } lamports = Math.max(lamports, 0) + 1e7; transaction.add( SystemProgram.createAccount({ fromPubkey: ownerAddress, newAccountPubkey: wrappedSolAccount.publicKey, lamports, space: 165, programId: TOKEN_PROGRAM_ID, }) ); transaction.add( TokenInstructions.initializeAccount({ account: wrappedSolAccount.publicKey, mint: WRAPPED_SOL_MINT, owner: ownerAddress, }) ); signers.push(wrappedSolAccount); } else { throw new Error('Invalid payer account'); } } const placeOrderInstruction = market.makePlaceOrderInstruction(connection, { owner, payer: wrappedSolAccount?.publicKey ?? payer, side, price, size, orderType, clientId, openOrdersAddressKey: openOrdersAddress, feeDiscountPubkey: useFeeDiscountPubkey, selfTradeBehavior, maxTs, replaceIfExists, }); transaction.add(placeOrderInstruction); if (wrappedSolAccount) { transaction.add( TokenInstructions.closeAccount({ source: wrappedSolAccount.publicKey, destination: ownerAddress, owner: ownerAddress, }) ); } return { transaction, signers, payer: owner }; }
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/placeAndMakePerp.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair } from '@solana/web3.js'; import { BN, PRICE_PRECISION, TestClient, PositionDirection, User, Wallet, EventSubscriber, BASE_PRECISION, getLimitOrderParams, OracleSource, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpers'; import { PEG_PRECISION, PostOnlyParams } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('place and make perp order', () => { const chProgram = anchor.workspace.Drift as Program; let makerDriftClient: TestClient; let makerDriftClientUser: User; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); let usdcMint; let userUSDCAccount; const usdcAmount = new BN(100 * 10 ** 6); let solUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 32.821); marketIndexes = [0]; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; makerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClient.initialize(usdcMint.publicKey, true); await makerDriftClient.subscribe(); await initializeQuoteSpotMarket(makerDriftClient, usdcMint.publicKey); const periodicity = new BN(0); await makerDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(32 * PEG_PRECISION.toNumber()) ); await makerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); makerDriftClientUser = new User({ driftClient: makerDriftClient, userAccountPublicKey: await makerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClientUser.subscribe(); }); after(async () => { await makerDriftClient.unsubscribe(); await makerDriftClientUser.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('make', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); await sleep(1000); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const takerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], 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(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const takerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, 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, }); await takerDriftClient.placePerpOrder(takerOrderParams); await takerDriftClientUser.fetchAccounts(); const order = takerDriftClientUser.getOrderByUserOrderId(1); assert(!order.postOnly); const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, price: new BN(33).mul(PRICE_PRECISION), userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, immediateOrCancel: true, }); const txSig = await makerDriftClient.placeAndMakePerpOrder( makerOrderParams, { taker: await takerDriftClient.getUserAccountPublicKey(), order: takerDriftClient.getOrderByUserId(1), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), } ); bankrunContextWrapper.printTxLogs(txSig); const makerPosition = makerDriftClient.getUser().getPerpPosition(0); assert(makerPosition.baseAssetAmount.eq(BASE_PRECISION.neg())); const takerPosition = takerDriftClient.getUser().getPerpPosition(0); assert(takerPosition.baseAssetAmount.eq(BASE_PRECISION)); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/pyth.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { BASE_PRECISION, BN } from '../sdk'; import { mockOracleNoProgram, mockUserUSDCAccount, mockUSDCMint, setFeedPriceNoProgram, initializeQuoteSpotMarket, initUserAccounts, sleep, getFeedDataNoProgram, } from './testHelpers'; import { Program } from '@coral-xyz/anchor'; import { Keypair, PublicKey } from '@solana/web3.js'; import { calculateReservePrice, PEG_PRECISION, PositionDirection, convertToNumber, MarketStatus, PRICE_PRECISION, FUNDING_RATE_BUFFER_PRECISION, TestClient, User, QUOTE_SPOT_MARKET_INDEX, } from '../sdk/src'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; async function updateFundingRateHelper( driftClient: TestClient, marketIndex: number, priceFeedAddress: PublicKey, prices: Array<number>, context: BankrunContextWrapper ) { for (let i = 0; i < prices.length; i++) { await new Promise((r) => setTimeout(r, 1000)); // wait 1 second const newprice = prices[i]; setFeedPriceNoProgram(context, newprice, priceFeedAddress); const marketData0 = driftClient.getPerpMarketAccount(marketIndex); const ammAccountState0 = marketData0.amm; const oraclePx0 = await getFeedDataNoProgram( // @ts-ignore context.connection, ammAccountState0.oracle ); const priceSpread0 = convertToNumber(ammAccountState0.lastMarkPriceTwap) - convertToNumber( ammAccountState0.historicalOracleData.lastOraclePriceTwap ); const frontEndFundingCalc0 = priceSpread0 / oraclePx0.twap / (24 * 3600); console.log( 'funding rate frontend calc0:', frontEndFundingCalc0, 'markTwap0:', ammAccountState0.lastMarkPriceTwap.toNumber() / PRICE_PRECISION.toNumber(), 'markTwap0:', ammAccountState0.lastMarkPriceTwap.toNumber(), 'oracleTwap0(vamm):', ammAccountState0.historicalOracleData.lastOraclePriceTwap.toNumber(), 'oracleTwap0:', oraclePx0.twap, 'oraclePrice', oraclePx0.price, 'priceSpread', priceSpread0 ); const cumulativeFundingRateLongOld = ammAccountState0.cumulativeFundingRateLong; const cumulativeFundingRateShortOld = ammAccountState0.cumulativeFundingRateShort; try { const _tx = await driftClient.updateFundingRate( marketIndex, priceFeedAddress ); } catch (e) { console.error(e); } const CONVERSION_SCALE = FUNDING_RATE_BUFFER_PRECISION.mul(PRICE_PRECISION); const marketData = driftClient.getPerpMarketAccount(marketIndex); const ammAccountState = marketData.amm; const peroidicity = marketData.amm.fundingPeriod; const lastFundingRate = convertToNumber( ammAccountState.lastFundingRate, CONVERSION_SCALE ); console.log('last funding rate:', lastFundingRate); console.log( 'cumfunding rate:', convertToNumber(ammAccountState.cumulativeFundingRate, CONVERSION_SCALE), 'cumfunding rate long', convertToNumber( ammAccountState.cumulativeFundingRateLong, CONVERSION_SCALE ), 'cumfunding rate short', convertToNumber( ammAccountState.cumulativeFundingRateShort, CONVERSION_SCALE ) ); const lastFundingLong = ammAccountState.cumulativeFundingRateLong .sub(cumulativeFundingRateLongOld) .abs(); const lastFundingShort = ammAccountState.cumulativeFundingRateShort .sub(cumulativeFundingRateShortOld) .abs(); assert(ammAccountState.lastFundingRate.abs().gte(lastFundingLong.abs())); assert(ammAccountState.lastFundingRate.abs().gte(lastFundingShort.abs())); const priceSpread = (ammAccountState.lastMarkPriceTwap.toNumber() - ammAccountState.historicalOracleData.lastOraclePriceTwap.toNumber()) / PRICE_PRECISION.toNumber(); const frontEndFundingCalc = priceSpread / ((24 * 3600) / Math.max(1, peroidicity.toNumber())); console.log( 'funding rate frontend calc:', frontEndFundingCalc, 'markTwap:', ammAccountState.lastMarkPriceTwap.toNumber() / PRICE_PRECISION.toNumber(), 'markTwap:', ammAccountState.lastMarkPriceTwap.toNumber(), 'oracleTwap(vamm):', ammAccountState.historicalOracleData.lastOraclePriceTwap.toNumber(), 'priceSpread:', priceSpread ); const s = new Date(ammAccountState.lastMarkPriceTwapTs.toNumber() * 1000); const sdate = s.toLocaleDateString('en-US'); const stime = s.toLocaleTimeString('en-US'); console.log('funding rate timestamp:', sdate, stime); // assert(Math.abs(frontEndFundingCalc - lastFundingRate) < 9e-6); } } describe('pyth-oracle', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let driftClient2: TestClient; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint: Keypair; let userUSDCAccount: Keypair; const ammInitialQuoteAssetAmount = new anchor.BN(5 * 10 ** 13); const ammInitialBaseAssetAmount = new anchor.BN(5 * 10 ** 13); const usdcAmount = new BN(10 * 10 ** 6); let userAccount: User; let userAccount2: User; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); const price = 50000; await mockOracleNoProgram(bankrunContextWrapper, price, -6); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0, 1], spotMarketIndexes: [0], subAccountIds: [], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); await driftClient.initializeUserAccount(); userAccount = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await userAccount.subscribe(); await driftClient.deposit( usdcAmount, QUOTE_SPOT_MARKET_INDEX, userUSDCAccount.publicKey ); // create <NUM_USERS> users with 10k that collectively do <NUM_EVENTS> actions const [_userUSDCAccounts, _user_keys, driftClients, userAccountInfos] = await initUserAccounts( 1, usdcMint, usdcAmount, bankrunContextWrapper, [0, 1], [0], [], bulkAccountLoader ); driftClient2 = driftClients[0]; userAccount2 = userAccountInfos[0]; // await driftClient.depositCollateral( // await userAccount2.getPublicKey(), // usdcAmount, // userUSDCAccounts[1].publicKey // ); }); after(async () => { await driftClient.unsubscribe(); await userAccount.unsubscribe(); await driftClient2.unsubscribe(); await userAccount2.unsubscribe(); }); it('change feed price', async () => { const price = 50000; const expo = -9; const priceFeedAddress = await mockOracleNoProgram( bankrunContextWrapper, price, expo ); const feedDataBefore = await getFeedDataNoProgram( bankrunContextWrapper.connection, priceFeedAddress ); assert.ok(feedDataBefore.price === price); assert.ok(feedDataBefore.exponent === expo); const newPrice = 55000; await setFeedPriceNoProgram( bankrunContextWrapper, newPrice, priceFeedAddress ); const feedDataAfter = await getFeedDataNoProgram( bankrunContextWrapper.connection, priceFeedAddress ); assert.ok(feedDataAfter.price === newPrice); assert.ok(feedDataAfter.exponent === expo); }); it('oracle/vamm: funding rate calc 0hour periodicity', async () => { const priceFeedAddress = await mockOracleNoProgram( bankrunContextWrapper, 40, -10 ); const periodicity = new BN(0); // 1 HOUR const marketIndex = 0; await driftClient.initializePerpMarket( 0, priceFeedAddress, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity, new BN(39.99 * PEG_PRECISION.toNumber()) ); await driftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); await updateFundingRateHelper( driftClient, marketIndex, priceFeedAddress, [42], bankrunContextWrapper ); }); it('oracle/vamm: funding rate calc2 0hour periodicity', async () => { const priceFeedAddress = await mockOracleNoProgram( bankrunContextWrapper, 40, -10 ); const periodicity = new BN(0); const marketIndex = 1; await driftClient.initializePerpMarket( 1, priceFeedAddress, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity, new BN(41.7 * PEG_PRECISION.toNumber()) ); await driftClient.updatePerpMarketStatus(marketIndex, MarketStatus.ACTIVE); // await driftClient.moveAmmToPrice( // marketIndex, // new BN(41.5 * PRICE_PRECISION.toNumber()) // ); await updateFundingRateHelper( driftClient, marketIndex, priceFeedAddress, [41.501, 41.499], bankrunContextWrapper ); }); it('oracle/vamm: asym funding rate calc 0hour periodicity', async () => { const marketIndex = 1; // await driftClient.moveAmmToPrice( // marketIndex, // new BN(41.5 * PRICE_PRECISION.toNumber()) // ); console.log( 'PRICE', convertToNumber( calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), driftClient.getOracleDataForPerpMarket(marketIndex) ) ) ); await driftClient.openPosition( PositionDirection.LONG, BASE_PRECISION, marketIndex ); await driftClient2.openPosition( PositionDirection.SHORT, BASE_PRECISION.div(new BN(100)), marketIndex ); await driftClient.fetchAccounts(); const market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'PRICE AFTER', convertToNumber( calculateReservePrice( market, driftClient.getOracleDataForPerpMarket(marketIndex) ) ) ); await updateFundingRateHelper( driftClient, marketIndex, market.amm.oracle, [43.501, 44.499], bankrunContextWrapper ); await sleep(1000); await driftClient.fetchAccounts(); const marketNew = driftClient.getPerpMarketAccount(marketIndex); console.log( 'lastOraclePriceTwap before:', market.amm.historicalOracleData.lastOraclePriceTwap.toString() ); console.log( 'lastMarkPriceTwap before:', market.amm.lastMarkPriceTwap.toString() ); console.log( 'lastOraclePriceTwap after:', marketNew.amm.historicalOracleData.lastOraclePriceTwap.toString() ); console.log( 'lastMarkPriceTwap after:', marketNew.amm.lastMarkPriceTwap.toString() ); const fundingRateLong = marketNew.amm.cumulativeFundingRateLong.sub( market.amm.cumulativeFundingRateLong ); console.log( marketNew.amm.cumulativeFundingRateLong.toString(), market.amm.cumulativeFundingRateLong.toString(), marketNew.amm.cumulativeFundingRateShort.toString(), market.amm.cumulativeFundingRateShort.toString() ); const fundingRateShort = marketNew.amm.cumulativeFundingRateShort.sub( market.amm.cumulativeFundingRateShort ); // more dollars long than short console.log(fundingRateLong.toString(), 'vs', fundingRateShort.toString()); assert(fundingRateLong.lt(new BN(0))); assert(fundingRateShort.lt(new BN(0))); // Z-TODO assert(fundingRateShort.abs().gt(fundingRateLong.abs())); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/liquidatePerpPnlForDeposit.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { PublicKey } from '@solana/web3.js'; import { BASE_PRECISION, BN, OracleSource, ZERO, TestClient, PRICE_PRECISION, PositionDirection, EventSubscriber, OracleGuardRails, LIQUIDATION_PCT_PRECISION, convertToNumber, } from '../sdk/src'; import { mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, createUserWithUSDCAndWSOLAccount, createWSolTokenAccountForUser, initializeSolSpotMarket, mockOracleNoProgram, setFeedPriceNoProgram, } from './testHelpers'; import { isVariant, PERCENTAGE_PRECISION, QUOTE_PRECISION, UserStatus, } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('liquidate perp pnl for deposit', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bankrunContextWrapper: BankrunContextWrapper; let bulkAccountLoader: TestBulkAccountLoader; let usdcMint; let userUSDCAccount; let userWSOLAccount; let liquidatorDriftClient: TestClient; let liquidatorDriftClientWSOLAccount: PublicKey; let solOracle: PublicKey; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); let _throwaway: PublicKey; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); userWSOLAccount = await createWSolTokenAccountForUser( bankrunContextWrapper, // @ts-ignore bankrunContextWrapper.provider.wallet, new BN(5 * 10 ** 9) ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 1); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0, 1], subAccountIds: [], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await driftClient.updateInitialPctToLiquidate( LIQUIDATION_PCT_PRECISION.toNumber() ); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await initializeSolSpotMarket(driftClient, solOracle); await driftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(0); await driftClient.initializePerpMarket( 0, solOracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: new BN(10).mul(PERCENTAGE_PRECISION), oracleTwap5MinPercentDivergence: new BN(100).mul(PERCENTAGE_PRECISION), }, validity: { slotsBeforeStaleForAmm: new BN(100), slotsBeforeStaleForMargin: new BN(100), confidenceIntervalMaxSize: new BN(100000), tooVolatileRatio: new BN(55), // allow 55x change }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); await driftClient.openPosition( PositionDirection.SHORT, new BN(10).mul(BASE_PRECISION), 0, new BN(0) ); const solAmount = new BN(10 * 10 ** 9); [liquidatorDriftClient, liquidatorDriftClientWSOLAccount, _throwaway] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount.mul(new BN(2000)), usdcAmount, [0], [0, 1], [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], bulkAccountLoader ); await liquidatorDriftClient.subscribe(); const spotMarketIndex = 1; await liquidatorDriftClient.deposit( solAmount.mul(new BN(1000)), spotMarketIndex, liquidatorDriftClientWSOLAccount ); const solBorrow = new BN(5 * 10 ** 8); await driftClient.withdraw(solBorrow, 1, userWSOLAccount); }); after(async () => { await driftClient.unsubscribe(); await liquidatorDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('liquidate', async () => { await setFeedPriceNoProgram(bankrunContextWrapper, 50, solOracle); await driftClient.updateInitialPctToLiquidate( LIQUIDATION_PCT_PRECISION.toNumber() ); await driftClient.updateLiquidationDuration(1); const txSig0 = await liquidatorDriftClient.liquidatePerp( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0, new BN(175).mul(BASE_PRECISION).div(new BN(10)) ); bankrunContextWrapper.connection.printTxLogs(txSig0); try { await liquidatorDriftClient.liquidatePerpPnlForDeposit( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0, 0, usdcAmount.mul(new BN(100)) ); } catch (e) { console.log('FAILED to perp pnl settle before paying off borrow'); // console.error(e); } // pay off borrow first (and withdraw all excess in attempt to full pay) await driftClient.deposit(new BN(5.02 * 10 ** 8), 1, userWSOLAccount); // await driftClient.withdraw(new BN(1 * 10 ** 8), 1, userWSOLAccount, true); await driftClient.fetchAccounts(); // const u = driftClient.getUserAccount(); // console.log(u.spotPositions[0]); // console.log(u.spotPositions[1]); // console.log(u.perpPositions[0]); const txSig = await liquidatorDriftClient.liquidatePerpPnlForDeposit( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0, 0, usdcAmount.mul(new BN(600)) ); const computeUnits = bankrunContextWrapper.connection.findComputeUnitConsumption(txSig); console.log('compute units', computeUnits); bankrunContextWrapper.connection.printTxLogs(txSig); console.log('user status:', driftClient.getUserAccount().status); console.log( 'user collateral:', convertToNumber( driftClient.getUser().getTotalCollateral(), QUOTE_PRECISION ) ); assert(driftClient.getUserAccount().status === UserStatus.BEING_LIQUIDATED); assert(driftClient.getUserAccount().nextLiquidationId === 2); assert( driftClient.getUserAccount().spotPositions[0].scaledBalance.eq(ZERO) ); assert( driftClient.getUserAccount().spotPositions[1].scaledBalance.gt(ZERO) ); const liquidationRecord = eventSubscriber.getEventsArray('LiquidationRecord')[0]; assert(liquidationRecord.liquidationId === 1); assert( isVariant(liquidationRecord.liquidationType, 'liquidatePerpPnlForDeposit') ); assert( liquidationRecord.liquidatePerpPnlForDeposit.marketOraclePrice.eq( new BN(50).mul(PRICE_PRECISION) ) ); assert(liquidationRecord.liquidatePerpPnlForDeposit.perpMarketIndex === 0); console.log(liquidationRecord.liquidatePerpPnlForDeposit.pnlTransfer); assert( liquidationRecord.liquidatePerpPnlForDeposit.pnlTransfer.eq( new BN(10000000) ) ); assert( liquidationRecord.liquidatePerpPnlForDeposit.assetPrice.eq( PRICE_PRECISION ) ); assert(liquidationRecord.liquidatePerpPnlForDeposit.assetMarketIndex === 0); assert( liquidationRecord.liquidatePerpPnlForDeposit.assetTransfer.eq( new BN(10000000) ) ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/liquidityBook.ts
import { BN } from '@coral-xyz/anchor'; import { PRICE_PRECISION, PerpMarketAccount, calculateReservePrice, calculateTargetPriceTrade, ZERO, } from '../sdk/src'; /** * liquidityBook * show snapshot of liquidity, similar to traditional orderbook * @param market * @param N number of bids/asks * @param incrementSize grouping of liquidity by pct price move * @returns */ export function liquidityBook( market: PerpMarketAccount, N = 5, incrementSize = 0.1 ) { const defaultSlippageBN = new BN(incrementSize * PRICE_PRECISION.toNumber()); const baseAssetPriceWithMantissa = calculateReservePrice(market); const bidsPrice = []; const bidsCumSize = []; const asksPrice = []; const asksCumSize = []; for (let i = 1; i <= N; i++) { const targetPriceDefaultSlippage = baseAssetPriceWithMantissa .mul(PRICE_PRECISION.add(defaultSlippageBN.mul(new BN(i)))) .div(PRICE_PRECISION); const [_direction, liquidity, entryPrice] = calculateTargetPriceTrade( market, BN.max(targetPriceDefaultSlippage, new BN(1)) ); console.log(liquidity.toString()); if (liquidity.gt(ZERO)) { asksPrice.push(entryPrice); asksCumSize.push(liquidity); } const targetPriceDefaultSlippageBid = baseAssetPriceWithMantissa .mul(PRICE_PRECISION.sub(defaultSlippageBN.mul(new BN(i)))) .div(PRICE_PRECISION); const [_directionBid, liquidityBid, entryPriceBid] = calculateTargetPriceTrade( market, BN.max(targetPriceDefaultSlippageBid, new BN(1)) ); if (liquidityBid.gt(ZERO)) { bidsPrice.push(entryPriceBid); bidsCumSize.push(liquidityBid); } } return [bidsPrice, bidsCumSize, asksPrice, asksCumSize]; }
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/delistMarketLiq.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { PublicKey } from '@solana/web3.js'; import { Wallet, BASE_PRECISION, BN, OracleSource, ZERO, TestClient, convertToNumber, PRICE_PRECISION, PositionDirection, EventSubscriber, QUOTE_PRECISION, User, AMM_RESERVE_PRECISION, isVariant, MARGIN_PRECISION, SPOT_MARKET_BALANCE_PRECISION, LIQUIDATION_PCT_PRECISION, } from '../sdk/src'; import { mockOracle, mockUSDCMint, mockUserUSDCAccount, setFeedPrice, initializeQuoteSpotMarket, createUserWithUSDCAndWSOLAccount, initializeSolSpotMarket, printTxLogs, getFeedData, sleep, } from './testHelpers'; import { Keypair } from '@solana/web3.js'; import { BulkAccountLoader, calculateReservePrice, ContractTier, UserStatus, } from '../sdk'; async function depositToFeePoolFromIF( amount: number, driftClient: TestClient, userUSDCAccount: Keypair ) { const ifAmount = new BN(amount * QUOTE_PRECISION.toNumber()); // // send $50 to market from IF const txSig00 = await driftClient.depositIntoPerpMarketFeePool( 0, ifAmount, userUSDCAccount.publicKey ); console.log(txSig00); } describe('delist market, liquidation of expired position', () => { const provider = anchor.AnchorProvider.local(undefined, { preflightCommitment: 'confirmed', commitment: 'confirmed', }); const connection = provider.connection; anchor.setProvider(provider); const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; const eventSubscriber = new EventSubscriber(connection, chProgram, { commitment: 'recent', }); eventSubscriber.subscribe(); const bulkAccountLoader = new BulkAccountLoader(connection, 'confirmed', 1); let usdcMint; let userUSDCAccount; let userUSDCAccount2; let driftClientLoser: TestClient; let driftClientLoserUser: User; let liquidatorDriftClient: TestClient; let liquidatorDriftClientWSOLAccount: PublicKey; let liquidatorDriftClientWUSDCAccount: PublicKey; let solOracle: PublicKey; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(AMM_RESERVE_PRECISION.toNumber() / 10000); const ammInitialQuoteAssetReserve = new anchor.BN(9 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(9 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(1000 * 10 ** 6); const userKeypair = new Keypair(); before(async () => { usdcMint = await mockUSDCMint(provider); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount.mul(new BN(100)), provider ); solOracle = await mockOracle(43.1337); driftClient = new TestClient({ connection, wallet: provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0, 1], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await initializeSolSpotMarket(driftClient, solOracle); await driftClient.updatePerpAuctionDuration(new BN(0)); await driftClient.updateInitialPctToLiquidate( LIQUIDATION_PCT_PRECISION.toNumber() ); const periodicity = new BN(0); await driftClient.initializePerpMarket( 0, solOracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(42_500_000), undefined, ContractTier.A, 1000, 900, // easy to liq undefined, undefined, undefined, true, 250, 500 ); await driftClient.updatePerpMarketMinOrderSize(0, new BN(1)); // await driftClient.updatePerpMarketBaseSpread(new BN(0), 2000); // await driftClient.updatePerpMarketCurveUpdateIntensity(new BN(0), 100); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); await provider.connection.requestAirdrop(userKeypair.publicKey, 10 ** 9); userUSDCAccount2 = await mockUserUSDCAccount( usdcMint, usdcAmount, provider, userKeypair.publicKey ); driftClientLoser = new TestClient({ connection, wallet: new Wallet(userKeypair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0, 1], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientLoser.subscribe(); await driftClientLoser.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount2.publicKey ); driftClientLoserUser = new User({ driftClient: driftClientLoser, userAccountPublicKey: await driftClientLoser.getUserAccountPublicKey(), }); await driftClientLoserUser.subscribe(); }); after(async () => { await driftClient.unsubscribe(); await driftClientLoser.unsubscribe(); await driftClientLoserUser.unsubscribe(); await liquidatorDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('put market in big drawdown and net user negative pnl', async () => { await depositToFeePoolFromIF(10000, driftClient, userUSDCAccount); try { await driftClient.openPosition( PositionDirection.SHORT, BASE_PRECISION, 0, calculateReservePrice( driftClient.getPerpMarketAccount(0), driftClient.getOracleDataForPerpMarket(0) ) ); } catch (e) { console.log('driftClient.openPosition'); console.error(e); } const uL = driftClientLoserUser.getUserAccount(); console.log( 'uL.spotPositions[0].scaledBalance:', uL.spotPositions[0].scaledBalance.toString() ); assert( uL.spotPositions[0].scaledBalance.eq( new BN(1000 * SPOT_MARKET_BALANCE_PRECISION.toNumber()) ) ); console.log(uL.perpPositions[0].baseAssetAmount.toString()); console.log(uL.perpPositions[0].quoteAssetAmount.toString()); const bank0Value = driftClientLoserUser.getSpotMarketAssetValue(0); console.log('uL.bank0Value:', bank0Value.toString()); assert(bank0Value.eq(new BN(1000 * 1e6))); const driftClientLoserUserValue = convertToNumber( driftClientLoserUser.getTotalCollateral(), QUOTE_PRECISION ); console.log('driftClientLoserUserValue:', driftClientLoserUserValue); assert(driftClientLoserUserValue == 1000); // ?? // todo try { const txSig = await driftClientLoser.openPosition( PositionDirection.LONG, BASE_PRECISION.mul(new BN(205)), 0, new BN(0) ); await printTxLogs(connection, txSig); } catch (e) { console.log('failed driftClientLoserc.openPosition'); console.error(e); } await driftClientLoser.fetchAccounts(); await driftClientLoserUser.fetchAccounts(); const userPos = driftClientLoser.getUserAccount().perpPositions[0]; console.log(userPos.baseAssetAmount.toString()); console.log(userPos.quoteAssetAmount.toString()); assert(userPos.baseAssetAmount.eq(new BN(205).mul(BASE_PRECISION))); // assert(userPos.quoteAssetAmount.eq(new BN(-8721212700))); const driftClientLoserUserLeverage = convertToNumber( driftClientLoserUser.getLeverage(), MARGIN_PRECISION ); const driftClientLoserUserLiqPrice = convertToNumber( driftClientLoserUser.liquidationPrice(0), PRICE_PRECISION ); console.log( 'driftClientLoserUser.getLeverage:', driftClientLoserUserLeverage, 'driftClientLoserUserLiqPrice:', driftClientLoserUserLiqPrice ); assert(driftClientLoserUserLeverage <= 7.8865); assert(driftClientLoserUserLeverage >= 7.8486); assert(driftClientLoserUserLiqPrice < 41.390493); assert(driftClientLoserUserLiqPrice > 41.300493); const market00 = driftClient.getPerpMarketAccount(0); assert(market00.amm.feePool.scaledBalance.eq(new BN(10000000000000))); const bank0Value1p5 = driftClientLoserUser.getSpotMarketAssetValue(0); console.log('uL.bank0Value1p5:', bank0Value1p5.toString()); const driftClientLoserUserValue1p5 = convertToNumber( driftClientLoserUser.getTotalCollateral(), QUOTE_PRECISION ); console.log('driftClientLoserUserValue1p5:', driftClientLoserUserValue1p5); const solAmount = new BN(1 * 10 ** 9); [ liquidatorDriftClient, liquidatorDriftClientWSOLAccount, liquidatorDriftClientWUSDCAccount, ] = await createUserWithUSDCAndWSOLAccount( provider, usdcMint, chProgram, solAmount, usdcAmount.mul(new BN(100)), [0], [0, 1], [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], bulkAccountLoader ); await liquidatorDriftClient.subscribe(); const bankIndex = 1; await liquidatorDriftClient.deposit( solAmount, bankIndex, liquidatorDriftClientWSOLAccount ); await liquidatorDriftClient.deposit( usdcAmount.mul(new BN(100)), 0, liquidatorDriftClientWUSDCAccount ); // sol falls const tankPrice = 36.7; await driftClient.moveAmmToPrice( 0, new BN(tankPrice * PRICE_PRECISION.toNumber()) ); await setFeedPrice(anchor.workspace.Pyth, tankPrice, solOracle); console.log('price move to $', tankPrice); await driftClientLoser.fetchAccounts(); await driftClientLoserUser.fetchAccounts(); const driftClientLoserUserLeverage2 = convertToNumber( driftClientLoserUser.getLeverage(), MARGIN_PRECISION ); const driftClientLoserUserLiqPrice2 = convertToNumber( driftClientLoserUser.liquidationPrice(0), PRICE_PRECISION ); const bank0Value2 = driftClientLoserUser.getSpotMarketAssetValue(0); console.log('uL.bank0Value2:', bank0Value2.toString()); const driftClientLoserUserValue2 = convertToNumber( driftClientLoserUser.getTotalCollateral(), QUOTE_PRECISION ); console.log('driftClientLoserUserValue2:', driftClientLoserUserValue2); console.log( 'driftClientLoserUser.getLeverage2:', driftClientLoserUserLeverage2, 'driftClientLoserUserLiqPrice2:', driftClientLoserUserLiqPrice2, 'bank0Value2:', bank0Value2.toString(), 'driftClientLoserUserValue2:', driftClientLoserUserValue2.toString() ); const market0 = driftClient.getPerpMarketAccount(0); const winnerUser = driftClient.getUserAccount(); const loserUser = driftClientLoser.getUserAccount(); console.log(winnerUser.perpPositions[0].quoteAssetAmount.toString()); console.log(loserUser.perpPositions[0].quoteAssetAmount.toString()); // TODO: quoteAssetAmountShort!= sum of users assert( market0.amm.quoteAssetAmount.eq( winnerUser.perpPositions[0].quoteAssetAmount.add( loserUser.perpPositions[0].quoteAssetAmount ) ) ); }); it('put market in reduce only mode', async () => { const marketIndex = 0; const slot = await connection.getSlot(); const now = await connection.getBlockTime(slot); const expiryTs = new BN(now + 3); // await driftClient.moveAmmToPrice( // new BN(0), // new BN(43.1337 * PRICE_PRECISION.toNumber()) // ); const market0 = driftClient.getPerpMarketAccount(marketIndex); assert(market0.expiryTs.eq(ZERO)); await driftClient.updatePerpMarketExpiry(marketIndex, expiryTs); await sleep(1000); driftClient.fetchAccounts(); const market = driftClient.getPerpMarketAccount(marketIndex); console.log(market.status); assert(isVariant(market.status, 'reduceOnly')); console.log( 'market.expiryTs == ', market.expiryTs.toString(), '(', expiryTs.toString(), ')' ); assert(market.expiryTs.eq(expiryTs)); console.log('totalExchangeFee:', market.amm.totalExchangeFee.toString()); console.log('totalFee:', market.amm.totalFee.toString()); console.log('totalMMFee:', market.amm.totalMmFee.toString()); console.log( 'totalFeeMinusDistributions:', market.amm.totalFeeMinusDistributions.toString() ); // should fail // try { // await driftClientLoser.openPosition( // PositionDirection.LONG, // new BN(10000000), // new BN(0), // new BN(0) // ); // assert(false); // } catch (e) { // console.log(e); // if (!e.toString().search('AnchorError occurred')) { // assert(false); // } // console.log('risk increase trade failed'); // } // should succeed // await driftClientLoser.openPosition( // PositionDirection.SHORT, // new BN(10000000), // new BN(0), // new BN(0) // ); }); it('put market in settlement mode', async () => { const marketIndex = 0; let slot = await connection.getSlot(); let now = await connection.getBlockTime(slot); const market0 = driftClient.getPerpMarketAccount(marketIndex); console.log('market0.status:', market0.status); while (market0.expiryTs.gte(new BN(now))) { console.log(market0.expiryTs.toString(), '>', now); await sleep(1000); slot = await connection.getSlot(); now = await connection.getBlockTime(slot); } // try { const txSig = await driftClient.settleExpiredMarket(marketIndex); // } catch (e) { // console.error(e); // } await printTxLogs(connection, txSig); driftClient.fetchAccounts(); const market = driftClient.getPerpMarketAccount(marketIndex); console.log(market.status); assert(isVariant(market.status, 'settlement')); console.log( 'market.expiryPrice:', market.expiryPrice.toString(), convertToNumber(market.expiryPrice) ); const curPrice = (await getFeedData(anchor.workspace.Pyth, solOracle)) .price; console.log('new oracle price:', curPrice); assert(market.expiryPrice.gt(ZERO)); assert(market.expiryPrice.eq(new BN(38820329))); // net user pnl calc more accurate now // assert(market.amm.lastMarkPriceTwap.eq(new BN(42753480))); console.log( 'market.amm.lastMarkPriceTwap:', convertToNumber(market.amm.lastMarkPriceTwap) ); assert(market.amm.lastMarkPriceTwap.gte(new BN(42503984 - 200))); assert(market.amm.lastMarkPriceTwap.lte(new BN(42504249 + 200))); }); it('liq and settle expired market position', async () => { const marketIndex = 0; const loserUser0 = driftClientLoser.getUserAccount(); assert(loserUser0.perpPositions[0].baseAssetAmount.gt(new BN(0))); assert(loserUser0.perpPositions[0].quoteAssetAmount.lt(new BN(0))); // console.log(loserUser0.perpPositions[0]); const liquidatorDriftClientUser = new User({ driftClient: liquidatorDriftClient, userAccountPublicKey: await liquidatorDriftClient.getUserAccountPublicKey(), }); await liquidatorDriftClientUser.subscribe(); await liquidatorDriftClient.fetchAccounts(); await liquidatorDriftClientUser.fetchAccounts(); await driftClientLoser.fetchAccounts(); await driftClientLoserUser.fetchAccounts(); const liquidatorDriftClientValue = convertToNumber( liquidatorDriftClientUser.getTotalCollateral(), QUOTE_PRECISION ); console.log( 'liquidatorDriftClientValue:', liquidatorDriftClientValue.toString() ); const driftClientLoserUserValue = convertToNumber( driftClientLoserUser.getTotalCollateral(), QUOTE_PRECISION ); console.log( 'driftClientLoserUserValue:', driftClientLoserUserValue.toString() ); console.log( 'driftClientLoser.baseamount', driftClientLoser .getUserAccount() .perpPositions[0].baseAssetAmount.toString() ); const loserMaintMarginReq0 = driftClientLoserUser.getMaintenanceMarginRequirement(); console.log('loserMaintMarginReq:', loserMaintMarginReq0.toNumber()); const liqBuf0 = driftClientLoser.getStateAccount().liquidationMarginBufferRatio; console.log('liqBuf:', liqBuf0); const loserMaintMarginReqWBuf0 = driftClientLoserUser.getMaintenanceMarginRequirement(); console.log( 'loserMaintMarginReqWBuf:', loserMaintMarginReqWBuf0.toNumber() ); // try { // const txSigLiq = await liquidatorDriftClient.liquidatePerp( // await driftClientLoser.getUserAccountPublicKey(), // driftClientLoser.getUserAccount(), // marketIndex, // BASE_PRECISION.mul(new BN(290)) // ); // console.log(txSigLiq); // await printTxLogs(connection, txSigLiq); // const liquidationRecord = // eventSubscriber.getEventsArray('LiquidationRecord')[0]; // console.log(liquidationRecord); // assert(liquidationRecord.liquidationId === 1); // assert(isVariant(liquidationRecord.liquidationType, 'liquidatePerp')); // } catch (e) { // console.error(e); // } await liquidatorDriftClient.fetchAccounts(); await liquidatorDriftClientUser.fetchAccounts(); await driftClientLoser.fetchAccounts(); await driftClientLoserUser.fetchAccounts(); const driftClientLoserUserValueAfter = convertToNumber( driftClientLoserUser.getTotalCollateral(), QUOTE_PRECISION ); console.log( 'driftClientLoserUserValueAfter:', driftClientLoserUserValueAfter.toString() ); console.log( 'driftClientLoser.baseamount', driftClientLoser .getUserAccount() .perpPositions[0].baseAssetAmount.toString() ); const liquidatorDriftClientValueAfter = convertToNumber( liquidatorDriftClientUser.getTotalCollateral(), QUOTE_PRECISION ); console.log( 'liquidatorDriftClientValueAfter:', liquidatorDriftClientValueAfter.toString() ); const loserMaintMarginReq = driftClientLoserUser.getMaintenanceMarginRequirement(); console.log('loserMaintMarginReq:', loserMaintMarginReq.toNumber()); const liqBuf = driftClientLoser.getStateAccount().liquidationMarginBufferRatio; console.log('liqBuf:', liqBuf); const loserMaintMarginReqWBuf = driftClientLoserUser.getMaintenanceMarginRequirement(); console.log('loserMaintMarginReqWBuf:', loserMaintMarginReqWBuf.toNumber()); assert(loserMaintMarginReq.eq(ZERO)); const txSigLiqPnl = await liquidatorDriftClient.liquidatePerpPnlForDeposit( await driftClientLoser.getUserAccountPublicKey(), driftClientLoser.getUserAccount(), marketIndex, 0, QUOTE_PRECISION.mul(new BN(10000)) ); console.log(txSigLiqPnl); await printTxLogs(connection, txSigLiqPnl); await sleep(100); await driftClientLoser.fetchAccounts(); console.log( 'driftClientLoserUser.getNetSpotMarketValue=', driftClientLoserUser.getNetSpotMarketValue().toString() ); console.log( driftClientLoser .getUserAccount() .spotPositions[0].scaledBalance.toString() ); console.log( driftClientLoser.getUserAccount().spotPositions, driftClientLoser.getUserAccount().perpPositions ); assert(driftClientLoser.getUserAccount().status === UserStatus.BANKRUPT); const txSigBankrupt = await liquidatorDriftClient.resolvePerpBankruptcy( await driftClientLoser.getUserAccountPublicKey(), driftClientLoser.getUserAccount(), marketIndex ); console.log(txSigBankrupt); await printTxLogs(connection, txSigBankrupt); await driftClientLoser.fetchAccounts(); assert(driftClientLoser.getUserAccount().status !== UserStatus.BANKRUPT); assert( driftClientLoser .getUserAccount() .perpPositions[0].baseAssetAmount.eq(ZERO) ); assert( driftClientLoser .getUserAccount() .perpPositions[0].quoteAssetAmount.eq(ZERO) ); try { // should fail console.log('settle position driftClientLoser'); const txSig = await driftClientLoser.settlePNL( await driftClientLoser.getUserAccountPublicKey(), driftClientLoser.getUserAccount(), marketIndex ); await printTxLogs(connection, txSig); console.log('settle pnl driftClientLoser'); } catch (e) { // console.error(e); } try { await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); } catch (e) { // if (!e.toString().search('AnchorError occurred')) { // assert(false); // } console.log('Cannot settle pnl under current market status'); } try { await liquidatorDriftClient.settlePNL( await liquidatorDriftClient.getUserAccountPublicKey(), liquidatorDriftClient.getUserAccount(), marketIndex ); } catch (e) { // if (!e.toString().search('AnchorError occurred')) { // assert(false); // } console.log('Cannot settle pnl under current market status'); } // const settleRecord = eventSubscriber.getEventsArray('SettlePnlRecord')[0]; // console.log(settleRecord); await driftClientLoser.fetchAccounts(); const liqUser = liquidatorDriftClient.getUserAccount(); // console.log(loserUser.perpPositions[0]); assert(liqUser.perpPositions[0].baseAssetAmount.eq(new BN(0))); assert(liqUser.perpPositions[0].quoteAssetAmount.eq(new BN(0))); const marketAfter0 = driftClient.getPerpMarketAccount(marketIndex); console.log(marketAfter0); assert(marketAfter0.numberOfUsersWithBase === 0); // old 1415296436 const finalPnlResultMin0 = new BN(2266346249000 - 110900000); const finalPnlResultMax0 = new BN(2266346249000 + 111090000); console.log( 'marketAfter0.pnlPool.scaledBalance:', marketAfter0.pnlPool.scaledBalance.toString() ); assert(marketAfter0.pnlPool.scaledBalance.gt(finalPnlResultMin0)); assert(marketAfter0.pnlPool.scaledBalance.lt(finalPnlResultMax0)); // const ammPnlResult = new BN(0); console.log('feePool:', marketAfter0.amm.feePool.scaledBalance.toString()); console.log( 'totalExchangeFee:', marketAfter0.amm.totalExchangeFee.toString() ); assert(marketAfter0.amm.feePool.scaledBalance.eq(ZERO)); assert(marketAfter0.amm.totalExchangeFee.eq(new BN(8712501))); await liquidatorDriftClientUser.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/repegAndSpread.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { BN, calculatePrice, getMarketOrderParams, OracleSource, BID_ASK_SPREAD_PRECISION, PEG_PRECISION, QUOTE_SPOT_MARKET_INDEX, getTokenAmount, SpotBalanceType, ZERO, getLimitOrderParams, TestClient, OraclePriceData, OracleGuardRails, BASE_PRECISION, BulkAccountLoader, PERCENTAGE_PRECISION, ContractTier, } from '../sdk'; import { Keypair } from '@solana/web3.js'; import { Program } from '@coral-xyz/anchor'; import { User, // PRICE_PRECISION, AMM_RESERVE_PRECISION, QUOTE_PRECISION, // calculateReservePrice, PositionDirection, EventSubscriber, convertToNumber, calculateBidAskPrice, calculateUpdatedAMM, calculateSpread, calculateSpreadBN, calculateInventoryScale, calculateEffectiveLeverage, calculateLiveOracleStd, } from '../sdk/src'; import { getFeedData, initUserAccounts, mockOracle, mockUserUSDCAccount, mockUSDCMint, setFeedPrice, getOraclePriceData, initializeQuoteSpotMarket, } from './testHelpers'; async function depositToFeePoolFromIF( amount: number, driftClient: TestClient, userUSDCAccount: Keypair ) { const ifAmount = new BN(amount * QUOTE_PRECISION.toNumber()); // // send $50 to market from IF try { const txSig00 = await driftClient.depositIntoPerpMarketFeePool( 0, ifAmount, userUSDCAccount.publicKey ); console.log('complete withdrawFromInsuranceVaultToMarket:', '$', amount); console.log(txSig00); } catch (e) { console.error(e); } } async function iterClosePosition( driftClient: TestClient, marketIndex: number, oraclePriceData: OraclePriceData ) { let userPosition = driftClient.getUser().getPerpPosition(marketIndex); let posDirection; let limitPrice: BN; if (userPosition.baseAssetAmount.lt(ZERO)) { posDirection = PositionDirection.LONG; limitPrice = oraclePriceData.price.mul(new BN(10248)).div(new BN(10000)); console.log( 'iterClosePosition:: close position limit: ', convertToNumber(limitPrice) ); assert(limitPrice.gt(oraclePriceData.price)); } else { posDirection = PositionDirection.SHORT; limitPrice = oraclePriceData.price.mul(new BN(10000)).div(new BN(10248)); console.log( 'iterClosePosition:: close position limit: ', convertToNumber(limitPrice) ); assert(limitPrice.lt(oraclePriceData.price)); } while (!userPosition.baseAssetAmount.eq(ZERO)) { const closeOrderParams = getLimitOrderParams({ marketIndex, direction: posDirection, baseAssetAmount: userPosition.baseAssetAmount.abs(), reduceOnly: true, price: limitPrice, immediateOrCancel: true, }); const txClose = await driftClient.placeAndTakePerpOrder(closeOrderParams); console.log( 'tx logs', ( await driftClient.connection.getTransaction(txClose, { commitment: 'confirmed', }) ).meta.logMessages ); await driftClient.fetchAccounts(); userPosition = driftClient.getUser().getPerpPosition(marketIndex); console.log( 'userPosition.baseAssetAmount: ', userPosition.baseAssetAmount.toString() ); } } describe('repeg and spread amm', () => { const provider = anchor.AnchorProvider.local(undefined, { preflightCommitment: 'confirmed', skipPreflight: false, commitment: 'confirmed', }); const connection = provider.connection; anchor.setProvider(provider); const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; const eventSubscriber = new EventSubscriber(connection, chProgram, { commitment: 'recent', }); eventSubscriber.subscribe(); const bulkAccountLoader = new BulkAccountLoader(connection, 'confirmed', 1); // let userAccountPublicKey: PublicKeys; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y // const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetAmount = new anchor.BN(94).mul( AMM_RESERVE_PRECISION ); const ammInitialBaseAssetAmount = new anchor.BN(94).mul( AMM_RESERVE_PRECISION ); const usdcAmount = new BN(10000 * 10 ** 6); let marketIndexes; let spotMarketIndexes; let oracleInfos; let btcUsd; const mockOracles = []; before(async () => { usdcMint = await mockUSDCMint(provider); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount.mul(new BN(2)), provider ); btcUsd = await mockOracle(21966.86); mockOracles.push(btcUsd); for (let i = 1; i <= 4; i++) { // init more oracles const thisUsd = await mockOracle(i); mockOracles.push(thisUsd); } spotMarketIndexes = [0]; marketIndexes = mockOracles.map((_, i) => i); oracleInfos = mockOracles.map((oracle) => { return { publicKey: oracle, source: OracleSource.PYTH }; }); driftClient = new TestClient({ connection, wallet: provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, oracleInfos: oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await driftClient.updatePerpAuctionDuration(0); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); const periodicity = new BN(60 * 60); // 1 HOUR // BTC await driftClient.initializePerpMarket( 0, btcUsd, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity, new BN(21966.868 * PEG_PRECISION.toNumber()), undefined, ContractTier.A, 500, 250, undefined, undefined, undefined, true, 250, 400 ); await driftClient.updatePerpMarketBaseSpread(0, 250); await driftClient.updatePerpMarketCurveUpdateIntensity(0, 100); // for (let i = 1; i <= 4; i++) { // // init more markets // const thisUsd = mockOracles[i]; // await driftClient.initializeMarket( // thisUsd, // ammInitialBaseAssetAmount, // ammInitialQuoteAssetAmount, // periodicity, // new BN(1_000 * i), // undefined, // 1000, // 201 // ); // await driftClient.updatePerpMarketBaseSpread(new BN(i), 2000); // await driftClient.updatePerpMarketCurveUpdateIntensity(new BN(i), 100); // } const [, _userAccountPublicKey] = await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); }); after(async () => { await driftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('BTC market massive spread', async () => { const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: PERCENTAGE_PRECISION, oracleTwap5MinPercentDivergence: PERCENTAGE_PRECISION, }, validity: { slotsBeforeStaleForAmm: new BN(100), slotsBeforeStaleForMargin: new BN(100), confidenceIntervalMaxSize: new BN(100000), tooVolatileRatio: new BN(2), }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); await driftClient.fetchAccounts(); const state = driftClient.getStateAccount(); assert( JSON.stringify(oracleGuardRails) === JSON.stringify(state.oracleGuardRails) ); const marketIndex = 0; const baseAssetAmount = new BN(0.19316 * AMM_RESERVE_PRECISION.toNumber()); const orderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, }); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), }); await driftClientUser.subscribe(); await depositToFeePoolFromIF(0.001, driftClient, userUSDCAccount); // await driftClient.closePosition(new BN(0)); const txSig0 = await driftClient.placeAndTakePerpOrder(orderParams); console.log( 'tx logs', (await connection.getTransaction(txSig0, { commitment: 'confirmed' })) .meta.logMessages ); await depositToFeePoolFromIF(50, driftClient, userUSDCAccount); await driftClient.fetchAccounts(); const btcPerpAccount = driftClient.getPerpMarketAccount(0); assert(btcPerpAccount.numberOfUsersWithBase == 1); assert(btcPerpAccount.numberOfUsers == 1); assert(btcPerpAccount.amm.baseAssetAmountWithAmm.lt(ZERO)); console.log( btcPerpAccount.amm.baseAssetAmountWithAmm.toString(), baseAssetAmount.toString() ); assert(btcPerpAccount.amm.baseAssetAmountWithAmm.eq(new BN('-193100000'))); assert(btcPerpAccount.amm.shortIntensityVolume.gt(ZERO)); assert(btcPerpAccount.amm.longIntensityVolume.eq(ZERO)); assert(btcPerpAccount.amm.markStd.gt(ZERO)); assert(btcPerpAccount.amm.oracleStd.gt(ZERO)); // old oracle price: 21966 await setFeedPrice(anchor.workspace.Pyth, 19790, btcUsd); const curPrice = (await getFeedData(anchor.workspace.Pyth, btcUsd)).price; console.log('new oracle price:', curPrice); const oraclePriceData = await getOraclePriceData( anchor.workspace.Pyth, btcUsd ); const market0 = driftClient.getPerpMarketAccount(0); console.log( 'market0.amm.totalFeeMinusDistributions:', market0.amm.totalFeeMinusDistributions.toNumber() / QUOTE_PRECISION.toNumber() ); console.log( 'market0.amm.pegMultiplier:', market0.amm.pegMultiplier.toNumber() / PEG_PRECISION.toNumber() ); const prepegAMM = calculateUpdatedAMM(market0.amm, oraclePriceData); console.log( 'market0.amm.netBaseAssetAmount:', market0.amm.baseAssetAmountWithAmm.toString(), 'terminalQuoteAssetReserve:', market0.amm.terminalQuoteAssetReserve.toString(), 'quoteAssetReserve:', market0.amm.quoteAssetReserve.toString(), 'pegMultiplier:', market0.amm.pegMultiplier.toString(), '->', prepegAMM.pegMultiplier.toString() ); const [bid, ask] = calculateBidAskPrice(market0.amm, oraclePriceData); const [longSpread, shortSpread] = calculateSpread( market0.amm, oraclePriceData ); const [bid2, ask2] = calculateBidAskPrice( prepegAMM, oraclePriceData, false ); const [longSpread2, shortSpread2] = calculateSpread( prepegAMM, oraclePriceData ); const reservePrice = calculatePrice( prepegAMM.baseAssetReserve, prepegAMM.quoteAssetReserve, prepegAMM.pegMultiplier ); console.log('maxSpread:', prepegAMM.maxSpread); console.log('bid/ask:', convertToNumber(bid), convertToNumber(ask)); console.log('spreads:', longSpread, shortSpread); console.log( 'bid2/reserve/ask2:', convertToNumber(bid2), convertToNumber(reservePrice), convertToNumber(ask2) ); console.log('spreads:', longSpread2, shortSpread2); assert(shortSpread2 > longSpread2); const targetPrice = oraclePriceData?.price || reservePrice; const targetMarkSpreadPct = reservePrice .sub(targetPrice) .mul(BID_ASK_SPREAD_PRECISION) .div(reservePrice); const tfMD = prepegAMM.totalFeeMinusDistributions.toNumber() / QUOTE_PRECISION.toNumber(); console.log('prepegAMM.totalFeeMinusDistributions:', tfMD); assert(tfMD < 0); // enforcing max spread console.log( 'prepegAMM.pegMultiplier:', prepegAMM.pegMultiplier.toNumber() / PEG_PRECISION.toNumber() ); 358332628 / 358340434; console.log( 'prepegAMM.netBaseAssetAmount:', prepegAMM.baseAssetAmountWithAmm.toString(), 'terminalQuoteAssetReserve:', prepegAMM.terminalQuoteAssetReserve.toString(), 'quoteAssetReserve:', prepegAMM.quoteAssetReserve.toString(), 'pegMultiplier:', prepegAMM.pegMultiplier.toString() ); const now = new BN(new Date().getTime() / 1000); //todo const liveOracleStd = calculateLiveOracleStd( prepegAMM, oraclePriceData, now ); const [ls1, ss1] = calculateSpreadBN( prepegAMM.baseSpread, targetMarkSpreadPct, new BN(0), prepegAMM.maxSpread, prepegAMM.quoteAssetReserve, prepegAMM.terminalQuoteAssetReserve, prepegAMM.pegMultiplier, prepegAMM.baseAssetAmountWithAmm, reservePrice, prepegAMM.totalFeeMinusDistributions, prepegAMM.netRevenueSinceLastFunding, prepegAMM.baseAssetReserve, prepegAMM.minBaseAssetReserve, prepegAMM.maxBaseAssetReserve, prepegAMM.markStd, liveOracleStd, prepegAMM.longIntensityVolume, prepegAMM.shortIntensityVolume, prepegAMM.volume24H ); console.log('spreads:', ls1, ss1); const maxSpread = market0.amm.maxSpread; assert(ls1 + ss1 == maxSpread); console.log( 'pre trade bid/ask:', convertToNumber(bid), '/', convertToNumber(ask), '\n pre trade mark price:', convertToNumber( calculatePrice( prepegAMM.baseAssetReserve, prepegAMM.quoteAssetReserve, prepegAMM.pegMultiplier ) ), 'peg:', prepegAMM.pegMultiplier.toString(), 'tfmq:', prepegAMM.totalFeeMinusDistributions.toString() ); const midPrice = (convertToNumber(bid) + convertToNumber(ask)) / 2; console.log(convertToNumber(oraclePriceData.price), midPrice); console.log( 'getSpotMarketAssetValue:', driftClientUser.getSpotMarketAssetValue().toString() ); const effectiveLeverage = calculateEffectiveLeverage( prepegAMM.baseSpread, prepegAMM.quoteAssetReserve, prepegAMM.terminalQuoteAssetReserve, prepegAMM.pegMultiplier, prepegAMM.baseAssetAmountWithAmm, reservePrice, prepegAMM.totalFeeMinusDistributions ); const inventoryScale = calculateInventoryScale( prepegAMM.baseAssetAmountWithAmm, prepegAMM.baseAssetReserve, prepegAMM.minBaseAssetReserve, prepegAMM.maxBaseAssetReserve, prepegAMM.baseSpread, prepegAMM.maxSpread ); console.log('inventoryScale:', inventoryScale); console.log('effectiveLeverage:', effectiveLeverage); assert(Math.min(effectiveLeverage, 10) == 10); // lol assert(Math.min(inventoryScale, 10) >= 1.66386); assert(Math.min(inventoryScale, 10) <= 1.66387); try { const txSig = await driftClient.updateAMMs([marketIndex]); console.log( 'tx logs', (await connection.getTransaction(txSig, { commitment: 'confirmed' })) .meta.logMessages ); } catch (e) { console.error(e); } const market = driftClient.getPerpMarketAccount(0); const [bid1, ask1] = calculateBidAskPrice( market.amm, oraclePriceData, false ); console.log( 'longSpread/shortSpread:', market.amm.longSpread, market.amm.shortSpread ); const mark1 = calculatePrice( market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier ); console.log( 'post trade bid/ask:', convertToNumber(bid1), '/', convertToNumber(ask1), '\n post trade mark price:', convertToNumber(mark1), 'peg:', market.amm.pegMultiplier.toString(), 'tfmq:', market.amm.totalFeeMinusDistributions.toString() ); assert(bid1.sub(bid).abs().lte(new BN(100))); // minor sdk/contract rounding diff on adj k cost assert(ask1.sub(ask).abs().lte(new BN(100))); // minor sdk/contract rounding diff on adj k cost assert(mark1.sub(reservePrice).abs().lte(new BN(100))); console.log(market.amm.pegMultiplier.toString()); console.log(oraclePriceData.price.toString()); assert(bid1.lt(ask1)); assert(ask1.gt(oraclePriceData.price)); assert(bid1.lt(oraclePriceData.price)); const actualDist = market.amm.totalFee.sub( market.amm.totalFeeMinusDistributions ); console.log('actual distribution:', actualDist.toString()); console.log(prepegAMM.sqrtK.toString(), '==', market.amm.sqrtK.toString()); const marketInvariant = market.amm.sqrtK.mul(market.amm.sqrtK); // check k math good const qAR1 = marketInvariant.div(market.amm.baseAssetReserve); const bAR1 = marketInvariant.div(market.amm.quoteAssetReserve); console.log(qAR1.toString(), '==', market.amm.quoteAssetReserve.toString()); assert(qAR1.eq(market.amm.quoteAssetReserve)); console.log(bAR1.toString(), '==', market.amm.baseAssetReserve.toString()); assert(bAR1.eq(market.amm.baseAssetReserve)); await driftClient.fetchAccounts(); console.log( driftClient.getUserAccount().perpPositions[0].quoteAssetAmount.toString() ); console.log( driftClient.getUserAccount().perpPositions[0].baseAssetAmount.toString() ); assert( driftClient .getUserAccount() .perpPositions[0].baseAssetAmount.eq( new BN(-0.1931 * BASE_PRECISION.toNumber()) ) ); // assert( // driftClient.getUserAccount().perpPositions[0].quoteAssetAmount.toString() == // '4229493402' // ); // $4229.49 let userPosition = driftClient.getUser().getPerpPosition(marketIndex); assert(market.amm.maxSlippageRatio == 50); const limitPrice = oraclePriceData.price .mul(new BN(10248)) .div(new BN(10000)); console.log('close position limit: ', convertToNumber(limitPrice)); assert(limitPrice.gt(oraclePriceData.price)); while (!userPosition.baseAssetAmount.eq(ZERO)) { const closeOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount: userPosition.baseAssetAmount.abs(), reduceOnly: true, price: limitPrice, immediateOrCancel: true, }); const txClose = await driftClient.placeAndTakePerpOrder(closeOrderParams); console.log( 'tx logs', (await connection.getTransaction(txClose, { commitment: 'confirmed' })) .meta.logMessages ); await driftClient.fetchAccounts(); userPosition = driftClient.getUser().getPerpPosition(marketIndex); console.log( 'userPosition.baseAssetAmount: ', userPosition.baseAssetAmount.toString() ); } console.log( driftClient.getUserAccount().perpPositions[0].baseAssetAmount.toString() ); console.log( driftClient.getUserAccount().perpPositions[0].quoteAssetAmount.toString() ); assert( driftClient .getUserAccount() .perpPositions[0].baseAssetAmount.toString() == '0' ); // assert( // driftClient.getUserAccount().perpPositions[0].quoteAssetAmount.toString() == // '203455312' // ); // $203.45 assert( driftClient .getUserAccount() .perpPositions[0].quoteBreakEvenAmount.toString() == '0' ); console.log( 'getSpotMarketAssetValue:', driftClientUser.getSpotMarketAssetValue().toString() ); const spotMarketAccount0 = driftClient.getSpotMarketAccount(0); const feePoolBalance0 = getTokenAmount( market.amm.feePool.scaledBalance, spotMarketAccount0, SpotBalanceType.DEPOSIT ); const pnlPoolBalance0 = getTokenAmount( market.pnlPool.scaledBalance, spotMarketAccount0, SpotBalanceType.DEPOSIT ); console.log('usdcAmount:', usdcAmount.toString()); console.log( 'getSpotMarketAssetValue:', driftClientUser.getSpotMarketAssetValue().toString() ); console.log('feePoolBalance0:', feePoolBalance0.toString()); console.log('pnlPoolBalance0:', pnlPoolBalance0.toString()); await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); await driftClient.fetchAccounts(); console.log( driftClient.getUserAccount().perpPositions[0].quoteAssetAmount.toString() ); console.log( driftClient .getUserAccount() .perpPositions[0].quoteBreakEvenAmount.toString() ); // assert( // driftClient.getUserAccount().perpPositions[0].quoteAssetAmount.toString() == // '157582183' // ); // $157.58 assert( driftClient .getUserAccount() .perpPositions[0].quoteBreakEvenAmount.toString() == '0' ); await depositToFeePoolFromIF(157.476328, driftClient, userUSDCAccount); const market1 = driftClient.getPerpMarketAccount(0); console.log( 'after fee pool deposit totalFeeMinusDistributions:', market1.amm.totalFeeMinusDistributions.toString() ); assert(!market1.amm.totalFeeMinusDistributions.eq(ZERO)); const spotMarketAccount = driftClient.getSpotMarketAccount(0); const revPoolBalance = getTokenAmount( spotMarketAccount.revenuePool.scaledBalance, spotMarketAccount, SpotBalanceType.DEPOSIT ); const feePoolBalance = getTokenAmount( market1.amm.feePool.scaledBalance, spotMarketAccount, SpotBalanceType.DEPOSIT ); const pnlPoolBalance = getTokenAmount( market1.pnlPool.scaledBalance, spotMarketAccount, SpotBalanceType.DEPOSIT ); console.log('usdcAmount:', usdcAmount.toString()); console.log( 'getSpotMarketAssetValue:', driftClientUser.getSpotMarketAssetValue().toString() ); console.log('revPoolBalance:', revPoolBalance.toString()); console.log('feePoolBalance:', feePoolBalance.toString()); console.log('pnlPoolBalance:', pnlPoolBalance.toString()); // assert(driftClientUser.getSpotMarketAssetValue().eq(new BN('10000000000'))); // remainder is of debt is for fees for revenue pool await driftClientUser.unsubscribe(); }); it('5 users, 15 trades, single market, user net win, check invariants', async () => { // create <NUM_USERS> users with 10k that collectively do <NUM_EVENTS> actions const driftClientOld = driftClient; const [_userUSDCAccounts, _user_keys, driftClients, _userAccountInfos] = await initUserAccounts( 5, usdcMint, usdcAmount, provider, marketIndexes, spotMarketIndexes, [], bulkAccountLoader ); let count = 0; let btcPrice = 19790; while (count < 15) { console.log(count); if (count % 3 == 0) { btcPrice *= 1.075; // btcPrice *= 1.001; } else { btcPrice *= 0.999; // btcPrice *= 0.925; } await setFeedPrice(anchor.workspace.Pyth, btcPrice, btcUsd); const oraclePriceData = await getOraclePriceData( anchor.workspace.Pyth, btcUsd ); const market0 = driftClient.getPerpMarketAccount(0); const prepegAMM = calculateUpdatedAMM(market0.amm, oraclePriceData); const [bid, ask] = calculateBidAskPrice(market0.amm, oraclePriceData); const [longSpread, shortSpread] = calculateSpread( prepegAMM, oraclePriceData ); console.log('spreads:', longSpread, shortSpread); console.log( 'bid/oracle/ask:', convertToNumber(bid), btcPrice, convertToNumber(ask) ); let tradeSize = 0.053 * ((count % 7) + 1) * AMM_RESERVE_PRECISION.toNumber(); let tradeDirection; if (count % 2 == 0) { tradeDirection = PositionDirection.LONG; tradeSize *= 2; } else { tradeDirection = PositionDirection.SHORT; } const orderParams = getMarketOrderParams({ marketIndex: 0, direction: tradeDirection, baseAssetAmount: new BN(tradeSize), }); await driftClients[count % 5].placeAndTakePerpOrder(orderParams); count += 1; } let allUserCollateral = 0; let allUserUnsettledPnl = 0; const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), }); await driftClientUser.subscribe(); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const userCollateral = convertToNumber( driftClientUser.getSpotMarketAssetValue(), QUOTE_PRECISION ); const userUnsettledPnl = convertToNumber( driftClientUser .getUserAccount() .perpPositions.reduce((unsettledPnl, position) => { return unsettledPnl.add( position.quoteAssetAmount.add(position.quoteBreakEvenAmount) ); }, ZERO), QUOTE_PRECISION ); console.log('unsettle pnl', userUnsettledPnl); allUserCollateral += userCollateral; allUserUnsettledPnl += userUnsettledPnl; console.log( 'user', 0, ':', '$', userCollateral, '+', userUnsettledPnl, '(unsettled)' ); await driftClientUser.unsubscribe(); const oraclePriceData1 = await getOraclePriceData( anchor.workspace.Pyth, btcUsd ); for (let i = 0; i < driftClients.length; i++) { const pos = driftClients[i].getUserAccount().perpPositions[0]; console.log( 'user', i, 'pos.baseAssetAmount:', pos.baseAssetAmount.toString() ); if (!pos.baseAssetAmount.eq(ZERO)) { // await driftClients[i].closePosition(new BN(0)); await iterClosePosition(driftClients[i], 0, oraclePriceData1); await driftClients[i].settlePNL( await driftClients[i].getUserAccountPublicKey(), driftClients[i].getUserAccount(), 0 ); await driftClients[i].fetchAccounts(); } const driftClientI = driftClients[i]; const driftClientUserI = _userAccountInfos[i]; const userCollateral = convertToNumber( driftClientUserI.getSpotMarketAssetValue(), QUOTE_PRECISION ); await driftClientI.fetchAccounts(); await driftClientUserI.fetchAccounts(); const unsettledPnl = driftClientUserI .getUserAccount() .perpPositions.reduce((unsettledPnl, position) => { return unsettledPnl.add( position.quoteAssetAmount.add(position.quoteEntryAmount) ); }, ZERO); console.log('unsettled pnl', unsettledPnl.toString()); const userUnsettledPnl = convertToNumber(unsettledPnl, QUOTE_PRECISION); allUserCollateral += userCollateral; allUserUnsettledPnl += userUnsettledPnl; console.log( 'user', i + 1, ':', '$', userCollateral, '+', userUnsettledPnl, '(unsettled)' ); await driftClientI.unsubscribe(); await driftClientUserI.unsubscribe(); } const market0 = driftClientOld.getPerpMarketAccount(0); console.log('total Fees:', market0.amm.totalFee.toString()); console.log( 'total Fees minus dist:', market0.amm.totalFeeMinusDistributions.toString() ); const spotMarketAccount = driftClientOld.getSpotMarketAccount( QUOTE_SPOT_MARKET_INDEX ); const revPoolBalance = convertToNumber( getTokenAmount( spotMarketAccount.revenuePool.scaledBalance, spotMarketAccount, SpotBalanceType.DEPOSIT ), QUOTE_PRECISION ); const pnlPoolBalance = convertToNumber( getTokenAmount( market0.pnlPool.scaledBalance, spotMarketAccount, SpotBalanceType.DEPOSIT ), QUOTE_PRECISION ); const feePoolBalance = convertToNumber( getTokenAmount( market0.amm.feePool.scaledBalance, spotMarketAccount, SpotBalanceType.DEPOSIT ), QUOTE_PRECISION ); const usdcDepositBalance = convertToNumber( getTokenAmount( spotMarketAccount.depositBalance, spotMarketAccount, SpotBalanceType.DEPOSIT ), QUOTE_PRECISION ); const usdcBorrowBalance = convertToNumber( getTokenAmount( spotMarketAccount.borrowBalance, spotMarketAccount, SpotBalanceType.DEPOSIT ), QUOTE_PRECISION ); console.log( 'usdc balance:', usdcDepositBalance.toString(), '-', usdcBorrowBalance.toString() ); const sinceStartTFMD = convertToNumber( market0.amm.totalFeeMinusDistributions, QUOTE_PRECISION ); console.log(allUserCollateral.toString()); console.log( 'sum all money:', allUserCollateral, '+', pnlPoolBalance, '+', feePoolBalance, '+', revPoolBalance, '+', allUserUnsettledPnl, '+', sinceStartTFMD, '==', usdcDepositBalance - usdcBorrowBalance ); // assert(allUserCollateral == 60207.477328); // old way for fee -> pnl pool // assert(allUserCollateral == 60115.507665); // assert(pnlPoolBalance == 0); // assert(feePoolBalance == 91.969663); // assert(allUserUnsettledPnl == 673.8094719999999); // assert(usdcDepositBalance == 60207.477328); // assert(sinceStartTFMD == -583.629353); const moneyMissing = Math.abs( allUserCollateral + pnlPoolBalance + feePoolBalance - (usdcDepositBalance - usdcBorrowBalance) ); console.log('moneyMissing:', moneyMissing); assert(moneyMissing < 1e-7); console.log( 'market0.amm.netBaseAssetAmount:', market0.amm.baseAssetAmountWithAmm.toString() ); assert(market0.amm.baseAssetAmountWithAmm.eq(new BN(0))); // console.log(market0); // todo: doesnt add up perfectly (~$2 off), adjust peg/k not precise? // must be less assert( allUserUnsettledPnl + (sinceStartTFMD - (pnlPoolBalance + feePoolBalance)) < 0 ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/resizeSwiftUserOrderIds.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair, PublicKey } from '@solana/web3.js'; import { BN, PRICE_PRECISION, TestClient, User, Wallet, EventSubscriber, OracleSource, ANCHOR_TEST_SWIFT_ID, getSwiftUserAccountPublicKey, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpers'; import { PEG_PRECISION } from '../sdk/src'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; import dotenv from 'dotenv'; dotenv.config(); describe('place and make swift order', () => { const chProgram = anchor.workspace.Drift as Program; let makerDriftClient: TestClient; let makerDriftClientUser: User; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); let usdcMint; let userUSDCAccount; const usdcAmount = new BN(100 * 10 ** 6); let solUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor('', [], []); // @ts-ignore bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), // @ts-ignore chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 32.821); marketIndexes = [0]; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; makerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, swiftID: new PublicKey(ANCHOR_TEST_SWIFT_ID), }); await makerDriftClient.initialize(usdcMint.publicKey, true); await makerDriftClient.subscribe(); await initializeQuoteSpotMarket(makerDriftClient, usdcMint.publicKey); const periodicity = new BN(0); await makerDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(33 * PEG_PRECISION.toNumber()) ); await makerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); makerDriftClientUser = new User({ driftClient: makerDriftClient, userAccountPublicKey: await makerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClientUser.subscribe(); }); after(async () => { await makerDriftClient.unsubscribe(); await makerDriftClientUser.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('increase size of swift user orders', async () => { const [takerDriftClient, takerDriftClientUser] = await initializeNewTakerClientAndUser( bankrunContextWrapper, chProgram, usdcMint, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClientUser.fetchAccounts(); await takerDriftClient.resizeSwiftUserOrders( takerDriftClientUser.userAccountPublicKey, 100 ); const swiftUserOrdersAccountPublicKey = getSwiftUserAccountPublicKey( takerDriftClient.program.programId, takerDriftClientUser.userAccountPublicKey ); const swiftUserOrders = (await takerDriftClient.program.account.swiftUserOrders.fetch( swiftUserOrdersAccountPublicKey )) as any; assert.equal(swiftUserOrders.swiftOrderData.length, 100); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); it('decrease size of swift user orders', async () => { const [takerDriftClient, takerDriftClientUser] = await initializeNewTakerClientAndUser( bankrunContextWrapper, chProgram, usdcMint, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClientUser.fetchAccounts(); await takerDriftClient.resizeSwiftUserOrders( takerDriftClientUser.userAccountPublicKey, 4 ); const swiftUserOrdersAccountPublicKey = getSwiftUserAccountPublicKey( takerDriftClient.program.programId, takerDriftClientUser.userAccountPublicKey ); const swiftUserOrders = (await takerDriftClient.program.account.swiftUserOrders.fetch( swiftUserOrdersAccountPublicKey )) as any; assert.equal(swiftUserOrders.swiftOrderData.length, 4); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); }); async function initializeNewTakerClientAndUser( bankrunContextWrapper: BankrunContextWrapper, chProgram: Program, usdcMint: Keypair, usdcAmount: BN, marketIndexes: number[], spotMarketIndexes: number[], oracleInfos: { publicKey: PublicKey; source: OracleSource }[], bulkAccountLoader: TestBulkAccountLoader ): Promise<[TestClient, User]> { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); await sleep(1000); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const takerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], 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 ); return [takerDriftClient, takerDriftClientUser]; }
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/ksolver.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { Keypair } from '@solana/web3.js'; import { BN, OracleSource } from '../sdk'; import { TestClient, PRICE_PRECISION, calculateReservePrice, calculateTradeSlippage, calculateTargetPriceTrade, PositionDirection, PEG_PRECISION, MAX_LEVERAGE, QUOTE_PRECISION, convertToNumber, User, } from '../sdk/src'; import { liquidityBook } from './liquidityBook'; import { mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } from './testHelpers'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('AMM Curve', () => { // K SOLVER: find opitimal k given exchange details // const NUM_USERS = 100; const MAX_DEPOSIT = 1000; const initialSOLPrice = 150; const MAX_USER_TRADE = MAX_DEPOSIT * MAX_LEVERAGE.toNumber(); // const ARB_CAPITAL = 50000; // const TARGET_MAX_SLIPPAGE = 0.2; // for MAX_DEPOSIT * MAX_LEVERAGE position // function calculateTheoPriceImpact( // direction: PositionDirection, // amount: BN, // kSqrt: BN, // unit?: // | 'entryPrice' // | 'maxPrice' // | 'priceDelta' // | 'priceDeltaAsNumber' // | 'pctAvg' // | 'pctMax' // | 'quoteAssetAmount' // | 'quoteAssetAmountPeg' // | 'acquiredBaseAssetAmount' // | 'acquiredQuoteAssetAmount' // ) { // if (amount.eq(new BN(0))) { // return new BN(0); // } // const market = this.getMarketsAccount().markets[marketIndex.toNumber()]; // const oldPrice = this.calculateReservePrice(marketIndex); // const invariant = market.amm.sqrtK.mul(market.amm.sqrtK); // const [newQuoteAssetAmount, newBaseAssetAmount] = this.findSwapOutput( // kSqrt, // kSqrt, // direction, // amount.abs(), // 'quote', // invariant, // market.amm.pegMultiplier // ); // const entryPrice = this.calculateCurvePriceWithMantissa( // market.amm.baseAssetReserve.sub(newBaseAssetAmount), // market.amm.quoteAssetReserve.sub(newQuoteAssetAmount), // market.amm.pegMultiplier // ).mul(new BN(-1)); // if (entryPrice.eq(new BN(0))) { // return new BN(0); // } // const newPrice = this.calculateCurvePriceWithMantissa( // newBaseAssetAmount, // newQuoteAssetAmount, // market.amm.pegMultiplier // ); // if (oldPrice == newPrice) { // throw new Error('insufficient `amount` passed:'); // } // let slippage; // if (newPrice.gt(oldPrice)) { // if (unit == 'pctMax') { // slippage = newPrice.sub(oldPrice).mul(PRICE_PRECISION).div(oldPrice); // } else if (unit == 'pctAvg') { // slippage = entryPrice.sub(oldPrice).mul(PRICE_PRECISION).div(oldPrice); // } else if ( // [ // 'priceDelta', // 'quoteAssetAmount', // 'quoteAssetAmountPeg', // 'priceDeltaAsNumber', // ].includes(unit) // ) { // slippage = newPrice.sub(oldPrice); // } // } else { // if (unit == 'pctMax') { // slippage = oldPrice.sub(newPrice).mul(PRICE_PRECISION).div(oldPrice); // } else if (unit == 'pctAvg') { // slippage = oldPrice.sub(entryPrice).mul(PRICE_PRECISION).div(oldPrice); // } else if ( // [ // 'priceDelta', // 'quoteAssetAmount', // 'quoteAssetAmountPeg', // 'priceDeltaAsNumber', // ].includes(unit) // ) { // slippage = oldPrice.sub(newPrice); // } // } // if (unit == 'quoteAssetAmount') { // slippage = slippage.mul(amount); // } else if (unit == 'quoteAssetAmountPeg') { // slippage = slippage.mul(amount).div(market.amm.pegMultiplier); // } else if (unit == 'priceDeltaAsNumber') { // slippage = convertToNumber(slippage); // } // return slippage; // } // function kSolver() { // const kSqrt0 = new anchor.BN(2 * 10 ** 13); // let count = 0; // let avgSlippageCenter = calculateTheoPriceImpact( // PositionDirection.LONG, // new BN(MAX_DEPOSIT).mul(MAX_LEVERAGE).mul(PRICE_PRECISION), // kSqrt0, // 'pctMax' // ); // const targetSlippageBN = new BN( // TARGET_MAX_SLIPPAGE * PRICE_PRECISION.toNumber() // ); // let kSqrtI: BN; // while (avgSlippageCenter.gt(targetSlippageBN) || count > 1000) { // kSqrtI = kSqrt0.mul(targetSlippageBN.div(avgSlippageCenter)); // avgSlippageCenter = calculateTheoPriceImpact( // PositionDirection.LONG, // new BN(MAX_DEPOSIT).mul(MAX_LEVERAGE).mul(PRICE_PRECISION), // kSqrtI, // 'pctMax' // ); // count += 1; // } // return kSqrtI; // } const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; const kSqrt = new anchor.BN(2 * 10 ** 12); let usdcMint: Keypair; let userUSDCAccount: Keypair; let solUsdOracle; const marketIndex = 0; const initialSOLPriceBN = new BN(initialSOLPrice * PEG_PRECISION.toNumber()); function normAssetAmount(assetAmount: BN, pegMultiplier: BN): BN { // assetAmount is scaled to offer comparable slippage return assetAmount.mul(PRICE_PRECISION).div(pegMultiplier); } const usdcAmount = new BN(1000 * 10 ** 6); const solPositionInitialValue = usdcAmount; let userAccount: User; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); solUsdOracle = await mockOracleNoProgram( bankrunContextWrapper, initialSOLPrice ); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [ { publicKey: solUsdOracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); const periodicity = new BN(60 * 60); // 1 HOUR const kSqrtNorm = normAssetAmount(kSqrt, initialSOLPriceBN); await driftClient.initializePerpMarket( 0, solUsdOracle, kSqrtNorm, kSqrtNorm, periodicity, initialSOLPriceBN ); await driftClient.initializeUserAccount(); userAccount = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await userAccount.subscribe(); }); after(async () => { await driftClient.unsubscribe(); await userAccount.unsubscribe(); }); const showBook = (marketIndex) => { const market = driftClient.getPerpMarketAccount(marketIndex); const oraclePriceData = driftClient.getOracleDataForPerpMarket(marketIndex); const currentMark = calculateReservePrice(market, oraclePriceData); const [bidsPrice, bidsCumSize, asksPrice, asksCumSize] = liquidityBook( market, 3, 0.5 ); for (let i = asksCumSize.length - 1; i >= 0; i--) { console.log( convertToNumber(asksPrice[i]), convertToNumber(asksCumSize[i], QUOTE_PRECISION) ); } console.log('------------'); console.log(currentMark.toNumber() / PRICE_PRECISION.toNumber()); console.log( 'peg:', convertToNumber(market.amm.pegMultiplier, PEG_PRECISION), 'k (M*M):', convertToNumber(market.amm.sqrtK) ); console.log('------------'); for (let i = 0; i < bidsCumSize.length; i++) { console.log( convertToNumber(bidsPrice[i]), convertToNumber(bidsCumSize[i], QUOTE_PRECISION) ); } }; it('After Deposit', async () => { await driftClient.deposit(usdcAmount, 0, userUSDCAccount.publicKey); }); it('After Position Taken', async () => { await driftClient.openPosition( PositionDirection.LONG, solPositionInitialValue, marketIndex ); const avgSlippageCenter = calculateTradeSlippage( PositionDirection.LONG, new BN(MAX_USER_TRADE * PRICE_PRECISION.toNumber()), driftClient.getPerpMarketAccount(0) )[0]; showBook(marketIndex); const targetPriceUp = new BN( initialSOLPrice * PRICE_PRECISION.toNumber() * 2 ); const [_direction, tradeSize, _] = calculateTargetPriceTrade( driftClient.getPerpMarketAccount(marketIndex), targetPriceUp ); await driftClient.moveAmmToPrice(marketIndex, targetPriceUp); const avgSlippage25PctOut = calculateTradeSlippage( PositionDirection.LONG, new BN(MAX_USER_TRADE * PRICE_PRECISION.toNumber()), driftClient.getPerpMarketAccount(0) )[0]; showBook(marketIndex); console.log( 'arbBot Long Size', convertToNumber(tradeSize, QUOTE_PRECISION), '\n Center Slippage:', convertToNumber(avgSlippageCenter) / 100, '\n 100% up out Slippage:', convertToNumber(avgSlippage25PctOut) / 100 ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/userAccount.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { mockOracleNoProgram, setFeedPriceNoProgram, mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, getFeedDataNoProgram, sleep, } from './testHelpers'; import { Keypair } from '@solana/web3.js'; import { assert } from 'chai'; import { TestClient, User, PEG_PRECISION, MAX_LEVERAGE, PositionDirection, QUOTE_SPOT_MARKET_INDEX, MarketStatus, BASE_PRECISION, BN, OracleSource, calculateWorstCaseBaseAssetAmount, calculateMarketMarginRatio, calculateReservePrice, convertToNumber, calculatePrice, AMM_RESERVE_PRECISION, } from '../sdk/src'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('User Account', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; const ammInitialQuoteAssetAmount = new anchor.BN(2 * 10 ** 9).mul( new BN(10 ** 5) ); const ammInitialBaseAssetAmount = new anchor.BN(2 * 10 ** 9).mul( new BN(10 ** 5) ); let usdcMint: Keypair; let userUSDCAccount: Keypair; let solUsdOracle; const marketIndex = 0; const initialSOLPrice = 50; const usdcAmount = new BN(20 * 10 ** 6); let userAccount: User; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsdOracle = await mockOracleNoProgram( bankrunContextWrapper, initialSOLPrice, -10, 0.0005 ); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [{ publicKey: solUsdOracle, source: OracleSource.PYTH }], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(0); const periodicity = new BN(60 * 60); // 1 HOUR await driftClient.initializePerpMarket( 0, solUsdOracle, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity, new BN(initialSOLPrice).mul(PEG_PRECISION) ); await driftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); await driftClient.initializeUserAccount(); userAccount = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await userAccount.subscribe(); }); after(async () => { await driftClient.unsubscribe(); await userAccount.unsubscribe(); }); const assertState = async ( expectedBuyingPower: BN, expectedFreeCollateral: BN, expectedPNL: BN, expectedTotalCollateral: BN, expectedLeverage: BN, expectedMarginRatio: BN ) => { // todo: dont hate me await userAccount.fetchAccounts(); const totalCollateral = userAccount.getTotalCollateral(); console.log( 'totalCollateral', totalCollateral.toNumber(), expectedTotalCollateral.toNumber() ); const pnl = userAccount.getUnrealizedPNL(false); console.log('pnl', pnl.toNumber(), expectedPNL.toNumber()); const freeCollateral = userAccount.getFreeCollateral(); console.log( 'freeCollateral', freeCollateral.toNumber(), expectedFreeCollateral.toNumber() ); const leverage = userAccount.getLeverage(); console.log('leverage', leverage.toNumber(), expectedLeverage.toNumber()); const marginRatio = userAccount.getMarginRatio(); console.log( 'marginRatio', marginRatio.toNumber(), expectedMarginRatio.toNumber() ); const buyingPower = userAccount.getPerpBuyingPower(0); console.log( 'buyingPower', buyingPower.toNumber(), expectedBuyingPower.toNumber() ); assert(pnl.eq(expectedPNL)); assert(buyingPower.eq(expectedBuyingPower)); assert(marginRatio.eq(expectedMarginRatio)); assert(totalCollateral.eq(expectedTotalCollateral)); assert(leverage.eq(expectedLeverage)); assert(freeCollateral.eq(expectedFreeCollateral)); }; it('Before Deposit', async () => { const expectedBuyingPower = new BN(0); const expectedFreeCollateral = new BN(0); const expectedPNL = new BN(0); const expectedTotalCollateral = new BN(0); const expectedLeverage = new BN(0); const expectedMarginRatio = new BN(Number.MAX_SAFE_INTEGER); await assertState( expectedBuyingPower, expectedFreeCollateral, expectedPNL, expectedTotalCollateral, expectedLeverage, expectedMarginRatio ); }); it('After Deposit', async () => { await driftClient.deposit( usdcAmount, QUOTE_SPOT_MARKET_INDEX, userUSDCAccount.publicKey ); const expectedBuyingPower = new BN(usdcAmount).mul(MAX_LEVERAGE); const expectedFreeCollateral = new BN(20000000); const expectedPNL = new BN(0); const expectedTotalCollateral = new BN(20000000); const expectedLeverage = new BN(0); const expectedMarginRatio = new BN(Number.MAX_SAFE_INTEGER); await assertState( expectedBuyingPower, expectedFreeCollateral, expectedPNL, expectedTotalCollateral, expectedLeverage, expectedMarginRatio ); }); it('After Position Taken', async () => { await driftClient.openPosition( PositionDirection.LONG, BASE_PRECISION, marketIndex ); await driftClient.fetchAccounts(); await userAccount.fetchAccounts(); const perpPosition = userAccount.getPerpPosition(marketIndex); const market = driftClient.getPerpMarketAccount(perpPosition.marketIndex); const oraclePrice = driftClient.getOracleDataForPerpMarket( market.marketIndex ).price; const reservePrice = calculatePrice( market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier ); console.log( 'mark vs oracle price:', convertToNumber(reservePrice), convertToNumber(oraclePrice) ); await setFeedPriceNoProgram( bankrunContextWrapper, convertToNumber(reservePrice.sub(new BN(250))), solUsdOracle ); await sleep(5000); await driftClient.fetchAccounts(); const oracleP2 = await getFeedDataNoProgram( bankrunContextWrapper.connection, solUsdOracle ); console.log('oracleP2:', oracleP2.price); const oraclePrice2 = driftClient.getOracleDataForPerpMarket( market.marketIndex ).price; const reservePrice2 = calculateReservePrice(market, oraclePrice); console.log( 'mark2 vs oracle2 price:', convertToNumber(reservePrice2), convertToNumber(oraclePrice2) ); const worstCaseBaseAssetAmount = calculateWorstCaseBaseAssetAmount( perpPosition, market, driftClient.getOracleDataForPerpMarket(perpPosition.marketIndex).price ); const worstCaseAssetValue = worstCaseBaseAssetAmount .abs() .mul(oraclePrice) .div(AMM_RESERVE_PRECISION); console.log('worstCaseAssetValue:', worstCaseAssetValue.toNumber()); const marketMarginRatio = calculateMarketMarginRatio( market, worstCaseBaseAssetAmount.abs(), 'Maintenance' ); console.log('marketMarginRatio:', marketMarginRatio); const expectedPNL = new BN(-50002); const expectedTotalCollateral = new BN(19949998); const expectedBuyingPower = new BN(49749740); const expectedFreeCollateral = new BN(9949948); const expectedLeverage = new BN(25062); const expectedMarginRatio = new BN(3989); await assertState( expectedBuyingPower, expectedFreeCollateral, expectedPNL, expectedTotalCollateral, expectedLeverage, expectedMarginRatio ); }); it('After Position Price Moves', async () => { await driftClient.moveAmmPrice( marketIndex, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount.mul(new BN(11)).div(new BN(10)) ); const perpPosition = userAccount.getPerpPosition(marketIndex); const market = driftClient.getPerpMarketAccount(perpPosition.marketIndex); const oraclePrice = driftClient.getOracleDataForPerpMarket( market.marketIndex ).price; const reservePrice = calculatePrice( market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier ); console.log( 'mark vs oracle price:', convertToNumber(reservePrice), convertToNumber(oraclePrice) ); await setFeedPriceNoProgram( bankrunContextWrapper, convertToNumber(reservePrice.sub(new BN(275))), solUsdOracle ); await sleep(5000); await driftClient.fetchAccounts(); const oracleP2 = await getFeedDataNoProgram( bankrunContextWrapper.connection, solUsdOracle ); console.log('oracleP2:', oracleP2.price); const oraclePrice2 = driftClient.getOracleDataForPerpMarket( market.marketIndex ).price; const reservePrice2 = calculateReservePrice(market, oraclePrice); console.log( 'mark2 vs oracle2 price:', convertToNumber(reservePrice2), convertToNumber(oraclePrice2) ); const expectedPNL = new BN(4949472); const expectedTotalCollateral = new BN(20000000); const expectedBuyingPower = new BN(45000280); const expectedFreeCollateral = new BN(9000056); const expectedLeverage = new BN(22044); const expectedMarginRatio = new BN(4536); await assertState( expectedBuyingPower, expectedFreeCollateral, expectedPNL, expectedTotalCollateral, expectedLeverage, expectedMarginRatio ); }); it('Close Position', async () => { await driftClient.closePosition(marketIndex); const expectedBuyingPower = new BN(100000000); const expectedFreeCollateral = new BN(20000000); const expectedPNL = new BN(4894473); const expectedTotalCollateral = new BN(20000000); const expectedLeverage = new BN(0); const expectedMarginRatio = new BN(Number.MAX_SAFE_INTEGER); await assertState( expectedBuyingPower, expectedFreeCollateral, expectedPNL, expectedTotalCollateral, expectedLeverage, expectedMarginRatio ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/subaccounts.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { getUserAccountPublicKey, isVariant, QUOTE_SPOT_MARKET_INDEX, TestClient, BN, EventSubscriber, fetchUserAccounts, } from '../sdk/src'; import { createFundedKeyPair, initializeQuoteSpotMarket, initializeSolSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } from './testHelpers'; import { decodeName } from '../sdk/src/userName'; import { assert } from 'chai'; import { getTokenAmount, LAMPORTS_PRECISION, MARGIN_PRECISION, SpotBalanceType, } from '../sdk'; import { PublicKey } from '@solana/web3.js'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('subaccounts', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let solOracle: PublicKey; let usdcMint; let usdcAccount; const usdcAmount = new BN(10 * 10 ** 6); before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); usdcAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); const marketIndexes = [0, 1]; const spotMarketIndexes = [0, 1]; driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 100); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await initializeSolSpotMarket(driftClient, solOracle); await driftClient.updatePerpAuctionDuration(new BN(0)); }); after(async () => { await driftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('Initialize first account', async () => { const donationAmount = LAMPORTS_PRECISION; const subAccountId = 0; const name = 'CRISP'; await driftClient.initializeUserAccountAndDepositCollateral( LAMPORTS_PRECISION, bankrunContextWrapper.provider.wallet.publicKey, 1, subAccountId, name, undefined, undefined, donationAmount ); await driftClient.fetchAccounts(); assert(driftClient.getUserAccount().subAccountId === subAccountId); assert(decodeName(driftClient.getUserAccount().name) === name); const userStats = driftClient.getUserStats().getAccount(); assert(userStats.numberOfSubAccounts === 1); assert(driftClient.getStateAccount().numberOfAuthorities.eq(new BN(1))); assert(driftClient.getStateAccount().numberOfSubAccounts.eq(new BN(1))); const solSpotMarket = driftClient.getSpotMarketAccount(1); const revenuePool = solSpotMarket.revenuePool; const tokenAmount = getTokenAmount( revenuePool.scaledBalance, solSpotMarket, SpotBalanceType.DEPOSIT ); assert(tokenAmount.eq(donationAmount)); }); it('Initialize second account', async () => { const donationAmount = LAMPORTS_PRECISION; const subAccountId = 1; const name = 'LIL PERP'; await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, usdcAccount.publicKey, 0, 1, name, undefined, undefined, donationAmount ); await driftClient.addUser(1); await driftClient.switchActiveUser(1); assert(driftClient.getUserAccount().subAccountId === subAccountId); assert(decodeName(driftClient.getUserAccount().name) === name); const userStats = driftClient.getUserStats().getAccount(); assert(userStats.numberOfSubAccounts === 2); assert(userStats.numberOfSubAccountsCreated === 2); assert(driftClient.getStateAccount().numberOfAuthorities.eq(new BN(1))); assert(driftClient.getStateAccount().numberOfSubAccounts.eq(new BN(2))); const solSpotMarket = driftClient.getSpotMarketAccount(1); const revenuePool = solSpotMarket.revenuePool; const tokenAmount = getTokenAmount( revenuePool.scaledBalance, solSpotMarket, SpotBalanceType.DEPOSIT ); assert(tokenAmount.eq(donationAmount.muln(2))); }); it('Fetch all user account', async () => { const userAccounts = await fetchUserAccounts( bankrunContextWrapper.connection.toConnection(), chProgram, bankrunContextWrapper.provider.wallet.publicKey, 2 ); assert(userAccounts.length === 2); }); it('Deposit and transfer between accounts', async () => { const txSig = await driftClient.transferDeposit( usdcAmount, QUOTE_SPOT_MARKET_INDEX, 1, 0 ); await driftClient.switchActiveUser(0); assert(driftClient.getQuoteAssetTokenAmount().eq(usdcAmount)); await eventSubscriber.awaitTx(txSig); const depositRecords = eventSubscriber.getEventsArray('DepositRecord'); const toUser = await getUserAccountPublicKey( chProgram.programId, bankrunContextWrapper.provider.wallet.publicKey, 0 ); const withdrawRecord = depositRecords[1]; assert(isVariant(withdrawRecord.direction, 'withdraw')); assert(withdrawRecord.transferUser.equals(toUser)); const fromUser = await getUserAccountPublicKey( chProgram.programId, bankrunContextWrapper.provider.wallet.publicKey, 1 ); const depositRecord = depositRecords[0]; assert(isVariant(depositRecord.direction, 'deposit')); assert(depositRecord.transferUser.equals(fromUser)); }); it('Update user name', async () => { const subAccountId = 0; const name = 'lil perp v2'; await driftClient.updateUserName(name, subAccountId); await driftClient.fetchAccounts(); assert(decodeName(driftClient.getUserAccount().name) === name); }); it('Update custom margin ratio', async () => { const subAccountId = 0; const customMarginRatio = MARGIN_PRECISION.toNumber() * 2; const updates = [{ marginRatio: customMarginRatio, subAccountId }]; await driftClient.updateUserCustomMarginRatio(updates); await driftClient.fetchAccounts(); assert(driftClient.getUserAccount().maxMarginRatio === customMarginRatio); }); it('Update delegate', async () => { const delegateKeyPair = await createFundedKeyPair(bankrunContextWrapper); await driftClient.updateUserDelegate(delegateKeyPair.publicKey); await driftClient.fetchAccounts(); assert( driftClient.getUserAccount().delegate.equals(delegateKeyPair.publicKey) ); }); it('delete user', async () => { await driftClient.switchActiveUser(1); let deleteFailed = false; try { const txSig = await driftClient.deleteUser(0); bankrunContextWrapper.printTxLogs(txSig); } catch (e) { deleteFailed = true; } assert(deleteFailed); await driftClient.deleteUser(1); assert(driftClient.getStateAccount().numberOfAuthorities.eq(new BN(1))); assert(driftClient.getStateAccount().numberOfSubAccounts.eq(new BN(1))); }); it('fail to reinitialize subaccount 0', async () => { const subAccountId = 1; const name = 'LIL PERP'; let initializeFailed = false; try { await driftClient.initializeUserAccount(subAccountId, name); } catch (e) { assert(e.toString().includes('0x1846')); initializeFailed = true; } assert(initializeFailed); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/switchboardOnDemand.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { AccountInfo, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; import { initializeQuoteSpotMarket, mockUSDCMint } from './testHelpers'; import { OracleSource, TestClient } from '../sdk/src'; import { startAnchor } from 'solana-bankrun'; import { ORACLE_ADDRESS_1, ORACLE_ADDRESS_1_DATA, ORACLE_ADDRESS_2, ORACLE_ADDRESS_2_DATA, ORACLE_ADDRESS_3, ORACLE_ADDRESS_3_DATA, ORACLE_ADDRESS_4, ORACLE_ADDRESS_4_DATA, ORACLE_ADDRESS_5, ORACLE_ADDRESS_5_DATA, ORACLE_ADDRESS_6, ORACLE_ADDRESS_6_DATA, ORACLE_ADDRESS_7, ORACLE_ADDRESS_7_DATA, PULL_FEED_ACCOUNT_DATA, PULL_FEED_ADDRESS, QUEUE_ACCOUNT_DATA, QUEUE_ADDRESS, } from './switchboardOnDemandData'; const SB_ON_DEMAND_PID = 'SBondMDrcV3K4kxZR1HNVT7osZxAHVHgYXL5Ze1oMUv'; const PULL_FEED_ACCOUNT_INFO: AccountInfo<Buffer> = { executable: false, lamports: LAMPORTS_PER_SOL, owner: new PublicKey(SB_ON_DEMAND_PID), rentEpoch: 0, data: Buffer.from(PULL_FEED_ACCOUNT_DATA, 'base64'), }; const QUEUE_ACCOUNT_INFO: AccountInfo<Buffer> = { executable: false, lamports: LAMPORTS_PER_SOL, owner: new PublicKey(SB_ON_DEMAND_PID), rentEpoch: 0, data: Buffer.from(QUEUE_ACCOUNT_DATA, 'base64'), }; const getOracleAccountInfo = (accountData: string): AccountInfo<Buffer> => { return { executable: false, lamports: LAMPORTS_PER_SOL, owner: new PublicKey(SB_ON_DEMAND_PID), rentEpoch: 0, data: Buffer.from(accountData, 'base64'), }; }; describe('switchboard on demand', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; before(async () => { // use bankrun builtin function to start solana program test const context = await startAnchor( '', [ { name: 'switchboard_on_demand', programId: new PublicKey(SB_ON_DEMAND_PID), }, ], [ // load account infos into banks client like this { address: PULL_FEED_ADDRESS, info: PULL_FEED_ACCOUNT_INFO, }, { address: QUEUE_ADDRESS, info: QUEUE_ACCOUNT_INFO, }, { address: ORACLE_ADDRESS_1, info: getOracleAccountInfo(ORACLE_ADDRESS_1_DATA), }, { address: ORACLE_ADDRESS_2, info: getOracleAccountInfo(ORACLE_ADDRESS_2_DATA), }, { address: ORACLE_ADDRESS_3, info: getOracleAccountInfo(ORACLE_ADDRESS_3_DATA), }, { address: ORACLE_ADDRESS_4, info: getOracleAccountInfo(ORACLE_ADDRESS_4_DATA), }, { address: ORACLE_ADDRESS_5, info: getOracleAccountInfo(ORACLE_ADDRESS_5_DATA), }, { address: ORACLE_ADDRESS_6, info: getOracleAccountInfo(ORACLE_ADDRESS_6_DATA), }, { address: ORACLE_ADDRESS_7, info: getOracleAccountInfo(ORACLE_ADDRESS_7_DATA), }, ] ); // wrap the context to use it with the test helpers bankrunContextWrapper = new BankrunContextWrapper(context); // don't use regular bulk account loader, use test bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); driftClient = new TestClient({ // call toConnection to avoid annoying type error connection: bankrunContextWrapper.connection.toConnection(), // make sure to avoid regular `provider.X`, they don't show as errors wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [], spotMarketIndexes: [0], subAccountIds: [], // make sure to add [] for subaccounts or client will gpa oracleInfos: [ { publicKey: PULL_FEED_ADDRESS, source: OracleSource.SWITCHBOARD_ON_DEMAND, }, ], // BANKRUN DOES NOT WORK WITH WEBSOCKET accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); }); after(async () => { await driftClient.unsubscribe(); }); // it('post update', async () => { // await driftClient.getPostSwitchboardOnDemandUpdateAtomicIx( // PULL_FEED_ADDRESS // ); // }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/multipleMakerOrders.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { TestClient, BN, PRICE_PRECISION, PositionDirection, EventSubscriber, MarketStatus, BASE_PRECISION, isVariant, OracleSource, PEG_PRECISION, } from '../sdk/src'; import { createUserWithUSDCAccount, initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, } from './testHelpers'; import { ContractTier, MARGIN_PRECISION, OrderType } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('multiple maker orders', () => { const chProgram = anchor.workspace.Drift as Program; let fillerDriftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(100000); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(100000 * 10 ** 6); let solUsd; let dogUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 100); dogUsd = await mockOracleNoProgram(bankrunContextWrapper, 0.6899, -4, 0); marketIndexes = [0, 1]; spotMarketIndexes = [0]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; fillerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClient.initialize(usdcMint.publicKey, true); await fillerDriftClient.subscribe(); await initializeQuoteSpotMarket(fillerDriftClient, usdcMint.publicKey); await fillerDriftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(60 * 60); // 1 HOUR await fillerDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(100 * PEG_PRECISION.toNumber()) ); await fillerDriftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); await fillerDriftClient.updatePerpMarketBaseSpread( 0, PRICE_PRECISION.toNumber() / 8 ); await fillerDriftClient.initializePerpMarket( 1, dogUsd, ammInitialBaseAssetReserve.div(new BN(100000)), ammInitialQuoteAssetReserve.div(new BN(100000)), periodicity, new BN(0.69 * PEG_PRECISION.toNumber()), OracleSource.PYTH, ContractTier.A, MARGIN_PRECISION.toNumber() / 4, // 4x MARGIN_PRECISION.toNumber() / 5 // 5x ); await fillerDriftClient.updatePerpMarketStatus(1, MarketStatus.ACTIVE); await fillerDriftClient.updatePerpMarketBaseSpread( 1, PRICE_PRECISION.toNumber() / 80 ); await fillerDriftClient.updatePerpMarketMarginRatio( 0, MARGIN_PRECISION.toNumber() / 2, MARGIN_PRECISION.toNumber() / 3 ); await fillerDriftClient.updatePerpMarketMaxSpread( 0, PRICE_PRECISION.toNumber() / 5 ); await fillerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); }); beforeEach(async () => { await fillerDriftClient.moveAmmPrice( 0, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve ); }); after(async () => { await fillerDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('taker long solUsd', async () => { const [takerDriftClient, takerUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClient.deposit(usdcAmount, 0, takerUSDCAccount); const [makerDriftClient, makerUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await makerDriftClient.deposit(usdcAmount, 0, makerUSDCAccount); for (let i = 0; i < 6; i++) { await makerDriftClient.placePerpOrder({ marketIndex: 0, direction: PositionDirection.SHORT, price: new BN(95 + i).mul(PRICE_PRECISION), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); } const [secondMakerDriftClient, secondMakerUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await secondMakerDriftClient.deposit(usdcAmount, 0, secondMakerUSDCAccount); for (let i = 0; i < 6; i++) { await secondMakerDriftClient.placePerpOrder({ marketIndex: 0, direction: PositionDirection.SHORT, price: new BN(95 + i).mul(PRICE_PRECISION), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); } const takerBaseAssetAmount = new BN(6).mul(BASE_PRECISION); await takerDriftClient.placePerpOrder({ marketIndex: 0, orderType: OrderType.LIMIT, price: new BN(100).mul(PRICE_PRECISION), direction: PositionDirection.LONG, baseAssetAmount: takerBaseAssetAmount, }); const makerInfo = [ { maker: await makerDriftClient.getUserAccountPublicKey(), makerUserAccount: makerDriftClient.getUserAccount(), makerStats: await makerDriftClient.getUserStatsAccountPublicKey(), }, { maker: await secondMakerDriftClient.getUserAccountPublicKey(), makerUserAccount: secondMakerDriftClient.getUserAccount(), makerStats: await secondMakerDriftClient.getUserStatsAccountPublicKey(), }, ]; const txSig = await fillerDriftClient.fillPerpOrder( await takerDriftClient.getUserAccountPublicKey(), takerDriftClient.getUserAccount(), takerDriftClient.getOrder(1), makerInfo ); bankrunContextWrapper.printTxLogs(txSig); const orderActionRecords = eventSubscriber .getEventsArray('OrderActionRecord') .filter((record) => isVariant(record.action, 'fill')); assert(orderActionRecords.length === 6); const takerPosition = takerDriftClient.getUser().getPerpPosition(0); assert(takerPosition.baseAssetAmount.eq(takerBaseAssetAmount)); assert(takerPosition.quoteAssetAmount.eq(new BN(-576576000))); const makerPosition = makerDriftClient.getUser().getPerpPosition(0); assert( makerPosition.baseAssetAmount.eq( takerBaseAssetAmount.neg().div(new BN(2)) ) ); assert(makerPosition.quoteAssetAmount.eq(new BN(288057600))); const secondMakerPosition = secondMakerDriftClient .getUser() .getPerpPosition(0); assert( secondMakerPosition.baseAssetAmount.eq( takerBaseAssetAmount.neg().div(new BN(2)) ) ); assert(secondMakerPosition.quoteAssetAmount.eq(new BN(288057600))); for (let i = 0; i < 3; i++) { await makerDriftClient.placePerpOrder({ marketIndex: 0, direction: PositionDirection.LONG, price: new BN(101 - i).mul(PRICE_PRECISION), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); } for (let i = 0; i < 3; i++) { await secondMakerDriftClient.placePerpOrder({ marketIndex: 0, direction: PositionDirection.LONG, price: new BN(101 - i).mul(PRICE_PRECISION), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); } await setFeedPriceNoProgram(bankrunContextWrapper, 90, solUsd); await takerDriftClient.placePerpOrder({ marketIndex: 0, orderType: OrderType.LIMIT, price: new BN(90).mul(PRICE_PRECISION), direction: PositionDirection.SHORT, baseAssetAmount: takerBaseAssetAmount, }); const txSig2 = await fillerDriftClient.fillPerpOrder( await takerDriftClient.getUserAccountPublicKey(), takerDriftClient.getUserAccount(), takerDriftClient.getOrder(2), makerInfo ); const takerPosition2 = takerDriftClient.getUser().getPerpPosition(0); assert(takerPosition2.baseAssetAmount.eq(new BN(0))); bankrunContextWrapper.printTxLogs(txSig2); await takerDriftClient.unsubscribe(); await makerDriftClient.unsubscribe(); await secondMakerDriftClient.unsubscribe(); }); it('taker short dogUsd', async () => { const [takerDriftClient, takerUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClient.deposit(usdcAmount, 0, takerUSDCAccount); const [makerDriftClient, makerUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await makerDriftClient.deposit(usdcAmount, 0, makerUSDCAccount); for (let i = 0; i < 1; i++) { await makerDriftClient.placePerpOrder({ marketIndex: 1, direction: PositionDirection.LONG, price: new BN((0.69 - i / 100) * PRICE_PRECISION.toNumber()), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); } const [secondMakerDriftClient, secondMakerUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await secondMakerDriftClient.deposit(usdcAmount, 0, secondMakerUSDCAccount); for (let i = 0; i < 16; i++) { await secondMakerDriftClient.placePerpOrder({ marketIndex: 1, direction: PositionDirection.LONG, price: new BN((0.69 - i / 500) * PRICE_PRECISION.toNumber()), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); } const [thirdMakerDriftClient, thirdMakerUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await thirdMakerDriftClient.deposit(usdcAmount, 0, thirdMakerUSDCAccount); for (let i = 0; i < 32; i++) { if (i % 2 == 0) { await thirdMakerDriftClient.placePerpOrder({ marketIndex: 1, direction: PositionDirection.LONG, price: new BN((0.69 - i / 1000) * PRICE_PRECISION.toNumber()), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); } else { await thirdMakerDriftClient.placePerpOrder({ marketIndex: 1, direction: PositionDirection.LONG, oraclePriceOffset: -(i / 1000) * PRICE_PRECISION.toNumber(), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); } } await setFeedPriceNoProgram(bankrunContextWrapper, 0.675, dogUsd); const takerBaseAssetAmount = new BN(600).mul(BASE_PRECISION); await takerDriftClient.placePerpOrder({ marketIndex: 1, orderType: OrderType.LIMIT, price: new BN(0.675 * PRICE_PRECISION.toNumber()), direction: PositionDirection.SHORT, baseAssetAmount: takerBaseAssetAmount, }); const makerInfo = [ { maker: await makerDriftClient.getUserAccountPublicKey(), makerUserAccount: makerDriftClient.getUserAccount(), makerStats: await makerDriftClient.getUserStatsAccountPublicKey(), }, { maker: await secondMakerDriftClient.getUserAccountPublicKey(), makerUserAccount: secondMakerDriftClient.getUserAccount(), makerStats: await secondMakerDriftClient.getUserStatsAccountPublicKey(), }, { maker: await thirdMakerDriftClient.getUserAccountPublicKey(), makerUserAccount: thirdMakerDriftClient.getUserAccount(), makerStats: await thirdMakerDriftClient.getUserStatsAccountPublicKey(), }, ]; const txSig = await fillerDriftClient.fillPerpOrder( await takerDriftClient.getUserAccountPublicKey(), takerDriftClient.getUserAccount(), takerDriftClient.getOrder(1), makerInfo ); bankrunContextWrapper.printTxLogs(txSig); const orderActionRecords = eventSubscriber .getEventsArray('OrderActionRecord') .filter((record) => isVariant(record.action, 'fill')); console.log('orderActionRecords.length=', orderActionRecords.length); assert(orderActionRecords.length === 20); const takerPosition = takerDriftClient.getUser().getPerpPosition(1); console.log( 'takerPosition.baseAssetAmount=', takerPosition.baseAssetAmount.toString() ); console.log( 'takerPosition.quoteAssetAmount=', takerPosition.quoteAssetAmount.toString() ); assert(takerPosition.baseAssetAmount.eq(new BN('-402388600000'))); assert(takerPosition.quoteAssetAmount.eq(new BN('273539365'))); const makerPosition = makerDriftClient.getUser().getPerpPosition(1); console.log( 'makerPosition.baseAssetAmount=', makerPosition.baseAssetAmount.toString() ); console.log( 'makerPosition.quoteAssetAmount=', makerPosition.quoteAssetAmount.toString() ); assert(makerPosition.baseAssetAmount.eq(new BN('1000000000'))); assert(makerPosition.quoteAssetAmount.eq(new BN('-689862'))); const secondMakerPosition = secondMakerDriftClient .getUser() .getPerpPosition(1); console.log( 'secondMakerPosition.baseAssetAmount=', secondMakerPosition.baseAssetAmount.toString() ); console.log( 'secondMakerPosition.quoteAssetAmount=', secondMakerPosition.quoteAssetAmount.toString() ); assert(secondMakerPosition.baseAssetAmount.eq(new BN('3000000000'))); assert(secondMakerPosition.quoteAssetAmount.eq(new BN('-2063588'))); const thirdMakerPosition = thirdMakerDriftClient .getUser() .getPerpPosition(1); console.log( 'thirdMakerPosition.baseAssetAmount=', thirdMakerPosition.baseAssetAmount.toString() ); console.log( 'thirdMakerPosition.quoteAssetAmount=', thirdMakerPosition.quoteAssetAmount.toString() ); assert(thirdMakerPosition.baseAssetAmount.eq(new BN('3000000000'))); assert(thirdMakerPosition.quoteAssetAmount.eq(new BN('-2063588'))); const dogMarket = takerDriftClient.getPerpMarketAccount(1); console.log( 'dogMarket.amm.baseAssetAmountWithAmm=', dogMarket.amm.baseAssetAmountWithAmm.toString() ); assert(dogMarket.amm.baseAssetAmountWithAmm.eq(new BN('-395388600000'))); // close position for (let i = 0; i < 3; i++) { await makerDriftClient.placePerpOrder({ marketIndex: 1, direction: PositionDirection.SHORT, price: new BN((0.69 + i / 100) * PRICE_PRECISION.toNumber()), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); } for (let i = 1; i < 2; i++) { await secondMakerDriftClient.placePerpOrder({ marketIndex: 1, direction: PositionDirection.SHORT, price: new BN((0.69 + i / 400) * PRICE_PRECISION.toNumber()), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION.mul(new BN(100)), }); } await setFeedPriceNoProgram(bankrunContextWrapper, 0.75, dogUsd); await takerDriftClient.placePerpOrder({ marketIndex: 1, orderType: OrderType.LIMIT, price: new BN(0.75 * PRICE_PRECISION.toNumber()), direction: PositionDirection.LONG, baseAssetAmount: takerPosition.baseAssetAmount, }); const txSig2 = await fillerDriftClient.fillPerpOrder( await takerDriftClient.getUserAccountPublicKey(), takerDriftClient.getUserAccount(), takerDriftClient.getOrder(2), makerInfo ); const takerPosition2 = takerDriftClient.getUser().getPerpPosition(1); console.log( 'takerPosition2.baseAssetAmount=', takerPosition2.baseAssetAmount.toString() ); assert(takerPosition2.baseAssetAmount.eq(new BN(0))); const dogMarketAfter = takerDriftClient.getPerpMarketAccount(1); console.log( 'dogMarketAfter.amm.baseAssetAmountWithAmm=', dogMarketAfter.amm.baseAssetAmountWithAmm.toString() ); assert( dogMarketAfter.amm.baseAssetAmountWithAmm.eq(new BN('-66279600000')) ); bankrunContextWrapper.printTxLogs(txSig2); await takerDriftClient.unsubscribe(); await makerDriftClient.unsubscribe(); await secondMakerDriftClient.unsubscribe(); await thirdMakerDriftClient.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/oracleFillPriceGuardrails.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { TestClient, BN, PRICE_PRECISION, PositionDirection, EventSubscriber, MarketStatus, BASE_PRECISION, isVariant, OracleSource, PEG_PRECISION, } from '../sdk/src'; import { createUserWithUSDCAccount, initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, } from './testHelpers'; import { MARGIN_PRECISION, OrderType, PostOnlyParams } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('oracle fill guardrails', () => { const chProgram = anchor.workspace.Drift as Program; let fillerDriftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(100000); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(100000 * 10 ** 6); let solUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 20); marketIndexes = [0, 1]; spotMarketIndexes = [0]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; fillerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClient.initialize(usdcMint.publicKey, true); await fillerDriftClient.subscribe(); await initializeQuoteSpotMarket(fillerDriftClient, usdcMint.publicKey); // dont fill against the vamm await fillerDriftClient.updatePerpAuctionDuration(new BN(100)); const periodicity = new BN(60 * 60); // 1 HOUR await fillerDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(20 * PEG_PRECISION.toNumber()) ); await fillerDriftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); await fillerDriftClient.updatePerpMarketBaseSpread( 0, PRICE_PRECISION.toNumber() / 8 ); await fillerDriftClient.updatePerpMarketMarginRatio( 0, MARGIN_PRECISION.toNumber() / 2, MARGIN_PRECISION.toNumber() / 3 ); await fillerDriftClient.updatePerpMarketMaxSpread( 0, PRICE_PRECISION.toNumber() / 5 ); await fillerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); }); beforeEach(async () => { await fillerDriftClient.moveAmmPrice( 0, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve ); }); after(async () => { await fillerDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('taker long solUsd', async () => { const [takerDriftClient, takerUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClient.deposit(usdcAmount, 0, takerUSDCAccount); const [makerDriftClient, makerUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await makerDriftClient.deposit(usdcAmount, 0, makerUSDCAccount); await setFeedPriceNoProgram(bankrunContextWrapper, 14, solUsd); await makerDriftClient.placePerpOrder({ marketIndex: 0, direction: PositionDirection.SHORT, price: new BN(14).mul(PRICE_PRECISION), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); await setFeedPriceNoProgram(bankrunContextWrapper, 31, solUsd); await takerDriftClient.placePerpOrder({ marketIndex: 0, orderType: OrderType.LIMIT, auctionStartPrice: new BN(100).mul(PRICE_PRECISION), auctionEndPrice: new BN(100).mul(PRICE_PRECISION), auctionDuration: 100, price: new BN(100).mul(PRICE_PRECISION), direction: PositionDirection.LONG, baseAssetAmount: BASE_PRECISION, }); // move price to $30 await setFeedPriceNoProgram(bankrunContextWrapper, 30, solUsd); const makerInfo = [ { maker: await makerDriftClient.getUserAccountPublicKey(), makerUserAccount: makerDriftClient.getUserAccount(), makerStats: await makerDriftClient.getUserStatsAccountPublicKey(), }, ]; const firstFillTxSig = await fillerDriftClient.fillPerpOrder( await takerDriftClient.getUserAccountPublicKey(), takerDriftClient.getUserAccount(), takerDriftClient.getOrder(1), makerInfo ); bankrunContextWrapper.printTxLogs(firstFillTxSig); // assert that the const orderActionRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; // console.log(eventSubscriber.getEventsArray('OrderActionRecord')); assert(isVariant(orderActionRecord.action, 'cancel')); await makerDriftClient.placePerpOrder({ marketIndex: 0, direction: PositionDirection.SHORT, price: new BN(31).mul(PRICE_PRECISION), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, postOnly: PostOnlyParams.MUST_POST_ONLY, }); let error = false; try { const txSig = await fillerDriftClient.fillPerpOrder( await takerDriftClient.getUserAccountPublicKey(), takerDriftClient.getUserAccount(), takerDriftClient.getOrder(1), makerInfo ); bankrunContextWrapper.printTxLogs(txSig); } catch (e) { error = true; assert(e.message.includes('0x1787')); } assert(error); await takerDriftClient.unsubscribe(); await makerDriftClient.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/liquidateMaxLps.ts
import * as anchor from '@coral-xyz/anchor'; import { BASE_PRECISION, BN, OracleSource, OracleGuardRails, TestClient, PRICE_PRECISION, PositionDirection, Wallet, LIQUIDATION_PCT_PRECISION, } from '../sdk/src'; import { Program } from '@coral-xyz/anchor'; import { Keypair, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js'; import { mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, mockOracleNoProgram, setFeedPriceNoProgram, } from './testHelpers'; import { PERCENTAGE_PRECISION } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('max lp liq', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let bankrunContextWrapper: BankrunContextWrapper; let bulkAccountLoader: TestBulkAccountLoader; let usdcMint; let userUSDCAccount; const liquidatorKeyPair = new Keypair(); let liquidatorUSDCAccount: Keypair; let liquidatorDriftClient: TestClient; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); const nLpShares = new BN(10000000); let oracle: PublicKey; const numMkts = 8; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); oracle = await mockOracleNoProgram(bankrunContextWrapper, 1); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [ { publicKey: oracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await driftClient.updateInitialPctToLiquidate( LIQUIDATION_PCT_PRECISION.toNumber() ); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(0); for (let i = 0; i < numMkts; i++) { await driftClient.initializePerpMarket( i, oracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); } await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); for (let i = 0; i < numMkts; i++) { await driftClient.openPosition( PositionDirection.LONG, new BN(175) .mul(BASE_PRECISION) .div(new BN(10)) .divn(numMkts * 4), i, new BN(0) ); const txSig = await driftClient.addPerpLpShares( nLpShares.divn(numMkts * 4), i ); bankrunContextWrapper.connection.printTxLogs(txSig); } // provider.connection.requestAirdrop(liquidatorKeyPair.publicKey, 10 ** 9); bankrunContextWrapper.fundKeypair(liquidatorKeyPair, LAMPORTS_PER_SOL); liquidatorUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, liquidatorKeyPair.publicKey ); liquidatorDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(liquidatorKeyPair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0, 1, 2, 3, 4, 5, 6, 7], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [ { publicKey: oracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await liquidatorDriftClient.subscribe(); await liquidatorDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, liquidatorUSDCAccount.publicKey ); }); after(async () => { await driftClient.unsubscribe(); await liquidatorDriftClient.unsubscribe(); }); it('liquidate', async () => { await setFeedPriceNoProgram(bankrunContextWrapper, 0.1, oracle); const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: PERCENTAGE_PRECISION, oracleTwap5MinPercentDivergence: PERCENTAGE_PRECISION.mul(new BN(10)), }, validity: { slotsBeforeStaleForAmm: new BN(100), slotsBeforeStaleForMargin: new BN(100), confidenceIntervalMaxSize: new BN(100000), tooVolatileRatio: new BN(11), // allow 11x change }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); const txSig = await liquidatorDriftClient.liquidatePerp( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0, new BN(175).mul(BASE_PRECISION).div(new BN(10)).divn(numMkts), undefined, { computeUnits: 300_000, } ); bankrunContextWrapper.connection.printTxLogs(txSig); const cus = bankrunContextWrapper.connection.findComputeUnitConsumption(txSig); console.log(cus); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/depositIntoSpotMarketVault.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair, PublicKey } from '@solana/web3.js'; import { TestClient, BN, EventSubscriber, SPOT_MARKET_RATE_PRECISION, OracleSource, SPOT_MARKET_WEIGHT_PRECISION, OracleInfo, } from '../sdk/src'; import { createUserWithUSDCAccount, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpers'; import { SPOT_MARKET_BALANCE_PRECISION } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('spot deposit and withdraw', () => { const chProgram = anchor.workspace.Drift as Program; let admin: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let solOracle: PublicKey; let usdcMint; let adminUsdcAccount: Keypair; let firstUserDriftClient: TestClient; let firstUserDriftClientUSDCAccount: PublicKey; const usdcAmount = new BN(10 * 10 ** 6); const largeUsdcAmount = new BN(10_000 * 10 ** 6); let marketIndexes: number[]; let spotMarketIndexes: number[]; let oracleInfos: OracleInfo[]; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); adminUsdcAccount = await mockUserUSDCAccount( usdcMint, largeUsdcAmount, bankrunContextWrapper ); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 30); marketIndexes = []; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solOracle, source: OracleSource.PYTH }]; admin = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await admin.initialize(usdcMint.publicKey, true); await admin.subscribe(); }); after(async () => { await admin.unsubscribe(); await eventSubscriber.unsubscribe(); await firstUserDriftClient.unsubscribe(); }); it('Deposit into spot market vault', async () => { const optimalUtilization = SPOT_MARKET_RATE_PRECISION.div( new BN(2) ).toNumber(); // 50% utilization const optimalRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(20)).toNumber(); // 2000% APR const maxRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(50)).toNumber(); // 5000% APR const initialAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const initialLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); await admin.initializeSpotMarket( usdcMint.publicKey, optimalUtilization, optimalRate, maxRate, PublicKey.default, OracleSource.QUOTE_ASSET, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight ); [firstUserDriftClient, firstUserDriftClientUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); const marketIndex = 0; await sleep(100); await firstUserDriftClient.fetchAccounts(); const txSig = await firstUserDriftClient.deposit( usdcAmount, marketIndex, firstUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); const spotMarket = await admin.getSpotMarketAccount(marketIndex); assert( spotMarket.depositBalance.eq( new BN(10 * SPOT_MARKET_BALANCE_PRECISION.toNumber()) ) ); const vaultAmount = new BN( ( await bankrunContextWrapper.connection.getTokenAccount(spotMarket.vault) ).amount.toString() ); assert(vaultAmount.eq(usdcAmount)); const depositTokenAmountBefore = firstUserDriftClient.getTokenAmount(0); assert(depositTokenAmountBefore.eq(usdcAmount)); await admin.depositIntoSpotMarketVault( 0, usdcAmount, adminUsdcAccount.publicKey ); const vaultAmountAfter = new BN( ( await bankrunContextWrapper.connection.getTokenAccount(spotMarket.vault) ).amount.toString() ); assert(vaultAmountAfter.eq(usdcAmount.muln(2))); const depositTokenAmount = firstUserDriftClient.getTokenAmount(0); assert(depositTokenAmount.eq(usdcAmount.muln(2))); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/oracleDiffSources.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { PublicKey } from '@solana/web3.js'; import { TestClient, BN, EventSubscriber, OracleSource, OracleInfo, PRICE_PRECISION, Wallet, DriftClient, PEG_PRECISION, } from '../sdk/src'; import { createFundedKeyPair, createUserWithUSDCAccount, initializeQuoteSpotMarket, initializeSolSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } from './testHelpers'; // import { PRICE_PRECISION, PEG_PRECISION, Wallet, DriftClient } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('oracle diff sources', () => { const chProgram = anchor.workspace.Drift as Program; let admin: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let solOracle: PublicKey; let usdcMint; const usdcAmount = new BN(10 * 10 ** 6); const largeUsdcAmount = new BN(10_000 * 10 ** 6); const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); let marketIndexes: number[]; let spotMarketIndexes: number[]; let oracleInfos: OracleInfo[]; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); await mockUserUSDCAccount(usdcMint, largeUsdcAmount, bankrunContextWrapper); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 3); marketIndexes = [0, 1]; spotMarketIndexes = [0, 1, 2]; oracleInfos = [ { publicKey: solOracle, source: OracleSource.PYTH }, { publicKey: solOracle, source: OracleSource.PYTH_1K }, ]; admin = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await admin.initialize(usdcMint.publicKey, true); await admin.subscribe(); await initializeQuoteSpotMarket(admin, usdcMint.publicKey); await initializeSolSpotMarket( admin, solOracle, undefined, OracleSource.PYTH ); await initializeSolSpotMarket( admin, solOracle, undefined, OracleSource.PYTH_1K ); const periodicity = new BN(0); await admin.initializePerpMarket( 0, solOracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(3 * PEG_PRECISION.toNumber()), OracleSource.PYTH ); await admin.initializePerpMarket( 1, solOracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(3000 * PEG_PRECISION.toNumber()), OracleSource.PYTH_1K ); }); beforeEach(async () => { // await admin.updateSpotMarketOracle(1, solOracle, OracleSource.PYTH); // await admin.updatePerpMarketOracle(0, solOracle, OracleSource.PYTH); }); after(async () => { await admin.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('polling', async () => { const [driftClient, _usdcAccount, _userKeyPair] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); assert(driftClient.getSpotMarketAccount(1).oracle.equals(solOracle)); assert(driftClient.getSpotMarketAccount(2).oracle.equals(solOracle)); const normalPrice = await driftClient.getOracleDataForSpotMarket(1); assert(normalPrice.price.eq(PRICE_PRECISION.muln(3))); const oneKPrice = await driftClient.getOracleDataForSpotMarket(2); assert(oneKPrice.price.eq(PRICE_PRECISION.muln(3000))); assert(driftClient.getPerpMarketAccount(0).amm.oracle.equals(solOracle)); assert(driftClient.getPerpMarketAccount(1).amm.oracle.equals(solOracle)); const normalPerpPrice = await driftClient.getOracleDataForPerpMarket(0); assert(normalPerpPrice.price.eq(PRICE_PRECISION.muln(3))); const oneKPerpPrice = await driftClient.getOracleDataForPerpMarket(1); assert(oneKPerpPrice.price.eq(PRICE_PRECISION.muln(3000))); await driftClient.unsubscribe(); }); it('ws', async () => { const userKeyPair = await createFundedKeyPair(bankrunContextWrapper); const driftClient = new DriftClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(userKeyPair), programID: admin.program.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'websocket', }, }); await driftClient.subscribe(); const normalPrice = await driftClient.getOracleDataForSpotMarket(1); assert(normalPrice.price.eq(PRICE_PRECISION.muln(3))); const oneKPrice = await driftClient.getOracleDataForSpotMarket(2); assert(oneKPrice.price.eq(PRICE_PRECISION.muln(3000))); const normalPerpPrice = await driftClient.getOracleDataForPerpMarket(0); assert(normalPerpPrice.price.eq(PRICE_PRECISION.muln(3))); const oneKPerpPrice = await driftClient.getOracleDataForPerpMarket(1); assert(oneKPerpPrice.price.eq(PRICE_PRECISION.muln(3000))); await driftClient.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/admin.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { assert } from 'chai'; import { startAnchor } from 'solana-bankrun'; import { BN, ExchangeStatus, getPythLazerOraclePublicKey, OracleGuardRails, OracleSource, TestClient, } from '../sdk/src'; import { decodeName, DEFAULT_MARKET_NAME } from '../sdk/src/userName'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, } from './testHelpers'; import { PublicKey } from '@solana/web3.js'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { checkIfAccountExists } from './placeAndMakeSwiftPerpBankrun'; describe('admin', () => { const chProgram = anchor.workspace.Drift as Program; let bulkAccountLoader: TestBulkAccountLoader; let driftClient: TestClient; let usdcMint; before(async () => { const context = await startAnchor('', [], []); const bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), // ugh. wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await driftClient.initializeUserAccount(0); await driftClient.fetchAccounts(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); await driftClient.fetchAccounts(); const periodicity = new BN(60 * 60); // 1 HOUR const solUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); await driftClient.initializePerpMarket( 0, solUsd, new BN(1000), new BN(1000), periodicity ); }); it('checks market name', async () => { const market = driftClient.getPerpMarketAccount(0); const name = decodeName(market.name); assert(name == DEFAULT_MARKET_NAME); const newName = 'Glory t0 the DAmm'; await driftClient.updatePerpMarketName(0, newName); await driftClient.fetchAccounts(); const newMarket = driftClient.getPerpMarketAccount(0); assert( decodeName(newMarket.name) == newName, `market name does not match \n actual: ${decodeName( newMarket.name )} \n expected: ${newName}` ); }); it('Update lp cooldown time', async () => { await driftClient.updateLpCooldownTime(new BN(420)); await driftClient.fetchAccounts(); assert( driftClient.getStateAccount().lpCooldownTime.eq(new BN(420)), `lp cooldown time does not match \n actual: ${ driftClient.getStateAccount().lpCooldownTime } \n expected: ${new BN(420)}` ); }); it('Update Amm Jit', async () => { await driftClient.fetchAccounts(); assert( driftClient.getPerpMarketAccount(0).amm.ammJitIntensity == 0, `amm jit intensity does not match \n actual: ${ driftClient.getPerpMarketAccount(0).amm.ammJitIntensity } \n expected: 0` ); await driftClient.updateAmmJitIntensity(0, 100); await driftClient.fetchAccounts(); assert( driftClient.getPerpMarketAccount(0).amm.ammJitIntensity == 100, `amm jit intensity does not match \n actual: ${ driftClient.getPerpMarketAccount(0).amm.ammJitIntensity } \n expected: 100` ); await driftClient.updateAmmJitIntensity(0, 50); await driftClient.fetchAccounts(); assert( driftClient.getPerpMarketAccount(0).amm.ammJitIntensity == 50, `amm jit intensity does not match \n actual: ${ driftClient.getPerpMarketAccount(0).amm.ammJitIntensity } \n expected: 50` ); }); it('Update Margin Ratio', async () => { const marginRatioInitial = 3000; const marginRatioMaintenance = 1000; await driftClient.updatePerpMarketMarginRatio( 0, marginRatioInitial, marginRatioMaintenance ); await driftClient.fetchAccounts(); const market = driftClient.getPerpMarketAccount(0); assert( market.marginRatioInitial === marginRatioInitial, `margin ratio initial does not match \n actual: ${market.marginRatioInitial} \n expected: ${marginRatioInitial}` ); assert( market.marginRatioMaintenance === marginRatioMaintenance, `margin ratio maintenance does not match \n actual: ${market.marginRatioMaintenance} \n expected: ${marginRatioMaintenance}` ); }); it('Update perp fee structure', async () => { const newFeeStructure = driftClient.getStateAccount().perpFeeStructure; newFeeStructure.flatFillerFee = new BN(0); await driftClient.updatePerpFeeStructure(newFeeStructure); await driftClient.fetchAccounts(); const state = driftClient.getStateAccount(); assert( JSON.stringify(newFeeStructure) === JSON.stringify(state.perpFeeStructure), `fee structure does not match \n actual: ${JSON.stringify( state.perpFeeStructure )} \n expected: ${JSON.stringify(newFeeStructure)}` ); }); it('Update spot fee structure', async () => { const newFeeStructure = driftClient.getStateAccount().spotFeeStructure; newFeeStructure.flatFillerFee = new BN(1); await driftClient.updateSpotFeeStructure(newFeeStructure); await driftClient.fetchAccounts(); const state = driftClient.getStateAccount(); assert( JSON.stringify(newFeeStructure) === JSON.stringify(state.spotFeeStructure), `fee structure does not match \n actual: ${JSON.stringify( state.spotFeeStructure )} \n expected: ${JSON.stringify(newFeeStructure)}` ); }); it('Update oracle guard rails', async () => { const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: new BN(1000000), oracleTwap5MinPercentDivergence: new BN(1000000), }, validity: { slotsBeforeStaleForAmm: new BN(1), slotsBeforeStaleForMargin: new BN(1), confidenceIntervalMaxSize: new BN(1), tooVolatileRatio: new BN(1), }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); await driftClient.fetchAccounts(); const state = driftClient.getStateAccount(); assert( JSON.stringify(oracleGuardRails) === JSON.stringify(state.oracleGuardRails), `oracle guard rails does not match \n actual: ${JSON.stringify( state.oracleGuardRails )} \n expected: ${JSON.stringify(oracleGuardRails)}` ); }); it('Update protocol mint', async () => { const mint = new PublicKey('2fvh6hkCYfpNqke9N48x6HcrW92uZVU3QSiXZX4A5L27'); await driftClient.updateDiscountMint(mint); await driftClient.fetchAccounts(); const state = driftClient.getStateAccount(); assert( state.discountMint.equals(mint), `discount mint does not match \n actual: ${state.discountMint} \n expected: ${mint}` ); }); // it('Update max deposit', async () => { // const maxDeposit = new BN(10); // await driftClient.updateMaxDeposit(maxDeposit); // await driftClient.fetchAccounts(); // const state = driftClient.getStateAccount(); // assert(state.maxDeposit.eq(maxDeposit)); // }); it('Update market oracle', async () => { const newOracle = PublicKey.default; const newOracleSource = OracleSource.QUOTE_ASSET; await driftClient.updatePerpMarketOracle(0, newOracle, newOracleSource); await driftClient.fetchAccounts(); const market = driftClient.getPerpMarketAccount(0); assert( market.amm.oracle.equals(PublicKey.default), `oracle does not match \n actual: ${market.amm.oracle} \n expected: ${PublicKey.default}` ); assert( JSON.stringify(market.amm.oracleSource) === JSON.stringify(newOracleSource), `oracle source does not match \n actual: ${JSON.stringify( market.amm.oracleSource )} \n expected: ${JSON.stringify(newOracleSource)}` ); }); it('Update market base asset step size', async () => { const stepSize = new BN(2); const tickSize = new BN(2); await driftClient.updatePerpMarketStepSizeAndTickSize( 0, stepSize, tickSize ); await driftClient.fetchAccounts(); const market = driftClient.getPerpMarketAccount(0); assert( market.amm.orderStepSize.eq(stepSize), `step size does not match \n actual: ${market.amm.orderStepSize} \n expected: ${stepSize}` ); assert( market.amm.orderTickSize.eq(tickSize), `tick size does not match \n actual: ${market.amm.orderTickSize} \n expected: ${tickSize}` ); }); it('Pause liq', async () => { await driftClient.updateExchangeStatus(ExchangeStatus.LIQ_PAUSED); await driftClient.fetchAccounts(); const state = driftClient.getStateAccount(); assert( state.exchangeStatus === ExchangeStatus.LIQ_PAUSED, `exchange status does not match \n actual: ${state.exchangeStatus} \n expected: ${ExchangeStatus.LIQ_PAUSED}` ); console.log('paused liq!'); // unpause await driftClient.updateExchangeStatus(ExchangeStatus.ACTIVE); await driftClient.fetchAccounts(); const state2 = driftClient.getStateAccount(); assert( state2.exchangeStatus === ExchangeStatus.ACTIVE, `exchange status does not match \n actual: ${state2.exchangeStatus} \n expected: ${ExchangeStatus.ACTIVE}` ); console.log('unpaused liq!'); }); it('Pause amm', async () => { await driftClient.updateExchangeStatus(ExchangeStatus.AMM_PAUSED); await driftClient.fetchAccounts(); const state = driftClient.getStateAccount(); assert( state.exchangeStatus === ExchangeStatus.AMM_PAUSED, `exchange status does not match \n actual: ${state.exchangeStatus} \n expected: ${ExchangeStatus.AMM_PAUSED}` ); console.log('paused amm!'); // unpause await driftClient.updateExchangeStatus(ExchangeStatus.ACTIVE); await driftClient.fetchAccounts(); const state2 = driftClient.getStateAccount(); assert( state2.exchangeStatus === ExchangeStatus.ACTIVE, `exchange status does not match \n actual: ${state2.exchangeStatus} \n expected: ${ExchangeStatus.ACTIVE}` ); console.log('unpaused amm!'); }); it('Pause funding', async () => { await driftClient.updateExchangeStatus(ExchangeStatus.FUNDING_PAUSED); await driftClient.fetchAccounts(); const state = driftClient.getStateAccount(); assert( state.exchangeStatus === ExchangeStatus.FUNDING_PAUSED, `exchange status does not match \n actual: ${state.exchangeStatus} \n expected: ${ExchangeStatus.FUNDING_PAUSED}` ); console.log('paused funding!'); // unpause await driftClient.updateExchangeStatus(ExchangeStatus.ACTIVE); await driftClient.fetchAccounts(); const state2 = driftClient.getStateAccount(); assert( state2.exchangeStatus === ExchangeStatus.ACTIVE, `exchange status does not match \n actual: ${state2.exchangeStatus} \n expected: ${ExchangeStatus.ACTIVE}` ); console.log('unpaused funding!'); }); it('Pause deposts and withdraws', async () => { await driftClient.updateExchangeStatus( ExchangeStatus.DEPOSIT_PAUSED | ExchangeStatus.WITHDRAW_PAUSED ); await driftClient.fetchAccounts(); const state = driftClient.getStateAccount(); assert( state.exchangeStatus === (ExchangeStatus.DEPOSIT_PAUSED | ExchangeStatus.WITHDRAW_PAUSED), `exchange status does not match \n actual: ${ state.exchangeStatus } \n expected: ${ ExchangeStatus.DEPOSIT_PAUSED | ExchangeStatus.WITHDRAW_PAUSED }` ); console.log('paused deposits and withdraw!'); // unpause await driftClient.updateExchangeStatus(ExchangeStatus.ACTIVE); await driftClient.fetchAccounts(); const state2 = driftClient.getStateAccount(); assert( state2.exchangeStatus === ExchangeStatus.ACTIVE, `exchange status does not match \n actual: ${state2.exchangeStatus} \n expected: ${ExchangeStatus.ACTIVE}` ); console.log('unpaused deposits and withdraws!'); }); it('Init pyth lazer', async () => { await driftClient.fetchAccounts(); const tx = await driftClient.initializePythLazerOracle(0); console.log(tx); assert( await checkIfAccountExists( driftClient.connection, getPythLazerOraclePublicKey(driftClient.program.programId, 0) ) ); }); it('Update admin', async () => { const newAdminKey = PublicKey.default; await driftClient.updateAdmin(newAdminKey); await driftClient.fetchAccounts(); const state = driftClient.getStateAccount(); assert( state.admin.equals(newAdminKey), `admin does not match \n actual: ${state.admin} \n expected: ${newAdminKey}` ); }); after(async () => { await driftClient.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/spotSwap.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Account, Keypair, LAMPORTS_PER_SOL, PublicKey, Transaction, } from '@solana/web3.js'; import { listMarket, makePlaceOrderTransaction, SERUM } from './serumHelper'; import { BN, TestClient, EventSubscriber, OracleSource, OracleInfo, getTokenAmount, SpotBalanceType, ZERO, getSerumSignerPublicKey, QUOTE_PRECISION, UserStatsAccount, getUserStatsAccountPublicKey, } from '../sdk/src'; import { createUserWithUSDCAndWSOLAccount, createWSolTokenAccountForUser, initializeQuoteSpotMarket, initializeSolSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } 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; let makerDriftClient: TestClient; let makerWSOL: PublicKey; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let solOracle: PublicKey; let serumMarketPublicKey: PublicKey; let usdcMint; let makerUSDC; let takerDriftClient: TestClient; let takerWSOL: PublicKey; let takerUSDC: PublicKey; let takerOpenOrders: PublicKey; const usdcAmount = new BN(200 * 10 ** 6); const solAmount = new BN(2 * 10 ** 9); let marketIndexes: number[]; let spotMarketIndexes: number[]; let oracleInfos: OracleInfo[]; const solSpotMarketIndex = 1; let openOrdersAccount: PublicKey; let takerKeypair: Keypair; before(async () => { const context = await startAnchor( '', [ { name: 'serum_dex', programId: new PublicKey( 'srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX' ), }, ], [] ); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); makerUSDC = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); makerWSOL = await createWSolTokenAccountForUser( bankrunContextWrapper, // @ts-ignore bankrunContextWrapper.provider.wallet, solAmount ); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 100); marketIndexes = []; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solOracle, source: OracleSource.PYTH }]; makerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClient.initialize(usdcMint.publicKey, true); await makerDriftClient.subscribe(); await makerDriftClient.initializeUserAccount(); await initializeQuoteSpotMarket(makerDriftClient, usdcMint.publicKey); await initializeSolSpotMarket(makerDriftClient, solOracle); await makerDriftClient.updateSpotMarketStepSizeAndTickSize( 1, new BN(100000000), new BN(100) ); await makerDriftClient.updateSpotAuctionDuration(0); [takerDriftClient, takerWSOL, takerUSDC, takerKeypair] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount, usdcAmount, [], [0, 1], [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], bulkAccountLoader ); await bankrunContextWrapper.fundKeypair( takerKeypair, 10 * LAMPORTS_PER_SOL ); await takerDriftClient.deposit(usdcAmount, 0, takerUSDC); }); after(async () => { await takerDriftClient.unsubscribe(); await makerDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('Add Serum Market', async () => { serumMarketPublicKey = await listMarket({ context: bankrunContextWrapper, wallet: bankrunContextWrapper.provider.wallet, baseMint: NATIVE_MINT, quoteMint: usdcMint.publicKey, baseLotSize: 100000000, quoteLotSize: 100, dexProgramId: SERUM, feeRateBps: 0, }); console.log('\n\n\n\n\n here \n\n\n\n\n'); await Market.load( bankrunContextWrapper.connection.toConnection(), serumMarketPublicKey, { commitment: 'confirmed' }, SERUM ); console.log('\n\n\n\n\n here \n\n\n\n\n'); await makerDriftClient.initializeSerumFulfillmentConfig( solSpotMarketIndex, serumMarketPublicKey, SERUM ); console.log('\n\n\n\n\n here \n\n\n\n\n'); const market = await Market.load( bankrunContextWrapper.connection.toConnection(), serumMarketPublicKey, { commitment: 'recent' }, SERUM ); console.log('\n\n\n\n\n here \n\n\n\n\n'); const openOrdersAccount = new Account(); const createOpenOrdersIx = await OpenOrders.makeCreateAccountTransaction( bankrunContextWrapper.connection.toConnection(), market.address, takerDriftClient.wallet.publicKey, openOrdersAccount.publicKey, market.programId ); await takerDriftClient.sendTransaction( new Transaction().add(createOpenOrdersIx), [openOrdersAccount] ); console.log('\n\n\n\n\n here \n\n\n\n\n'); 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(), serumMarketPublicKey, { commitment: 'recent' }, SERUM ); // place ask to sell 1 sol for 100 usdc // @ts-ignore const { transaction, signers } = await makePlaceOrderTransaction( bankrunContextWrapper.connection.toConnection(), market, { // @ts-ignore owner: bankrunContextWrapper.provider.wallet, payer: makerWSOL, side: 'sell', price: 100, size: 1, orderType: 'postOnly', clientId: undefined, // todo? openOrdersAddressKey: undefined, openOrdersAccount: undefined, feeDiscountPubkey: null, selfTradeBehavior: 'abortTransaction', } ); openOrdersAccount = signers[0].publicKey; const signerKeypairs = signers.map((signer) => { return Keypair.fromSecretKey(signer.secretKey); }); await bankrunContextWrapper.sendTransaction(transaction, signerKeypairs); const amountIn = new BN(200).mul(QUOTE_PRECISION); const { beginSwapIx, endSwapIx } = await takerDriftClient.getSwapIx({ amountIn: amountIn, inMarketIndex: 0, outMarketIndex: 1, inTokenAccount: takerUSDC, outTokenAccount: takerWSOL, }); // @ts-ignore const serumBidIx = await market.makePlaceOrderInstruction( bankrunContextWrapper.connection.toConnection(), { // @ts-ignore owner: takerDriftClient.wallet, payer: takerUSDC, side: 'buy', price: 100, size: 2, // larger than maker orders so that entire maker order is taken orderType: 'ioc', clientId: new BN(1), // todo? openOrdersAddressKey: takerOpenOrders, feeDiscountPubkey: null, selfTradeBehavior: 'abortTransaction', } ); const serumConfig = await takerDriftClient.getSerumV3FulfillmentConfig( market.publicKey ); const settleFundsIx = DexInstructions.settleFunds({ market: market.publicKey, openOrders: takerOpenOrders, owner: takerDriftClient.wallet.publicKey, // @ts-ignore baseVault: serumConfig.serumBaseVault, // @ts-ignore quoteVault: serumConfig.serumQuoteVault, baseWallet: takerWSOL, quoteWallet: takerUSDC, vaultSigner: getSerumSignerPublicKey( market.programId, market.publicKey, serumConfig.serumSignerNonce ), programId: market.programId, }); const tx = new Transaction() .add(beginSwapIx) .add(serumBidIx) .add(settleFundsIx) .add(endSwapIx); const { txSig } = await takerDriftClient.sendTransaction(tx); bankrunContextWrapper.printTxLogs(txSig); // await printTxLogs(connection, txSig); const takerSOLAmount = await takerDriftClient.getTokenAmount(1); assert(takerSOLAmount.eq(new BN(1000000000))); const takerUSDCAmount = await takerDriftClient.getTokenAmount(0); assert(takerUSDCAmount.eq(new BN(99959999))); // const cumulativeSpotFees = // takerDriftClient.getUserAccount().cumulativeSpotFees; // assert(cumulativeSpotFees.eq(new BN(-50000))); const userStatsPublicKey = getUserStatsAccountPublicKey( new PublicKey(DRIFT_PROGRAM_ID), takerDriftClient.wallet.publicKey ); const accountInfo = await bankrunContextWrapper.connection.getAccountInfo( userStatsPublicKey ); const userStatsAccount = accountInfo ? (takerDriftClient.program.account.user.coder.accounts.decodeUnchecked( 'UserStats', accountInfo.data ) as UserStatsAccount) : undefined; // assert(userStatsAccount.fees.totalFeePaid.eq(new BN(50000))); assert(userStatsAccount.takerVolume30D.eq(new BN(0))); const swapRecord = eventSubscriber.getEventsArray('SwapRecord')[0]; assert(swapRecord.amountOut.eq(new BN(1000000000))); assert(swapRecord.outMarketIndex === 1); assert(swapRecord.amountIn.eq(new BN(100040000))); assert(swapRecord.inMarketIndex === 0); // assert(swapRecord.fee.eq(new BN(500000))); assert(swapRecord.fee.eq(new BN(0))); const solSpotMarket = takerDriftClient.getSpotMarketAccount(1); // assert(solSpotMarket.totalSwapFee.eq(new BN(500000))); assert(solSpotMarket.totalSwapFee.eq(new BN(0))); // const solRevPool = getTokenAmount( // solSpotMarket.revenuePool.scaledBalance, // solSpotMarket, // SpotBalanceType.DEPOSIT // ); // assert(solRevPool.eq(new BN(500000))); await crankMarkets(); }); it('swap usdc for sol', async () => { const market = await Market.load( bankrunContextWrapper.connection.toConnection(), serumMarketPublicKey, { commitment: 'recent' }, SERUM ); // place ask to sell 1 sol for 100 usdc // @ts-ignore const { transaction, signers } = await makePlaceOrderTransaction( bankrunContextWrapper.connection.toConnection(), market, { // @ts-ignore owner: bankrunContextWrapper.provider.wallet, payer: makerUSDC.publicKey, side: 'buy', price: 100, size: 1, orderType: 'postOnly', clientId: undefined, // todo? openOrdersAddressKey: undefined, openOrdersAccount: undefined, feeDiscountPubkey: null, selfTradeBehavior: 'abortTransaction', } ); const signerKeypairs = signers.map((signer) => { return Keypair.fromSecretKey(signer.secretKey); }); await bankrunContextWrapper.sendTransaction(transaction, signerKeypairs); const amountIn = new BN(1).mul(new BN(LAMPORTS_PER_SOL)); // .mul(new BN(1999)) // .div(new BN(2000)); // .9995 SOL const { beginSwapIx, endSwapIx } = await takerDriftClient.getSwapIx({ amountIn: amountIn, inMarketIndex: 1, outMarketIndex: 0, inTokenAccount: takerWSOL, outTokenAccount: takerUSDC, }); // @ts-ignore const serumAskIx = await market.makePlaceOrderInstruction( bankrunContextWrapper.connection.toConnection(), { // @ts-ignore owner: takerDriftClient.wallet, payer: takerWSOL, side: 'sell', price: 100, size: 1, orderType: 'limit', clientId: undefined, // todo? openOrdersAddressKey: takerOpenOrders, feeDiscountPubkey: null, selfTradeBehavior: 'abortTransaction', } ); const serumConfig = await takerDriftClient.getSerumV3FulfillmentConfig( market.publicKey ); const settleFundsIx = DexInstructions.settleFunds({ market: market.publicKey, openOrders: takerOpenOrders, owner: takerDriftClient.wallet.publicKey, // @ts-ignore baseVault: serumConfig.serumBaseVault, // @ts-ignore quoteVault: serumConfig.serumQuoteVault, baseWallet: takerWSOL, quoteWallet: takerUSDC, vaultSigner: getSerumSignerPublicKey( market.programId, market.publicKey, serumConfig.serumSignerNonce ), programId: market.programId, }); const tx = new Transaction() .add(beginSwapIx) .add(serumAskIx) .add(settleFundsIx) .add(endSwapIx); const { txSig } = await takerDriftClient.sendTransaction(tx); bankrunContextWrapper.printTxLogs(txSig); const takerSOLAmount = await takerDriftClient.getTokenAmount(1); assert(takerSOLAmount.eq(new BN(0))); const takerUSDCAmount = await takerDriftClient.getTokenAmount(0); console.log(takerUSDCAmount.toString()); assert(takerUSDCAmount.eq(new BN(199919999))); // const cumulativeSpotFees = // takerDriftClient.getUserAccount().cumulativeSpotFees; // assert(cumulativeSpotFees.eq(new BN(-99980))); // const userStatsAccount = await fetchUserStatsAccount( // connection, // takerDriftClient.program, // takerDriftClient.wallet.publicKey // ); // assert(userStatsAccount.fees.totalFeePaid.eq(new BN(99980))); const swapRecord = eventSubscriber.getEventsArray('SwapRecord')[0]; assert(swapRecord.amountOut.eq(new BN(99960000))); assert(swapRecord.outMarketIndex === 0); assert(swapRecord.amountIn.eq(new BN(1000000000))); assert(swapRecord.inMarketIndex === 1); // assert(swapRecord.fee.eq(new BN(0))); // const usdcSpotMarket = takerDriftClient.getSpotMarketAccount(0); // // assert(usdcSpotMarket.totalSwapFee.eq(new BN(49980))); // // const usdcRevPool = getTokenAmount( // usdcSpotMarket.revenuePool.scaledBalance, // usdcSpotMarket, // SpotBalanceType.DEPOSIT // ); // assert(usdcRevPool.eq(new BN(49980))); await crankMarkets(); }); it('invalid swaps', async () => { const amountIn = new BN(100).mul(QUOTE_PRECISION); const { beginSwapIx, endSwapIx } = await takerDriftClient.getSwapIx({ amountIn, inMarketIndex: 0, outMarketIndex: 1, outTokenAccount: takerWSOL, inTokenAccount: takerUSDC, }); let tx = new Transaction().add(beginSwapIx); let failed = false; try { await takerDriftClient.sendTransaction(tx); } catch (e) { const err = e as Error; if (err.toString().includes('0x1868')) { failed = true; } } assert(failed); tx = new Transaction().add(endSwapIx); failed = false; try { const txO = await takerDriftClient.sendTransaction(tx); const txL = await bankrunContextWrapper.connection.getTransaction( txO.txSig, { commitment: 'confirmed', } ); console.log('tx logs', txL.meta.logMessages); } catch (e) { const err = e as Error; if (err.toString().includes('0x1868')) { failed = true; } } assert(failed); tx = new Transaction() .add(beginSwapIx) .add(beginSwapIx) .add(endSwapIx) .add(endSwapIx); failed = false; try { await takerDriftClient.sendTransaction(tx); } catch (e) { const err = e as Error; if (err.toString().includes('0x1868')) { failed = true; } } assert(failed); tx = new Transaction().add(beginSwapIx).add(beginSwapIx).add(endSwapIx); failed = false; try { await takerDriftClient.sendTransaction(tx); } catch (e) { const err = e as Error; if (err.toString().includes('0x1868')) { failed = true; } } assert(failed); // Try making end swap be signed from different user const { endSwapIx: invalidEndSwapIx } = await makerDriftClient.getSwapIx({ amountIn, inMarketIndex: 0, outMarketIndex: 1, outTokenAccount: takerWSOL, inTokenAccount: takerUSDC, }); tx = new Transaction().add(beginSwapIx).add(invalidEndSwapIx); failed = false; try { await takerDriftClient.sendTransaction(tx, [ // @ts-ignore makerDriftClient.wallet.payer, ]); } catch (e) { const err = e as Error; if (err.toString().includes('0x1868')) { failed = true; } } assert(failed); }); it('donate to revenue pool for a great feature!', async () => { const solSpotMarket = takerDriftClient.getSpotMarketAccount(1); const solRevPool = getTokenAmount( solSpotMarket.revenuePool.scaledBalance, solSpotMarket, SpotBalanceType.DEPOSIT ); assert(solRevPool.eq(ZERO)); const charity = new BN(1); await takerDriftClient.depositIntoSpotMarketRevenuePool( 1, charity, takerWSOL ); await takerDriftClient.fetchAccounts(); const solSpotMarketAfter = takerDriftClient.getSpotMarketAccount(1); const solRevPoolAfter = getTokenAmount( solSpotMarketAfter.revenuePool.scaledBalance, solSpotMarketAfter, SpotBalanceType.DEPOSIT ); assert(solRevPoolAfter.gt(solRevPool)); assert(solRevPoolAfter.eq(charity)); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/maxDeposit.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { TestClient, QUOTE_PRECISION, BN, OracleSource } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } from './testHelpers'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('max deposit', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; const usdcAmount = new BN(10 * 10 ** 6); before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); const solUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [{ publicKey: solUsd, source: OracleSource.PYTH }], userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); }); after(async () => { await driftClient.unsubscribe(); }); it('update max deposit', async () => { await driftClient.updateSpotMarketMaxTokenDeposits(0, QUOTE_PRECISION); const market = driftClient.getSpotMarketAccount(0); console.assert(market.maxTokenDeposits.eq(QUOTE_PRECISION)); }); it('block deposit', async () => { try { await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); } catch (e) { return; } assert(false); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/testHelpers.ts
import * as anchor from '@coral-xyz/anchor'; import { AnchorProvider, Program, Provider } from '@coral-xyz/anchor'; import { AccountLayout, MintLayout, NATIVE_MINT, TOKEN_PROGRAM_ID, createInitializeMintInstruction, createInitializeAccountInstruction, createMintToInstruction, getAssociatedTokenAddressSync, createAssociatedTokenAccountIdempotentInstruction, ACCOUNT_SIZE, createSyncNativeInstruction, } from '@solana/spl-token'; import { AccountInfo, Connection, Keypair, LAMPORTS_PER_SOL, PublicKey, sendAndConfirmTransaction, SystemProgram, Transaction, TransactionSignature, } from '@solana/web3.js'; import { assert } from 'chai'; import buffer from 'buffer'; import { BN, Wallet, OraclePriceData, OracleInfo } from '../sdk'; import { TestClient, SPOT_MARKET_RATE_PRECISION, SPOT_MARKET_WEIGHT_PRECISION, PRICE_PRECISION, QUOTE_PRECISION, User, OracleSource, } from '../sdk/src'; import { BankrunContextWrapper, BankrunConnection, } from '../sdk/src/bankrun/bankrunConnection'; import pythIDL from '../sdk/src/idl/pyth.json'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; export async function mockOracle( price: number = 50 * 10e7, expo = -7, confidence?: number ): Promise<PublicKey> { // default: create a $50 coin oracle const program = anchor.workspace.Pyth; anchor.setProvider( anchor.AnchorProvider.local(undefined, { commitment: 'confirmed', preflightCommitment: 'confirmed', }) ); const priceFeedAddress = await createPriceFeed({ oracleProgram: program, initPrice: price, expo: expo, confidence, }); const feedData = await getFeedData(program, priceFeedAddress); if (feedData.price !== price) { console.log('mockOracle precision error:', feedData.price, '!=', price); } assert.ok(Math.abs(feedData.price - price) < 1e-10); return priceFeedAddress; } export async function mockOracleNoProgram( context: BankrunContextWrapper, price: number = 50 * 10e7, expo = -7, confidence?: number ): Promise<PublicKey> { const provider = new AnchorProvider( context.connection.toConnection(), context.provider.wallet, { commitment: 'processed', } ); const program = new Program( pythIDL as anchor.Idl, new PublicKey('FsJ3A3u2vn5cTVofAjvy6y5kwABJAqYWpe4975bi2epH'), provider ); const priceFeedAddress = await createPriceFeedBankrun({ oracleProgram: program, context: context, initPrice: price, expo: expo, confidence, }); // @ts-ignore const feedData = await getFeedDataNoProgram( context.connection, priceFeedAddress ); if (feedData.price !== price) { console.log('mockOracle precision error:', feedData.price, '!=', price); } assert.ok(Math.abs(feedData.price - price) < 1e-10); return priceFeedAddress; } export async function mockUSDCMint( context: BankrunContextWrapper, tokenProgram = TOKEN_PROGRAM_ID ): Promise<Keypair> { const fakeUSDCMint = anchor.web3.Keypair.generate(); const createUSDCMintAccountIx = SystemProgram.createAccount({ fromPubkey: context.provider.wallet.publicKey, newAccountPubkey: fakeUSDCMint.publicKey, lamports: 10_000_000_000, space: MintLayout.span, programId: tokenProgram, }); const initCollateralMintIx = createInitializeMintInstruction( fakeUSDCMint.publicKey, 6, // @ts-ignore context.provider.wallet.publicKey, // @ts-ignore context.provider.wallet.publicKey, tokenProgram ); const fakeUSDCTx = new Transaction(); fakeUSDCTx.add(createUSDCMintAccountIx); fakeUSDCTx.add(initCollateralMintIx); await context.sendTransaction(fakeUSDCTx, [fakeUSDCMint]); return fakeUSDCMint; } export async function mockUserUSDCAccount( fakeUSDCMint: Keypair, usdcMintAmount: BN, context: BankrunContextWrapper, owner?: PublicKey ): Promise<Keypair> { const userUSDCAccount = anchor.web3.Keypair.generate(); const fakeUSDCTx = new Transaction(); if (owner === undefined) { owner = context.context.payer.publicKey; } const tokenProgram = ( await context.connection.getAccountInfo(fakeUSDCMint.publicKey) ).owner; const createUSDCTokenAccountIx = SystemProgram.createAccount({ fromPubkey: context.context.payer.publicKey, newAccountPubkey: userUSDCAccount.publicKey, lamports: 100_000_000, space: AccountLayout.span, programId: tokenProgram, }); fakeUSDCTx.add(createUSDCTokenAccountIx); const initUSDCTokenAccountIx = createInitializeAccountInstruction( userUSDCAccount.publicKey, fakeUSDCMint.publicKey, owner, tokenProgram ); fakeUSDCTx.add(initUSDCTokenAccountIx); const mintToUserAccountTx = createMintToInstruction( fakeUSDCMint.publicKey, userUSDCAccount.publicKey, // @ts-ignore context.context.payer.publicKey, usdcMintAmount.toNumber(), undefined, tokenProgram ); fakeUSDCTx.add(mintToUserAccountTx); await context.sendTransaction(fakeUSDCTx, [userUSDCAccount, fakeUSDCMint]); return userUSDCAccount; } export function getMockUserUsdcAccountInfo( fakeUSDCMint: Keypair, usdcMintAmount: BN, context: BankrunContextWrapper, owner?: PublicKey ): [PublicKey, AccountInfo<Buffer>] { if (owner === undefined) { owner = context.context.payer.publicKey; } const ata = getAssociatedTokenAddressSync(fakeUSDCMint.publicKey, owner); const tokenAccData = Buffer.alloc(ACCOUNT_SIZE); AccountLayout.encode( { mint: fakeUSDCMint.publicKey, owner, amount: BigInt(usdcMintAmount.toNumber()), delegateOption: 0, delegate: PublicKey.default, delegatedAmount: BigInt(0), state: 1, isNativeOption: 0, isNative: BigInt(0), closeAuthorityOption: 0, closeAuthority: PublicKey.default, }, tokenAccData ); const accountInfo: AccountInfo<Buffer> = { data: tokenAccData, executable: false, lamports: 100_000_000, owner, rentEpoch: 0, }; return [ata, accountInfo]; } export async function mintUSDCToUser( fakeUSDCMint: Keypair, userUSDCAccount: PublicKey, usdcMintAmount: BN, context: BankrunContextWrapper ): Promise<void> { const tx = new Transaction(); const tokenProgram = ( await context.connection.getAccountInfo(fakeUSDCMint.publicKey) ).owner; const mintToUserAccountTx = await createMintToInstruction( fakeUSDCMint.publicKey, userUSDCAccount, // @ts-ignore context.provider.wallet.payer.publicKey, usdcMintAmount.toNumber(), undefined, tokenProgram ); tx.add(mintToUserAccountTx); await context.sendTransaction(tx); } export async function createFundedKeyPair( context: BankrunContextWrapper ): Promise<Keypair> { const keypair = Keypair.generate(); await context.fundKeypair(keypair, BigInt(100 * LAMPORTS_PER_SOL)); return keypair; } export async function createUSDCAccountForUser( context: BankrunContextWrapper, userKeyPair: Keypair, usdcMint: Keypair, usdcAmount: BN ): Promise<PublicKey> { const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, context, userKeyPair.publicKey ); return userUSDCAccount.publicKey; } export async function initializeAndSubscribeDriftClient( connection: Connection, program: Program, userKeyPair: Keypair, marketIndexes: number[], bankIndexes: number[], oracleInfos: OracleInfo[] = [], accountLoader?: TestBulkAccountLoader ): Promise<TestClient> { const driftClient = new TestClient({ connection, wallet: new Wallet(userKeyPair), programID: program.programId, opts: { commitment: 'confirmed', }, // activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: bankIndexes, oracleInfos, subAccountIds: [], userStats: false, accountSubscription: accountLoader ? { type: 'polling', accountLoader, } : { type: 'websocket', }, }); await driftClient.subscribe(); await driftClient.initializeUserAccount(); return driftClient; } export async function createUserWithUSDCAccount( context: BankrunContextWrapper, usdcMint: Keypair, chProgram: Program, usdcAmount: BN, marketIndexes: number[], bankIndexes: number[], oracleInfos: OracleInfo[] = [], accountLoader?: TestBulkAccountLoader ): Promise<[TestClient, PublicKey, Keypair]> { const userKeyPair = await createFundedKeyPair(context); const usdcAccount = await createUSDCAccountForUser( context, userKeyPair, usdcMint, usdcAmount ); const driftClient = await initializeAndSubscribeDriftClient( context.connection.toConnection(), chProgram, userKeyPair, marketIndexes, bankIndexes, oracleInfos, accountLoader ); return [driftClient, usdcAccount, userKeyPair]; } export async function createWSolTokenAccountForUser( context: BankrunContextWrapper, userKeypair: Keypair | Wallet, amount: BN ): Promise<PublicKey> { // @ts-ignore await context.fundKeypair(userKeypair, amount.toNumber()); const addr = getAssociatedTokenAddressSync( NATIVE_MINT, userKeypair.publicKey ); const ix = createAssociatedTokenAccountIdempotentInstruction( context.context.payer.publicKey, addr, userKeypair.publicKey, NATIVE_MINT ); const ixs = [ SystemProgram.transfer({ fromPubkey: context.context.payer.publicKey, toPubkey: addr, lamports: amount.toNumber(), }), createSyncNativeInstruction(addr), ]; const tx = new Transaction().add(ix).add(...ixs); await context.sendTransaction(tx); return addr; } export async function fundWsolTokenAccountForUser( context: BankrunContextWrapper, userKeypair: Keypair | Wallet, amount: BN ): Promise<void> { // @ts-ignore await context.fundKeypair(userKeypair, amount.toNumber() * 5); const addr = getAssociatedTokenAddressSync( NATIVE_MINT, userKeypair.publicKey ); const ixs = [ SystemProgram.transfer({ fromPubkey: context.context.payer.publicKey, toPubkey: addr, lamports: amount.toNumber(), }), createSyncNativeInstruction(addr), ]; const tx = new Transaction().add(...ixs); await context.sendTransaction(tx); } export async function createUserWithUSDCAndWSOLAccount( context: BankrunContextWrapper, usdcMint: Keypair, chProgram: Program, solAmount: BN, usdcAmount: BN, marketIndexes: number[], bankIndexes: number[], oracleInfos: OracleInfo[] = [], accountLoader?: TestBulkAccountLoader ): Promise<[TestClient, PublicKey, PublicKey, Keypair]> { const keypair = Keypair.generate(); await context.fundKeypair(keypair, BigInt(LAMPORTS_PER_SOL)); const solAccount = await createWSolTokenAccountForUser( context, keypair, solAmount ); const usdcAccount = await createUSDCAccountForUser( context, keypair, usdcMint, usdcAmount ); const driftClient = await initializeAndSubscribeDriftClient( context.connection.toConnection(), chProgram, keypair, marketIndexes, bankIndexes, oracleInfos, accountLoader ); return [driftClient, solAccount, usdcAccount, keypair]; } export async function printTxLogs( connection: Connection, txSig: TransactionSignature ): Promise<void> { console.log( 'tx logs', (await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta .logMessages ); } export async function mintToInsuranceFund( chInsuranceAccountPubkey: PublicKey, fakeUSDCMint: Keypair, amount: BN, provider: Provider ): Promise<TransactionSignature> { const mintToUserAccountTx = await createMintToInstruction( fakeUSDCMint.publicKey, chInsuranceAccountPubkey, // @ts-ignore provider.wallet.publicKey, amount.toNumber() ); const fakeUSDCTx = new Transaction(); fakeUSDCTx.add(mintToUserAccountTx); return await sendAndConfirmTransaction( provider.connection, fakeUSDCTx, // @ts-ignore [provider.wallet.payer], { skipPreflight: false, commitment: 'recent', preflightCommitment: 'recent', } ); } export async function initUserAccounts( NUM_USERS: number, usdcMint: Keypair, usdcAmount: BN, context: BankrunContextWrapper, marketIndexes: number[], bankIndexes: number[], oracleInfos: OracleInfo[], accountLoader?: TestBulkAccountLoader ) { const user_keys = []; const userUSDCAccounts = []; const driftClients = []; const userAccountInfos = []; let userAccountPublicKey: PublicKey; for (let i = 0; i < NUM_USERS; i++) { console.log('user', i, 'initialize'); const owner = anchor.web3.Keypair.generate(); const ownerWallet = new anchor.Wallet(owner); await context.fundKeypair(owner, BigInt(100 * LAMPORTS_PER_SOL)); const newUserAcct = await mockUserUSDCAccount( usdcMint, usdcAmount, context, ownerWallet.publicKey ); const chProgram = anchor.workspace.Drift as anchor.Program; // this.program-ify const driftClient1 = new TestClient({ connection: context.connection.toConnection(), //@ts-ignore wallet: ownerWallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, perpMarketIndexes: marketIndexes, spotMarketIndexes: bankIndexes, oracleInfos, subAccountIds: [], accountSubscription: accountLoader ? { type: 'polling', accountLoader, } : { type: 'websocket', }, }); // await driftClient1.initialize(usdcMint.publicKey, false); await driftClient1.subscribe(); userUSDCAccounts.push(newUserAcct); driftClients.push(driftClient1); // var last_idx = userUSDCAccounts.length - 1; // try { [, userAccountPublicKey] = await driftClient1.initializeUserAccountAndDepositCollateral( // marketPublicKey, usdcAmount, newUserAcct.publicKey ); // const userAccount = 0; const userAccount = new User({ driftClient: driftClient1, userAccountPublicKey: await driftClient1.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: accountLoader, }, }); await userAccount.subscribe(); userAccountInfos.push(userAccount); // } catch (e) { // assert(true); // } user_keys.push(userAccountPublicKey); } return [userUSDCAccounts, user_keys, driftClients, userAccountInfos]; } const empty32Buffer = buffer.Buffer.alloc(32); const PKorNull = (data) => data.equals(empty32Buffer) ? null : new anchor.web3.PublicKey(data); export const createPriceFeed = async ({ oracleProgram, initPrice, confidence = undefined, expo = -4, }: { oracleProgram: Program; initPrice: number; confidence?: number; expo?: number; }): Promise<PublicKey> => { const conf = new BN(confidence) || new BN((initPrice / 10) * 10 ** -expo); const collateralTokenFeed = new anchor.web3.Account(); const txid = await oracleProgram.rpc.initialize( new BN(initPrice * 10 ** -expo), expo, conf, { accounts: { price: collateralTokenFeed.publicKey }, signers: [collateralTokenFeed], instructions: [ anchor.web3.SystemProgram.createAccount({ // @ts-ignore fromPubkey: oracleProgram.provider.wallet.publicKey, newAccountPubkey: collateralTokenFeed.publicKey, space: 3312, lamports: await oracleProgram.provider.connection.getMinimumBalanceForRentExemption( 3312 ), programId: oracleProgram.programId, }), ], } ); console.log(txid); return collateralTokenFeed.publicKey; }; export const createPriceFeedBankrun = async ({ oracleProgram, context, initPrice, confidence = undefined, expo = -4, }: { oracleProgram: Program; context: BankrunContextWrapper; initPrice: number; confidence?: number; expo?: number; }): Promise<PublicKey> => { const conf = new BN(confidence) || new BN((initPrice / 10) * 10 ** -expo); const collateralTokenFeed = new anchor.web3.Account(); const createAccountIx = anchor.web3.SystemProgram.createAccount({ fromPubkey: context.context.payer.publicKey, newAccountPubkey: collateralTokenFeed.publicKey, space: 3312, lamports: LAMPORTS_PER_SOL / 20, // just hardcode based on mainnet programId: oracleProgram.programId, }); const ix = oracleProgram.instruction.initialize( new BN(initPrice * 10 ** -expo), expo, conf, { accounts: { price: collateralTokenFeed.publicKey }, } ); const tx = new Transaction().add(createAccountIx).add(ix); tx.feePayer = context.context.payer.publicKey; tx.recentBlockhash = context.context.lastBlockhash; tx.sign(...[collateralTokenFeed, context.context.payer]); await context.connection.sendTransaction(tx); return collateralTokenFeed.publicKey; }; export const setFeedPrice = async ( oracleProgram: Program, newPrice: number, priceFeed: PublicKey ) => { const info = await oracleProgram.provider.connection.getAccountInfo( priceFeed ); const data = parsePriceData(info.data); await oracleProgram.rpc.setPrice(new BN(newPrice * 10 ** -data.exponent), { accounts: { price: priceFeed }, }); }; export const setFeedPriceNoProgram = async ( context: BankrunContextWrapper, newPrice: number, priceFeed: PublicKey ) => { const info = await context.connection.getAccountInfo(priceFeed); const data = parsePriceData(info.data); const provider = new AnchorProvider( context.connection.toConnection(), context.provider.wallet, { commitment: 'processed', } ); const program = new Program( pythIDL as anchor.Idl, new PublicKey('FsJ3A3u2vn5cTVofAjvy6y5kwABJAqYWpe4975bi2epH'), provider ); const ix = program.instruction.setPrice( new BN(newPrice * 10 ** -data.exponent), { accounts: { price: priceFeed }, } ); const tx = new Transaction().add(ix); tx.feePayer = context.context.payer.publicKey; tx.recentBlockhash = (await context.getLatestBlockhash()).toString(); tx.sign(...[context.context.payer]); await context.connection.sendTransaction(tx); }; export const setFeedTwap = async ( oracleProgram: Program, newTwap: number, priceFeed: PublicKey ) => { const info = await oracleProgram.provider.connection.getAccountInfo( priceFeed ); const data = parsePriceData(info.data); await oracleProgram.rpc.setTwap(new BN(newTwap * 10 ** -data.exponent), { accounts: { price: priceFeed }, }); }; export const getFeedData = async ( oracleProgram: Program, priceFeed: PublicKey ) => { const info = await oracleProgram.provider.connection.getAccountInfo( priceFeed ); return parsePriceData(info.data); }; export const getFeedDataNoProgram = async ( connection: BankrunConnection, priceFeed: PublicKey ) => { // @ts-ignore const info = await connection.getAccountInfoAndContext(priceFeed); return parsePriceData(info.value.data); }; export const getOraclePriceData = async ( oracleProgram: Program, priceFeed: PublicKey ): Promise<OraclePriceData> => { const info = await oracleProgram.provider.connection.getAccountInfo( priceFeed ); const interData = parsePriceData(info.data); const oraclePriceData: OraclePriceData = { price: new BN(interData.price * PRICE_PRECISION.toNumber()), slot: new BN(interData.currentSlot.toString()), confidence: new BN(interData.confidence * PRICE_PRECISION.toNumber()), hasSufficientNumberOfDataPoints: true, }; return oraclePriceData; }; // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L758 const ERR_BUFFER_OUT_OF_BOUNDS = () => new Error('Attempt to access memory outside buffer bounds'); // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L968 const ERR_INVALID_ARG_TYPE = (name, expected, actual) => new Error( `The "${name}" argument must be of type ${expected}. Received ${actual}` ); // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L1262 const ERR_OUT_OF_RANGE = (str, range, received) => new Error( `The value of "${str} is out of range. It must be ${range}. Received ${received}` ); // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/validators.js#L127-L130 function validateNumber(value, name) { if (typeof value !== 'number') throw ERR_INVALID_ARG_TYPE(name, 'number', value); } // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/buffer.js#L68-L80 function boundsError(value, length) { if (Math.floor(value) !== value) { validateNumber(value, 'offset'); throw ERR_OUT_OF_RANGE('offset', 'an integer', value); } if (length < 0) throw ERR_BUFFER_OUT_OF_BOUNDS(); throw ERR_OUT_OF_RANGE('offset', `>= 0 and <= ${length}`, value); } function readBigInt64LE(buffer, offset = 0) { validateNumber(offset, 'offset'); const first = buffer[offset]; const last = buffer[offset + 7]; if (first === undefined || last === undefined) boundsError(offset, buffer.length - 8); const val = buffer[offset + 4] + buffer[offset + 5] * 2 ** 8 + buffer[offset + 6] * 2 ** 16 + (last << 24); // Overflow return ( (BigInt(val) << BigInt(32)) + BigInt( first + buffer[++offset] * 2 ** 8 + buffer[++offset] * 2 ** 16 + buffer[++offset] * 2 ** 24 ) ); } // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/buffer.js#L89-L107 function readBigUInt64LE(buffer, offset = 0) { validateNumber(offset, 'offset'); const first = buffer[offset]; const last = buffer[offset + 7]; if (first === undefined || last === undefined) boundsError(offset, buffer.length - 8); const lo = first + buffer[++offset] * 2 ** 8 + buffer[++offset] * 2 ** 16 + buffer[++offset] * 2 ** 24; const hi = buffer[++offset] + buffer[++offset] * 2 ** 8 + buffer[++offset] * 2 ** 16 + last * 2 ** 24; return BigInt(lo) + (BigInt(hi) << BigInt(32)); // tslint:disable-line:no-bitwise } const parsePriceData = (data) => { // Pyth magic number. const magic = data.readUInt32LE(0); // Program version. const version = data.readUInt32LE(4); // Account type. const type = data.readUInt32LE(8); // Price account size. const size = data.readUInt32LE(12); // Price or calculation type. const priceType = data.readUInt32LE(16); // Price exponent. const exponent = data.readInt32LE(20); // Number of component prices. const numComponentPrices = data.readUInt32LE(24); // unused // const unused = accountInfo.data.readUInt32LE(28) // Currently accumulating price slot. const currentSlot = readBigUInt64LE(data, 32); // Valid on-chain slot of aggregate price. const validSlot = readBigUInt64LE(data, 40); // Time-weighted average price. const twapComponent = readBigInt64LE(data, 48); const twap = Number(twapComponent) * 10 ** exponent; // Annualized price volatility. const avolComponent = readBigUInt64LE(data, 56); const avol = Number(avolComponent) * 10 ** exponent; // Space for future derived values. const drv0Component = readBigInt64LE(data, 64); const drv0 = Number(drv0Component) * 10 ** exponent; const drv1Component = readBigInt64LE(data, 72); const drv1 = Number(drv1Component) * 10 ** exponent; const drv2Component = readBigInt64LE(data, 80); const drv2 = Number(drv2Component) * 10 ** exponent; const drv3Component = readBigInt64LE(data, 88); const drv3 = Number(drv3Component) * 10 ** exponent; const drv4Component = readBigInt64LE(data, 96); const drv4 = Number(drv4Component) * 10 ** exponent; const drv5Component = readBigInt64LE(data, 104); const drv5 = Number(drv5Component) * 10 ** exponent; // Product id / reference account. const productAccountKey = new anchor.web3.PublicKey(data.slice(112, 144)); // Next price account in list. const nextPriceAccountKey = PKorNull(data.slice(144, 176)); // Aggregate price updater. const aggregatePriceUpdaterAccountKey = new anchor.web3.PublicKey( data.slice(176, 208) ); const aggregatePriceInfo = parsePriceInfo(data.slice(208, 240), exponent); // Price components - up to 32. const priceComponents = []; let offset = 240; let shouldContinue = true; while (offset < data.length && shouldContinue) { const publisher = PKorNull(data.slice(offset, offset + 32)); offset += 32; if (publisher) { const aggregate = parsePriceInfo( data.slice(offset, offset + 32), exponent ); offset += 32; const latest = parsePriceInfo(data.slice(offset, offset + 32), exponent); offset += 32; priceComponents.push({ publisher, aggregate, latest }); } else { shouldContinue = false; } } return Object.assign( Object.assign( { magic, version, type, size, priceType, exponent, numComponentPrices, currentSlot, validSlot, twapComponent, twap, avolComponent, avol, drv0Component, drv0, drv1Component, drv1, drv2Component, drv2, drv3Component, drv3, drv4Component, drv4, drv5Component, drv5, productAccountKey, nextPriceAccountKey, aggregatePriceUpdaterAccountKey, }, aggregatePriceInfo ), { priceComponents } ); }; const _parseProductData = (data) => { // Pyth magic number. const magic = data.readUInt32LE(0); // Program version. const version = data.readUInt32LE(4); // Account type. const type = data.readUInt32LE(8); // Price account size. const size = data.readUInt32LE(12); // First price account in list. const priceAccountBytes = data.slice(16, 48); const priceAccountKey = new anchor.web3.PublicKey(priceAccountBytes); const product = {}; let idx = 48; while (idx < data.length) { const keyLength = data[idx]; idx++; if (keyLength) { const key = data.slice(idx, idx + keyLength).toString(); idx += keyLength; const valueLength = data[idx]; idx++; const value = data.slice(idx, idx + valueLength).toString(); idx += valueLength; product[key] = value; } } return { magic, version, type, size, priceAccountKey, product }; }; const parsePriceInfo = (data, exponent) => { // Aggregate price. const priceComponent = data.readBigUInt64LE(0); const price = Number(priceComponent) * 10 ** exponent; // Aggregate confidence. const confidenceComponent = data.readBigUInt64LE(8); const confidence = Number(confidenceComponent) * 10 ** exponent; // Aggregate status. const status = data.readUInt32LE(16); // Aggregate corporate action. const corporateAction = data.readUInt32LE(20); // Aggregate publish slot. const publishSlot = data.readBigUInt64LE(24); return { priceComponent, price, confidenceComponent, confidence, status, corporateAction, publishSlot, }; }; export function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } export async function getTokenAmountAsBN( connection: Connection, tokenAccount: PublicKey ): Promise<BN> { return new BN( (await connection.getTokenAccountBalance(tokenAccount)).value.amount ); } export async function initializeQuoteSpotMarket( admin: TestClient, usdcMint: PublicKey ): Promise<void> { const optimalUtilization = SPOT_MARKET_RATE_PRECISION.div( new BN(2) ).toNumber(); // 50% utilization const optimalRate = SPOT_MARKET_RATE_PRECISION.toNumber(); const maxRate = SPOT_MARKET_RATE_PRECISION.toNumber(); const initialAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const initialLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const imfFactor = 0; const marketIndex = admin.getStateAccount().numberOfSpotMarkets; await admin.initializeSpotMarket( usdcMint, optimalUtilization, optimalRate, maxRate, PublicKey.default, OracleSource.QUOTE_ASSET, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight, imfFactor ); // @ts-ignore admin.accountSubscriber.spotOracleMap.set(0, PublicKey.default); await admin.updateWithdrawGuardThreshold( marketIndex, new BN(10 ** 10).mul(QUOTE_PRECISION) ); } export async function initializeSolSpotMarket( admin: TestClient, solOracle: PublicKey, solMint = NATIVE_MINT, oracleSource: OracleSource = OracleSource.PYTH ): Promise<string> { const optimalUtilization = SPOT_MARKET_RATE_PRECISION.div( new BN(2) ).toNumber(); // 50% utilization const optimalRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(20)).toNumber(); // 2000% APR const maxRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(50)).toNumber(); // 5000% APR const initialAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(8)) .div(new BN(10)) .toNumber(); const maintenanceAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(9)) .div(new BN(10)) .toNumber(); const initialLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(12)) .div(new BN(10)) .toNumber(); const maintenanceLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.mul( new BN(11) ) .div(new BN(10)) .toNumber(); const marketIndex = admin.getStateAccount().numberOfSpotMarkets; const txSig = await admin.initializeSpotMarket( solMint, optimalUtilization, optimalRate, maxRate, solOracle, oracleSource, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight ); await admin.updateWithdrawGuardThreshold( marketIndex, new BN(10 ** 10).mul(QUOTE_PRECISION) ); return txSig; }
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/switchboardTxCus.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { BASE_PRECISION, BN, OracleSource, TestClient, EventSubscriber, PRICE_PRECISION, PositionDirection, Wallet, LIQUIDATION_PCT_PRECISION, } from '../sdk/src'; import { Program } from '@coral-xyz/anchor'; import { Keypair, PublicKey } from '@solana/web3.js'; import { mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, } from './testHelpers'; import { getOrderParams, MarketType, OrderParams, OrderType, PostOnlyParams, } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('switchboard place orders cus', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; const traderKeyPair = new Keypair(); let traderUSDCAccount: Keypair; let traderDriftClient: TestClient; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); const nLpShares = new BN(10000000); let oracle: PublicKey; const numMkts = 8; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); oracle = await mockOracleNoProgram(bankrunContextWrapper, 1); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [ { publicKey: oracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await driftClient.updateInitialPctToLiquidate( LIQUIDATION_PCT_PRECISION.toNumber() ); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(0); for (let i = 0; i < numMkts; i++) { await driftClient.initializePerpMarket( i, oracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); } await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); for (let i = 0; i < numMkts; i++) { await driftClient.openPosition( PositionDirection.LONG, new BN(175) .mul(BASE_PRECISION) .div(new BN(10)) .divn(numMkts * 4), i, new BN(0) ); await driftClient.addPerpLpShares(nLpShares.divn(numMkts * 4), i); } await bankrunContextWrapper.fundKeypair(traderKeyPair, 10 ** 9); traderUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, traderKeyPair.publicKey ); traderDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(traderKeyPair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0, 1, 2, 3, 4, 5, 6, 7], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [ { publicKey: oracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await traderDriftClient.subscribe(); await traderDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, traderUSDCAccount.publicKey ); }); after(async () => { await driftClient.unsubscribe(); await traderDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('liquidate', async () => { const orderParams: Array<OrderParams> = []; for (let i = 0; i < 26; i++) { orderParams.push( getOrderParams({ marketType: MarketType.PERP, marketIndex: 0, orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, postOnly: PostOnlyParams.SLIDE, direction: PositionDirection.LONG, price: PRICE_PRECISION, }) ); } const txSig = await traderDriftClient.placeOrders(orderParams); bankrunContextWrapper.printTxLogs(txSig); const cus = bankrunContextWrapper.connection.findComputeUnitConsumption(txSig); console.log(cus); assert(cus < 400000); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/pythLazerBankrun.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { BN, OracleSource, PEG_PRECISION, PRICE_PRECISION, PTYH_LAZER_PROGRAM_ID, PYTH_LAZER_STORAGE_ACCOUNT_KEY, TestClient, assert, getPythLazerOraclePublicKey, isVariant, } from '../sdk/src'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; import { startAnchor } from 'solana-bankrun'; import { AccountInfo, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js'; import { initializeQuoteSpotMarket, mockUSDCMint } from './testHelpers'; import { PYTH_LAZER_HEX_STRING_MULTI, PYTH_LAZER_HEX_STRING_SOL, PYTH_STORAGE_DATA, } from './pythLazerData'; import { mockOracleNoProgram } from './testHelpers'; // set up account infos to load into banks client const PYTH_STORAGE_ACCOUNT_INFO: AccountInfo<Buffer> = { executable: false, lamports: LAMPORTS_PER_SOL, owner: new PublicKey(PTYH_LAZER_PROGRAM_ID), rentEpoch: 0, data: Buffer.from(PYTH_STORAGE_DATA, 'base64'), }; describe('pyth pull oracles', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; const feedId = 0; let feedAddress: PublicKey; before(async () => { // use bankrun builtin function to start solana program test const context = await startAnchor( '', [], [ { address: PYTH_LAZER_STORAGE_ACCOUNT_KEY, info: PYTH_STORAGE_ACCOUNT_INFO, }, ] ); // wrap the context to use it with the test helpers bankrunContextWrapper = new BankrunContextWrapper(context); // don't use regular bulk account loader, use test bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); feedAddress = getPythLazerOraclePublicKey(chProgram.programId, feedId); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [ { publicKey: feedAddress, source: OracleSource.PYTH_LAZER, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(10 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(10 * 10 ** 13).mul( mantissaSqrtScale ); const periodicity = new BN(0); await driftClient.initializePerpMarket( 0, await mockOracleNoProgram(bankrunContextWrapper, 224.3), ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(224 * PEG_PRECISION.toNumber()) ); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); }); after(async () => { await driftClient.unsubscribe(); }); it('init feed', async () => { await driftClient.initializePythLazerOracle(1); await driftClient.initializePythLazerOracle(2); await driftClient.initializePythLazerOracle(6); }); it('crank single', async () => { await driftClient.postPythLazerOracleUpdate([6], PYTH_LAZER_HEX_STRING_SOL); await driftClient.updatePerpMarketOracle( 0, getPythLazerOraclePublicKey(driftClient.program.programId, 6), OracleSource.PYTH_LAZER ); await driftClient.fetchAccounts(); assert( isVariant( driftClient.getPerpMarketAccount(0).amm.oracleSource, 'pythLazer' ) ); }); it('crank multi', async () => { const tx = await driftClient.postPythLazerOracleUpdate( [1, 2, 6], PYTH_LAZER_HEX_STRING_MULTI ); console.log(tx); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/ordersWithSpread.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { TestClient, BN, PRICE_PRECISION, PositionDirection, User, getMarketOrderParams, AMM_RESERVE_PRECISION, calculateTradeAcquiredAmounts, convertToNumber, ZERO, calculateQuoteAssetAmountSwapped, EventSubscriber, calculateBaseAssetAmountForAmmToFulfill, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, } from './testHelpers'; import { calculateReservePrice, getLimitOrderParams, getSwapDirection, OracleSource, PEG_PRECISION, } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('amm spread: market order', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let driftClientUser: User; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(100000); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); const marketIndex = 0; let solUsd; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); const marketIndexes = [0, 1]; const spotMarketIndexes = [0]; const oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(60 * 60); // 1 HOUR await driftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await driftClient.updatePerpMarketBaseSpread(marketIndex, 500); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); }); beforeEach(async () => { await driftClient.moveAmmPrice( 0, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve ); await setFeedPriceNoProgram(bankrunContextWrapper, 1, solUsd); }); after(async () => { await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('Long market order base', async () => { const initialCollateral = driftClient.getQuoteAssetTokenAmount(); const direction = PositionDirection.LONG; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const tradeAcquiredAmountsNoSpread = calculateTradeAcquiredAmounts( direction, baseAssetAmount, driftClient.getPerpMarketAccount(0), 'base', undefined, false ); const tradeAcquiredAmountsWithSpread = calculateTradeAcquiredAmounts( direction, baseAssetAmount, driftClient.getPerpMarketAccount(0), 'base', undefined, true ); const expectedQuoteAssetAmount = calculateQuoteAssetAmountSwapped( tradeAcquiredAmountsWithSpread[1].abs(), driftClient.getPerpMarketAccount(marketIndex).amm.pegMultiplier, getSwapDirection('base', direction) ).neg(); console.log( 'expected quote with out spread', calculateQuoteAssetAmountSwapped( tradeAcquiredAmountsNoSpread[1].abs(), driftClient.getPerpMarketAccount(marketIndex).amm.pegMultiplier, getSwapDirection('base', direction) ).toString() ); console.log( 'expected quote with spread', calculateQuoteAssetAmountSwapped( tradeAcquiredAmountsWithSpread[1].abs(), driftClient.getPerpMarketAccount(marketIndex).amm.pegMultiplier, getSwapDirection('base', direction) ).toString() ); const orderParams = getMarketOrderParams({ marketIndex, direction, baseAssetAmount, }); const txSig = await driftClient.placeAndTakePerpOrder(orderParams); const computeUnits = bankrunContextWrapper.connection.findComputeUnitConsumption(txSig); console.log('compute units', computeUnits); bankrunContextWrapper.printTxLogs(txSig); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const unrealizedPnl = driftClientUser.getUnrealizedPNL(); console.log('unrealized pnl', unrealizedPnl.toString()); const market = driftClient.getPerpMarketAccount(marketIndex); const expectedQuoteAssetSurplus = new BN(250); const expectedExchangeFee = new BN(1001); const expectedFeeToMarket = expectedExchangeFee.add( expectedQuoteAssetSurplus ); console.log(market.amm.totalFee.toString()); assert(market.amm.totalFee.eq(expectedFeeToMarket)); const firstPosition = driftClient.getUserAccount().perpPositions[0]; assert(firstPosition.baseAssetAmount.eq(baseAssetAmount)); console.log( 'expectedQuoteAssetAmount:', firstPosition.quoteBreakEvenAmount.toString(), expectedQuoteAssetAmount.toString() ); assert(firstPosition.quoteEntryAmount.eq(expectedQuoteAssetAmount)); assert(firstPosition.quoteBreakEvenAmount.eq(new BN(-1001252))); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderRecord.baseAssetAmountFilled.eq(baseAssetAmount)); assert.ok( orderRecord.quoteAssetAmountFilled.eq(expectedQuoteAssetAmount.abs()) ); assert.ok( orderRecord.quoteAssetAmountSurplus.eq(expectedQuoteAssetSurplus) ); await driftClient.closePosition(marketIndex); await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const pnl = driftClient.getQuoteAssetTokenAmount().sub(initialCollateral); assert(pnl.eq(new BN(-2502))); console.log(driftClient.getPerpMarketAccount(0).amm.totalFee.toString()); assert(driftClient.getPerpMarketAccount(0).amm.totalFee.eq(new BN(2501))); }); it('short market order base', async () => { const initialCollateral = driftClient.getQuoteAssetTokenAmount(); const initialAmmTotalFee = driftClient.getPerpMarketAccount(0).amm.totalFee; const direction = PositionDirection.SHORT; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const tradeAcquiredAmountsNoSpread = calculateTradeAcquiredAmounts( direction, baseAssetAmount, driftClient.getPerpMarketAccount(0), 'base', undefined, false ); const tradeAcquiredAmountsWithSpread = calculateTradeAcquiredAmounts( direction, baseAssetAmount, driftClient.getPerpMarketAccount(0), 'base', undefined, true ); const expectedQuoteAssetAmount = calculateQuoteAssetAmountSwapped( tradeAcquiredAmountsWithSpread[1].abs(), driftClient.getPerpMarketAccount(marketIndex).amm.pegMultiplier, getSwapDirection('base', direction) ); console.log( 'expected quote with out spread', calculateQuoteAssetAmountSwapped( tradeAcquiredAmountsNoSpread[1].abs(), driftClient.getPerpMarketAccount(marketIndex).amm.pegMultiplier, getSwapDirection('base', direction) ).toString() ); console.log( 'expected quote with spread', calculateQuoteAssetAmountSwapped( tradeAcquiredAmountsWithSpread[1].abs(), driftClient.getPerpMarketAccount(marketIndex).amm.pegMultiplier, getSwapDirection('base', direction) ).toString() ); const orderParams = getMarketOrderParams({ marketIndex, direction, baseAssetAmount, }); const txSig = await driftClient.placeAndTakePerpOrder(orderParams); const computeUnits = bankrunContextWrapper.connection.findComputeUnitConsumption(txSig); console.log('compute units', computeUnits); bankrunContextWrapper.printTxLogs(txSig); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const unrealizedPnl = driftClientUser.getUnrealizedPNL(); console.log('unrealized pnl', unrealizedPnl.toString()); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderRecord.baseAssetAmountFilled.eq(baseAssetAmount)); assert.ok(orderRecord.quoteAssetAmountFilled.eq(expectedQuoteAssetAmount)); assert.ok(orderRecord.quoteAssetAmountSurplus.eq(new BN(250))); console.log('surplus', orderRecord.quoteAssetAmountSurplus.toString()); console.log(orderRecord.quoteAssetAmountSurplus.toString()); assert(orderRecord.quoteAssetAmountSurplus.eq(new BN(250))); await driftClient.closePosition(marketIndex); await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const pnl = driftClient.getQuoteAssetTokenAmount().sub(initialCollateral); console.log(pnl.toString()); assert(pnl.eq(new BN(-2502))); console.log( driftClient .getPerpMarketAccount(0) .amm.totalFee.sub(initialAmmTotalFee) .toString() ); assert( driftClient .getPerpMarketAccount(0) .amm.totalFee.sub(initialAmmTotalFee) .eq(new BN(2501)) ); }); it('unable to fill bid between mark and ask price', async () => { const direction = PositionDirection.LONG; const baseAssetAmount = AMM_RESERVE_PRECISION; const limitPrice = calculateReservePrice( driftClient.getPerpMarketAccount(0), undefined ).add(PRICE_PRECISION.div(new BN(10000))); // limit price plus 1bp const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price: limitPrice, userOrderId: 1, }); await driftClient.placePerpOrder(orderParams); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const unfilledOrder = driftClientUser.getUserAccount().orders[0]; const expectedBaseAssetAmount = calculateBaseAssetAmountForAmmToFulfill( unfilledOrder, driftClient.getPerpMarketAccount(0), driftClient.getOracleDataForPerpMarket(unfilledOrder.marketIndex), 0 ); assert(expectedBaseAssetAmount.eq(ZERO)); // fill should fail because nothing to fill try { await driftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), unfilledOrder ); assert(false); } catch (e) { // good } await driftClient.cancelOrderByUserId(1); }); it('unable to fill ask between mark and bid price', async () => { const direction = PositionDirection.SHORT; const baseAssetAmount = AMM_RESERVE_PRECISION; const limitPrice = calculateReservePrice( driftClient.getPerpMarketAccount(0), undefined ).add(PRICE_PRECISION.sub(new BN(10000))); // limit price plus 1bp const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price: limitPrice, userOrderId: 1, }); await driftClient.placePerpOrder(orderParams); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const unfilledOrder = driftClientUser.getUserAccount().orders[0]; const expectedBaseAssetAmount = calculateBaseAssetAmountForAmmToFulfill( unfilledOrder, driftClient.getPerpMarketAccount(0), driftClient.getOracleDataForPerpMarket(unfilledOrder.marketIndex), 0 ); assert(expectedBaseAssetAmount.eq(ZERO)); // fill should fail because nothing to fill try { await driftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), unfilledOrder ); assert(false); } catch (e) { // good } await driftClient.cancelOrderByUserId(1); }); it('fill limit order above ask', async () => { const initialAmmTotalFee = driftClient.getPerpMarketAccount(0).amm.totalFee; const direction = PositionDirection.LONG; const baseAssetAmount = AMM_RESERVE_PRECISION; const limitPrice = calculateReservePrice( driftClient.getPerpMarketAccount(0), undefined ).add(PRICE_PRECISION.div(new BN(1000))); // limit price plus 10bp const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price: limitPrice, userOrderId: 1, }); await driftClient.placePerpOrder(orderParams); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const order = driftClientUser.getUserAccount().orders[0]; console.log(order.baseAssetAmount.toString()); console.log( driftClientUser .getUserAccount() .perpPositions[0].baseAssetAmount.toString() ); const expectedBaseAssetAmount = calculateBaseAssetAmountForAmmToFulfill( order, driftClient.getPerpMarketAccount(0), driftClient.getOracleDataForPerpMarket(order.marketIndex), 0 ); assert(expectedBaseAssetAmount.eq(AMM_RESERVE_PRECISION)); const tradeAcquiredAmountsWithSpread = calculateTradeAcquiredAmounts( direction, baseAssetAmount, driftClient.getPerpMarketAccount(0), 'base', undefined, true ); const expectedQuoteAssetAmount = calculateQuoteAssetAmountSwapped( tradeAcquiredAmountsWithSpread[1].abs(), driftClient.getPerpMarketAccount(marketIndex).amm.pegMultiplier, getSwapDirection('base', direction) ).neg(); const txSig = await driftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); bankrunContextWrapper.printTxLogs(txSig); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const firstOrder = driftClientUser.getUserAccount().orders[0]; const firstPosition = driftClientUser.getUserAccount().perpPositions[0]; console.log(firstOrder.baseAssetAmount.toString()); console.log(firstPosition.baseAssetAmount.toString()); console.log(firstPosition.quoteBreakEvenAmount.toString()); assert(firstPosition.baseAssetAmount.eq(baseAssetAmount)); assert(firstPosition.quoteEntryAmount.eq(expectedQuoteAssetAmount)); assert(firstPosition.quoteBreakEvenAmount.eq(new BN(-1001252))); await driftClient.closePosition(marketIndex); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); assert( driftClient .getPerpMarketAccount(0) .amm.totalFee.sub(initialAmmTotalFee) .eq(new BN(2501)) ); }); it('fill limit order below bid', async () => { const initialAmmTotalFee = driftClient.getPerpMarketAccount(0).amm.totalFee; const direction = PositionDirection.SHORT; const baseAssetAmount = AMM_RESERVE_PRECISION; const limitPrice = calculateReservePrice( driftClient.getPerpMarketAccount(0), undefined ).sub(PRICE_PRECISION.div(new BN(1000))); // limit price minus 10bp const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price: limitPrice, userOrderId: 1, }); await driftClient.placePerpOrder(orderParams); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const order = driftClientUser.getUserAccount().orders[0]; console.log(order.baseAssetAmount.toString()); console.log( driftClientUser .getUserAccount() .perpPositions[0].baseAssetAmount.toString() ); const expectedBaseAssetAmount = calculateBaseAssetAmountForAmmToFulfill( order, driftClient.getPerpMarketAccount(0), driftClient.getOracleDataForPerpMarket(order.marketIndex), 0 ); assert(expectedBaseAssetAmount.eq(AMM_RESERVE_PRECISION)); const tradeAcquiredAmountsWithSpread = calculateTradeAcquiredAmounts( direction, baseAssetAmount, driftClient.getPerpMarketAccount(0), 'base', undefined, true ); const expectedQuoteAssetAmount = calculateQuoteAssetAmountSwapped( tradeAcquiredAmountsWithSpread[1].abs(), driftClient.getPerpMarketAccount(marketIndex).amm.pegMultiplier, getSwapDirection('base', direction) ); const txSig = await driftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); bankrunContextWrapper.printTxLogs(txSig); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const firstOrder = driftClientUser.getUserAccount().orders[0]; const firstPosition = driftClientUser.getUserAccount().perpPositions[0]; console.log(firstOrder.baseAssetAmount.toString()); console.log(firstPosition.baseAssetAmount.toString()); console.log(firstPosition.quoteBreakEvenAmount.toString()); assert(firstPosition.baseAssetAmount.abs().eq(baseAssetAmount)); assert(firstPosition.quoteEntryAmount.eq(expectedQuoteAssetAmount)); assert(firstPosition.quoteBreakEvenAmount.eq(new BN(998750))); await driftClient.closePosition(marketIndex); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); assert( driftClient .getPerpMarketAccount(0) .amm.totalFee.sub(initialAmmTotalFee) .eq(new BN(2501)) ); }); it('Long market order base w/ variable reduce/close', async () => { const marketIndex2Num = 1; const marketIndex2 = marketIndex2Num; const peg = 40000; const btcUsd = await mockOracleNoProgram(bankrunContextWrapper, peg); const periodicity = new BN(60 * 60); // 1 HOUR const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 15).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 15).mul( mantissaSqrtScale ); await driftClient.initializePerpMarket( marketIndex2, btcUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(peg * PEG_PRECISION.toNumber()) ); await driftClient.updatePerpMarketBaseSpread(marketIndex2, 500); const initialCollateral = driftClient.getQuoteAssetTokenAmount(); const direction = PositionDirection.LONG; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION.toNumber() / 10000); // ~$4 of btc const market2 = driftClient.getPerpMarketAccount(marketIndex2Num); const tradeAcquiredAmountsNoSpread = calculateTradeAcquiredAmounts( direction, baseAssetAmount, market2, 'base', undefined, false ); const tradeAcquiredAmountsWithSpread = calculateTradeAcquiredAmounts( direction, baseAssetAmount, market2, 'base', undefined, true ); const expectedQuoteAssetAmount = calculateQuoteAssetAmountSwapped( tradeAcquiredAmountsWithSpread[1].abs(), driftClient.getPerpMarketAccount(marketIndex2Num).amm.pegMultiplier, getSwapDirection('base', direction) ).neg(); console.log( 'expected quote with out spread', calculateQuoteAssetAmountSwapped( tradeAcquiredAmountsNoSpread[1].abs(), driftClient.getPerpMarketAccount(marketIndex2Num).amm.pegMultiplier, getSwapDirection('base', direction) ).toString() ); console.log( 'expected quote with spread', calculateQuoteAssetAmountSwapped( tradeAcquiredAmountsWithSpread[1].abs(), driftClient.getPerpMarketAccount(marketIndex2Num).amm.pegMultiplier, getSwapDirection('base', direction) ).toString() ); const orderParams = getMarketOrderParams({ marketIndex: marketIndex2, direction, baseAssetAmount, }); const txSig = await driftClient.placeAndTakePerpOrder(orderParams); const computeUnits = bankrunContextWrapper.connection.findComputeUnitConsumption(txSig); console.log('compute units', computeUnits); bankrunContextWrapper.printTxLogs(txSig); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const unrealizedPnl = driftClientUser.getUnrealizedPNL(); console.log('unrealized pnl', unrealizedPnl.toString()); const expectedFeeToMarket = new BN(1040); const firstPosition = driftClient.getUserAccount().perpPositions[1]; console.log( convertToNumber(firstPosition.baseAssetAmount), convertToNumber(baseAssetAmount) ); assert(firstPosition.baseAssetAmount.eq(baseAssetAmount)); console.log( convertToNumber(firstPosition.quoteAssetAmount), convertToNumber(expectedQuoteAssetAmount) ); assert(firstPosition.quoteEntryAmount.eq(expectedQuoteAssetAmount)); assert(firstPosition.quoteBreakEvenAmount.eq(new BN(-4005043))); //todo const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderRecord.baseAssetAmountFilled.eq(baseAssetAmount)); assert.ok( orderRecord.quoteAssetAmountFilled.eq(expectedQuoteAssetAmount.abs()) ); console.log('surplus', orderRecord.quoteAssetAmountSurplus.toString()); assert.ok(orderRecord.quoteAssetAmountSurplus.eq(expectedFeeToMarket)); const numCloses = 10; const directionToClose = PositionDirection.SHORT; for (let i = numCloses; i > 0; i--) { const orderParams = getMarketOrderParams({ marketIndex: marketIndex2, direction: directionToClose, baseAssetAmount: baseAssetAmount.div(new BN(numCloses * i)), // variable sized close }); try { await driftClient.placeAndTakePerpOrder(orderParams); } catch (e) { console.error(e); } } try { await driftClient.closePosition(marketIndex2); // close rest } catch (e) { console.error(e); } await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const pnl = driftClient.getQuoteAssetTokenAmount().sub(initialCollateral); console.log('pnl', pnl.toString()); console.log( 'total fee', driftClient.getPerpMarketAccount(marketIndex2Num).amm.totalFee.toString() ); assert( driftClient .getPerpMarketAccount(marketIndex2Num) .amm.totalFee.eq(new BN(10041)) ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/perpLpJit.ts
import * as web3 from '@solana/web3.js'; import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { assert } from 'chai'; import { TestClient, QUOTE_PRECISION, EventSubscriber, PRICE_PRECISION, PositionDirection, ZERO, BN, calculateAmmReservesAfterSwap, calculatePrice, User, OracleSource, SwapDirection, Wallet, LPRecord, BASE_PRECISION, getLimitOrderParams, OracleGuardRails, PostOnlyParams, isVariant, calculateBidAskPrice, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, sleep, // sleep, } from './testHelpers'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; let lastOrderRecordsLength = 0; async function adjustOraclePostSwap(baa, swapDirection, market, context) { const price = calculatePrice( market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier ); const [newQaa, newBaa] = calculateAmmReservesAfterSwap( market.amm, 'base', baa.abs(), swapDirection ); const newPrice = calculatePrice(newBaa, newQaa, market.amm.pegMultiplier); const _newPrice = newPrice.toNumber() / PRICE_PRECISION.toNumber(); await setFeedPriceNoProgram(context, _newPrice, market.amm.oracle); console.log('price => new price', price.toString(), newPrice.toString()); return _newPrice; } async function createNewUser( program, context, usdcMint, usdcAmount, oracleInfos, wallet, bulkAccountLoader ) { let walletFlag = true; if (wallet == undefined) { const kp = new web3.Keypair(); await context.fundKeypair(kp, 10 ** 9); wallet = new Wallet(kp); walletFlag = false; } console.log('wallet:', walletFlag); const usdcAta = await mockUserUSDCAccount( usdcMint, usdcAmount, context, wallet.publicKey ); const driftClient = new TestClient({ connection: context.connection.toConnection(), wallet: wallet, programID: program.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0, 1, 2, 3], spotMarketIndexes: [0], subAccountIds: [], oracleInfos, accountSubscription: bulkAccountLoader ? { type: 'polling', accountLoader: bulkAccountLoader, } : { type: 'websocket', }, }); if (walletFlag) { await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); } else { await driftClient.subscribe(); } await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, usdcAta.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); driftClientUser.subscribe(); return [driftClient, driftClientUser]; } describe('lp jit', () => { const chProgram = anchor.workspace.Drift as Program; async function _viewLogs(txsig) { bankrunContextWrapper.printTxLogs(txsig); } async function delay(time) { await new Promise((resolve) => setTimeout(resolve, time)); } // ammInvariant == k == x * y const ammInitialBaseAssetReserve = new BN(300).mul(BASE_PRECISION); const ammInitialQuoteAssetReserve = new BN(300).mul(BASE_PRECISION); const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const stableAmmInitialQuoteAssetReserve = BASE_PRECISION.mul(mantissaSqrtScale); const stableAmmInitialBaseAssetReserve = BASE_PRECISION.mul(mantissaSqrtScale); const usdcAmount = new BN(1_000_000_000 * 1e6); // 1 milli let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint: web3.Keypair; let driftClientUser: User; let traderDriftClient: TestClient; let traderDriftClientUser: User; let poorDriftClient: TestClient; let poorDriftClientUser: User; let solusdc; let solusdc2; let solusdc3; let btcusdc; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); solusdc3 = await mockOracleNoProgram(bankrunContextWrapper, 1, -7); // make invalid solusdc2 = await mockOracleNoProgram(bankrunContextWrapper, 1, -7); // make invalid solusdc = await mockOracleNoProgram(bankrunContextWrapper, 1, -7); // make invalid btcusdc = await mockOracleNoProgram(bankrunContextWrapper, 26069, -7); const oracleInfos = [ { publicKey: solusdc, source: OracleSource.PYTH }, { publicKey: solusdc2, source: OracleSource.PYTH }, { publicKey: solusdc3, source: OracleSource.PYTH }, { publicKey: btcusdc, source: OracleSource.PYTH }, ]; // @ts-ignore [driftClient, driftClientUser] = await createNewUser( chProgram, bankrunContextWrapper, usdcMint, usdcAmount, oracleInfos, bankrunContextWrapper.provider.wallet, bulkAccountLoader ); // used for trading / taking on baa await driftClient.initializePerpMarket( 0, solusdc, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, new BN(60 * 60) ); await driftClient.updateLpCooldownTime(new BN(0)); await driftClient.updatePerpMarketMaxFillReserveFraction(0, 1); const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: new BN(1000000), oracleTwap5MinPercentDivergence: new BN(1000000), }, validity: { slotsBeforeStaleForAmm: new BN(10), slotsBeforeStaleForMargin: new BN(10), confidenceIntervalMaxSize: new BN(100), tooVolatileRatio: new BN(100), }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); // await driftClient.updateMarketBaseAssetAmountStepSize( // new BN(0), // new BN(1) // ); // second market -- used for funding .. await driftClient.initializePerpMarket( 1, solusdc2, stableAmmInitialBaseAssetReserve, stableAmmInitialQuoteAssetReserve, new BN(0) ); await driftClient.updateLpCooldownTime(new BN(0)); await driftClient.updatePerpAuctionDuration(new BN(0)); // third market await driftClient.initializePerpMarket( 2, solusdc3, stableAmmInitialBaseAssetReserve, stableAmmInitialQuoteAssetReserve, new BN(0) ); // third market await driftClient.initializePerpMarket( 3, btcusdc, stableAmmInitialBaseAssetReserve.div(new BN(1000)), stableAmmInitialQuoteAssetReserve.div(new BN(1000)), new BN(0), new BN(26690 * 1000) ); await driftClient.updateLpCooldownTime(new BN(0)); await driftClient.updatePerpAuctionDuration(new BN(0)); // @ts-ignore [traderDriftClient, traderDriftClientUser] = await createNewUser( chProgram, bankrunContextWrapper, usdcMint, usdcAmount, oracleInfos, undefined, bulkAccountLoader ); // @ts-ignore [poorDriftClient, poorDriftClientUser] = await createNewUser( chProgram, bankrunContextWrapper, usdcMint, QUOTE_PRECISION.mul(new BN(10000)), oracleInfos, undefined, bulkAccountLoader ); }); after(async () => { await eventSubscriber.unsubscribe(); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); await traderDriftClient.unsubscribe(); await traderDriftClientUser.unsubscribe(); await poorDriftClient.unsubscribe(); await poorDriftClientUser.unsubscribe(); }); const lpCooldown = 1; it('perp jit check (amm jit intensity = 0)', async () => { const marketIndex = 0; console.log('adding liquidity...'); await driftClient.updatePerpMarketTargetBaseAssetAmountPerLp( 0, BASE_PRECISION.toNumber() ); sleep(1200); await driftClient.fetchAccounts(); let market = driftClient.getPerpMarketAccount(0); console.log( 'market.amm.sqrtK:', market.amm.userLpShares.toString(), '/', market.amm.sqrtK.toString(), 'target:', market.amm.targetBaseAssetAmountPerLp ); assert(market.amm.sqrtK.eq(new BN('300000000000'))); assert(market.amm.baseAssetAmountPerLp.eq(ZERO)); // assert(market.amm.targetBaseAssetAmountPerLp == BASE_PRECISION.toNumber()); const _sig = await driftClient.addPerpLpShares( new BN(100 * BASE_PRECISION.toNumber()), market.marketIndex ); await delay(lpCooldown + 1000); await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(0); console.log( 'market.amm.sqrtK:', market.amm.userLpShares.toString(), '/', market.amm.sqrtK.toString() ); assert(market.amm.sqrtK.eq(new BN('400000000000'))); assert(market.amm.baseAssetAmountPerLp.eq(ZERO)); assert(market.amm.targetBaseAssetAmountPerLp == BASE_PRECISION.toNumber()); let user = await driftClientUser.getUserAccount(); assert(user.perpPositions[0].lpShares.toString() == '100000000000'); // 10 * 1e9 // lp goes long const tradeSize = new BN(5 * BASE_PRECISION.toNumber()); try { await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await driftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex // new BN(100 * BASE_PRECISION.toNumber()) ); await _viewLogs(_txsig); } catch (e) { console.log(e); } await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(0); console.log( 'market.amm.baseAssetAmountPerLp:', market.amm.baseAssetAmountPerLp.toString() ); assert(market.amm.baseAssetAmountPerLp.eq(new BN('-12500000'))); // some user goes long (lp should get a short + pnl for closing long on settle) try { await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await traderDriftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex // new BN(100 * BASE_PRECISION.toNumber()) ); await _viewLogs(_txsig); } catch (e) { console.log(e); } await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(0); console.log( 'market.amm.baseAssetAmountPerLp:', market.amm.baseAssetAmountPerLp.toString() ); assert(market.amm.baseAssetAmountPerLp.eq(new BN('-25000000'))); console.log( 'market.amm.baseAssetAmountWithAmm:', market.amm.baseAssetAmountWithAmm.toString() ); assert(market.amm.baseAssetAmountWithAmm.eq(new BN('7500000000'))); // add jit maker going other way const takerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount: tradeSize, price: new BN(0.9 * PRICE_PRECISION.toNumber()), auctionStartPrice: new BN(0.99 * PRICE_PRECISION.toNumber()), auctionEndPrice: new BN(0.929 * PRICE_PRECISION.toNumber()), auctionDuration: 10, userOrderId: 1, postOnly: PostOnlyParams.NONE, }); await traderDriftClient.placePerpOrder(takerOrderParams); await traderDriftClient.fetchAccounts(); const order = traderDriftClientUser.getOrderByUserOrderId(1); assert(!order.postOnly); const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount: tradeSize, price: new BN(1.011 * PRICE_PRECISION.toNumber()), userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, immediateOrCancel: true, }); const txSig = await poorDriftClient.placeAndMakePerpOrder( makerOrderParams, { taker: await traderDriftClient.getUserAccountPublicKey(), order: traderDriftClient.getOrderByUserId(1), takerUserAccount: traderDriftClient.getUserAccount(), takerStats: traderDriftClient.getUserStatsAccountPublicKey(), } ); await _viewLogs(txSig); await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(0); console.log( 'market.amm.baseAssetAmountPerLp:', market.amm.baseAssetAmountPerLp.toString() ); assert(market.amm.baseAssetAmountPerLp.eq(new BN('-12500000'))); console.log( 'market.amm.baseAssetAmountWithAmm:', market.amm.baseAssetAmountWithAmm.toString() ); assert(market.amm.baseAssetAmountWithAmm.eq(new BN('3750000000'))); console.log( 'market.amm.baseAssetAmountWithUnsettledLp:', market.amm.baseAssetAmountWithUnsettledLp.toString() ); assert(market.amm.baseAssetAmountWithUnsettledLp.eq(new BN('1250000000'))); const trader = await traderDriftClient.getUserAccount(); console.log( 'trader size', trader.perpPositions[0].baseAssetAmount.toString() ); await driftClientUser.fetchAccounts(); const sdkPnl = driftClientUser.getPerpPositionWithLPSettle(0)[2]; console.log('settling...'); try { const _txsigg = await driftClient.settleLP( await driftClient.getUserAccountPublicKey(), 0 ); await _viewLogs(_txsigg); } catch (e) { console.log(e); } user = await await driftClientUser.getUserAccount(); const settleLiquidityRecord: LPRecord = eventSubscriber.getEventsArray('LPRecord')[0]; console.log( 'settle pnl vs sdk', settleLiquidityRecord.pnl.toString(), sdkPnl.toString() ); assert(settleLiquidityRecord.pnl.eq(sdkPnl)); }); it('perp jit check (amm jit intensity = 100)', async () => { const marketIndex = 1; await driftClient.updateAmmJitIntensity(marketIndex, 100); console.log('adding liquidity...'); await driftClient.updatePerpMarketTargetBaseAssetAmountPerLp( marketIndex, BASE_PRECISION.toNumber() ); await delay(lpCooldown + 1000); await driftClient.fetchAccounts(); let market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market.amm.sqrtK:', market.amm.userLpShares.toString(), '/', market.amm.sqrtK.toString() ); assert(market.amm.sqrtK.eq(new BN('1000000000000'))); assert(market.amm.baseAssetAmountPerLp.eq(ZERO)); assert(market.amm.targetBaseAssetAmountPerLp == BASE_PRECISION.toNumber()); const _sig = await driftClient.addPerpLpShares( new BN(100 * BASE_PRECISION.toNumber()), market.marketIndex ); await delay(lpCooldown + 1000); await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market.amm.sqrtK:', market.amm.userLpShares.toString(), '/', market.amm.sqrtK.toString() ); assert(market.amm.sqrtK.eq(new BN('1100000000000'))); assert(market.amm.baseAssetAmountPerLp.eq(ZERO)); assert(market.amm.targetBaseAssetAmountPerLp == BASE_PRECISION.toNumber()); await driftClientUser.fetchAccounts(); let user = await driftClientUser.getUserAccount(); assert(user.perpPositions[0].lpShares.toString() == '100000000000'); // 10 * 1e9 // lp goes long const tradeSize = new BN(5 * BASE_PRECISION.toNumber()); try { await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await driftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex // new BN(100 * BASE_PRECISION.toNumber()) ); await _viewLogs(_txsig); } catch (e) { console.log(e); } await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market.amm.baseAssetAmountPerLp:', market.amm.baseAssetAmountPerLp.toString() ); assert(market.amm.baseAssetAmountPerLp.eq(new BN('-4545454'))); // some user goes long (lp should get a short + pnl for closing long on settle) try { await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await traderDriftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex // new BN(100 * BASE_PRECISION.toNumber()) ); await _viewLogs(_txsig); } catch (e) { console.log(e); } await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market.amm.baseAssetAmountPerLp:', market.amm.baseAssetAmountPerLp.toString() ); assert(market.amm.baseAssetAmountPerLp.eq(new BN('-9090908'))); console.log( 'market.amm.baseAssetAmountWithAmm:', market.amm.baseAssetAmountWithAmm.toString() ); assert(market.amm.baseAssetAmountWithAmm.eq(new BN('9090909200'))); // add jit maker going other way const takerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount: tradeSize, price: new BN(0.9 * PRICE_PRECISION.toNumber()), auctionStartPrice: new BN(0.99 * PRICE_PRECISION.toNumber()), auctionEndPrice: new BN(0.929 * PRICE_PRECISION.toNumber()), auctionDuration: 10, userOrderId: 1, postOnly: PostOnlyParams.NONE, }); await traderDriftClient.placePerpOrder(takerOrderParams); await traderDriftClient.fetchAccounts(); const order = traderDriftClient.getUser().getOrderByUserOrderId(1); assert(!order.postOnly); const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount: tradeSize, price: new BN(1.011 * PRICE_PRECISION.toNumber()), userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, immediateOrCancel: true, }); const txSig = await poorDriftClient.placeAndMakePerpOrder( makerOrderParams, { taker: await traderDriftClient.getUserAccountPublicKey(), order: traderDriftClient.getOrderByUserId(1), takerUserAccount: traderDriftClient.getUserAccount(), takerStats: traderDriftClient.getUserStatsAccountPublicKey(), } ); await _viewLogs(txSig); await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market.amm.baseAssetAmountPerLp:', market.amm.baseAssetAmountPerLp.toString() ); assert(market.amm.baseAssetAmountPerLp.eq(new BN('-5455090'))); console.log( 'market.amm.baseAssetAmountWithAmm:', market.amm.baseAssetAmountWithAmm.toString() ); assert(market.amm.baseAssetAmountWithAmm.eq(new BN('5204991000'))); console.log( 'market.amm.baseAssetAmountWithUnsettledLp:', market.amm.baseAssetAmountWithUnsettledLp.toString() ); assert(market.amm.baseAssetAmountWithUnsettledLp.eq(new BN('545509000'))); const trader = await traderDriftClient.getUserAccount(); console.log( 'trader size', trader.perpPositions[0].baseAssetAmount.toString() ); await driftClientUser.fetchAccounts(); const sdkPnl = driftClientUser.getPerpPositionWithLPSettle(0)[2]; console.log('settling...'); try { const _txsigg = await driftClient.settleLP( await driftClient.getUserAccountPublicKey(), 0 ); await _viewLogs(_txsigg); } catch (e) { console.log(e); } await driftClientUser.fetchAccounts(); user = await driftClientUser.getUserAccount(); const settleLiquidityRecord: LPRecord = eventSubscriber.getEventsArray('LPRecord')[0]; console.log( 'settle pnl vs sdk', settleLiquidityRecord.pnl.toString(), sdkPnl.toString() ); // assert(settleLiquidityRecord.pnl.eq(sdkPnl)); //TODO }); it('perp jit check (amm jit intensity = 200)', async () => { const marketIndex = 2; await driftClient.updateAmmJitIntensity(marketIndex, 200); console.log('adding liquidity...'); await driftClient.updatePerpMarketTargetBaseAssetAmountPerLp( marketIndex, BASE_PRECISION.toNumber() ); sleep(1200); await driftClient.fetchAccounts(); let market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market.amm.sqrtK:', market.amm.userLpShares.toString(), '/', market.amm.sqrtK.toString() ); assert(market.amm.sqrtK.eq(new BN('1000000000000'))); assert(market.amm.baseAssetAmountPerLp.eq(ZERO)); assert( market.amm.targetBaseAssetAmountPerLp == BASE_PRECISION.toNumber(), `targetBaseAssetAmountPerLp: ${ market.amm.targetBaseAssetAmountPerLp } != ${BASE_PRECISION.toNumber()}` ); const _sig = await driftClient.addPerpLpShares( new BN(100 * BASE_PRECISION.toNumber()), market.marketIndex ); await delay(lpCooldown + 1000); await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market.amm.sqrtK:', market.amm.userLpShares.toString(), '/', market.amm.sqrtK.toString() ); assert(market.amm.sqrtK.eq(new BN('1100000000000'))); assert(market.amm.baseAssetAmountPerLp.eq(ZERO)); assert(market.amm.targetBaseAssetAmountPerLp == BASE_PRECISION.toNumber()); await driftClientUser.fetchAccounts(); let user = await driftClientUser.getUserAccount(); assert(user.perpPositions[0].lpShares.toString() == '100000000000'); // 10 * 1e9 // lp goes long const tradeSize = new BN(5 * BASE_PRECISION.toNumber()); try { await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await driftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex // new BN(100 * BASE_PRECISION.toNumber()) ); await _viewLogs(_txsig); } catch (e) { console.log(e); } await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market.amm.baseAssetAmountPerLp:', market.amm.baseAssetAmountPerLp.toString() ); assert(market.amm.baseAssetAmountPerLp.eq(new BN('-4545454'))); // some user goes long (lp should get a short + pnl for closing long on settle) // try { await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await traderDriftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex // new BN(100 * BASE_PRECISION.toNumber()) ); await _viewLogs(_txsig); // } catch (e) { // console.log(e); // } await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market.amm.baseAssetAmountPerLp:', market.amm.baseAssetAmountPerLp.toString() ); assert(market.amm.baseAssetAmountPerLp.eq(new BN('-9090908'))); console.log( 'market.amm.baseAssetAmountWithAmm:', market.amm.baseAssetAmountWithAmm.toString() ); assert(market.amm.baseAssetAmountWithAmm.eq(new BN('9090909200'))); // const trader = await traderDriftClient.getUserAccount(); // console.log( // 'trader size', // trader.perpPositions[0].baseAssetAmount.toString() // ); for (let i = 0; i < 10; i++) { // add jit maker going other way const takerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount: tradeSize, price: new BN(0.9 * PRICE_PRECISION.toNumber()), auctionStartPrice: new BN(0.99 * PRICE_PRECISION.toNumber()), auctionEndPrice: new BN(0.929 * PRICE_PRECISION.toNumber()), auctionDuration: 10, userOrderId: 1, postOnly: PostOnlyParams.NONE, }); await traderDriftClient.placePerpOrder(takerOrderParams); await traderDriftClient.fetchAccounts(); // console.log(takerOrderParams); const order = traderDriftClient.getUser().getOrderByUserOrderId(1); // console.log(order); assert(!order.postOnly); const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount: tradeSize, price: new BN(1.011 * PRICE_PRECISION.toNumber()), userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, immediateOrCancel: true, }); // console.log('maker:', makerOrderParams); const txSig = await poorDriftClient.placeAndMakePerpOrder( makerOrderParams, { taker: await traderDriftClient.getUserAccountPublicKey(), order: traderDriftClient.getOrderByUserId(1), takerUserAccount: traderDriftClient.getUserAccount(), takerStats: traderDriftClient.getUserStatsAccountPublicKey(), } ); await _viewLogs(txSig); await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market.amm.baseAssetAmountPerLp:', market.amm.baseAssetAmountPerLp.toString() ); console.log( 'market.amm.baseAssetAmountWithAmm:', market.amm.baseAssetAmountWithAmm.toString() ); console.log( 'market.amm.baseAssetAmountWithUnsettledLp:', market.amm.baseAssetAmountWithUnsettledLp.toString() ); if (i == 0) { assert(market.amm.baseAssetAmountPerLp.eq(new BN('-5227727'))); assert(market.amm.baseAssetAmountWithAmm.eq(new BN('5227727300'))); assert( market.amm.baseAssetAmountWithUnsettledLp.eq(new BN('522772700')) ); } } market = driftClient.getPerpMarketAccount(marketIndex); assert(market.amm.baseAssetAmountPerLp.eq(new BN('12499904'))); assert(market.amm.baseAssetAmountWithAmm.eq(new BN('90400'))); assert(market.amm.baseAssetAmountWithUnsettledLp.eq(new BN('-1249990400'))); const trader = await traderDriftClient.getUserAccount(); console.log( 'trader size', trader.perpPositions[0].baseAssetAmount.toString() ); await driftClientUser.fetchAccounts(); const sdkPnl = driftClientUser.getPerpPositionWithLPSettle(0)[2]; console.log('settling...'); try { const _txsigg = await driftClient.settleLP( await driftClient.getUserAccountPublicKey(), 0 ); await _viewLogs(_txsigg); } catch (e) { console.log(e); } user = await driftClientUser.getUserAccount(); const orderRecords = eventSubscriber.getEventsArray('OrderActionRecord'); const matchOrderRecord = orderRecords[1]; assert( isVariant(matchOrderRecord.actionExplanation, 'orderFilledWithMatchJit') ); assert(matchOrderRecord.baseAssetAmountFilled.toString(), '3750000000'); assert(matchOrderRecord.quoteAssetAmountFilled.toString(), '3791212'); const jitOrderRecord = orderRecords[2]; assert(isVariant(jitOrderRecord.actionExplanation, 'orderFilledWithLpJit')); assert(jitOrderRecord.baseAssetAmountFilled.toString(), '1250000000'); assert(jitOrderRecord.quoteAssetAmountFilled.toString(), '1263738'); // console.log('len of orderRecords', orderRecords.length); lastOrderRecordsLength = orderRecords.length; // Convert the array to a JSON string // const fs = require('fs'); // // Custom replacer function to convert BN values to numerical representation // const replacer = (key, value) => { // if (value instanceof BN) { // return value.toString(10); // Convert BN to base-10 string // } // return value; // }; // const jsonOrderRecords = JSON.stringify(orderRecords, replacer); // // Write the JSON string to a file // fs.writeFile('orderRecords.json', jsonOrderRecords, 'utf8', (err) => { // if (err) { // console.error('Error writing to JSON file:', err); // return; // } // console.log('orderRecords successfully written to orderRecords.json'); // }); // assert(orderRecords) const settleLiquidityRecord: LPRecord = eventSubscriber.getEventsArray('LPRecord')[0]; console.log( 'settle pnl vs sdk', settleLiquidityRecord.pnl.toString(), sdkPnl.toString() ); // assert(settleLiquidityRecord.pnl.eq(sdkPnl)); }); it('perp jit check BTC inout (amm jit intensity = 200)', async () => { const marketIndex = 3; await driftClient.updateAmmJitIntensity(marketIndex, 200); await driftClient.updatePerpMarketCurveUpdateIntensity(marketIndex, 100); await driftClient.updatePerpMarketMaxSpread(marketIndex, 100000); await driftClient.updatePerpMarketBaseSpread(marketIndex, 10000); sleep(1200); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); let market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market.amm.sqrtK:', market.amm.userLpShares.toString(), '/', market.amm.sqrtK.toString() ); assert(market.amm.sqrtK.eq(new BN('1000000000'))); assert(market.amm.baseAssetAmountPerLp.eq(ZERO)); assert(market.amm.targetBaseAssetAmountPerLp == 0); console.log('adding liquidity...'); const _sig = await driftClient.addPerpLpShares( BASE_PRECISION, market.marketIndex ); await delay(lpCooldown + 1000); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market.amm.sqrtK:', market.amm.userLpShares.toString(), '/', market.amm.sqrtK.toString() ); assert(market.amm.sqrtK.eq(new BN('2000000000'))); assert(market.amm.baseAssetAmountPerLp.eq(ZERO)); let [bid, ask] = calculateBidAskPrice( driftClient.getPerpMarketAccount(marketIndex).amm, driftClient.getOracleDataForPerpMarket(marketIndex) ); console.log(bid.toString(), '/', ask.toString()); console.log('bid:', bid.toString()); console.log('ask:', ask.toString()); let perpy = await driftClientUser.getPerpPosition(marketIndex); assert(perpy.lpShares.toString() == '1000000000'); // 1e9 console.log( 'user.perpPositions[0].baseAssetAmount:', perpy.baseAssetAmount.toString() ); assert(perpy.baseAssetAmount.toString() == '0'); // no fills // trader goes long const tradeSize = BASE_PRECISION.div(new BN(20)); const _txsig = await traderDriftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex // new BN(100 * BASE_PRECISION.toNumber()) ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); perpy = await driftClientUser.getPerpPosition(marketIndex); assert(perpy.baseAssetAmount.toString() == '0'); // unsettled await driftClient.settleLP( await driftClient.getUserAccountPublicKey(), marketIndex ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); perpy = await driftClientUser.getPerpPosition(marketIndex); console.log('perpy.baseAssetAmount:', perpy.baseAssetAmount.toString()); assert(perpy.baseAssetAmount.toString() == '-10000000'); // settled [bid, ask] = calculateBidAskPrice( driftClient.getPerpMarketAccount(marketIndex).amm, driftClient.getOracleDataForPerpMarket(marketIndex) ); console.log(bid.toString(), '/', ask.toString()); console.log('bid:', bid.toString()); console.log('ask:', ask.toString()); const takerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount: tradeSize, price: new BN(26000 * PRICE_PRECISION.toNumber()), auctionStartPrice: new BN(26400.99 * PRICE_PRECISION.toNumber()), auctionEndPrice: new BN(26000.929 * PRICE_PRECISION.toNumber()), auctionDuration: 10, userOrderId: 1, postOnly: PostOnlyParams.NONE, }); await traderDriftClient.placePerpOrder(takerOrderParams); await traderDriftClient.fetchAccounts(); // console.log(takerOrderParams); // const order = traderDriftClientUser.getOrderByUserOrderId(1); const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount: tradeSize, price: new BN(26488.88 * PRICE_PRECISION.toNumber()), userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, immediateOrCancel: true, }); [bid, ask] = calculateBidAskPrice( driftClient.getPerpMarketAccount(marketIndex).amm, driftClient.getOracleDataForPerpMarket(marketIndex) ); console.log(bid.toString(), '/', ask.toString()); console.log('bid:', bid.toString()); console.log('ask:', ask.toString()); await poorDriftClient.placeAndMakePerpOrder(makerOrderParams, { taker: await traderDriftClient.getUserAccountPublicKey(), order: traderDriftClient.getOrderByUserId(1), takerUserAccount: traderDriftClient.getUserAccount(), takerStats: traderDriftClient.getUserStatsAccountPublicKey(), }); await driftClient.fetchAccounts(); const marketAfter = driftClient.getPerpMarketAccount(marketIndex); const orderRecords = eventSubscriber.getEventsArray('OrderActionRecord'); console.log('len of orderRecords', orderRecords.length); assert(orderRecords.length - lastOrderRecordsLength == 7); lastOrderRecordsLength = orderRecords.length; // Convert the array to a JSON string // console.log(marketAfter); console.log(marketAfter.amm.baseAssetAmountPerLp.toString()); console.log(marketAfter.amm.quoteAssetAmountPerLp.toString()); console.log(marketAfter.amm.baseAssetAmountWithUnsettledLp.toString()); console.log(marketAfter.amm.baseAssetAmountWithAmm.toString()); assert(marketAfter.amm.baseAssetAmountPerLp.eq(new BN(-5000000))); assert(marketAfter.amm.quoteAssetAmountPerLp.eq(new BN(144606790 - 1))); assert(marketAfter.amm.baseAssetAmountWithUnsettledLp.eq(new BN(-5000000))); assert(marketAfter.amm.baseAssetAmountWithAmm.eq(new BN(5000000))); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const perpPos = driftClientUser.getPerpPosition(marketIndex); console.log(perpPos.baseAssetAmount.toString()); assert(perpPos.baseAssetAmount.toString() == '-10000000'); const [settledPos, dustPos, lpPnl] = driftClientUser.getPerpPositionWithLPSettle( marketIndex, undefined, false, true ); // console.log('settlePos:', settledPos); console.log('dustPos:', dustPos.toString()); console.log('lpPnl:', lpPnl.toString()); assert(dustPos.toString() == '0'); assert(lpPnl.toString() == '6134171'); const _sig2 = await driftClient.settleLP( await driftClient.getUserAccountPublicKey(), marketIndex ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const perpPosAfter = driftClientUser.getPerpPosition(marketIndex); console.log( 'perpPosAfter.baseAssetAmount:', perpPosAfter.baseAssetAmount.toString() ); assert(perpPosAfter.baseAssetAmount.toString() == '-5000000'); assert(perpPosAfter.baseAssetAmount.eq(settledPos.baseAssetAmount)); const takerOrderParams2 = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount: tradeSize.mul(new BN(20)), price: new BN(26000 * PRICE_PRECISION.toNumber()), auctionStartPrice: new BN(26400.99 * PRICE_PRECISION.toNumber()), auctionEndPrice: new BN(26000.929 * PRICE_PRECISION.toNumber()), auctionDuration: 10, userOrderId: 1, postOnly: PostOnlyParams.NONE, }); await traderDriftClient.placePerpOrder(takerOrderParams2); await traderDriftClient.fetchAccounts(); // console.log(takerOrderParams); // const order = traderDriftClientUser.getOrderByUserOrderId(1); const makerOrderParams2 = getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount: tradeSize.mul(new BN(20)), price: new BN(26488.88 * PRICE_PRECISION.toNumber()), userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, immediateOrCancel: true, }); [bid, ask] = calculateBidAskPrice( driftClient.getPerpMarketAccount(marketIndex).amm, driftClient.getOracleDataForPerpMarket(marketIndex) ); console.log(bid.toString(), '/', ask.toString()); console.log('bid:', bid.toString()); console.log('ask:', ask.toString()); await poorDriftClient.placeAndMakePerpOrder(makerOrderParams2, { taker: await traderDriftClient.getUserAccountPublicKey(), order: traderDriftClient.getOrderByUserId(1), takerUserAccount: traderDriftClient.getUserAccount(), takerStats: traderDriftClient.getUserStatsAccountPublicKey(), }); const marketAfter2 = driftClient.getPerpMarketAccount(marketIndex); console.log(marketAfter2.amm.baseAssetAmountPerLp.toString()); console.log(marketAfter2.amm.quoteAssetAmountPerLp.toString()); console.log(marketAfter2.amm.baseAssetAmountWithUnsettledLp.toString()); console.log(marketAfter2.amm.baseAssetAmountWithAmm.toString()); assert(marketAfter2.amm.baseAssetAmountPerLp.eq(new BN(-2500000))); assert(marketAfter2.amm.quoteAssetAmountPerLp.eq(new BN(78437566))); assert( marketAfter2.amm.baseAssetAmountWithUnsettledLp.eq(new BN(-2500000)) ); assert(marketAfter2.amm.baseAssetAmountWithAmm.eq(new BN(2500000))); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const perpPos2 = driftClientUser.getPerpPosition(marketIndex); console.log(perpPos2.baseAssetAmount.toString()); assert(perpPos2.baseAssetAmount.toString() == '-5000000'); const [settledPos2, dustPos2, lpPnl2] = driftClientUser.getPerpPositionWithLPSettle( marketIndex, undefined, false, true ); // console.log('settlePos:', settledPos2); console.log('dustPos:', dustPos2.toString()); console.log('lpPnl:', lpPnl2.toString()); assert(dustPos2.toString() == '0'); assert(lpPnl2.toString() == '3067086'); await driftClient.settleLP( await driftClient.getUserAccountPublicKey(), marketIndex ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const perpPosAfter2 = driftClientUser.getPerpPosition(marketIndex); console.log( 'perpPosAfter2.baseAssetAmount:', perpPosAfter2.baseAssetAmount.toString() ); assert(perpPosAfter2.baseAssetAmount.toString() == '-2500000'); assert(perpPosAfter2.baseAssetAmount.eq(settledPos2.baseAssetAmount)); const orderRecords2 = eventSubscriber.getEventsArray('OrderActionRecord'); console.log('len of orderRecords', orderRecords2.length); // assert(orderRecords.length - lastOrderRecordsLength == 7); lastOrderRecordsLength = orderRecords2.length; // const fs = require('fs'); // // Custom replacer function to convert BN values to numerical representation // const replacer = (key, value) => { // if (value instanceof BN) { // return value.toString(10); // Convert BN to base-10 string // } // return value; // }; // const jsonOrderRecords2 = JSON.stringify(orderRecords2, replacer); // // Write the JSON string to a file // fs.writeFile('orderRecords.json', jsonOrderRecords2, 'utf8', (err) => { // if (err) { // console.error('Error writing to JSON file:', err); // return; // } // console.log('orderRecords successfully written to orderRecords.json'); // }); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/roundInFavorBaseAsset.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { BASE_PRECISION, BN, getMarketOrderParams, OracleSource, Wallet, MarketStatus, TestClient, PositionDirection, } from '../sdk/src'; import { Program } from '@coral-xyz/anchor'; import { Keypair } from '@solana/web3.js'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } from './testHelpers'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('round in favor', () => { const chProgram = anchor.workspace.Drift as Program; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let primaryDriftClient: TestClient; // ammInvariant == k == x * y const ammInitialQuoteAssetReserve = new anchor.BN( 17 * BASE_PRECISION.toNumber() ); const ammInitialBaseAssetReserve = new anchor.BN( 17 * BASE_PRECISION.toNumber() ); const usdcAmount = new BN(9999 * 10 ** 3); let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); const solUsd = await mockOracleNoProgram(bankrunContextWrapper, 63000); marketIndexes = [0]; spotMarketIndexes = [0]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; primaryDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await primaryDriftClient.initialize(usdcMint.publicKey, true); await primaryDriftClient.subscribe(); await initializeQuoteSpotMarket(primaryDriftClient, usdcMint.publicKey); await primaryDriftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(60 * 60); // 1 HOUR await primaryDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(63000000000) ); await primaryDriftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); }); after(async () => { await primaryDriftClient.unsubscribe(); }); it('short', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); await driftClient.fetchAccounts(); const marketIndex = 0; const baseAssetAmount = new BN(789640); const orderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, }); await driftClient.placeAndTakePerpOrder(orderParams); assert(driftClient.getQuoteAssetTokenAmount().eq(new BN(9999000))); await driftClient.fetchAccounts(); await driftClient.closePosition(marketIndex); await driftClient.fetchAccounts(); console.log( driftClient.getUserAccount().perpPositions[0].quoteAssetAmount.toString() ); assert( driftClient .getUserAccount() .perpPositions[0].quoteAssetAmount.eq(new BN(-88262)) ); await driftClient.unsubscribe(); }); it('long', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); await driftClient.fetchAccounts(); const marketIndex = 0; const baseAssetAmount = new BN(789566); const orderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, }); await driftClient.placeAndTakePerpOrder(orderParams); assert(driftClient.getQuoteAssetTokenAmount().eq(new BN(9999000))); await driftClient.closePosition(marketIndex); await driftClient.fetchAccounts(); console.log( driftClient.getUserAccount().perpPositions[0].quoteAssetAmount.toString() ); assert( driftClient .getUserAccount() .perpPositions[0].quoteAssetAmount.eq(new BN(-88268)) ); await driftClient.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/liquidityProvider.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import * as web3 from '@solana/web3.js'; import { TestClient, QUOTE_PRECISION, AMM_RESERVE_PRECISION, EventSubscriber, PRICE_PRECISION, PositionDirection, ZERO, BN, calculateAmmReservesAfterSwap, calculatePrice, User, OracleSource, SwapDirection, Wallet, isVariant, LPRecord, BASE_PRECISION, getLimitOrderParams, OracleGuardRails, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, sleep, } from './testHelpers'; import { PerpPosition } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; async function adjustOraclePostSwap(baa, swapDirection, market, context) { const price = calculatePrice( market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier ); const [newQaa, newBaa] = calculateAmmReservesAfterSwap( market.amm, 'base', baa.abs(), swapDirection ); const newPrice = calculatePrice(newBaa, newQaa, market.amm.pegMultiplier); const _newPrice = newPrice.toNumber() / PRICE_PRECISION.toNumber(); await setFeedPriceNoProgram(context, _newPrice, market.amm.oracle); console.log('price => new price', price.toString(), newPrice.toString()); return _newPrice; } async function createNewUser( program, provider, usdcMint, usdcAmount, oracleInfos, wallet, bulkAccountLoader ): Promise<[TestClient, User]> { let walletFlag = true; if (wallet == undefined) { const kp = new web3.Keypair(); await provider.fundKeypair(kp, 10 ** 9); wallet = new Wallet(kp); walletFlag = false; } console.log('wallet:', walletFlag); const usdcAta = await mockUserUSDCAccount( usdcMint, usdcAmount, provider, wallet.publicKey ); const driftClient = new TestClient({ connection: provider.connection, wallet: wallet, programID: program.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0, 1], spotMarketIndexes: [0], subAccountIds: [], oracleInfos, accountSubscription: bulkAccountLoader ? { type: 'polling', accountLoader: bulkAccountLoader, } : { type: 'websocket', }, }); if (walletFlag) { await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); } else { await driftClient.subscribe(); } await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, usdcAta.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); driftClientUser.subscribe(); return [driftClient, driftClientUser]; } async function fullClosePosition(driftClient, userPosition) { console.log('=> closing:', userPosition.baseAssetAmount.toString()); let position = (await driftClient.getUserAccount()).perpPositions[0]; let sig; let flag = true; while (flag) { sig = await driftClient.closePosition(0); await driftClient.fetchAccounts(); position = (await driftClient.getUserAccount()).perpPositions[0]; if (position.baseAssetAmount.eq(ZERO)) { flag = false; } } return sig; } describe('liquidity providing', () => { const chProgram = anchor.workspace.Drift as Program; let bankrunContextWrapper: BankrunContextWrapper; let bulkAccountLoader: TestBulkAccountLoader; async function _viewLogs(txsig) { const tx = await bankrunContextWrapper.connection.getTransaction(txsig, { commitment: 'confirmed', }); console.log('tx logs', tx.meta.logMessages); } async function delay(time) { await new Promise((resolve) => setTimeout(resolve, time)); } // ammInvariant == k == x * y const ammInitialBaseAssetReserve = new BN(300).mul(BASE_PRECISION); const ammInitialQuoteAssetReserve = new BN(300).mul(BASE_PRECISION); const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const stableAmmInitialQuoteAssetReserve = BASE_PRECISION.mul(mantissaSqrtScale); const stableAmmInitialBaseAssetReserve = BASE_PRECISION.mul(mantissaSqrtScale); const usdcAmount = new BN(1_000_000_000 * 1e6); let driftClient: TestClient; let eventSubscriber: EventSubscriber; let usdcMint: web3.Keypair; let driftClientUser: User; let traderDriftClient: TestClient; let traderDriftClientUser: User; let poorDriftClient: TestClient; let poorDriftClientUser: User; let solusdc; let solusdc2; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection, chProgram ); await eventSubscriber.subscribe(); solusdc2 = await mockOracleNoProgram(bankrunContextWrapper, 1, -7); // make invalid solusdc = await mockOracleNoProgram(bankrunContextWrapper, 1, -7); // make invalid const oracleInfos = [ { publicKey: solusdc, source: OracleSource.PYTH }, { publicKey: solusdc2, source: OracleSource.PYTH }, ]; [driftClient, driftClientUser] = await createNewUser( chProgram, bankrunContextWrapper, usdcMint, usdcAmount, oracleInfos, bankrunContextWrapper.provider.wallet, bulkAccountLoader ); // used for trading / taking on baa await driftClient.initializePerpMarket( 0, solusdc, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, new BN(60 * 60) ); await driftClient.updateLpCooldownTime(new BN(0)); await driftClient.updatePerpMarketMaxFillReserveFraction(0, 1); const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: new BN(1000000), oracleTwap5MinPercentDivergence: new BN(1000000), }, validity: { slotsBeforeStaleForAmm: new BN(10), slotsBeforeStaleForMargin: new BN(10), confidenceIntervalMaxSize: new BN(100), tooVolatileRatio: new BN(100), }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); // await driftClient.updateMarketBaseAssetAmountStepSize( // new BN(0), // new BN(1) // ); // second market -- used for funding .. await driftClient.initializePerpMarket( 1, solusdc2, stableAmmInitialBaseAssetReserve, stableAmmInitialQuoteAssetReserve, new BN(0) ); await driftClient.updateLpCooldownTime(new BN(0)); await driftClient.updatePerpAuctionDuration(new BN(0)); [traderDriftClient, traderDriftClientUser] = await createNewUser( chProgram, bankrunContextWrapper, usdcMint, usdcAmount, oracleInfos, undefined, bulkAccountLoader ); [poorDriftClient, poorDriftClientUser] = await createNewUser( chProgram, bankrunContextWrapper, usdcMint, QUOTE_PRECISION, oracleInfos, undefined, bulkAccountLoader ); }); after(async () => { await eventSubscriber.unsubscribe(); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); await traderDriftClient.unsubscribe(); await traderDriftClientUser.unsubscribe(); await poorDriftClient.unsubscribe(); await poorDriftClientUser.unsubscribe(); }); const lpCooldown = 1; it('burn with standardized baa', async () => { console.log('adding liquidity...'); const initMarginReq = driftClientUser.getInitialMarginRequirement(); assert(initMarginReq.eq(ZERO)); let market = driftClient.getPerpMarketAccount(0); const lpAmount = new BN(100 * BASE_PRECISION.toNumber()); // 100 / (100 + 300) = 1/4 const _sig = await driftClient.addPerpLpShares( lpAmount, market.marketIndex ); await driftClient.fetchAccounts(); const addLiquidityRecord: LPRecord = eventSubscriber.getEventsArray('LPRecord')[0]; assert(isVariant(addLiquidityRecord.action, 'addLiquidity')); assert(addLiquidityRecord.nShares.eq(lpAmount)); assert(addLiquidityRecord.marketIndex === 0); assert( addLiquidityRecord.user.equals( await driftClient.getUserAccountPublicKey() ) ); const [bids, asks] = driftClientUser.getLPBidAsks(0); console.log( 'bar, min_bar, max_bar:', market.amm.baseAssetReserve.toString(), market.amm.minBaseAssetReserve.toString(), market.amm.maxBaseAssetReserve.toString() ); console.log('LP open bids/asks:', bids.toString(), asks.toString()); assert(bids.eq(new BN(41419999989))); assert(asks.eq(new BN(-29288643749))); await driftClient.placePerpOrder( getLimitOrderParams({ baseAssetAmount: BASE_PRECISION, marketIndex: 0, direction: PositionDirection.LONG, // ++ bids price: PRICE_PRECISION, }) ); await driftClient.placePerpOrder( getLimitOrderParams({ baseAssetAmount: BASE_PRECISION, marketIndex: 0, direction: PositionDirection.SHORT, // ++ asks price: PRICE_PRECISION.mul(new BN(100)), }) ); await driftClient.fetchAccounts(); const [bids2, asks2] = driftClientUser.getPerpBidAsks(0); assert(bids2.eq(bids.add(BASE_PRECISION))); assert(asks2.eq(asks.sub(BASE_PRECISION))); await driftClient.cancelOrders(); await driftClient.fetchAccounts(); const position3 = driftClientUser.getPerpPosition(0); assert(position3.openOrders == 0); assert(position3.openAsks.eq(ZERO)); assert(position3.openBids.eq(ZERO)); const newInitMarginReq = driftClientUser.getInitialMarginRequirement(); console.log(initMarginReq.toString(), '->', newInitMarginReq.toString()); assert(newInitMarginReq.eq(new BN(9284008))); // 8284008 + $1 // ensure margin calcs didnt modify user position const _position = driftClientUser.getPerpPosition(0); assert(_position.openAsks.eq(ZERO)); assert(_position.openBids.eq(ZERO)); const stepSize = new BN(1 * BASE_PRECISION.toNumber()); await driftClient.updatePerpMarketStepSizeAndTickSize( 0, stepSize, driftClient.getPerpMarketAccount(0).amm.orderTickSize ); let user = await driftClientUser.getUserAccount(); console.log('lpUser lpShares:', user.perpPositions[0].lpShares.toString()); console.log( 'lpUser baa:', user.perpPositions[0].baseAssetAmount.toString() ); assert(user.perpPositions[0].lpShares.eq(new BN('100000000000'))); assert(user.perpPositions[0].baseAssetAmount.eq(ZERO)); // some user goes long (lp should get a short) console.log('user trading...'); market = driftClient.getPerpMarketAccount(0); assert(market.amm.sqrtK.eq(new BN('400000000000'))); const tradeSize = new BN(5 * BASE_PRECISION.toNumber()); const [newQaa, _newBaa] = calculateAmmReservesAfterSwap( market.amm, 'base', tradeSize.abs(), SwapDirection.ADD ); const quoteAmount = newQaa.sub(market.amm.quoteAssetReserve); const lpQuoteAmount = quoteAmount.mul(lpAmount).div(market.amm.sqrtK); console.log( lpQuoteAmount.mul(QUOTE_PRECISION).div(AMM_RESERVE_PRECISION).toString() ); const newPrice = await adjustOraclePostSwap( tradeSize, SwapDirection.ADD, market, bankrunContextWrapper ); const sig = await traderDriftClient.openPosition( PositionDirection.SHORT, tradeSize, market.marketIndex, new BN((newPrice * PRICE_PRECISION.toNumber() * 99) / 100) ); await _viewLogs(sig); // amm gets 33 (3/4 * 50 = 37.5) // lp gets stepSize (1/4 * 50 = 12.5 => 10 with remainder 2.5) // 2.5 / 12.5 = 0.2 await traderDriftClient.fetchAccounts(); const traderUserAccount = await traderDriftClient.getUserAccount(); const position = traderUserAccount.perpPositions[0]; console.log( 'trader position:', position.baseAssetAmount.toString(), position.quoteAssetAmount.toString() ); assert(position.baseAssetAmount.eq(new BN('-5000000000'))); await driftClient.fetchAccounts(); const marketNetBaa = driftClient.getPerpMarketAccount(0).amm.baseAssetAmountWithAmm; console.log('removing liquidity...'); const _txSig = await driftClient.settleLP( await driftClient.getUserAccountPublicKey(), market.marketIndex ); await _viewLogs(_txSig); const settleLiquidityRecord: LPRecord = eventSubscriber.getEventsArray('LPRecord')[0]; assert(isVariant(settleLiquidityRecord.action, 'settleLiquidity')); assert(settleLiquidityRecord.marketIndex === 0); assert( settleLiquidityRecord.user.equals( await driftClient.getUserAccountPublicKey() ) ); // net baa doesnt change on settle await driftClient.fetchAccounts(); assert( driftClient .getPerpMarketAccount(0) .amm.baseAssetAmountWithAmm.eq(marketNetBaa) ); const marketAfter = driftClient.getPerpMarketAccount(0); assert( marketAfter.amm.baseAssetAmountWithUnsettledLp.eq(new BN('-250000000')) ); assert(marketAfter.amm.baseAssetAmountWithAmm.eq(new BN('-3750000000'))); user = await driftClientUser.getUserAccount(); const lpPosition = user.perpPositions[0]; assert( settleLiquidityRecord.deltaBaseAssetAmount.eq(lpPosition.baseAssetAmount) ); assert( settleLiquidityRecord.deltaQuoteAssetAmount.eq( lpPosition.quoteAssetAmount ) ); console.log( 'lp tokens, baa, qaa:', lpPosition.lpShares.toString(), lpPosition.baseAssetAmount.toString(), lpPosition.quoteAssetAmount.toString(), // lpPosition.unsettledPnl.toString(), lpPosition.lastBaseAssetAmountPerLp.toString(), lpPosition.lastQuoteAssetAmountPerLp.toString() ); // assert(lpPosition.lpShares.eq(new BN(0))); await driftClient.fetchAccounts(); assert(user.perpPositions[0].baseAssetAmount.eq(new BN(1000000000))); // lp is long console.log( '=> net baa:', driftClient.getPerpMarketAccount(0).amm.baseAssetAmountWithAmm.toString() ); assert(user.perpPositions[0].quoteAssetAmount.eq(new BN(-1233700))); // assert(user.perpPositions[0].unsettledPnl.eq(new BN(900))); // remainder goes into the last assert(user.perpPositions[0].lastBaseAssetAmountPerLp.eq(new BN(12500000))); assert(user.perpPositions[0].lastQuoteAssetAmountPerLp.eq(new BN(-12337))); market = await driftClient.getPerpMarketAccount(0); console.log( market.amm.quoteAssetAmountPerLp.toString(), market.amm.baseAssetAmountPerLp.toString() ); assert(market.amm.baseAssetAmountPerLp.eq(new BN(12500000))); assert(market.amm.quoteAssetAmountPerLp.eq(new BN(-12337))); console.log(user.perpPositions[0].remainderBaseAssetAmount.toString()); // lp remainder assert(user.perpPositions[0].remainderBaseAssetAmount != 0); // lp remainder assert(user.perpPositions[0].remainderBaseAssetAmount == 250000000); // lp remainder // remove console.log('removing liquidity...'); await driftClient.removePerpLpShares(0); await driftClient.fetchAccounts(); const removeLiquidityRecord: LPRecord = eventSubscriber.getEventsArray('LPRecord')[0]; assert(isVariant(removeLiquidityRecord.action, 'removeLiquidity')); assert(removeLiquidityRecord.nShares.eq(lpAmount)); assert(removeLiquidityRecord.marketIndex === 0); assert( removeLiquidityRecord.user.equals( await driftClient.getUserAccountPublicKey() ) ); console.log( 'removeLiquidityRecord.deltaQuoteAssetAmount', removeLiquidityRecord.deltaQuoteAssetAmount.toString() ); assert(removeLiquidityRecord.deltaBaseAssetAmount.eq(ZERO)); assert(removeLiquidityRecord.deltaQuoteAssetAmount.eq(new BN('-243866'))); // show pnl from burn in record console.log('closing trader ...'); await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); await fullClosePosition( traderDriftClient, traderDriftClient.getUserAccount().perpPositions[0] ); const traderUserAccount2 = traderDriftClient.getUserAccount().perpPositions[0]; console.log( traderUserAccount2.lpShares.toString(), traderUserAccount2.baseAssetAmount.toString(), traderUserAccount2.quoteAssetAmount.toString() ); console.log('closing lp ...'); console.log( user.perpPositions[0].baseAssetAmount .div(new BN(BASE_PRECISION.toNumber())) .toString() ); await adjustOraclePostSwap( user.perpPositions[0].baseAssetAmount, SwapDirection.ADD, market, bankrunContextWrapper ); const _ttxsig = await fullClosePosition(driftClient, user.perpPositions[0]); // await _viewLogs(ttxsig); await driftClient.updatePerpMarketStepSizeAndTickSize( 0, new BN(1), market.amm.orderTickSize ); const user2 = await driftClientUser.getUserAccount(); const position2 = user2.perpPositions[0]; console.log( position2.lpShares.toString(), position2.baseAssetAmount.toString(), position2.quoteAssetAmount.toString() ); await driftClient.fetchAccounts(); console.log( '=> net baa:', driftClient.getPerpMarketAccount(0).amm.baseAssetAmountWithAmm.toString() ); assert( driftClient.getPerpMarketAccount(0).amm.baseAssetAmountWithAmm.eq(ZERO) ); console.log('done!'); }); it('settles lp', async () => { console.log('adding liquidity...'); const market = driftClient.getPerpMarketAccount(0); const _sig = await driftClient.addPerpLpShares( new BN(100 * BASE_PRECISION.toNumber()), market.marketIndex ); await delay(lpCooldown + 1000); let user = await driftClientUser.getUserAccount(); console.log(user.perpPositions[0].lpShares.toString()); // some user goes long (lp should get a short) console.log('user trading...'); const tradeSize = new BN(5 * BASE_PRECISION.toNumber()); try { await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await traderDriftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex // new BN(100 * BASE_PRECISION.toNumber()) ); await _viewLogs(_txsig); } catch (e) { console.log(e); } const trader = await traderDriftClient.getUserAccount(); console.log( 'trader size', trader.perpPositions[0].baseAssetAmount.toString() ); const [settledLPPosition, _, sdkPnl] = driftClientUser.getPerpPositionWithLPSettle(0); console.log('settling...'); try { const _txsigg = await driftClient.settleLP( await driftClient.getUserAccountPublicKey(), 0 ); await _viewLogs(_txsigg); } catch (e) { console.log(e); } user = await await driftClientUser.getUserAccount(); const position = user.perpPositions[0]; const settleLiquidityRecord: LPRecord = eventSubscriber.getEventsArray('LPRecord')[0]; console.log( 'settle pnl vs sdk', settleLiquidityRecord.pnl.toString(), sdkPnl.toString() ); console.log( 'deltaBaseAssetAmount:', settleLiquidityRecord.deltaBaseAssetAmount.toString() ); console.log( 'deltaQuoteAssetAmount:', settleLiquidityRecord.deltaQuoteAssetAmount.toString() ); assert(settleLiquidityRecord.pnl.toString() === sdkPnl.toString()); // gets a short on settle console.log( 'simulated settle position:', settledLPPosition.baseAssetAmount.toString(), settledLPPosition.quoteAssetAmount.toString(), settledLPPosition.quoteEntryAmount.toString() ); // gets a short on settle console.log( position.baseAssetAmount.toString(), position.quoteAssetAmount.toString(), position.quoteEntryAmount.toString(), position.remainderBaseAssetAmount.toString() ); assert(settledLPPosition.baseAssetAmount.eq(position.baseAssetAmount)); assert(settledLPPosition.quoteAssetAmount.eq(position.quoteAssetAmount)); assert(settledLPPosition.quoteEntryAmount.eq(position.quoteEntryAmount)); assert( settledLPPosition.remainderBaseAssetAmount === position.remainderBaseAssetAmount ); console.log( position.baseAssetAmount.toString(), position.quoteAssetAmount.toString() ); assert(position.baseAssetAmount.lt(ZERO)); assert(position.quoteAssetAmount.gt(ZERO)); assert(position.lpShares.gt(ZERO)); console.log('removing liquidity...'); const _txSig = await driftClient.removePerpLpShares(market.marketIndex); await _viewLogs(_txSig); user = await driftClientUser.getUserAccount(); const lpPosition = user.perpPositions[0]; const lpTokenAmount = lpPosition.lpShares; assert(lpTokenAmount.eq(ZERO)); console.log( 'lp position:', lpPosition.baseAssetAmount.toString(), lpPosition.quoteAssetAmount.toString() ); console.log('closing trader ...'); await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await fullClosePosition( traderDriftClient, trader.perpPositions[0] ); await _viewLogs(_txsig); const traderPosition = (await traderDriftClient.getUserAccount()) .perpPositions[0]; console.log( 'trader position:', traderPosition.baseAssetAmount.toString(), traderPosition.quoteAssetAmount.toString() ); console.log('closing lp ...'); const market2 = driftClient.getPerpMarketAccount(0); await adjustOraclePostSwap( user.perpPositions[0].baseAssetAmount, SwapDirection.ADD, market2, bankrunContextWrapper ); await fullClosePosition(driftClient, user.perpPositions[0]); await driftClient.fetchAccounts(); console.log( '=> net baa:', driftClient.getPerpMarketAccount(0).amm.baseAssetAmountWithAmm.toString() ); assert( driftClient.getPerpMarketAccount(0).amm.baseAssetAmountWithAmm.eq(ZERO) ); console.log('done!'); }); it('provides and removes liquidity', async () => { let market = driftClient.getPerpMarketAccount(0); const prevSqrtK = market.amm.sqrtK; const prevbar = market.amm.baseAssetReserve; const prevqar = market.amm.quoteAssetReserve; const prevQaa = driftClient.getUserAccount().perpPositions[0].quoteAssetAmount; console.log('adding liquidity...'); try { const _txsig = await driftClient.addPerpLpShares( new BN(100 * AMM_RESERVE_PRECISION.toNumber()), market.marketIndex ); } catch (e) { console.error(e); } await delay(lpCooldown + 1000); market = driftClient.getPerpMarketAccount(0); console.log( 'sqrtK:', prevSqrtK.toString(), '->', market.amm.sqrtK.toString() ); console.log( 'baseAssetReserve:', prevbar.toString(), '->', market.amm.baseAssetReserve.toString() ); console.log( 'quoteAssetReserve:', prevqar.toString(), '->', market.amm.quoteAssetReserve.toString() ); // k increases = more liquidity assert(prevSqrtK.lt(market.amm.sqrtK)); assert(prevqar.lt(market.amm.quoteAssetReserve)); assert(prevbar.lt(market.amm.baseAssetReserve)); const lpShares = (await driftClientUser.getUserAccount()).perpPositions[0] .lpShares; console.log('lpShares:', lpShares.toString()); assert(lpShares.gt(ZERO)); console.log('removing liquidity...'); const _txSig = await driftClient.removePerpLpShares(market.marketIndex); await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(0); const user = await driftClientUser.getUserAccount(); const lpTokenAmount = user.perpPositions[0].lpShares; console.log('lp token amount:', lpTokenAmount.toString()); assert(lpTokenAmount.eq(ZERO)); // dont round down for no change assert(user.perpPositions[0].quoteAssetAmount.eq(prevQaa)); console.log('asset reserves:'); console.log(prevSqrtK.toString(), market.amm.sqrtK.toString()); console.log(prevbar.toString(), market.amm.baseAssetReserve.toString()); console.log(prevqar.toString(), market.amm.quoteAssetReserve.toString()); const errThreshold = new BN(500); assert(prevSqrtK.eq(market.amm.sqrtK)); assert( prevbar.sub(market.amm.baseAssetReserve).abs().lte(errThreshold), prevbar.sub(market.amm.baseAssetReserve).abs().toString() ); assert( prevqar.sub(market.amm.quoteAssetReserve).abs().lte(errThreshold), prevqar.sub(market.amm.quoteAssetReserve).abs().toString() ); assert(prevSqrtK.eq(market.amm.sqrtK)); }); it('mints too many lp tokens', async () => { console.log('adding liquidity...'); const market = driftClient.getPerpMarketAccount(0); try { const _sig = await poorDriftClient.addPerpLpShares( market.amm.sqrtK.mul(new BN(5)), market.marketIndex ); _viewLogs(_sig); assert(false); } catch (e) { console.error(e.message); assert(e.message.includes('0x1773')); // insufficient collateral } }); it('provides lp, users shorts, removes lp, lp has long', async () => { await driftClient.fetchAccounts(); await traderDriftClient.fetchAccounts(); console.log('adding liquidity...'); const traderUserAccount3 = await driftClient.getUserAccount(); const position3 = traderUserAccount3.perpPositions[0]; console.log( 'lp position:', position3.baseAssetAmount.toString(), position3.quoteAssetAmount.toString() ); const traderUserAccount0 = await traderDriftClient.getUserAccount(); const position0 = traderUserAccount0.perpPositions[0]; console.log( 'trader position:', position0.baseAssetAmount.toString(), position0.quoteAssetAmount.toString() ); assert(position0.baseAssetAmount.eq(new BN('0'))); const market = driftClient.getPerpMarketAccount(0); console.log( 'market.amm.netBaseAssetAmount:', market.amm.baseAssetAmountWithAmm.toString() ); assert(market.amm.baseAssetAmountWithAmm.eq(new BN('0'))); const _sig = await driftClient.addPerpLpShares( new BN(100 * BASE_PRECISION.toNumber()), market.marketIndex ); // await delay(lpCooldown + 1000); let user = await driftClientUser.getUserAccount(); console.log('lpUser lpShares:', user.perpPositions[0].lpShares.toString()); console.log( 'lpUser baa:', user.perpPositions[0].baseAssetAmount.toString() ); // some user goes long (lp should get a short) console.log('user trading...'); const tradeSize = new BN(40 * BASE_PRECISION.toNumber()); const _newPrice = await adjustOraclePostSwap( tradeSize, SwapDirection.ADD, market, bankrunContextWrapper ); try { const _txsig = await traderDriftClient.openPosition( PositionDirection.SHORT, tradeSize, market.marketIndex // new BN(newPrice * PRICE_PRECISION.toNumber()) ); } catch (e) { console.error(e); } await traderDriftClient.fetchAccounts(); const market1 = driftClient.getPerpMarketAccount(0); console.log( 'market1.amm.netBaseAssetAmount:', market1.amm.baseAssetAmountWithAmm.toString() ); const ammLpRatio = market1.amm.userLpShares.toNumber() / market1.amm.sqrtK.toNumber(); console.log('amm ratio:', ammLpRatio, '(', 40 * ammLpRatio, ')'); assert(market1.amm.baseAssetAmountWithAmm.eq(new BN('-30000000000'))); const traderUserAccount = await traderDriftClient.getUserAccount(); // console.log(traderUserAccount); const position = traderUserAccount.perpPositions[0]; console.log( 'trader position:', position.baseAssetAmount.toString(), position.quoteAssetAmount.toString() ); console.log('removing liquidity...'); const _txSig = await driftClient.removePerpLpShares(market.marketIndex); await _viewLogs(_txSig); user = await driftClientUser.getUserAccount(); const lpPosition = user.perpPositions[0]; const lpTokenAmount = lpPosition.lpShares; console.log( 'lp tokens', lpTokenAmount.toString(), 'baa, qaa', lpPosition.baseAssetAmount.toString(), lpPosition.quoteAssetAmount.toString() // lpPosition.unsettledPnl.toString() ); const removeLiquidityRecord: LPRecord = eventSubscriber.getEventsArray('LPRecord')[0]; assert(isVariant(removeLiquidityRecord.action, 'removeLiquidity')); assert( removeLiquidityRecord.deltaBaseAssetAmount.eq( lpPosition.baseAssetAmount.sub(position3.baseAssetAmount) ) ); assert( removeLiquidityRecord.deltaQuoteAssetAmount.eq( lpPosition.quoteAssetAmount.sub(position3.quoteAssetAmount) ) ); assert(lpTokenAmount.eq(new BN(0))); console.log(user.perpPositions[0].baseAssetAmount.toString()); console.log(user.perpPositions[0].quoteAssetAmount.toString()); assert(user.perpPositions[0].baseAssetAmount.eq(new BN('10000000000'))); // lp is long assert(user.perpPositions[0].quoteAssetAmount.eq(new BN(-9550985))); console.log('closing trader ...'); await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); await fullClosePosition( traderDriftClient, traderUserAccount.perpPositions[0] ); console.log('closing lp ...'); console.log( user.perpPositions[0].baseAssetAmount .div(new BN(BASE_PRECISION.toNumber())) .toString() ); await adjustOraclePostSwap( user.perpPositions[0].baseAssetAmount, SwapDirection.ADD, market, bankrunContextWrapper ); await fullClosePosition(driftClient, user.perpPositions[0]); const user2 = await driftClientUser.getUserAccount(); const position2 = user2.perpPositions[0]; console.log( position2.lpShares.toString(), position2.baseAssetAmount.toString(), position2.quoteAssetAmount.toString() ); console.log('done!'); }); it('provides lp, users longs, removes lp, lp has short', async () => { const market = driftClient.getPerpMarketAccount(0); console.log('adding liquidity...'); const _sig = await driftClient.addPerpLpShares( new BN(100 * BASE_PRECISION.toNumber()), market.marketIndex ); // await delay(lpCooldown + 1000); // some user goes long (lp should get a short) console.log('user trading...'); const tradeSize = new BN(40 * BASE_PRECISION.toNumber()); const _newPrice0 = await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await traderDriftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex // new BN(newPrice0 * PRICE_PRECISION.toNumber()) ); const position = (await traderDriftClient.getUserAccount()) .perpPositions[0]; console.log( 'trader position:', position.baseAssetAmount.toString(), position.quoteAssetAmount.toString() ); console.log('removing liquidity...'); const _txSig = await driftClient.removePerpLpShares(market.marketIndex); await _viewLogs(_txSig); await driftClientUser.fetchAccounts(); const user = await driftClientUser.getUserAccount(); const lpPosition = user.perpPositions[0]; const lpTokenAmount = lpPosition.lpShares; console.log('lp tokens', lpTokenAmount.toString()); console.log( 'baa, qaa, qea', lpPosition.baseAssetAmount.toString(), lpPosition.quoteAssetAmount.toString(), lpPosition.quoteEntryAmount.toString() // lpPosition.unsettledPnl.toString() ); assert(lpTokenAmount.eq(ZERO)); assert(user.perpPositions[0].baseAssetAmount.eq(new BN('-10000000000'))); // lp is short assert(user.perpPositions[0].quoteAssetAmount.eq(new BN('11940540'))); assert(user.perpPositions[0].quoteEntryAmount.eq(new BN('11139500'))); console.log('closing trader...'); await adjustOraclePostSwap( tradeSize, SwapDirection.ADD, market, bankrunContextWrapper ); await fullClosePosition(traderDriftClient, position); console.log('closing lp ...'); await adjustOraclePostSwap( user.perpPositions[0].baseAssetAmount, SwapDirection.REMOVE, market, bankrunContextWrapper ); await fullClosePosition(driftClient, lpPosition); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const user2 = await driftClientUser.getUserAccount(); const lpPosition2 = user2.perpPositions[0]; console.log('lp tokens', lpPosition2.lpShares.toString()); console.log( 'lp position for market', lpPosition2.marketIndex, ':\n', 'baa, qaa, qea', lpPosition2.baseAssetAmount.toString(), lpPosition2.quoteAssetAmount.toString(), lpPosition2.quoteEntryAmount.toString() ); assert(lpPosition2.baseAssetAmount.eq(ZERO)); console.log('done!'); }); it('lp burns a partial position', async () => { const market = driftClient.getPerpMarketAccount(0); console.log('adding liquidity...'); await driftClient.addPerpLpShares( new BN(100).mul(AMM_RESERVE_PRECISION), market.marketIndex ); // await delay(lpCooldown + 1000); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const user0 = await driftClient.getUserAccount(); const position0 = user0.perpPositions[0]; console.log( 'assert LP has 0 position in market index', market.marketIndex, ':', position0.baseAssetAmount.toString(), position0.quoteAssetAmount.toString() ); console.log(position0.lpShares.toString()); const baa0 = position0.baseAssetAmount; assert(baa0.eq(ZERO)); console.log('user trading...'); const tradeSize = new BN(40 * BASE_PRECISION.toNumber()); const _newPrice = await adjustOraclePostSwap( tradeSize, SwapDirection.ADD, market, bankrunContextWrapper ); await traderDriftClient.openPosition( PositionDirection.SHORT, tradeSize, market.marketIndex // new BN(newPrice * PRICE_PRECISION.toNumber()) ); console.log('removing liquidity...'); let user = await driftClient.getUserAccount(); let position = user.perpPositions[0]; const fullShares = position.lpShares; const halfShares = position.lpShares.div(new BN(2)); const otherHalfShares = fullShares.sub(halfShares); try { const _txSig = await driftClient.removePerpLpShares( market.marketIndex, halfShares ); } catch (e) { console.log(e); } await driftClient.fetchAccounts(); user = await driftClient.getUserAccount(); position = user.perpPositions[0]; console.log( 'lp first half burn:', user.perpPositions[0].baseAssetAmount.toString(), user.perpPositions[0].quoteAssetAmount.toString(), user.perpPositions[0].lpShares.toString() ); const baa = user.perpPositions[0].baseAssetAmount; const qaa = user.perpPositions[0].quoteAssetAmount; assert(baa.eq(new BN(10000000000))); assert(qaa.eq(new BN(-6860662))); console.log('removing the other half of liquidity'); await driftClient.removePerpLpShares(market.marketIndex, otherHalfShares); await driftClient.fetchAccounts(); user = await driftClient.getUserAccount(); console.log( 'lp second half burn:', user.perpPositions[0].baseAssetAmount.toString(), user.perpPositions[0].quoteAssetAmount.toString(), user.perpPositions[0].lpShares.toString() ); // lp is already settled so full burn baa is already in baa assert(user.perpPositions[0].lpShares.eq(ZERO)); console.log('closing trader ...'); await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); // await traderDriftClient.closePosition(new BN(0)); const trader = await traderDriftClient.getUserAccount(); const _txsig = await fullClosePosition( traderDriftClient, trader.perpPositions[0] ); console.log('closing lp ...'); await adjustOraclePostSwap( baa, SwapDirection.ADD, market, bankrunContextWrapper ); await fullClosePosition(driftClient, user.perpPositions[0]); }); it('settles lp with pnl', async () => { console.log('adding liquidity...'); const market = driftClient.getPerpMarketAccount(0); const _sig = await driftClient.addPerpLpShares( new BN(100 * BASE_PRECISION.toNumber()), market.marketIndex ); await delay(lpCooldown + 1000); let user = await driftClientUser.getUserAccount(); console.log(user.perpPositions[0].lpShares.toString()); // lp goes long const tradeSize = new BN(5 * BASE_PRECISION.toNumber()); try { await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await driftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex // new BN(100 * BASE_PRECISION.toNumber()) ); await _viewLogs(_txsig); } catch (e) { console.log(e); } // some user goes long (lp should get a short + pnl for closing long on settle) console.log('user trading...'); try { await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await traderDriftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex // new BN(100 * BASE_PRECISION.toNumber()) ); await _viewLogs(_txsig); } catch (e) { console.log(e); } const trader = await traderDriftClient.getUserAccount(); console.log( 'trader size', trader.perpPositions[0].baseAssetAmount.toString() ); await driftClientUser.fetchAccounts(); const sdkPnl = driftClientUser.getPerpPositionWithLPSettle(0)[2]; console.log('settling...'); try { const _txsigg = await driftClient.settleLP( await driftClient.getUserAccountPublicKey(), 0 ); await _viewLogs(_txsigg); } catch (e) { console.log(e); } user = await await driftClientUser.getUserAccount(); const settleLiquidityRecord: LPRecord = eventSubscriber.getEventsArray('LPRecord')[0]; console.log( 'settle pnl vs sdk', settleLiquidityRecord.pnl.toString(), sdkPnl.toString() ); assert(settleLiquidityRecord.pnl.eq(sdkPnl)); }); it('update per lp base (0->1)', async () => { //ensure non-zero for test await driftClient.updatePerpMarketTargetBaseAssetAmountPerLp(0, 169); await driftClient.fetchAccounts(); const marketBefore = driftClient.getPerpMarketAccount(0); console.log( 'marketBefore.amm.totalFeeEarnedPerLp', marketBefore.amm.totalFeeEarnedPerLp.toString() ); assert(marketBefore.amm.totalFeeEarnedPerLp.eq(new BN('272'))); const txSig1 = await driftClient.updatePerpMarketPerLpBase(0, 1); await _viewLogs(txSig1); await sleep(1400); // todo? await driftClient.fetchAccounts(); const marketAfter = driftClient.getPerpMarketAccount(0); assert( marketAfter.amm.totalFeeEarnedPerLp.eq( marketBefore.amm.totalFeeEarnedPerLp.mul(new BN(10)) ) ); assert( marketAfter.amm.baseAssetAmountPerLp.eq( marketBefore.amm.baseAssetAmountPerLp.mul(new BN(10)) ) ); assert( marketAfter.amm.quoteAssetAmountPerLp.eq( marketBefore.amm.quoteAssetAmountPerLp.mul(new BN(10)) ) ); console.log(marketAfter.amm.targetBaseAssetAmountPerLp); console.log(marketBefore.amm.targetBaseAssetAmountPerLp); assert( marketAfter.amm.targetBaseAssetAmountPerLp == marketBefore.amm.targetBaseAssetAmountPerLp ); assert(marketAfter.amm.totalFeeEarnedPerLp.eq(new BN('2720'))); assert(marketBefore.amm.perLpBase == 0); console.log('marketAfter.amm.perLpBase:', marketAfter.amm.perLpBase); assert(marketAfter.amm.perLpBase == 1); }); it('settle lp position after perLpBase change', async () => { // some user goes long (lp should get a short + pnl for closing long on settle) const market = driftClient.getPerpMarketAccount(0); console.log( 'baseAssetAmountWithUnsettledLp:', market.amm.baseAssetAmountWithUnsettledLp.toString() ); assert(market.amm.baseAssetAmountWithUnsettledLp.eq(ZERO)); // await delay(lpCooldown + 1000); const user = await driftClientUser.getUserAccount(); console.log(user.perpPositions[0].lpShares.toString()); console.log(user.perpPositions[0].perLpBase); const tradeSize = new BN(5 * BASE_PRECISION.toNumber()); console.log('user trading...'); try { await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await traderDriftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex // new BN(100 * BASE_PRECISION.toNumber()) ); await _viewLogs(_txsig); } catch (e) { console.log(e); } const marketAfter0 = driftClient.getPerpMarketAccount(0); console.log( 'baseAssetAmountWithUnsettledLp:', marketAfter0.amm.baseAssetAmountWithUnsettledLp.toString() ); assert( marketAfter0.amm.baseAssetAmountWithUnsettledLp.eq(new BN('1250000000')) ); const netValueBefore = await driftClient.getUser().getNetSpotMarketValue(); const posBefore0: PerpPosition = await driftClient .getUser() .getPerpPosition(0); assert(posBefore0.perLpBase == 0); const posBefore: PerpPosition = await driftClient .getUser() .getPerpPositionWithLPSettle(0)[0]; // console.log(posBefore); assert(posBefore.perLpBase == 1); // properly sets it const _txSig = await driftClient.settleLP( await driftClient.getUserAccountPublicKey(), market.marketIndex ); await _viewLogs(_txSig); await driftClient.fetchAccounts(); const marketAfter1 = driftClient.getPerpMarketAccount(0); console.log( 'baseAssetAmountWithUnsettledLp:', marketAfter1.amm.baseAssetAmountWithUnsettledLp.toString() ); assert(marketAfter1.amm.baseAssetAmountWithUnsettledLp.eq(new BN('0'))); const posAfter0: PerpPosition = await driftClient .getUser() .getPerpPosition(0); assert(posAfter0.perLpBase == 1); const posAfter: PerpPosition = await driftClient .getUser() .getPerpPositionWithLPSettle(0)[0]; assert(posAfter.perLpBase == 1); assert( posAfter0.lastBaseAssetAmountPerLp.gt(posBefore0.lastBaseAssetAmountPerLp) ); // console.log(posAfter.lastBaseAssetAmountPerLp.toString()); // console.log(posBefore.lastBaseAssetAmountPerLp.toString()); assert(posAfter.lastBaseAssetAmountPerLp.eq(new BN('625000000'))); assert(posBefore.lastBaseAssetAmountPerLp.eq(new BN('750000000'))); const netValueAfter = await driftClient.getUser().getNetSpotMarketValue(); assert(netValueBefore.eq(netValueAfter)); const marketAfter2 = driftClient.getPerpMarketAccount(0); console.log( 'baseAssetAmountWithUnsettledLp:', marketAfter2.amm.baseAssetAmountWithUnsettledLp.toString() ); assert(marketAfter2.amm.baseAssetAmountWithUnsettledLp.eq(new BN('0'))); console.log( 'marketBefore.amm.totalFeeEarnedPerLp', marketAfter2.amm.totalFeeEarnedPerLp.toString() ); assert(marketAfter2.amm.totalFeeEarnedPerLp.eq(new BN('2826'))); }); it('add back lp shares from 0, after rebase', async () => { const leShares = driftClientUser.getPerpPosition(0).lpShares; await driftClient.removePerpLpShares(0, leShares); await driftClient.fetchAccounts(); await driftClient.updatePerpMarketPerLpBase(0, 2); // update from 1->2 const posBeforeReadd: PerpPosition = await driftClient .getUser() .getPerpPositionWithLPSettle(0)[0]; console.log(posBeforeReadd.baseAssetAmount.toString()); console.log(posBeforeReadd.quoteAssetAmount.toString()); console.log(posBeforeReadd.lastBaseAssetAmountPerLp.toString()); console.log(posBeforeReadd.lastQuoteAssetAmountPerLp.toString()); console.log( posBeforeReadd.lpShares.toString(), posBeforeReadd.perLpBase.toString() ); await driftClient.addPerpLpShares(leShares, 0); // lmao why is this different param order const posBefore: PerpPosition = await driftClient .getUser() .getPerpPositionWithLPSettle(0)[0]; console.log('posBefore'); console.log(posBefore.baseAssetAmount.toString()); console.log(posBefore.quoteAssetAmount.toString()); console.log(posBefore.lastBaseAssetAmountPerLp.toString()); console.log(posBefore.lastQuoteAssetAmountPerLp.toString()); console.log(posBefore.lpShares.toString(), posBefore.perLpBase.toString()); const tradeSize = new BN(5 * BASE_PRECISION.toNumber()); const market = driftClient.getPerpMarketAccount(0); console.log('user trading...'); try { await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await traderDriftClient.openPosition( PositionDirection.SHORT, tradeSize, market.marketIndex ); await _viewLogs(_txsig); } catch (e) { console.log(e); } await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const posAfter: PerpPosition = await driftClient .getUser() .getPerpPositionWithLPSettle(0)[0]; console.log('posAfter'); console.log(posAfter.baseAssetAmount.toString()); console.log(posAfter.quoteAssetAmount.toString()); console.log(posAfter.lastBaseAssetAmountPerLp.toString()); console.log(posAfter.lastQuoteAssetAmountPerLp.toString()); console.log(posAfter.perLpBase.toString()); const _txSig = await driftClient.settleLP( await driftClient.getUserAccountPublicKey(), market.marketIndex ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const posAfterSettle: PerpPosition = await driftClient .getUser() .getPerpPositionWithLPSettle(0)[0]; console.log('posAfterSettle'); console.log(posAfterSettle.baseAssetAmount.toString()); console.log(posAfterSettle.quoteAssetAmount.toString()); console.log(posAfterSettle.lastBaseAssetAmountPerLp.toString()); console.log(posAfterSettle.lastQuoteAssetAmountPerLp.toString()); console.log(posAfterSettle.perLpBase.toString()); assert(posAfterSettle.baseAssetAmount.eq(posAfter.baseAssetAmount)); assert(posAfterSettle.quoteAssetAmount.eq(posAfter.quoteAssetAmount)); }); it('settled at negative rebase value', async () => { await driftClient.updatePerpMarketPerLpBase(0, 1); await driftClient.updatePerpMarketPerLpBase(0, 0); await driftClient.updatePerpMarketPerLpBase(0, -1); await driftClient.updatePerpMarketPerLpBase(0, -2); await driftClient.updatePerpMarketPerLpBase(0, -3); const tradeSize = new BN(5 * BASE_PRECISION.toNumber()); const market = driftClient.getPerpMarketAccount(0); console.log('user trading...'); await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await traderDriftClient.openPosition( PositionDirection.SHORT, tradeSize, market.marketIndex ); await _viewLogs(_txsig); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const posAfter: PerpPosition = await driftClient .getUser() .getPerpPositionWithLPSettle(0)[0]; console.log('posAfter'); console.log(posAfter.baseAssetAmount.toString()); console.log(posAfter.quoteAssetAmount.toString()); console.log(posAfter.lastBaseAssetAmountPerLp.toString()); console.log(posAfter.lastQuoteAssetAmountPerLp.toString()); console.log(posAfter.perLpBase.toString()); const _txSig = await driftClient.settleLP( await driftClient.getUserAccountPublicKey(), market.marketIndex ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const posAfterSettle: PerpPosition = await driftClient .getUser() .getPerpPositionWithLPSettle(0)[0]; console.log('posAfterSettle'); console.log(posAfterSettle.baseAssetAmount.toString()); console.log(posAfterSettle.quoteAssetAmount.toString()); console.log(posAfterSettle.lastBaseAssetAmountPerLp.toString()); console.log(posAfterSettle.lastQuoteAssetAmountPerLp.toString()); console.log(posAfterSettle.perLpBase.toString()); assert(posAfterSettle.baseAssetAmount.eq(posAfter.baseAssetAmount)); assert(posAfterSettle.quoteAssetAmount.eq(posAfter.quoteAssetAmount)); }); it('permissionless lp burn', async () => { const lpAmount = new BN(1 * BASE_PRECISION.toNumber()); const _sig = await driftClient.addPerpLpShares(lpAmount, 0); const time = bankrunContextWrapper.connection.getTime(); const _2sig = await driftClient.updatePerpMarketExpiry(0, new BN(time + 5)); await sleep(5000); await driftClient.fetchAccounts(); const market = driftClient.getPerpMarketAccount(0); console.log(market.status); await traderDriftClient.removePerpLpSharesInExpiringMarket( 0, await driftClient.getUserAccountPublicKey() ); await driftClientUser.fetchAccounts(); const position = driftClientUser.getPerpPosition(0); console.log(position); // assert(position.lpShares.eq(ZERO)); }); return; it('lp gets paid in funding (todo)', async () => { const market = driftClient.getPerpMarketAccount(1); const marketIndex = market.marketIndex; console.log('adding liquidity to market ', marketIndex, '...'); try { const _sig = await driftClient.addPerpLpShares( new BN(100_000).mul(new BN(BASE_PRECISION.toNumber())), marketIndex ); } catch (e) { console.error(e); } await delay(lpCooldown + 1000); console.log('user trading...'); // const trader0 = await traderDriftClient.getUserAccount(); const tradeSize = new BN(100).mul(AMM_RESERVE_PRECISION); const newPrice = await adjustOraclePostSwap( tradeSize, SwapDirection.ADD, market, bankrunContextWrapper ); console.log('market', marketIndex, 'post trade price:', newPrice); try { const _txig = await traderDriftClient.openPosition( PositionDirection.LONG, tradeSize, marketIndex, new BN(newPrice * PRICE_PRECISION.toNumber()) ); } catch (e) { console.error(e); } console.log('updating funding rates'); const _txsig = await driftClient.updateFundingRate(marketIndex, solusdc2); console.log('removing liquidity...'); try { const _txSig = await driftClient.removePerpLpShares(marketIndex); _viewLogs(_txSig); } catch (e) { console.log(e); } await driftClient.fetchAccounts(); const user = driftClientUser.getUserAccount(); // const feePayment = new BN(1300000); // const fundingPayment = new BN(900000); // dont get paid in fees bc the sqrtk is so big that fees dont get given to the lps // TODO // assert(user.perpPositions[1].unsettledPnl.eq(fundingPayment.add(feePayment))); const position1 = user.perpPositions[1]; console.log( 'lp position:', position1.baseAssetAmount.toString(), position1.quoteAssetAmount.toString(), 'vs step size:', market.amm.orderStepSize.toString() ); assert(user.perpPositions[1].baseAssetAmount.eq(ZERO)); // lp has no position assert( user.perpPositions[1].baseAssetAmount.abs().lt(market.amm.orderStepSize) ); // const trader = traderDriftClient.getUserAccount(); // await adjustOraclePostSwap( // trader.perpPositions[1].baseAssetAmount, // SwapDirection.ADD, // market // ); // await traderDriftClient.closePosition(market.marketIndex); // close lp position // console.log('closing lp ...'); // console.log(user.perpPositions[1].baseAssetAmount.toString()); // await adjustOraclePostSwap( // user.perpPositions[1].baseAssetAmount, // SwapDirection.REMOVE, // market // ); }); // // TODO // it('provides and removes liquidity too fast', async () => { // const market = driftClient.getPerpMarketAccount(0); // const lpShares = new BN(100 * AMM_RESERVE_PRECISION); // const addLpIx = await driftClient.getAddLiquidityIx( // lpShares, // market.marketIndex // ); // const removeLpIx = await driftClient.getRemoveLiquidityIx( // market.marketIndex, // lpShares // ); // const tx = new web3.Transaction().add(addLpIx).add(removeLpIx); // try { // await provider.sendAll([{ tx }]); // assert(false); // } catch (e) { // console.error(e); // assert(e.message.includes('0x17ce')); // } // }); // it('removes liquidity when market position is small', async () => { // console.log('adding liquidity...'); // await driftClient.addLiquidity(usdcAmount, new BN(0)); // // console.log('user trading...'); // await traderDriftClient.openPosition( // PositionDirection.LONG, // new BN(1 * 1e6), // new BN(0) // ); // // console.log('removing liquidity...'); // await driftClient.removeLiquidity(new BN(0)); // // const user = driftClient.getUserAccount(); // const position = user.perpPositions[0]; // // // small loss // assert(position.unsettledPnl.lt(ZERO)); // // no position // assert(position.baseAssetAmount.eq(ZERO)); // assert(position.quoteAssetAmount.eq(ZERO)); // }); // // uncomment when settle fcn is ready /* it('adds additional liquidity to an already open lp', async () => { console.log('adding liquidity...'); const lp_amount = new BN(300 * 1e6); const _txSig = await driftClient.addLiquidity(lp_amount, new BN(0)); console.log( 'tx logs', (await connection.getTransaction(txsig, { commitment: 'confirmed' })).meta .logMessages ); const init_user = driftClientUser.getUserAccount(); await driftClient.addLiquidity(lp_amount, new BN(0)); const user = driftClientUser.getUserAccount(); const init_tokens = init_user.perpPositions[0].lpTokens; const tokens = user.perpPositions[0].lpTokens; console.log(init_tokens.toString(), tokens.toString()); assert(init_tokens.lt(tokens)); await driftClient.removeLiquidity(new BN(0)); }); */ /* it('settles an lps position', async () => { console.log('adding liquidity...'); await driftClient.addLiquidity(usdcAmount, new BN(0)); let user = driftClient.getUserAccount(); const baa = user.perpPositions[0].baseAssetAmount; const qaa = user.perpPositions[0].quoteAssetAmount; const upnl = user.perpPositions[0].unsettledPnl; console.log('user trading...'); await traderDriftClient.openPosition( PositionDirection.SHORT, new BN(115 * 1e5), new BN(0) ); console.log('settling...'); await traderDriftClient.settleLP( await driftClient.getUserAccountPublicKey(), new BN(0) ); user = driftClient.getUserAccount(); const position = user.perpPositions[0]; const post_baa = position.baseAssetAmount; const post_qaa = position.quoteAssetAmount; const post_upnl = position.unsettledPnl; // they got the market position + upnl console.log(baa.toString(), post_baa.toString()); console.log(qaa.toString(), post_qaa.toString()); console.log(upnl.toString(), post_upnl.toString()); assert(!post_baa.eq(baa)); assert(post_qaa.gt(qaa)); assert(!post_upnl.eq(upnl)); // other sht was updated const market = driftClient.getPerpMarketAccount(new BN(0)); assert(market.amm.netBaseAssetAmount.eq(position.lastNetBaseAssetAmount)); assert( market.amm.totalFeeMinusDistributions.eq( position.lastTotalFeeMinusDistributions ) ); const _txSig = await driftClient.removeLiquidity(new BN(0)); console.log('done!'); }); */ /* it('simulates a settle via sdk', async () => { const userPosition2 = driftClient.getUserAccount().perpPositions[0]; console.log( userPosition2.baseAssetAmount.toString(), userPosition2.quoteAssetAmount.toString(), userPosition2.unsettledPnl.toString() ); console.log('add lp ...'); await driftClient.addLiquidity(usdcAmount, new BN(0)); console.log('user trading...'); await traderDriftClient.openPosition( PositionDirection.SHORT, new BN(115 * 1e5), new BN(0) ); const [settledPosition, result, _] = driftClientUser.getPerpPositionWithLPSettle( new BN(0) ); console.log('settling...'); const _txSig = await traderDriftClient.settleLP( await driftClient.getUserAccountPublicKey(), new BN(0) ); console.log( 'tx logs', (await connection.getTransaction(txsig, { commitment: 'confirmed' })).meta .logMessages ); const userPosition = driftClient.getUserAccount().perpPositions[0]; console.log( userPosition.baseAssetAmount.toString(), settledPosition.baseAssetAmount.toString(), userPosition.quoteAssetAmount.toString(), settledPosition.quoteAssetAmount.toString(), userPosition.unsettledPnl.toString(), settledPosition.unsettledPnl.toString() ); assert(result == SettleResult.RECIEVED_MARKET_POSITION); assert(userPosition.baseAssetAmount.eq(settledPosition.baseAssetAmount)); assert(userPosition.quoteAssetAmount.eq(settledPosition.quoteAssetAmount)); assert(userPosition.unsettledPnl.eq(settledPosition.unsettledPnl)); }); */ });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/curve.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { Keypair } from '@solana/web3.js'; import { TestClient, PRICE_PRECISION, PEG_PRECISION, QUOTE_PRECISION, BASE_PRECISION, BN, calculateReservePrice, calculateTargetPriceTrade, User, PositionDirection, convertToNumber, calculateBudgetedPeg, QUOTE_SPOT_MARKET_INDEX, } from '../sdk/src'; import { liquidityBook } from './liquidityBook'; import { assert } from '../sdk/src/assert/assert'; import { mockOracleNoProgram, initializeQuoteSpotMarket, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, } from './testHelpers'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('AMM Curve', () => { const chProgram = anchor.workspace.Drift as Program; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let driftClient: TestClient; const ammInitialQuoteAssetAmount = new anchor.BN(10 ** 8).mul(BASE_PRECISION); const ammInitialBaseAssetAmount = new anchor.BN(10 ** 8).mul(BASE_PRECISION); let usdcMint: Keypair; let userUSDCAccount: Keypair; let solUsdOracle; const marketIndex = 0; const initialSOLPrice = 150; const usdcAmount = new BN(1e9 * QUOTE_PRECISION.toNumber()); const initialBaseAssetAmount = new BN( // eslint-disable-next-line @typescript-eslint/no-loss-of-precision 662251.6556291390728 * BASE_PRECISION.toNumber() ); let userAccount: User; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); solUsdOracle = await mockOracleNoProgram( bankrunContextWrapper, initialSOLPrice ); const periodicity = new BN(60 * 60); // 1 HOUR await driftClient.initializePerpMarket( 0, solUsdOracle, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity, PEG_PRECISION.mul(new BN(initialSOLPrice)) ); await driftClient.initializeUserAccount(); userAccount = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await userAccount.subscribe(); }); after(async () => { await driftClient.unsubscribe(); await userAccount.unsubscribe(); }); const showCurve = async (marketIndex) => { const marketData = driftClient.getPerpMarketAccount(marketIndex); const ammAccountState = marketData.amm; console.log( 'baseAssetAmountShort', convertToNumber(marketData.amm.baseAssetAmountShort, BASE_PRECISION), 'baseAssetAmountLong', convertToNumber(marketData.amm.baseAssetAmountLong, BASE_PRECISION) ); console.log( 'pegMultiplier', convertToNumber(ammAccountState.pegMultiplier, PEG_PRECISION) ); const totalFeeNum = convertToNumber( ammAccountState.totalFee, QUOTE_PRECISION ); const cumFeeNum = convertToNumber( ammAccountState.totalFeeMinusDistributions, QUOTE_PRECISION ); console.log('totalFee', totalFeeNum); console.log('cumFee', cumFeeNum); return totalFeeNum - cumFeeNum; }; const showBook = async (marketIndex) => { const market = driftClient.getPerpMarketAccount(marketIndex); const currentMark = calculateReservePrice(market, undefined); const [bidsPrice, bidsCumSize, asksPrice, asksCumSize] = liquidityBook( market, 3, 0.1 ); for (let i = asksCumSize.length - 1; i >= 0; i--) { console.log( convertToNumber(asksPrice[i]), convertToNumber(asksCumSize[i], QUOTE_PRECISION) ); } console.log('------------'); console.log(currentMark.toNumber() / PRICE_PRECISION.toNumber()); console.log( 'peg:', convertToNumber(market.amm.pegMultiplier, PEG_PRECISION), 'k (M*M):', convertToNumber(market.amm.sqrtK, BASE_PRECISION) ); console.log('------------'); for (let i = 0; i < bidsCumSize.length; i++) { console.log( convertToNumber(bidsPrice[i]), convertToNumber(bidsCumSize[i], QUOTE_PRECISION) ); } }; it('After Deposit', async () => { await driftClient.deposit( usdcAmount, QUOTE_SPOT_MARKET_INDEX, userUSDCAccount.publicKey ); await showBook(marketIndex); }); it('After Position Taken', async () => { await driftClient.openPosition( PositionDirection.LONG, initialBaseAssetAmount, marketIndex ); await showBook(marketIndex); }); it('After Position Price Moves', async () => { // const _priceIncreaseFactor = new BN(2); await driftClient.moveAmmToPrice( marketIndex, new BN(initialSOLPrice * PRICE_PRECISION.toNumber() * 1.0001) ); await showBook(marketIndex); }); it('Arb back to Oracle Price Moves', async () => { const [direction, basesize] = calculateTargetPriceTrade( driftClient.getPerpMarketAccount(marketIndex), new BN(initialSOLPrice).mul(PRICE_PRECISION), undefined, 'base' ); console.log('arbing', direction, basesize.toString()); await driftClient.openPosition(direction, basesize, marketIndex); await showBook(marketIndex); }); it('Repeg Curve LONG', async () => { let marketData = driftClient.getPerpMarketAccount(marketIndex); const ammAccountState = marketData.amm; assert(ammAccountState.totalFee.eq(ammAccountState.totalFee)); const oldPeg = ammAccountState.pegMultiplier; const newOraclePrice = 155; const newOraclePriceWithMantissa = new BN( newOraclePrice * PRICE_PRECISION.toNumber() ); await setFeedPriceNoProgram( bankrunContextWrapper, newOraclePrice, solUsdOracle ); // showCurve(marketIndex); await driftClient.openPosition( PositionDirection.LONG, BASE_PRECISION.div(new BN(10)), marketIndex ); // showBook(marketIndex); const priceBefore = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); await driftClient.repegAmmCurve( new BN(150.001 * PEG_PRECISION.toNumber()), marketIndex ); const priceAfter = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); assert(newOraclePriceWithMantissa.gt(priceBefore)); assert(priceAfter.gt(priceBefore)); assert(newOraclePriceWithMantissa.gt(priceAfter)); console.log('\n post repeg: \n --------'); await showCurve(marketIndex); // showBook(marketIndex); marketData = driftClient.getPerpMarketAccount(marketIndex); console.log(marketData.amm); console.log(); assert( marketData.amm.totalFee.gte(marketData.amm.totalFeeMinusDistributions) ); const newPeg = marketData.amm.pegMultiplier; const userPerpPosition = userAccount.getUserAccount().perpPositions[0]; const linearApproxCostToAMM = convertToNumber( newPeg .sub(oldPeg) .mul(userPerpPosition.baseAssetAmount) .div(PEG_PRECISION), BASE_PRECISION ); // console.log('cur user position:', convertBaseAssetAmountToNumber(userPerpPosition.baseAssetAmount)); const totalCostToAMMChain = await showCurve(marketIndex); assert(linearApproxCostToAMM > totalCostToAMMChain); assert(linearApproxCostToAMM / totalCostToAMMChain < 1.1); // const feeDist1h = calculateFeeDist(marketIndex); await driftClient.closePosition(marketIndex); // showCurve(marketIndex); // const feeDist2 = calculateFeeDist(marketIndex); }); // it('Repeg Curve SHORT', async () => { // const newOraclePrice = 145; // const newOraclePriceWithMantissa = new BN( // newOraclePrice * PRICE_PRECISION.toNumber() // ); // await setFeedPrice(anchor.workspace.Pyth, newOraclePrice, solUsdOracle); // showCurve(marketIndex); // await driftClient.openPosition( // PositionDirection.SHORT, // BASE_PRECISION.div(new BN(1000)), // marketIndex // ); // const marketData1 = driftClient.getPerpMarketAccount(marketIndex); // const ammAccountState = marketData1.amm; // const oldPeg = ammAccountState.pegMultiplier; // const priceBefore = calculateReservePrice( // driftClient.getPerpMarketAccount(marketIndex) // ); // await driftClient.repegAmmCurve( // new BN(148 * PEG_PRECISION.toNumber()), // marketIndex // ); // const priceAfter = calculateReservePrice( // driftClient.getPerpMarketAccount(marketIndex) // ); // assert(newOraclePriceWithMantissa.lt(priceBefore)); // assert(priceAfter.lt(priceBefore)); // assert(newOraclePriceWithMantissa.lt(priceAfter)); // const marketData = driftClient.getPerpMarketAccount(marketIndex); // const newPeg = marketData.amm.pegMultiplier; // const userPerpPosition = userAccount.getUserAccount().perpPositions[0]; // console.log('\n post repeg: \n --------'); // const linearApproxCostToAMM = convertToNumber( // newPeg // .sub(oldPeg) // .mul(userPerpPosition.baseAssetAmount) // .div(PEG_PRECISION), // BASE_PRECISION // ); // showCurve(marketIndex); // const totalCostToAMMChain = convertToNumber( // marketData1.amm.totalFeeMinusDistributions.sub( // marketData.amm.totalFeeMinusDistributions // ), // QUOTE_PRECISION // ); // console.log(linearApproxCostToAMM, 'vs', totalCostToAMMChain); // assert(linearApproxCostToAMM > totalCostToAMMChain); // assert(linearApproxCostToAMM / totalCostToAMMChain < 1.02); // await driftClient.closePosition(marketIndex); // }); it('calculateBudgetedPeg (sdk tests)', async () => { const marketData1 = driftClient.getPerpMarketAccount(marketIndex); let amm = marketData1.amm; // unbalanced but no net position console.log('netBaseAssetAmount:', amm.baseAssetAmountWithAmm.toString()); assert(!amm.baseAssetReserve.eq(amm.quoteAssetReserve)); console.log(amm.baseAssetAmountWithAmm); assert(amm.baseAssetAmountWithAmm.eq(new BN(0))); // check if balanced const candidatePegUp0 = calculateBudgetedPeg( amm, QUOTE_PRECISION, new BN(200 * PRICE_PRECISION.toNumber()) ); const candidatePegDown0 = calculateBudgetedPeg( amm, QUOTE_PRECISION, new BN(10 * PRICE_PRECISION.toNumber()) ); console.log(candidatePegUp0.toString(), candidatePegDown0.toString()); assert(candidatePegUp0.eq(new BN(202637647))); assert(candidatePegDown0.eq(new BN(10131882))); // check if short await driftClient.openPosition( PositionDirection.SHORT, BASE_PRECISION, marketIndex ); amm = driftClient.getPerpMarketAccount(marketIndex).amm; const candidatePegUp = calculateBudgetedPeg( amm, QUOTE_PRECISION, new BN(200 * PRICE_PRECISION.toNumber()) ); console.log(amm.pegMultiplier.toString(), '->', candidatePegUp.toString()); assert(candidatePegUp.eq(new BN(202637651))); const candidatePegDown = calculateBudgetedPeg( amm, QUOTE_PRECISION, new BN(10 * PRICE_PRECISION.toNumber()) ); console.log( amm.pegMultiplier.toString(), '->', candidatePegDown.toString() ); assert(candidatePegDown.eq(new BN(148987813))); await driftClient.closePosition(marketIndex); // check if long await driftClient.openPosition( PositionDirection.LONG, BASE_PRECISION, marketIndex ); await driftClient.fetchAccounts(); amm = driftClient.getPerpMarketAccount(marketIndex).amm; const candidatePegUp2 = calculateBudgetedPeg( amm, QUOTE_PRECISION, new BN(200 * PRICE_PRECISION.toNumber()) ); console.log( 'USER LONG: target $200', amm.pegMultiplier.toString(), '->', candidatePegUp2.toString() ); assert(candidatePegUp2.eq(new BN(151014187))); const candidatePegDown2 = calculateBudgetedPeg( amm, QUOTE_PRECISION, new BN(10 * PRICE_PRECISION.toNumber()) ); console.log( 'USER LONG: target $10', amm.pegMultiplier.toString(), '->', candidatePegDown2.toString() ); assert(candidatePegDown2.eq(new BN(10131882))); await driftClient.fetchAccounts(); await driftClient.closePosition(marketIndex); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/prepegMarketOrderBaseAssetAmount.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { BN, calculateEffectiveLeverage, getMarketOrderParams, OracleSource, ZERO, calculatePrice, PEG_PRECISION, BASE_PRECISION, BulkAccountLoader, ContractTier, } from '../sdk'; import { Program } from '@coral-xyz/anchor'; import { PublicKey } from '@solana/web3.js'; import { TestClient, PRICE_PRECISION, calculateReservePrice, calculateTradeSlippage, PositionDirection, EventSubscriber, convertToNumber, findComputeUnitConsumption, calculateBidAskPrice, calculateUpdatedAMM, AMM_TO_QUOTE_PRECISION_RATIO, calculateTradeAcquiredAmounts, calculateSpread, calculateInventoryScale, QUOTE_PRECISION, } from '../sdk/src'; import { getFeedData, // initUserAccounts, mockOracle, mockUserUSDCAccount, mockUSDCMint, setFeedPrice, getOraclePriceData, initializeQuoteSpotMarket, sleep, } from './testHelpers'; describe('prepeg', () => { const provider = anchor.AnchorProvider.local(undefined, { commitment: 'confirmed', skipPreflight: false, preflightCommitment: 'confirmed', }); const connection = provider.connection; anchor.setProvider(provider); const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; const eventSubscriber = new EventSubscriber(connection, chProgram, { commitment: 'recent', }); eventSubscriber.subscribe(); const bulkAccountLoader = new BulkAccountLoader(connection, 'confirmed', 1); let userAccountPublicKey: PublicKey; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(100000); const ammInitialQuoteAssetAmount = new anchor.BN( 5 * BASE_PRECISION.toNumber() ).mul(mantissaSqrtScale); const ammInitialBaseAssetAmount = new anchor.BN( 5 * BASE_PRECISION.toNumber() ).mul(mantissaSqrtScale); const usdcAmount = new BN(10000 * QUOTE_PRECISION.toNumber()); let marketIndexes; let spotMarketIndexes; let oracleInfos; let solUsd; const mockOracles = []; before(async () => { usdcMint = await mockUSDCMint(provider); userUSDCAccount = await mockUserUSDCAccount(usdcMint, usdcAmount, provider); solUsd = await mockOracle(1, -7, 0); mockOracles.push(solUsd); for (let i = 1; i <= 4; i++) { // init more oracles const thisUsd = await mockOracle(i); mockOracles.push(thisUsd); } spotMarketIndexes = [0]; marketIndexes = mockOracles.map((_, i) => i); oracleInfos = mockOracles.map((oracle) => { return { publicKey: oracle, source: OracleSource.PYTH }; }); driftClient = new TestClient({ connection, wallet: provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(0); const periodicity = new BN(60 * 60); // 1 HOUR await driftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity, PEG_PRECISION, undefined, ContractTier.A, 1000, 500, undefined, undefined, undefined, true, 2000, 5000 ); // await driftClient.updatePerpMarketBaseSpread(0, 1000); await driftClient.updatePerpMarketCurveUpdateIntensity(0, 100); await driftClient.updatePerpMarketStepSizeAndTickSize( 0, new BN(1), new BN(1) ); for (let i = 1; i <= 4; i++) { // init more markets const thisUsd = mockOracles[i]; await driftClient.initializePerpMarket( i, thisUsd, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity, new BN(1_000 * i), undefined, ContractTier.A, 1000, 500, undefined, undefined, undefined, true, 2000, 5000 ); await driftClient.updatePerpMarketBaseSpread(i, 2000); await driftClient.updatePerpMarketCurveUpdateIntensity(i, 100); await driftClient.updatePerpMarketStepSizeAndTickSize( i, new BN(1), new BN(1) ); } [, userAccountPublicKey] = await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); }); after(async () => { await driftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('Long from 0 position', async () => { const marketIndex = 0; const baseAssetAmount = new BN(49745050000); const direction = PositionDirection.LONG; const market0 = driftClient.getPerpMarketAccount(0); // await setFeedPrice(anchor.workspace.Pyth, 1.01, solUsd); const curPrice = (await getFeedData(anchor.workspace.Pyth, solUsd)).price; console.log('new oracle price:', curPrice); const oraclePriceData = await getOraclePriceData( anchor.workspace.Pyth, solUsd ); const position0Before = driftClient.getUserAccount().perpPositions[0]; console.log(position0Before.quoteAssetAmount.eq(ZERO)); const [_pctAvgSlippage, _pctMaxSlippage, _entryPrice, newPrice] = calculateTradeSlippage( direction, baseAssetAmount, market0, 'base', oraclePriceData ); const [ _acquiredBaseReserve, _acquiredQuoteReserve, acquiredQuoteAssetAmount, ] = calculateTradeAcquiredAmounts( direction, baseAssetAmount, market0, 'base', oraclePriceData ); console.log( 'acquiredQuoteAssetAmount:', acquiredQuoteAssetAmount.toString() ); const [bid, ask] = calculateBidAskPrice(market0.amm, oraclePriceData); console.log( 'bid/ask:', convertToNumber(bid), '/', convertToNumber(ask), 'after trade est. mark price:', convertToNumber(newPrice) ); const orderParams = getMarketOrderParams({ marketIndex, direction, baseAssetAmount, }); const txSig = await driftClient.placeAndTakePerpOrder(orderParams); const computeUnits = await findComputeUnitConsumption( driftClient.program.programId, connection, txSig, 'confirmed' ); console.log('compute units', computeUnits); console.log( 'tx logs', (await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta .logMessages ); const market = driftClient.getPerpMarketAccount(0); const [bid1, ask1] = calculateBidAskPrice(market.amm, oraclePriceData); console.log( 'after trade bid/ask:', convertToNumber(bid1), '/', convertToNumber(ask1), 'after trade mark price:', convertToNumber(calculateReservePrice(market, oraclePriceData)) ); const position0 = driftClient.getUserAccount().perpPositions[0]; console.log( position0.quoteAssetAmount.toString(), 'vs', acquiredQuoteAssetAmount.toString(), 'vs', position0.quoteBreakEvenAmount.toString() ); console.log('quoteEntryAmount:', position0.quoteEntryAmount.toString()); assert.ok(position0.quoteEntryAmount.eq(new BN(-49874459))); assert.ok(acquiredQuoteAssetAmount.eq(position0.quoteEntryAmount.abs())); assert.ok(position0.quoteBreakEvenAmount.eq(new BN(-49924334))); assert.ok( acquiredQuoteAssetAmount.eq( position0.quoteBreakEvenAmount.add(market.amm.totalExchangeFee).abs() ) ); console.log( driftClient.getUserAccount().perpPositions[0].baseAssetAmount.toString() ); assert.ok( driftClient .getUserAccount() .perpPositions[0].baseAssetAmount.eq(baseAssetAmount) ); console.log('sqrtK:', market.amm.sqrtK.toString()); console.log('totalExchangeFee:', market.amm.totalExchangeFee.toString()); assert.ok(market.amm.baseAssetAmountWithAmm.eq(new BN(49745050000))); assert.ok(market.amm.baseAssetAmountLong.eq(new BN(49745050000))); assert.ok(market.amm.baseAssetAmountShort.eq(ZERO)); assert.ok(market.numberOfUsersWithBase === 1); assert.ok(market.amm.totalFee.gt(new BN(49750))); assert.ok(market.amm.totalFeeMinusDistributions.gt(new BN(49750))); assert.ok(market.amm.totalExchangeFee.eq(new BN(49875))); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderRecord.taker.equals(userAccountPublicKey)); assert.ok(orderRecord.baseAssetAmountFilled.eq(new BN(49745050000))); assert.ok(orderRecord.quoteAssetAmountFilled.gt(new BN(49750001))); assert.ok(orderRecord.marketIndex === 0); // console.log(orderRecord); console.log(market.amm.totalExchangeFee.toNumber()); console.log(position0.quoteAssetAmount.toNumber()); assert.ok(position0.quoteAssetAmount.eq(new BN(-49874459 - 49875))); assert.ok( position0.quoteAssetAmount.eq( position0.quoteEntryAmount.sub(market.amm.totalExchangeFee) ) ); assert.ok(position0.quoteAssetAmount.eq(position0.quoteBreakEvenAmount)); }); it('Long even more', async () => { const marketIndex = 0; const baseAssetAmount = new BN(49745050367 / 50); const market0 = driftClient.getPerpMarketAccount(0); await setFeedPrice(anchor.workspace.Pyth, 1.0281, solUsd); const curPrice = (await getFeedData(anchor.workspace.Pyth, solUsd)).price; console.log('new oracle price:', curPrice); const oraclePriceData = await getOraclePriceData( anchor.workspace.Pyth, solUsd ); console.log('oraclePriceData', oraclePriceData.price.toNumber()); assert(market0.amm.pegMultiplier.eq(new BN(1000000))); const prepegAMM = calculateUpdatedAMM(market0.amm, oraclePriceData); console.log(prepegAMM.pegMultiplier.toString()); assert(prepegAMM.pegMultiplier.eq(new BN(1025325))); const estDist = prepegAMM.totalFee.sub( prepegAMM.totalFeeMinusDistributions ); console.log('est distribution:', estDist.toString()); const [_pctAvgSlippage, _pctMaxSlippage, _entryPrice, newPrice] = calculateTradeSlippage( PositionDirection.LONG, baseAssetAmount, market0, 'base', oraclePriceData ); const [ _acquiredBaseReserve, _acquiredQuoteReserve, acquiredQuoteAssetAmount, ] = calculateTradeAcquiredAmounts( PositionDirection.LONG, baseAssetAmount, market0, 'base', oraclePriceData ); const acquiredQuote = _entryPrice .mul(baseAssetAmount.abs()) .div(AMM_TO_QUOTE_PRECISION_RATIO) .div(PRICE_PRECISION); console.log( 'est acquiredQuote:', acquiredQuote.toNumber(), acquiredQuoteAssetAmount.toNumber() ); const newAmm = calculateUpdatedAMM(market0.amm, oraclePriceData); const reservePrice = calculatePrice( newAmm.baseAssetReserve, newAmm.quoteAssetReserve, newAmm.pegMultiplier ); const effectiveLeverage = calculateEffectiveLeverage( newAmm.baseSpread, newAmm.quoteAssetReserve, newAmm.terminalQuoteAssetReserve, newAmm.pegMultiplier, newAmm.baseAssetAmountWithAmm, reservePrice, newAmm.totalFeeMinusDistributions ); const inventoryScale = calculateInventoryScale( newAmm.baseAssetAmountWithAmm, newAmm.baseAssetReserve, newAmm.minBaseAssetReserve, newAmm.maxBaseAssetReserve, 0, 1e6 ); console.log(inventoryScale, effectiveLeverage); const [longSpread, shortSpread] = calculateSpread( newAmm, oraclePriceData, newAmm.historicalOracleData.lastOraclePriceTwapTs.add(new BN(1)) ); console.log(newAmm.baseSpread, longSpread, shortSpread, newAmm.maxSpread); console.log(inventoryScale); console.log(effectiveLeverage); assert(newAmm.maxSpread == 5000); assert(inventoryScale == 341); assert(effectiveLeverage == 5078.000001); assert(shortSpread == 2490); assert(longSpread.toString() == '24902'); const [bid, ask] = calculateBidAskPrice(market0.amm, oraclePriceData); console.log( 'bid/ask:', convertToNumber(bid), '/', convertToNumber(ask), 'after trade est. mark price:', convertToNumber(newPrice) ); const orderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, }); const txSig = await driftClient.placeAndTakePerpOrder(orderParams); const computeUnits = await findComputeUnitConsumption( driftClient.program.programId, connection, txSig, 'confirmed' ); console.log('compute units', computeUnits); console.log( 'tx logs', (await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta .logMessages ); await sleep(2000); await driftClient.fetchAccounts(); const market = driftClient.getPerpMarketAccount(0); const [bid1, ask1] = calculateBidAskPrice(market.amm, oraclePriceData); console.log( 'after trade bid/ask:', convertToNumber(bid1), '/', convertToNumber(ask1), 'after trade mark price:', convertToNumber(calculateReservePrice(market, oraclePriceData)) ); assert(bid1.lt(ask1)); assert(ask1.gt(oraclePriceData.price)); assert(bid1.lt(oraclePriceData.price)); console.log('prepegAMM.pegMultiplier:', prepegAMM.pegMultiplier.toString()); console.log( 'market.amm.pegMultiplier:', market.amm.pegMultiplier.toString() ); assert(market.amm.pegMultiplier.eq(new BN(1025325))); const actualDist = market.amm.totalFee.sub( market.amm.totalFeeMinusDistributions ); console.log( 'actual vs est distribution:', actualDist.toString(), '==', estDist.toString() ); console.log(prepegAMM.sqrtK.toString(), '==', market.amm.sqrtK.toString()); const marketInvariant = market.amm.sqrtK.mul(market.amm.sqrtK); // check k math good assert( marketInvariant .div(market.amm.baseAssetReserve) .eq(market.amm.quoteAssetReserve) ); assert( marketInvariant .div(market.amm.quoteAssetReserve) .eq(market.amm.baseAssetReserve) ); // check prepeg and post trade worked as expected assert(prepegAMM.sqrtK.eq(market.amm.sqrtK)); // predicted k = post trade k assert(actualDist.sub(estDist).abs().lte(new BN(4))); // cost is near equal assert(market.amm.sqrtK.lt(market0.amm.sqrtK)); // k was lowered console.log(market.amm.longSpread); console.log(market.amm.shortSpread); assert(market.amm.longSpread === 24901); assert(market.amm.shortSpread === 2490); const orderActionRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderActionRecord.taker.equals(userAccountPublicKey)); // console.log(orderRecord); await driftClient.fetchAccounts(); const position0 = driftClient.getUserAccount().perpPositions[0]; const position0qea = position0.quoteEntryAmount; console.log( 'position0qea:', position0qea.toNumber(), '(+', acquiredQuoteAssetAmount.toNumber(), ')' ); console.log( 'baseASsetAmounts:', position0.baseAssetAmount.toNumber(), 'vs', orderActionRecord.baseAssetAmountFilled.toNumber(), 'vs', baseAssetAmount.toNumber() ); console.log( 'position0.quoteAssetAmount:', position0.quoteAssetAmount.toNumber() ); assert(orderActionRecord.baseAssetAmountFilled.eq(baseAssetAmount)); const recordEntryPrice = orderActionRecord.quoteAssetAmountFilled .mul(AMM_TO_QUOTE_PRECISION_RATIO) .mul(PRICE_PRECISION) .div(orderActionRecord.baseAssetAmountFilled.abs()); console.log( 'entry sdk', convertToNumber(_entryPrice), 'vs entry record', convertToNumber(recordEntryPrice) ); const orderRecord = eventSubscriber.getEventsArray('OrderRecord')[0]; console.log( 'record Auction:', convertToNumber(orderRecord.order.auctionStartPrice), '->', convertToNumber(orderRecord.order.auctionEndPrice), 'record oracle:', convertToNumber(orderActionRecord.oraclePrice) ); // assert.ok( // position0qea // .abs() // .eq(acquiredQuoteAssetAmount.add(new BN(49999074)).add(new BN(-1001))) // ); console.log( 'position0.quoteAssetAmount:', position0.quoteAssetAmount.toNumber() ); console.log( 'position0.quoteEntryAmount:', position0.quoteBreakEvenAmount.toNumber() ); console.log( 'acquiredQuoteAssetAmount:', acquiredQuoteAssetAmount.toNumber() ); assert(acquiredQuoteAssetAmount.eq(new BN(1045969))); console.log(position0qea.toString()); assert.ok(position0qea.eq(new BN(-50920428))); assert.ok(position0.quoteBreakEvenAmount.eq(new BN(-50971349))); assert.ok(position0.quoteAssetAmount.eq(new BN(-50971349))); }); it('Reduce long position', async () => { const marketIndex = 0; const baseAssetAmount = new BN(24872525000); const market0 = driftClient.getPerpMarketAccount(0); const orderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, }); await setFeedPrice(anchor.workspace.Pyth, 1.02234232, solUsd); const curPrice = (await getFeedData(anchor.workspace.Pyth, solUsd)).price; console.log('new oracle price:', curPrice); const oraclePriceData = await getOraclePriceData( anchor.workspace.Pyth, solUsd ); const [_pctAvgSlippage, _pctMaxSlippage, _entryPrice, newPrice] = calculateTradeSlippage( PositionDirection.SHORT, baseAssetAmount, market0, 'base', oraclePriceData ); const acquiredQuote = _entryPrice .mul(baseAssetAmount.abs()) .div(AMM_TO_QUOTE_PRECISION_RATIO) .div(PRICE_PRECISION); console.log('est acquiredQuote:', acquiredQuote.toNumber()); const [bid, ask] = calculateBidAskPrice(market0.amm, oraclePriceData); console.log( 'bid/ask:', convertToNumber(bid), '/', convertToNumber(ask), 'after trade est. mark price:', convertToNumber(newPrice) ); const txSig = await driftClient.placeAndTakePerpOrder(orderParams); const computeUnits = await findComputeUnitConsumption( driftClient.program.programId, connection, txSig, 'confirmed' ); console.log('compute units', computeUnits); console.log( 'tx logs', (await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta .logMessages ); const market = driftClient.getPerpMarketAccount(0); const [bid1, ask1] = calculateBidAskPrice(market.amm, oraclePriceData); console.log( 'after trade bid/ask:', convertToNumber(bid1), '/', convertToNumber(ask1), 'after trade mark price:', convertToNumber(calculateReservePrice(market, oraclePriceData)) ); console.log( driftClient.getUserAccount().perpPositions[0].baseAssetAmount.toNumber() ); console.log(market.amm.baseAssetAmountWithAmm.toString()); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderRecord.taker.equals(userAccountPublicKey)); console.log(orderRecord.baseAssetAmountFilled.toNumber()); assert.ok(orderRecord.baseAssetAmountFilled.eq(new BN(24872525000))); assert.ok(orderRecord.marketIndex === 0); }); it('Many market balanced prepegs, long position', async () => { for (let i = 1; i <= 4; i++) { const thisUsd = mockOracles[i]; const marketIndex = i; const baseAssetAmount = new BN(31.02765 * BASE_PRECISION.toNumber()); const market0 = driftClient.getPerpMarketAccount(i); const orderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, }); const curPrice = (await getFeedData(anchor.workspace.Pyth, thisUsd)) .price; console.log('market_index=', i, 'new oracle price:', curPrice); const oraclePriceData = await getOraclePriceData( anchor.workspace.Pyth, thisUsd ); const [_pctAvgSlippage, _pctMaxSlippage, _entryPrice, newPrice] = calculateTradeSlippage( PositionDirection.LONG, baseAssetAmount, market0, 'base', oraclePriceData ); const [bid, ask] = calculateBidAskPrice(market0.amm, oraclePriceData); console.log( 'bid/ask:', convertToNumber(bid), '/', convertToNumber(ask), 'after trade est. mark price:', convertToNumber(newPrice) ); try { const txSig = await driftClient.placeAndTakePerpOrder(orderParams); const computeUnits = await findComputeUnitConsumption( driftClient.program.programId, connection, txSig, 'confirmed' ); console.log('compute units', computeUnits); console.log( 'tx logs', (await connection.getTransaction(txSig, { commitment: 'confirmed' })) .meta.logMessages ); } catch (e) { console.error(e); assert(false); } const market = driftClient.getPerpMarketAccount(i); const [bid1, ask1] = calculateBidAskPrice(market.amm, oraclePriceData); console.log( 'after trade bid/ask:', convertToNumber(bid1), '/', convertToNumber(ask1), 'after trade mark price:', convertToNumber(calculateReservePrice(market, oraclePriceData)) ); console.log('----'); } }); it('Many market expensive prepeg margin', async () => { const user = driftClient.getUserAccount(); // todo cheapen margin peg enough to make this work w/ 5 positions for (let i = 1; i <= 4; i++) { console.log( 'user market', user.perpPositions[i].marketIndex.toString(), ' base position', '=', user.perpPositions[i].baseAssetAmount.toNumber() / 1e13 ); const thisUsd = mockOracles[i]; const curPrice = (await getFeedData(anchor.workspace.Pyth, thisUsd)) .price; await setFeedPrice(anchor.workspace.Pyth, curPrice * 1.03, thisUsd); } const curPrice = (await getFeedData(anchor.workspace.Pyth, mockOracles[0])) .price; await setFeedPrice(anchor.workspace.Pyth, curPrice * 1.01, mockOracles[0]); const orderParams = getMarketOrderParams({ marketIndex: 0, direction: PositionDirection.SHORT, baseAssetAmount: user.perpPositions[0].baseAssetAmount.div(new BN(2)), }); const txSig = await driftClient.placeAndTakePerpOrder(orderParams); const computeUnits = await findComputeUnitConsumption( driftClient.program.programId, connection, txSig, 'confirmed' ); console.log('compute units', computeUnits); console.log( 'tx logs', (await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta .logMessages ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/oracleOffsetOrders.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { Keypair } from '@solana/web3.js'; import { assert } from 'chai'; import { BN, PRICE_PRECISION, TestClient, PositionDirection, User, Wallet, getLimitOrderParams, MarketStatus, AMM_RESERVE_PRECISION, OracleSource, ZERO, calculateBreakEvenPrice, } from '../sdk/src'; import { mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, initializeQuoteSpotMarket, } from './testHelpers'; import { calculateEntryPrice, PostOnlyParams } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('oracle offset', () => { const chProgram = anchor.workspace.Drift as Program; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let fillerDriftClient: TestClient; let fillerDriftClientUser: User; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(100000); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 9).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 9).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); const marketIndex = 0; let solUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); marketIndexes = [0]; spotMarketIndexes = [0]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; fillerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClient.initialize(usdcMint.publicKey, true); await fillerDriftClient.subscribe(); await initializeQuoteSpotMarket(fillerDriftClient, usdcMint.publicKey); await fillerDriftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(60 * 60); // 1 HOUR await fillerDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await fillerDriftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); await fillerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); fillerDriftClientUser = new User({ driftClient: fillerDriftClient, userAccountPublicKey: await fillerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClientUser.subscribe(); }); beforeEach(async () => { await fillerDriftClient.moveAmmPrice( 0, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve ); await setFeedPriceNoProgram(bankrunContextWrapper, 1, solUsd); }); after(async () => { await fillerDriftClient.unsubscribe(); await fillerDriftClientUser.unsubscribe(); }); it('long taker', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const direction = PositionDirection.LONG; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const price = ZERO; const reduceOnly = false; const priceOffset = PRICE_PRECISION.div(new BN(20)).neg(); const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price, reduceOnly, userOrderId: 1, oraclePriceOffset: priceOffset.toNumber(), }); await driftClient.placePerpOrder(orderParams); await fillerDriftClient.moveAmmPrice( marketIndex, ammInitialBaseAssetReserve.mul(new BN(11)).div(new BN(10)), ammInitialQuoteAssetReserve ); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClient.getUserAccount(), order ); await driftClientUser.fetchAccounts(); const position = driftClientUser.getPerpPosition(marketIndex); const breakEvenPrice = calculateBreakEvenPrice(position); const entryPrice = calculateEntryPrice(position); assert(breakEvenPrice.eq(new BN(910003))); assert(entryPrice.eq(new BN(909093))); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('long maker', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const direction = PositionDirection.LONG; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const reduceOnly = false; const priceOffset = PRICE_PRECISION.div(new BN(20)).neg(); const price = ZERO; // oracle offsetoor const orderParams = getLimitOrderParams({ marketIndex, direction, price, baseAssetAmount, reduceOnly, userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, oraclePriceOffset: priceOffset.toNumber(), }); await driftClient.placePerpOrder(orderParams); await fillerDriftClient.moveAmmPrice( marketIndex, ammInitialBaseAssetReserve.mul(new BN(11)).div(new BN(10)), ammInitialQuoteAssetReserve ); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await driftClientUser.fetchAccounts(); const position = driftClientUser.getPerpPosition(marketIndex); const breakEvenPrice = calculateBreakEvenPrice(position); console.log(breakEvenPrice.toString()); const entryPrice = calculateEntryPrice(position); console.log(entryPrice.toString()); const expectedBreakEvenPrice = new BN(949810); const expectedEntryPrice = new BN(950000); console.log(breakEvenPrice.toString(), 'vs', expectedEntryPrice.toString()); assert(breakEvenPrice.eq(expectedBreakEvenPrice)); assert(entryPrice.eq(expectedEntryPrice)); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('short taker', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const direction = PositionDirection.SHORT; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const reduceOnly = false; const priceOffset = PRICE_PRECISION.div(new BN(20)); const price = ZERO; // oracle offsetoor const orderParams = getLimitOrderParams({ marketIndex, direction, price, baseAssetAmount, reduceOnly, userOrderId: 1, oraclePriceOffset: priceOffset.toNumber(), }); await driftClient.placePerpOrder(orderParams); await fillerDriftClient.moveAmmPrice( marketIndex, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve.mul(new BN(11)).div(new BN(10)) ); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await driftClientUser.fetchAccounts(); const position = driftClientUser.getPerpPosition(marketIndex); const breakEvenPrice = calculateBreakEvenPrice(position); const entryPrice = calculateEntryPrice(position); console.log(breakEvenPrice.toString()); console.log(entryPrice.toString()); assert(breakEvenPrice.eq(new BN(1098897))); assert(entryPrice.eq(new BN(1099997))); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('short maker', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const direction = PositionDirection.SHORT; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const reduceOnly = false; const priceOffset = PRICE_PRECISION.div(new BN(20)); const price = ZERO; const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, reduceOnly, price, userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, oraclePriceOffset: priceOffset.toNumber(), }); await driftClient.placePerpOrder(orderParams); await fillerDriftClient.moveAmmPrice( marketIndex, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve.mul(new BN(11)).div(new BN(10)) ); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await driftClientUser.fetchAccounts(); const position = driftClientUser.getPerpPosition(marketIndex); const breakEvenPrice = calculateBreakEvenPrice(position); const entryPrice = calculateEntryPrice(position); console.log(breakEvenPrice.toString()); console.log(entryPrice.toString()); const expectedEntryPrice = new BN(1050000); const expectedBreakEvenPrice = new BN(1050210); assert(breakEvenPrice.eq(expectedBreakEvenPrice)); assert(entryPrice.eq(expectedEntryPrice)); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('cancel by order id', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const direction = PositionDirection.SHORT; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const reduceOnly = false; const priceOffset = PRICE_PRECISION.div(new BN(20)); const price = ZERO; const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price, reduceOnly, postOnly: PostOnlyParams.MUST_POST_ONLY, oraclePriceOffset: priceOffset.toNumber(), }); await driftClient.placePerpOrder(orderParams); await driftClientUser.fetchAccounts(); const orderId = driftClientUser.getUserAccount().orders[0].orderId; await driftClient.cancelOrder(orderId); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('cancel by user order id', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const direction = PositionDirection.SHORT; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const reduceOnly = false; const priceOffset = PRICE_PRECISION.div(new BN(20)); const price = ZERO; const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price, reduceOnly, postOnly: PostOnlyParams.MUST_POST_ONLY, userOrderId: 1, oraclePriceOffset: priceOffset.toNumber(), }); await driftClient.placePerpOrder(orderParams); await driftClientUser.fetchAccounts(); await driftClient.cancelOrderByUserId(1); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/userOrderId.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { TestClient, BN, PRICE_PRECISION, PositionDirection, User, getLimitOrderParams, MarketStatus, AMM_RESERVE_PRECISION, OracleSource, isVariant, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } from './testHelpers'; import { ContractTier, ExchangeStatus } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('user order id', () => { const chProgram = anchor.workspace.Drift as Program; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let driftClient: TestClient; let driftClientUser: User; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); const marketIndex = 0; let solUsd; let btcUsd; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); btcUsd = await mockOracleNoProgram(bankrunContextWrapper, 60000); const marketIndexes = [marketIndex, 1]; const spotMarketIndexes = [0]; const oracleInfos = [ { publicKey: solUsd, source: OracleSource.PYTH }, { publicKey: btcUsd, source: OracleSource.PYTH }, ]; driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); await driftClient.fetchAccounts(); assert( driftClient.getStateAccount().exchangeStatus === ExchangeStatus.ACTIVE ); const periodicity = new BN(60 * 60); // 1 HOUR await driftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, undefined, undefined, undefined, undefined, undefined, false ); await driftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); await driftClient.initializePerpMarket( 1, btcUsd, ammInitialBaseAssetReserve.div(new BN(3000)), ammInitialQuoteAssetReserve.div(new BN(3000)), periodicity, new BN(60000000), // btc-ish price level undefined, ContractTier.A, undefined, undefined, undefined, undefined, undefined, false ); await driftClient.fetchAccounts(); assert( isVariant(driftClient.getPerpMarketAccount(1).status, 'initialized') ); await driftClient.updatePerpMarketStatus(1, MarketStatus.ACTIVE); await driftClient.fetchAccounts(); assert(isVariant(driftClient.getPerpMarketAccount(1).status, 'active')); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); }); after(async () => { await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('place order', async () => { const direction = PositionDirection.LONG; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const price = PRICE_PRECISION.mul(new BN(2)); const reduceOnly = false; const userOrderId = 1; const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price, reduceOnly, userOrderId, }); await driftClient.placePerpOrder(orderParams); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const order = driftClientUser.getUserAccount().orders[0]; assert(order.userOrderId === userOrderId); }); it('fail to place same user id twice', async () => { const direction = PositionDirection.LONG; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const price = PRICE_PRECISION.mul(new BN(2)); const reduceOnly = false; const userOrderId = 1; const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price, reduceOnly, userOrderId, }); try { await driftClient.placePerpOrder(orderParams); } catch (_) { // return; } assert(false); }); it('cancel ', async () => { await driftClient.cancelOrderByUserId(1); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const order = driftClientUser.getUserAccount().orders[0]; assert(order.userOrderId === 0); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/spotMarketPoolIds.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { PublicKey } from '@solana/web3.js'; import { TestClient, BN, EventSubscriber, SPOT_MARKET_RATE_PRECISION, OracleSource, SPOT_MARKET_WEIGHT_PRECISION, OracleInfo, MarketStatus, } from '../sdk/src'; import { createUserWithUSDCAccount, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpers'; import { QUOTE_PRECISION } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('spot deposit and withdraw', () => { const chProgram = anchor.workspace.Drift as Program; let admin: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let solOracle: PublicKey; let usdcMint; let firstUserDriftClient: TestClient; let firstUserDriftClientUSDCAccount: PublicKey; let secondUserDriftClient: TestClient; let secondUserDriftClientUSDCAccount: PublicKey; const usdcAmount = new BN(10 * 10 ** 6); const largeUsdcAmount = new BN(10_000 * 10 ** 6); let marketIndexes: number[]; let spotMarketIndexes: number[]; let oracleInfos: OracleInfo[]; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); await mockUserUSDCAccount(usdcMint, largeUsdcAmount, bankrunContextWrapper); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 30); marketIndexes = []; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solOracle, source: OracleSource.PYTH }]; admin = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await admin.initialize(usdcMint.publicKey, true); await admin.subscribe(); }); after(async () => { await admin.unsubscribe(); await eventSubscriber.unsubscribe(); await firstUserDriftClient.unsubscribe(); await secondUserDriftClient.unsubscribe(); }); it('Initialize Markets', async () => { const optimalUtilization = SPOT_MARKET_RATE_PRECISION.div( new BN(2) ).toNumber(); // 50% utilization const optimalRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(20)).toNumber(); // 2000% APR const maxRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(50)).toNumber(); // 5000% APR const initialAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const initialLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); await admin.initializeSpotMarket( usdcMint.publicKey, optimalUtilization, optimalRate, maxRate, PublicKey.default, OracleSource.QUOTE_ASSET, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight ); await admin.updateWithdrawGuardThreshold( 0, new BN(10 ** 10).mul(QUOTE_PRECISION) ); await admin.fetchAccounts(); const spotMarket = await admin.getSpotMarketAccount(0); assert(spotMarket.poolId === 0); await admin.initializeSpotMarket( usdcMint.publicKey, optimalUtilization, optimalRate, maxRate, PublicKey.default, OracleSource.QUOTE_ASSET, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight, undefined, undefined, undefined, false ); await admin.updateSpotMarketPoolId(1, 1); await admin.updateSpotMarketStatus(1, MarketStatus.ACTIVE); await admin.updateWithdrawGuardThreshold( 0, new BN(10 ** 10).mul(QUOTE_PRECISION) ); await admin.fetchAccounts(); await admin.fetchAccounts(); const spotMarket1 = await admin.getSpotMarketAccount(1); assert(spotMarket1.poolId === 1); }); it('First User Deposit USDC', async () => { [firstUserDriftClient, firstUserDriftClientUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await sleep(100); await firstUserDriftClient.fetchAccounts(); await firstUserDriftClient.deposit( usdcAmount.divn(2), 0, firstUserDriftClientUSDCAccount ); try { await firstUserDriftClient.deposit( usdcAmount.divn(2), 1, firstUserDriftClientUSDCAccount ); assert(false); } catch (e) { assert(true); } }); it('Second User Deposit USDC', async () => { [secondUserDriftClient, secondUserDriftClientUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await secondUserDriftClient.updateUserPoolId([ { subAccountId: 0, poolId: 1 }, ]); await sleep(100); await secondUserDriftClient.fetchAccounts(); await secondUserDriftClient.deposit( usdcAmount.divn(2), 1, secondUserDriftClientUSDCAccount ); try { await secondUserDriftClient.deposit( usdcAmount.divn(2), 0, secondUserDriftClientUSDCAccount ); assert(false); } catch (e) { assert(true); } }); // it('Second User Deposit SOL', async () => { // [ // secondUserDriftClient, // secondUserDriftClientWSOLAccount, // secondUserDriftClientUSDCAccount, // ] = await createUserWithUSDCAndWSOLAccount( // bankrunContextWrapper, // usdcMint, // chProgram, // solAmount, // ZERO, // marketIndexes, // spotMarketIndexes, // oracleInfos, // bulkAccountLoader // ); // const marketIndex = 1; // const txSig = await secondUserDriftClient.deposit( // solAmount, // marketIndex, // secondUserDriftClientWSOLAccount // ); // bankrunContextWrapper.printTxLogs(txSig); // const spotMarket = await admin.getSpotMarketAccount(marketIndex); // assert(spotMarket.depositBalance.eq(SPOT_MARKET_BALANCE_PRECISION)); // console.log(spotMarket.historicalOracleData); // assert(spotMarket.historicalOracleData.lastOraclePriceTwapTs.gt(ZERO)); // assert( // spotMarket.historicalOracleData.lastOraclePrice.eq( // new BN(30 * PRICE_PRECISION.toNumber()) // ) // ); // assert( // spotMarket.historicalOracleData.lastOraclePriceTwap.eq( // new BN(30 * PRICE_PRECISION.toNumber()) // ) // ); // assert( // spotMarket.historicalOracleData.lastOraclePriceTwap5Min.eq( // new BN(30 * PRICE_PRECISION.toNumber()) // ) // ); // const vaultAmount = new BN( // ( // await bankrunContextWrapper.connection.getTokenAccount(spotMarket.vault) // ).amount.toString() // ); // assert(vaultAmount.eq(solAmount)); // const expectedBalance = getBalance( // solAmount, // spotMarket, // SpotBalanceType.DEPOSIT // ); // const spotPosition = // secondUserDriftClient.getUserAccount().spotPositions[1]; // assert(isVariant(spotPosition.balanceType, 'deposit')); // assert(spotPosition.scaledBalance.eq(expectedBalance)); // assert( // secondUserDriftClient // .getUserAccount() // .totalDeposits.eq(new BN(30).mul(PRICE_PRECISION)) // ); // }); // it('Second User Withdraw First half USDC', async () => { // const marketIndex = 0; // const withdrawAmount = usdcAmount.div(new BN(2)); // const txSig = await secondUserDriftClient.withdraw( // withdrawAmount, // marketIndex, // secondUserDriftClientUSDCAccount // ); // bankrunContextWrapper.printTxLogs(txSig); // const spotMarket = await admin.getSpotMarketAccount(marketIndex); // const expectedBorrowBalance = new BN(5000000001); // assert(spotMarket.borrowBalance.eq(expectedBorrowBalance)); // const vaultAmount = new BN( // ( // await bankrunContextWrapper.connection.getTokenAccount(spotMarket.vault) // ).amount.toString() // ); // const expectedVaultAmount = usdcAmount.sub(withdrawAmount); // assert(vaultAmount.eq(expectedVaultAmount)); // const expectedBalance = getBalance( // withdrawAmount, // spotMarket, // SpotBalanceType.BORROW // ); // const spotPosition = // secondUserDriftClient.getUserAccount().spotPositions[0]; // assert(isVariant(spotPosition.balanceType, 'borrow')); // assert(spotPosition.scaledBalance.eq(expectedBalance)); // const actualAmountWithdrawn = new BN( // ( // await bankrunContextWrapper.connection.getTokenAccount( // secondUserDriftClientUSDCAccount // ) // ).amount.toString() // ); // assert(withdrawAmount.eq(actualAmountWithdrawn)); // assert( // secondUserDriftClient.getUserAccount().totalWithdraws.eq(withdrawAmount) // ); // }); // it('Update Cumulative Interest with 50% utilization', async () => { // const usdcmarketIndex = 0; // const oldSpotMarketAccount = // firstUserDriftClient.getSpotMarketAccount(usdcmarketIndex); // await sleep(5000); // const txSig = await firstUserDriftClient.updateSpotMarketCumulativeInterest( // usdcmarketIndex // ); // bankrunContextWrapper.printTxLogs(txSig); // await firstUserDriftClient.fetchAccounts(); // const newSpotMarketAccount = // firstUserDriftClient.getSpotMarketAccount(usdcmarketIndex); // const expectedInterestAccumulated = calculateInterestAccumulated( // oldSpotMarketAccount, // newSpotMarketAccount.lastInterestTs // ); // const expectedCumulativeDepositInterest = // oldSpotMarketAccount.cumulativeDepositInterest.add( // expectedInterestAccumulated.depositInterest // ); // const expectedCumulativeBorrowInterest = // oldSpotMarketAccount.cumulativeBorrowInterest.add( // expectedInterestAccumulated.borrowInterest // ); // assert( // newSpotMarketAccount.cumulativeDepositInterest.eq( // expectedCumulativeDepositInterest // ) // ); // assert( // newSpotMarketAccount.cumulativeBorrowInterest.eq( // expectedCumulativeBorrowInterest // ) // ); // }); // it('Second User Withdraw second half USDC', async () => { // const marketIndex = 0; // let spotMarketAccount = // secondUserDriftClient.getSpotMarketAccount(marketIndex); // const spotMarketDepositTokenAmountBefore = getTokenAmount( // spotMarketAccount.depositBalance, // spotMarketAccount, // SpotBalanceType.DEPOSIT // ); // const spotMarketBorrowTokenAmountBefore = getTokenAmount( // spotMarketAccount.borrowBalance, // spotMarketAccount, // SpotBalanceType.BORROW // ); // const spotMarketBorrowBalanceBefore = spotMarketAccount.borrowBalance; // const userUSDCAmountBefore = new BN( // ( // await bankrunContextWrapper.connection.getTokenAccount( // secondUserDriftClientUSDCAccount // ) // ).amount.toString() // ); // const spotPositionBefore = // secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; // const withdrawAmount = spotMarketDepositTokenAmountBefore // .sub(spotMarketBorrowTokenAmountBefore) // .sub(ONE); // const txSig = await secondUserDriftClient.withdraw( // withdrawAmount, // marketIndex, // secondUserDriftClientUSDCAccount // ); // bankrunContextWrapper.printTxLogs(txSig); // spotMarketAccount = secondUserDriftClient.getSpotMarketAccount(marketIndex); // const increaseInspotPosition = getBalance( // withdrawAmount, // spotMarketAccount, // SpotBalanceType.BORROW // ); // const expectedspotPosition = spotPositionBefore.add(increaseInspotPosition); // console.log('withdrawAmount:', withdrawAmount.toString()); // assert( // secondUserDriftClient // .getSpotPosition(marketIndex) // .scaledBalance.eq(expectedspotPosition) // ); // const expectedUserUSDCAmount = userUSDCAmountBefore.add(withdrawAmount); // const userUSDCAmountAfter = new BN( // ( // await bankrunContextWrapper.connection.getTokenAccount( // secondUserDriftClientUSDCAccount // ) // ).amount.toString() // ); // assert(expectedUserUSDCAmount.eq(userUSDCAmountAfter)); // assert( // secondUserDriftClient // .getUserAccount() // .totalWithdraws.eq(userUSDCAmountAfter) // ); // const expectedSpotMarketBorrowBalance = spotMarketBorrowBalanceBefore.add( // increaseInspotPosition // ); // console.assert( // spotMarketAccount.borrowBalance.eq(expectedSpotMarketBorrowBalance) // ); // const expectedVaultBalance = usdcAmount.sub(expectedUserUSDCAmount); // const vaultUSDCAmountAfter = new BN( // ( // await bankrunContextWrapper.connection.getTokenAccount( // spotMarketAccount.vault // ) // ).amount.toString() // ); // assert(expectedVaultBalance.eq(vaultUSDCAmountAfter)); // const spotMarketDepositTokenAmountAfter = getTokenAmount( // spotMarketAccount.depositBalance, // spotMarketAccount, // SpotBalanceType.DEPOSIT // ); // const spotMarketBorrowTokenAmountAfter = getTokenAmount( // spotMarketAccount.borrowBalance, // spotMarketAccount, // SpotBalanceType.BORROW // ); // // TODO // console.log( // spotMarketDepositTokenAmountAfter.toString(), // spotMarketBorrowTokenAmountAfter.toString() // ); // assert( // spotMarketDepositTokenAmountAfter // .sub(spotMarketBorrowTokenAmountAfter) // .lte(ONE) // ); // }); // it('Update Cumulative Interest with 100% utilization', async () => { // const usdcmarketIndex = 0; // const oldSpotMarketAccount = // firstUserDriftClient.getSpotMarketAccount(usdcmarketIndex); // await sleep(5000); // const txSig = await firstUserDriftClient.updateSpotMarketCumulativeInterest( // usdcmarketIndex // ); // bankrunContextWrapper.printTxLogs(txSig); // await firstUserDriftClient.fetchAccounts(); // const newSpotMarketAccount = // firstUserDriftClient.getSpotMarketAccount(usdcmarketIndex); // const expectedInterestAccumulated = calculateInterestAccumulated( // oldSpotMarketAccount, // newSpotMarketAccount.lastInterestTs // ); // const expectedCumulativeDepositInterest = // oldSpotMarketAccount.cumulativeDepositInterest.add( // expectedInterestAccumulated.depositInterest // ); // const expectedCumulativeBorrowInterest = // oldSpotMarketAccount.cumulativeBorrowInterest.add( // expectedInterestAccumulated.borrowInterest // ); // assert( // newSpotMarketAccount.cumulativeDepositInterest.eq( // expectedCumulativeDepositInterest // ) // ); // console.log( // newSpotMarketAccount.cumulativeBorrowInterest.sub(ONE).toString(), // expectedCumulativeBorrowInterest.toString() // ); // // inconcistent time leads to slight differences over runs? // assert( // newSpotMarketAccount.cumulativeBorrowInterest // .sub(ONE) // .eq(expectedCumulativeBorrowInterest) || // newSpotMarketAccount.cumulativeBorrowInterest.eq( // expectedCumulativeBorrowInterest // ) // ); // }); // it('Flip second user borrow to deposit', async () => { // const marketIndex = 0; // const mintAmount = new BN(2 * 10 ** 6); // $2 // const userUSDCAmountBefore = new BN( // ( // await bankrunContextWrapper.connection.getTokenAccount( // secondUserDriftClientUSDCAccount // ) // ).amount.toString() // ); // await mintUSDCToUser( // usdcMint, // secondUserDriftClientUSDCAccount, // mintAmount, // bankrunContextWrapper // ); // const userBorrowBalanceBefore = // secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; // const spotMarketDepositBalanceBefore = // secondUserDriftClient.getSpotMarketAccount(marketIndex).depositBalance; // const depositAmount = userUSDCAmountBefore.add(mintAmount.div(new BN(2))); // const txSig = await secondUserDriftClient.deposit( // depositAmount, // marketIndex, // secondUserDriftClientUSDCAccount // ); // bankrunContextWrapper.printTxLogs(txSig); // await secondUserDriftClient.fetchAccounts(); // const spotMarketAccount = // secondUserDriftClient.getSpotMarketAccount(marketIndex); // const borrowToPayOff = getTokenAmount( // userBorrowBalanceBefore, // spotMarketAccount, // SpotBalanceType.BORROW // ); // const newDepositTokenAmount = depositAmount.sub(borrowToPayOff); // const expectedUserBalance = getBalance( // newDepositTokenAmount, // spotMarketAccount, // SpotBalanceType.DEPOSIT // ); // const userBalanceAfter = secondUserDriftClient.getSpotPosition(marketIndex); // console.log( // expectedUserBalance.toString(), // userBalanceAfter.scaledBalance.toString() // ); // assert(expectedUserBalance.eq(userBalanceAfter.scaledBalance)); // assert(isVariant(userBalanceAfter.balanceType, 'deposit')); // const expectedSpotMarketDepositBalance = // spotMarketDepositBalanceBefore.add(expectedUserBalance); // console.log( // spotMarketAccount.depositBalance.toString(), // expectedSpotMarketDepositBalance.toString() // ); // assert( // spotMarketAccount.depositBalance.eq(expectedSpotMarketDepositBalance) // ); // assert(spotMarketAccount.borrowBalance.eq(ZERO)); // }); // it('Flip second user deposit to borrow', async () => { // const marketIndex = 0; // const spotMarketAccountBefore = // secondUserDriftClient.getSpotMarketAccount(marketIndex); // const userDepositBalanceBefore = // secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; // const spotMarketDepositBalanceBefore = // secondUserDriftClient.getSpotMarketAccount(marketIndex).depositBalance; // const userDepositokenAmountBefore = getTokenAmount( // userDepositBalanceBefore, // spotMarketAccountBefore, // SpotBalanceType.DEPOSIT // ); // const borrowAmount = userDepositokenAmountBefore.add(new BN(1 * 10 ** 6)); // const txSig = await secondUserDriftClient.withdraw( // borrowAmount, // marketIndex, // secondUserDriftClientUSDCAccount // ); // bankrunContextWrapper.printTxLogs(txSig); // await secondUserDriftClient.fetchAccounts(); // const spotMarketAccount = // secondUserDriftClient.getSpotMarketAccount(marketIndex); // const depositToWithdrawAgainst = getTokenAmount( // userDepositBalanceBefore, // spotMarketAccount, // SpotBalanceType.DEPOSIT // ); // const newBorrowTokenAmount = borrowAmount.sub(depositToWithdrawAgainst); // const expectedUserBalance = getBalance( // newBorrowTokenAmount, // spotMarketAccount, // SpotBalanceType.BORROW // ); // const userBalanceAfter = secondUserDriftClient.getSpotPosition(marketIndex); // assert(expectedUserBalance.eq(userBalanceAfter.scaledBalance)); // assert(isVariant(userBalanceAfter.balanceType, 'borrow')); // const expectedSpotMarketDepositBalance = spotMarketDepositBalanceBefore.sub( // userDepositBalanceBefore // ); // assert( // spotMarketAccount.depositBalance.eq(expectedSpotMarketDepositBalance) // ); // assert(spotMarketAccount.borrowBalance.eq(expectedUserBalance)); // }); // it('Second user reduce only pay down borrow', async () => { // const marketIndex = 0; // const userUSDCAmountBefore = new BN( // ( // await bankrunContextWrapper.connection.getTokenAccount( // secondUserDriftClientUSDCAccount // ) // ).amount.toString() // ); // const currentUserBorrowBalance = // secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; // const spotMarketDepositBalanceBefore = // secondUserDriftClient.getSpotMarketAccount(marketIndex).depositBalance; // const depositAmount = userUSDCAmountBefore.mul(new BN(100000)); // huge number // const txSig = await secondUserDriftClient.deposit( // depositAmount, // marketIndex, // secondUserDriftClientUSDCAccount, // undefined, // true // ); // bankrunContextWrapper.printTxLogs(txSig); // const spotMarketAccountAfter = // secondUserDriftClient.getSpotMarketAccount(marketIndex); // const borrowToPayBack = getTokenAmount( // currentUserBorrowBalance, // spotMarketAccountAfter, // SpotBalanceType.BORROW // ); // const userUSDCAmountAfter = new BN( // ( // await bankrunContextWrapper.connection.getTokenAccount( // secondUserDriftClientUSDCAccount // ) // ).amount.toString() // ); // const expectedUserUSDCAmount = userUSDCAmountBefore.sub(borrowToPayBack); // console.log( // expectedUserUSDCAmount.toString(), // userUSDCAmountAfter.toString() // ); // assert(expectedUserUSDCAmount.eq(userUSDCAmountAfter)); // const userBalanceAfter = secondUserDriftClient.getSpotPosition(marketIndex); // assert(userBalanceAfter.scaledBalance.eq(ZERO)); // assert(spotMarketAccountAfter.borrowBalance.eq(ZERO)); // assert( // spotMarketAccountAfter.depositBalance.eq(spotMarketDepositBalanceBefore) // ); // }); // it('Second user reduce only withdraw deposit', async () => { // const marketIndex = 1; // const userWSOLAmountBefore = new BN( // ( // await bankrunContextWrapper.connection.getTokenAccount( // secondUserDriftClientWSOLAccount // ) // ).amount.toString() // ); // const currentUserDepositBalance = // secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; // const withdrawAmount = new BN(LAMPORTS_PER_SOL * 100); // const txSig = await secondUserDriftClient.withdraw( // withdrawAmount, // marketIndex, // secondUserDriftClientWSOLAccount, // true // ); // bankrunContextWrapper.printTxLogs(txSig); // const spotMarketAccountAfter = // secondUserDriftClient.getSpotMarketAccount(marketIndex); // const amountAbleToWithdraw = getTokenAmount( // currentUserDepositBalance, // spotMarketAccountAfter, // SpotBalanceType.DEPOSIT // ); // const userWSOLAmountAfter = new BN( // ( // await bankrunContextWrapper.connection.getTokenAccount( // secondUserDriftClientWSOLAccount // ) // ).amount.toString() // ); // const expectedUserWSOLAmount = // amountAbleToWithdraw.sub(userWSOLAmountBefore); // console.log(expectedUserWSOLAmount.toString()); // console.log(userWSOLAmountAfter.toString()); // assert(expectedUserWSOLAmount.eq(userWSOLAmountAfter)); // const userBalanceAfter = secondUserDriftClient.getSpotPosition(marketIndex); // assert(userBalanceAfter.scaledBalance.eq(ZERO)); // }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/multipleSpotMakerOrders.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { TestClient, BN, PRICE_PRECISION, PositionDirection, EventSubscriber, MarketStatus, BASE_PRECISION, isVariant, OracleSource, PEG_PRECISION, } from '../sdk/src'; import { createUserWithUSDCAccount, initializeQuoteSpotMarket, initializeSolSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, } from './testHelpers'; import { MARGIN_PRECISION, OrderType, SpotOperation } from '../sdk/src'; import { LAMPORTS_PER_SOL } from '@solana/web3.js'; import { ContractTier } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('multiple maker orders', () => { const chProgram = anchor.workspace.Drift as Program; let fillerDriftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(100000); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(100000 * 10 ** 6); let solUsd; let dogUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 100); dogUsd = await mockOracleNoProgram(bankrunContextWrapper, 0.6899, -4, 0); marketIndexes = [0, 1]; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; fillerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClient.initialize(usdcMint.publicKey, true); await fillerDriftClient.subscribe(); await initializeQuoteSpotMarket(fillerDriftClient, usdcMint.publicKey); await initializeSolSpotMarket(fillerDriftClient, solUsd); await fillerDriftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(60 * 60); // 1 HOUR await fillerDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(100 * PEG_PRECISION.toNumber()) ); await fillerDriftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); await fillerDriftClient.updatePerpMarketBaseSpread( 0, PRICE_PRECISION.toNumber() / 8 ); await fillerDriftClient.initializePerpMarket( 1, dogUsd, ammInitialBaseAssetReserve.div(new BN(100000)), ammInitialQuoteAssetReserve.div(new BN(100000)), periodicity, new BN(0.69 * PEG_PRECISION.toNumber()), OracleSource.PYTH, ContractTier.A, MARGIN_PRECISION.toNumber() / 4, // 4x MARGIN_PRECISION.toNumber() / 5 // 5x ); await fillerDriftClient.updatePerpMarketStatus(1, MarketStatus.ACTIVE); await fillerDriftClient.updatePerpMarketBaseSpread( 1, PRICE_PRECISION.toNumber() / 80 ); await fillerDriftClient.updatePerpMarketMarginRatio( 0, MARGIN_PRECISION.toNumber() / 2, MARGIN_PRECISION.toNumber() / 3 ); await fillerDriftClient.updatePerpMarketMaxSpread( 0, PRICE_PRECISION.toNumber() / 5 ); await fillerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const oneSol = new BN(LAMPORTS_PER_SOL); try { await fillerDriftClient.deposit( oneSol.muln(100), 1, bankrunContextWrapper.provider.wallet.publicKey ); } catch (e) { console.error(e); } await fillerDriftClient.updateSpotMarketPausedOperations( 1, SpotOperation.UPDATE_CUMULATIVE_INTEREST ); }); after(async () => { await fillerDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('taker long solUsd', async () => { const [takerDriftClient, takerUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClient.updateUserMarginTradingEnabled([ { marginTradingEnabled: true, subAccountId: 0, }, ]); await takerDriftClient.deposit(usdcAmount, 0, takerUSDCAccount); const [makerDriftClient, makerUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await makerDriftClient.deposit(usdcAmount, 0, makerUSDCAccount); await makerDriftClient.updateUserMarginTradingEnabled([ { marginTradingEnabled: true, subAccountId: 0, }, ]); for (let i = 0; i < 6; i++) { await makerDriftClient.placeSpotOrder({ marketIndex: 1, direction: PositionDirection.SHORT, price: new BN(95 + i).mul(PRICE_PRECISION), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); } const [secondMakerDriftClient, secondMakerUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await secondMakerDriftClient.deposit(usdcAmount, 0, secondMakerUSDCAccount); await secondMakerDriftClient.updateUserMarginTradingEnabled([ { marginTradingEnabled: true, subAccountId: 0, }, ]); for (let i = 0; i < 6; i++) { await secondMakerDriftClient.placeSpotOrder({ marketIndex: 1, direction: PositionDirection.SHORT, price: new BN(95 + i).mul(PRICE_PRECISION), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); } const takerBaseAssetAmount = new BN(6).mul(BASE_PRECISION); await takerDriftClient.placeSpotOrder({ marketIndex: 1, orderType: OrderType.LIMIT, price: new BN(100).mul(PRICE_PRECISION), direction: PositionDirection.LONG, baseAssetAmount: takerBaseAssetAmount, }); const makerInfo = [ { maker: await makerDriftClient.getUserAccountPublicKey(), makerUserAccount: makerDriftClient.getUserAccount(), makerStats: await makerDriftClient.getUserStatsAccountPublicKey(), }, { maker: await secondMakerDriftClient.getUserAccountPublicKey(), makerUserAccount: secondMakerDriftClient.getUserAccount(), makerStats: await secondMakerDriftClient.getUserStatsAccountPublicKey(), }, ]; const txSig = await fillerDriftClient.fillSpotOrder( await takerDriftClient.getUserAccountPublicKey(), takerDriftClient.getUserAccount(), takerDriftClient.getOrder(1), null, makerInfo, null, { computeUnits: 1400000, } ); bankrunContextWrapper.printTxLogs(txSig); const orderActionRecords = eventSubscriber .getEventsArray('OrderActionRecord') .filter((record) => isVariant(record.action, 'fill')); assert(orderActionRecords.length === 6); const takerQuoteAmount = takerDriftClient.getUser().getTokenAmount(0); const takerBaseAmount = takerDriftClient.getUser().getTokenAmount(1); assert(takerBaseAmount.eq(new BN(6000000000))); assert(takerQuoteAmount.eq(new BN(99423424000))); const makerQuoteAmount = makerDriftClient.getUser().getTokenAmount(0); const makerBaseAmount = makerDriftClient.getUser().getTokenAmount(1); assert(makerBaseAmount.eq(new BN(-3000000003))); assert(makerQuoteAmount.eq(new BN(100288057600))); const secondMakerQuoteAmount = secondMakerDriftClient .getUser() .getTokenAmount(0); const secondMakerBaseAmount = secondMakerDriftClient .getUser() .getTokenAmount(1); assert(secondMakerBaseAmount.eq(new BN(-3000000003))); assert(secondMakerQuoteAmount.eq(new BN(100288057600))); for (let i = 0; i < 3; i++) { await makerDriftClient.placeSpotOrder({ marketIndex: 1, direction: PositionDirection.LONG, price: new BN(101 - i).mul(PRICE_PRECISION), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); } console.log('here'); for (let i = 0; i < 3; i++) { await secondMakerDriftClient.placeSpotOrder({ marketIndex: 1, direction: PositionDirection.LONG, price: new BN(101 - i).mul(PRICE_PRECISION), orderType: OrderType.LIMIT, baseAssetAmount: BASE_PRECISION, }); } console.log('here2'); await setFeedPriceNoProgram(bankrunContextWrapper, 90, solUsd); await takerDriftClient.placeSpotOrder({ marketIndex: 1, orderType: OrderType.LIMIT, price: new BN(90).mul(PRICE_PRECISION), direction: PositionDirection.SHORT, baseAssetAmount: takerBaseAssetAmount, }); console.log('here3'); await fillerDriftClient.fetchAccounts(); const txSig2 = await fillerDriftClient.fillSpotOrder( await takerDriftClient.getUserAccountPublicKey(), takerDriftClient.getUserAccount(), takerDriftClient.getOrder(2), null, makerInfo, null, { computeUnits: 1400000, } ); bankrunContextWrapper.printTxLogs(txSig2); const takerPosition2 = takerDriftClient.getUser().getTokenAmount(1); console.log(takerPosition2.toString()); assert(takerPosition2.eq(new BN(0))); await takerDriftClient.unsubscribe(); await makerDriftClient.unsubscribe(); await secondMakerDriftClient.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/pythPull.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { OracleSource, TestClient, getPythPullOraclePublicKey, } from '../sdk/src'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; import { startAnchor } from 'solana-bankrun'; import { AccountInfo, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js'; import { DEFAULT_WORMHOLE_PROGRAM_ID } from '@pythnetwork/pyth-solana-receiver'; import { WORMHOLE_DATA } from './pythPullOracleData'; import { initializeQuoteSpotMarket, mockUSDCMint } from './testHelpers'; // set up account infos to load into banks client const GUARDIAN_SET_ACCOUNT_INFO: AccountInfo<Buffer> = { executable: false, lamports: LAMPORTS_PER_SOL, owner: DEFAULT_WORMHOLE_PROGRAM_ID, rentEpoch: 0, data: Buffer.from(WORMHOLE_DATA, 'base64'), }; const GUARDIAN_SET_KEY = new PublicKey( '5gxPdahvSzcKySxXxPuRXZZ9s6h8hZ88XDVKavWpaQGn' ); describe('pyth pull oracles', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; const feedId = '0x2f2d17abbc1e781bd87b4a5d52c8b2856886f5c482fa3593cebf6795040ab0b6'; const feedId2 = '0x8ac0c70fff57e9aefdf5edf44b51d62c2d433653cbb2cf5cc06bb115af04d221'; let feedAddress: PublicKey; before(async () => { // use bankrun builtin function to start solana program test const context = await startAnchor( '', [ { name: 'pyth_solana_receiver', programId: new PublicKey( 'G6EoTTTgpkNBtVXo96EQp2m6uwwVh2Kt6YidjkmQqoha' ), }, ], [ // load account infos into banks client like this { address: GUARDIAN_SET_KEY, info: GUARDIAN_SET_ACCOUNT_INFO, }, ] ); // wrap the context to use it with the test helpers bankrunContextWrapper = new BankrunContextWrapper(context); // don't use regular bulk account loader, use test bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); const feedIdBuffer = Uint8Array.from(Buffer.from(feedId, 'hex')); feedAddress = getPythPullOraclePublicKey(chProgram.programId, feedIdBuffer); driftClient = new TestClient({ // call toConnection to avoid annoying type error connection: bankrunContextWrapper.connection.toConnection(), // make sure to avoid regular `provider.X`, they don't show as errors wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [], spotMarketIndexes: [0], subAccountIds: [], // make sure to add [] for subaccounts or client will gpa oracleInfos: [ { publicKey: feedAddress, source: OracleSource.PYTH_PULL, }, ], // BANKRUN DOES NOT WORK WITH WEBSOCKET accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); }); after(async () => { await driftClient.unsubscribe(); }); it('init feed', async () => { const txsig = await driftClient.initializePythPullOracle(feedId); console.log(txsig); const txsig2 = await driftClient.initializePythPullOracle(feedId2); console.log(txsig2); }); it('post atomic', async () => { const vaa = 'UE5BVQEAAAADuAEAAAAEDQCGP2Fjz2LFIX48Qqm/paFzO/iEtFgH5sC1FHhNroyIC2fuzsISzz9IHbvBrlknA0UvM8r9UHSvsAwaqzquhzFsAALnhRblTgAMLanjq38YctnwqDsdV39WviJ0QAnWgRn+a2i4ljPkbVQl1+MM47qcsua4+1L6jo8i3LPMivVx+HQgAQRRADMkx28oGLPnNZnaZp8wtsxckjtx1GvXi+l9d89Yu1DJnYEGkVF4TzZSKtIQe+5OoUPAaIpnEauGVe0AEeh7AAYzopa5UFEUji5zKjTRRUxlQWAWDq3LuGMeV7osio6L/jyD0jMxpYMR0r/dqIdUi2a4GP0uF15k9yFMkANh7OCRAAgb/WNBqaYjLjZsqRqEFKbG3ZVR2vS5ph7EO6D8TKP2gg3Mk3Mhyr2O21KAboy061vKPbHTjX1w3dq8ipnz6EacAQpOpdNfjx1LhMu7ZaMfSM6IFqHOZnQqGxQOQHwh5lAd50Vj8LVu3rng211UchelGHtROvhN1IapTkVSEhD0dbeeAQs+IYIUBk8EahKpPnD0hk6E2d8ge3gKDcgakWgDhRMunArMASyVWkWw0N3p9FvOobXg4V4L5Tim6L1AhHf5Rj0YAAxsygUAwlhGQPEThxT72eY0HVbi8C1LATsBXrW6jksUNTllCqWWbRwgwDSlgibrk05BKtO1pjFCjkWRZZ+TCvrsAA05LnYl0RwpRYUs31y5Lbk8mZHrFDj02MkTC05rGcjVzmddlNcj5/IIp8Hc44GJFZ4XZO3kx7jW3vuF6RQm6RPmAA6xLKcvzZllJT8kxn/LI4AYUuCIOVyLMG/kVodeXWkOKSrkXr0SNwMFsLfl9xvPk2dCa7SyicGwMTUfKP4P8cyeAQ9Q5G4EDpPCq/A0J3luHRoCnSDpCuCu4zTzESAmRe80aSwDl7tN4wSn369Nu4iD6JSyUx/y3bHF7BgvlyGfQYHjABCZpnivKtKFNYpaLR627OKG//Vv3zol7gdCoMOXRcIxLhwSuhn5QlVHgeoOrHiLtOBlTzpz4bwa8btRxvU43pCgABK2TIKVKUnv5OyTjkQh8N5IMpaRK83UH3hpvsJKejNpJQK2zR/WfCkrYjy6pYQfhenZYHi4GCMQ0ALSh9cojaDlAGaVh0wAAAAAABrhAfrtrFhR4yubI7X5QRqMK6xKrj7U3XuBHdGnLqSqcQAAAAAEHJOLAUFVV1YAAAAAAAknGqgAACcQdoC/4vcjI21wyoVC1q3FUZH0FpwBAFUALy0Xq7weeBvYe0pdUsiyhWiG9cSC+jWTzr9nlQQKsLYAAAAAAICwNAAAAAAAAS4k////+AAAAABmlYdMAAAAAGaVh0sAAAAAAH6C+QAAAAAAAPFsCz2Sz2/hyAOSwCA+M8lRiOs+jGuZp6wcFR4rTAFuR2bAYNycVYQFeCxlkQJrEKDSba6FxQXgPZ7wBb/43EHuHHKQaaGb3NVsxnHFnLHefZDbF235q+aRnadgJfm6gqckqb0IczoHBaSuyrVYfSEbPuyNjXE7V++G/OwwVrwQOWqD6ti/nzLgnQ+qCVpEBto25YvZQzkmfYMKg1tJepxs/Sbgyx2fayAJtK8pRlJIixSTRbLiQX408KCq/ElVNzOSqt6Aw1KrAg81sLzKSjMEqnhbdFxgSzqncj8kPFw='; await driftClient.postPythPullOracleUpdateAtomic(vaa, feedId); }); it('post multi atomic', async () => { const vaa2 = 'UE5BVQEAAAADuAEAAAAEDQDPP3vBZtvwgUMxoM69PVRAwlNN0rbaATeIel0C04tK1AppR+bagz9IYDqmS/QD9VJAH3QoKkYubGufEUl/EGPLAAFz8UHK2WqkSuJ4bxqo8vgUFXmK029hf3ytn0QaN75Z0RloHWsufFdPDQugU1sX1XcGHfESCfdPBcyFUU0IcwPqAQKh4o/rYhf7/Hfg6Kn4WujXpd+KX2KsWoBJ5jV8wO35iRuMbrpBVk1cPsvPVMA/AQc53SThZfEnRWjQEqksacXuAQMin83DepWl5wh6Iw+ckpXvOO4TnVmi6Hp3omItcMYxiydLAvnH8rbPUprMMEgB3Jj+GZou05cvJRv2Emr2InD2AQR4osfpuVMe0pb28th0AqlYk75WYRVSUlIKEWeiPhDK60iGfk6s7bQDl0dJldO7rHzh+aHgVPQy5gLxFEDZnYBAAAZ17sK/vkD+ob8asZRtZjhZlihJTNKdFO1okvRQjk17Hz/ur1LO9cfm7oOBkwaB+GcztDNG7FL9vpBi3oRfHDTXAAnXTMZ5Akz9kySKeOgLAlsxGy0KWLTvInjfv3oqdIMqr2XPvev4xFmsR4FQYS4X6bAnNRt+gB+Ke1XwtEsdQJ8/AQs6qkwxe0VsLdCNVVJ5l5OO2LWYK8IEBFVjinqi3mallCvpx8u9k3Jr4KVFh7hekA+gyYSx5EEGAZBJ8oaq0DfgAQwSnHypODY9FnZCWZ4fuCYj/ahgJuI4edECp8Zvgb8u1w5iBR3vlbCzlCQsMe71A/ljwQGmEJVNHX716UOWVoPCAQ27k3uUpIaEiZfz6uCJSxPtl9flowhkXP0UIKRBsm+79F1vhr0yBguNgc7kNSA106V91BUDwr8qFJfIYzQjQ/GrAA7ocdrOsQqOiWI7Nx0/wZ/jhcY4u/yAgUTmxPsMzcStCRAKDQdMXIm3jrWyTi4xVyxAAHvOng5rvxQPtdTwocUYAQ++YSeIPyf+8sOmVyDqd5Oemx16Y5i3jt/KjMM4Imo6U25yW25rr+NuijnsRzB7lAOe02iQbeTLcOiV/VeF2MWRARLoGhQRHfuML6QGb9iaAMg9YM8373ZPAKivl8EQtb6RHwY/Ukv80N4PftCKLhzWyUWw8qtw+t58Z/xTKWkxgazxAGaVwckAAAAAABrhAfrtrFhR4yubI7X5QRqMK6xKrj7U3XuBHdGnLqSqcQAAAAAEHPbpAUFVV1YAAAAAAAknfksAACcQvESssFXSeYIMlIFj3+YaWZRicloCAFUALy0Xq7weeBvYe0pdUsiyhWiG9cSC+jWTzr9nlQQKsLYAAAAAAH5uPwAAAAAAALGm////+AAAAABmlcHJAAAAAGaVwcgAAAAAAH9qPgAAAAAAANFgC//c+vJ2Fng21c85lRU0S9fZ/SPOCWY+ONFaeYadHndmM8uif3P7a9yqh66xyq+c5FsbmzPMW4B0YIpxfhmXqtF/ZONLxiVVgziAHZgCfFThGFZWkpu+EhtNznDVRvu5e9G9dFeDtGKnHC4379MCRy5Y5dAPRBRySGopnaOAYyHHfGhHQwOdn0sd6RU+eOEA+C695m7vVG4AJffXuXCvBtaOdq1zCUyYu5c2StUSkchnvPO5rPH1qDOjYR3sR9guVi4N4VOBwBVQ4Oqz5sK3de0pP0GHbP8k5f0ghg0AVQCKwMcP/1fprv317fRLUdYsLUM2U8uyz1zAa7EVrwTSIQAAAABVoqk9AAAAAAAXGVr////4AAAAAGaVwckAAAAAZpXByQAAAABVsrWIAAAAAAAYkT0LatsRzxEFq/Jmcc8fxzgcTVMXMyjbLoq9P0rPyGy/wErpN6UxLaOn2tmBb6n20/3e88sqH41xuNmMQIXdVM1kku+uZVGpaGDPXapi9F+hN6nWax80mGcunX3PXSq5ziwrMjE30QzPwPds5Ie6R6X3qVChMT2VnJIqhQVTuYFKpLb9z1Wi8yolXfGAn8nR5y09glR1dGzKDBUV0v3rtP4qvFj9wMV9EU4EetEqD1b30myXBz+X8fWoM6NhHexH2C5WLg3hU4HAFVDg6rPmwrd17Sk/QYds/yTl/SCGDQ=='; await driftClient.postMultiPythPullOracleUpdatesAtomic(vaa2, [ feedId, feedId2, ]); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/tradingLP.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { BN, User, OracleSource, Wallet, MARGIN_PRECISION } from '../sdk'; import { Program } from '@coral-xyz/anchor'; import * as web3 from '@solana/web3.js'; import { TestClient, PRICE_PRECISION, PositionDirection, ZERO, OracleGuardRails, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } from './testHelpers'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; async function createNewUser( program, context: BankrunContextWrapper, usdcMint, usdcAmount, oracleInfos, wallet, bulkAccountLoader ) { let walletFlag = true; if (wallet == undefined) { const kp = new web3.Keypair(); await context.fundKeypair(kp, 10 ** 9); wallet = new Wallet(kp); walletFlag = false; } console.log('wallet:', walletFlag); const usdcAta = await mockUserUSDCAccount( usdcMint, usdcAmount, context, wallet.publicKey ); const driftClient = new TestClient({ connection: context.connection.toConnection(), wallet: wallet, programID: program.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0, 1], spotMarketIndexes: [0], subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); if (walletFlag) { await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); } else { await driftClient.subscribe(); } await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, usdcAta.publicKey ); const driftClientUser = new User({ // @ts-ignore driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); driftClientUser.subscribe(); return [driftClient, driftClientUser]; } describe('trading liquidity providing', () => { const chProgram = anchor.workspace.Drift as Program; // ammInvariant == k == x * y const ammInitialBaseAssetReserve = new BN(300).mul(new BN(1e13)); const ammInitialQuoteAssetReserve = new BN(300).mul(new BN(1e13)); const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const stableAmmInitialQuoteAssetReserve = new anchor.BN(1 * 10 ** 13).mul( mantissaSqrtScale ); const stableAmmInitialBaseAssetReserve = new anchor.BN(1 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(1_000_000_000 * 1e6); let driftClient: TestClient; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint: web3.Keypair; let driftClientUser: User; let traderDriftClient: TestClient; let traderDriftClientUser: User; let solusdc; let solusdc2; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); solusdc2 = await mockOracleNoProgram(bankrunContextWrapper, 1, -7); // make invalid solusdc = await mockOracleNoProgram(bankrunContextWrapper, 1, -7); // make invalid const oracleInfos = [ { publicKey: solusdc, source: OracleSource.PYTH }, { publicKey: solusdc2, source: OracleSource.PYTH }, ]; [driftClient, driftClientUser] = await createNewUser( chProgram, bankrunContextWrapper, usdcMint, usdcAmount, oracleInfos, bankrunContextWrapper.provider.wallet, bulkAccountLoader ); // used for trading / taking on baa await driftClient.initializePerpMarket( 0, solusdc, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, new BN(60 * 60) ); await driftClient.updateLpCooldownTime(new BN(0)); await driftClient.updatePerpMarketMaxFillReserveFraction(0, 1); await driftClient.updatePerpMarketStepSizeAndTickSize( 0, new BN(1), new BN(1) ); const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: new BN(1000000), oracleTwap5MinPercentDivergence: new BN(1000000), }, validity: { slotsBeforeStaleForAmm: new BN(10), slotsBeforeStaleForMargin: new BN(10), confidenceIntervalMaxSize: new BN(100), tooVolatileRatio: new BN(100), }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); // second market -- used for funding .. await driftClient.initializePerpMarket( 1, solusdc2, stableAmmInitialBaseAssetReserve, stableAmmInitialQuoteAssetReserve, new BN(0) ); await driftClient.updatePerpAuctionDuration(new BN(0)); await driftClient.updatePerpMarketMarginRatio( 0, MARGIN_PRECISION.toNumber() / 2, MARGIN_PRECISION.toNumber() / 4 ); [traderDriftClient, traderDriftClientUser] = await createNewUser( chProgram, bankrunContextWrapper, usdcMint, usdcAmount, oracleInfos, undefined, bulkAccountLoader ); }); after(async () => { await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); await traderDriftClient.unsubscribe(); await traderDriftClientUser.unsubscribe(); }); it('lp trades with short', async () => { let market = driftClient.getPerpMarketAccount(0); console.log('adding liquidity...'); const _sig = await driftClient.addPerpLpShares( new BN(100 * 1e13), market.marketIndex ); // some user goes long (lp should get a short) console.log('user trading...'); const tradeSize = new BN(40 * 1e13); const _txsig = await traderDriftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex ); await traderDriftClient.fetchAccounts(); const position = traderDriftClient.getUserAccount().perpPositions[0]; console.log( 'trader position:', position.baseAssetAmount.toString(), position.quoteAssetAmount.toString() ); assert(position.baseAssetAmount.gt(ZERO)); // settle says the lp would take on a short const lpPosition = driftClientUser.getPerpPositionWithLPSettle(0)[0]; console.log( 'sdk settled lp position:', lpPosition.baseAssetAmount.toString(), lpPosition.quoteAssetAmount.toString() ); assert(lpPosition.baseAssetAmount.lt(ZERO)); assert(lpPosition.quoteAssetAmount.gt(ZERO)); // lp trades a big long await driftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); // lp now has a long const newLpPosition = driftClientUser.getUserAccount().perpPositions[0]; console.log( 'lp position:', newLpPosition.baseAssetAmount.toString(), newLpPosition.quoteAssetAmount.toString() ); assert(newLpPosition.baseAssetAmount.gt(ZERO)); assert(newLpPosition.quoteAssetAmount.lt(ZERO)); // is still an lp assert(newLpPosition.lpShares.gt(ZERO)); market = driftClient.getPerpMarketAccount(0); console.log('done!'); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/updateAMM.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { BASE_PRECISION, BN, BulkAccountLoader, ContractTier, getMarketOrderParams, OracleSource, PEG_PRECISION, } from '../sdk'; import { Program } from '@coral-xyz/anchor'; import { TestClient, PRICE_PRECISION, AMM_RESERVE_PRECISION, QUOTE_PRECISION, calculateReservePrice, OracleGuardRails, calculateTradeSlippage, PositionDirection, EventSubscriber, convertToNumber, findComputeUnitConsumption, calculateBidAskPrice, calculateUpdatedAMM, } from '../sdk/src'; import { getFeedData, // initUserAccounts, mockOracle, mockUserUSDCAccount, mockUSDCMint, setFeedPrice, getOraclePriceData, initializeQuoteSpotMarket, } from './testHelpers'; async function feePoolInjection(fees, marketIndex, driftClient) { let market0 = driftClient.getPerpMarketAccount(marketIndex); await driftClient.updatePerpMarketCurveUpdateIntensity(marketIndex, 0); const connection = anchor.AnchorProvider.local().connection; while (market0.amm.totalFeeMinusDistributions.lt(fees)) { const reservePrice = calculateReservePrice( market0, driftClient.getOracleDataForPerpMarket(marketIndex) ); const baseAmountToTrade = new BN(9000) .mul(PRICE_PRECISION) .mul(BASE_PRECISION) .div(reservePrice); const tx = await driftClient.openPosition( PositionDirection.LONG, baseAmountToTrade, marketIndex ); console.log( 'tx logs', (await connection.getTransaction(tx, { commitment: 'confirmed' })).meta .logMessages ); // try to cancel remaining order try { await driftClient.cancelOrder(); } catch (e) { console.error(e); } await driftClient.closePosition(marketIndex); await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); market0 = driftClient.getPerpMarketAccount(marketIndex); console.log( market0.amm.totalFeeMinusDistributions.toString(), '<', fees.toString() ); } await driftClient.updatePerpMarketCurveUpdateIntensity(marketIndex, 100); } describe('update amm', () => { const provider = anchor.AnchorProvider.local(undefined, { preflightCommitment: 'confirmed', skipPreflight: false, commitment: 'confirmed', }); const connection = provider.connection; anchor.setProvider(provider); const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; const eventSubscriber = new EventSubscriber(connection, chProgram, { commitment: 'recent', }); eventSubscriber.subscribe(); const bulkAccountLoader = new BulkAccountLoader(connection, 'confirmed', 1); // let userAccountPublicKey: PublicKeys; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const ammInitialQuoteAssetAmount = new anchor.BN(9) .mul(AMM_RESERVE_PRECISION) .mul(AMM_RESERVE_PRECISION); const ammInitialBaseAssetAmount = new anchor.BN(9) .mul(AMM_RESERVE_PRECISION) .mul(AMM_RESERVE_PRECISION); const usdcAmount = new BN(10000 * 10 ** 6); let marketIndexes; let spotMarketIndexes; let oracleInfos; let solUsd; const mockOracles = []; before(async () => { usdcMint = await mockUSDCMint(provider); userUSDCAccount = await mockUserUSDCAccount(usdcMint, usdcAmount, provider); solUsd = await mockOracle(1); mockOracles.push(solUsd); for (let i = 1; i <= 4; i++) { // init more oracles const thisUsd = await mockOracle(i); mockOracles.push(thisUsd); } spotMarketIndexes = [0]; marketIndexes = mockOracles.map((_, i) => i); oracleInfos = mockOracles.map((oracle) => { return { publicKey: oracle, source: OracleSource.PYTH }; }); driftClient = new TestClient({ connection, wallet: provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, oracleInfos: oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await driftClient.updatePerpAuctionDuration(0); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); const periodicity = new BN(60 * 60); // 1 HOUR await driftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity, new BN(1 * PEG_PRECISION.toNumber()), undefined, ContractTier.A, 1000, 500, undefined, undefined, undefined, true, 2000, 5000 ); await driftClient.updatePerpMarketBaseSpread(0, 2000); await driftClient.updatePerpMarketCurveUpdateIntensity(0, 100); for (let i = 1; i <= 4; i++) { // init more markets const thisUsd = mockOracles[i]; await driftClient.initializePerpMarket( i, thisUsd, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity, new BN(i * PEG_PRECISION.toNumber()), undefined, ContractTier.A, 1000, 500, undefined, undefined, undefined, true, 2000, 5000 ); await driftClient.updatePerpMarketBaseSpread(i, 2000); await driftClient.updatePerpMarketCurveUpdateIntensity(i, 100); } const [, _userAccountPublicKey] = await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); }); after(async () => { await driftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('update AMM (balanced) move peg up to oracle', async () => { // console.log('hi'); const marketIndex = 0; const baseAssetAmount = new BN( (49.7450503674885 * AMM_RESERVE_PRECISION.toNumber()) / 50 ); const market0 = driftClient.getPerpMarketAccount(0); await setFeedPrice(anchor.workspace.Pyth, 1.003, solUsd); const curPrice = (await getFeedData(anchor.workspace.Pyth, solUsd)).price; console.log('new oracle price:', curPrice); const oraclePriceData = await getOraclePriceData( anchor.workspace.Pyth, solUsd ); const prepegAMM = calculateUpdatedAMM(market0.amm, oraclePriceData); const expectedPeg = new BN(1002999); console.log( prepegAMM.pegMultiplier.toString(), '==', expectedPeg.toString() ); assert(prepegAMM.pegMultiplier.eq(expectedPeg)); const estDist = prepegAMM.totalFee.sub( prepegAMM.totalFeeMinusDistributions ); console.log('est distribution:', estDist.toString()); const [_pctAvgSlippage, _pctMaxSlippage, _entryPrice, newPrice] = calculateTradeSlippage( PositionDirection.LONG, baseAssetAmount, market0, 'base', oraclePriceData ); const [bid, ask] = calculateBidAskPrice(market0.amm, oraclePriceData); console.log( 'bid/ask:', convertToNumber(bid), '/', convertToNumber(ask), 'after trade est. mark price:', convertToNumber(newPrice) ); const txSig = await driftClient.updateAMMs([marketIndex]); const computeUnits = await findComputeUnitConsumption( driftClient.program.programId, connection, txSig, 'confirmed' ); console.log('compute units', computeUnits); console.log( 'tx logs', (await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta .logMessages ); const market = driftClient.getPerpMarketAccount(0); const [bid1, ask1] = calculateBidAskPrice(market.amm, oraclePriceData); console.log( 'after trade bid/ask:', convertToNumber(bid1), '/', convertToNumber(ask1), 'after trade mark price:', convertToNumber(calculateReservePrice(market, oraclePriceData)) ); assert(bid1.lt(ask1)); assert(ask1.gt(oraclePriceData.price)); assert(bid1.lt(oraclePriceData.price)); const expectedPeg2 = new BN(1.003 * PEG_PRECISION.toNumber()); console.log( prepegAMM.pegMultiplier.toString(), '==', expectedPeg2.toString() ); assert(market.amm.pegMultiplier.eq(expectedPeg2)); const actualDist = market.amm.totalFee.sub( market.amm.totalFeeMinusDistributions ); console.log('actual distribution:', actualDist.toString()); console.log(prepegAMM.sqrtK.toString(), '==', market.amm.sqrtK.toString()); const marketInvariant = market.amm.sqrtK.mul(market.amm.sqrtK); // check k math good assert( marketInvariant .div(market.amm.baseAssetReserve) .eq(market.amm.quoteAssetReserve) ); assert( marketInvariant .div(market.amm.quoteAssetReserve) .eq(market.amm.baseAssetReserve) ); // check prepeg and post trade worked as expected assert(prepegAMM.sqrtK.eq(market.amm.sqrtK)); // predicted k = post trade k assert(actualDist.sub(estDist).abs().lte(new BN(1))); // cost is near equal assert(market.amm.sqrtK.eq(market0.amm.sqrtK)); // k was same }); it('update AMM (balanced) move peg down to oracle', async () => { // console.log('hi'); const marketIndex = 1; const baseAssetAmount = new BN( (49.7450503674885 * AMM_RESERVE_PRECISION.toNumber()) / 50 ); const market0 = driftClient.getPerpMarketAccount(1); await setFeedPrice(anchor.workspace.Pyth, 0.9378, mockOracles[1]); const curPrice = (await getFeedData(anchor.workspace.Pyth, mockOracles[1])) .price; console.log('new oracle price:', curPrice); const oraclePriceData = await getOraclePriceData( anchor.workspace.Pyth, mockOracles[1] ); const prepegAMM = calculateUpdatedAMM(market0.amm, oraclePriceData); console.log(prepegAMM.pegMultiplier.toString()); assert( prepegAMM.pegMultiplier.eq(new BN(0.9378 * PEG_PRECISION.toNumber())) ); const estDist = prepegAMM.totalFee.sub( prepegAMM.totalFeeMinusDistributions ); console.log('est distribution:', estDist.toString()); const [_pctAvgSlippage, _pctMaxSlippage, _entryPrice, newPrice] = calculateTradeSlippage( PositionDirection.LONG, baseAssetAmount, market0, 'base', oraclePriceData ); const [bid, ask] = calculateBidAskPrice(market0.amm, oraclePriceData); console.log( 'bid/ask:', convertToNumber(bid), '/', convertToNumber(ask), 'after trade est. mark price:', convertToNumber(newPrice) ); const txSig = await driftClient.updateAMMs([marketIndex]); const computeUnits = await findComputeUnitConsumption( driftClient.program.programId, connection, txSig, 'confirmed' ); console.log('compute units', computeUnits); console.log( 'tx logs', (await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta .logMessages ); const market = driftClient.getPerpMarketAccount(1); const [bid1, ask1] = calculateBidAskPrice(market.amm, oraclePriceData); console.log( 'after trade bid/ask:', convertToNumber(bid1), '/', convertToNumber(ask1), 'after trade mark price:', convertToNumber(calculateReservePrice(market, oraclePriceData)) ); assert(bid1.lt(ask1)); assert(ask1.gt(oraclePriceData.price)); assert(bid1.lt(oraclePriceData.price)); const expectedPeg2 = new BN(0.9378 * PEG_PRECISION.toNumber()); console.log( market.amm.pegMultiplier.toString(), '==', expectedPeg2.toString() ); assert(market.amm.pegMultiplier.eq(expectedPeg2)); const actualDist = market.amm.totalFee.sub( market.amm.totalFeeMinusDistributions ); console.log('actual distribution:', actualDist.toString()); console.log(prepegAMM.sqrtK.toString(), '==', market.amm.sqrtK.toString()); const marketInvariant = market.amm.sqrtK.mul(market.amm.sqrtK); // check k math good assert( marketInvariant .div(market.amm.baseAssetReserve) .eq(market.amm.quoteAssetReserve) ); assert( marketInvariant .div(market.amm.quoteAssetReserve) .eq(market.amm.baseAssetReserve) ); // check prepeg and post trade worked as expected assert(prepegAMM.sqrtK.eq(market.amm.sqrtK)); // predicted k = post trade k assert(actualDist.sub(estDist).abs().lte(new BN(1))); // cost is near equal assert(market.amm.sqrtK.eq(market0.amm.sqrtK)); // k was same }); it('update AMM (imbalanced, oracle > peg, sufficient fees)', async () => { const marketIndex = 1; await feePoolInjection( new BN(250 * QUOTE_PRECISION.toNumber()), 1, driftClient ); const market = driftClient.getPerpMarketAccount(marketIndex); const oraclePriceData = await getOraclePriceData( anchor.workspace.Pyth, mockOracles[marketIndex] ); const baseAssetAmount = new BN(1.02765 * AMM_RESERVE_PRECISION.toNumber()); const orderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, }); const [_pctAvgSlippage, _pctMaxSlippage, _entryPrice, newPrice] = calculateTradeSlippage( PositionDirection.LONG, baseAssetAmount, market, 'base', oraclePriceData ); const [bid, ask] = calculateBidAskPrice(market.amm, oraclePriceData); console.log( 'bid/ask:', convertToNumber(bid), '/', convertToNumber(ask), 'after trade est. mark price:', convertToNumber(newPrice) ); let txSig; try { txSig = await driftClient.placeAndTakePerpOrder(orderParams); } catch (e) { console.error(e); } console.log( 'tx logs', (await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta .logMessages ); await setFeedPrice(anchor.workspace.Pyth, 1.9378, mockOracles[marketIndex]); const curPrice = ( await getFeedData(anchor.workspace.Pyth, mockOracles[marketIndex]) ).price; console.log('new oracle price:', curPrice); const _txSig2 = await driftClient.updateAMMs([marketIndex]); const market2 = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market2.amm.pegMultiplier = ', market2.amm.pegMultiplier.toString() ); assert(market2.amm.pegMultiplier.eq(new BN(1937799))); assert( market2.amm.totalFeeMinusDistributions.gte( market.amm.totalFeeMinusDistributions.div(new BN(2)) ) ); }); it('Many market balanced prepegs, long position', async () => { const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: new BN(1000000), oracleTwap5MinPercentDivergence: new BN(1000000), }, validity: { slotsBeforeStaleForAmm: new BN(100), slotsBeforeStaleForMargin: new BN(100), confidenceIntervalMaxSize: new BN(100000), tooVolatileRatio: new BN(1000), }, // useForLiquidations: false, }; await driftClient.updateOracleGuardRails(oracleGuardRails); for (let i = 0; i <= 4; i++) { const thisUsd = mockOracles[i]; const marketIndex = i; const baseAssetAmount = new BN( 31.02765 * AMM_RESERVE_PRECISION.toNumber() ); const market0 = driftClient.getPerpMarketAccount(i); const orderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, }); const curPrice = (await getFeedData(anchor.workspace.Pyth, thisUsd)) .price; console.log('new oracle price:', curPrice); const oraclePriceData = await getOraclePriceData( anchor.workspace.Pyth, thisUsd ); const [_pctAvgSlippage, _pctMaxSlippage, _entryPrice, newPrice] = calculateTradeSlippage( PositionDirection.LONG, baseAssetAmount, market0, 'base', oraclePriceData ); const [bid, ask] = calculateBidAskPrice(market0.amm, oraclePriceData); console.log( 'bid/ask:', convertToNumber(bid), '/', convertToNumber(ask), 'after trade est. mark price:', convertToNumber(newPrice) ); let txSig; try { txSig = await driftClient.placeAndTakePerpOrder(orderParams); } catch (e) { console.error(e); } const computeUnits = await findComputeUnitConsumption( driftClient.program.programId, connection, txSig, 'confirmed' ); console.log('compute units', computeUnits); console.log( 'tx logs', (await connection.getTransaction(txSig, { commitment: 'confirmed' })) .meta.logMessages ); const market = driftClient.getPerpMarketAccount(i); const [bid1, ask1] = calculateBidAskPrice(market.amm, oraclePriceData); console.log( 'after trade bid/ask:', convertToNumber(bid1), '/', convertToNumber(ask1), 'after trade mark price:', convertToNumber(calculateReservePrice(market, oraclePriceData)) ); console.log('----'); } }); it('update AMMs (unbalanced, oracle > peg, cost > 0 and insufficient fees)', async () => { const prepegAMMs = []; const market0s = []; const tradeDirection = PositionDirection.SHORT; const tradeSize = AMM_RESERVE_PRECISION; for (let i = 0; i <= 4; i++) { const thisUsd = mockOracles[i]; const marketIndex = i; const market0 = driftClient.getPerpMarketAccount(marketIndex); market0s.push(market0); const curPrice = (await getFeedData(anchor.workspace.Pyth, thisUsd)) .price; await setFeedPrice(anchor.workspace.Pyth, curPrice * 1.02, thisUsd); const newPrice = (await getFeedData(anchor.workspace.Pyth, thisUsd)) .price; // const curPrice = (await getFeedData(anchor.workspace.Pyth, solUsd)).price; console.log('new oracle price:', newPrice); const oraclePriceData = await getOraclePriceData( anchor.workspace.Pyth, thisUsd ); const prepegAMM = calculateUpdatedAMM(market0.amm, oraclePriceData); prepegAMMs.push(prepegAMM); console.log('market', i, ':', prepegAMM.pegMultiplier.toString()); // assert(prepegAMM.pegMultiplier.eq(new BN(1006))); const estDist = prepegAMM.totalFee.sub( prepegAMM.totalFeeMinusDistributions ); console.log('est distribution:', estDist.toString()); // const [_pctAvgSlippage, _pctMaxSlippage, _entryPrice, newPrice] = // calculateTradeSlippage( // PositionDirection.LONG, // baseAssetAmount, // market0, // 'base', // oraclePriceData // ); const [bid, ask] = calculateBidAskPrice(market0.amm, oraclePriceData); console.log( 'bid/ask:', convertToNumber(bid), '/', convertToNumber(ask) // 'after trade est. mark price:', // convertToNumber(newPrice) ); } const orderParams = getMarketOrderParams({ marketIndex: 4, direction: tradeDirection, baseAssetAmount: tradeSize, }); const txSig21 = await driftClient.updateAMMs([0, 1, 2, 3]); const computeUnits21 = await findComputeUnitConsumption( driftClient.program.programId, connection, txSig21, 'confirmed' ); console.log(computeUnits21); const txSig3 = await driftClient.placeAndTakePerpOrder(orderParams); await driftClient.fetchAccounts(); console.log( 'tx logs', (await connection.getTransaction(txSig3, { commitment: 'confirmed' })) .meta.logMessages ); // check if markets were updated as expected for (let i = 0; i <= 4; i++) { const thisUsd = mockOracles[i]; const oraclePriceData = await getOraclePriceData( anchor.workspace.Pyth, thisUsd ); const market = driftClient.getPerpMarketAccount(i); const [bid1, ask1] = calculateBidAskPrice(market.amm, oraclePriceData); console.log( 'after trade bid/ask:', convertToNumber(bid1), '/', convertToNumber(ask1), 'after trade mark price:', convertToNumber(calculateReservePrice(market, oraclePriceData)) ); assert(bid1.lt(ask1)); assert(ask1.gt(oraclePriceData.price)); assert(bid1.lt(oraclePriceData.price)); const prepegAMM = prepegAMMs[i]; const market0 = market0s[i]; console.log(market.amm.pegMultiplier.toString()); if (i == 0) { assert(market.amm.pegMultiplier.eq(new BN(1020500))); } else if (i == 1) { assert( market.amm.pegMultiplier.eq( new BN(1.976555 * PEG_PRECISION.toNumber()) ) ); } else if (i == 2) { assert(market.amm.pegMultiplier.eq(new BN(2021060))); } else if (i == 3) { assert( market.amm.pegMultiplier.eq( new BN(3.03159 * PEG_PRECISION.toNumber()) ) ); } else if (i == 4) { assert(market.amm.pegMultiplier.eq(new BN(4042120))); } assert(market.amm.pegMultiplier.gt(market0.amm.pegMultiplier)); const actualDist = market.amm.totalFee.sub( market.amm.totalFeeMinusDistributions ); console.log('actual distribution:', actualDist.toString()); console.log( prepegAMM.sqrtK.toString(), '==', market.amm.sqrtK.toString() ); const marketInvariant = market.amm.sqrtK.mul(market.amm.sqrtK); // check k math good // TODO can be off by 1? console.log( marketInvariant.div(market.amm.baseAssetReserve).toString(), '==', market.amm.quoteAssetReserve.toString() ); assert( marketInvariant .div(market.amm.baseAssetReserve) .sub(market.amm.quoteAssetReserve) .abs() .lte(new BN(1)) ); console.log( marketInvariant.div(market.amm.quoteAssetReserve).toString(), '==', market.amm.baseAssetReserve.toString() ); assert( marketInvariant .div(market.amm.quoteAssetReserve) .sub(market.amm.baseAssetReserve) .abs() .lte(new BN(1)) ); const estDist = prepegAMM.totalFee.sub( prepegAMM.totalFeeMinusDistributions ); console.log('estDist:', estDist.toString()); // check prepeg and post trade worked as expected assert(prepegAMM.sqrtK.eq(market.amm.sqrtK)); // predicted k = post trade k // TODO: fix est cost rounding assert( actualDist .sub(estDist) .abs() .lte(market0.amm.pegMultiplier.sub(market.amm.pegMultiplier).abs()) ); // cost is near equal assert(prepegAMM.pegMultiplier.eq(market.amm.pegMultiplier)); if (i != 1) { assert(market.amm.sqrtK.lt(market0.amm.sqrtK)); // k was lowered } } }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/placeAndMakeSwiftPerpBankrun.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { AccountInfo, AddressLookupTableAccount, AddressLookupTableProgram, Connection, Keypair, LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction, TransactionInstruction, TransactionMessage, VersionedTransaction, } from '@solana/web3.js'; import { BN, PRICE_PRECISION, TestClient, PositionDirection, User, Wallet, EventSubscriber, BASE_PRECISION, getLimitOrderParams, OracleSource, OrderTriggerCondition, SwiftOrderParamsMessage, MarketType, getMarketOrderParams, loadKeypair, SwiftServerMessage, ANCHOR_TEST_SWIFT_ID, SwiftOrderRecord, getSwiftUserAccountPublicKey, digest, PYTH_LAZER_STORAGE_ACCOUNT_KEY, PTYH_LAZER_PROGRAM_ID, OrderType, ZERO, Order, getPythLazerOraclePublicKey, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpers'; import { getTriggerLimitOrderParams, PEG_PRECISION, PostOnlyParams, } from '../sdk/src'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; import dotenv from 'dotenv'; import { nanoid } from 'nanoid'; import { createHash } from 'crypto'; import { PYTH_LAZER_HEX_STRING_SOL, PYTH_STORAGE_DATA } from './pythLazerData'; dotenv.config(); const PYTH_STORAGE_ACCOUNT_INFO: AccountInfo<Buffer> = { executable: false, lamports: LAMPORTS_PER_SOL, owner: new PublicKey(PTYH_LAZER_PROGRAM_ID), rentEpoch: 0, data: Buffer.from(PYTH_STORAGE_DATA, 'base64'), }; describe('place and make swift order', () => { const chProgram = anchor.workspace.Drift as Program; if (!process.env.SWIFT_PRIVATE_KEY) { throw new Error('SWIFT_PRIVATE_KEY not set'); } let slot: BN; const swiftKeypair = loadKeypair(process.env.SWIFT_PRIVATE_KEY); let makerDriftClient: TestClient; let makerDriftClientUser: User; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(10 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(10 * 10 ** 13).mul( mantissaSqrtScale ); let usdcMint; let userUSDCAccount; const usdcAmount = new BN(10000 * 10 ** 6); let solUsd: PublicKey; let solUsdLazer: PublicKey; let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor( '', [], [ { address: PYTH_LAZER_STORAGE_ACCOUNT_KEY, info: PYTH_STORAGE_ACCOUNT_INFO, }, ] ); // @ts-ignore bankrunContextWrapper = new BankrunContextWrapper(context); slot = new BN( await bankrunContextWrapper.connection.toConnection().getSlot() ); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), // @ts-ignore chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 224.3); solUsdLazer = getPythLazerOraclePublicKey(chProgram.programId, 6); marketIndexes = [0]; spotMarketIndexes = [0, 1]; oracleInfos = [ { publicKey: solUsd, source: OracleSource.PYTH }, { publicKey: solUsdLazer, source: OracleSource.PYTH_LAZER }, ]; makerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, swiftID: new PublicKey(ANCHOR_TEST_SWIFT_ID), }); await makerDriftClient.initialize(usdcMint.publicKey, true); await makerDriftClient.subscribe(); await initializeQuoteSpotMarket(makerDriftClient, usdcMint.publicKey); const periodicity = new BN(0); await makerDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(224 * PEG_PRECISION.toNumber()) ); await makerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); makerDriftClientUser = new User({ driftClient: makerDriftClient, userAccountPublicKey: await makerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClientUser.subscribe(); }); after(async () => { await makerDriftClient.unsubscribe(); await makerDriftClientUser.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('makeSwiftOrder and reject bad orders', async () => { slot = new BN( await bankrunContextWrapper.connection.toConnection().getSlot() ); const [takerDriftClient, takerDriftClientUser] = await initializeNewTakerClientAndUser( bankrunContextWrapper, chProgram, usdcMint, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClientUser.fetchAccounts(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const takerOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount: baseAssetAmount.muln(2), price: new BN(224).mul(PRICE_PRECISION), auctionStartPrice: new BN(223).mul(PRICE_PRECISION), auctionEndPrice: new BN(224).mul(PRICE_PRECISION), auctionDuration: 10, userOrderId: 1, postOnly: PostOnlyParams.NONE, marketType: MarketType.PERP, }); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, takeProfitOrderParams: null, stopLossOrderParams: null, }; const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount: BASE_PRECISION, price: new BN(223).mul(PRICE_PRECISION), userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, immediateOrCancel: true, }); const takerOrderParamsSig = takerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage ); const swiftServerMessage: SwiftServerMessage = { slot, swiftOrderSignature: takerOrderParamsSig, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const encodedSwiftServerMessage = makerDriftClient.encodeSwiftServerMessage(swiftServerMessage); const swiftSignature = makerDriftClient.signMessage( digest(encodedSwiftServerMessage), swiftKeypair ); const txSig = await makerDriftClient.placeAndMakeSwiftPerpOrder( encodedSwiftServerMessage, swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, swiftServerMessage.uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), }, makerOrderParams ); const makerPosition = makerDriftClient.getUser().getPerpPosition(0); assert(makerPosition.baseAssetAmount.eq(BASE_PRECISION.neg())); const takerPosition = takerDriftClient.getUser().getPerpPosition(0); assert(takerPosition.baseAssetAmount.eq(BASE_PRECISION)); // Make sure that the event is in the logs const events = eventSubscriber.getEventsByTx(txSig); const event = events.find((event) => event.eventType == 'SwiftOrderRecord'); assert(event !== undefined); assert( (event as SwiftOrderRecord).hash == createHash('sha256') .update(Uint8Array.from(takerOrderParamsSig)) .digest('base64') ); await makerDriftClient.placeAndMakeSwiftPerpOrder( encodedSwiftServerMessage, swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, swiftServerMessage.uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), }, makerOrderParams ); const takerPositionAfter = takerDriftClient.getUser().getPerpPosition(0); const makerPositionAfter = makerDriftClient.getUser().getPerpPosition(0); assert(takerPositionAfter.baseAssetAmount.eq(baseAssetAmount.muln(2))); assert( makerPositionAfter.baseAssetAmount.eq(baseAssetAmount.muln(2).neg()) ); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); it('should work with pyth lazer crank and filling against vamm in one tx', async () => { const slot = new BN( await bankrunContextWrapper.connection.toConnection().getSlot() ); // Switch the oracle over to using pyth lazer await makerDriftClient.initializePythLazerOracle(6); await makerDriftClient.postPythLazerOracleUpdate( [6], PYTH_LAZER_HEX_STRING_SOL ); await makerDriftClient.postPythLazerOracleUpdate( [6], PYTH_LAZER_HEX_STRING_SOL ); await makerDriftClient.updatePerpMarketOracle( 0, solUsdLazer, OracleSource.PYTH_LAZER ); const [lookupTableInst, lookupTableAddress] = AddressLookupTableProgram.createLookupTable({ authority: makerDriftClient.wallet.publicKey, payer: makerDriftClient.wallet.publicKey, recentSlot: slot.toNumber() - 10, }); const extendInstruction = AddressLookupTableProgram.extendLookupTable({ payer: makerDriftClient.wallet.publicKey, authority: makerDriftClient.wallet.publicKey, lookupTable: lookupTableAddress, addresses: [ SystemProgram.programId, solUsd, solUsdLazer, ...makerDriftClient .getPerpMarketAccounts() .map((account) => account.pubkey), ...makerDriftClient .getPerpMarketAccounts() .map((account) => account.amm.oracle), ...makerDriftClient .getSpotMarketAccounts() .map((account) => account.pubkey), ...makerDriftClient .getSpotMarketAccounts() .map((account) => account.oracle), PYTH_LAZER_STORAGE_ACCOUNT_KEY, ], }); const tx = new Transaction().add(lookupTableInst).add(extendInstruction); await makerDriftClient.sendTransaction(tx); console.log(`Lookup table: ${lookupTableAddress.toBase58()}`); const [takerDriftClient, takerDriftClientUser] = await initializeNewTakerClientAndUser( bankrunContextWrapper, chProgram, usdcMint, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClientUser.fetchAccounts(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const takerOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, auctionStartPrice: new BN(223).mul(PRICE_PRECISION), auctionEndPrice: new BN(226).mul(PRICE_PRECISION), auctionDuration: 30, userOrderId: 1, postOnly: PostOnlyParams.NONE, }); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, takeProfitOrderParams: null, stopLossOrderParams: null, }; const takerOrderParamsSig = takerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage ); const uuid = nanoid(8); const swiftSlot = slot.subn(15); const swiftServerMessage: SwiftServerMessage = { slot: swiftSlot, swiftOrderSignature: takerOrderParamsSig, uuid: Uint8Array.from(Buffer.from(uuid)), }; const encodedSwiftServerMessage = takerDriftClient.encodeSwiftServerMessage(swiftServerMessage); const swiftSignature = takerDriftClient.signMessage( digest(encodedSwiftServerMessage), swiftKeypair ); // Get pyth lazer instruction const pythLazerCrankIxs = makerDriftClient.getPostPythLazerOracleUpdateIxs( [6], PYTH_LAZER_HEX_STRING_SOL, undefined, 1 ); const placeSwiftTakerOrderIxs = await makerDriftClient.getPlaceSwiftTakerPerpOrderIxs( encodedSwiftServerMessage, swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, takerOrderParams.marketIndex, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), } ); const swiftOrder: Order = { status: 'open', orderType: OrderType.MARKET, orderId: null, slot: swiftSlot, marketIndex: 0, marketType: MarketType.PERP, baseAssetAmount: takerOrderParams.baseAssetAmount, auctionDuration: takerOrderParams.auctionDuration!, auctionStartPrice: takerOrderParams.auctionStartPrice!, auctionEndPrice: takerOrderParams.auctionEndPrice!, immediateOrCancel: true, direction: takerOrderParams.direction, postOnly: false, oraclePriceOffset: takerOrderParams.oraclePriceOffset ?? 0, // Rest are not required for DLOB price: ZERO, maxTs: ZERO, triggerPrice: ZERO, triggerCondition: OrderTriggerCondition.ABOVE, existingPositionDirection: PositionDirection.LONG, reduceOnly: false, baseAssetAmountFilled: ZERO, quoteAssetAmountFilled: ZERO, quoteAssetAmount: ZERO, userOrderId: 0, }; const fillIx = await makerDriftClient.getFillPerpOrderIx( takerDriftClientUser.getUserAccountPublicKey(), takerDriftClientUser.getUserAccount(), swiftOrder, undefined, undefined, undefined, true ); const txMessage = new TransactionMessage({ payerKey: makerDriftClient.wallet.publicKey, recentBlockhash: (await makerDriftClient.connection.getLatestBlockhash()) .blockhash, instructions: [...pythLazerCrankIxs, ...placeSwiftTakerOrderIxs, fillIx], }); const lookupTableAccount = ( await bankrunContextWrapper.connection.getAddressLookupTable( lookupTableAddress ) ).value; const message = txMessage.compileToV0Message([lookupTableAccount]); const txSig = await makerDriftClient.connection.sendTransaction( new VersionedTransaction(message) ); console.log(txSig); await takerDriftClient.fetchAccounts(); assert( takerDriftClient .getUser() .getPerpPosition(0) .baseAssetAmount.eq(BASE_PRECISION) ); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); it('fills swift with trigger orders ', async () => { slot = new BN( await bankrunContextWrapper.connection.toConnection().getSlot() ); const [takerDriftClient, takerDriftClientUser] = await initializeNewTakerClientAndUser( bankrunContextWrapper, chProgram, usdcMint, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClientUser.fetchAccounts(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const takerOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, price: new BN(224).mul(PRICE_PRECISION), auctionStartPrice: new BN(223).mul(PRICE_PRECISION), auctionEndPrice: new BN(224).mul(PRICE_PRECISION), auctionDuration: 10, userOrderId: 1, postOnly: PostOnlyParams.NONE, marketType: MarketType.PERP, }); const stopLossTakerParams = getTriggerLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, price: new BN(220).mul(PRICE_PRECISION), triggerPrice: new BN(220).mul(PRICE_PRECISION), userOrderId: 2, triggerCondition: OrderTriggerCondition.BELOW, marketType: MarketType.PERP, }); const takeProfitTakerParams = getTriggerLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, price: new BN(240).mul(PRICE_PRECISION), triggerPrice: new BN(240).mul(PRICE_PRECISION), userOrderId: 3, triggerCondition: OrderTriggerCondition.ABOVE, marketType: MarketType.PERP, }); await takerDriftClientUser.fetchAccounts(); const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, price: new BN(223).mul(PRICE_PRECISION), postOnly: PostOnlyParams.MUST_POST_ONLY, immediateOrCancel: true, marketType: MarketType.PERP, }); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, stopLossOrderParams: { triggerPrice: stopLossTakerParams.triggerPrice, baseAssetAmount: stopLossTakerParams.baseAssetAmount, }, takeProfitOrderParams: { triggerPrice: takeProfitTakerParams.triggerPrice, baseAssetAmount: takeProfitTakerParams.baseAssetAmount, }, }; const takerOrderParamsSig = takerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage ); const swiftDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(swiftKeypair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); const swiftServerMessage: SwiftServerMessage = { slot, swiftOrderSignature: takerOrderParamsSig, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const encodedSwiftServerMessage = swiftDriftClient.encodeSwiftServerMessage(swiftServerMessage); const swiftSignature = swiftDriftClient.signMessage( digest(encodedSwiftServerMessage), swiftKeypair ); const ixs = await makerDriftClient.getPlaceAndMakeSwiftPerpOrderIxs( encodedSwiftServerMessage, swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, swiftServerMessage.uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), }, makerOrderParams ); /* Transaction size should be largest for filling with trigger orders w/ place and take Max size: 1232 We currently trade on sol market w/ sol oracle so would be better with LUT, so -64 bytes + 2 bytes We dont have referrers for maker so need to add 64 bytes We want to allow for positions to be full with maximally different markets for maker/taker and spot/perp, so add 30 bytes for market/oracle for taker and 30 bytes for maker Add 32 bytes for LUT size of transaction + 32 + 2 + 30 + 30 < 1232 */ assert(getSizeOfTransaction(ixs, false) < 1138); const tx = await makerDriftClient.buildTransaction(ixs); await makerDriftClient.sendTransaction(tx as Transaction); const makerPosition = makerDriftClient.getUser().getPerpPosition(0); assert(makerPosition.baseAssetAmount.eq(BASE_PRECISION.neg().muln(3))); const takerPosition = takerDriftClient.getUser().getPerpPosition(0); // All orders are placed and one is assert(takerPosition.baseAssetAmount.eq(BASE_PRECISION)); assert( takerDriftClient .getUser() .getOpenOrders() .some((order) => order.orderId == 2) ); assert( takerDriftClient .getUser() .getOpenOrders() .some((order) => order.orderId == 3) ); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); it('should fail if taker order is a limit order ', async () => { slot = new BN( await bankrunContextWrapper.connection.toConnection().getSlot() ); const [takerDriftClient, takerDriftClientUser] = await initializeNewTakerClientAndUser( bankrunContextWrapper, chProgram, usdcMint, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClientUser.fetchAccounts(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const takerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, price: new BN(224).mul(PRICE_PRECISION), auctionStartPrice: new BN(223).mul(PRICE_PRECISION), auctionEndPrice: new BN(224).mul(PRICE_PRECISION), auctionDuration: 10, userOrderId: 1, postOnly: PostOnlyParams.NONE, }); await takerDriftClientUser.fetchAccounts(); const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, price: new BN(223).mul(PRICE_PRECISION), postOnly: PostOnlyParams.MUST_POST_ONLY, immediateOrCancel: true, }); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, takeProfitOrderParams: null, stopLossOrderParams: null, }; const takerOrderParamsSig = takerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage ); const swiftServerMessage: SwiftServerMessage = { slot, swiftOrderSignature: takerOrderParamsSig, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const encodedSwiftServerMessage = takerDriftClient.encodeSwiftServerMessage(swiftServerMessage); const swiftSignature = takerDriftClient.signMessage( digest(encodedSwiftServerMessage), swiftKeypair ); try { await makerDriftClient.placeAndMakeSwiftPerpOrder( encodedSwiftServerMessage, swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, swiftServerMessage.uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), }, makerOrderParams ); } catch (e) { assert(e); } const takerPosition = takerDriftClient.getUser().getPerpPosition(0); assert(takerPosition == undefined); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); it('should work with off-chain auctions', async () => { const slot = new BN( await bankrunContextWrapper.connection.toConnection().getSlot() ); const [takerDriftClient, takerDriftClientUser] = await initializeNewTakerClientAndUser( bankrunContextWrapper, chProgram, usdcMint, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClientUser.fetchAccounts(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const takerOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, auctionStartPrice: new BN(223).mul(PRICE_PRECISION), auctionEndPrice: new BN(227).mul(PRICE_PRECISION), auctionDuration: 10, userOrderId: 1, postOnly: PostOnlyParams.NONE, }); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, takeProfitOrderParams: null, stopLossOrderParams: null, }; const takerOrderParamsSig = takerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage ); const swiftServerMessage: SwiftServerMessage = { slot: slot.subn(5), swiftOrderSignature: takerOrderParamsSig, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const encodedSwiftServerMessage = takerDriftClient.encodeSwiftServerMessage(swiftServerMessage); const swiftSignature = takerDriftClient.signMessage( digest(encodedSwiftServerMessage), swiftKeypair ); await makerDriftClient.placeSwiftTakerOrder( encodedSwiftServerMessage, swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, takerOrderParams.marketIndex, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), } ); assert(takerDriftClient.getOrderByUserId(1) !== undefined); assert(takerDriftClient.getOrderByUserId(1).slot.eq(slot.subn(5))); const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, price: new BN(225).mul(PRICE_PRECISION), postOnly: PostOnlyParams.MUST_POST_ONLY, immediateOrCancel: true, }); await makerDriftClient.placeAndMakeSwiftPerpOrder( encodedSwiftServerMessage, swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, swiftServerMessage.uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), }, makerOrderParams ); const takerPosition = takerDriftClient.getUser().getPerpPosition(0); assert(takerPosition.baseAssetAmount.eq(baseAssetAmount)); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); it('should fail if auction params are not set', async () => { slot = new BN( await bankrunContextWrapper.connection.toConnection().getSlot() ); const [takerDriftClient, takerDriftClientUser] = await initializeNewTakerClientAndUser( bankrunContextWrapper, chProgram, usdcMint, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClientUser.fetchAccounts(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const takerOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount: baseAssetAmount.muln(2), price: new BN(224).mul(PRICE_PRECISION), userOrderId: 1, postOnly: PostOnlyParams.NONE, marketType: MarketType.PERP, }); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, takeProfitOrderParams: null, stopLossOrderParams: null, }; const takerOrderParamsSig = takerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage ); const swiftServerMessage: SwiftServerMessage = { slot, swiftOrderSignature: takerOrderParamsSig, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const encodedSwiftServerMessage = makerDriftClient.encodeSwiftServerMessage(swiftServerMessage); const swiftSignature = makerDriftClient.signMessage( digest(encodedSwiftServerMessage), swiftKeypair ); try { await makerDriftClient.placeSwiftTakerOrder( encodedSwiftServerMessage, swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, 0, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), } ); assert.fail('Should have failed'); } catch (error) { assert(error.message.includes('custom program error: 0x1890')); } await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); it('should verify that auction params are not sanitized', async () => { slot = new BN( await bankrunContextWrapper.connection.toConnection().getSlot() ); const [takerDriftClient, takerDriftClientUser] = await initializeNewTakerClientAndUser( bankrunContextWrapper, chProgram, usdcMint, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClientUser.fetchAccounts(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const takerOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount: baseAssetAmount.muln(2), auctionStartPrice: new BN(223).mul(PRICE_PRECISION), auctionEndPrice: new BN(10000).mul(PRICE_PRECISION), auctionDuration: 50, userOrderId: 1, postOnly: PostOnlyParams.NONE, marketType: MarketType.PERP, }); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, takeProfitOrderParams: null, stopLossOrderParams: null, }; const takerOrderParamsSig = takerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage ); const swiftServerMessage: SwiftServerMessage = { slot, swiftOrderSignature: takerOrderParamsSig, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const encodedSwiftServerMessage = makerDriftClient.encodeSwiftServerMessage(swiftServerMessage); const swiftSignature = makerDriftClient.signMessage( digest(encodedSwiftServerMessage), swiftKeypair ); await makerDriftClient.placeSwiftTakerOrder( encodedSwiftServerMessage, swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, 0, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), } ); assert( takerDriftClientUser .getOrderByUserOrderId(1) .auctionEndPrice.eq(new BN(10000).mul(PRICE_PRECISION)) ); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); it('can let user delete their account', async () => { const [takerDriftClient, takerDriftClientUser] = await initializeNewTakerClientAndUser( bankrunContextWrapper, chProgram, usdcMint, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); await takerDriftClientUser.fetchAccounts(); const userAccountPubkey = await takerDriftClient.getUserAccountPublicKey(); await takerDriftClient.deleteSwiftUserOrders(); assert( (await checkIfAccountExists( takerDriftClient.connection, getSwiftUserAccountPublicKey( takerDriftClient.program.programId, userAccountPubkey ) )) == false ); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); }); async function initializeNewTakerClientAndUser( bankrunContextWrapper: BankrunContextWrapper, chProgram: Program, usdcMint: Keypair, usdcAmount: BN, marketIndexes: number[], spotMarketIndexes: number[], oracleInfos: { publicKey: PublicKey; source: OracleSource }[], bulkAccountLoader: TestBulkAccountLoader ): Promise<[TestClient, User]> { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); await sleep(1000); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const takerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], 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 ); return [takerDriftClient, takerDriftClientUser]; } export function getSizeOfTransaction( instructions: TransactionInstruction[], versionedTransaction = true, addressLookupTables: AddressLookupTableAccount[] = [] ): number { const programs = new Set<string>(); const signers = new Set<string>(); let accounts = new Set<string>(); instructions.map((ix) => { programs.add(ix.programId.toBase58()); accounts.add(ix.programId.toBase58()); ix.keys.map((key) => { if (key.isSigner) { signers.add(key.pubkey.toBase58()); } accounts.add(key.pubkey.toBase58()); }); }); const instruction_sizes: number = instructions .map( (ix) => 1 + getSizeOfCompressedU16(ix.keys.length) + ix.keys.length + getSizeOfCompressedU16(ix.data.length) + ix.data.length ) .reduce((a, b) => a + b, 0); let numberOfAddressLookups = 0; if (addressLookupTables.length > 0) { const lookupTableAddresses = addressLookupTables .map((addressLookupTable) => addressLookupTable.state.addresses.map((address) => address.toBase58()) ) .flat(); const totalNumberOfAccounts = accounts.size; accounts = new Set( [...accounts].filter((account) => !lookupTableAddresses.includes(account)) ); accounts = new Set([...accounts, ...programs, ...signers]); numberOfAddressLookups = totalNumberOfAccounts - accounts.size; } return ( getSizeOfCompressedU16(signers.size) + signers.size * 64 + // array of signatures 3 + getSizeOfCompressedU16(accounts.size) + 32 * accounts.size + // array of account addresses 32 + // recent blockhash getSizeOfCompressedU16(instructions.length) + instruction_sizes + // array of instructions (versionedTransaction ? 1 + getSizeOfCompressedU16(0) : 0) + (versionedTransaction ? 32 * addressLookupTables.length : 0) + (versionedTransaction && addressLookupTables.length > 0 ? 2 : 0) + numberOfAddressLookups ); } function getSizeOfCompressedU16(n: number) { return 1 + Number(n >= 128) + Number(n >= 16384); } export async function checkIfAccountExists( connection: Connection, account: PublicKey ): Promise<boolean> { try { const accountInfo = await connection.getAccountInfo(account); return accountInfo != null; } catch (e) { // Doesn't already exist return false; } }
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/liquidateSpot.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { PublicKey } from '@solana/web3.js'; import { TestClient, BN, OracleSource, ZERO, EventSubscriber, PRICE_PRECISION, getTokenAmount, SpotBalanceType, isVariant, User, QUOTE_PRECISION, convertToNumber, LIQUIDATION_PCT_PRECISION, } from '../sdk/src'; import { mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, createUserWithUSDCAndWSOLAccount, createWSolTokenAccountForUser, initializeSolSpotMarket, sleep, setFeedPriceNoProgram, } from './testHelpers'; import { PERCENTAGE_PRECISION } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('liquidate spot', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bankrunContextWrapper: BankrunContextWrapper; let bulkAccountLoader: TestBulkAccountLoader; let usdcMint; let userUSDCAccount; let userWSOLAccount; let liquidatorDriftClient: TestClient; let liquidatorDriftClientWSOLAccount: PublicKey; let solOracle: PublicKey; const usdcAmount = new BN(100 * 10 ** 6); let _throwaway: PublicKey; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); userWSOLAccount = await createWSolTokenAccountForUser( bankrunContextWrapper, // @ts-ignore bankrunContextWrapper.provider.wallet, ZERO ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 100); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [], spotMarketIndexes: [0, 1], subAccountIds: [], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await driftClient.updateInitialPctToLiquidate( LIQUIDATION_PCT_PRECISION.toNumber() ); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await initializeSolSpotMarket(driftClient, solOracle); const oracleGuardrails = await driftClient.getStateAccount() .oracleGuardRails; oracleGuardrails.priceDivergence.oracleTwap5MinPercentDivergence = new BN( 100 ).mul(PERCENTAGE_PRECISION); await driftClient.updateOracleGuardRails(oracleGuardrails); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const solAmount = new BN(1 * 10 ** 9); [liquidatorDriftClient, liquidatorDriftClientWSOLAccount, _throwaway] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount, usdcAmount, [], [0, 1], [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], bulkAccountLoader ); const marketIndex = 1; await liquidatorDriftClient.deposit( solAmount, marketIndex, liquidatorDriftClientWSOLAccount ); const solBorrow = new BN(5 * 10 ** 8); await driftClient.withdraw(solBorrow, 1, userWSOLAccount); }); after(async () => { await driftClient.unsubscribe(); await liquidatorDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('liquidate', async () => { const user = new User({ driftClient: driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await user.subscribe(); await driftClient.fetchAccounts(); const healthBefore100 = user.getHealth(); console.log('healthBefore100:', healthBefore100); assert(healthBefore100 == 45); console.log( 'spotLiquidationPrice:', convertToNumber( user.spotLiquidationPrice(user.getSpotPosition(1).marketIndex) ) ); await setFeedPriceNoProgram(bankrunContextWrapper, 179, solOracle); await sleep(1000); await driftClient.fetchAccounts(); await user.fetchAccounts(); const healthBefore179 = user.getHealth(); console.log('healthBefore179:', healthBefore179); assert(healthBefore179 == 2); console.log( 'spotLiquidationPrice:', convertToNumber( user.spotLiquidationPrice(user.getSpotPosition(1).marketIndex) ) ); let mtc = user.getTotalCollateral('Maintenance'); let mmr = user.getMaintenanceMarginRequirement(); console.log( '$', convertToNumber(mtc.sub(mmr), QUOTE_PRECISION), 'away from liq' ); await setFeedPriceNoProgram( bankrunContextWrapper, 179 + convertToNumber(mtc.sub(mmr), QUOTE_PRECISION) * (2 / 1.1 - 0.001), solOracle ); await sleep(1000); await driftClient.fetchAccounts(); await user.fetchAccounts(); mtc = user.getTotalCollateral('Maintenance'); mmr = user.getMaintenanceMarginRequirement(); console.log( '$', convertToNumber(mtc.sub(mmr), QUOTE_PRECISION), 'away from liq' ); const healthBefore181 = user.getHealth(); console.log('healthBefore181:', healthBefore181); assert(healthBefore181 == 0); console.log( 'spotLiquidationPrice:', convertToNumber( user.spotLiquidationPrice(user.getSpotPosition(1).marketIndex), PRICE_PRECISION ) ); await setFeedPriceNoProgram(bankrunContextWrapper, 190, solOracle); await sleep(1000); const spotMarketBefore = driftClient.getSpotMarketAccount(0); const spotMarket1Before = driftClient.getSpotMarketAccount(1); await driftClient.fetchAccounts(); await user.fetchAccounts(); const healthAfter = user.getHealth(); console.log('healthAfter:', healthAfter); assert(healthAfter == 0); await user.unsubscribe(); const txSig = await liquidatorDriftClient.liquidateSpot( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0, 1, new BN(6 * 10 ** 8) ); const computeUnits = bankrunContextWrapper.connection.findComputeUnitConsumption(txSig); console.log('compute units', computeUnits); bankrunContextWrapper.connection.printTxLogs(txSig); // assert(!driftClient.getUserAccount().isBeingLiquidated); // out of liq territory assert(driftClient.getUserAccount().status === 0); assert(driftClient.getUserAccount().nextLiquidationId === 2); assert( isVariant( driftClient.getUserAccount().spotPositions[0].balanceType, 'deposit' ) ); assert( driftClient.getUserAccount().spotPositions[0].scaledBalance.gt(ZERO) ); // assert( // driftClient.getUserAccount().spotPositions[1].scaledBalance.gt(new BN(2)) // ); // assert( // isVariant( // driftClient.getUserAccount().spotPositions[0].balanceType, // 'borrow' // ) // ); console.log( driftClient.getUserAccount().spotPositions[0].scaledBalance.toString() ); const liquidationRecord = eventSubscriber.getEventsArray('LiquidationRecord')[0]; assert(liquidationRecord.liquidationId === 1); assert(isVariant(liquidationRecord.liquidationType, 'liquidateSpot')); assert(liquidationRecord.liquidateSpot.assetPrice.eq(PRICE_PRECISION)); assert(liquidationRecord.liquidateSpot.assetMarketIndex === 0); console.log( 'asset transfer', liquidationRecord.liquidateSpot.assetTransfer.toString() ); // todo, why? console.log(liquidationRecord.liquidateSpot.assetTransfer.toString()); assert( liquidationRecord.liquidateSpot.liabilityPrice.eq( new BN(190).mul(PRICE_PRECISION) ) ); assert(liquidationRecord.liquidateSpot.liabilityMarketIndex === 1); console.log( 'liability transfer', liquidationRecord.liquidateSpot.liabilityTransfer.toString() ); // if fee costs 1/100th of liability transfer assert(liquidationRecord.liquidateSpot.ifFee.eq(new BN(0))); await driftClient.fetchAccounts(); const spotMarket = driftClient.getSpotMarketAccount(0); const spotMarket1 = driftClient.getSpotMarketAccount(1); console.log( 'usdc borrows in spotMarket:', getTokenAmount( spotMarketBefore.borrowBalance, spotMarketBefore, SpotBalanceType.BORROW ).toString(), '->', getTokenAmount( spotMarket.borrowBalance, spotMarket, SpotBalanceType.BORROW ).toString() ); console.log( 'usdc deposits in spotMarket:', getTokenAmount( spotMarketBefore.depositBalance, spotMarketBefore, SpotBalanceType.DEPOSIT ).toString(), '->', getTokenAmount( spotMarket.depositBalance, spotMarket, SpotBalanceType.DEPOSIT ).toString() ); console.log( 'sol borrows in spotMarket:', getTokenAmount( spotMarket1Before.borrowBalance, spotMarket1Before, SpotBalanceType.BORROW ).toString(), '->', getTokenAmount( spotMarket1.borrowBalance, spotMarket1, SpotBalanceType.BORROW ).toString() ); console.log( 'sol deposits in spotMarket:', getTokenAmount( spotMarket1Before.depositBalance, spotMarket1Before, SpotBalanceType.DEPOSIT ).toString(), '->', getTokenAmount( spotMarket1.depositBalance, spotMarket1, SpotBalanceType.DEPOSIT ).toString() ); const netBalanceBefore = spotMarket1Before.depositBalance.sub( spotMarket1Before.borrowBalance ); const netBalanceAfter = spotMarket1.depositBalance.sub( spotMarket1.borrowBalance ); console.log( 'netBalance:', netBalanceBefore.toString(), '->', netBalanceAfter.toString() ); assert(netBalanceBefore.sub(netBalanceAfter).lte(new BN(1245))); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/phoenixTest.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { Keypair, Transaction, PublicKey, SystemProgram, TransactionInstruction, Connection, AccountInfo, } from '@solana/web3.js'; import { createAssociatedTokenAccountInstruction, createMintToInstruction, getAssociatedTokenAddress, NATIVE_MINT, } from '@solana/spl-token'; import { BN, TestClient, EventSubscriber, OracleSource, OracleInfo, } from '../sdk/src'; import { initializeQuoteSpotMarket, initializeSolSpotMarket, mockOracleNoProgram, } from './testHelpers'; import { castNumberToSpotPrecision, getLimitOrderParams, getTokenAmount, isVariant, PositionDirection, PRICE_PRECISION, SpotBalanceType, Wallet, } from '../sdk'; import { deserializeMarketData, TokenConfig } from '@ellipsis-labs/phoenix-sdk'; import * as Phoenix from '@ellipsis-labs/phoenix-sdk'; import { assert } from 'chai'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; import { BankrunProvider } from 'anchor-bankrun'; import { seatAccountData, marketAccountData, baseVaultAccountData, quoteVaultAccountData, } from './phoenixTestAccountData'; const PHOENIX_MARKET: AccountInfo<Buffer> = { executable: false, lamports: 6066670080, owner: new PublicKey('PhoeNiXZ8ByJGLkxNfZRnkUfjvmuYqLR89jjFHGqdXY'), rentEpoch: 0, data: Buffer.from(marketAccountData, 'base64'), }; const PHOENIX_SEAT: AccountInfo<Buffer> = { executable: false, lamports: 1781760, owner: new PublicKey('PhoeNiXZ8ByJGLkxNfZRnkUfjvmuYqLR89jjFHGqdXY'), rentEpoch: 0, data: Buffer.from(seatAccountData, 'base64'), }; const PHOENIX_BASE_VAULT: AccountInfo<Buffer> = { executable: false, lamports: 2039280, owner: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), rentEpoch: 0, data: Buffer.from(baseVaultAccountData, 'base64'), }; const PHOENIX_QUOTE_VAULT: AccountInfo<Buffer> = { executable: false, lamports: 2039280, owner: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), rentEpoch: 0, data: Buffer.from(quoteVaultAccountData, 'base64'), }; const USDC_MINT: AccountInfo<Buffer> = { executable: false, lamports: 1461600, owner: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), rentEpoch: 157, data: Buffer.from( 'AQAAANuZX+JRadFByrm7upK6oB+fLh7OffTLKsBRkPN/zB+dAAAAAAAAAAAGAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==', 'base64' ), }; // DO NOT USE THIS PRIVATE KEY IN PRODUCTION // This key is the market authority as well as the market maker const god = Keypair.fromSeed( new Uint8Array([ 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, ]) ); // Hardcoded market address of SOL/USDC Phoenix market // This market is loaded at genesis const solMarketAddress = new PublicKey( 'HhHRvLFvZid6FD7C96H93F2MkASjYfYAx8Y2P8KMAr6b' ); const usdcMint = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const tokenConfig: TokenConfig[] = [ { name: 'USD Coin', symbol: 'USDC', mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', logoUri: 'https://raw.githubusercontent.com/solana-labs/token-list/main/assets/mainnet/EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v/logo.png', }, { name: 'Wrapped SOL', symbol: 'SOL', mint: 'So11111111111111111111111111111111111111112', logoUri: 'https://raw.githubusercontent.com/solana-labs/token-list/main/assets/mainnet/So11111111111111111111111111111111111111112/logo.png', }, ]; const createPhoenixClient = async ( connection: Connection ): Promise<Phoenix.Client> => { console.log('Creating Phoenix client'); const client = await Phoenix.Client.createWithoutConfig(connection, []); console.log('Phoenix client created'); client.tokenConfig = tokenConfig; console.log('Token config set'); await client.addMarket(solMarketAddress.toBase58()); console.log('Market added'); return client; }; const createTokenAccountInstructions = async ( provider: BankrunProvider, tokenMintAddress: PublicKey, owner?: PublicKey ): Promise<[PublicKey, TransactionInstruction]> => { owner = owner || provider.wallet.publicKey; const userTokenAccount = await getAssociatedTokenAddress( tokenMintAddress, owner ); const createAta = createAssociatedTokenAccountInstruction( provider.wallet.publicKey, userTokenAccount, owner, tokenMintAddress ); return [userTokenAccount, createAta]; }; const createWSOLAccount = async ( context: BankrunContextWrapper, mintAmount?: BN, owner?: PublicKey ): Promise<PublicKey> => { const tx = new Transaction(); const [userWSOLAccount, createAta] = await createTokenAccountInstructions( context.provider, NATIVE_MINT, owner ); if (mintAmount.gtn(0)) { const transferIx = SystemProgram.transfer({ fromPubkey: context.provider.wallet.publicKey, toPubkey: userWSOLAccount, lamports: mintAmount.toNumber(), }); tx.add(transferIx); } tx.add(createAta); await context.sendTransaction(tx); return userWSOLAccount; }; const createTokenAccountAndMintTokens = async ( context: BankrunContextWrapper, tokenMintAddress: PublicKey, mintAmount: BN, mintAuthority: Keypair, owner?: PublicKey ): Promise<PublicKey> => { const tx = new Transaction(); const [userTokenAccount, createAta] = await createTokenAccountInstructions( context.provider, tokenMintAddress, owner ); tx.add(createAta); const mintToUserAccountTx = await createMintToInstruction( tokenMintAddress, userTokenAccount, mintAuthority.publicKey, mintAmount.toNumber() ); tx.add(mintToUserAccountTx); tx.recentBlockhash = (await context.getLatestBlockhash()).toString(); tx.feePayer = mintAuthority.publicKey; tx.sign(context.provider.wallet.payer, mintAuthority); await context.connection.sendTransaction(tx); return userTokenAccount; }; describe('phoenix spot market', () => { const driftProgram = anchor.workspace.Drift as Program; let phoenixClient: Phoenix.Client; let takerUsdcTokenAccount: PublicKey; let makerUsdcTokenAccount: PublicKey; let takerWrappedSolTokenAccount: PublicKey; let makerWrappedSolTokenAccount: PublicKey; let makerDriftClient: TestClient; let takerDriftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let solOracle: PublicKey; // 200 USDC const usdcAmount = new BN(200 * 10 ** 6); // 2 SOL const solAmount = new BN(2 * 10 ** 9); let marketIndexes: number[]; let spotMarketIndexes: number[]; let oracleInfos: OracleInfo[]; const solSpotMarketIndex = 1; before(async () => { const context = await startAnchor( '', [ { name: 'phoenix_dex', programId: new PublicKey( 'PhoeNiXZ8ByJGLkxNfZRnkUfjvmuYqLR89jjFHGqdXY' ), }, ], [ { address: new PublicKey( 'HhHRvLFvZid6FD7C96H93F2MkASjYfYAx8Y2P8KMAr6b' ), info: PHOENIX_MARKET, }, { address: new PublicKey( 'GDqLPXfwDHXnqwfqtEJmqovA4KEy9XhoZxkg3MVyFK9N' ), info: PHOENIX_SEAT, }, { address: new PublicKey( 'EyZsJZJWXuix6Zgw34JXb2fAbF4d62nfUgp4tzZBPxhW' ), info: PHOENIX_BASE_VAULT, }, { address: new PublicKey( 'B9SETfVeH1vx7sEJ7v41CRJncJnpMpGxHg4Mztc3sZKX' ), info: PHOENIX_QUOTE_VAULT, }, { address: new PublicKey( 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' ), info: USDC_MINT, }, ] ); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), driftProgram ); await eventSubscriber.subscribe(); console.log('Event subscriber created'); const val = await bankrunContextWrapper.connection.getAccountInfo( solMarketAddress ); console.log(val); deserializeMarketData(val.data); console.log('here'); phoenixClient = await createPhoenixClient( bankrunContextWrapper.connection.toConnection() ); console.log('Phoenix client created'); const phoenixMarket = phoenixClient.markets.get( solMarketAddress.toBase58() ); assert(phoenixMarket.data.header.authority.equals(god.publicKey)); assert(phoenixMarket.data.traders.has(god.publicKey.toBase58())); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 100); marketIndexes = []; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solOracle, source: OracleSource.PYTH }]; // Top-up god key's SOL balance await bankrunContextWrapper.fundKeypair(god, 10 * 10 ** 9); makerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(god), programID: driftProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClient.initialize(usdcMint, true); await makerDriftClient.subscribe(); await makerDriftClient.initializeUserAccount(); await initializeQuoteSpotMarket(makerDriftClient, usdcMint); await initializeSolSpotMarket(makerDriftClient, solOracle); await makerDriftClient.updateSpotMarketStepSizeAndTickSize( 1, new BN(100000000), new BN(100) ); await makerDriftClient.updateSpotAuctionDuration(0); takerUsdcTokenAccount = await createTokenAccountAndMintTokens( bankrunContextWrapper, usdcMint, usdcAmount, god ); makerUsdcTokenAccount = await createTokenAccountAndMintTokens( bankrunContextWrapper, usdcMint, usdcAmount, god, god.publicKey ); takerWrappedSolTokenAccount = await createWSOLAccount( bankrunContextWrapper, solAmount ); makerWrappedSolTokenAccount = await createWSOLAccount( bankrunContextWrapper, solAmount, god.publicKey ); console.log("Minted tokens for maker and taker's accounts"); console.log('taker USDC token account', takerUsdcTokenAccount.toString()); console.log('maker USDC token account', makerUsdcTokenAccount.toString()); console.log( 'taker WSOL token account', takerWrappedSolTokenAccount.toString() ); console.log( 'maker WSOL token account', makerWrappedSolTokenAccount.toString() ); takerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: driftProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await takerDriftClient.subscribe(); await takerDriftClient.initializeUserAccount(); await takerDriftClient.deposit(usdcAmount, 0, takerUsdcTokenAccount); }); after(async () => { await takerDriftClient.unsubscribe(); await makerDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('Add Phoenix Market', async () => { await makerDriftClient.initializePhoenixFulfillmentConfig( solSpotMarketIndex, solMarketAddress ); }); it('Fill bid', async () => { const baseAssetAmount = castNumberToSpotPrecision( 1, makerDriftClient.getSpotMarketAccount(solSpotMarketIndex) ); await takerDriftClient.placeSpotOrder( getLimitOrderParams({ marketIndex: solSpotMarketIndex, direction: PositionDirection.LONG, baseAssetAmount, userOrderId: 1, price: new BN(100).mul(PRICE_PRECISION), }) ); await takerDriftClient.fetchAccounts(); const spotOrder = takerDriftClient.getOrderByUserId(1); assert(isVariant(spotOrder.marketType, 'spot')); assert(spotOrder.baseAssetAmount.eq(baseAssetAmount)); const askOrderPacket: Phoenix.OrderPacket = { __kind: 'PostOnly', side: Phoenix.Side.Ask, priceInTicks: Phoenix.toBN( phoenixClient.floatPriceToTicks(100.0, solMarketAddress.toString()) ), numBaseLots: Phoenix.toBN( phoenixClient.rawBaseUnitsToBaseLotsRoundedDown( 1, solMarketAddress.toString() ) ), clientOrderId: Phoenix.toBN(2), rejectPostOnly: false, useOnlyDepositedFunds: false, lastValidSlot: null, lastValidUnixTimestampInSeconds: null, }; const placeAskInstruction = phoenixClient.createPlaceLimitOrderInstruction( askOrderPacket, solMarketAddress.toString(), god.publicKey ); const tx = new Transaction().add(placeAskInstruction); tx.recentBlockhash = ( await bankrunContextWrapper.getLatestBlockhash() ).toString(); tx.feePayer = god.publicKey; tx.sign(god); const placeTxId = await bankrunContextWrapper.connection.sendTransaction( tx ); bankrunContextWrapper.printTxLogs(placeTxId); await phoenixClient.refreshAllMarkets(); const phoenixFulfillmentConfigAccount = await makerDriftClient.getPhoenixV1FulfillmentConfig(solMarketAddress); const txSig = await makerDriftClient.fillSpotOrder( await takerDriftClient.getUserAccountPublicKey(), takerDriftClient.getUserAccount(), takerDriftClient.getOrderByUserId(1), phoenixFulfillmentConfigAccount ); await eventSubscriber.awaitTx(txSig); bankrunContextWrapper.printTxLogs(txSig); await takerDriftClient.fetchAccounts(); const takerQuoteSpotBalance = takerDriftClient.getSpotPosition(0); const takerBaseSpotBalance = takerDriftClient.getSpotPosition(1); const quoteTokenAmount = getTokenAmount( takerQuoteSpotBalance.scaledBalance, takerDriftClient.getQuoteSpotMarketAccount(), takerQuoteSpotBalance.balanceType ); console.log(quoteTokenAmount.toString()); assert(quoteTokenAmount.eq(new BN(99899999))); const baseTokenAmount = getTokenAmount( takerBaseSpotBalance.scaledBalance, takerDriftClient.getSpotMarketAccount(1), takerBaseSpotBalance.balanceType ); assert(baseTokenAmount.eq(new BN(1000000000))); const takerOrder = takerDriftClient.getUserAccount().orders[0]; assert(isVariant(takerOrder.status, 'init')); const orderActionRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert(isVariant(orderActionRecord.action, 'fill')); assert(orderActionRecord.baseAssetAmountFilled.eq(new BN(1000000000))); assert(orderActionRecord.quoteAssetAmountFilled.eq(new BN(100000000))); assert(orderActionRecord.takerFee.eq(new BN(100000))); await makerDriftClient.fetchAccounts(); assert(makerDriftClient.getQuoteAssetTokenAmount().eq(new BN(11800))); const solSpotMarket = takerDriftClient.getSpotMarketAccount(solSpotMarketIndex); assert(solSpotMarket.totalSpotFee.eq(new BN(68200))); const spotFeePoolAmount = getTokenAmount( solSpotMarket.spotFeePool.scaledBalance, takerDriftClient.getQuoteSpotMarketAccount(), SpotBalanceType.DEPOSIT ); // The spot fee pool at this point should be equal to the taker fee - the keeper fee - the spot fulfillment method fee console.log('Spot fee pool balance', spotFeePoolAmount.toNumber() / 1e6); assert( spotFeePoolAmount.eq( new BN( orderActionRecord.takerFee .sub(makerDriftClient.getQuoteAssetTokenAmount()) .sub(orderActionRecord.spotFulfillmentMethodFee) ) ) ); const phoenixMarketStart = phoenixClient.markets.get( solMarketAddress.toString() ).data; await phoenixClient.refreshAllMarkets(); const phoenixMarketEnd = phoenixClient.markets.get( solMarketAddress.toString() ).data; // Verify that there are no orders on the book after the fill assert(phoenixMarketStart.asks.length > 0); assert(phoenixMarketEnd.asks.length === 0); // Verify that the recorded fee from Drift is the same as Phoenix assert( phoenixClient.quoteLotsToQuoteAtoms( phoenixMarketEnd.unclaimedQuoteLotFees - phoenixMarketStart.unclaimedQuoteLotFees, solMarketAddress.toBase58() ) === orderActionRecord.spotFulfillmentMethodFee.toNumber() ); }); it('Fill ask', async () => { const solSpotMarketStart = takerDriftClient.getSpotMarketAccount(solSpotMarketIndex); const spotFeePoolAmountStart = getTokenAmount( solSpotMarketStart.spotFeePool.scaledBalance, takerDriftClient.getQuoteSpotMarketAccount(), SpotBalanceType.DEPOSIT ); const baseAssetAmount = castNumberToSpotPrecision( 1, makerDriftClient.getSpotMarketAccount(solSpotMarketIndex) ); const makerQuoteTokenAmountStart = makerDriftClient.getQuoteAssetTokenAmount(); await takerDriftClient.placeSpotOrder( getLimitOrderParams({ marketIndex: solSpotMarketIndex, direction: PositionDirection.SHORT, baseAssetAmount, userOrderId: 1, price: new BN(100).mul(PRICE_PRECISION), }) ); await takerDriftClient.fetchAccounts(); const spotOrder = takerDriftClient.getOrderByUserId(1); assert(isVariant(spotOrder.marketType, 'spot')); assert(spotOrder.baseAssetAmount.eq(baseAssetAmount)); await phoenixClient.refreshAllMarkets(); const askOrderPacket: Phoenix.OrderPacket = { __kind: 'PostOnly', side: Phoenix.Side.Bid, priceInTicks: Phoenix.toBN( phoenixClient.floatPriceToTicks(100.0, solMarketAddress.toString()) ), numBaseLots: Phoenix.toBN( phoenixClient.rawBaseUnitsToBaseLotsRoundedDown( 1, solMarketAddress.toString() ) ), clientOrderId: Phoenix.toBN(2), rejectPostOnly: false, useOnlyDepositedFunds: false, lastValidSlot: null, lastValidUnixTimestampInSeconds: null, }; const placeAskInstruction = phoenixClient.createPlaceLimitOrderInstruction( askOrderPacket, solMarketAddress.toString(), god.publicKey ); const tx = new Transaction().add(placeAskInstruction); tx.recentBlockhash = ( await bankrunContextWrapper.getLatestBlockhash() ).toString(); tx.feePayer = god.publicKey; tx.sign(god); const placeTxId = await bankrunContextWrapper.connection.sendTransaction( tx ); bankrunContextWrapper.printTxLogs(placeTxId); await phoenixClient.refreshAllMarkets(); const phoenixFulfillmentConfigAccount = await makerDriftClient.getPhoenixV1FulfillmentConfig(solMarketAddress); const txSig = await makerDriftClient.fillSpotOrder( await takerDriftClient.getUserAccountPublicKey(), takerDriftClient.getUserAccount(), takerDriftClient.getOrderByUserId(1), phoenixFulfillmentConfigAccount ); await eventSubscriber.awaitTx(txSig); bankrunContextWrapper.printTxLogs(txSig); await takerDriftClient.fetchAccounts(); const takerQuoteSpotBalance = takerDriftClient.getSpotPosition(0); const takerBaseSpotBalance = takerDriftClient.getSpotPosition(1); const quoteTokenAmount = getTokenAmount( takerQuoteSpotBalance.scaledBalance, takerDriftClient.getQuoteSpotMarketAccount(), takerQuoteSpotBalance.balanceType ); console.log(quoteTokenAmount.toString()); assert(quoteTokenAmount.eq(new BN(199799999))); const baseTokenAmount = getTokenAmount( takerBaseSpotBalance.scaledBalance, takerDriftClient.getSpotMarketAccount(1), takerBaseSpotBalance.balanceType ); assert(baseTokenAmount.eq(new BN(0))); const takerOrder = takerDriftClient.getUserAccount().orders[0]; assert(isVariant(takerOrder.status, 'init')); const orderActionRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert(isVariant(orderActionRecord.action, 'fill')); assert(orderActionRecord.baseAssetAmountFilled.eq(new BN(1000000000))); assert(orderActionRecord.quoteAssetAmountFilled.eq(new BN(100000000))); assert(orderActionRecord.takerFee.eq(new BN(100000))); const keeperFee = new BN( makerDriftClient .getQuoteAssetTokenAmount() .sub(makerQuoteTokenAmountStart) ); assert(keeperFee.eq(new BN(11800))); const solSpotMarket = takerDriftClient.getSpotMarketAccount(solSpotMarketIndex); assert(solSpotMarket.totalSpotFee.eq(new BN(136400))); const spotFeePoolAmount = getTokenAmount( solSpotMarket.spotFeePool.scaledBalance, takerDriftClient.getQuoteSpotMarketAccount(), SpotBalanceType.DEPOSIT ); assert( spotFeePoolAmount.eq( new BN(spotFeePoolAmountStart).add( new BN( orderActionRecord.takerFee .sub(keeperFee) .sub(orderActionRecord.spotFulfillmentMethodFee) ) ) ) ); const phoenixMarketStart = phoenixClient.markets.get( solMarketAddress.toString() ).data; await phoenixClient.refreshAllMarkets(); const phoenixMarketEnd = phoenixClient.markets.get( solMarketAddress.toString() ).data; // Verify that there are no orders on the book after the fill assert(phoenixMarketStart.bids.length > 0); assert(phoenixMarketEnd.bids.length === 0); // Verify that the recorded fee from Drift is the same as Phoenix assert( phoenixClient.quoteLotsToQuoteAtoms( phoenixMarketEnd.unclaimedQuoteLotFees - phoenixMarketStart.unclaimedQuoteLotFees, solMarketAddress.toBase58() ) === orderActionRecord.spotFulfillmentMethodFee.toNumber() ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/spotDepositWithdraw22.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js'; import { TestClient, BN, EventSubscriber, SPOT_MARKET_RATE_PRECISION, SpotBalanceType, isVariant, OracleSource, SPOT_MARKET_WEIGHT_PRECISION, SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION, OracleInfo, } from '../sdk/src'; import { createUserWithUSDCAccount, createUserWithUSDCAndWSOLAccount, mintUSDCToUser, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpers'; import { getBalance, calculateInterestAccumulated, getTokenAmount, } from '../sdk/src/math/spotBalance'; import { NATIVE_MINT, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; import { QUOTE_PRECISION, ZERO, ONE, SPOT_MARKET_BALANCE_PRECISION, PRICE_PRECISION, } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('spot deposit and withdraw 22', () => { const chProgram = anchor.workspace.Drift as Program; let admin: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let solOracle: PublicKey; let usdcMint; let firstUserDriftClient: TestClient; let firstUserDriftClientUSDCAccount: PublicKey; let secondUserDriftClient: TestClient; let secondUserDriftClientWSOLAccount: PublicKey; let secondUserDriftClientUSDCAccount: PublicKey; const usdcAmount = new BN(10 * 10 ** 6); const largeUsdcAmount = new BN(10_000 * 10 ** 6); const solAmount = new BN(1 * 10 ** 9); let marketIndexes: number[]; let spotMarketIndexes: number[]; let oracleInfos: OracleInfo[]; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper, TOKEN_2022_PROGRAM_ID); await mockUserUSDCAccount(usdcMint, largeUsdcAmount, bankrunContextWrapper); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 30); marketIndexes = []; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solOracle, source: OracleSource.PYTH }]; admin = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await admin.initialize(usdcMint.publicKey, true); await admin.subscribe(); }); after(async () => { await admin.unsubscribe(); await eventSubscriber.unsubscribe(); await firstUserDriftClient.unsubscribe(); await secondUserDriftClient.unsubscribe(); }); it('Initialize USDC Market', async () => { const optimalUtilization = SPOT_MARKET_RATE_PRECISION.div( new BN(2) ).toNumber(); // 50% utilization const optimalRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(20)).toNumber(); // 2000% APR const maxRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(50)).toNumber(); // 5000% APR const initialAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const initialLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); await admin.initializeSpotMarket( usdcMint.publicKey, optimalUtilization, optimalRate, maxRate, PublicKey.default, OracleSource.QUOTE_ASSET, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined ); const txSig = await admin.updateWithdrawGuardThreshold( 0, new BN(10 ** 10).mul(QUOTE_PRECISION) ); bankrunContextWrapper.printTxLogs(txSig); await admin.fetchAccounts(); const spotMarket = await admin.getSpotMarketAccount(0); assert(spotMarket.marketIndex === 0); assert(spotMarket.optimalUtilization === optimalUtilization); assert(spotMarket.optimalBorrowRate === optimalRate); assert(spotMarket.maxBorrowRate === maxRate); assert( spotMarket.cumulativeBorrowInterest.eq( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); assert( spotMarket.cumulativeDepositInterest.eq( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); assert(spotMarket.initialAssetWeight === initialAssetWeight); assert(spotMarket.maintenanceAssetWeight === maintenanceAssetWeight); assert(spotMarket.initialLiabilityWeight === initialLiabilityWeight); assert(spotMarket.maintenanceAssetWeight === maintenanceAssetWeight); assert(admin.getStateAccount().numberOfSpotMarkets === 1); }); it('Initialize SOL Market', async () => { const optimalUtilization = SPOT_MARKET_RATE_PRECISION.div( new BN(2) ).toNumber(); // 50% utilization const optimalRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(20)).toNumber(); // 2000% APR const maxRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(50)).toNumber(); // 5000% APR const initialAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(8)) .div(new BN(10)) .toNumber(); const maintenanceAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(9)) .div(new BN(10)) .toNumber(); const initialLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(12)) .div(new BN(10)) .toNumber(); const maintenanceLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.mul( new BN(11) ) .div(new BN(10)) .toNumber(); await admin.initializeSpotMarket( NATIVE_MINT, optimalUtilization, optimalRate, maxRate, solOracle, OracleSource.PYTH, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight ); const txSig = await admin.updateWithdrawGuardThreshold( 1, new BN(10 ** 10).mul(QUOTE_PRECISION) ); bankrunContextWrapper.printTxLogs(txSig); await admin.fetchAccounts(); const spotMarket = await admin.getSpotMarketAccount(1); assert(spotMarket.marketIndex === 1); assert(spotMarket.optimalUtilization === optimalUtilization); assert(spotMarket.optimalBorrowRate === optimalRate); assert(spotMarket.maxBorrowRate === maxRate); assert( spotMarket.cumulativeBorrowInterest.eq( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); assert( spotMarket.cumulativeDepositInterest.eq( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); assert(spotMarket.initialAssetWeight === initialAssetWeight); assert(spotMarket.maintenanceAssetWeight === maintenanceAssetWeight); assert(spotMarket.initialLiabilityWeight === initialLiabilityWeight); assert(spotMarket.maintenanceAssetWeight === maintenanceAssetWeight); console.log(spotMarket.historicalOracleData); assert(spotMarket.historicalOracleData.lastOraclePriceTwapTs.eq(ZERO)); assert( spotMarket.historicalOracleData.lastOraclePrice.eq( new BN(30 * PRICE_PRECISION.toNumber()) ) ); assert( spotMarket.historicalOracleData.lastOraclePriceTwap.eq( new BN(30 * PRICE_PRECISION.toNumber()) ) ); assert( spotMarket.historicalOracleData.lastOraclePriceTwap5Min.eq( new BN(30 * PRICE_PRECISION.toNumber()) ) ); assert(admin.getStateAccount().numberOfSpotMarkets === 2); }); it('First User Deposit USDC', async () => { [firstUserDriftClient, firstUserDriftClientUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); const marketIndex = 0; await sleep(100); await firstUserDriftClient.fetchAccounts(); const txSig = await firstUserDriftClient.deposit( usdcAmount, marketIndex, firstUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); const spotMarket = await admin.getSpotMarketAccount(marketIndex); assert( spotMarket.depositBalance.eq( new BN(10 * SPOT_MARKET_BALANCE_PRECISION.toNumber()) ) ); const vaultAmount = new BN( ( await bankrunContextWrapper.connection.getTokenAccount(spotMarket.vault) ).amount.toString() ); assert(vaultAmount.eq(usdcAmount)); const expectedBalance = getBalance( usdcAmount, spotMarket, SpotBalanceType.DEPOSIT ); const spotPosition = firstUserDriftClient.getUserAccount().spotPositions[0]; assert(isVariant(spotPosition.balanceType, 'deposit')); assert(spotPosition.scaledBalance.eq(expectedBalance)); assert(firstUserDriftClient.getUserAccount().totalDeposits.eq(usdcAmount)); }); it('Second User Deposit SOL', async () => { [ secondUserDriftClient, secondUserDriftClientWSOLAccount, secondUserDriftClientUSDCAccount, ] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount, ZERO, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); const marketIndex = 1; const txSig = await secondUserDriftClient.deposit( solAmount, marketIndex, secondUserDriftClientWSOLAccount ); bankrunContextWrapper.printTxLogs(txSig); const spotMarket = await admin.getSpotMarketAccount(marketIndex); assert(spotMarket.depositBalance.eq(SPOT_MARKET_BALANCE_PRECISION)); console.log(spotMarket.historicalOracleData); assert(spotMarket.historicalOracleData.lastOraclePriceTwapTs.gt(ZERO)); assert( spotMarket.historicalOracleData.lastOraclePrice.eq( new BN(30 * PRICE_PRECISION.toNumber()) ) ); assert( spotMarket.historicalOracleData.lastOraclePriceTwap.eq( new BN(30 * PRICE_PRECISION.toNumber()) ) ); assert( spotMarket.historicalOracleData.lastOraclePriceTwap5Min.eq( new BN(30 * PRICE_PRECISION.toNumber()) ) ); const vaultAmount = new BN( ( await bankrunContextWrapper.connection.getTokenAccount(spotMarket.vault) ).amount.toString() ); assert(vaultAmount.eq(solAmount)); const expectedBalance = getBalance( solAmount, spotMarket, SpotBalanceType.DEPOSIT ); const spotPosition = secondUserDriftClient.getUserAccount().spotPositions[1]; assert(isVariant(spotPosition.balanceType, 'deposit')); assert(spotPosition.scaledBalance.eq(expectedBalance)); assert( secondUserDriftClient .getUserAccount() .totalDeposits.eq(new BN(30).mul(PRICE_PRECISION)) ); }); it('Second User Withdraw First half USDC', async () => { const marketIndex = 0; const withdrawAmount = usdcAmount.div(new BN(2)); const txSig = await secondUserDriftClient.withdraw( withdrawAmount, marketIndex, secondUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); const spotMarket = await admin.getSpotMarketAccount(marketIndex); const expectedBorrowBalance = new BN(5000000001); assert(spotMarket.borrowBalance.eq(expectedBorrowBalance)); const vaultAmount = new BN( ( await bankrunContextWrapper.connection.getTokenAccount(spotMarket.vault) ).amount.toString() ); const expectedVaultAmount = usdcAmount.sub(withdrawAmount); assert(vaultAmount.eq(expectedVaultAmount)); const expectedBalance = getBalance( withdrawAmount, spotMarket, SpotBalanceType.BORROW ); const spotPosition = secondUserDriftClient.getUserAccount().spotPositions[0]; assert(isVariant(spotPosition.balanceType, 'borrow')); assert(spotPosition.scaledBalance.eq(expectedBalance)); const actualAmountWithdrawn = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientUSDCAccount ) ).amount.toString() ); assert(withdrawAmount.eq(actualAmountWithdrawn)); assert( secondUserDriftClient.getUserAccount().totalWithdraws.eq(withdrawAmount) ); }); it('Update Cumulative Interest with 50% utilization', async () => { const usdcmarketIndex = 0; const oldSpotMarketAccount = firstUserDriftClient.getSpotMarketAccount(usdcmarketIndex); await sleep(5000); const txSig = await firstUserDriftClient.updateSpotMarketCumulativeInterest( usdcmarketIndex ); bankrunContextWrapper.printTxLogs(txSig); await firstUserDriftClient.fetchAccounts(); const newSpotMarketAccount = firstUserDriftClient.getSpotMarketAccount(usdcmarketIndex); const expectedInterestAccumulated = calculateInterestAccumulated( oldSpotMarketAccount, newSpotMarketAccount.lastInterestTs ); const expectedCumulativeDepositInterest = oldSpotMarketAccount.cumulativeDepositInterest.add( expectedInterestAccumulated.depositInterest ); const expectedCumulativeBorrowInterest = oldSpotMarketAccount.cumulativeBorrowInterest.add( expectedInterestAccumulated.borrowInterest ); assert( newSpotMarketAccount.cumulativeDepositInterest.eq( expectedCumulativeDepositInterest ) ); assert( newSpotMarketAccount.cumulativeBorrowInterest.eq( expectedCumulativeBorrowInterest ) ); }); it('Second User Withdraw second half USDC', async () => { const marketIndex = 0; let spotMarketAccount = secondUserDriftClient.getSpotMarketAccount(marketIndex); const spotMarketDepositTokenAmountBefore = getTokenAmount( spotMarketAccount.depositBalance, spotMarketAccount, SpotBalanceType.DEPOSIT ); const spotMarketBorrowTokenAmountBefore = getTokenAmount( spotMarketAccount.borrowBalance, spotMarketAccount, SpotBalanceType.BORROW ); const spotMarketBorrowBalanceBefore = spotMarketAccount.borrowBalance; const userUSDCAmountBefore = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientUSDCAccount ) ).amount.toString() ); const spotPositionBefore = secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; const withdrawAmount = spotMarketDepositTokenAmountBefore .sub(spotMarketBorrowTokenAmountBefore) .sub(ONE); const txSig = await secondUserDriftClient.withdraw( withdrawAmount, marketIndex, secondUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); spotMarketAccount = secondUserDriftClient.getSpotMarketAccount(marketIndex); const increaseInspotPosition = getBalance( withdrawAmount, spotMarketAccount, SpotBalanceType.BORROW ); const expectedspotPosition = spotPositionBefore.add(increaseInspotPosition); console.log('withdrawAmount:', withdrawAmount.toString()); assert( secondUserDriftClient .getSpotPosition(marketIndex) .scaledBalance.eq(expectedspotPosition) ); const expectedUserUSDCAmount = userUSDCAmountBefore.add(withdrawAmount); const userUSDCAmountAfter = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientUSDCAccount ) ).amount.toString() ); assert(expectedUserUSDCAmount.eq(userUSDCAmountAfter)); assert( secondUserDriftClient .getUserAccount() .totalWithdraws.eq(userUSDCAmountAfter) ); const expectedSpotMarketBorrowBalance = spotMarketBorrowBalanceBefore.add( increaseInspotPosition ); console.assert( spotMarketAccount.borrowBalance.eq(expectedSpotMarketBorrowBalance) ); const expectedVaultBalance = usdcAmount.sub(expectedUserUSDCAmount); const vaultUSDCAmountAfter = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( spotMarketAccount.vault ) ).amount.toString() ); assert(expectedVaultBalance.eq(vaultUSDCAmountAfter)); const spotMarketDepositTokenAmountAfter = getTokenAmount( spotMarketAccount.depositBalance, spotMarketAccount, SpotBalanceType.DEPOSIT ); const spotMarketBorrowTokenAmountAfter = getTokenAmount( spotMarketAccount.borrowBalance, spotMarketAccount, SpotBalanceType.BORROW ); // TODO console.log( spotMarketDepositTokenAmountAfter.toString(), spotMarketBorrowTokenAmountAfter.toString() ); assert( spotMarketDepositTokenAmountAfter .sub(spotMarketBorrowTokenAmountAfter) .lte(ONE) ); }); it('Update Cumulative Interest with 100% utilization', async () => { const usdcmarketIndex = 0; const oldSpotMarketAccount = firstUserDriftClient.getSpotMarketAccount(usdcmarketIndex); await sleep(5000); const txSig = await firstUserDriftClient.updateSpotMarketCumulativeInterest( usdcmarketIndex ); bankrunContextWrapper.printTxLogs(txSig); await firstUserDriftClient.fetchAccounts(); const newSpotMarketAccount = firstUserDriftClient.getSpotMarketAccount(usdcmarketIndex); const expectedInterestAccumulated = calculateInterestAccumulated( oldSpotMarketAccount, newSpotMarketAccount.lastInterestTs ); const expectedCumulativeDepositInterest = oldSpotMarketAccount.cumulativeDepositInterest.add( expectedInterestAccumulated.depositInterest ); const expectedCumulativeBorrowInterest = oldSpotMarketAccount.cumulativeBorrowInterest.add( expectedInterestAccumulated.borrowInterest ); assert( newSpotMarketAccount.cumulativeDepositInterest.eq( expectedCumulativeDepositInterest ) ); console.log( newSpotMarketAccount.cumulativeBorrowInterest.sub(ONE).toString(), expectedCumulativeBorrowInterest.toString() ); // inconcistent time leads to slight differences over runs? assert( newSpotMarketAccount.cumulativeBorrowInterest .sub(ONE) .eq(expectedCumulativeBorrowInterest) || newSpotMarketAccount.cumulativeBorrowInterest.eq( expectedCumulativeBorrowInterest ) ); }); it('Flip second user borrow to deposit', async () => { const marketIndex = 0; const mintAmount = new BN(2 * 10 ** 6); // $2 const userUSDCAmountBefore = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientUSDCAccount ) ).amount.toString() ); await mintUSDCToUser( usdcMint, secondUserDriftClientUSDCAccount, mintAmount, bankrunContextWrapper ); const userBorrowBalanceBefore = secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; const spotMarketDepositBalanceBefore = secondUserDriftClient.getSpotMarketAccount(marketIndex).depositBalance; const depositAmount = userUSDCAmountBefore.add(mintAmount.div(new BN(2))); const txSig = await secondUserDriftClient.deposit( depositAmount, marketIndex, secondUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); await secondUserDriftClient.fetchAccounts(); const spotMarketAccount = secondUserDriftClient.getSpotMarketAccount(marketIndex); const borrowToPayOff = getTokenAmount( userBorrowBalanceBefore, spotMarketAccount, SpotBalanceType.BORROW ); const newDepositTokenAmount = depositAmount.sub(borrowToPayOff); const expectedUserBalance = getBalance( newDepositTokenAmount, spotMarketAccount, SpotBalanceType.DEPOSIT ); const userBalanceAfter = secondUserDriftClient.getSpotPosition(marketIndex); console.log( expectedUserBalance.toString(), userBalanceAfter.scaledBalance.toString() ); assert(expectedUserBalance.eq(userBalanceAfter.scaledBalance)); assert(isVariant(userBalanceAfter.balanceType, 'deposit')); const expectedSpotMarketDepositBalance = spotMarketDepositBalanceBefore.add(expectedUserBalance); console.log( spotMarketAccount.depositBalance.toString(), expectedSpotMarketDepositBalance.toString() ); assert( spotMarketAccount.depositBalance.eq(expectedSpotMarketDepositBalance) ); assert(spotMarketAccount.borrowBalance.eq(ZERO)); }); it('Flip second user deposit to borrow', async () => { const marketIndex = 0; const spotMarketAccountBefore = secondUserDriftClient.getSpotMarketAccount(marketIndex); const userDepositBalanceBefore = secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; const spotMarketDepositBalanceBefore = secondUserDriftClient.getSpotMarketAccount(marketIndex).depositBalance; const userDepositokenAmountBefore = getTokenAmount( userDepositBalanceBefore, spotMarketAccountBefore, SpotBalanceType.DEPOSIT ); const borrowAmount = userDepositokenAmountBefore.add(new BN(1 * 10 ** 6)); const txSig = await secondUserDriftClient.withdraw( borrowAmount, marketIndex, secondUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); await secondUserDriftClient.fetchAccounts(); const spotMarketAccount = secondUserDriftClient.getSpotMarketAccount(marketIndex); const depositToWithdrawAgainst = getTokenAmount( userDepositBalanceBefore, spotMarketAccount, SpotBalanceType.DEPOSIT ); const newBorrowTokenAmount = borrowAmount.sub(depositToWithdrawAgainst); const expectedUserBalance = getBalance( newBorrowTokenAmount, spotMarketAccount, SpotBalanceType.BORROW ); const userBalanceAfter = secondUserDriftClient.getSpotPosition(marketIndex); assert(expectedUserBalance.eq(userBalanceAfter.scaledBalance)); assert(isVariant(userBalanceAfter.balanceType, 'borrow')); const expectedSpotMarketDepositBalance = spotMarketDepositBalanceBefore.sub( userDepositBalanceBefore ); assert( spotMarketAccount.depositBalance.eq(expectedSpotMarketDepositBalance) ); assert(spotMarketAccount.borrowBalance.eq(expectedUserBalance)); }); it('Second user reduce only pay down borrow', async () => { const marketIndex = 0; const userUSDCAmountBefore = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientUSDCAccount ) ).amount.toString() ); const currentUserBorrowBalance = secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; const spotMarketDepositBalanceBefore = secondUserDriftClient.getSpotMarketAccount(marketIndex).depositBalance; const depositAmount = userUSDCAmountBefore.mul(new BN(100000)); // huge number const txSig = await secondUserDriftClient.deposit( depositAmount, marketIndex, secondUserDriftClientUSDCAccount, undefined, true ); bankrunContextWrapper.printTxLogs(txSig); const spotMarketAccountAfter = secondUserDriftClient.getSpotMarketAccount(marketIndex); const borrowToPayBack = getTokenAmount( currentUserBorrowBalance, spotMarketAccountAfter, SpotBalanceType.BORROW ); const userUSDCAmountAfter = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientUSDCAccount ) ).amount.toString() ); const expectedUserUSDCAmount = userUSDCAmountBefore.sub(borrowToPayBack); console.log( expectedUserUSDCAmount.toString(), userUSDCAmountAfter.toString() ); assert(expectedUserUSDCAmount.eq(userUSDCAmountAfter)); const userBalanceAfter = secondUserDriftClient.getSpotPosition(marketIndex); assert(userBalanceAfter.scaledBalance.eq(ZERO)); assert(spotMarketAccountAfter.borrowBalance.eq(ZERO)); assert( spotMarketAccountAfter.depositBalance.eq(spotMarketDepositBalanceBefore) ); }); it('Second user reduce only withdraw deposit', async () => { const marketIndex = 1; const userWSOLAmountBefore = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientWSOLAccount ) ).amount.toString() ); const currentUserDepositBalance = secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; const withdrawAmount = new BN(LAMPORTS_PER_SOL * 100); const txSig = await secondUserDriftClient.withdraw( withdrawAmount, marketIndex, secondUserDriftClientWSOLAccount, true ); bankrunContextWrapper.printTxLogs(txSig); const spotMarketAccountAfter = secondUserDriftClient.getSpotMarketAccount(marketIndex); const amountAbleToWithdraw = getTokenAmount( currentUserDepositBalance, spotMarketAccountAfter, SpotBalanceType.DEPOSIT ); const userWSOLAmountAfter = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientWSOLAccount ) ).amount.toString() ); const expectedUserWSOLAmount = amountAbleToWithdraw.sub(userWSOLAmountBefore); console.log(expectedUserWSOLAmount.toString()); console.log(userWSOLAmountAfter.toString()); assert(expectedUserWSOLAmount.eq(userWSOLAmountAfter)); const userBalanceAfter = secondUserDriftClient.getSpotPosition(marketIndex); assert(userBalanceAfter.scaledBalance.eq(ZERO)); }); it('Third user deposits when cumulative interest off init value', async () => { // rounding on spot market balance <-> token conversions can lead to tiny epislon of loss on deposits const [ thirdUserDriftClient, _thirdUserDriftClientWSOLAccount, thirdUserDriftClientUSDCAccount, ] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount, largeUsdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); const marketIndex = 0; await thirdUserDriftClient.fetchAccounts(); const spotPosition = thirdUserDriftClient.getSpotPosition(marketIndex); console.log(spotPosition); assert(spotPosition.scaledBalance.eq(ZERO)); const spotMarket = thirdUserDriftClient.getSpotMarketAccount(marketIndex); console.log(spotMarket.cumulativeDepositInterest.toString()); console.log(spotMarket.cumulativeBorrowInterest.toString()); assert( spotMarket.cumulativeDepositInterest.gt( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); assert( spotMarket.cumulativeBorrowInterest.gt( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); console.log('usdcAmount:', largeUsdcAmount.toString(), 'user deposits'); const txSig = await thirdUserDriftClient.deposit( largeUsdcAmount, marketIndex, thirdUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); const spotPositionAfter = thirdUserDriftClient.getSpotPosition(marketIndex); const tokenAmount = getTokenAmount( spotPositionAfter.scaledBalance, spotMarket, spotPositionAfter.balanceType ); console.log('tokenAmount:', tokenAmount.toString()); assert( tokenAmount.gte(largeUsdcAmount.sub(QUOTE_PRECISION.div(new BN(100)))) ); // didnt lose more than a penny assert(tokenAmount.lt(largeUsdcAmount)); // lose a lil bit await thirdUserDriftClient.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/insuranceFundStake.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { PublicKey, Keypair } from '@solana/web3.js'; import { OracleGuardRails, TestClient, User, BN, OracleSource, EventSubscriber, getInsuranceFundStakeAccountPublicKey, InsuranceFundStake, ZERO, QUOTE_SPOT_MARKET_INDEX, QUOTE_PRECISION, ONE, getTokenAmount, SpotBalanceType, getBalance, isVariant, PEG_PRECISION, SPOT_MARKET_RATE_PRECISION, convertToNumber, AMM_RESERVE_PRECISION, unstakeSharesToAmount, MarketStatus, LIQUIDATION_PCT_PRECISION, } from '../sdk/src'; import { mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, initializeSolSpotMarket, createUserWithUSDCAndWSOLAccount, sleep, mockOracleNoProgram, setFeedPriceNoProgram, } from './testHelpers'; import { ContractTier, PERCENTAGE_PRECISION, UserStatus } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper, asBN, } from '../sdk/src/bankrun/bankrunConnection'; describe('insurance fund stake', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount: Keypair; let solOracle: PublicKey; const usdcAmount = new BN(1000000 * 10 ** 6); //1M let secondUserDriftClient: TestClient; let secondUserDriftClientWSOLAccount: PublicKey; let secondUserDriftClientUSDCAccount: PublicKey; let driftClientUser: User; const solAmount = new BN(10000 * 10 ** 9); before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount.mul(new BN(2)), // 2x it bankrunContextWrapper ); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 22500); // a future we all need to believe in driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0, 1], subAccountIds: [], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await driftClient.updateInitialPctToLiquidate( LIQUIDATION_PCT_PRECISION.toNumber() ); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await initializeSolSpotMarket(driftClient, solOracle); const periodicity = new BN(60 * 60); // 1 HOUR await driftClient.initializePerpMarket( 0, solOracle, AMM_RESERVE_PRECISION, AMM_RESERVE_PRECISION, periodicity, new BN(22500 * PEG_PRECISION.toNumber()), undefined, ContractTier.A ); await driftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); await driftClient.updatePerpMarketBaseSpread(0, 2000); await driftClient.updatePerpMarketCurveUpdateIntensity(0, 100); const subAccountId = 0; const name = 'BIGZ'; await driftClient.initializeUserAccount(subAccountId, name); await driftClient.deposit( usdcAmount, QUOTE_SPOT_MARKET_INDEX, userUSDCAccount.publicKey ); }); after(async () => { await driftClient.unsubscribe(); await secondUserDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); await driftClientUser.unsubscribe(); }); it('initialize if stake', async () => { const marketIndex = 0; await driftClient.initializeInsuranceFundStake(marketIndex); const ifStakePublicKey = getInsuranceFundStakeAccountPublicKey( driftClient.program.programId, bankrunContextWrapper.provider.wallet.publicKey, marketIndex ); const ifStakeAccount = (await driftClient.program.account.insuranceFundStake.fetch( ifStakePublicKey )) as InsuranceFundStake; assert(ifStakeAccount.marketIndex === marketIndex); assert( ifStakeAccount.authority.equals( bankrunContextWrapper.provider.wallet.publicKey ) ); const userStats = driftClient.getUserStats().getAccount(); assert(userStats.numberOfSubAccounts === 1); assert(userStats.ifStakedQuoteAssetAmount.eq(ZERO)); }); it('user if stake', async () => { const marketIndex = 0; const spotMarketBefore = driftClient.getSpotMarketAccount(marketIndex); // console.log(spotMarketBefore); console.log( 'spotMarketBefore.totalIfShares:', spotMarketBefore.insuranceFund.totalShares.toString() ); try { const txSig = await driftClient.addInsuranceFundStake({ marketIndex: marketIndex, amount: usdcAmount, collateralAccountPublicKey: userUSDCAccount.publicKey, }); bankrunContextWrapper.connection.printTxLogs(txSig); } catch (e) { console.error(e); } const spotMarket0 = driftClient.getSpotMarketAccount(marketIndex); console.log( 'spotMarket0.insurance.totalIfShares:', spotMarket0.insuranceFund.totalShares.toString() ); // console.log(spotMarket0); assert(spotMarket0.revenuePool.scaledBalance.eq(ZERO)); assert(spotMarket0.insuranceFund.totalShares.gt(ZERO)); assert(spotMarket0.insuranceFund.totalShares.eq(usdcAmount)); assert(spotMarket0.insuranceFund.userShares.eq(usdcAmount)); const userStats = driftClient.getUserStats().getAccount(); console.log(userStats); assert(userStats.ifStakedQuoteAssetAmount.eq(usdcAmount)); }); it('user request if unstake (half)', async () => { const marketIndex = 0; const nShares = usdcAmount.div(new BN(2)); const spotMarket0Before = driftClient.getSpotMarketAccount(marketIndex); const insuranceVaultAmountBefore = ( await bankrunContextWrapper.connection.getTokenAccount( spotMarket0Before.insuranceFund.vault ) ).amount; const amountFromShare = unstakeSharesToAmount( nShares, spotMarket0Before.insuranceFund.totalShares, new BN(Number(insuranceVaultAmountBefore)) ); console.log(amountFromShare.toString()); try { const txSig = await driftClient.requestRemoveInsuranceFundStake( marketIndex, amountFromShare ); bankrunContextWrapper.connection.printTxLogs(txSig); } catch (e) { console.error(e); } const spotMarket0 = driftClient.getSpotMarketAccount(marketIndex); assert(spotMarket0.insuranceFund.totalShares.gt(ZERO)); assert(spotMarket0.insuranceFund.totalShares.eq(usdcAmount)); assert(spotMarket0.insuranceFund.userShares.eq(usdcAmount)); const userStats = driftClient.getUserStats().getAccount(); assert(userStats.ifStakedQuoteAssetAmount.eq(usdcAmount)); const ifStakePublicKey = getInsuranceFundStakeAccountPublicKey( driftClient.program.programId, bankrunContextWrapper.provider.wallet.publicKey, marketIndex ); const ifStakeAccount = (await driftClient.program.account.insuranceFundStake.fetch( ifStakePublicKey )) as InsuranceFundStake; assert(ifStakeAccount.lastWithdrawRequestShares.gt(ZERO)); console.log(ifStakeAccount.lastWithdrawRequestShares.toString()); console.log(nShares.toString()); assert(ifStakeAccount.lastWithdrawRequestShares.eq(nShares)); assert(ifStakeAccount.lastWithdrawRequestValue.eq(amountFromShare)); }); it('user if unstake (half)', async () => { const marketIndex = 0; // const nShares = usdcAmount.div(new BN(2)); await driftClient.updateInsuranceFundUnstakingPeriod( marketIndex, new BN(1) ); await sleep(1000); const txSig = await driftClient.removeInsuranceFundStake( marketIndex, userUSDCAccount.publicKey ); bankrunContextWrapper.connection.printTxLogs(txSig); const spotMarket0 = driftClient.getSpotMarketAccount(marketIndex); console.log( 'totalIfShares:', spotMarket0.insuranceFund.totalShares.toString() ); console.log( 'userIfShares:', spotMarket0.insuranceFund.userShares.toString() ); assert(spotMarket0.insuranceFund.totalShares.eq(usdcAmount.div(new BN(2)))); assert(spotMarket0.insuranceFund.userShares.eq(usdcAmount.div(new BN(2)))); const userStats = driftClient.getUserStats().getAccount(); assert(userStats.ifStakedQuoteAssetAmount.eq(usdcAmount.div(new BN(2)))); const ifStakePublicKey = getInsuranceFundStakeAccountPublicKey( driftClient.program.programId, bankrunContextWrapper.provider.wallet.publicKey, marketIndex ); const balance = ( await bankrunContextWrapper.connection.getAccountInfo( userUSDCAccount.publicKey ) ).lamports; console.log('sol balance:', balance.toString()); const usdcbalance = ( await bankrunContextWrapper.connection.getTokenAccount( userUSDCAccount.publicKey ) ).amount; console.log('usdc balance:', usdcbalance); assert(usdcbalance.toString() == '500000000000'); const ifStakeAccount = (await driftClient.program.account.insuranceFundStake.fetch( ifStakePublicKey )) as InsuranceFundStake; assert(ifStakeAccount.lastWithdrawRequestShares.eq(ZERO)); }); it('user request if unstake with escrow period (last half)', async () => { const txSig = await driftClient.updateInsuranceFundUnstakingPeriod( 0, new BN(10) ); bankrunContextWrapper.connection.printTxLogs(txSig); const marketIndex = 0; const nShares = usdcAmount.div(new BN(2)); const txSig2 = await driftClient.requestRemoveInsuranceFundStake( marketIndex, nShares ); bankrunContextWrapper.connection.printTxLogs(txSig2); try { const txSig3 = await driftClient.removeInsuranceFundStake( marketIndex, userUSDCAccount.publicKey ); bankrunContextWrapper.connection.printTxLogs(txSig3); assert(false); // todo } catch (e) { console.error(e); } await driftClient.fetchAccounts(); const spotMarket0 = driftClient.getSpotMarketAccount(marketIndex); assert(spotMarket0.insuranceFund.unstakingPeriod.eq(new BN(10))); assert(spotMarket0.insuranceFund.totalShares.gt(ZERO)); assert(spotMarket0.insuranceFund.totalShares.eq(usdcAmount.div(new BN(2)))); assert(spotMarket0.insuranceFund.userShares.eq(usdcAmount.div(new BN(2)))); const userStats = driftClient.getUserStats().getAccount(); assert(userStats.ifStakedQuoteAssetAmount.gt(ZERO)); const ifStakePublicKey = getInsuranceFundStakeAccountPublicKey( driftClient.program.programId, bankrunContextWrapper.provider.wallet.publicKey, marketIndex ); const ifStakeAccount = (await driftClient.program.account.insuranceFundStake.fetch( ifStakePublicKey )) as InsuranceFundStake; assert(ifStakeAccount.lastWithdrawRequestShares.gt(ZERO)); }); it('user if unstake with escrow period (last half)', async () => { const marketIndex = 0; try { await driftClient.updateSpotMarketIfFactor( 0, new BN(90000), new BN(100000) ); } catch (e) { console.log('cant set reserve factor'); console.error(e); assert(false); } const spotMarket0Pre = driftClient.getSpotMarketAccount(marketIndex); assert(spotMarket0Pre.insuranceFund.unstakingPeriod.eq(new BN(10))); await bankrunContextWrapper.moveTimeForward(10); // const nShares = usdcAmount.div(new BN(2)); const txSig = await driftClient.removeInsuranceFundStake( marketIndex, userUSDCAccount.publicKey ); bankrunContextWrapper.connection.printTxLogs(txSig); await driftClient.fetchAccounts(); const spotMarket0 = driftClient.getSpotMarketAccount(marketIndex); console.log( 'totalIfShares:', spotMarket0.insuranceFund.totalShares.toString() ); console.log( 'userIfShares:', spotMarket0.insuranceFund.userShares.toString() ); assert(spotMarket0.insuranceFund.totalShares.eq(ZERO)); assert(spotMarket0.insuranceFund.userShares.eq(ZERO)); const ifStakePublicKey = getInsuranceFundStakeAccountPublicKey( driftClient.program.programId, bankrunContextWrapper.provider.wallet.publicKey, marketIndex ); const ifStakeAccount = (await driftClient.program.account.insuranceFundStake.fetch( ifStakePublicKey )) as InsuranceFundStake; assert(ifStakeAccount.lastWithdrawRequestShares.eq(ZERO)); const userStats = driftClient.getUserStats().getAccount(); assert(userStats.ifStakedQuoteAssetAmount.eq(ZERO)); const usdcbalance = ( await bankrunContextWrapper.connection.getTokenAccount( userUSDCAccount.publicKey ) ).amount; console.log('usdc balance:', usdcbalance); assert(usdcbalance.toString() == '999999999999'); }); it('Second User Deposit SOL', async () => { [ secondUserDriftClient, secondUserDriftClientWSOLAccount, secondUserDriftClientUSDCAccount, ] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount, ZERO, [0], [0, 1], [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], bulkAccountLoader ); const marketIndex = 1; const txSig = await secondUserDriftClient.deposit( solAmount, marketIndex, secondUserDriftClientWSOLAccount ); bankrunContextWrapper.connection.printTxLogs(txSig); const spotMarket = await driftClient.getSpotMarketAccount(marketIndex); console.log(spotMarket.depositBalance.toString()); // assert(spotMarket.depositBalance.eq('10000000000')); // const vaultAmount = new BN( // ( // await provider.connection.getTokenAccountBalance(spotMarket.vault) // ).value.amount // ); const vaultAmount = ( await bankrunContextWrapper.connection.getTokenAccount(spotMarket.vault) ).amount; assert(asBN(vaultAmount).eq(solAmount)); const expectedBalance = getBalance( solAmount, spotMarket, SpotBalanceType.DEPOSIT ); const userspotMarketBalance = secondUserDriftClient.getUserAccount().spotPositions[1]; assert(isVariant(userspotMarketBalance.balanceType, 'deposit')); assert(userspotMarketBalance.scaledBalance.eq(expectedBalance)); }); it('Second User Withdraw First half USDC', async () => { const marketIndex = 0; const withdrawAmount = usdcAmount.div(new BN(2)); const txSig = await secondUserDriftClient.withdraw( withdrawAmount, marketIndex, secondUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); await driftClient.fetchAccounts(); const spotMarket = await driftClient.getSpotMarketAccount(marketIndex); const expectedBorrowBalance = new BN(500000000000001); console.log( 'spotMarket.borrowBalance:', spotMarket.borrowBalance.toString() ); assert(spotMarket.borrowBalance.eq(expectedBorrowBalance)); const vaultAmount = asBN( (await bankrunContextWrapper.connection.getTokenAccount(spotMarket.vault)) .amount ); const expectedVaultAmount = usdcAmount.sub(withdrawAmount); assert(vaultAmount.eq(expectedVaultAmount)); const expectedBalance = getBalance( withdrawAmount, spotMarket, SpotBalanceType.BORROW ); const userspotMarketBalance = secondUserDriftClient.getUserAccount().spotPositions[0]; assert(isVariant(userspotMarketBalance.balanceType, 'borrow')); assert(userspotMarketBalance.scaledBalance.eq(expectedBalance)); const actualAmountWithdrawn = asBN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientUSDCAccount ) ).amount ); assert(withdrawAmount.eq(actualAmountWithdrawn)); }); it('if pool revenue from borrows', async () => { let spotMarket = driftClient.getSpotMarketAccount(0); // await mintToInsuranceFund( // spotMarket.insurance.vault, // usdcMint, // new BN(80085).mul(QUOTE_PRECISION), // provider // ); const ifPoolBalance = getTokenAmount( spotMarket.revenuePool.scaledBalance, spotMarket, SpotBalanceType.DEPOSIT ); assert(spotMarket.borrowBalance.gt(ZERO)); assert(ifPoolBalance.eq(new BN(0))); await driftClient.updateSpotMarketCumulativeInterest(0); await driftClient.fetchAccounts(); spotMarket = driftClient.getSpotMarketAccount(0); console.log( 'cumulativeBorrowInterest:', spotMarket.cumulativeBorrowInterest.toString() ); console.log( 'cumulativeDepositInterest:', spotMarket.cumulativeDepositInterest.toString() ); const ifPoolBalanceAfterUpdate = getTokenAmount( spotMarket.revenuePool.scaledBalance, spotMarket, SpotBalanceType.DEPOSIT ); assert(ifPoolBalanceAfterUpdate.gt(new BN(0))); assert(spotMarket.cumulativeBorrowInterest.gt(SPOT_MARKET_RATE_PRECISION)); assert(spotMarket.cumulativeDepositInterest.gt(SPOT_MARKET_RATE_PRECISION)); const insuranceVaultAmountBefore = asBN( ( await bankrunContextWrapper.connection.getTokenAccount( spotMarket.insuranceFund.vault ) ).amount ); console.log('insuranceVaultAmount:', insuranceVaultAmountBefore.toString()); assert(insuranceVaultAmountBefore.eq(ONE)); await driftClient.updateSpotMarketRevenueSettlePeriod(0, ONE); try { const txSig = await driftClient.settleRevenueToInsuranceFund(0); bankrunContextWrapper.printTxLogs(txSig); } catch (e) { console.error(e); } const insuranceVaultAmount = asBN( ( await bankrunContextWrapper.connection.getTokenAccount( spotMarket.insuranceFund.vault ) ).amount ); console.log( 'insuranceVaultAmount:', insuranceVaultAmountBefore.toString(), '->', insuranceVaultAmount.toString() ); assert(insuranceVaultAmount.gt(ONE)); await driftClient.fetchAccounts(); spotMarket = driftClient.getSpotMarketAccount(0); const ifPoolBalanceAfterSettle = getTokenAmount( spotMarket.revenuePool.scaledBalance, spotMarket, SpotBalanceType.DEPOSIT ); assert(ifPoolBalanceAfterSettle.eq(new BN(0))); }); it('no user -> user stake when there is a vault balance', async () => { const marketIndex = 0; const spotMarket0Before = driftClient.getSpotMarketAccount(marketIndex); const insuranceVaultAmountBefore = asBN( ( await bankrunContextWrapper.connection.getTokenAccount( spotMarket0Before.insuranceFund.vault ) ).amount ); assert(spotMarket0Before.revenuePool.scaledBalance.eq(ZERO)); assert(spotMarket0Before.insuranceFund.userShares.eq(ZERO)); assert(spotMarket0Before.insuranceFund.totalShares.eq(ZERO)); const usdcbalance = asBN( ( await bankrunContextWrapper.connection.getTokenAccount( userUSDCAccount.publicKey ) ).amount ); console.log('usdc balance:', usdcbalance); assert(usdcbalance.toString() == '999999999999'); try { const txSig = await driftClient.addInsuranceFundStake({ marketIndex, amount: new BN(usdcbalance), collateralAccountPublicKey: userUSDCAccount.publicKey, }); bankrunContextWrapper.connection.printTxLogs(txSig); } catch (e) { console.error(e); assert(false); } const spotMarket0 = driftClient.getSpotMarketAccount(marketIndex); assert(spotMarket0.revenuePool.scaledBalance.eq(ZERO)); const insuranceVaultAmountAfter = asBN( ( await bankrunContextWrapper.connection.getTokenAccount( spotMarket0.insuranceFund.vault ) ).amount ); assert(insuranceVaultAmountAfter.gt(insuranceVaultAmountBefore)); console.log( 'userIfShares:', spotMarket0.insuranceFund.userShares.toString(), 'totalIfShares:', spotMarket0.insuranceFund.totalShares.toString() ); assert(spotMarket0.insuranceFund.totalShares.gt(ZERO)); assert(spotMarket0.insuranceFund.totalShares.gt(usdcAmount)); assert(spotMarket0.insuranceFund.totalShares.gt(new BN('1000000004698'))); // totalIfShares lower bound, kinda random basd on timestamps assert(spotMarket0.insuranceFund.userShares.eq(new BN(usdcbalance))); const userStats = driftClient.getUserStats().getAccount(); assert(userStats.ifStakedQuoteAssetAmount.eq(new BN(usdcbalance))); }); it('user stake misses out on gains during escrow period after cancel', async () => { const marketIndex = 0; const spotMarket0Before = driftClient.getSpotMarketAccount(marketIndex); const insuranceVaultAmountBefore = asBN( ( await bankrunContextWrapper.connection.getTokenAccount( spotMarket0Before.insuranceFund.vault ) ).amount ); assert(spotMarket0Before.revenuePool.scaledBalance.eq(ZERO)); console.log( 'cumulativeBorrowInterest:', spotMarket0Before.cumulativeBorrowInterest.toString() ); console.log( 'cumulativeDepositInterest:', spotMarket0Before.cumulativeDepositInterest.toString() ); // user requests partial withdraw const ifStakePublicKey = getInsuranceFundStakeAccountPublicKey( driftClient.program.programId, bankrunContextWrapper.provider.wallet.publicKey, marketIndex ); const ifStakeAccount = (await driftClient.program.account.insuranceFundStake.fetch( ifStakePublicKey )) as InsuranceFundStake; const amountFromShare = unstakeSharesToAmount( ifStakeAccount.ifShares.div(new BN(10)), spotMarket0Before.insuranceFund.totalShares, insuranceVaultAmountBefore ); await driftClient.requestRemoveInsuranceFundStake( marketIndex, amountFromShare ); console.log('letting interest accum (2s)'); await sleep(2000); await driftClient.updateSpotMarketCumulativeInterest(0); await driftClient.fetchAccounts(); const spotMarketIUpdate = await driftClient.getSpotMarketAccount( marketIndex ); console.log( 'cumulativeBorrowInterest:', spotMarketIUpdate.cumulativeBorrowInterest.toString() ); console.log( 'cumulativeDepositInterest:', spotMarketIUpdate.cumulativeDepositInterest.toString() ); console.log(spotMarketIUpdate.revenuePool.scaledBalance.toString()); assert(spotMarketIUpdate.revenuePool.scaledBalance.gt(ZERO)); try { const txSig = await driftClient.settleRevenueToInsuranceFund(marketIndex); bankrunContextWrapper.printTxLogs(txSig); } catch (e) { console.error(e); assert(false); } const insuranceVaultAmountAfter = asBN( ( await bankrunContextWrapper.connection.getTokenAccount( spotMarket0Before.insuranceFund.vault ) ).amount ); assert(insuranceVaultAmountAfter.gt(insuranceVaultAmountBefore)); const txSig = await driftClient.cancelRequestRemoveInsuranceFundStake( marketIndex ); bankrunContextWrapper.connection.printTxLogs(txSig); const ifStakeAccountAfter = (await driftClient.program.account.insuranceFundStake.fetch( ifStakePublicKey )) as InsuranceFundStake; const userStats = driftClient.getUserStats().getAccount(); console.log( 'ifshares:', ifStakeAccount.ifShares.toString(), '->', ifStakeAccountAfter.ifShares.toString(), '(quoteAssetInsuranceFundStake=', userStats.ifStakedQuoteAssetAmount.toString(), ')' ); assert(ifStakeAccountAfter.ifShares.lt(ifStakeAccount.ifShares)); // the user should have slightly less quote staked than the total quote in if assert( insuranceVaultAmountAfter .sub(userStats.ifStakedQuoteAssetAmount) .lt(QUOTE_PRECISION) ); }); it('liquidate borrow (w/ IF revenue)', async () => { const spotMarketBefore = driftClient.getSpotMarketAccount(0); const revPoolBalance = getTokenAmount( spotMarketBefore.revenuePool.scaledBalance, spotMarketBefore, SpotBalanceType.DEPOSIT ); console.log('revPoolBalance:', revPoolBalance.toString()); assert(spotMarketBefore.borrowBalance.gt(ZERO)); assert(revPoolBalance.gt(new BN(0))); // should be a little residual left in rev pool assert(revPoolBalance.lt(QUOTE_PRECISION)); driftClientUser = new User({ driftClient: secondUserDriftClient, userAccountPublicKey: await secondUserDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const prevTC = driftClientUser.getTotalCollateral(); const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: PERCENTAGE_PRECISION, oracleTwap5MinPercentDivergence: PERCENTAGE_PRECISION, }, validity: { slotsBeforeStaleForAmm: new BN(100), slotsBeforeStaleForMargin: new BN(100), confidenceIntervalMaxSize: new BN(100000), tooVolatileRatio: new BN(100000), }, }; await driftClient.updateLiquidationDuration(1); await driftClient.updateOracleGuardRails(oracleGuardRails); await setFeedPriceNoProgram( bankrunContextWrapper, 22500 / 10000, solOracle ); // down 99.99% await sleep(2000); const state = await driftClient.getStateAccount(); console.log('state.liquidationDuration', state.liquidationDuration); assert(state.liquidationDuration > 0); await driftClientUser.fetchAccounts(); const newTC = driftClientUser.getTotalCollateral(); console.log( "Borrower's TotalCollateral: ", convertToNumber(prevTC, QUOTE_PRECISION), '->', convertToNumber(newTC, QUOTE_PRECISION) ); assert(!prevTC.eq(newTC)); assert(driftClientUser.canBeLiquidated()); const beforecbb0 = driftClient.getUserAccount().spotPositions[0]; const beforecbb1 = driftClient.getUserAccount().spotPositions[1]; const beforeLiquiderUSDCDeposit = getTokenAmount( beforecbb0.scaledBalance, spotMarketBefore, SpotBalanceType.DEPOSIT ); const beforeLiquiderSOLDeposit = getTokenAmount( beforecbb1.scaledBalance, spotMarketBefore, SpotBalanceType.DEPOSIT ); console.log( 'LD:', beforeLiquiderUSDCDeposit.toString(), beforeLiquiderSOLDeposit.toString() ); assert(beforecbb0.marketIndex === 0); // assert(beforecbb1.marketIndex.eq(ONE)); assert(isVariant(beforecbb0.balanceType, 'deposit')); // assert(isVariant(beforecbb1.balanceType, 'deposit')); const beforebb0 = secondUserDriftClient.getUserAccount().spotPositions[0]; const beforebb1 = secondUserDriftClient.getUserAccount().spotPositions[1]; const usdcDepositsBefore = getTokenAmount( spotMarketBefore.depositBalance, spotMarketBefore, SpotBalanceType.DEPOSIT ); const beforeLiquiteeUSDCBorrow = getTokenAmount( beforebb0.scaledBalance, spotMarketBefore, SpotBalanceType.BORROW ); const beforeLiquiteeSOLDeposit = getTokenAmount( beforebb1.scaledBalance, spotMarketBefore, SpotBalanceType.DEPOSIT ); console.log( 'LT:', beforeLiquiteeUSDCBorrow.toString(), beforeLiquiteeSOLDeposit.toString() ); assert(beforebb0.marketIndex === 0); assert(beforebb1.marketIndex === 1); assert(isVariant(beforebb0.balanceType, 'borrow')); assert(isVariant(beforebb1.balanceType, 'deposit')); assert(beforeLiquiderUSDCDeposit.gt(new BN('1000000066000'))); assert(beforeLiquiderSOLDeposit.eq(new BN('0'))); assert(beforeLiquiteeUSDCBorrow.gt(new BN('500000033001'))); assert(beforeLiquiteeSOLDeposit.gt(new BN('10000000997'))); const txSig = await driftClient.liquidateSpot( await secondUserDriftClient.getUserAccountPublicKey(), secondUserDriftClient.getUserAccount(), 1, 0, new BN(6 * 10 ** 8) ); const computeUnits = bankrunContextWrapper.connection.findComputeUnitConsumption(txSig); console.log('compute units', computeUnits); bankrunContextWrapper.printTxLogs(txSig); await driftClient.fetchAccounts(); await secondUserDriftClient.fetchAccounts(); const spotMarket = driftClient.getSpotMarketAccount(0); const cbb0 = driftClient.getUserAccount().spotPositions[0]; const cbb1 = driftClient.getUserAccount().spotPositions[1]; const afterLiquiderUSDCDeposit = getTokenAmount( cbb0.scaledBalance, spotMarket, SpotBalanceType.DEPOSIT ); const afterLiquiderSOLDeposit = getTokenAmount( cbb1.scaledBalance, spotMarket, SpotBalanceType.DEPOSIT ); console.log( 'LD:', afterLiquiderUSDCDeposit.toString(), afterLiquiderSOLDeposit.toString() ); assert(cbb0.marketIndex === 0); assert(cbb1.marketIndex === 1); assert(isVariant(cbb0.balanceType, 'deposit')); assert(isVariant(cbb1.balanceType, 'deposit')); const bb0 = secondUserDriftClient.getUserAccount().spotPositions[0]; const bb1 = secondUserDriftClient.getUserAccount().spotPositions[1]; const afterLiquiteeUSDCBorrow = getTokenAmount( bb0.scaledBalance, spotMarket, SpotBalanceType.BORROW ); const afterLiquiteeSOLDeposit = getTokenAmount( bb1.scaledBalance, spotMarket, SpotBalanceType.DEPOSIT ); console.log( 'LT:', afterLiquiteeUSDCBorrow.toString(), afterLiquiteeSOLDeposit.toString() ); assert(bb0.marketIndex === 0); assert(bb1.marketIndex === 1); assert(isVariant(bb0.balanceType, 'borrow')); assert(isVariant(bb1.balanceType, 'deposit')); assert(afterLiquiderUSDCDeposit.gt(new BN('999400065806'))); assert(afterLiquiderSOLDeposit.gt(new BN('266660042'))); console.log(afterLiquiteeUSDCBorrow.toString()); console.log(afterLiquiteeSOLDeposit.toString()); // assert(afterLiquiteeUSDCBorrow.gte(new BN('499406444150'))); // assert(afterLiquiteeSOLDeposit.gte(new BN('9733337361'))); // console.log( // secondUserDriftClient // .getUserAccount() // .spotPositions[0].scaledBalance.toString(), // secondUserDriftClient // .getUserAccount() // .spotPositions[0].marketIndex.toString(), // secondUserDriftClient.getUserAccount().spotPositions[0].balanceType // ); // console.log( // secondUserDriftClient // .getUserAccount() // .spotPositions[1].scaledBalance.toString(), // secondUserDriftClient // .getUserAccount() // .spotPositions[1].marketIndex.toString(), // secondUserDriftClient.getUserAccount().spotPositions[1].balanceType // ); assert( secondUserDriftClient.getUserAccount().status === UserStatus.BEING_LIQUIDATED ); assert( secondUserDriftClient.getUserAccount().status !== UserStatus.BANKRUPT ); const liquidationRecord = eventSubscriber.getEventsArray('LiquidationRecord')[0]; assert(liquidationRecord.liquidationId === 1); assert(isVariant(liquidationRecord.liquidationType, 'liquidateSpot')); assert(liquidationRecord.liquidateSpot.liabilityMarketIndex === 0); console.log(liquidationRecord.liquidateSpot.liabilityTransfer.toString()); assert( liquidationRecord.liquidateSpot.liabilityTransfer.eq(new BN(600000000)) ); console.log(liquidationRecord.liquidateSpot.ifFee.toString()); console.log(spotMarketBefore.liquidatorFee.toString()); console.log(spotMarketBefore.ifLiquidationFee.toString()); console.log( liquidationRecord.liquidateSpot.liabilityTransfer .div(new BN(100)) .toString() ); // if liquidator fee is non-zero, it should be equal to that assert( liquidationRecord.liquidateSpot.ifFee.eq( new BN(spotMarketBefore.liquidatorFee) ) ); // but it is zero assert(liquidationRecord.liquidateSpot.ifFee.eq(ZERO)); const ifPoolBalanceAfter = getTokenAmount( spotMarket.revenuePool.scaledBalance, spotMarket, SpotBalanceType.DEPOSIT ); console.log('ifPoolBalance: 0 ->', ifPoolBalanceAfter.toString()); assert(ifPoolBalanceAfter.gte(new BN('8840'))); assert(ifPoolBalanceAfter.lte(new BN('30080'))); // assert(ifPoolBalanceAfter.gte(new BN('6004698'))); // before IF fee change const usdcBefore = ifPoolBalanceAfter .add(afterLiquiderUSDCDeposit) .sub(afterLiquiteeUSDCBorrow); const usdcAfter = ZERO.add(beforeLiquiderUSDCDeposit).sub( beforeLiquiteeUSDCBorrow ); const usdcDepositsAfter = getTokenAmount( spotMarket.depositBalance, spotMarket, SpotBalanceType.DEPOSIT ); console.log( 'usdc borrows in spotMarket:', getTokenAmount( spotMarketBefore.borrowBalance, spotMarketBefore, SpotBalanceType.BORROW ).toString(), '->', getTokenAmount( spotMarket.borrowBalance, spotMarket, SpotBalanceType.BORROW ).toString() ); console.log( 'usdc balances in spotMarket:', spotMarketBefore.depositBalance.toString(), '->', spotMarket.depositBalance.toString() ); console.log( 'usdc cum dep interest in spotMarket:', spotMarketBefore.cumulativeDepositInterest.toString(), '->', spotMarket.cumulativeDepositInterest.toString() ); console.log( 'usdc deposits in spotMarket:', usdcDepositsBefore.toString(), '->', usdcDepositsAfter.toString() ); console.log( 'usdc for users:', usdcBefore.toString(), '->', usdcAfter.toString() ); await driftClientUser.unsubscribe(); // TODO: resolve any issues in liq borrow before adding asserts in test here // assert(usdcBefore.eq(usdcAfter)); }); // it('settle spotMarket to insurance vault', async () => { // const marketIndex = new BN(0); // const spotMarket0Before = driftClient.getSpotMarketAccount(marketIndex); // const insuranceVaultAmountBefore = new BN( // ( // await provider.connection.getTokenAccountBalance( // spotMarket0Before.insurance.vault // ) // ).value.amount // ); // assert(insuranceVaultAmountBefore.gt(ZERO)); // assert(spotMarket0Before.revenuePool.scaledBalance.gt(ZERO)); // console.log( // 'userIfShares:', // spotMarket0Before.insurance.userIfShares.toString(), // 'totalIfShares:', // spotMarket0Before.insurance.totalIfShares.toString() // ); // assert(spotMarket0Before.insurance.userIfShares.eq(ZERO)); // assert(spotMarket0Before.insurance.totalIfShares.eq(ZERO)); // 0_od // try { // const txSig = await driftClient.settleRevenueToInsuranceFund(marketIndex); // console.log( // 'tx logs', // (await connection.getTransaction(txSig, { commitment: 'confirmed' })) // .meta.logMessages // ); // } catch (e) { // console.error(e); // assert(false); // } // const spotMarket0 = driftClient.getSpotMarketAccount(marketIndex); // assert(spotMarket0.revenuePool.scaledBalance.eq(ZERO)); // assert(spotMarket0.insurance.totalIfShares.eq(ZERO)); // }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/pauseExchange.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { BN, QUOTE_SPOT_MARKET_INDEX } from '../sdk'; import { Program } from '@coral-xyz/anchor'; import { TestClient, PRICE_PRECISION, PositionDirection, ExchangeStatus, OracleSource, } from '../sdk/src'; import { mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, } from './testHelpers'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('Pause exchange', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 9).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 9).mul( mantissaSqrtScale ); const usdcAmount = new BN(100 * 10 ** 6); before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); const solOracle = await mockOracleNoProgram(bankrunContextWrapper, 30); const periodicity = new BN(60 * 60); // 1 HOUR driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0, 1], subAccountIds: [], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await driftClient.initializePerpMarket( 0, solOracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const marketIndex = 0; const incrementalUSDCNotionalAmount = usdcAmount.mul(new BN(5)); await driftClient.openPosition( PositionDirection.LONG, incrementalUSDCNotionalAmount, marketIndex ); }); after(async () => { await driftClient.unsubscribe(); }); it('Pause exchange', async () => { await driftClient.updateExchangeStatus(ExchangeStatus.PAUSED); const state = driftClient.getStateAccount(); assert(state.exchangeStatus === ExchangeStatus.PAUSED); }); it('Block open position', async () => { try { await driftClient.openPosition(PositionDirection.LONG, usdcAmount, 0); } catch (e) { console.log(e); assert(e.message.includes('0x1788')); //Error Number: 6024. Error Message: Exchange is paused. return; } console.assert(false); }); it('Block close position', async () => { try { await driftClient.closePosition(0); } catch (e) { console.log(e.msg); assert(e.message.includes('0x1788')); return; } console.assert(false); }); it('Block withdrawal', async () => { try { await driftClient.withdraw( usdcAmount, QUOTE_SPOT_MARKET_INDEX, userUSDCAccount.publicKey ); } catch (e) { console.log(e.message); assert(e.message.includes('0x1788')); return; } console.assert(false); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/driftClient.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { BASE_PRECISION, BN, isVariant, PerpMarketAccount, OracleSource, ZERO, } from '../sdk'; import { Program } from '@coral-xyz/anchor'; import { PublicKey, TransactionSignature } from '@solana/web3.js'; import { TestClient, calculateTradeSlippage, PositionDirection, getPerpMarketPublicKey, EventSubscriber, QUOTE_SPOT_MARKET_INDEX, } from '../sdk/src'; import { mockUSDCMint, mockUserUSDCAccount, mockOracleNoProgram, setFeedPriceNoProgram, initializeQuoteSpotMarket, mintUSDCToUser, sleep, } from './testHelpers'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('drift client', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bankrunContextWrapper: BankrunContextWrapper; let bulkAccountLoader: TestBulkAccountLoader; let userAccountPublicKey: PublicKey; let usdcMint; let userUSDCAccount; let solUsd; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(100000); const ammInitialQuoteAssetAmount = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetAmount = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [{ publicKey: solUsd, source: OracleSource.PYTH }], userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); }); after(async () => { await driftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('Initialize State', async () => { await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); const state = driftClient.getStateAccount(); await driftClient.updatePerpAuctionDuration(new BN(0)); assert.ok( state.admin.equals(bankrunContextWrapper.provider.wallet.publicKey) ); const expectedSigner = driftClient.getSignerPublicKey(); assert(state.signer.equals(expectedSigner)); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); }); it('Initialize Market', async () => { const periodicity = new BN(60 * 60); // 1 HOUR const marketIndex = 0; const txSig = await driftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity ); await driftClient.updatePerpMarketStepSizeAndTickSize( 0, new BN(1), new BN(1) ); bankrunContextWrapper.connection.printTxLogs(txSig); const marketPublicKey = await getPerpMarketPublicKey( driftClient.program.programId, marketIndex ); const market = (await driftClient.program.account.perpMarket.fetch( marketPublicKey )) as PerpMarketAccount; assert.ok(JSON.stringify(market.status) === JSON.stringify({ active: {} })); assert.ok(market.amm.baseAssetAmountWithAmm.eq(new BN(0))); assert.ok(market.numberOfUsersWithBase === 0); const ammD = market.amm; console.log(ammD.oracle.toString()); assert.ok(ammD.oracle.equals(solUsd)); assert.ok(ammD.baseAssetReserve.eq(ammInitialBaseAssetAmount)); assert.ok(ammD.quoteAssetReserve.eq(ammInitialQuoteAssetAmount)); assert.ok(ammD.cumulativeFundingRateLong.eq(new BN(0))); assert.ok(ammD.cumulativeFundingRateShort.eq(new BN(0))); assert.ok(ammD.fundingPeriod.eq(periodicity)); assert.ok(ammD.lastFundingRate.eq(new BN(0))); assert.ok(!ammD.lastFundingRateTs.eq(new BN(0))); assert.ok(!ammD.historicalOracleData.lastOraclePriceTwapTs.eq(new BN(0))); }); it('Initialize user account and deposit collateral atomically', async () => { let txSig: TransactionSignature; [txSig, userAccountPublicKey] = await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const user: any = await driftClient.program.account.user.fetch( userAccountPublicKey ); assert.ok( user.authority.equals(bankrunContextWrapper.provider.wallet.publicKey) ); const depositTokenAmount = driftClient.getQuoteAssetTokenAmount(); assert(depositTokenAmount.eq(usdcAmount)); assert( isVariant( driftClient.getSpotPosition(QUOTE_SPOT_MARKET_INDEX).balanceType, 'deposit' ) ); // Check that drift collateral account has proper collateral const quoteSpotVault = await bankrunContextWrapper.connection.getTokenAccount( driftClient.getQuoteSpotMarketAccount().vault ); assert.ok(new BN(Number(quoteSpotVault.amount)).eq(usdcAmount)); assert.ok(user.perpPositions.length == 8); assert.ok(user.perpPositions[0].baseAssetAmount.toNumber() === 0); assert.ok(user.perpPositions[0].quoteBreakEvenAmount.toNumber() === 0); assert.ok(user.perpPositions[0].lastCumulativeFundingRate.toNumber() === 0); await eventSubscriber.awaitTx(txSig); const depositRecord = eventSubscriber.getEventsArray('DepositRecord')[0]; assert.ok( depositRecord.userAuthority.equals( bankrunContextWrapper.provider.wallet.publicKey ) ); assert.ok(depositRecord.user.equals(userAccountPublicKey)); assert.ok( JSON.stringify(depositRecord.direction) === JSON.stringify({ deposit: {} }) ); assert.ok(depositRecord.amount.eq(new BN(10000000))); }); it('Withdraw Collateral', async () => { await driftClient.withdraw( usdcAmount, QUOTE_SPOT_MARKET_INDEX, userUSDCAccount.publicKey, true ); await driftClient.fetchAccounts(); assert(driftClient.getQuoteAssetTokenAmount().eq(ZERO)); // Check that drift collateral account has proper collateral] const quoteSpotVault = await bankrunContextWrapper.connection.getTokenAccount( driftClient.getQuoteSpotMarketAccount().vault ); assert.ok(new BN(Number(quoteSpotVault.amount)).eq(ZERO)); const userUSDCtoken = await bankrunContextWrapper.connection.getTokenAccount( userUSDCAccount.publicKey ); assert.ok(new BN(Number(userUSDCtoken.amount)).eq(usdcAmount)); const depositRecord = eventSubscriber.getEventsArray('DepositRecord')[0]; assert.ok( depositRecord.userAuthority.equals( bankrunContextWrapper.provider.wallet.publicKey ) ); assert.ok(depositRecord.user.equals(userAccountPublicKey)); assert.ok( JSON.stringify(depositRecord.direction) === JSON.stringify({ withdraw: {} }) ); assert.ok(depositRecord.amount.eq(new BN(10000000))); }); it('Long from 0 position', async () => { // Re-Deposit USDC, assuming we have 0 balance here await driftClient.deposit( usdcAmount, QUOTE_SPOT_MARKET_INDEX, userUSDCAccount.publicKey ); const marketIndex = 0; const baseAssetAmount = new BN(48000000000); const txSig = await driftClient.openPosition( PositionDirection.LONG, baseAssetAmount, marketIndex ); bankrunContextWrapper.connection.printTxLogs(txSig); const marketData = driftClient.getPerpMarketAccount(0); await setFeedPriceNoProgram( bankrunContextWrapper, 1.01, marketData.amm.oracle ); const orderR = eventSubscriber.getEventsArray('OrderActionRecord')[0]; console.log(orderR.takerFee.toString()); console.log(orderR.baseAssetAmountFilled.toString()); const user: any = await driftClient.program.account.user.fetch( userAccountPublicKey ); console.log( 'getQuoteAssetTokenAmount:', driftClient.getQuoteAssetTokenAmount().toString() ); assert(driftClient.getQuoteAssetTokenAmount().eq(new BN(10000000))); assert( driftClient .getUserStats() .getAccountAndSlot() .data.fees.totalFeePaid.eq(new BN(48001)) ); assert.ok(user.perpPositions[0].quoteEntryAmount.eq(new BN(-48000001))); assert.ok(user.perpPositions[0].quoteBreakEvenAmount.eq(new BN(-48048002))); assert.ok(user.perpPositions[0].baseAssetAmount.eq(new BN(48000000000))); const market = driftClient.getPerpMarketAccount(0); console.log(market.amm.baseAssetAmountWithAmm.toNumber()); console.log(market); assert.ok(market.amm.baseAssetAmountWithAmm.eq(new BN(48000000000))); console.log(market.amm.totalFee.toString()); assert.ok(market.amm.totalFee.eq(new BN(48001))); assert.ok(market.amm.totalFeeMinusDistributions.eq(new BN(48001))); const orderActionRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderActionRecord.taker.equals(userAccountPublicKey)); assert.ok(orderActionRecord.fillRecordId.eq(new BN(1))); assert.ok(orderActionRecord.baseAssetAmountFilled.eq(new BN(48000000000))); assert.ok(orderActionRecord.quoteAssetAmountFilled.eq(new BN(48000001))); assert.ok(orderActionRecord.marketIndex === marketIndex); assert(driftClient.getPerpMarketAccount(0).nextFillRecordId.eq(new BN(2))); }); it('Withdraw fails due to insufficient collateral', async () => { // lil hack to stop printing errors const oldConsoleLog = console.log; const oldConsoleError = console.error; console.log = function () { const _noop = ''; }; console.error = function () { const _noop = ''; }; try { await driftClient.withdraw( usdcAmount, QUOTE_SPOT_MARKET_INDEX, userUSDCAccount.publicKey ); assert(false, 'Withdrawal succeeded'); } catch (e) { assert(true); } finally { console.log = oldConsoleLog; console.error = oldConsoleError; } }); it('Reduce long position', async () => { const marketIndex = 0; const baseAssetAmount = new BN(24000000000); await driftClient.openPosition( PositionDirection.SHORT, baseAssetAmount, marketIndex ); await driftClient.fetchAccounts(); await driftClient.fetchAccounts(); const user = driftClient.getUserAccount(); console.log( 'quoteAssetAmount:', user.perpPositions[0].quoteAssetAmount.toNumber() ); console.log( 'quoteBreakEvenAmount:', user.perpPositions[0].quoteBreakEvenAmount.toNumber() ); assert.ok(user.perpPositions[0].quoteAssetAmount.eq(new BN(-24072002))); assert.ok(user.perpPositions[0].quoteEntryAmount.eq(new BN(-24000001))); assert.ok(user.perpPositions[0].quoteBreakEvenAmount.eq(new BN(-24048001))); assert.ok(user.perpPositions[0].baseAssetAmount.eq(new BN(24000000000))); console.log(driftClient.getQuoteAssetTokenAmount().toString()); assert.ok(driftClient.getQuoteAssetTokenAmount().eq(new BN(10000000))); console.log( driftClient .getUserStats() .getAccountAndSlot() .data.fees.totalFeePaid.toString() ); assert( driftClient .getUserStats() .getAccountAndSlot() .data.fees.totalFeePaid.eq(new BN(72001)) ); const market = driftClient.getPerpMarketAccount(0); assert.ok(market.amm.baseAssetAmountWithAmm.eq(new BN(24000000000))); assert.ok(market.amm.totalFee.eq(new BN(72001))); assert.ok(market.amm.totalFeeMinusDistributions.eq(new BN(72001))); const orderActionRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderActionRecord.taker.equals(userAccountPublicKey)); assert.ok(orderActionRecord.fillRecordId.eq(new BN(2))); assert.ok(orderActionRecord.baseAssetAmountFilled.eq(new BN(24000000000))); assert.ok(orderActionRecord.quoteAssetAmountFilled.eq(new BN(24000000))); assert.ok(orderActionRecord.marketIndex === 0); }); it('Reverse long position', async () => { const marketData = driftClient.getPerpMarketAccount(0); await setFeedPriceNoProgram( bankrunContextWrapper, 1.0, marketData.amm.oracle ); const baseAssetAmount = new BN(48000000000); await driftClient.openPosition(PositionDirection.SHORT, baseAssetAmount, 0); await driftClient.fetchAccounts(); await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0 ); await driftClient.fetchAccounts(); const user = driftClient.getUserAccount(); console.log( 'quoteAssetAmount:', user.perpPositions[0].quoteAssetAmount.toNumber() ); console.log( 'quoteBreakEvenAmount:', user.perpPositions[0].quoteBreakEvenAmount.toNumber() ); console.log(driftClient.getQuoteAssetTokenAmount().toString()); console.log( driftClient .getUserStats() .getAccountAndSlot() .data.fees.totalFeePaid.toString() ); assert.ok(driftClient.getQuoteAssetTokenAmount().eq(new BN(9879998))); assert( driftClient .getUserStats() .getAccountAndSlot() .data.fees.totalFeePaid.eq(new BN(120001)) ); console.log(user.perpPositions[0].quoteBreakEvenAmount.toString()); console.log(user.perpPositions[0].quoteAssetAmount.toString()); assert.ok(user.perpPositions[0].quoteEntryAmount.eq(new BN(24000000))); assert.ok(user.perpPositions[0].quoteBreakEvenAmount.eq(new BN(23952000))); assert.ok(user.perpPositions[0].quoteAssetAmount.eq(new BN(24000000))); console.log(user.perpPositions[0].baseAssetAmount.toString()); assert.ok(user.perpPositions[0].baseAssetAmount.eq(new BN(-24000000000))); const market = driftClient.getPerpMarketAccount(0); assert.ok(market.amm.baseAssetAmountWithAmm.eq(new BN(-24000000000))); assert.ok(market.amm.totalFee.eq(new BN(120001))); assert.ok(market.amm.totalFeeMinusDistributions.eq(new BN(120001))); const orderActionRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderActionRecord.taker.equals(userAccountPublicKey)); assert.ok(orderActionRecord.fillRecordId.eq(new BN(3))); console.log(orderActionRecord.baseAssetAmountFilled.toNumber()); assert.ok(orderActionRecord.baseAssetAmountFilled.eq(new BN(48000000000))); assert.ok(orderActionRecord.quoteAssetAmountFilled.eq(new BN(48000000))); assert.ok(orderActionRecord.marketIndex === 0); }); it('Close position', async () => { const marketIndex = 0; await driftClient.closePosition(marketIndex); await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); const user: any = await driftClient.program.account.user.fetch( userAccountPublicKey ); assert.ok(user.perpPositions[0].quoteBreakEvenAmount.eq(new BN(0))); assert.ok(user.perpPositions[0].baseAssetAmount.eq(new BN(0))); console.log(driftClient.getQuoteAssetTokenAmount().toString()); assert.ok(driftClient.getQuoteAssetTokenAmount().eq(new BN(9855998))); console.log( driftClient .getUserStats() .getAccountAndSlot() .data.fees.totalFeePaid.toString() ); assert( driftClient .getUserStats() .getAccountAndSlot() .data.fees.totalFeePaid.eq(new BN(144001)) ); const market = driftClient.getPerpMarketAccount(0); assert.ok(market.amm.baseAssetAmountWithAmm.eq(new BN(0))); assert.ok(market.amm.totalFee.eq(new BN(144001))); assert.ok(market.amm.totalFeeMinusDistributions.eq(new BN(144001))); const orderActionRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderActionRecord.taker.equals(userAccountPublicKey)); assert.ok(orderActionRecord.fillRecordId.eq(new BN(4))); assert.ok(orderActionRecord.baseAssetAmountFilled.eq(new BN(24000000000))); assert.ok(orderActionRecord.quoteAssetAmountFilled.eq(new BN(24000000))); assert.ok(orderActionRecord.marketIndex === 0); }); it('Open short position', async () => { const baseAssetAmount = new BN(48000000000); await driftClient.openPosition(PositionDirection.SHORT, baseAssetAmount, 0); await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0 ); const user = await driftClient.program.account.user.fetch( userAccountPublicKey ); console.log(user.perpPositions[0].quoteBreakEvenAmount.toString()); assert.ok(user.perpPositions[0].quoteEntryAmount.eq(new BN(47999999))); assert.ok(user.perpPositions[0].quoteBreakEvenAmount.eq(new BN(47951999))); assert.ok(user.perpPositions[0].baseAssetAmount.eq(new BN(-48000000000))); const market = driftClient.getPerpMarketAccount(0); assert.ok(market.amm.baseAssetAmountWithAmm.eq(new BN(-48000000000))); const orderActionRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderActionRecord.taker.equals(userAccountPublicKey)); assert.ok(orderActionRecord.fillRecordId.eq(new BN(5))); assert.ok(orderActionRecord.baseAssetAmountFilled.eq(new BN(48000000000))); assert.ok(orderActionRecord.quoteAssetAmountFilled.eq(new BN(47999999))); assert.ok(orderActionRecord.marketIndex === 0); }); it('Trade small size position', async () => { await mintUSDCToUser( usdcMint, userUSDCAccount.publicKey, usdcAmount, bankrunContextWrapper ); await sleep(2000); await driftClient.deposit( usdcAmount, QUOTE_SPOT_MARKET_INDEX, userUSDCAccount.publicKey ); try { await driftClient.openPosition( PositionDirection.LONG, driftClient.getPerpMarketAccount(0).amm.orderStepSize, 0 ); } catch (e) { console.log(e); } }); it('Short order succeeds due to realiziable limit price ', async () => { const baseAssetAmount = BASE_PRECISION; const marketIndex = 0; const market = driftClient.getPerpMarketAccount(marketIndex); const estTradePrice = calculateTradeSlippage( PositionDirection.SHORT, baseAssetAmount, market, 'base', undefined, true )[2]; await driftClient.openPosition( PositionDirection.SHORT, baseAssetAmount, marketIndex, estTradePrice ); await driftClient.fetchAccounts(); await driftClient.closePosition(marketIndex); }); it('Long order succeeds due to realiziable limit price ', async () => { const baseAssetAmount = BASE_PRECISION; const marketIndex = 0; const market = driftClient.getPerpMarketAccount(marketIndex); const estTradePrice = calculateTradeSlippage( PositionDirection.LONG, baseAssetAmount, market, 'base' )[2]; await driftClient.openPosition( PositionDirection.LONG, baseAssetAmount, marketIndex, estTradePrice.add(market.amm.orderTickSize) ); await driftClient.fetchAccounts(); await driftClient.closePosition(marketIndex); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/postOnlyAmmFulfillment.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair } from '@solana/web3.js'; import { TestClient, BN, PRICE_PRECISION, PositionDirection, User, Wallet, EventSubscriber, MarketStatus, BASE_PRECISION, calculateReservePrice, getLimitOrderParams, isVariant, OracleSource, PEG_PRECISION, ZERO, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, sleep, } from './testHelpers'; import { convertToNumber, PostOnlyParams } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('post only maker order w/ amm fulfillments', () => { const chProgram = anchor.workspace.Drift as Program; let fillerDriftClient: TestClient; let fillerDriftClientUser: User; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(100000); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); let solUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 32.821); marketIndexes = [0]; spotMarketIndexes = [0]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; fillerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClient.initialize(usdcMint.publicKey, true); await fillerDriftClient.subscribe(); await initializeQuoteSpotMarket(fillerDriftClient, usdcMint.publicKey); await fillerDriftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(60 * 60); // 1 HOUR await fillerDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(32.821 * PEG_PRECISION.toNumber()) ); await fillerDriftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); await fillerDriftClient.updatePerpMarketBaseSpread(0, 500); await fillerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); fillerDriftClientUser = new User({ driftClient: fillerDriftClient, userAccountPublicKey: await fillerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClientUser.subscribe(); }); beforeEach(async () => { await fillerDriftClient.moveAmmPrice( 0, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve ); await setFeedPriceNoProgram(bankrunContextWrapper, 32.821, solUsd); }); after(async () => { await fillerDriftClient.unsubscribe(); await fillerDriftClientUser.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('long', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); await sleep(1000); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const reservePrice = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); const newOraclePrice = 0.98 * 32.821; const newOraclePriceBN = new BN( newOraclePrice * PRICE_PRECISION.toNumber() ); setFeedPriceNoProgram(bankrunContextWrapper, newOraclePrice, solUsd); await fillerDriftClient.moveAmmToPrice(marketIndex, newOraclePriceBN); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); await fillerDriftClient.fetchAccounts(); const reservePrice2 = calculateReservePrice( fillerDriftClient.getPerpMarketAccount(marketIndex), undefined ); console.log( 'new amm prices:', newOraclePrice, 'vs', reservePrice2.toString() ); assert(reservePrice2.eq(new BN('32172703'))); const makerOrderParams2 = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount: baseAssetAmount.div(new BN(2)), price: reservePrice2.add( driftClient.getPerpMarketAccount(marketIndex).amm.orderTickSize ), userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, }); await fillerDriftClient.placePerpOrder(makerOrderParams2); await fillerDriftClient.fetchAccounts(); const order2 = fillerDriftClient.getOrderByUserId(1); assert(order2.postOnly); await setFeedPriceNoProgram( bankrunContextWrapper, convertToNumber(reservePrice), solUsd ); const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, price: reservePrice, userOrderId: 1, postOnly: PostOnlyParams.NONE, }); await driftClient.placePerpOrder(makerOrderParams); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); assert(!order.postOnly); await setFeedPriceNoProgram(bankrunContextWrapper, newOraclePrice, solUsd); const makerInfo = { maker: await fillerDriftClient.getUserAccountPublicKey(), makerStats: fillerDriftClient.getUserStatsAccountPublicKey(), makerUserAccount: fillerDriftClient.getUserAccount(), order: order2, }; const txSig = await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order, makerInfo ); bankrunContextWrapper.printTxLogs(txSig); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const position = driftClientUser.getPerpPosition(marketIndex); assert(position.baseAssetAmount.eq(baseAssetAmount)); console.log(position.quoteAssetAmount.toString()); console.log(position.quoteBreakEvenAmount.toString()); console.log(position.quoteEntryAmount.toString()); assert(position.quoteAssetAmount.eq(new BN(-32208912))); assert(position.quoteEntryAmount.eq(new BN(-32176734))); assert(position.quoteBreakEvenAmount.eq(new BN(-32208912))); console.log( 'driftClient.getQuoteAssetTokenAmount:', driftClient.getQuoteAssetTokenAmount().toString(), 'vs', usdcAmount.toString() ); assert(driftClient.getQuoteAssetTokenAmount().eq(usdcAmount)); const driftClientUserStats = driftClient.getUserStats().getAccount(); console.log('user stats:', driftClientUserStats); assert(driftClientUserStats.fees.totalFeePaid.eq(new BN(32178))); assert(driftClientUserStats.fees.totalFeeRebate.eq(ZERO)); await fillerDriftClient.fetchAccounts(); const orderRecords = eventSubscriber.getEventsArray('OrderActionRecord'); console.log(orderRecords.length, 'orderRecords found.'); assert(orderRecords.length == 4); const orderRecord = orderRecords[0]; // console.log(orderRecords); console.log(orderRecord); assert(isVariant(orderRecord.action, 'fill')); assert(isVariant(orderRecord.actionExplanation, 'orderFilledWithAmm')); assert(orderRecord.takerFee.eq(new BN(16091))); assert(orderRecord.fillRecordId.eq(new BN(2))); assert(orderRecord.fillerReward.eq(ZERO)); assert(orderRecord.quoteAssetAmountSurplus.eq(new BN(4022))); assert(orderRecord.oraclePrice.eq(new BN(32164580))); assert(orderRecord.baseAssetAmountFilled.eq(new BN(1000000000 / 2))); assert(orderRecord.quoteAssetAmountFilled.eq(new BN(16090374))); assert(orderRecord.maker == null); const orderRecord2 = orderRecords[1]; console.log(orderRecord2); assert(isVariant(orderRecord2.action, 'fill')); assert(isVariant(orderRecord2.actionExplanation, 'orderFilledWithMatch')); // assert(orderRecord2.maker == await fillerDriftClient.getUserAccountPublicKey()); // assert(orderRecord2.taker == await driftClient.getUserAccountPublicKey()); assert(orderRecord2.baseAssetAmountFilled.eq(new BN(1000000000 / 2))); console.log(orderRecord2.quoteAssetAmountFilled.toString()); assert(orderRecord2.quoteAssetAmountFilled.eq(new BN(16086360))); assert(orderRecord2.quoteAssetAmountSurplus == null); assert(orderRecord2.makerFee.eq(new BN(-3217))); assert(orderRecord2.takerFee.eq(new BN(16087))); assert(orderRecord2.fillerReward.eq(ZERO)); const orderRecord3 = orderRecords[2]; console.log(orderRecord3); assert(isVariant(orderRecord3.action, 'place')); assert(isVariant(orderRecord3.actionExplanation, 'none')); const orderRecord4 = orderRecords[3]; console.log(orderRecord4); assert(isVariant(orderRecord4.action, 'place')); assert(isVariant(orderRecord4.actionExplanation, 'none')); await fillerDriftClientUser.fetchAccounts(); const positionMaker = fillerDriftClientUser.getPerpPosition(marketIndex); console.log(positionMaker); assert(positionMaker.baseAssetAmount.eq(new BN(-500000000))); console.log(positionMaker.quoteAssetAmount.toString()); console.log(positionMaker.quoteBreakEvenAmount.toString()); assert(positionMaker.quoteAssetAmount.eq(new BN(16089577))); assert(positionMaker.quoteEntryAmount.eq(new BN(16086360))); assert(positionMaker.quoteBreakEvenAmount.eq(new BN(16089577))); await fillerDriftClient.fetchAccounts(); const perpMarket = fillerDriftClient.getPerpMarketAccount(0); console.log(perpMarket.amm.totalFee.toString()); console.log(perpMarket.amm.totalFeeMinusDistributions.toString()); console.log(perpMarket.amm.totalExchangeFee.toString()); console.log(perpMarket.amm.totalMmFee.toString()); console.log(perpMarket.amm.totalFeeWithdrawn.toString()); assert(perpMarket.amm.totalFee.eq(new BN(32983))); assert(perpMarket.amm.totalFeeMinusDistributions.eq(new BN(32983))); assert(perpMarket.amm.totalExchangeFee.eq(new BN(28961))); assert(perpMarket.amm.totalMmFee.eq(new BN(4022))); assert(perpMarket.amm.totalFeeWithdrawn.eq(ZERO)); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/order.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair, PublicKey } from '@solana/web3.js'; import { TestClient, BN, PRICE_PRECISION, PositionDirection, User, OrderStatus, OrderAction, OrderTriggerCondition, calculateTargetPriceTrade, convertToNumber, QUOTE_PRECISION, Wallet, calculateTradeSlippage, getLimitOrderParams, getTriggerMarketOrderParams, EventSubscriber, standardizeBaseAssetAmount, calculateBaseAssetAmountForAmmToFulfill, OracleGuardRails, } from '../sdk/src'; import { mockOracleNoProgram, mockUserUSDCAccount, mockUSDCMint, setFeedPriceNoProgram, initializeQuoteSpotMarket, sleep, } from './testHelpers'; import { AMM_RESERVE_PRECISION, calculateReservePrice, getMarketOrderParams, isVariant, OracleSource, PEG_PRECISION, TEN_THOUSAND, TWO, ZERO, } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; const enumsAreEqual = ( actual: Record<string, unknown>, expected: Record<string, unknown> ): boolean => { return JSON.stringify(actual) === JSON.stringify(expected); }; describe('orders', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let driftClientUser: User; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let userAccountPublicKey: PublicKey; let whaleAccountPublicKey: PublicKey; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 11).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 11).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); const whaleKeyPair = new Keypair(); const usdcAmountWhale = new BN(10000000 * 10 ** 6); let whaleUSDCAccount: Keypair; let whaleDriftClient: TestClient; let whaleUser: User; const fillerKeyPair = new Keypair(); let fillerUSDCAccount: Keypair; let fillerDriftClient: TestClient; let fillerUser: User; const marketIndex = 0; const marketIndexBTC = 1; const marketIndexEth = 2; let solUsd; let btcUsd; let ethUsd; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); btcUsd = await mockOracleNoProgram(bankrunContextWrapper, 60000); ethUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); const marketIndexes = [marketIndex, marketIndexBTC, marketIndexEth]; const bankIndexes = [0]; const oracleInfos = [ { publicKey: PublicKey.default, source: OracleSource.QUOTE_ASSET }, { publicKey: solUsd, source: OracleSource.PYTH }, { publicKey: btcUsd, source: OracleSource.PYTH }, { publicKey: ethUsd, source: OracleSource.PYTH }, ]; driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: bankIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); let oraclesLoaded = false; while (!oraclesLoaded) { const found = !!driftClient.accountSubscriber.getOraclePriceDataAndSlotForSpotMarket( 0 ); if (found) { oraclesLoaded = found; } await sleep(1000); } console.log(bulkAccountLoader.mostRecentSlot); const periodicity = new BN(60 * 60); // 1 HOUR await driftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await driftClient.updatePerpMarketStepSizeAndTickSize( 0, new BN(1000), new BN(1) ); await driftClient.initializePerpMarket( 1, btcUsd, ammInitialBaseAssetReserve.div(new BN(3000)), ammInitialQuoteAssetReserve.div(new BN(3000)), periodicity, new BN(60000 * PEG_PRECISION.toNumber()) // btc-ish price level ); await driftClient.updatePerpMarketStepSizeAndTickSize( 1, new BN(1000), new BN(1) ); await driftClient.initializePerpMarket( 2, ethUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await driftClient.updatePerpMarketStepSizeAndTickSize( 2, new BN(1000), new BN(1) ); [, userAccountPublicKey] = await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); await bankrunContextWrapper.fundKeypair(fillerKeyPair, 10 ** 9); fillerUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, fillerKeyPair.publicKey ); fillerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(fillerKeyPair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: bankIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClient.subscribe(); await fillerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, fillerUSDCAccount.publicKey ); fillerUser = new User({ driftClient: fillerDriftClient, userAccountPublicKey: await fillerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerUser.subscribe(); await bankrunContextWrapper.fundKeypair(whaleKeyPair, 10 ** 9); whaleUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmountWhale, bankrunContextWrapper, whaleKeyPair.publicKey ); whaleDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(whaleKeyPair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, perpMarketIndexes: marketIndexes, spotMarketIndexes: bankIndexes, oracleInfos, subAccountIds: [], userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await whaleDriftClient.subscribe(); [, whaleAccountPublicKey] = await whaleDriftClient.initializeUserAccountAndDepositCollateral( usdcAmountWhale, whaleUSDCAccount.publicKey ); whaleUser = new User({ driftClient: whaleDriftClient, userAccountPublicKey: await whaleDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await whaleUser.subscribe(); }); after(async () => { await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); await fillerDriftClient.unsubscribe(); await fillerUser.unsubscribe(); await whaleDriftClient.unsubscribe(); await whaleUser.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('Open long limit order', async () => { // user has $10, no open positions, trading in market of $1 mark price coin const direction = PositionDirection.LONG; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const price = PRICE_PRECISION.add(PRICE_PRECISION.div(new BN(100))); const reduceOnly = false; const triggerPrice = new BN(0); const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price, reduceOnly, }); const txSig = await driftClient.placePerpOrder(orderParams); bankrunContextWrapper.printTxLogs(txSig); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const order = driftClientUser.getUserAccount().orders[0]; const expectedOrderId = 1; assert(order.baseAssetAmount.eq(baseAssetAmount)); assert(order.price.eq(price)); assert(order.triggerPrice.eq(triggerPrice)); assert(order.marketIndex === marketIndex); assert(order.reduceOnly === reduceOnly); assert(enumsAreEqual(order.direction, direction)); assert(enumsAreEqual(order.status, OrderStatus.OPEN)); assert(order.orderId === expectedOrderId); const position = driftClientUser.getUserAccount().perpPositions[0]; assert(position.openOrders === 1); assert(position.openBids.eq(baseAssetAmount)); assert(position.openAsks.eq(ZERO)); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert(orderRecord.ts.gt(ZERO)); assert(enumsAreEqual(orderRecord.action, OrderAction.PLACE)); assert( orderRecord.taker.equals(await driftClientUser.getUserAccountPublicKey()) ); }); it('Cancel order', async () => { const orderIndex = new BN(0); await driftClient.cancelOrder(undefined); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const order = driftClientUser.getUserAccount().orders[orderIndex.toNumber()]; assert(order.baseAssetAmount.eq(new BN(0))); assert(order.price.eq(new BN(0))); assert(order.marketIndex === 0); assert(enumsAreEqual(order.direction, PositionDirection.LONG)); assert(enumsAreEqual(order.status, OrderStatus.INIT)); const position = driftClientUser.getUserAccount().perpPositions[0]; assert(position.openOrders === 0); assert(position.openBids.eq(ZERO)); assert(position.openAsks.eq(ZERO)); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; const expectedOrderId = 1; assert(orderRecord.ts.gt(ZERO)); assert(orderRecord.takerOrderId === expectedOrderId); assert(enumsAreEqual(orderRecord.action, OrderAction.CANCEL)); assert( orderRecord.taker.equals(await driftClientUser.getUserAccountPublicKey()) ); }); it('Fill limit long order', async () => { const direction = PositionDirection.LONG; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const price = PRICE_PRECISION.add(PRICE_PRECISION.div(new BN(100))); const market0 = driftClient.getPerpMarketAccount(marketIndex); console.log('markPrice:', calculateReservePrice(market0).toString()); const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price, }); await driftClient.placePerpOrder(orderParams); const orderIndex = new BN(0); const orderId = 2; await driftClientUser.fetchAccounts(); assert( driftClientUser.getPerpPosition(marketIndex).openBids.eq(baseAssetAmount) ); assert(driftClientUser.getPerpPosition(marketIndex).openAsks.eq(ZERO)); let order = driftClientUser.getOrder(orderId); await fillerDriftClient.fillPerpOrder( userAccountPublicKey, driftClientUser.getUserAccount(), order ); await fillerDriftClient.settlePNLs( [ { settleeUserAccountPublicKey: await driftClient.getUserAccountPublicKey(), settleeUserAccount: driftClient.getUserAccount(), }, { settleeUserAccountPublicKey: await fillerDriftClient.getUserAccountPublicKey(), settleeUserAccount: fillerDriftClient.getUserAccount(), }, ], [marketIndex] ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); await fillerUser.fetchAccounts(); assert(driftClientUser.getPerpPosition(marketIndex).openBids.eq(ZERO)); assert(driftClientUser.getPerpPosition(marketIndex).openAsks.eq(ZERO)); order = driftClientUser.getUserAccount().orders[orderIndex.toString()]; const expectedFillerReward = new BN(100); console.log( 'FillerReward: $', convertToNumber( fillerDriftClient.getQuoteAssetTokenAmount().sub(usdcAmount), QUOTE_PRECISION ) ); console.log(); assert( fillerDriftClient .getQuoteAssetTokenAmount() .sub(usdcAmount) .eq(expectedFillerReward) ); const market = driftClient.getPerpMarketAccount(marketIndex); console.log('markPrice After:', calculateReservePrice(market).toString()); const expectedFeeToMarket = new BN(901); assert(market.amm.totalFee.eq(expectedFeeToMarket)); assert(order.baseAssetAmount.eq(new BN(0))); assert(order.price.eq(new BN(0))); assert(order.marketIndex === 0); assert(enumsAreEqual(order.direction, PositionDirection.LONG)); assert(enumsAreEqual(order.status, OrderStatus.INIT)); const firstPosition = driftClientUser.getUserAccount().perpPositions[0]; assert(firstPosition.baseAssetAmount.eq(baseAssetAmount)); assert(firstPosition.openBids.eq(new BN(0))); const expectedQuoteAssetAmount = new BN(-1000003); const expectedQuoteBreakEvenAmount = new BN(-1001004); // console.log(convertToNumber(firstPosition.quoteAssetAmount, QUOTE_PRECISION), // '!=', // convertToNumber(expectedQuoteAssetAmount, QUOTE_PRECISION), // ); assert(firstPosition.quoteEntryAmount.eq(expectedQuoteAssetAmount)); assert(firstPosition.quoteBreakEvenAmount.eq(expectedQuoteBreakEvenAmount)); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderRecord.baseAssetAmountFilled.eq(baseAssetAmount)); assert.ok( orderRecord.quoteAssetAmountFilled.eq(expectedQuoteAssetAmount.abs()) ); const expectedFillRecordId = new BN(1); const expectedFee = new BN(1001); assert(orderRecord.ts.gt(ZERO)); assert(orderRecord.takerFee.eq(expectedFee)); assert(enumsAreEqual(orderRecord.action, OrderAction.FILL)); assert( orderRecord.taker.equals(await driftClientUser.getUserAccountPublicKey()) ); assert( orderRecord.filler.equals(await fillerUser.getUserAccountPublicKey()) ); assert(orderRecord.baseAssetAmountFilled.eq(baseAssetAmount)); assert( orderRecord.quoteAssetAmountFilled.eq(expectedQuoteAssetAmount.abs()) ); assert(orderRecord.fillerReward.eq(expectedFillerReward)); assert(orderRecord.fillRecordId.eq(expectedFillRecordId)); }); it('Fill stop short order', async () => { const direction = PositionDirection.SHORT; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const triggerPrice = PRICE_PRECISION.sub(PRICE_PRECISION.div(new BN(10))); const triggerCondition = OrderTriggerCondition.ABOVE; const market0 = driftClient.getPerpMarketAccount(marketIndex); console.log('markPrice:', calculateReservePrice(market0).toString()); const orderParams = getTriggerMarketOrderParams({ marketIndex, direction, baseAssetAmount, triggerPrice, triggerCondition, }); await driftClient.placePerpOrder(orderParams); const orderId = 3; const orderIndex = new BN(0); await driftClientUser.fetchAccounts(); assert(driftClientUser.getPerpPosition(marketIndex).openAsks.eq(ZERO)); assert(driftClientUser.getPerpPosition(marketIndex).openBids.eq(ZERO)); let order = driftClientUser.getOrder(orderId); await fillerDriftClient.triggerOrder( userAccountPublicKey, driftClientUser.getUserAccount(), order ); const txSig = await fillerDriftClient.fillPerpOrder( userAccountPublicKey, driftClientUser.getUserAccount(), order ); const computeUnits = bankrunContextWrapper.connection.findComputeUnitConsumption(txSig); console.log('compute units', computeUnits); bankrunContextWrapper.printTxLogs(txSig); await fillerDriftClient.settlePNLs( [ { settleeUserAccountPublicKey: await driftClient.getUserAccountPublicKey(), settleeUserAccount: driftClient.getUserAccount(), }, { settleeUserAccountPublicKey: await fillerDriftClient.getUserAccountPublicKey(), settleeUserAccount: fillerDriftClient.getUserAccount(), }, ], [marketIndex] ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); await fillerUser.fetchAccounts(); assert(driftClientUser.getPerpPosition(marketIndex) === undefined); order = driftClientUser.getUserAccount().orders[orderIndex.toString()]; const expectedFillerReward = new BN(10200); console.log( 'FillerReward: $', convertToNumber( fillerDriftClient.getQuoteAssetTokenAmount().sub(usdcAmount), QUOTE_PRECISION ) ); assert( fillerDriftClient .getQuoteAssetTokenAmount() .sub(usdcAmount) .eq(expectedFillerReward) ); const market = driftClient.getPerpMarketAccount(marketIndex); console.log('markPrice after:', calculateReservePrice(market).toString()); console.log('market.amm.totalFee:', market.amm.totalFee.toString()); const expectedFeeToMarket = new BN(1802); assert(market.amm.totalFee.eq(expectedFeeToMarket)); assert(order.baseAssetAmount.eq(new BN(0))); assert(order.price.eq(new BN(0))); assert(order.marketIndex === 0); assert(enumsAreEqual(order.direction, PositionDirection.LONG)); assert(enumsAreEqual(order.status, OrderStatus.INIT)); const firstPosition = driftClientUser.getUserAccount().perpPositions[0]; const expectedBaseAssetAmount = new BN(0); assert(firstPosition.baseAssetAmount.eq(expectedBaseAssetAmount)); const expectedQuoteAssetAmount = new BN(0); assert(firstPosition.quoteBreakEvenAmount.eq(expectedQuoteAssetAmount)); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderRecord.baseAssetAmountFilled.eq(baseAssetAmount)); const expectedTradeQuoteAssetAmount = new BN(1000002); console.log( 'expectedTradeQuoteAssetAmount check:', orderRecord.quoteAssetAmountFilled.toString(), '=', expectedTradeQuoteAssetAmount.toString() ); assert.ok( orderRecord.quoteAssetAmountFilled.eq(expectedTradeQuoteAssetAmount) ); const expectedOrderId = 3; const expectedFillRecordId = new BN(2); assert(orderRecord.ts.gt(ZERO)); assert(orderRecord.takerOrderId === expectedOrderId); assert(enumsAreEqual(orderRecord.action, OrderAction.FILL)); assert( orderRecord.taker.equals(await driftClientUser.getUserAccountPublicKey()) ); assert( orderRecord.filler.equals(await fillerUser.getUserAccountPublicKey()) ); assert(orderRecord.baseAssetAmountFilled.eq(baseAssetAmount)); assert( orderRecord.quoteAssetAmountFilled.eq(expectedTradeQuoteAssetAmount) ); assert(orderRecord.fillRecordId.eq(expectedFillRecordId)); }); it('Fail to fill limit short order', async () => { const direction = PositionDirection.SHORT; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const market = driftClient.getPerpMarketAccount(marketIndex); const limitPrice = calculateReservePrice(market); // 0 liquidity at current mark price const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price: limitPrice, }); await driftClient.placePerpOrder(orderParams); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); let order = driftClientUser.getUserAccount().orders[0]; const amountToFill = calculateBaseAssetAmountForAmmToFulfill( order, market, driftClient.getOracleDataForPerpMarket(order.marketIndex), 0 ); assert( driftClientUser .getPerpPosition(marketIndex) .openAsks.eq(baseAssetAmount.neg()) ); assert(driftClientUser.getPerpPosition(marketIndex).openBids.eq(ZERO)); assert(amountToFill.eq(ZERO)); console.log(amountToFill); const orderId = 4; await driftClientUser.fetchAccounts(); order = driftClientUser.getOrder(orderId); console.log(order); await fillerDriftClient.fillPerpOrder( userAccountPublicKey, driftClientUser.getUserAccount(), order ); const order2 = driftClientUser.getOrder(orderId); console.log(order2); await driftClient.cancelOrder(orderId); assert(driftClientUser.getPerpPosition(marketIndex) === undefined); }); it('Partial fill limit short order', async () => { const direction = PositionDirection.SHORT; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); await driftClient.fetchAccounts(); const market = driftClient.getPerpMarketAccount(marketIndex); const limitPrice = calculateReservePrice(market).sub( market.amm.orderTickSize.mul(new BN(2)) ); // 0 liquidity at current mark price const [newDirection, amountToPrice, _entryPrice, newMarkPrice] = calculateTargetPriceTrade(market, limitPrice, new BN(1000), 'base'); assert(!amountToPrice.eq(ZERO)); assert(newDirection == direction); console.log( convertToNumber(calculateReservePrice(market)), 'then short @', convertToNumber(limitPrice), newDirection, convertToNumber(newMarkPrice), 'available liquidity', convertToNumber(amountToPrice, AMM_RESERVE_PRECISION) ); assert(baseAssetAmount.gt(amountToPrice)); // assert its a partial fill of liquidity // const triggerPrice = new BN(0); // const triggerCondition = OrderTriggerCondition.BELOW; const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price: limitPrice, }); await driftClient.placePerpOrder(orderParams); await driftClientUser.fetchAccounts(); const order = driftClientUser.getUserAccount().orders[0]; const amountToFill = calculateBaseAssetAmountForAmmToFulfill( order, market, driftClient.getOracleDataForPerpMarket(order.marketIndex), 0 ); assert( driftClientUser .getPerpPosition(marketIndex) .openAsks.eq(baseAssetAmount.neg()) ); assert(driftClientUser.getPerpPosition(marketIndex).openBids.eq(ZERO)); console.log(amountToFill.toString()); const orderId = 5; await fillerDriftClient.fillPerpOrder( userAccountPublicKey, driftClientUser.getUserAccount(), order ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); await fillerUser.fetchAccounts(); const market2 = driftClient.getPerpMarketAccount(marketIndex); const order2 = driftClientUser.getUserAccount().orders[0]; console.log( 'order filled: ', convertToNumber(order.baseAssetAmount), '->', convertToNumber(order2.baseAssetAmount) ); console.log(order2); const position = driftClientUser.getUserAccount().perpPositions[0]; console.log( 'curPosition', convertToNumber(position.baseAssetAmount, AMM_RESERVE_PRECISION) ); assert(order.baseAssetAmountFilled.eq(ZERO)); assert(order.baseAssetAmount.eq(order2.baseAssetAmount)); assert(order2.baseAssetAmountFilled.gt(ZERO)); assert( order2.baseAssetAmount .sub(order2.baseAssetAmountFilled) .add(position.baseAssetAmount.abs()) .eq(order.baseAssetAmount) ); assert( driftClientUser .getPerpPosition(marketIndex) .openAsks.eq(baseAssetAmount.sub(order2.baseAssetAmountFilled).neg()) ); assert(driftClientUser.getPerpPosition(marketIndex).openBids.eq(ZERO)); const amountToFill2 = calculateBaseAssetAmountForAmmToFulfill( order2, market2, driftClient.getOracleDataForPerpMarket(order.marketIndex), 0 ); assert(amountToFill2.eq(ZERO)); await driftClient.cancelOrder(orderId); }); it('Max leverage fill limit short order', async () => { //todo, partial fill wont work on order too large const userLeverage0 = driftClientUser.getLeverage(); console.log( 'user initial leverage:', convertToNumber(userLeverage0, TEN_THOUSAND) ); const direction = PositionDirection.SHORT; const market = driftClient.getPerpMarketAccount(marketIndex); const limitPrice = calculateReservePrice(market); // 0 liquidity at current mark price const baseAssetAmount = new BN(27571723885); //long 50 base amount at $1 with ~$10 collateral (max leverage = 5x) const [newDirection, amountToPrice, _entryPrice, newMarkPrice] = calculateTargetPriceTrade(market, limitPrice, new BN(1000), 'base'); assert(amountToPrice.eq(ZERO)); // no liquidity now console.log( convertToNumber(calculateReservePrice(market)), 'then short', convertToNumber(baseAssetAmount, AMM_RESERVE_PRECISION), 'CRISP @', convertToNumber(limitPrice), newDirection, convertToNumber(newMarkPrice), 'available liquidity', convertToNumber(amountToPrice, AMM_RESERVE_PRECISION) ); assert(baseAssetAmount.gt(amountToPrice)); // assert its a partial fill of liquidity console.log(limitPrice.toString()); const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price: limitPrice, }); await driftClient.placePerpOrder(orderParams); const newPrice = convertToNumber( limitPrice.mul(new BN(104)).div(new BN(100)), PRICE_PRECISION ); // move price to make liquidity for order @ $1.05 (5%) await setFeedPriceNoProgram(bankrunContextWrapper, newPrice, solUsd); await driftClient.moveAmmToPrice( marketIndex, new BN(newPrice * PRICE_PRECISION.toNumber()) ); console.log('user leverage:', convertToNumber(userLeverage0, TEN_THOUSAND)); await driftClientUser.fetchAccounts(); const order = driftClientUser.getUserAccount().orders[0]; const amountToFill = calculateBaseAssetAmountForAmmToFulfill( order, market, driftClient.getOracleDataForPerpMarket(order.marketIndex), 0 ); const standardizedBaseAssetAmount = standardizeBaseAssetAmount( baseAssetAmount, driftClient.getPerpMarketAccount(marketIndex).amm.orderStepSize ); assert( driftClientUser .getPerpPosition(marketIndex) .openAsks.eq(standardizedBaseAssetAmount.neg()) ); assert(driftClientUser.getPerpPosition(marketIndex).openBids.eq(ZERO)); console.log(amountToFill); await fillerDriftClient.fillPerpOrder( userAccountPublicKey, driftClientUser.getUserAccount(), order ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); await fillerUser.fetchAccounts(); assert(driftClientUser.getPerpPosition(marketIndex).openAsks.eq(ZERO)); assert(driftClientUser.getPerpPosition(marketIndex).openBids.eq(ZERO)); const order1 = driftClientUser.getUserAccount().orders[0]; const newMarket1 = driftClient.getPerpMarketAccount(marketIndex); const newMarkPrice1 = calculateReservePrice(newMarket1); // 0 liquidity at current mark price const userLeverage = driftClientUser.getLeverage(); console.log( 'mark price:', convertToNumber(newMarkPrice1, PRICE_PRECISION), 'base filled / amt:', convertToNumber(order1.baseAssetAmountFilled, AMM_RESERVE_PRECISION), '/', convertToNumber(order1.baseAssetAmount, AMM_RESERVE_PRECISION), '\n', 'user leverage:', convertToNumber(userLeverage, TEN_THOUSAND), '\n' ); // await driftClient.closePosition(marketIndex); }); it('When in Max leverage short, fill limit long order to reduce to ZERO', async () => { //todo, partial fill wont work on order too large const userLeverage0 = driftClientUser.getLeverage(); const prePosition = driftClientUser.getPerpPosition(marketIndex); console.log( 'user initial leverage:', convertToNumber(userLeverage0, TEN_THOUSAND) ); const direction = PositionDirection.LONG; const market = driftClient.getPerpMarketAccount(marketIndex); const limitPrice = calculateReservePrice(market); // 0 liquidity at current mark price const baseAssetAmount = prePosition.baseAssetAmount.abs(); //new BN(AMM_RESERVE_PRECISION.mul(new BN(50))); //long 50 base amount at $1 with ~$10 collateral (max leverage = 5x) const [newDirection, amountToPrice, _entryPrice, newMarkPrice] = calculateTargetPriceTrade(market, limitPrice, new BN(1000), 'base'); assert(amountToPrice.eq(ZERO)); // no liquidity now console.log( convertToNumber(calculateReservePrice(market)), 'then long', convertToNumber(baseAssetAmount, AMM_RESERVE_PRECISION), '$CRISP @', convertToNumber(limitPrice), newDirection, convertToNumber(newMarkPrice), 'available liquidity', convertToNumber(amountToPrice, AMM_RESERVE_PRECISION) ); assert(baseAssetAmount.gt(amountToPrice)); // assert its a partial fill of liquidity // const triggerPrice = new BN(0); // const triggerCondition = OrderTriggerCondition.BELOW; const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price: limitPrice, }); try { await driftClient.placePerpOrder(orderParams); } catch (e) { console.error(e); throw e; } const newPrice = convertToNumber( limitPrice.mul(new BN(96)).div(new BN(100)), PRICE_PRECISION ); // move price to make liquidity for order @ $1.05 (5%) await setFeedPriceNoProgram(bankrunContextWrapper, newPrice, solUsd); await driftClient.moveAmmToPrice( marketIndex, new BN(newPrice * PRICE_PRECISION.toNumber()) ); const order = driftClientUser.getUserAccount().orders[0]; console.log(order.status); // assert(order.status == OrderStatus.INIT); const amountToFill = calculateBaseAssetAmountForAmmToFulfill( order, market, driftClient.getOracleDataForPerpMarket(order.marketIndex), 0 ); console.log(amountToFill); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); await fillerUser.fetchAccounts(); const orderPriceMove = driftClientUser.getUserAccount().orders[0]; const newMarketPriceMove = driftClient.getPerpMarketAccount(marketIndex); const newMarkPricePriceMove = calculateReservePrice(newMarketPriceMove); assert(driftClientUser.getPerpPosition(marketIndex).openAsks.eq(ZERO)); assert( driftClientUser.getPerpPosition(marketIndex).openBids.eq(baseAssetAmount) ); const userLeveragePriceMove = driftClientUser.getLeverage(); console.log( 'ON PRICE MOVE:\n', 'mark price:', convertToNumber(newMarkPricePriceMove, PRICE_PRECISION), 'base filled / amt:', convertToNumber( orderPriceMove.baseAssetAmountFilled, AMM_RESERVE_PRECISION ), '/', convertToNumber(orderPriceMove.baseAssetAmount, AMM_RESERVE_PRECISION), '\n', 'user leverage:', convertToNumber(userLeveragePriceMove, TEN_THOUSAND), '\n' ); try { await fillerDriftClient.fillPerpOrder( userAccountPublicKey, driftClientUser.getUserAccount(), order ); } catch (e) { console.error(e); throw e; } await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); await fillerUser.fetchAccounts(); const order1 = driftClientUser.getUserAccount().orders[0]; const newMarket1 = driftClient.getPerpMarketAccount(marketIndex); const newMarkPrice1 = calculateReservePrice(newMarket1); // 0 liquidity at current mark price const userLeverage = driftClientUser.getLeverage(); const postPosition = driftClientUser.getPerpPosition(marketIndex); assert(driftClientUser.getPerpPosition(marketIndex).openAsks.eq(ZERO)); assert(driftClientUser.getPerpPosition(marketIndex).openBids.eq(ZERO)); console.log( 'FILLED:', 'position: ', convertToNumber(prePosition.baseAssetAmount, AMM_RESERVE_PRECISION), '->', convertToNumber(postPosition.baseAssetAmount, AMM_RESERVE_PRECISION), 'mark price:', convertToNumber(newMarkPrice1, PRICE_PRECISION), 'base filled / amt:', convertToNumber(order1.baseAssetAmountFilled, AMM_RESERVE_PRECISION), '/', convertToNumber(order1.baseAssetAmount, AMM_RESERVE_PRECISION), '\n', 'user leverage:', convertToNumber(userLeverage, TEN_THOUSAND), '\n' ); // assert(userNetGain.lte(ZERO)); // ensure no funny business assert(userLeverage.eq(ZERO)); assert(postPosition.baseAssetAmount.eq(ZERO)); assert(driftClientUser.getPerpPosition(marketIndex).openOrders == 0); // await driftClient.closePosition(marketIndex); // await driftClient.cancelOrder(orderId); }); it('Max leverage fill limit long order', async () => { //todo, partial fill wont work on order too large const userLeverage0 = driftClientUser.getLeverage(); console.log( 'user initial leverage:', convertToNumber(userLeverage0, TEN_THOUSAND) ); assert(driftClientUser.getPerpPosition(marketIndex).openOrders == 0); const direction = PositionDirection.LONG; const market = driftClient.getPerpMarketAccount(marketIndex); const limitPrice = calculateReservePrice(market); // 0 liquidity at current mark price const baseAssetAmount = new BN(37711910000); //long 50 base amount at $1 with ~$10 collateral (max leverage = 5x) const [newDirection, amountToPrice, _entryPrice, newMarkPrice] = calculateTargetPriceTrade(market, limitPrice, new BN(1000), 'base'); assert(amountToPrice.eq(ZERO)); // no liquidity now console.log( convertToNumber(calculateReservePrice(market)), 'then long', convertToNumber(baseAssetAmount, AMM_RESERVE_PRECISION), '$CRISP @', convertToNumber(limitPrice), newDirection, convertToNumber(newMarkPrice), 'available liquidity', convertToNumber(amountToPrice, AMM_RESERVE_PRECISION) ); assert(baseAssetAmount.gt(amountToPrice)); // assert its a partial fill of liquidity // const triggerPrice = new BN(0); // const triggerCondition = OrderTriggerCondition.BELOW; const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price: limitPrice, }); await driftClient.placePerpOrder(orderParams); await driftClientUser.fetchAccounts(); const newPrice = convertToNumber( limitPrice.mul(new BN(97)).div(new BN(100)), PRICE_PRECISION ); // move price to make liquidity for order @ $1.05 (5%) await setFeedPriceNoProgram(bankrunContextWrapper, newPrice, solUsd); try { await driftClient.moveAmmToPrice( marketIndex, new BN(newPrice * PRICE_PRECISION.toNumber()) ); } catch (e) { console.error(e); } const order = driftClientUser.getUserAccount().orders[0]; const amountToFill = calculateBaseAssetAmountForAmmToFulfill( order, market, driftClient.getOracleDataForPerpMarket(order.marketIndex), 0 ); assert(driftClientUser.getPerpPosition(marketIndex).openAsks.eq(ZERO)); console.log( driftClientUser.getPerpPosition(marketIndex).openBids.toString(), 'vs', baseAssetAmount.toString() ); assert( driftClientUser.getPerpPosition(marketIndex).openBids.eq(baseAssetAmount) ); console.log(amountToFill); assert(order.orderId >= 7); try { await fillerDriftClient.fillPerpOrder( userAccountPublicKey, driftClientUser.getUserAccount(), order ); } catch (e) { console.error(e); } await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); await fillerUser.fetchAccounts(); const order1 = driftClientUser.getUserAccount().orders[0]; const newMarket1 = driftClient.getPerpMarketAccount(marketIndex); const newMarkPrice1 = calculateReservePrice(newMarket1); // 0 liquidity at current mark price const userLeverage = driftClientUser.getLeverage(); // assert(userNetGain.lte(ZERO)); // ensure no funny business console.log( 'mark price:', convertToNumber(newMarkPrice1, PRICE_PRECISION), 'base filled / amt:', convertToNumber(order1.baseAssetAmountFilled, AMM_RESERVE_PRECISION), '/', convertToNumber(order1.baseAssetAmount, AMM_RESERVE_PRECISION), '\n', 'user leverage:', convertToNumber(userLeverage, TEN_THOUSAND), '\n' ); assert(driftClientUser.getPerpPosition(marketIndex).openAsks.eq(ZERO)); assert(driftClientUser.getPerpPosition(marketIndex).openBids.eq(ZERO)); }); it('When in Max leverage long, fill limit short order to flip to max leverage short', async () => { // determining max leverage short is harder than max leverage long // (using linear assumptions since it is smaller base amt) const userLeverage0 = driftClientUser.getLeverage(); const prePosition = driftClientUser.getPerpPosition(marketIndex); console.log( 'user initial leverage:', convertToNumber(userLeverage0, TEN_THOUSAND) ); const direction = PositionDirection.SHORT; const market = driftClient.getPerpMarketAccount(marketIndex); // const limitPrice = calculateReservePrice(market); // 0 liquidity at current mark price const baseAssetAmount = prePosition.baseAssetAmount.abs().mul(new BN(2)); //new BN(AMM_RESERVE_PRECISION.mul(new BN(50))); const limitPrice = calculateTradeSlippage( direction, baseAssetAmount, market, 'base' )[3]; //long 50 base amount at $1 with ~$10 collateral (max leverage = 5x) const [newDirection, amountToPrice, _entryPrice, newMarkPrice] = calculateTargetPriceTrade(market, limitPrice, new BN(1000), 'base'); console.log( convertToNumber(calculateReservePrice(market)), 'then long', convertToNumber(baseAssetAmount, AMM_RESERVE_PRECISION), '$CRISP @', convertToNumber(limitPrice), newDirection, convertToNumber(newMarkPrice), 'available liquidity', convertToNumber(amountToPrice, AMM_RESERVE_PRECISION) ); // assert(baseAssetAmount.gt(amountToPrice)); // assert its a partial fill of liquidity // const triggerPrice = new BN(0); // const triggerCondition = OrderTriggerCondition.BELOW; const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price: limitPrice, }); try { await driftClient.placePerpOrder(orderParams); } catch (e) { console.error(e); throw e; } // move price to make liquidity for order @ $1.05 (5%) // setFeedPrice(anchor.workspace.Pyth, 1.55, solUsd); // await driftClient.moveAmmToPrice( // marketIndex, // new BN(1.55 * PRICE_PRECISION.toNumber()) // ); await driftClientUser.fetchAccounts(); const order = driftClient.getUserAccount().orders[0]; console.log(order.status); // assert(order.status == OrderStatus.INIT); const amountToFill = calculateBaseAssetAmountForAmmToFulfill( order, market, driftClient.getOracleDataForPerpMarket(order.marketIndex), 0 ); console.log(amountToFill.toString()); console.log( driftClientUser.getPerpPosition(marketIndex).openAsks.toString() ); assert( driftClientUser .getPerpPosition(marketIndex) .openAsks.eq(baseAssetAmount.neg()) ); assert(driftClientUser.getPerpPosition(marketIndex).openBids.eq(ZERO)); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); await fillerUser.fetchAccounts(); const orderPriceMove = driftClientUser.getUserAccount().orders[0]; const newMarketPriceMove = driftClient.getPerpMarketAccount(marketIndex); const newMarkPricePriceMove = calculateReservePrice(newMarketPriceMove); const userLeveragePriceMove = driftClientUser.getLeverage(); console.log( 'ON PRICE MOVE:\n', 'mark price:', convertToNumber(newMarkPricePriceMove, PRICE_PRECISION), 'base filled / amt:', convertToNumber( orderPriceMove.baseAssetAmountFilled, AMM_RESERVE_PRECISION ), '/', convertToNumber(orderPriceMove.baseAssetAmount, AMM_RESERVE_PRECISION), '\n', 'user leverage:', convertToNumber(userLeveragePriceMove, TEN_THOUSAND), '\n' ); try { const txSig = await fillerDriftClient.fillPerpOrder( userAccountPublicKey, driftClientUser.getUserAccount(), order ); bankrunContextWrapper.printTxLogs(txSig); } catch (e) { console.error(e); throw e; } await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); await fillerUser.fetchAccounts(); const order1 = driftClientUser.getUserAccount().orders[0]; const newMarket1 = driftClient.getPerpMarketAccount(marketIndex); const newMarkPrice1 = calculateReservePrice(newMarket1); // 0 liquidity at current mark price const userTC = driftClientUser.getTotalCollateral(); const userTPV = driftClientUser.getTotalPerpPositionLiability(); const userLeverage = driftClientUser.getLeverage(); const postPosition = driftClientUser.getPerpPosition(marketIndex); // console.log( // driftClientUser.getPerpPosition(marketIndex).openAsks.toString() // ); // assert(driftClientUser.getPerpPosition(marketIndex).openAsks.eq(ZERO)); // assert(driftClientUser.getPerpPosition(marketIndex).openBids.eq(ZERO)); console.log( 'FILLED:', 'position: ', convertToNumber(prePosition.baseAssetAmount, AMM_RESERVE_PRECISION), '->', convertToNumber(postPosition.baseAssetAmount, AMM_RESERVE_PRECISION), 'mark price:', convertToNumber(newMarkPrice1, PRICE_PRECISION), 'base filled / amt:', convertToNumber(order1.baseAssetAmountFilled, AMM_RESERVE_PRECISION), '/', convertToNumber(order1.baseAssetAmount, AMM_RESERVE_PRECISION), '\n', 'user TC:', convertToNumber(userTC, QUOTE_PRECISION), '\n', 'user TPV:', convertToNumber(userTPV, QUOTE_PRECISION), '\n', 'user leverage:', convertToNumber(userLeverage, TEN_THOUSAND), '\n' ); try { await driftClient.closePosition(marketIndex); } catch (e) { console.error(e); throw e; } assert(userLeverage.gt(new BN(0))); assert(postPosition.baseAssetAmount.lt(ZERO)); }); it('PlaceAndTake LONG Order 100% filled', async () => { const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: new BN(1000000), oracleTwap5MinPercentDivergence: new BN(1000000), }, validity: { slotsBeforeStaleForAmm: new BN(100), slotsBeforeStaleForMargin: new BN(100), confidenceIntervalMaxSize: new BN(100000), tooVolatileRatio: new BN(2), }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); const direction = PositionDirection.LONG; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const price = new BN('1330000').add(PRICE_PRECISION.div(new BN(40))); await driftClientUser.fetchAccounts(); const prePosition = driftClientUser.getPerpPosition(marketIndex); console.log(prePosition); assert(prePosition.baseAssetAmount.eq(ZERO)); // no existing position const fillerCollateralBefore = fillerDriftClient.getQuoteAssetTokenAmount(); const newPrice = convertToNumber( price.mul(new BN(96)).div(new BN(100)), PRICE_PRECISION ); await setFeedPriceNoProgram(bankrunContextWrapper, newPrice, solUsd); await driftClient.moveAmmToPrice( marketIndex, new BN(newPrice * PRICE_PRECISION.toNumber()) ); const orderParams = getLimitOrderParams({ marketIndex, direction, baseAssetAmount, price, }); const txSig = await driftClient.placeAndTakePerpOrder(orderParams); const computeUnits = bankrunContextWrapper.connection.findComputeUnitConsumption(txSig); console.log('placeAndTake compute units', computeUnits[0]); // await driftClient.settlePNL( // await driftClient.getUserAccountPublicKey(), // driftClient.getUserAccount(), // marketIndex // ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); await fillerUser.fetchAccounts(); const postPosition = driftClientUser.getPerpPosition(marketIndex); console.log( 'User position: ', convertToNumber(new BN(0), AMM_RESERVE_PRECISION), '->', convertToNumber(postPosition.baseAssetAmount, AMM_RESERVE_PRECISION) ); assert(postPosition.baseAssetAmount.eq(baseAssetAmount)); // 100% filled // zero filler reward const fillerReward = fillerCollateralBefore.sub( fillerDriftClient.getQuoteAssetTokenAmount() ); console.log( 'FillerReward: $', convertToNumber(fillerReward, QUOTE_PRECISION) ); assert(fillerReward.eq(new BN(0))); await driftClient.closePosition(marketIndex); }); it('Time-based fee reward cap', async () => { const direction = PositionDirection.SHORT; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION.mul(new BN(10000))); const triggerPrice = PRICE_PRECISION.div(new BN(1000)); const triggerCondition = OrderTriggerCondition.ABOVE; const orderParams = getTriggerMarketOrderParams({ marketIndex, direction, baseAssetAmount, triggerPrice, triggerCondition, }); const placeTxSig = await whaleDriftClient.placePerpOrder(orderParams); bankrunContextWrapper.printTxLogs(placeTxSig); await whaleDriftClient.fetchAccounts(); await whaleUser.fetchAccounts(); await fillerUser.fetchAccounts(); const orderIndex = new BN(0); const order = whaleUser.getUserAccount().orders[orderIndex.toString()]; const fillerCollateralBefore = fillerDriftClient.getQuoteAssetTokenAmount(); const fillerUnsettledPNLBefore = fillerDriftClient.getUserAccount().perpPositions[0].quoteAssetAmount; await fillerDriftClient.triggerOrder( whaleAccountPublicKey, whaleUser.getUserAccount(), order ); await fillerDriftClient.fillPerpOrder( whaleAccountPublicKey, whaleUser.getUserAccount(), order ); await whaleDriftClient.fetchAccounts(); await whaleUser.fetchAccounts(); await fillerUser.fetchAccounts(); const whaleStats = await whaleDriftClient.getUserStats().getAccount(); const expectedFillerReward = new BN(2e6 / 100); //1 cent const fillerReward = fillerDriftClient .getQuoteAssetTokenAmount() .sub(fillerCollateralBefore) .add(fillerUser.getUserAccount().perpPositions[0].quoteAssetAmount) .sub(fillerUnsettledPNLBefore); console.log( 'FillerReward: $', convertToNumber(fillerReward, QUOTE_PRECISION) ); assert(fillerReward.eq(expectedFillerReward)); assert(whaleStats.fees.totalFeePaid.gt(fillerReward.mul(new BN(5)))); // ensure whale fee more than x100 filler }); it('reduce only', async () => { const openPositionOrderParams = getMarketOrderParams({ marketIndex: marketIndexEth, direction: PositionDirection.SHORT, baseAssetAmount: AMM_RESERVE_PRECISION, }); await driftClient.placeAndTakePerpOrder(openPositionOrderParams); console.log(driftClient.getUser().getPerpPosition(marketIndexEth)); const reduceMarketOrderParams = getMarketOrderParams({ marketIndex: marketIndexEth, direction: PositionDirection.LONG, baseAssetAmount: TWO.mul(AMM_RESERVE_PRECISION), reduceOnly: true, }); await driftClient.placeAndTakePerpOrder(reduceMarketOrderParams); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); console.log('2'); let orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[1]; console.log(orderRecord); assert(orderRecord.baseAssetAmountFilled.eq(AMM_RESERVE_PRECISION)); assert( isVariant(driftClientUser.getUserAccount().orders[1].status, 'init') ); await driftClient.placeAndTakePerpOrder(openPositionOrderParams); const reduceLimitOrderParams = getLimitOrderParams({ marketIndex: marketIndexEth, direction: PositionDirection.LONG, baseAssetAmount: TWO.mul(AMM_RESERVE_PRECISION), price: calculateReservePrice( driftClient.getPerpMarketAccount(marketIndexEth) ).add(PRICE_PRECISION.div(new BN(40))), reduceOnly: true, }); console.log('3'); try { await driftClient.placeAndTakePerpOrder(reduceLimitOrderParams); } catch (e) { console.error(e); } console.log('4'); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[1]; assert(orderRecord.baseAssetAmountFilled.eq(AMM_RESERVE_PRECISION)); assert( isVariant(driftClientUser.getUserAccount().orders[1].status, 'init') ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/maxLeverageOrderParams.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { PublicKey } from '@solana/web3.js'; import { BN, OracleSource, TestClient, PRICE_PRECISION, PositionDirection, EventSubscriber, OracleGuardRails, MarketStatus, LIQUIDATION_PCT_PRECISION, } from '../sdk/src'; import { mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, createUserWithUSDCAndWSOLAccount, initializeSolSpotMarket, } from './testHelpers'; import { getMarketOrderParams, MAX_LEVERAGE_ORDER_SIZE, PERCENTAGE_PRECISION, } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('max leverage order params', () => { const chProgram = anchor.workspace.Drift as Program; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let usdcMint; let userUSDCAccount; let lendorDriftClient: TestClient; let lendorDriftClientWSOLAccount: PublicKey; let lendorDriftClientUSDCAccount: PublicKey; let solOracle: PublicKey; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 1); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0, 1], subAccountIds: [], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await driftClient.updateInitialPctToLiquidate( LIQUIDATION_PCT_PRECISION.toNumber() ); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await initializeSolSpotMarket(driftClient, solOracle); await driftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(0); await driftClient.initializePerpMarket( 0, solOracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await driftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: PERCENTAGE_PRECISION.div(new BN(10)), oracleTwap5MinPercentDivergence: PERCENTAGE_PRECISION, }, validity: { slotsBeforeStaleForAmm: new BN(100), slotsBeforeStaleForMargin: new BN(100), confidenceIntervalMaxSize: new BN(100000), tooVolatileRatio: new BN(55), // allow 55x change }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); const lenderSolAmount = new BN(100 * 10 ** 9); const lenderUSDCAmount = usdcAmount.mul(new BN(100)); [ lendorDriftClient, lendorDriftClientWSOLAccount, lendorDriftClientUSDCAccount, ] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, lenderSolAmount, lenderUSDCAmount, [0], [0, 1], [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], bulkAccountLoader ); await lendorDriftClient.subscribe(); const spotMarketIndex = 1; await lendorDriftClient.deposit( lenderSolAmount, spotMarketIndex, lendorDriftClientWSOLAccount ); await lendorDriftClient.deposit( lenderUSDCAmount, 0, lendorDriftClientUSDCAccount ); }); after(async () => { await driftClient.unsubscribe(); await lendorDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('max perp leverage', async () => { await driftClient.placePerpOrder( getMarketOrderParams({ direction: PositionDirection.LONG, marketIndex: 0, baseAssetAmount: MAX_LEVERAGE_ORDER_SIZE, userOrderId: 1, }) ); let leverage = driftClient.getUser().getLeverage().toNumber() / 10000; assert(leverage === 4.9949); await driftClient.cancelOrderByUserId(1); // test placing order with short direction await driftClient.placePerpOrder( getMarketOrderParams({ direction: PositionDirection.SHORT, marketIndex: 0, baseAssetAmount: MAX_LEVERAGE_ORDER_SIZE, userOrderId: 1, }) ); leverage = driftClient.getUser().getLeverage().toNumber() / 10000; assert(leverage === 4.9949); await driftClient.cancelOrderByUserId(1); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/delistMarket.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { PublicKey } from '@solana/web3.js'; import { Wallet, BASE_PRECISION, BN, OracleSource, ZERO, TestClient, convertToNumber, PRICE_PRECISION, PositionDirection, EventSubscriber, QUOTE_PRECISION, calculateBaseAssetValueWithOracle, OracleGuardRails, } from '../sdk/src'; import { mockOracle, mockUSDCMint, mockUserUSDCAccount, setFeedPrice, initializeQuoteSpotMarket, createUserWithUSDCAndWSOLAccount, initializeSolSpotMarket, printTxLogs, getFeedData, getOraclePriceData, sleep, } from './testHelpers'; import { BulkAccountLoader, isVariant, PERCENTAGE_PRECISION } from '../sdk'; import { Keypair } from '@solana/web3.js'; async function depositToFeePoolFromIF( amount: number, driftClient: TestClient, userUSDCAccount: Keypair ) { const ifAmount = new BN(amount * QUOTE_PRECISION.toNumber()); // const state = await driftClient.getStateAccount(); // const tokenIx = Token.createTransferInstruction( // TOKEN_PROGRAM_ID, // userUSDCAccount.publicKey, // state.insuranceVault, // driftClient.provider.wallet.publicKey, // // usdcMint.publicKey, // [], // ifAmount.toNumber() // ); // // await sendAndConfirmTransaction( // driftClient.provider.connection, // new Transaction().add(tokenIx), // // @ts-ignore // [driftClient.provider.wallet.payer], // { // skipPreflight: false, // commitment: 'recent', // preflightCommitment: 'recent', // } // ); console.log(userUSDCAccount.publicKey.toString()); // // send $50 to market from IF const txSig00 = await driftClient.depositIntoPerpMarketFeePool( 0, ifAmount, userUSDCAccount.publicKey ); console.log(txSig00); } describe('delist market', () => { const provider = anchor.AnchorProvider.local(undefined, { preflightCommitment: 'confirmed', commitment: 'confirmed', }); const connection = provider.connection; anchor.setProvider(provider); const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; const eventSubscriber = new EventSubscriber(connection, chProgram, { commitment: 'recent', }); eventSubscriber.subscribe(); const bulkAccountLoader = new BulkAccountLoader(connection, 'confirmed', 1); let usdcMint; let userUSDCAccount; let userUSDCAccount2; let driftClientLoser: TestClient; let liquidatorDriftClient: TestClient; let liquidatorDriftClientWSOLAccount: PublicKey; let solOracle: PublicKey; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(1000 * 10 ** 6); const userKeypair = new Keypair(); before(async () => { usdcMint = await mockUSDCMint(provider); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount.mul(new BN(10)), provider ); solOracle = await mockOracle(43.1337); driftClient = new TestClient({ connection, wallet: provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0, 1], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await initializeSolSpotMarket(driftClient, solOracle); await driftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(0); await driftClient.initializePerpMarket( 0, solOracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(43_133_000) ); // await driftClient.updatePerpMarketBaseSpread(new BN(0), 2000); // await driftClient.updatePerpMarketCurveUpdateIntensity(new BN(0), 100); await driftClient.updatePerpMarketStepSizeAndTickSize( 0, new BN(10), new BN(1) ); await driftClient.updatePerpMarketMinOrderSize(0, new BN(1)); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); await provider.connection.requestAirdrop(userKeypair.publicKey, 10 ** 9); userUSDCAccount2 = await mockUserUSDCAccount( usdcMint, usdcAmount, provider, userKeypair.publicKey ); driftClientLoser = new TestClient({ connection, wallet: new Wallet(userKeypair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0, 1], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientLoser.subscribe(); await driftClientLoser.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount2.publicKey ); }); after(async () => { await driftClient.unsubscribe(); await driftClientLoser.unsubscribe(); await liquidatorDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('put market in big drawdown and net user positive pnl', async () => { await sleep(1000); await depositToFeePoolFromIF(1000, driftClient, userUSDCAccount); await driftClient.fetchAccounts(); // try { await driftClient.openPosition( PositionDirection.SHORT, BASE_PRECISION, 0, new BN(0) ); // } catch (e) { // console.log('driftClient.openPosition'); // console.error(e); // } const market001 = driftClient.getPerpMarketAccount(0); console.log( 'market001 num users with base:', market001.numberOfUsersWithBase.toString() ); console.log( 'market001 num users with quote:', market001.numberOfUsers.toString() ); assert(market001.numberOfUsersWithBase == 1); // todo // try { await driftClientLoser.fetchAccounts(); await driftClientLoser.openPosition( PositionDirection.LONG, new BN(2000 * 2), 0 ); // } catch (e) { // console.log('driftClientLoserc.openPosition'); // console.error(e); // return 0; // } await driftClient.fetchAccounts(); const market00 = driftClient.getPerpMarketAccount(0); assert(market00.amm.feePool.scaledBalance.eq(new BN(1000000000000))); console.log( 'market00 num users with base:', market00.numberOfUsersWithBase.toString() ); console.log( 'market00 num users with quote:', market00.numberOfUsers.toString() ); assert(market00.numberOfUsersWithBase == 2); const solAmount = new BN(1 * 10 ** 9); [liquidatorDriftClient, liquidatorDriftClientWSOLAccount] = await createUserWithUSDCAndWSOLAccount( provider, usdcMint, chProgram, solAmount, usdcAmount, [0], [0, 1], [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], bulkAccountLoader ); await liquidatorDriftClient.subscribe(); const bankIndex = 1; await liquidatorDriftClient.deposit( solAmount, bankIndex, liquidatorDriftClientWSOLAccount ); const market0 = driftClient.getPerpMarketAccount(0); const winnerUser = driftClient.getUserAccount(); const loserUser = driftClientLoser.getUserAccount(); console.log(winnerUser.perpPositions[0].quoteAssetAmount.toString()); console.log(loserUser.perpPositions[0].quoteAssetAmount.toString()); assert( market0.amm.quoteAssetAmount.eq( winnerUser.perpPositions[0].quoteAssetAmount.add( loserUser.perpPositions[0].quoteAssetAmount ) ) ); }); it('go through multiple market state changes', async () => { const marketIndex = 0; const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: new BN(10).mul(PERCENTAGE_PRECISION), oracleTwap5MinPercentDivergence: new BN(10).mul(PERCENTAGE_PRECISION), }, validity: { slotsBeforeStaleForAmm: new BN(100), slotsBeforeStaleForMargin: new BN(100), confidenceIntervalMaxSize: new BN(100000), tooVolatileRatio: new BN(100000000), }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); await driftClient.updateFundingRate(marketIndex, solOracle); await driftClient.fetchAccounts(); const perpMarket = await driftClient.getPerpMarketAccount(marketIndex); // console.log(perpMarket.amm.cumulativeFundingRateLong.toString()); assert(!perpMarket.amm.cumulativeFundingRateLong.eq(ZERO)); const marketBefore = driftClient.getPerpMarketAccount(0); console.log( 'marketBefore num users with base:', marketBefore.numberOfUsersWithBase.toString() ); console.log( 'marketBefore num users with quote:', marketBefore.numberOfUsers.toString() ); assert(marketBefore.numberOfUsersWithBase == 2); assert(marketBefore.numberOfUsers == 2); await liquidatorDriftClient.addPerpLpShares(BASE_PRECISION, marketIndex); await driftClient.updateK( marketIndex, perpMarket.amm.sqrtK.mul(new BN(10012345)).div(new BN(9912345)) ); await driftClient.openPosition( PositionDirection.LONG, BASE_PRECISION, 0, new BN(0) ); await driftClient.fetchAccounts(); let marketBefore2 = driftClient.getPerpMarketAccount(0); console.log( 'marketBefore num users with base:', marketBefore2.numberOfUsersWithBase.toString() ); console.log( 'marketBefore num users with quote:', marketBefore2.numberOfUsers.toString() ); assert(marketBefore2.numberOfUsersWithBase == 1); assert(marketBefore2.numberOfUsers == 2); await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); marketBefore2 = driftClient.getPerpMarketAccount(0); console.log( 'marketBefore num users with base:', marketBefore2.numberOfUsersWithBase.toString() ); console.log( 'marketBefore num users with quote:', marketBefore2.numberOfUsers.toString() ); assert(marketBefore2.numberOfUsersWithBase == 1); assert(marketBefore2.numberOfUsers == 1); await driftClient.updateK(marketIndex, perpMarket.amm.sqrtK); await driftClient.openPosition( PositionDirection.SHORT, BASE_PRECISION, 0, new BN(0) ); marketBefore2 = driftClient.getPerpMarketAccount(0); console.log( 'marketBefore num users with base:', marketBefore2.numberOfUsersWithBase.toString() ); console.log( 'marketBefore num users with quote:', marketBefore2.numberOfUsers.toString() ); assert(marketBefore2.numberOfUsersWithBase == 2); assert(marketBefore2.numberOfUsers == 2); await driftClient.updateFundingRate(marketIndex, solOracle); await driftClient.fetchAccounts(); await liquidatorDriftClient.fetchAccounts(); marketBefore2 = driftClient.getPerpMarketAccount(0); console.log( 'marketBefore num users with base:', marketBefore2.numberOfUsersWithBase.toString() ); console.log( 'marketBefore num users with quote:', marketBefore2.numberOfUsers.toString() ); assert(marketBefore2.numberOfUsersWithBase == 2); assert(marketBefore2.numberOfUsers == 2); assert( liquidatorDriftClient .getUserAccount() .perpPositions[0].baseAssetAmount.eq(ZERO) ); // assert( // liquidatorDriftClient.getUserAccount().perpPositions[0].remainderBaseAssetAmount != 0 // ); console.log( 'liquidatorDriftClient perps:', liquidatorDriftClient.getUserAccount().perpPositions[0] ); await liquidatorDriftClient.removePerpLpShares(marketIndex); await driftClient.updateK( marketIndex, perpMarket.amm.sqrtK.mul(new BN(9912345)).div(new BN(10012345)) ); console.log( 'liquidatorDriftClient perps:', liquidatorDriftClient.getUserAccount().perpPositions[0] ); const market001 = driftClient.getPerpMarketAccount(0); console.log( 'market001 num users with base:', market001.numberOfUsersWithBase.toString() ); console.log( 'market001 num users with quote:', market001.numberOfUsers.toString() ); assert( liquidatorDriftClient .getUserAccount() .perpPositions[0].baseAssetAmount.eq(ZERO) ); assert( liquidatorDriftClient.getUserAccount().perpPositions[0] .remainderBaseAssetAmount == 0 ); assert(market001.numberOfUsersWithBase == 2); assert(market001.numberOfUsers == 3); console.log( 'liquidatorDriftClient perps:', liquidatorDriftClient .getUserAccount() .perpPositions[0].baseAssetAmount.toString() ); // await liquidatorDriftClient.closePosition(marketIndex); // sol tanks 90% await driftClient.moveAmmToPrice( 0, new BN(43.1337 * PRICE_PRECISION.toNumber()).div(new BN(10)) ); await setFeedPrice(anchor.workspace.Pyth, 43.1337 / 10, solOracle); }); // return 0; it('put market in reduce only mode', async () => { const marketIndex = 0; const slot = await connection.getSlot(); const now = await connection.getBlockTime(slot); const expiryTs = new BN(now + 3); const market0 = driftClient.getPerpMarketAccount(marketIndex); assert(market0.expiryTs.eq(ZERO)); await driftClient.updatePerpMarketExpiry(marketIndex, expiryTs); await sleep(1000); driftClient.fetchAccounts(); const market = driftClient.getPerpMarketAccount(marketIndex); console.log(market.status); assert(isVariant(market.status, 'reduceOnly')); console.log( 'market.expiryTs == ', market.expiryTs.toString(), '(', expiryTs.toString(), ')' ); assert(market.expiryTs.eq(expiryTs)); console.log('totalExchangeFee:', market.amm.totalExchangeFee.toString()); console.log('totalFee:', market.amm.totalFee.toString()); console.log('totalMMFee:', market.amm.totalMmFee.toString()); console.log( 'totalFeeMinusDistributions:', market.amm.totalFeeMinusDistributions.toString() ); await driftClient.fetchAccounts(); console.log( 'lastOraclePriceTwap:', market.amm.historicalOracleData.lastOraclePriceTwap.toString() ); assert( market.amm.historicalOracleData.lastOraclePriceTwap.eq(new BN(43133700)) ); // should fail try { await driftClientLoser.openPosition( PositionDirection.LONG, new BN(10000000), 0, new BN(0) ); console.log('risk increase trade succeed when it should have failed!'); assert(false); } catch (e) { console.log(e); if (!e.toString().search('AnchorError occurred')) { assert(false); } console.log('risk increase trade failed'); } await driftClientLoser.fetchAccounts(); const loserUser0 = driftClientLoser.getUserAccount(); console.log(loserUser0.perpPositions[0]); await driftClient.fetchAccounts(); const marketBeforeReduceUser = driftClient.getPerpMarketAccount(0); console.log( 'lastOraclePriceTwap:', marketBeforeReduceUser.amm.historicalOracleData.lastOraclePriceTwap.toString() ); assert( marketBeforeReduceUser.amm.historicalOracleData.lastOraclePriceTwap.eq( new BN(43133700) ) ); // should succeed await driftClientLoser.openPosition( PositionDirection.SHORT, new BN(2000), 0, new BN(0) ); await driftClient.fetchAccounts(); const marketBeforeReduceUser2 = driftClient.getPerpMarketAccount(0); console.log( 'lastOraclePriceTwap:', marketBeforeReduceUser2.amm.historicalOracleData.lastOraclePriceTwap.toString() ); // assert(marketBeforeReduceUser2.amm.historicalOracleData.lastOraclePriceTwap.eq(new BN(28755800))) assert( marketBeforeReduceUser2.amm.historicalOracleData.lastOraclePriceTwap.eq( new BN(19170534) ) ); }); it('put market in settlement mode', async () => { const marketIndex = 0; let slot = await connection.getSlot(); let now = await connection.getBlockTime(slot); const market0 = driftClient.getPerpMarketAccount(marketIndex); console.log('market0.status:', market0.status); while (market0.expiryTs.gte(new BN(now))) { console.log(market0.expiryTs.toString(), '>', now); await sleep(1000); slot = await connection.getSlot(); now = await connection.getBlockTime(slot); } const winningUserBefore = driftClient.getUserAccount(); console.log(winningUserBefore.perpPositions[0]); const oraclePriceDataBefore = await getOraclePriceData( anchor.workspace.Pyth, solOracle ); const beforeExpiryValue = calculateBaseAssetValueWithOracle( market0, winningUserBefore.perpPositions[0], oraclePriceDataBefore ); // try { const txSig = await driftClient.settleExpiredMarket(marketIndex); // } catch (e) { // console.error(e); // } await printTxLogs(connection, txSig); await driftClient.fetchAccounts(); const market = driftClient.getPerpMarketAccount(marketIndex); console.log(market.status); assert(isVariant(market.status, 'settlement')); console.log('market.expiryPrice:', convertToNumber(market.expiryPrice)); console.log( 'market.amm.historicalOracleData.lastOraclePriceTwap:', convertToNumber(market.amm.historicalOracleData.lastOraclePriceTwap) ); assert( market.amm.historicalOracleData.lastOraclePriceTwap.eq(new BN(12780356)) ); const curPrice = (await getFeedData(anchor.workspace.Pyth, solOracle)) .price; console.log('new oracle price:', curPrice); const oraclePriceData = await getOraclePriceData( anchor.workspace.Pyth, solOracle ); assert(Math.abs(convertToNumber(oraclePriceData.price) - curPrice) < 1e-4); assert(market.expiryPrice.gt(ZERO)); assert(market.amm.baseAssetAmountWithAmm.lt(ZERO)); assert(oraclePriceData.price.lt(market.expiryPrice)); assert( market.amm.historicalOracleData.lastOraclePriceTwap.lt(market.expiryPrice) ); assert( market.expiryPrice.eq( market.amm.historicalOracleData.lastOraclePriceTwap.add(new BN(1)) ) ); const winningUser = driftClient.getUserAccount(); console.log(winningUser.perpPositions[0]); const afterExpiryValue = calculateBaseAssetValueWithOracle( market, winningUser.perpPositions[0], oraclePriceData ); console.log( 'user position value:', beforeExpiryValue.toString(), '->', afterExpiryValue.toString() ); assert(beforeExpiryValue.lt(afterExpiryValue)); }); it('settle expired market position', async () => { const marketIndex = 0; await driftClientLoser.fetchAccounts(); const loserUser0 = driftClientLoser.getUserAccount(); console.log(loserUser0.perpPositions[0]); assert(loserUser0.perpPositions[0].baseAssetAmount.gt(new BN(0))); assert(loserUser0.perpPositions[0].quoteAssetAmount.lt(new BN(0))); const txSig = await driftClientLoser.settlePNL( await driftClientLoser.getUserAccountPublicKey(), driftClientLoser.getUserAccount(), marketIndex ); await printTxLogs(connection, txSig); // const settleRecord = eventSubscriber.getEventsArray('SettlePnlRecord')[0]; // console.log(settleRecord); await driftClientLoser.fetchAccounts(); const loserUser = driftClientLoser.getUserAccount(); // console.log(loserUser.perpPositions[0]); assert(loserUser.perpPositions[0].baseAssetAmount.eq(new BN(0))); assert(loserUser.perpPositions[0].quoteAssetAmount.eq(new BN(0))); const marketAfter0 = driftClient.getPerpMarketAccount(marketIndex); const finalPnlResultMin0 = new BN(1000020719000 - 100090); console.log(marketAfter0.pnlPool.scaledBalance.toString()); console.log(marketAfter0.pnlPool.scaledBalance.toString()); console.log(marketAfter0.pnlPool.scaledBalance.toString()); assert(marketAfter0.pnlPool.scaledBalance.gt(finalPnlResultMin0)); assert( marketAfter0.pnlPool.scaledBalance.lt(new BN(1000020719000 + 1000000)) ); console.log( 'lastFundingRateLong:', marketAfter0.amm.lastFundingRateLong.toString() ); console.log( 'lastFundingRateShort:', marketAfter0.amm.lastFundingRateShort.toString() ); assert(marketAfter0.amm.lastFundingRateLong.toString() === '79877208'); assert(marketAfter0.amm.lastFundingRateShort.toString() === '79877208'); console.log( 'marketAfter0 num users with base:', marketAfter0.numberOfUsersWithBase.toString() ); console.log( 'marketAfter0 num users with quote:', marketAfter0.numberOfUsers.toString() ); const txSig2 = await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); await printTxLogs(connection, txSig2); await driftClient.fetchAccounts(); const winnerUser = driftClient.getUserAccount(); // console.log(winnerUser.perpPositions[0]); assert(winnerUser.perpPositions[0].baseAssetAmount.eq(new BN(0))); // assert(winnerUser.perpPositions[0].quoteAssetAmount.gt(new BN(0))); // todo they lose money too after fees // await driftClient.settlePNL( // await driftClientLoser.getUserAccountPublicKey(), // driftClientLoser.getUserAccount(), // marketIndex // ); const marketAfter = driftClient.getPerpMarketAccount(marketIndex); console.log( 'marketAfter num users with base:', marketAfter.numberOfUsersWithBase.toString() ); console.log( 'marketAfter num users with quote:', marketAfter.numberOfUsers.toString() ); const finalPnlResultMin = new BN(969643453000 - 109000); console.log('pnlPool:', marketAfter.pnlPool.scaledBalance.toString()); assert(marketAfter.pnlPool.scaledBalance.gt(finalPnlResultMin)); assert(marketAfter.pnlPool.scaledBalance.lt(new BN(969643453000 + 109000))); console.log('feePool:', marketAfter.amm.feePool.scaledBalance.toString()); console.log( 'totalExchangeFee:', marketAfter.amm.totalExchangeFee.toString() ); assert(marketAfter.amm.feePool.scaledBalance.eq(new BN(64700000))); // assert(marketAfter.amm.totalExchangeFee.eq(new BN(43134))); assert(marketAfter.amm.totalExchangeFee.eq(new BN(129401))); }); it('put settle market pools to revenue pool', async () => { const marketIndex = 0; const marketBefore = driftClient.getPerpMarketAccount(marketIndex); const userCostBasisBefore = marketBefore.amm.quoteAssetAmount; console.log('userCostBasisBefore:', userCostBasisBefore.toString()); assert(userCostBasisBefore.eq(new BN(-2))); // from LP burn console.log( 'num users with base:', marketBefore.numberOfUsersWithBase.toString() ); console.log('num users with quote:', marketBefore.numberOfUsers.toString()); console.log( 'liquidatorDriftClient perps:', liquidatorDriftClient .getUserAccount() .perpPositions[0].baseAssetAmount.toString() ); await liquidatorDriftClient.settlePNL( await liquidatorDriftClient.getUserAccountPublicKey(), liquidatorDriftClient.getUserAccount(), marketIndex ); await driftClient.fetchAccounts(); assert( liquidatorDriftClient .getUserAccount() .perpPositions[0].baseAssetAmount.eq(ZERO) ); const market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'num users with base:', market.numberOfUsersWithBase.toString() ); console.log('num users with quote:', market.numberOfUsers.toString()); const userCostBasis = market.amm.quoteAssetAmount; console.log('userCostBasis:', userCostBasis.toString()); assert(userCostBasis.eq(ZERO)); // ready to settle expiration try { await driftClient.settleExpiredMarketPoolsToRevenuePool(marketIndex); } catch (e) { console.log('failed'); } await driftClient.updateStateSettlementDuration(1000); // too far away try { await driftClient.settleExpiredMarketPoolsToRevenuePool(marketIndex); } catch (e) { console.log('failed'); } await driftClient.updateStateSettlementDuration(1); try { await driftClient.settleExpiredMarketPoolsToRevenuePool(marketIndex); } catch (e) { console.log('settleExpiredMarketPoolsToRevenuePool err'); console.error(e); return 0; } await driftClient.fetchAccounts(); const marketAfter = driftClient.getPerpMarketAccount(marketIndex); console.log( marketAfter.amm.baseAssetReserve.toString(), marketAfter.amm.quoteAssetReserve.toString(), marketAfter.amm.sqrtK.toString(), marketAfter.amm.terminalQuoteAssetReserve.toString() ); console.log(marketAfter.pnlPool.scaledBalance.toString()); console.log(marketAfter.amm.feePool.scaledBalance.toString()); assert( marketAfter.amm.feePool.scaledBalance .add(marketAfter.pnlPool.scaledBalance) .eq(ZERO) ); const usdcMarket = driftClient.getQuoteSpotMarketAccount(); console.log(usdcMarket.revenuePool.scaledBalance.toString()); assert(usdcMarket.revenuePool.scaledBalance.gt(ZERO)); assert( usdcMarket.revenuePool.scaledBalance.gt(new BN(969763827000 - 100000)) ); assert( usdcMarket.revenuePool.scaledBalance.lt(new BN(969763827000 + 100000)) ); console.log('works'); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/whitelist.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { BASE_PRECISION, BN, OracleSource } from '../sdk'; import { Program } from '@coral-xyz/anchor'; import { Keypair, PublicKey, SystemProgram, Transaction, } from '@solana/web3.js'; import { MINT_SIZE, TOKEN_PROGRAM_ID, createAssociatedTokenAccountIdempotentInstruction, createInitializeMint2Instruction, createMintToInstruction, getAssociatedTokenAddressSync, } from '@solana/spl-token'; import { TestClient, PRICE_PRECISION } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } from './testHelpers'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('whitelist', () => { const chProgram = anchor.workspace.Drift as Program; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let driftClient: TestClient; let userAccountPublicKey: PublicKey; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN( 5 * BASE_PRECISION.toNumber() ).mul(mantissaSqrtScale); const ammInitialBaseAssetReserve = new anchor.BN( 5 * BASE_PRECISION.toNumber() ).mul(mantissaSqrtScale); const usdcAmount = new BN(10 * 10 ** 6); let whitelistMint: PublicKey; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); const solUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); const periodicity = new BN(60 * 60); // 1 HOUR driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [{ publicKey: solUsd, source: OracleSource.PYTH }], userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); const keypair = Keypair.generate(); const transaction = new Transaction().add( SystemProgram.createAccount({ fromPubkey: bankrunContextWrapper.provider.wallet.publicKey, newAccountPubkey: keypair.publicKey, space: MINT_SIZE, lamports: 10_000_000_000, programId: TOKEN_PROGRAM_ID, }), createInitializeMint2Instruction( keypair.publicKey, 0, bankrunContextWrapper.provider.wallet.publicKey, bankrunContextWrapper.provider.wallet.publicKey, TOKEN_PROGRAM_ID ) ); await bankrunContextWrapper.sendTransaction(transaction, [keypair]); whitelistMint = keypair.publicKey; }); after(async () => { await driftClient.unsubscribe(); }); it('Assert whitelist mint null', async () => { const state = driftClient.getStateAccount(); assert(state.whitelistMint.equals(PublicKey.default)); }); it('enable whitelist mint', async () => { await driftClient.updateWhitelistMint(whitelistMint); const state = driftClient.getStateAccount(); console.assert(state.whitelistMint.equals(whitelistMint)); }); it('block initialize user', async () => { try { [, userAccountPublicKey] = await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); } catch (e) { console.log(e); return; } assert(false); }); it('successful initialize user', async () => { const whitelistMintAta = getAssociatedTokenAddressSync( whitelistMint, bankrunContextWrapper.provider.wallet.publicKey ); const ix = createAssociatedTokenAccountIdempotentInstruction( bankrunContextWrapper.context.payer.publicKey, whitelistMintAta, bankrunContextWrapper.provider.wallet.publicKey, whitelistMint ); const mintToIx = createMintToInstruction( whitelistMint, whitelistMintAta, bankrunContextWrapper.provider.wallet.publicKey, 1 ); await bankrunContextWrapper.sendTransaction( new Transaction().add(ix, mintToIx) ); [, userAccountPublicKey] = await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const user: any = await driftClient.program.account.user.fetch( userAccountPublicKey ); assert.ok( user.authority.equals(bankrunContextWrapper.provider.wallet.publicKey) ); }); it('disable whitelist mint', async () => { await driftClient.updateWhitelistMint(PublicKey.default); const state = driftClient.getStateAccount(); console.assert(state.whitelistMint.equals(PublicKey.default)); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/fuel.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js'; import { TestClient, BN, PRICE_PRECISION, PositionDirection, User, Wallet, BASE_PRECISION, UserStatsAccount, getLimitOrderParams, OracleSource, ONE, ContractTier, FUEL_START_TS, } from '../sdk/src'; import { initializeQuoteSpotMarket, initializeSolSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpers'; import { QUOTE_PRECISION, calculatePerpFuelBonus } from '../sdk/src'; import { MARGIN_PRECISION, PostOnlyParams, ReferrerInfo, ZERO } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe("fuelin'", () => { const chProgram = anchor.workspace.Drift as Program; let fillerDriftClient: TestClient; let fillerDriftClientUser: User; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; const usdcAmount = new BN(100 * 10 ** 6); let solUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; const createTestClient = async ( referrerInfo?: ReferrerInfo ): Promise<[TestClient, Keypair]> => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); await sleep(1000); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount.muln(100), bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey, 0, 0, undefined, undefined, referrerInfo ); await driftClient.updateUserMarginTradingEnabled([ { subAccountId: 0, marginTradingEnabled: true }, ]); return [driftClient, userUSDCAccount]; }; beforeEach(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount.muln(10), bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 32.821); marketIndexes = [0]; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; fillerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClient.initialize(usdcMint.publicKey, true); await fillerDriftClient.subscribe(); await initializeQuoteSpotMarket(fillerDriftClient, usdcMint.publicKey); await initializeSolSpotMarket(fillerDriftClient, solUsd); const initBase1 = BASE_PRECISION.muln(100000); await fillerDriftClient.initializePerpMarket( 0, solUsd, initBase1, initBase1, new BN(3600), new BN(32_821_000), undefined, ContractTier.A, 1000, 500, undefined, undefined, undefined, true, 250, 500 ); await fillerDriftClient.updatePerpMarketCurveUpdateIntensity(0, 100); await fillerDriftClient.updatePerpMarketPausedOperations(0, 1 & 2); await sleep(100); await fillerDriftClient.updatePerpAuctionDuration(new BN(0)); await fillerDriftClient.updateSpotMarketMarginWeights( 1, MARGIN_PRECISION.toNumber() * 0.75, MARGIN_PRECISION.toNumber() * 0.8, MARGIN_PRECISION.toNumber() * 1.25, MARGIN_PRECISION.toNumber() * 1.2 ); await fillerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const oneSol = new BN(LAMPORTS_PER_SOL); await fillerDriftClient.deposit( oneSol, 1, bankrunContextWrapper.provider.wallet.publicKey ); fillerDriftClientUser = new User({ driftClient: fillerDriftClient, userAccountPublicKey: await fillerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClientUser.subscribe(); await bankrunContextWrapper.setTimestamp(FUEL_START_TS.toNumber()); }); afterEach(async () => { await fillerDriftClient.unsubscribe(); await fillerDriftClientUser.unsubscribe(); }); it('fuel for staking', async () => { const [takerDriftClient, _takerUSDCAccount] = await createTestClient({ referrer: fillerDriftClientUser.getUserAccount().authority, referrerStats: fillerDriftClient.getUserStatsAccountPublicKey(), }); const takerDriftClientUser = new User({ driftClient: takerDriftClient, userAccountPublicKey: await takerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await takerDriftClientUser.subscribe(); const marketIndex = 0; const txSig = await takerDriftClient.addInsuranceFundStake({ marketIndex: marketIndex, amount: usdcAmount, collateralAccountPublicKey: _takerUSDCAccount.publicKey, initializeStakeAccount: true, }); bankrunContextWrapper.connection.printTxLogs(txSig); await takerDriftClient.fetchAccounts(); const takerUserStats: UserStatsAccount = takerDriftClient .getUserStats() .getAccount(); console.log(takerUserStats); assert(takerUserStats.ifStakedQuoteAssetAmount.gt(ZERO)); await fillerDriftClient.updateSpotMarketFuel(0, 100, 200, 200, 0, 250); const currentClockInit = await bankrunContextWrapper.context.banksClient.getClock(); await takerDriftClient.fetchAccounts(); assert(takerDriftClient.getSpotMarketAccount(0).fuelBoostInsurance > 0); const fuelDictInit = takerDriftClientUser.getFuelBonus( new BN(currentClockInit.unixTimestamp.toString()).addn(36000), true, true ); console.log(fuelDictInit); assert(fuelDictInit['insuranceFuel'].gt(ZERO)); const timeProgress = 36000; // 30 days in seconds await bankrunContextWrapper.moveTimeForward(timeProgress); const _ = await takerDriftClient.requestRemoveInsuranceFundStake( marketIndex, usdcAmount.divn(3) ); const currentClockInit2 = await bankrunContextWrapper.context.banksClient.getClock(); const fuelDictInit2 = takerDriftClientUser.getFuelBonus( new BN(currentClockInit2.unixTimestamp.toString()), true, true ); console.log(fuelDictInit2); assert(fuelDictInit2['insuranceFuel'].gt(ZERO)); console.log( 'insurance before/after:', fuelDictInit['insuranceFuel'].toNumber(), '->', fuelDictInit2['insuranceFuel'].toNumber() ); assert( Math.abs( fuelDictInit['insuranceFuel'].toNumber() - fuelDictInit2['insuranceFuel'].toNumber() ) <= 1 ); await bankrunContextWrapper.moveTimeForward( takerDriftClient .getSpotMarketAccount(0) .insuranceFund.unstakingPeriod.toNumber() ); const _again = await takerDriftClient.removeInsuranceFundStake( marketIndex, _takerUSDCAccount.publicKey ); const currentClockRm = await bankrunContextWrapper.context.banksClient.getClock(); const fuelDictRmStake = takerDriftClientUser.getFuelBonus( new BN(currentClockRm.unixTimestamp.toString()), true, true ); console.log(fuelDictRmStake); const totalFuelIfNoUnstake = 119791; const expectedFuel = (totalFuelIfNoUnstake - fuelDictInit2['insuranceFuel'].toNumber()) / 3 + fuelDictInit2['insuranceFuel'].toNumber(); console.log( expectedFuel, 'vs', fuelDictRmStake['insuranceFuel'].toNumber() ); assert( Math.abs(fuelDictRmStake['insuranceFuel'].toNumber() - expectedFuel) < 1 ); assert(fuelDictRmStake['insuranceFuel'].gt(ZERO)); console.log( 'insurance before/after remove:', fuelDictInit2['insuranceFuel'].toNumber(), '->', fuelDictRmStake['insuranceFuel'].toNumber() ); await takerDriftClient.unsubscribe(); await takerDriftClientUser.unsubscribe(); }); it('fuel for perp taker/maker/position', async () => { const [takerDriftClient, _takerUSDCAccount] = await createTestClient({ referrer: fillerDriftClientUser.getUserAccount().authority, referrerStats: fillerDriftClient.getUserStatsAccountPublicKey(), }); const takerDriftClientUser = new User({ driftClient: takerDriftClient, userAccountPublicKey: await takerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await takerDriftClientUser.subscribe(); // const perp0 = fillerDriftClient.getPerpMarketAccount(0); // console.log(perp0); const [makerDriftClient, _makerUSDCAccount] = await createTestClient(); const makerDriftClientUser = new User({ driftClient: makerDriftClient, userAccountPublicKey: await makerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClientUser.subscribe(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; await makerDriftClient.placePerpOrder( getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, price: new BN(32).mul(PRICE_PRECISION), userOrderId: 2, postOnly: PostOnlyParams.NONE, }) ); await makerDriftClientUser.fetchAccounts(); assert(!makerDriftClientUser.getOrderByUserOrderId(2).postOnly); await fillerDriftClient.updateSpotMarketFuel(0, 100, 200, 200); await fillerDriftClient.updatePerpMarketFuel(marketIndex, 100, 200, 200); await takerDriftClient.placePerpOrder( getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, price: new BN(33).mul(PRICE_PRECISION), userOrderId: 1, postOnly: PostOnlyParams.NONE, }) ); await takerDriftClientUser.fetchAccounts(); const takerOrder = takerDriftClientUser.getOrderByUserOrderId(1); assert(!takerOrder.postOnly); const fillTx = await fillerDriftClient.fillPerpOrder( takerDriftClientUser.getUserAccountPublicKey(), takerDriftClientUser.getUserAccount(), takerOrder, { maker: makerDriftClientUser.getUserAccountPublicKey(), makerStats: makerDriftClient.getUserStatsAccountPublicKey(), makerUserAccount: makerDriftClientUser.getUserAccount(), // order: makerDriftClientUser.getOrderByUserOrderId(2), }, { referrer: fillerDriftClientUser.getUserAccount().authority, referrerStats: fillerDriftClient.getUserStatsAccountPublicKey(), } ); bankrunContextWrapper.connection.printTxLogs(fillTx); const currentClock2 = await bankrunContextWrapper.context.banksClient.getClock(); const fuelDict = takerDriftClientUser.getFuelBonus( new BN(currentClock2.unixTimestamp.toString()).addn(36000), true, true ); console.log(fuelDict); assert(fuelDict['depositFuel'].gt(ZERO)); assert(fuelDict['depositFuel'].eqn(1488)); assert(fuelDict['takerFuel'].eqn(3200)); assert( makerDriftClientUser .getPerpPosition(0) .baseAssetAmount.abs() .eq(baseAssetAmount) ); assert( takerDriftClientUser .getPerpPosition(0) .baseAssetAmount.abs() .eq(baseAssetAmount) ); const fuelDictMaker = makerDriftClientUser.getFuelBonus( new BN(currentClock2.unixTimestamp.toString()).addn(36000), true, true ); console.log(fuelDictMaker); assert(fuelDictMaker['depositFuel'].gt(ZERO)); assert(fuelDictMaker['depositFuel'].eqn(1488)); assert(fuelDictMaker['makerFuel'].eqn(3200 * 2)); const perp0 = fillerDriftClient.getPerpMarketAccount(0); // console.log( // perp0.amm.historicalOracleData.lastOraclePriceTwap5Min.toString() // ); const fuelPosition = calculatePerpFuelBonus( perp0, QUOTE_PRECISION.muln(32), new BN(36000) ); console.log(fuelPosition.toString()); assert(fuelPosition.gt(ZERO)); await makerDriftClientUser.unsubscribe(); await makerDriftClient.unsubscribe(); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); it('fuel for deposit', async () => { const [takerDriftClient, _takerUSDCAccount] = await createTestClient({ referrer: fillerDriftClientUser.getUserAccount().authority, referrerStats: fillerDriftClient.getUserStatsAccountPublicKey(), }); const takerDriftClientUser = new User({ driftClient: takerDriftClient, userAccountPublicKey: await takerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await takerDriftClientUser.subscribe(); assert(takerDriftClientUser.getTokenAmount(0).gt(ZERO)); const currentClock = await bankrunContextWrapper.context.banksClient.getClock(); // console.log('current ts:', currentClock.unixTimestamp.toString()); assert(new BN(currentClock.unixTimestamp.toString()).gt(ZERO)); await fillerDriftClient.updateSpotMarketFuel(0, 2); const fuelDictOGZERO = takerDriftClientUser.getFuelBonus( new BN(currentClock.unixTimestamp.toString()), true, true ); console.log(fuelDictOGZERO); assert(fuelDictOGZERO['depositFuel'].eq(ZERO)); const fuelDictOG = takerDriftClientUser.getFuelBonus( new BN(currentClock.unixTimestamp.toString()).addn(3600), true, true ); console.log(fuelDictOG); assert(fuelDictOG['depositFuel'].gt(ZERO)); assert(fuelDictOG['depositFuel'].eqn(2)); const timeProgress = 2592000; // 30 days in seconds await bankrunContextWrapper.moveTimeForward(timeProgress); const currentClock2 = await bankrunContextWrapper.context.banksClient.getClock(); const fuelDict = takerDriftClientUser.getFuelBonus( new BN(currentClock2.unixTimestamp.toString()), true, true ); console.log(fuelDict); assert(fuelDict['depositFuel'].gt(ZERO)); assert(fuelDict['depositFuel'].eqn(2142)); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); it('fuel for borrow', async () => { const [takerDriftClient, _takerUSDCAccount] = await createTestClient({ referrer: fillerDriftClientUser.getUserAccount().authority, referrerStats: fillerDriftClient.getUserStatsAccountPublicKey(), }); const takerDriftClientUser = new User({ driftClient: takerDriftClient, userAccountPublicKey: await takerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await takerDriftClientUser.subscribe(); assert(takerDriftClientUser.getTokenAmount(0).gt(ZERO)); const currentClock = await bankrunContextWrapper.context.banksClient.getClock(); // console.log('current ts:', currentClock.unixTimestamp.toString()); assert(new BN(currentClock.unixTimestamp.toString()).gt(ZERO)); await fillerDriftClient.updateSpotMarketFuel(0, 2, 5); await fillerDriftClient.updateSpotMarketFuel(1, 0, 100); const fuelDictOGZERO = takerDriftClientUser.getFuelBonus( new BN(currentClock.unixTimestamp.toString()), true, true ); console.log(fuelDictOGZERO); assert(fuelDictOGZERO['depositFuel'].eq(ZERO)); const fuelDictOG = takerDriftClientUser.getFuelBonus( new BN(currentClock.unixTimestamp.toString()).addn(3600), true, true ); console.log(fuelDictOG); assert(fuelDictOG['depositFuel'].gt(ZERO)); assert(fuelDictOG['depositFuel'].eqn(2)); const timeProgress = 2592000; // 30 days in seconds await bankrunContextWrapper.moveTimeForward(timeProgress); const currentClock2 = await bankrunContextWrapper.context.banksClient.getClock(); const fuelDict = takerDriftClientUser.getFuelBonus( new BN(currentClock2.unixTimestamp.toString()), true, true ); console.log(fuelDict); assert(fuelDict['depositFuel'].gt(ZERO)); assert(fuelDict['depositFuel'].eqn(2142)); assert(takerDriftClientUser.getTokenAmount(0).eq(usdcAmount)); console.log( 'last fuel update:', takerDriftClientUser.getUserAccount().lastFuelBonusUpdateTs.toString() ); await takerDriftClient.withdraw(ONE, 0, _takerUSDCAccount.publicKey, true); await takerDriftClient.fetchAccounts(); await takerDriftClientUser.fetchAccounts(); const userStatsAfterWithdraw = takerDriftClient.getUserStats().getAccount(); console.log(userStatsAfterWithdraw.fuelDeposits.toString()); assert(userStatsAfterWithdraw.fuelDeposits > 0); console.log(takerDriftClientUser.getTokenAmount(0).toString()); assert(takerDriftClientUser.getTokenAmount(0).eq(usdcAmount.subn(2))); // 2 for rounding purposes? console.log( 'last fuel update:', takerDriftClientUser.getUserAccount().lastFuelBonusUpdateTs.toString() ); const fuelDictAfter = takerDriftClientUser.getFuelBonus( new BN(currentClock2.unixTimestamp.toString()), true, true ); console.log(fuelDictAfter); assert(fuelDictAfter['depositFuel'].gt(ZERO)); assert(fuelDictAfter['depositFuel'].eqn(2142)); // withdraw/borrow .01 sol await takerDriftClient.withdraw( new BN(LAMPORTS_PER_SOL / 10), 1, takerDriftClient.provider.wallet.publicKey ); console.log(takerDriftClientUser.getTokenAmount(1).toString()); assert(takerDriftClientUser.getTokenAmount(1).lt(ZERO)); // 2 for rounding purposes? assert(takerDriftClientUser.getTokenAmount(1).toString() == '-100000001'); // 2 for rounding purposes? const fuelDictAfter2 = takerDriftClientUser.getFuelBonus( new BN(currentClock2.unixTimestamp.toString()).addn(36000), true, true ); console.log(fuelDictAfter2); assert(takerDriftClient.getSpotMarketAccount(1).fuelBoostBorrows == 100); assert(fuelDictAfter2['depositFuel'].gt(ZERO)); assert(fuelDictAfter2['depositFuel'].eqn(2171)); assert(fuelDictAfter2['borrowFuel'].eqn(48)); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); }); it('fuel for taker/maker spot trade', async () => { const [takerDriftClient, _takerUSDCAccount] = await createTestClient({ referrer: fillerDriftClientUser.getUserAccount().authority, referrerStats: fillerDriftClient.getUserStatsAccountPublicKey(), }); const takerDriftClientUser = new User({ driftClient: takerDriftClient, userAccountPublicKey: await takerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await takerDriftClientUser.subscribe(); const [makerDriftClient, _makerUSDCAccount] = await createTestClient(); const makerDriftClientUser = new User({ driftClient: makerDriftClient, userAccountPublicKey: await makerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClientUser.subscribe(); const marketIndex = 1; const baseAssetAmount = BASE_PRECISION; await makerDriftClient.placeSpotOrder( getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, price: new BN(40).mul(PRICE_PRECISION), userOrderId: 2, postOnly: PostOnlyParams.NONE, }) ); await makerDriftClientUser.fetchAccounts(); assert(!makerDriftClientUser.getOrderByUserOrderId(2).postOnly); await fillerDriftClient.updateSpotMarketFuel(1, null, null, 100, 200); // paused cumulative interest to avoid test failing due to race await fillerDriftClient.updateSpotMarketPausedOperations(1, 1); await takerDriftClient.placeSpotOrder( getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, price: new BN(41).mul(PRICE_PRECISION), // auctionStartPrice: null, // auctionEndPrice: null, // auctionDuration: 0, userOrderId: 1, postOnly: PostOnlyParams.NONE, }) ); await takerDriftClientUser.fetchAccounts(); const takerOrder = takerDriftClientUser.getOrderByUserOrderId(1); assert(!takerOrder.postOnly); const fillTx = await fillerDriftClient.fillSpotOrder( takerDriftClientUser.getUserAccountPublicKey(), takerDriftClientUser.getUserAccount(), takerOrder, null, { maker: makerDriftClientUser.getUserAccountPublicKey(), makerStats: makerDriftClient.getUserStatsAccountPublicKey(), makerUserAccount: makerDriftClientUser.getUserAccount(), // order: makerDriftClientUser.getOrderByUserOrderId(2), }, { referrer: fillerDriftClientUser.getUserAccount().authority, referrerStats: fillerDriftClient.getUserStatsAccountPublicKey(), } ); bankrunContextWrapper.connection.printTxLogs(fillTx); await makerDriftClientUser.fetchAccounts(); const makerUSDCAmount = makerDriftClient.getQuoteAssetTokenAmount(); const makerSolAmount = makerDriftClient.getTokenAmount(1); console.log(makerUSDCAmount.toString(), makerSolAmount.toString()); assert(makerUSDCAmount.gte(new BN(140000000))); assert(makerSolAmount.lte(new BN(-1000000000))); // round borrows up const takerUSDCAmount = takerDriftClient.getQuoteAssetTokenAmount(); const takerSolAmount = takerDriftClient.getTokenAmount(1); console.log(takerUSDCAmount.toString(), takerSolAmount.toString()); assert(takerUSDCAmount.eq(new BN(59960000))); assert(takerSolAmount.gte(new BN(1000000000 - 5))); assert(takerSolAmount.lte(new BN(1000000005))); console.log(fillerDriftClient.getQuoteAssetTokenAmount().toNumber()); // successful fill assert(fillerDriftClient.getQuoteAssetTokenAmount().gt(ZERO)); const currentClock2 = await bankrunContextWrapper.context.banksClient.getClock(); const fuelDictTaker = takerDriftClientUser.getFuelBonus( new BN(currentClock2.unixTimestamp.toString()), true, true ); console.log(fuelDictTaker); assert(fuelDictTaker['takerFuel'].gt(ZERO)); assert(fuelDictTaker['takerFuel'].eqn(4000)); const fuelDictMaker = makerDriftClientUser.getFuelBonus( new BN(currentClock2.unixTimestamp.toString()), true, true ); // console.log(fuelDictMaker); assert(fuelDictMaker['takerFuel'].eq(ZERO)); assert(fuelDictMaker['makerFuel'].gt(ZERO)); assert(fuelDictMaker['makerFuel'].eqn(4000 * 2)); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); await makerDriftClient.unsubscribe(); await makerDriftClientUser.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/postOnly.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair } from '@solana/web3.js'; import { TestClient, BN, PRICE_PRECISION, PositionDirection, User, Wallet, EventSubscriber, MarketStatus, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, } from './testHelpers'; import { BASE_PRECISION, calculateReservePrice, getLimitOrderParams, isVariant, OracleSource, PostOnlyParams, ZERO, } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('post only', () => { const chProgram = anchor.workspace.Drift as Program; let fillerDriftClient: TestClient; let fillerDriftClientUser: User; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(100000); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); let solUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); marketIndexes = [0]; spotMarketIndexes = [0]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; fillerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClient.initialize(usdcMint.publicKey, true); await fillerDriftClient.subscribe(); await initializeQuoteSpotMarket(fillerDriftClient, usdcMint.publicKey); await fillerDriftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(60 * 60); // 1 HOUR await fillerDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await fillerDriftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); await fillerDriftClient.updatePerpMarketBaseSpread(0, 500); await fillerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); fillerDriftClientUser = new User({ driftClient: fillerDriftClient, userAccountPublicKey: await fillerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClientUser.subscribe(); }); beforeEach(async () => { await fillerDriftClient.moveAmmPrice( 0, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve ); await setFeedPriceNoProgram(bankrunContextWrapper, 1, solUsd); }); after(async () => { await fillerDriftClient.unsubscribe(); await fillerDriftClientUser.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('long', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const reservePrice = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, price: reservePrice, userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, }); await driftClient.placePerpOrder(makerOrderParams); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); assert(order.postOnly); const newOraclePrice = 0.98; setFeedPriceNoProgram(bankrunContextWrapper, newOraclePrice, solUsd); await fillerDriftClient.moveAmmToPrice( marketIndex, new BN(newOraclePrice * PRICE_PRECISION.toNumber()) ); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const position = driftClientUser.getPerpPosition(marketIndex); assert(position.baseAssetAmount.eq(baseAssetAmount)); console.log(position.quoteBreakEvenAmount.toString()); assert(driftClient.getQuoteAssetTokenAmount().eq(usdcAmount)); assert(driftClient.getUserStats().getAccount().fees.totalFeePaid.eq(ZERO)); await fillerDriftClient.fetchAccounts(); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert(isVariant(orderRecord.action, 'fill')); assert(orderRecord.takerFee.eq(ZERO)); assert(orderRecord.quoteAssetAmountSurplus.eq(new BN(19507))); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('short', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const reservePrice = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, price: reservePrice, userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, }); await driftClient.placePerpOrder(makerOrderParams); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); assert(order.postOnly); const newOraclePrice = 1.02; setFeedPriceNoProgram(bankrunContextWrapper, newOraclePrice, solUsd); await fillerDriftClient.moveAmmToPrice( marketIndex, new BN(newOraclePrice * PRICE_PRECISION.toNumber()) ); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const position = driftClientUser.getPerpPosition(marketIndex); assert(position.baseAssetAmount.abs().eq(baseAssetAmount)); assert(position.quoteBreakEvenAmount.eq(new BN(1000200))); assert(driftClient.getQuoteAssetTokenAmount().eq(usdcAmount)); assert(driftClient.getUserStats().getAccount().fees.totalFeePaid.eq(ZERO)); assert( driftClient .getUserStats() .getAccount() .fees.totalFeeRebate.eq(new BN(200)) ); await fillerDriftClient.fetchAccounts(); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert(isVariant(orderRecord.action, 'fill')); assert(orderRecord.takerFee.eq(new BN(0))); console.log(orderRecord.quoteAssetAmountSurplus.toString()); assert(orderRecord.quoteAssetAmountSurplus.eq(new BN(19492))); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/perpLpRiskMitigation.ts
import * as web3 from '@solana/web3.js'; import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { assert } from 'chai'; import { TestClient, QUOTE_PRECISION, EventSubscriber, PRICE_PRECISION, PositionDirection, ZERO, BN, calculateAmmReservesAfterSwap, calculatePrice, User, OracleSource, SwapDirection, Wallet, LPRecord, BASE_PRECISION, OracleGuardRails, isVariant, MARGIN_PRECISION, SettlePnlMode, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, sleep, // sleep, } from './testHelpers'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; async function adjustOraclePostSwap(baa, swapDirection, market, context) { const price = calculatePrice( market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier ); const [newQaa, newBaa] = calculateAmmReservesAfterSwap( market.amm, 'base', baa.abs(), swapDirection ); const newPrice = calculatePrice(newBaa, newQaa, market.amm.pegMultiplier); const _newPrice = newPrice.toNumber() / PRICE_PRECISION.toNumber(); await setFeedPriceNoProgram(context, _newPrice, market.amm.oracle); console.log('price => new price', price.toString(), newPrice.toString()); return _newPrice; } async function createNewUser( program, context: BankrunContextWrapper, usdcMint, usdcAmount, oracleInfos, wallet, bulkAccountLoader ): Promise<[TestClient, User]> { let walletFlag = true; if (wallet == undefined) { const kp = new web3.Keypair(); await context.fundKeypair(kp, 10 ** 9); wallet = new Wallet(kp); walletFlag = false; } console.log('wallet:', walletFlag); const usdcAta = await mockUserUSDCAccount( usdcMint, usdcAmount, context, wallet.publicKey ); const driftClient = new TestClient({ connection: context.connection.toConnection(), wallet: wallet, programID: program.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0, 1, 2, 3], spotMarketIndexes: [0], subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); if (walletFlag) { await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); } else { await driftClient.subscribe(); } await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, usdcAta.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); driftClientUser.subscribe(); return [driftClient, driftClientUser]; } describe('lp risk mitigation', () => { const chProgram = anchor.workspace.Drift as Program; async function _viewLogs(txsig) { bankrunContextWrapper.printTxLogs(txsig); } async function delay(time) { await new Promise((resolve) => setTimeout(resolve, time)); } // ammInvariant == k == x * y const ammInitialBaseAssetReserve = new BN(10000).mul(BASE_PRECISION); const ammInitialQuoteAssetReserve = new BN(10000).mul(BASE_PRECISION); const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const stableAmmInitialQuoteAssetReserve = BASE_PRECISION.mul(mantissaSqrtScale); const stableAmmInitialBaseAssetReserve = BASE_PRECISION.mul(mantissaSqrtScale); const usdcAmount = new BN(5000 * 1e6); // 2000 bucks let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint: web3.Keypair; let driftClientUser: User; let traderDriftClient: TestClient; let traderDriftClientUser: User; let poorDriftClient: TestClient; let poorDriftClientUser: User; let solusdc; let solusdc2; let solusdc3; let btcusdc; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); solusdc3 = await mockOracleNoProgram(bankrunContextWrapper, 1, -7); // make invalid solusdc2 = await mockOracleNoProgram(bankrunContextWrapper, 1, -7); // make invalid solusdc = await mockOracleNoProgram(bankrunContextWrapper, 1, -7); // make invalid btcusdc = await mockOracleNoProgram(bankrunContextWrapper, 26069, -7); const oracleInfos = [ { publicKey: solusdc, source: OracleSource.PYTH }, { publicKey: solusdc2, source: OracleSource.PYTH }, { publicKey: solusdc3, source: OracleSource.PYTH }, { publicKey: btcusdc, source: OracleSource.PYTH }, ]; [driftClient, driftClientUser] = await createNewUser( chProgram, bankrunContextWrapper, usdcMint, usdcAmount, oracleInfos, bankrunContextWrapper.provider.wallet, bulkAccountLoader ); // used for trading / taking on baa await driftClient.initializePerpMarket( 0, solusdc, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, new BN(60 * 60) ); await driftClient.updateLpCooldownTime(new BN(0)); await driftClient.updatePerpMarketMaxFillReserveFraction(0, 1); const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: new BN(1000000), oracleTwap5MinPercentDivergence: new BN(1000000), }, validity: { slotsBeforeStaleForAmm: new BN(10), slotsBeforeStaleForMargin: new BN(10), confidenceIntervalMaxSize: new BN(100), tooVolatileRatio: new BN(100), }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); // await driftClient.updateMarketBaseAssetAmountStepSize( // new BN(0), // new BN(1) // ); // second market -- used for funding .. await driftClient.initializePerpMarket( 1, solusdc2, stableAmmInitialBaseAssetReserve, stableAmmInitialQuoteAssetReserve, new BN(0) ); await driftClient.updateLpCooldownTime(new BN(0)); await driftClient.updatePerpAuctionDuration(new BN(0)); // third market await driftClient.initializePerpMarket( 2, solusdc3, stableAmmInitialBaseAssetReserve, stableAmmInitialQuoteAssetReserve, new BN(0) ); // third market await driftClient.initializePerpMarket( 3, btcusdc, stableAmmInitialBaseAssetReserve.div(new BN(1000)), stableAmmInitialQuoteAssetReserve.div(new BN(1000)), new BN(0), new BN(26690 * 1000) ); await driftClient.updateLpCooldownTime(new BN(0)); await driftClient.updatePerpAuctionDuration(new BN(0)); [traderDriftClient, traderDriftClientUser] = await createNewUser( chProgram, bankrunContextWrapper, usdcMint, usdcAmount, oracleInfos, undefined, bulkAccountLoader ); await traderDriftClient.updateUserAdvancedLp([ { advancedLp: true, subAccountId: 0, }, ]); [poorDriftClient, poorDriftClientUser] = await createNewUser( chProgram, bankrunContextWrapper, usdcMint, QUOTE_PRECISION.mul(new BN(10000)), oracleInfos, undefined, bulkAccountLoader ); await poorDriftClient.updateUserAdvancedLp([ { advancedLp: true, subAccountId: 0, }, ]); }); after(async () => { await eventSubscriber.unsubscribe(); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); await traderDriftClient.unsubscribe(); await traderDriftClientUser.unsubscribe(); await poorDriftClient.unsubscribe(); await poorDriftClientUser.unsubscribe(); }); const lpCooldown = 1; it('perp risk mitigation', async () => { const marketIndex = 0; console.log('adding liquidity...'); await driftClient.updatePerpMarketTargetBaseAssetAmountPerLp( marketIndex, BASE_PRECISION.toNumber() ); sleep(1200); await driftClient.fetchAccounts(); let market = driftClient.getPerpMarketAccount(marketIndex); console.log( 'market.amm.sqrtK:', market.amm.userLpShares.toString(), '/', market.amm.sqrtK.toString(), 'target:', market.amm.targetBaseAssetAmountPerLp ); assert(market.amm.sqrtK.eq(new BN('10000000000000'))); assert(market.amm.baseAssetAmountPerLp.eq(ZERO)); // assert(market.amm.targetBaseAssetAmountPerLp == BASE_PRECISION.toNumber()); const _sig = await driftClient.addPerpLpShares( new BN(1000 * BASE_PRECISION.toNumber()), market.marketIndex ); await delay(lpCooldown + 1000); await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(0); console.log( 'market.amm.sqrtK:', market.amm.userLpShares.toString(), '/', market.amm.sqrtK.toString() ); assert(market.amm.sqrtK.eq(new BN('11000000000000'))); assert(market.amm.baseAssetAmountPerLp.eq(ZERO)); assert(market.amm.targetBaseAssetAmountPerLp == BASE_PRECISION.toNumber()); let user = await driftClientUser.getUserAccount(); assert(user.perpPositions[0].lpShares.toString() == '1000000000000'); // 1000 * 1e9 // lp goes short const tradeSize = new BN(500 * BASE_PRECISION.toNumber()); try { await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await driftClient.openPosition( PositionDirection.SHORT, tradeSize, market.marketIndex, new BN(0.1 * PRICE_PRECISION.toNumber()) ); await _viewLogs(_txsig); } catch (e) { console.log(e); } await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(0); console.log( 'market.amm.baseAssetAmountPerLp:', market.amm.baseAssetAmountPerLp.toString() ); assert(market.amm.baseAssetAmountPerLp.eq(new BN('45454545'))); await driftClientUser.fetchAccounts(); await driftClient.accountSubscriber.setSpotOracleMap(); console.log( 'driftClientUser.getFreeCollateral()=', driftClientUser.getFreeCollateral().toString() ); assert(driftClientUser.getFreeCollateral().eq(new BN('4761073360'))); // some user goes long (lp should get more short) try { await adjustOraclePostSwap( tradeSize, SwapDirection.REMOVE, market, bankrunContextWrapper ); const _txsig = await traderDriftClient.openPosition( PositionDirection.LONG, tradeSize, market.marketIndex // new BN(100 * BASE_PRECISION.toNumber()) ); await _viewLogs(_txsig); } catch (e) { console.log(e); } await driftClient.fetchAccounts(); market = driftClient.getPerpMarketAccount(0); console.log( 'market.amm.baseAssetAmountPerLp:', market.amm.baseAssetAmountPerLp.toString() ); assert(market.amm.baseAssetAmountPerLp.eq(new BN('0'))); console.log( 'market.amm.baseAssetAmountWithAmm:', market.amm.baseAssetAmountWithAmm.toString() ); assert(market.amm.baseAssetAmountWithAmm.eq(new BN('0'))); const trader = await traderDriftClient.getUserAccount(); console.log( 'trader size', trader.perpPositions[0].baseAssetAmount.toString() ); await driftClientUser.fetchAccounts(); const [userPos, dustBase, sdkPnl] = driftClientUser.getPerpPositionWithLPSettle(0); console.log('baseAssetAmount:', userPos.baseAssetAmount.toString()); console.log('dustBase:', dustBase.toString()); console.log('settling...'); try { const _txsigg = await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), await driftClient.getUserAccount(), 0 ); await _viewLogs(_txsigg); } catch (e) { console.log(e); } user = driftClientUser.getUserAccount(); const settleLiquidityRecord: LPRecord = eventSubscriber.getEventsArray('LPRecord')[0]; console.log( 'settle pnl vs sdk', settleLiquidityRecord.pnl.toString(), sdkPnl.toString() ); assert(settleLiquidityRecord.pnl.eq(sdkPnl)); const perpLiqPrice = driftClientUser.liquidationPrice(0); console.log('perpLiqPrice:', perpLiqPrice.toString()); await setFeedPriceNoProgram(bankrunContextWrapper, 8, solusdc); console.log('settling...'); try { const _txsigg = await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), await driftClient.getUserAccount(), 0 ); await _viewLogs(_txsigg); } catch (e) { console.log(e); } await driftClient.updateUserCustomMarginRatio([ { marginRatio: MARGIN_PRECISION.toNumber(), subAccountId: 0, }, ]); await sleep(1000); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); console.log( 'driftClientUser.getUserAccount().openOrders=', driftClientUser.getUserAccount().openOrders ); assert(driftClientUser.getUserAccount().openOrders == 0); console.log('settling after margin ratio update...'); try { const _txsigg = await driftClient.settleMultiplePNLs( await driftClient.getUserAccountPublicKey(), await driftClient.getUserAccount(), [0], SettlePnlMode.TRY_SETTLE ); await _viewLogs(_txsigg); } catch (e) { console.log(e); } await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); const afterReduceOrdersAccount = driftClientUser.getUserAccount(); assert(afterReduceOrdersAccount.openOrders == 1); const leOrder = afterReduceOrdersAccount.orders[0]; console.log(leOrder); assert(leOrder.auctionDuration == 80); assert(leOrder.auctionStartPrice.lt(leOrder.auctionEndPrice)); assert(leOrder.auctionEndPrice.gt(ZERO)); assert(leOrder.reduceOnly); assert(!leOrder.postOnly); assert(leOrder.marketIndex == 0); assert(leOrder.baseAssetAmount.eq(new BN('500000000000'))); assert(isVariant(leOrder.direction, 'long')); assert(isVariant(leOrder.existingPositionDirection, 'short')); const afterReduceShares = afterReduceOrdersAccount.perpPositions[0].lpShares; console.log('afterReduceShares=', afterReduceShares.toString()); assert(afterReduceShares.lt(new BN(1000 * BASE_PRECISION.toNumber()))); assert(afterReduceShares.eq(new BN('400000000000'))); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/updateK.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { AMM_RESERVE_PRECISION, BASE_PRECISION, BN, BulkAccountLoader, calculateTradeSlippage, } from '../sdk'; import { Keypair } from '@solana/web3.js'; import { Program } from '@coral-xyz/anchor'; import { TestClient, PRICE_PRECISION, calculateReservePrice, User, PEG_PRECISION, PositionDirection, convertToNumber, squareRootBN, calculateBudgetedKBN, QUOTE_SPOT_MARKET_INDEX, MarketStatus, } from '../sdk/src'; import { createPriceFeed, mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, } from './testHelpers'; import { QUOTE_PRECISION } from '../sdk/src'; const ZERO = new BN(0); describe('update k', () => { const provider = anchor.AnchorProvider.local(undefined, { preflightCommitment: 'confirmed', skipPreflight: false, commitment: 'confirmed', }); const connection = provider.connection; anchor.setProvider(provider); const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; const bulkAccountLoader = new BulkAccountLoader(connection, 'confirmed', 1); let usdcMint: Keypair; let userUSDCAccount: Keypair; const initialSOLPrice = 150; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 9).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 9).mul( mantissaSqrtScale ); const usdcAmount = new BN(1e9 * 10 ** 6); let userAccount: User; before(async () => { usdcMint = await mockUSDCMint(provider); userUSDCAccount = await mockUserUSDCAccount(usdcMint, usdcAmount, provider); driftClient = new TestClient({ connection, wallet: provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(60 * 60); // 1 HOUR const solUsdOracle = await createPriceFeed({ oracleProgram: anchor.workspace.Pyth, initPrice: initialSOLPrice, }); await driftClient.initializePerpMarket( 0, solUsdOracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(initialSOLPrice * PEG_PRECISION.toNumber()) ); await driftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); await driftClient.initializeUserAccount(); userAccount = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), }); await userAccount.subscribe(); }); after(async () => { await driftClient.unsubscribe(); await userAccount.unsubscribe(); }); it('increase k (FREE)', async () => { const marketIndex = 0; const oldKPrice = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); const ammOld = driftClient.getPerpMarketAccount(0).amm; const newSqrtK = ammInitialBaseAssetReserve.mul(new BN(10)); await driftClient.updateK(marketIndex, newSqrtK); await driftClient.fetchAccounts(); const newKPrice = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); const amm = driftClient.getPerpMarketAccount(0).amm; const marginOfError = new BN(100); console.log( 'oldSqrtK', convertToNumber(ammOld.sqrtK, AMM_RESERVE_PRECISION), 'oldKPrice:', convertToNumber(oldKPrice) ); console.log( 'newSqrtK', convertToNumber(newSqrtK, AMM_RESERVE_PRECISION), 'newKPrice:', convertToNumber(newKPrice) ); assert(ammOld.sqrtK.lt(amm.sqrtK)); assert(newKPrice.sub(oldKPrice).abs().lt(marginOfError)); assert(amm.sqrtK.eq(newSqrtK)); }); it('increase k base/quote imbalance (FREE)', async () => { await driftClient.deposit( usdcAmount, QUOTE_SPOT_MARKET_INDEX, userUSDCAccount.publicKey ); const marketIndex = 0; const targetPriceUp = new BN( initialSOLPrice * PRICE_PRECISION.toNumber() * 44.1 ); await driftClient.moveAmmToPrice(marketIndex, targetPriceUp); await driftClient.fetchAccounts(); const marketOld = driftClient.getPerpMarketAccount(0); const oldKPrice = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); const ammOld = marketOld.amm; const newSqrtK = ammOld.sqrtK .mul(new BN(1.000132325235 * PRICE_PRECISION.toNumber())) .div(PRICE_PRECISION); await driftClient.updateK(marketIndex, newSqrtK); await driftClient.fetchAccounts(); const newKPrice = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); const amm = driftClient.getPerpMarketAccount(0).amm; const marginOfError = new BN(PRICE_PRECISION.div(new BN(1000))); // price change less than 3 decimal places console.log( 'oldSqrtK', convertToNumber(ammOld.sqrtK), 'baa/qaa:', ammOld.baseAssetReserve.toString(), '/', ammOld.quoteAssetReserve.toString(), 'oldKPrice:', convertToNumber(oldKPrice) ); console.log( 'newSqrtK', convertToNumber(newSqrtK), 'baa/qaa:', amm.baseAssetReserve.toString(), '/', amm.quoteAssetReserve.toString(), 'newKPrice:', convertToNumber(newKPrice) ); assert(ammOld.sqrtK.lt(amm.sqrtK)); assert(newKPrice.sub(oldKPrice).abs().lt(marginOfError)); assert(amm.sqrtK.eq(newSqrtK)); }); it('failure: lower k (more than 2.5%) position imbalance (AMM PROFIT)', async () => { const marketIndex = 0; const targetPriceBack = new BN( initialSOLPrice * PRICE_PRECISION.toNumber() ); // const [direction, tradeSize, _] = driftClient.calculateTargetPriceTrade( // marketIndex, // targetPriceUp // ); await driftClient.moveAmmToPrice(marketIndex, targetPriceBack); console.log('taking position'); await driftClient.openPosition( PositionDirection.LONG, BASE_PRECISION.div(new BN(initialSOLPrice)), marketIndex ); console.log('$1 position taken'); await driftClient.fetchAccounts(); const marketOld = driftClient.getPerpMarketAccount(0); assert(!marketOld.amm.baseAssetAmountWithAmm.eq(ZERO)); const oldKPrice = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); const ammOld = marketOld.amm; console.log( 'USER getTotalCollateral', convertToNumber(userAccount.getTotalCollateral(), QUOTE_PRECISION) ); const newSqrtK = ammOld.sqrtK .mul(new BN(0.5 * PRICE_PRECISION.toNumber())) .div(PRICE_PRECISION); try { await driftClient.updateK(marketIndex, newSqrtK); assert(false); } catch { await driftClient.fetchAccounts(); const marketKChange = await driftClient.getPerpMarketAccount(0); const ammKChange = marketKChange.amm; const newKPrice = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); console.log('$1 position closing'); await driftClient.closePosition(marketIndex); console.log('$1 position closed'); const amm = driftClient.getPerpMarketAccount(0).amm; const marginOfError = new BN(PRICE_PRECISION.div(new BN(1000))); // price change less than 3 decimal places console.log( 'oldSqrtK', convertToNumber(ammOld.sqrtK), 'oldKPrice:', convertToNumber(oldKPrice) ); console.log( 'newSqrtK', convertToNumber(newSqrtK), 'newKPrice:', convertToNumber(newKPrice) ); assert(ammOld.sqrtK.eq(amm.sqrtK)); assert(newKPrice.sub(oldKPrice).abs().lt(marginOfError)); assert(!amm.sqrtK.eq(newSqrtK)); console.log( 'realizedFeeOld', convertToNumber(ammOld.totalFeeMinusDistributions, QUOTE_PRECISION), 'realizedFeePostK', convertToNumber(ammKChange.totalFeeMinusDistributions, QUOTE_PRECISION), 'realizedFeePostClose', convertToNumber(amm.totalFeeMinusDistributions, QUOTE_PRECISION) ); console.log( 'USER getTotalCollateral', convertToNumber(userAccount.getTotalCollateral(), QUOTE_PRECISION) ); assert( ammKChange.totalFeeMinusDistributions.eq( ammOld.totalFeeMinusDistributions ) ); // equal since no k change assert( amm.totalFeeMinusDistributions.gte(ammOld.totalFeeMinusDistributions) ); // greater/equal since user closed } }); it('lower k (2%) position imbalance (AMM PROFIT)', async () => { const marketIndex = 0; const targetPriceBack = new BN( initialSOLPrice * PRICE_PRECISION.toNumber() ); // const [direction, tradeSize, _] = driftClient.calculateTargetPriceTrade( // marketIndex, // targetPriceUp // ); await driftClient.moveAmmToPrice(marketIndex, targetPriceBack); console.log('taking position'); await driftClient.openPosition( PositionDirection.LONG, BASE_PRECISION.div(new BN(initialSOLPrice)).mul(new BN(1000)), marketIndex ); console.log('$1000 position taken'); await driftClient.fetchAccounts(); const marketOld = driftClient.getPerpMarketAccount(0); assert(!marketOld.amm.baseAssetAmountWithAmm.eq(ZERO)); const oldKPrice = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); const ammOld = marketOld.amm; console.log( 'USER getTotalCollateral', convertToNumber(userAccount.getTotalCollateral(), QUOTE_PRECISION) ); const newSqrtK = ammOld.sqrtK .mul(new BN(0.98 * PRICE_PRECISION.toNumber())) .div(PRICE_PRECISION); const smallTradeSlipOld = calculateTradeSlippage( PositionDirection.LONG, QUOTE_PRECISION.mul(new BN(1000)), marketOld )[0]; try { await driftClient.updateK(marketIndex, newSqrtK); } catch (e) { console.error(e); assert(false); } await driftClient.fetchAccounts(); const marketKChange = driftClient.getPerpMarketAccount(0); const ammKChange = marketKChange.amm; const newKPrice = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); const smallTradeSlip = calculateTradeSlippage( PositionDirection.LONG, QUOTE_PRECISION.mul(new BN(1000)), marketKChange )[0]; console.log( '$1000 slippage (', convertToNumber(smallTradeSlipOld), '->', convertToNumber(smallTradeSlip), ')' ); assert(smallTradeSlipOld.lt(smallTradeSlip)); console.log('$1000 position closing'); await driftClient.closePosition(marketIndex); console.log('$1 position closed'); const amm = driftClient.getPerpMarketAccount(0).amm; const marginOfError = new BN(PRICE_PRECISION.div(new BN(1000))); // price change less than 3 decimal places console.log( 'oldSqrtK', convertToNumber(ammOld.sqrtK), 'oldKPrice:', convertToNumber(oldKPrice) ); console.log( 'newSqrtK', convertToNumber(newSqrtK), 'newKPrice:', convertToNumber(newKPrice) ); assert(ammOld.sqrtK.gt(amm.sqrtK)); assert(newKPrice.sub(oldKPrice).abs().lt(marginOfError)); assert(amm.sqrtK.eq(newSqrtK)); console.log( 'realizedFeeOld', convertToNumber(ammOld.totalFeeMinusDistributions, QUOTE_PRECISION), 'realizedFeePostK', convertToNumber(ammKChange.totalFeeMinusDistributions, QUOTE_PRECISION), 'realizedFeePostClose', convertToNumber(amm.totalFeeMinusDistributions, QUOTE_PRECISION) ); console.log( 'USER getTotalCollateral', convertToNumber(userAccount.getTotalCollateral(), QUOTE_PRECISION) ); assert( amm.totalFeeMinusDistributions.gt(ammOld.totalFeeMinusDistributions) ); }); it('increase k position imbalance (AMM LOSS)', async () => { const marketIndex = 0; const targetPriceBack = new BN( initialSOLPrice * PRICE_PRECISION.toNumber() ); // const [direction, tradeSize, _] = driftClient.calculateTargetPriceTrade( // marketIndex, // targetPriceUp // ); await driftClient.moveAmmToPrice(marketIndex, targetPriceBack); console.log('taking position'); await driftClient.openPosition( PositionDirection.LONG, new BN(QUOTE_PRECISION).mul(new BN(30000)), marketIndex ); console.log('$1 position taken'); await driftClient.fetchAccounts(); const marketOld = driftClient.getPerpMarketAccount(0); assert(!marketOld.amm.baseAssetAmountWithAmm.eq(ZERO)); const oldKPrice = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); const ammOld = marketOld.amm; console.log( 'USER getTotalCollateral', convertToNumber(userAccount.getTotalCollateral(), QUOTE_PRECISION) ); const smallTradeSlipOld = calculateTradeSlippage( PositionDirection.LONG, QUOTE_PRECISION, marketOld )[0]; const newSqrtK = ammOld.sqrtK .mul(new BN(1.02 * PRICE_PRECISION.toNumber())) .div(PRICE_PRECISION); await driftClient.updateK(marketIndex, newSqrtK); await driftClient.fetchAccounts(); const marketKChange = driftClient.getPerpMarketAccount(0); const ammKChange = marketKChange.amm; const newKPrice = calculateReservePrice( driftClient.getPerpMarketAccount(marketIndex), undefined ); const smallTradeSlip = calculateTradeSlippage( PositionDirection.LONG, QUOTE_PRECISION, marketKChange )[0]; console.log( '$1 slippage (', convertToNumber(smallTradeSlipOld), '->', convertToNumber(smallTradeSlip), ')' ); assert(smallTradeSlipOld.gte(smallTradeSlip)); console.log('$1 position closing'); await driftClient.closePosition(marketIndex); console.log('$1 position closed'); await driftClient.fetchAccounts(); const markets = driftClient.getPerpMarketAccount(0); const amm = markets.amm; const marginOfError = new BN(PRICE_PRECISION.div(new BN(1000))); // price change less than 3 decimal places console.log( 'oldSqrtK', convertToNumber(ammOld.sqrtK, AMM_RESERVE_PRECISION), 'oldKPrice:', convertToNumber(oldKPrice) ); console.log( 'newSqrtK', convertToNumber(newSqrtK, AMM_RESERVE_PRECISION), 'newKPrice:', convertToNumber(newKPrice) ); assert(ammOld.sqrtK.lt(amm.sqrtK)); assert(newKPrice.sub(oldKPrice).abs().lt(marginOfError)); assert(amm.sqrtK.eq(newSqrtK)); console.log( 'old sqrt X*Y:', convertToNumber( squareRootBN(ammOld.baseAssetReserve.mul(ammOld.quoteAssetReserve)), AMM_RESERVE_PRECISION ), 'close sqrt X*Y:', convertToNumber( squareRootBN( ammKChange.baseAssetReserve.mul(ammKChange.quoteAssetReserve) ), AMM_RESERVE_PRECISION ), 'close sqrt X*Y:', convertToNumber( squareRootBN(amm.baseAssetReserve.mul(amm.quoteAssetReserve)), AMM_RESERVE_PRECISION ) ); console.log( 'realizedFeeOld', convertToNumber(ammOld.totalFeeMinusDistributions, QUOTE_PRECISION), 'realizedFeePostK', convertToNumber(ammKChange.totalFeeMinusDistributions, QUOTE_PRECISION), 'realizedFeePostClose', convertToNumber(amm.totalFeeMinusDistributions, QUOTE_PRECISION) ); assert( amm.totalFeeMinusDistributions.gt(ammOld.totalFeeMinusDistributions) ); console.log( 'USER getTotalCollateral', convertToNumber(userAccount.getTotalCollateral(), QUOTE_PRECISION) ); }); it('budget k change (sdk math)', async () => { // // pay $.11 to increase k let [numer1, denom1] = calculateBudgetedKBN( new BN('4975000000'), // x new BN('5025000000'), // y new BN('114638'), // cost new BN('40000000'), // peg new BN('4975000000') // net position ); console.log(numer1.toString(), '/', denom1.toString()); // Z-TODO console.log(denom1.toString()); console.log(numer1.toString()); assert(denom1.eq(new BN(4969200900))); assert(numer1.gte(new BN(4980550349))); // gain $.11 by decreasing k [numer1, denom1] = calculateBudgetedKBN( new BN('4975000000'), // x new BN('5025000000'), // y new BN('-114638'), // cost new BN('40000000'), // peg new BN('4975000000') // net position ); console.log(numer1.toString(), '/', denom1.toString()); assert(numer1.eq(new BN(4969200900))); assert(denom1.eq(new BN(4980550349))); assert(numer1.lt(denom1)); // pay $11 to increase k [numer1, denom1] = calculateBudgetedKBN( new BN('4975000000'), new BN('5025000000'), new BN('11463800'), new BN('40000000'), new BN('4975000000') ); console.log(numer1.toString(), '/', denom1.toString()); assert(numer1.eq(new BN(5542348054))); assert(denom1.eq(new BN(4407403195))); assert(numer1.gt(denom1)); // net pos so small that decreasing k for .01 is sending to zero (squeezing a stone) [numer1, denom1] = calculateBudgetedKBN( new BN('50000000004975000000'), new BN('49999999995025000000'), new BN('-10000'), new BN('40000000'), new BN('-4975000000') ); console.log(numer1.toString(), '/', denom1.toString()); assert(numer1.eq(new BN('49498762495074625625'))); assert(denom1.eq(new BN('25000049503737495074625625'))); // impossible task trying to spend more than amount to make k infinity [numer1, denom1] = calculateBudgetedKBN( new BN('50000000004975000000'), new BN('49999999995025000000'), new BN('10000'), new BN('40000000'), new BN('-4975000000') ); console.log(numer1.toString(), '/', denom1.toString()); assert(numer1.eq(new BN(10000))); // max k assert(denom1.eq(new BN(1))); // max k }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/spotDepositWithdraw.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js'; import { TestClient, BN, EventSubscriber, SPOT_MARKET_RATE_PRECISION, SpotBalanceType, isVariant, OracleSource, SPOT_MARKET_WEIGHT_PRECISION, SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION, OracleInfo, } from '../sdk/src'; import { createUserWithUSDCAccount, createUserWithUSDCAndWSOLAccount, mintUSDCToUser, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpers'; import { getBalance, calculateInterestAccumulated, getTokenAmount, } from '../sdk/src/math/spotBalance'; import { NATIVE_MINT } from '@solana/spl-token'; import { QUOTE_PRECISION, ZERO, ONE, SPOT_MARKET_BALANCE_PRECISION, PRICE_PRECISION, } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('spot deposit and withdraw', () => { const chProgram = anchor.workspace.Drift as Program; let admin: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let solOracle: PublicKey; let usdcMint; let firstUserDriftClient: TestClient; let firstUserDriftClientUSDCAccount: PublicKey; let secondUserDriftClient: TestClient; let secondUserDriftClientWSOLAccount: PublicKey; let secondUserDriftClientUSDCAccount: PublicKey; const usdcAmount = new BN(10 * 10 ** 6); const largeUsdcAmount = new BN(10_000 * 10 ** 6); const solAmount = new BN(1 * 10 ** 9); let marketIndexes: number[]; let spotMarketIndexes: number[]; let oracleInfos: OracleInfo[]; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); await mockUserUSDCAccount(usdcMint, largeUsdcAmount, bankrunContextWrapper); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 30); marketIndexes = []; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solOracle, source: OracleSource.PYTH }]; admin = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await admin.initialize(usdcMint.publicKey, true); await admin.subscribe(); }); after(async () => { await admin.unsubscribe(); await eventSubscriber.unsubscribe(); await firstUserDriftClient.unsubscribe(); await secondUserDriftClient.unsubscribe(); }); it('Initialize USDC Market', async () => { const optimalUtilization = SPOT_MARKET_RATE_PRECISION.div( new BN(2) ).toNumber(); // 50% utilization const optimalRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(20)).toNumber(); // 2000% APR const maxRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(50)).toNumber(); // 5000% APR const initialAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const initialLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); await admin.initializeSpotMarket( usdcMint.publicKey, optimalUtilization, optimalRate, maxRate, PublicKey.default, OracleSource.QUOTE_ASSET, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight ); const txSig = await admin.updateWithdrawGuardThreshold( 0, new BN(10 ** 10).mul(QUOTE_PRECISION) ); bankrunContextWrapper.printTxLogs(txSig); await admin.fetchAccounts(); const spotMarket = await admin.getSpotMarketAccount(0); assert(spotMarket.marketIndex === 0); assert(spotMarket.optimalUtilization === optimalUtilization); assert(spotMarket.optimalBorrowRate === optimalRate); assert(spotMarket.maxBorrowRate === maxRate); assert( spotMarket.cumulativeBorrowInterest.eq( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); assert( spotMarket.cumulativeDepositInterest.eq( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); assert(spotMarket.initialAssetWeight === initialAssetWeight); assert(spotMarket.maintenanceAssetWeight === maintenanceAssetWeight); assert(spotMarket.initialLiabilityWeight === initialLiabilityWeight); assert(spotMarket.maintenanceAssetWeight === maintenanceAssetWeight); assert(admin.getStateAccount().numberOfSpotMarkets === 1); }); it('Initialize SOL Market', async () => { const optimalUtilization = SPOT_MARKET_RATE_PRECISION.div( new BN(2) ).toNumber(); // 50% utilization const optimalRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(20)).toNumber(); // 2000% APR const maxRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(50)).toNumber(); // 5000% APR const initialAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(8)) .div(new BN(10)) .toNumber(); const maintenanceAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(9)) .div(new BN(10)) .toNumber(); const initialLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(12)) .div(new BN(10)) .toNumber(); const maintenanceLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.mul( new BN(11) ) .div(new BN(10)) .toNumber(); await admin.initializeSpotMarket( NATIVE_MINT, optimalUtilization, optimalRate, maxRate, solOracle, OracleSource.PYTH, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight ); const txSig = await admin.updateWithdrawGuardThreshold( 1, new BN(10 ** 10).mul(QUOTE_PRECISION) ); bankrunContextWrapper.printTxLogs(txSig); await admin.fetchAccounts(); const spotMarket = await admin.getSpotMarketAccount(1); assert(spotMarket.marketIndex === 1); assert(spotMarket.optimalUtilization === optimalUtilization); assert(spotMarket.optimalBorrowRate === optimalRate); assert(spotMarket.maxBorrowRate === maxRate); assert( spotMarket.cumulativeBorrowInterest.eq( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); assert( spotMarket.cumulativeDepositInterest.eq( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); assert(spotMarket.initialAssetWeight === initialAssetWeight); assert(spotMarket.maintenanceAssetWeight === maintenanceAssetWeight); assert(spotMarket.initialLiabilityWeight === initialLiabilityWeight); assert(spotMarket.maintenanceAssetWeight === maintenanceAssetWeight); console.log(spotMarket.historicalOracleData); assert(spotMarket.historicalOracleData.lastOraclePriceTwapTs.eq(ZERO)); assert( spotMarket.historicalOracleData.lastOraclePrice.eq( new BN(30 * PRICE_PRECISION.toNumber()) ) ); assert( spotMarket.historicalOracleData.lastOraclePriceTwap.eq( new BN(30 * PRICE_PRECISION.toNumber()) ) ); assert( spotMarket.historicalOracleData.lastOraclePriceTwap5Min.eq( new BN(30 * PRICE_PRECISION.toNumber()) ) ); assert(admin.getStateAccount().numberOfSpotMarkets === 2); }); it('First User Deposit USDC', async () => { [firstUserDriftClient, firstUserDriftClientUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); const marketIndex = 0; await sleep(100); await firstUserDriftClient.fetchAccounts(); const txSig = await firstUserDriftClient.deposit( usdcAmount, marketIndex, firstUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); const spotMarket = await admin.getSpotMarketAccount(marketIndex); assert( spotMarket.depositBalance.eq( new BN(10 * SPOT_MARKET_BALANCE_PRECISION.toNumber()) ) ); const vaultAmount = new BN( ( await bankrunContextWrapper.connection.getTokenAccount(spotMarket.vault) ).amount.toString() ); assert(vaultAmount.eq(usdcAmount)); const expectedBalance = getBalance( usdcAmount, spotMarket, SpotBalanceType.DEPOSIT ); const spotPosition = firstUserDriftClient.getUserAccount().spotPositions[0]; assert(isVariant(spotPosition.balanceType, 'deposit')); assert(spotPosition.scaledBalance.eq(expectedBalance)); assert(firstUserDriftClient.getUserAccount().totalDeposits.eq(usdcAmount)); }); it('Second User Deposit SOL', async () => { [ secondUserDriftClient, secondUserDriftClientWSOLAccount, secondUserDriftClientUSDCAccount, ] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount, ZERO, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); const marketIndex = 1; const txSig = await secondUserDriftClient.deposit( solAmount, marketIndex, secondUserDriftClientWSOLAccount ); bankrunContextWrapper.printTxLogs(txSig); const spotMarket = await admin.getSpotMarketAccount(marketIndex); assert(spotMarket.depositBalance.eq(SPOT_MARKET_BALANCE_PRECISION)); console.log(spotMarket.historicalOracleData); assert(spotMarket.historicalOracleData.lastOraclePriceTwapTs.gt(ZERO)); assert( spotMarket.historicalOracleData.lastOraclePrice.eq( new BN(30 * PRICE_PRECISION.toNumber()) ) ); assert( spotMarket.historicalOracleData.lastOraclePriceTwap.eq( new BN(30 * PRICE_PRECISION.toNumber()) ) ); assert( spotMarket.historicalOracleData.lastOraclePriceTwap5Min.eq( new BN(30 * PRICE_PRECISION.toNumber()) ) ); const vaultAmount = new BN( ( await bankrunContextWrapper.connection.getTokenAccount(spotMarket.vault) ).amount.toString() ); assert(vaultAmount.eq(solAmount)); const expectedBalance = getBalance( solAmount, spotMarket, SpotBalanceType.DEPOSIT ); const spotPosition = secondUserDriftClient.getUserAccount().spotPositions[1]; assert(isVariant(spotPosition.balanceType, 'deposit')); assert(spotPosition.scaledBalance.eq(expectedBalance)); assert( secondUserDriftClient .getUserAccount() .totalDeposits.eq(new BN(30).mul(PRICE_PRECISION)) ); }); it('Second User Withdraw First half USDC', async () => { const marketIndex = 0; const withdrawAmount = usdcAmount.div(new BN(2)); const txSig = await secondUserDriftClient.withdraw( withdrawAmount, marketIndex, secondUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); const spotMarket = await admin.getSpotMarketAccount(marketIndex); const expectedBorrowBalance = new BN(5000000001); assert(spotMarket.borrowBalance.eq(expectedBorrowBalance)); const vaultAmount = new BN( ( await bankrunContextWrapper.connection.getTokenAccount(spotMarket.vault) ).amount.toString() ); const expectedVaultAmount = usdcAmount.sub(withdrawAmount); assert(vaultAmount.eq(expectedVaultAmount)); const expectedBalance = getBalance( withdrawAmount, spotMarket, SpotBalanceType.BORROW ); const spotPosition = secondUserDriftClient.getUserAccount().spotPositions[0]; assert(isVariant(spotPosition.balanceType, 'borrow')); assert(spotPosition.scaledBalance.eq(expectedBalance)); const actualAmountWithdrawn = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientUSDCAccount ) ).amount.toString() ); assert(withdrawAmount.eq(actualAmountWithdrawn)); assert( secondUserDriftClient.getUserAccount().totalWithdraws.eq(withdrawAmount) ); }); it('Update Cumulative Interest with 50% utilization', async () => { const usdcmarketIndex = 0; const oldSpotMarketAccount = firstUserDriftClient.getSpotMarketAccount(usdcmarketIndex); await sleep(5000); const txSig = await firstUserDriftClient.updateSpotMarketCumulativeInterest( usdcmarketIndex ); bankrunContextWrapper.printTxLogs(txSig); await firstUserDriftClient.fetchAccounts(); const newSpotMarketAccount = firstUserDriftClient.getSpotMarketAccount(usdcmarketIndex); const expectedInterestAccumulated = calculateInterestAccumulated( oldSpotMarketAccount, newSpotMarketAccount.lastInterestTs ); const expectedCumulativeDepositInterest = oldSpotMarketAccount.cumulativeDepositInterest.add( expectedInterestAccumulated.depositInterest ); const expectedCumulativeBorrowInterest = oldSpotMarketAccount.cumulativeBorrowInterest.add( expectedInterestAccumulated.borrowInterest ); assert( newSpotMarketAccount.cumulativeDepositInterest.eq( expectedCumulativeDepositInterest ) ); assert( newSpotMarketAccount.cumulativeBorrowInterest.eq( expectedCumulativeBorrowInterest ) ); }); it('Second User Withdraw second half USDC', async () => { const marketIndex = 0; let spotMarketAccount = secondUserDriftClient.getSpotMarketAccount(marketIndex); const spotMarketDepositTokenAmountBefore = getTokenAmount( spotMarketAccount.depositBalance, spotMarketAccount, SpotBalanceType.DEPOSIT ); const spotMarketBorrowTokenAmountBefore = getTokenAmount( spotMarketAccount.borrowBalance, spotMarketAccount, SpotBalanceType.BORROW ); const spotMarketBorrowBalanceBefore = spotMarketAccount.borrowBalance; const userUSDCAmountBefore = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientUSDCAccount ) ).amount.toString() ); const spotPositionBefore = secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; const withdrawAmount = spotMarketDepositTokenAmountBefore .sub(spotMarketBorrowTokenAmountBefore) .sub(ONE); const txSig = await secondUserDriftClient.withdraw( withdrawAmount, marketIndex, secondUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); spotMarketAccount = secondUserDriftClient.getSpotMarketAccount(marketIndex); const increaseInspotPosition = getBalance( withdrawAmount, spotMarketAccount, SpotBalanceType.BORROW ); const expectedspotPosition = spotPositionBefore.add(increaseInspotPosition); console.log('withdrawAmount:', withdrawAmount.toString()); assert( secondUserDriftClient .getSpotPosition(marketIndex) .scaledBalance.eq(expectedspotPosition) ); const expectedUserUSDCAmount = userUSDCAmountBefore.add(withdrawAmount); const userUSDCAmountAfter = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientUSDCAccount ) ).amount.toString() ); assert(expectedUserUSDCAmount.eq(userUSDCAmountAfter)); assert( secondUserDriftClient .getUserAccount() .totalWithdraws.eq(userUSDCAmountAfter) ); const expectedSpotMarketBorrowBalance = spotMarketBorrowBalanceBefore.add( increaseInspotPosition ); console.assert( spotMarketAccount.borrowBalance.eq(expectedSpotMarketBorrowBalance) ); const expectedVaultBalance = usdcAmount.sub(expectedUserUSDCAmount); const vaultUSDCAmountAfter = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( spotMarketAccount.vault ) ).amount.toString() ); assert(expectedVaultBalance.eq(vaultUSDCAmountAfter)); const spotMarketDepositTokenAmountAfter = getTokenAmount( spotMarketAccount.depositBalance, spotMarketAccount, SpotBalanceType.DEPOSIT ); const spotMarketBorrowTokenAmountAfter = getTokenAmount( spotMarketAccount.borrowBalance, spotMarketAccount, SpotBalanceType.BORROW ); // TODO console.log( spotMarketDepositTokenAmountAfter.toString(), spotMarketBorrowTokenAmountAfter.toString() ); assert( spotMarketDepositTokenAmountAfter .sub(spotMarketBorrowTokenAmountAfter) .lte(ONE) ); }); it('Update Cumulative Interest with 100% utilization', async () => { const usdcmarketIndex = 0; const oldSpotMarketAccount = firstUserDriftClient.getSpotMarketAccount(usdcmarketIndex); await sleep(5000); const txSig = await firstUserDriftClient.updateSpotMarketCumulativeInterest( usdcmarketIndex ); bankrunContextWrapper.printTxLogs(txSig); await firstUserDriftClient.fetchAccounts(); const newSpotMarketAccount = firstUserDriftClient.getSpotMarketAccount(usdcmarketIndex); const expectedInterestAccumulated = calculateInterestAccumulated( oldSpotMarketAccount, newSpotMarketAccount.lastInterestTs ); const expectedCumulativeDepositInterest = oldSpotMarketAccount.cumulativeDepositInterest.add( expectedInterestAccumulated.depositInterest ); const expectedCumulativeBorrowInterest = oldSpotMarketAccount.cumulativeBorrowInterest.add( expectedInterestAccumulated.borrowInterest ); assert( newSpotMarketAccount.cumulativeDepositInterest.eq( expectedCumulativeDepositInterest ) ); console.log( newSpotMarketAccount.cumulativeBorrowInterest.sub(ONE).toString(), expectedCumulativeBorrowInterest.toString() ); // inconcistent time leads to slight differences over runs? assert( newSpotMarketAccount.cumulativeBorrowInterest .sub(ONE) .eq(expectedCumulativeBorrowInterest) || newSpotMarketAccount.cumulativeBorrowInterest.eq( expectedCumulativeBorrowInterest ) ); }); it('Flip second user borrow to deposit', async () => { const marketIndex = 0; const mintAmount = new BN(2 * 10 ** 6); // $2 const userUSDCAmountBefore = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientUSDCAccount ) ).amount.toString() ); await mintUSDCToUser( usdcMint, secondUserDriftClientUSDCAccount, mintAmount, bankrunContextWrapper ); const userBorrowBalanceBefore = secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; const spotMarketDepositBalanceBefore = secondUserDriftClient.getSpotMarketAccount(marketIndex).depositBalance; const depositAmount = userUSDCAmountBefore.add(mintAmount.div(new BN(2))); const txSig = await secondUserDriftClient.deposit( depositAmount, marketIndex, secondUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); await secondUserDriftClient.fetchAccounts(); const spotMarketAccount = secondUserDriftClient.getSpotMarketAccount(marketIndex); const borrowToPayOff = getTokenAmount( userBorrowBalanceBefore, spotMarketAccount, SpotBalanceType.BORROW ); const newDepositTokenAmount = depositAmount.sub(borrowToPayOff); const expectedUserBalance = getBalance( newDepositTokenAmount, spotMarketAccount, SpotBalanceType.DEPOSIT ); const userBalanceAfter = secondUserDriftClient.getSpotPosition(marketIndex); console.log( expectedUserBalance.toString(), userBalanceAfter.scaledBalance.toString() ); assert(expectedUserBalance.eq(userBalanceAfter.scaledBalance)); assert(isVariant(userBalanceAfter.balanceType, 'deposit')); const expectedSpotMarketDepositBalance = spotMarketDepositBalanceBefore.add(expectedUserBalance); console.log( spotMarketAccount.depositBalance.toString(), expectedSpotMarketDepositBalance.toString() ); assert( spotMarketAccount.depositBalance.eq(expectedSpotMarketDepositBalance) ); assert(spotMarketAccount.borrowBalance.eq(ZERO)); }); it('Flip second user deposit to borrow', async () => { const marketIndex = 0; const spotMarketAccountBefore = secondUserDriftClient.getSpotMarketAccount(marketIndex); const userDepositBalanceBefore = secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; const spotMarketDepositBalanceBefore = secondUserDriftClient.getSpotMarketAccount(marketIndex).depositBalance; const userDepositokenAmountBefore = getTokenAmount( userDepositBalanceBefore, spotMarketAccountBefore, SpotBalanceType.DEPOSIT ); const borrowAmount = userDepositokenAmountBefore.add(new BN(1 * 10 ** 6)); const txSig = await secondUserDriftClient.withdraw( borrowAmount, marketIndex, secondUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); await secondUserDriftClient.fetchAccounts(); const spotMarketAccount = secondUserDriftClient.getSpotMarketAccount(marketIndex); const depositToWithdrawAgainst = getTokenAmount( userDepositBalanceBefore, spotMarketAccount, SpotBalanceType.DEPOSIT ); const newBorrowTokenAmount = borrowAmount.sub(depositToWithdrawAgainst); const expectedUserBalance = getBalance( newBorrowTokenAmount, spotMarketAccount, SpotBalanceType.BORROW ); const userBalanceAfter = secondUserDriftClient.getSpotPosition(marketIndex); assert(expectedUserBalance.eq(userBalanceAfter.scaledBalance)); assert(isVariant(userBalanceAfter.balanceType, 'borrow')); const expectedSpotMarketDepositBalance = spotMarketDepositBalanceBefore.sub( userDepositBalanceBefore ); assert( spotMarketAccount.depositBalance.eq(expectedSpotMarketDepositBalance) ); assert(spotMarketAccount.borrowBalance.eq(expectedUserBalance)); }); it('Second user reduce only pay down borrow', async () => { const marketIndex = 0; const userUSDCAmountBefore = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientUSDCAccount ) ).amount.toString() ); const currentUserBorrowBalance = secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; const spotMarketDepositBalanceBefore = secondUserDriftClient.getSpotMarketAccount(marketIndex).depositBalance; const depositAmount = userUSDCAmountBefore.mul(new BN(100000)); // huge number const txSig = await secondUserDriftClient.deposit( depositAmount, marketIndex, secondUserDriftClientUSDCAccount, undefined, true ); bankrunContextWrapper.printTxLogs(txSig); const spotMarketAccountAfter = secondUserDriftClient.getSpotMarketAccount(marketIndex); const borrowToPayBack = getTokenAmount( currentUserBorrowBalance, spotMarketAccountAfter, SpotBalanceType.BORROW ); const userUSDCAmountAfter = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientUSDCAccount ) ).amount.toString() ); const expectedUserUSDCAmount = userUSDCAmountBefore.sub(borrowToPayBack); console.log( expectedUserUSDCAmount.toString(), userUSDCAmountAfter.toString() ); assert(expectedUserUSDCAmount.eq(userUSDCAmountAfter)); const userBalanceAfter = secondUserDriftClient.getSpotPosition(marketIndex); assert(userBalanceAfter.scaledBalance.eq(ZERO)); assert(spotMarketAccountAfter.borrowBalance.eq(ZERO)); assert( spotMarketAccountAfter.depositBalance.eq(spotMarketDepositBalanceBefore) ); }); it('Second user reduce only withdraw deposit', async () => { const marketIndex = 1; const userWSOLAmountBefore = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientWSOLAccount ) ).amount.toString() ); const currentUserDepositBalance = secondUserDriftClient.getSpotPosition(marketIndex).scaledBalance; const withdrawAmount = new BN(LAMPORTS_PER_SOL * 100); const txSig = await secondUserDriftClient.withdraw( withdrawAmount, marketIndex, secondUserDriftClientWSOLAccount, true ); bankrunContextWrapper.printTxLogs(txSig); const spotMarketAccountAfter = secondUserDriftClient.getSpotMarketAccount(marketIndex); const amountAbleToWithdraw = getTokenAmount( currentUserDepositBalance, spotMarketAccountAfter, SpotBalanceType.DEPOSIT ); const userWSOLAmountAfter = new BN( ( await bankrunContextWrapper.connection.getTokenAccount( secondUserDriftClientWSOLAccount ) ).amount.toString() ); const expectedUserWSOLAmount = amountAbleToWithdraw.sub(userWSOLAmountBefore); console.log(expectedUserWSOLAmount.toString()); console.log(userWSOLAmountAfter.toString()); assert(expectedUserWSOLAmount.eq(userWSOLAmountAfter)); const userBalanceAfter = secondUserDriftClient.getSpotPosition(marketIndex); assert(userBalanceAfter.scaledBalance.eq(ZERO)); }); it('Third user deposits when cumulative interest off init value', async () => { // rounding on spot market balance <-> token conversions can lead to tiny epislon of loss on deposits const [ thirdUserDriftClient, _thirdUserDriftClientWSOLAccount, thirdUserDriftClientUSDCAccount, ] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount, largeUsdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); const marketIndex = 0; await thirdUserDriftClient.fetchAccounts(); const spotPosition = thirdUserDriftClient.getSpotPosition(marketIndex); console.log(spotPosition); assert(spotPosition.scaledBalance.eq(ZERO)); const spotMarket = thirdUserDriftClient.getSpotMarketAccount(marketIndex); console.log(spotMarket.cumulativeDepositInterest.toString()); console.log(spotMarket.cumulativeBorrowInterest.toString()); assert( spotMarket.cumulativeDepositInterest.gt( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); assert( spotMarket.cumulativeBorrowInterest.gt( SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION ) ); console.log('usdcAmount:', largeUsdcAmount.toString(), 'user deposits'); const txSig = await thirdUserDriftClient.deposit( largeUsdcAmount, marketIndex, thirdUserDriftClientUSDCAccount ); bankrunContextWrapper.printTxLogs(txSig); const spotPositionAfter = thirdUserDriftClient.getSpotPosition(marketIndex); const tokenAmount = getTokenAmount( spotPositionAfter.scaledBalance, spotMarket, spotPositionAfter.balanceType ); console.log('tokenAmount:', tokenAmount.toString()); assert( tokenAmount.gte(largeUsdcAmount.sub(QUOTE_PRECISION.div(new BN(100)))) ); // didnt lose more than a penny assert(tokenAmount.lt(largeUsdcAmount)); // lose a lil bit await thirdUserDriftClient.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/openbookTest.ts
import { assert } from 'chai'; import * as anchor from '@coral-xyz/anchor'; import { Program, Idl, BN } from '@coral-xyz/anchor'; import { OracleSource, OrderType, PositionDirection, PublicKey, TestClient, } from '../sdk/src'; import openbookIDL from '../sdk/src/idl/openbook.json'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; import { createOpenOrdersAccount, createOpenOrdersAccountV2, OPENBOOK, OrderType as ObOrderType, placeOrder, SelfTradeBehavior, Side, } from './openbookHelpers'; import { createWSolTokenAccountForUser, initializeQuoteSpotMarket, initializeSolSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } from './testHelpers'; import { createBidsAsksEventHeap, createMarket } from './openbookHelpers'; import { Keypair } from '@solana/web3.js'; import { LAMPORTS_PRECISION, PRICE_PRECISION } from '../sdk/src'; import { WRAPPED_SOL_MINT } from '../sdk/src'; import { ZERO } from '../sdk'; describe('openbook v2', () => { const chProgram = anchor.workspace.Drift as Program; const openbookProgram = new Program(openbookIDL as Idl, OPENBOOK); let driftClient: TestClient; let fillerDriftClient: TestClient; const fillerKeypair = Keypair.generate(); let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; const solSpotMarketIndex = 1; const bids = Keypair.generate(); const asks = Keypair.generate(); const eventHeap = Keypair.generate(); const market = Keypair.generate(); let usdcMint: Keypair; const usdcAmount = new anchor.BN(200 * 1_000 * 10 ** 6); const solAmount = new anchor.BN(200 * 1_000 * 10 ** 9); let userUsdcAccount: Keypair; let userWSolAccount: PublicKey; let _marketAuthority: PublicKey; let marketBaseVault: PublicKey; let marketQuoteVault: PublicKey; let openOrdersAccount: PublicKey; let openOrdersIndexer: PublicKey; const openOrdersAccounts: PublicKey[] = []; before(async () => { const context = await startAnchor( '', [ { name: 'openbook', programId: OPENBOOK, }, ], [] ); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); const solOracle = await mockOracleNoProgram(bankrunContextWrapper, 100); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUsdcAccount = await mockUserUSDCAccount( usdcMint, // @ts-ignore usdcAmount.muln(2), bankrunContextWrapper ); userWSolAccount = await createWSolTokenAccountForUser( bankrunContextWrapper, // @ts-ignore bankrunContextWrapper.provider.wallet, solAmount ); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0, 1], subAccountIds: [], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await createBidsAsksEventHeap(bankrunContextWrapper, bids, asks, eventHeap); const quoteSizeLot = new BN(1); const baseSizeLot = new BN(100000); [_marketAuthority, marketBaseVault, marketQuoteVault] = await createMarket( bankrunContextWrapper, openbookProgram, market, WRAPPED_SOL_MINT, usdcMint.publicKey, bids.publicKey, asks.publicKey, eventHeap.publicKey, quoteSizeLot, baseSizeLot ); [openOrdersIndexer, openOrdersAccount] = await createOpenOrdersAccount( bankrunContextWrapper, openbookProgram, market.publicKey ); const names = [ 'Bob', 'Marley', 'Nicky', 'Minaj', 'Bad', 'Bunny', 'Luis', 'Miguel', 'Anita', 'Soul', 'Bronco', 'Marilina', 'Rytmus', 'Separ', 'Meiko', 'Kaji', 'Karol', 'G', 'Ricky', 'Martin', ]; let index = 1; for (const name of names) { index += 1; openOrdersAccounts.push( await createOpenOrdersAccountV2( bankrunContextWrapper, openbookProgram, market.publicKey, openOrdersIndexer, name, index ) ); } console.log(`OpenOrdersAccounts: ${openOrdersAccounts}`); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await initializeSolSpotMarket(driftClient, solOracle); await driftClient.updateSpotMarketStepSizeAndTickSize( 1, baseSizeLot, quoteSizeLot ); await driftClient.updateSpotMarketOrdersEnabled(1, true); await driftClient.initializeUserAccountAndDepositCollateral( // @ts-ignore usdcAmount, userUsdcAccount.publicKey ); await driftClient.addUser(0); // @ts-ignore // await driftClient.deposit(solAmount, 1, userWSolAccount.publicKey); fillerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new anchor.Wallet(fillerKeypair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0, 1], subAccountIds: [], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClient.subscribe(); await bankrunContextWrapper.fundKeypair(fillerKeypair, 10 * 10 ** 9); await fillerDriftClient.initializeUserAccount(); await fillerDriftClient.addUser(0); }); after(async () => { await driftClient.unsubscribe(); await fillerDriftClient.unsubscribe(); }); it('add market', async () => { await driftClient.initializeOpenbookV2FulfillmentConfig( solSpotMarketIndex, market.publicKey ); }); it('fill ask and bids', async () => { for (let i = 0; i < 10; i++) { const ooa = openOrdersAccounts[i]; for (let j = 0; j < 15; j++) { await placeOrder( bankrunContextWrapper, openbookProgram, ooa, openOrdersIndexer, market.publicKey, bids.publicKey, asks.publicKey, eventHeap.publicKey, marketBaseVault, userWSolAccount, { side: Side.ASK, priceLots: new anchor.BN(10000 + (j + 1) * 300), maxBaseLots: new anchor.BN(1_000_000_000), maxQuoteLotsIncludingFees: new anchor.BN( 100_000_000 + (j + 1) * 3_000_000 ), clientOrderId: new anchor.BN(0), orderType: ObOrderType.LIMIT, expiryTimestamp: new anchor.BN(0), selfTradeBehavior: SelfTradeBehavior.DECREMENT_TAKE, limit: new anchor.BN(20), } ); } } for (let i = 10; i < 20; i++) { const ooa = openOrdersAccounts[i]; for (let j = 0; j < 15; j++) { console.log('BIDING'); await placeOrder( bankrunContextWrapper, openbookProgram, ooa, openOrdersIndexer, market.publicKey, bids.publicKey, asks.publicKey, eventHeap.publicKey, marketQuoteVault, userUsdcAccount.publicKey, { side: Side.BID, priceLots: new anchor.BN(10000 - (j + 1) * 300), maxBaseLots: new anchor.BN(1_000_000_000), maxQuoteLotsIncludingFees: new anchor.BN( 100_000_000 - (j + 1) * 3_000_000 ), clientOrderId: new anchor.BN(0), orderType: ObOrderType.LIMIT, expiryTimestamp: new anchor.BN(0), selfTradeBehavior: SelfTradeBehavior.DECREMENT_TAKE, limit: new anchor.BN(20), } ); } } }); it('fill long', async () => { const quoteTokenAmountBefore = driftClient.getTokenAmount(0); const baseTokenAmountBefore = driftClient.getTokenAmount(1); console.log(`quoteTokenAmountBefore ${quoteTokenAmountBefore.toString()}`); console.log(`baseTokenAmountBefore ${baseTokenAmountBefore.toString()}`); await placeOrder( bankrunContextWrapper, openbookProgram, openOrdersAccount, openOrdersIndexer, market.publicKey, bids.publicKey, asks.publicKey, eventHeap.publicKey, marketBaseVault, userWSolAccount, { side: Side.ASK, priceLots: new anchor.BN(10000), maxBaseLots: new anchor.BN(1_000_000_000), maxQuoteLotsIncludingFees: new anchor.BN(100_000_000), clientOrderId: new anchor.BN(0), orderType: ObOrderType.LIMIT, expiryTimestamp: new anchor.BN(0), selfTradeBehavior: SelfTradeBehavior.DECREMENT_TAKE, limit: new anchor.BN(10), } ); await driftClient.placeSpotOrder({ orderType: OrderType.LIMIT, marketIndex: 1, // @ts-ignore baseAssetAmount: driftClient.convertToSpotPrecision(1, 1), direction: PositionDirection.LONG, price: PRICE_PRECISION.muln(100), }); const fulfillmentConfig = await driftClient.getOpenbookV2FulfillmentConfig( market.publicKey ); fulfillmentConfig.remainingAccounts = [ openOrdersAccount, openOrdersAccounts[2], openOrdersAccounts[13], ]; const userAccount = driftClient.getUserAccount(); const order = userAccount.orders.filter( (order) => order.marketIndex == 1 )[0]; await fillerDriftClient.fillSpotOrder( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), order, fulfillmentConfig ); await driftClient.fetchAccounts(); const quoteTokenAmountAfter = driftClient.getTokenAmount(0); const baseTokenAmountAfter = driftClient.getTokenAmount(1); const openOrdersAccountInfo = await bankrunContextWrapper.connection.getAccountInfo(openOrdersAccount); const openOrdersAccountParsedData = await openbookProgram.account.openOrdersAccount.coder.accounts.decode( 'OpenOrdersAccount', openOrdersAccountInfo.data ); assert( openOrdersAccountParsedData.position.quoteFreeNative.eq(new BN(100000000)) ); console.log(`quoteTokenAmountAfter ${quoteTokenAmountAfter.toString()}`); console.log(`baseTokenAmountAfter ${baseTokenAmountAfter.toString()}`); assert(baseTokenAmountAfter.eq(LAMPORTS_PRECISION)); assert(quoteTokenAmountAfter.eq(new BN('199899899999'))); }); it('fill short', async () => { await placeOrder( bankrunContextWrapper, openbookProgram, openOrdersAccount, openOrdersIndexer, market.publicKey, bids.publicKey, asks.publicKey, eventHeap.publicKey, marketQuoteVault, userUsdcAccount.publicKey, { side: Side.BID, priceLots: new anchor.BN(10000), maxBaseLots: new anchor.BN(1_000_000_000), maxQuoteLotsIncludingFees: new anchor.BN(100_000_000), clientOrderId: new anchor.BN(0), orderType: ObOrderType.LIMIT, expiryTimestamp: new anchor.BN(0), selfTradeBehavior: SelfTradeBehavior.DECREMENT_TAKE, limit: new anchor.BN(10), } ); await driftClient.placeSpotOrder({ orderType: OrderType.LIMIT, marketIndex: 1, // @ts-ignore baseAssetAmount: driftClient.convertToSpotPrecision(1, 1), direction: PositionDirection.SHORT, price: PRICE_PRECISION.muln(100), }); const fulfillmentConfig = await driftClient.getOpenbookV2FulfillmentConfig( market.publicKey ); fulfillmentConfig.remainingAccounts = [ openOrdersAccount, openOrdersAccounts[1], openOrdersAccounts[12], ]; const userAccount = driftClient.getUserAccount(); const order = userAccount.orders.filter( (order) => order.marketIndex == 1 )[0]; await fillerDriftClient.fillSpotOrder( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), order, fulfillmentConfig ); await driftClient.fetchAccounts(); const quoteTokenAmountAfter = driftClient.getTokenAmount(0); const baseTokenAmountAfter = driftClient.getTokenAmount(1); console.log(`quoteTokenAmountAfter ${quoteTokenAmountAfter.toString()}`); console.log(`baseTokenAmountAfter ${baseTokenAmountAfter.toString()}`); assert(baseTokenAmountAfter.eq(ZERO)); assert(quoteTokenAmountAfter.eq(new BN('199999799999'))); const openOrdersAccountInfo = await bankrunContextWrapper.connection.getAccountInfo(openOrdersAccount); const openOrdersAccountParsedData = await openbookProgram.account.openOrdersAccount.coder.accounts.decode( 'OpenOrdersAccount', openOrdersAccountInfo.data ); assert(openOrdersAccountParsedData.position.baseFreeNative.eq(new BN(1e9))); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/liquidateSpotSocialLoss.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { PublicKey } from '@solana/web3.js'; import { TestClient, BN, OracleSource, ZERO, EventSubscriber, PRICE_PRECISION, getTokenAmount, SpotBalanceType, LIQUIDATION_PCT_PRECISION, } from '../sdk/src'; import { mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, initializeQuoteSpotMarket, createUserWithUSDCAndWSOLAccount, createWSolTokenAccountForUser, initializeSolSpotMarket, } from './testHelpers'; import { isVariant, UserStatus, PERCENTAGE_PRECISION } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('liquidate spot w/ social loss', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; let userWSOLAccount; let liquidatorDriftClient: TestClient; let liquidatorDriftClientWSOLAccount: PublicKey; let solOracle: PublicKey; const usdcAmount = new BN(100 * 10 ** 6); let _throwaway: PublicKey; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); userWSOLAccount = await createWSolTokenAccountForUser( bankrunContextWrapper, // @ts-ignore bankrunContextWrapper.provider.wallet, ZERO ); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 100); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [], spotMarketIndexes: [0, 1], subAccountIds: [], oracleInfos: [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection, chProgram ); await eventSubscriber.subscribe(); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await driftClient.updateInitialPctToLiquidate( LIQUIDATION_PCT_PRECISION.toNumber() ); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await initializeSolSpotMarket(driftClient, solOracle); const oracleGuardrails = await driftClient.getStateAccount() .oracleGuardRails; oracleGuardrails.priceDivergence.oracleTwap5MinPercentDivergence = new BN( 100 ).mul(PERCENTAGE_PRECISION); await driftClient.updateOracleGuardRails(oracleGuardrails); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const solAmount = new BN(10 * 10 ** 9); [liquidatorDriftClient, liquidatorDriftClientWSOLAccount, _throwaway] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount, usdcAmount, [], [0, 1], [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], bulkAccountLoader ); const marketIndex = 1; await liquidatorDriftClient.deposit( solAmount, marketIndex, liquidatorDriftClientWSOLAccount ); const solBorrow = new BN(5 * 10 ** 8); await driftClient.withdraw(solBorrow, 1, userWSOLAccount); }); after(async () => { await driftClient.unsubscribe(); await liquidatorDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('liquidate', async () => { await setFeedPriceNoProgram(bankrunContextWrapper, 200, solOracle); const spotMarketBefore = driftClient.getSpotMarketAccount(0); const spotMarket1Before = driftClient.getSpotMarketAccount(1); const txSig = await liquidatorDriftClient.liquidateSpot( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0, 1, new BN(6 * 10 ** 8) ); const computeUnits = bankrunContextWrapper.connection.findComputeUnitConsumption(txSig); console.log('compute units', computeUnits); bankrunContextWrapper.connection.printTxLogs(txSig); console.log(driftClient.getUserAccount().status); // assert(driftClient.getUserAccount().isBeingLiquidated); assert(driftClient.getUserAccount().status === UserStatus.BANKRUPT); assert(driftClient.getUserAccount().nextLiquidationId === 2); // assert( // driftClient.getUserAccount().spotPositions[0].scaledBalance.eq(ZERO) // ); const liquidationRecord = eventSubscriber.getEventsArray('LiquidationRecord')[0]; assert(liquidationRecord.liquidationId === 1); assert(isVariant(liquidationRecord.liquidationType, 'liquidateSpot')); assert(liquidationRecord.liquidateSpot.assetPrice.eq(PRICE_PRECISION)); assert(liquidationRecord.liquidateSpot.assetMarketIndex === 0); assert(liquidationRecord.liquidateSpot.assetTransfer.eq(new BN(100000000))); assert( liquidationRecord.liquidateSpot.liabilityPrice.eq( new BN(200).mul(PRICE_PRECISION) ) ); assert(liquidationRecord.liquidateSpot.liabilityMarketIndex === 1); assert( liquidationRecord.liquidateSpot.liabilityTransfer.eq(new BN(500000000)) ); console.log(liquidationRecord.liquidateSpot.ifFee.toString()); console.log(spotMarketBefore.liquidatorFee.toString()); console.log(spotMarketBefore.ifLiquidationFee.toString()); console.log( liquidationRecord.liquidateSpot.liabilityTransfer .div(new BN(100)) .toString() ); // if liq fee is 0 since user is bankrupt assert(liquidationRecord.liquidateSpot.ifFee.eq(new BN(0))); // if liquidator fee is non-zero, it should be equal to that assert( liquidationRecord.liquidateSpot.ifFee.eq( new BN(spotMarketBefore.liquidatorFee) ) ); // but it is zero assert(liquidationRecord.liquidateSpot.ifFee.eq(ZERO)); assert( new BN(5000000).eq( liquidationRecord.liquidateSpot.liabilityTransfer.div(new BN(100)) ) ); await driftClient.fetchAccounts(); const spotMarket = driftClient.getSpotMarketAccount(0); const spotMarket1 = driftClient.getSpotMarketAccount(1); console.log( 'usdc borrows in spotMarket:', getTokenAmount( spotMarketBefore.borrowBalance, spotMarketBefore, SpotBalanceType.BORROW ).toString(), '->', getTokenAmount( spotMarket.borrowBalance, spotMarket, SpotBalanceType.BORROW ).toString() ); console.log( 'usdc deposits in spotMarket:', getTokenAmount( spotMarketBefore.depositBalance, spotMarketBefore, SpotBalanceType.DEPOSIT ).toString(), '->', getTokenAmount( spotMarket.depositBalance, spotMarket, SpotBalanceType.DEPOSIT ).toString() ); console.log( 'sol borrows in spotMarket:', getTokenAmount( spotMarket1Before.borrowBalance, spotMarket1Before, SpotBalanceType.BORROW ).toString(), '->', getTokenAmount( spotMarket1.borrowBalance, spotMarket1, SpotBalanceType.BORROW ).toString() ); console.log( 'sol deposits in spotMarket:', getTokenAmount( spotMarket1Before.depositBalance, spotMarket1Before, SpotBalanceType.DEPOSIT ).toString(), '->', getTokenAmount( spotMarket1.depositBalance, spotMarket1, SpotBalanceType.DEPOSIT ).toString() ); const borrowDecrease = getTokenAmount( spotMarket1Before.borrowBalance, spotMarket1Before, SpotBalanceType.BORROW ).sub( getTokenAmount( spotMarket1.borrowBalance, spotMarket1, SpotBalanceType.BORROW ) ); const depositAmountBefore = getTokenAmount( spotMarket1Before.depositBalance, spotMarket1Before, SpotBalanceType.DEPOSIT ).sub(borrowDecrease); const currentDepositAmount = getTokenAmount( spotMarket1.depositBalance, spotMarket1, SpotBalanceType.DEPOSIT ); const interestOfUpdate = currentDepositAmount.sub(depositAmountBefore); console.log('interestOfUpdate:', interestOfUpdate.toString()); assert(interestOfUpdate.abs().lte(new BN(1))); }); it('resolve bankruptcy', async () => { const spotMarketBefore = driftClient.getSpotMarketAccount(0); const spotMarket1Before = driftClient.getSpotMarketAccount(1); const spotMarketCumulativeDepositInterestBefore = driftClient.getSpotMarketAccount(1).cumulativeDepositInterest; await liquidatorDriftClient.resolveSpotBankruptcy( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 1 ); await driftClient.fetchAccounts(); assert(driftClient.getUserAccount().status === 0); // assert(!driftClient.getUserAccount().isBankrupt); // assert( // driftClient.getUserAccount().spotPositions[1].scaledBalance.eq(ZERO) // ); const bankruptcyRecord = eventSubscriber.getEventsArray('LiquidationRecord')[0]; assert(isVariant(bankruptcyRecord.liquidationType, 'spotBankruptcy')); console.log(bankruptcyRecord.spotBankruptcy); assert(bankruptcyRecord.spotBankruptcy.marketIndex === 1); console.log(bankruptcyRecord.spotBankruptcy.borrowAmount.toString()); const spotMarket = driftClient.getSpotMarketAccount(1); assert( spotMarket.cumulativeDepositInterest.eq( spotMarketCumulativeDepositInterestBefore.sub( bankruptcyRecord.spotBankruptcy.cumulativeDepositInterestDelta ) ) ); await driftClient.fetchAccounts(); const spotMarket0 = driftClient.getSpotMarketAccount(0); const spotMarket1 = driftClient.getSpotMarketAccount(1); console.log( 'usdc borrows in spotMarket:', getTokenAmount( spotMarketBefore.borrowBalance, spotMarketBefore, SpotBalanceType.BORROW ).toString(), '->', getTokenAmount( spotMarket0.borrowBalance, spotMarket0, SpotBalanceType.BORROW ).toString() ); console.log( 'usdc deposits in spotMarket:', getTokenAmount( spotMarketBefore.depositBalance, spotMarketBefore, SpotBalanceType.DEPOSIT ).toString(), '->', getTokenAmount( spotMarket0.depositBalance, spotMarket0, SpotBalanceType.DEPOSIT ).toString() ); console.log( 'sol borrows in spotMarket:', getTokenAmount( spotMarket1Before.borrowBalance, spotMarket1Before, SpotBalanceType.BORROW ).toString(), '->', getTokenAmount( spotMarket1.borrowBalance, spotMarket1, SpotBalanceType.BORROW ).toString() ); console.log( 'sol deposits in spotMarket:', getTokenAmount( spotMarket1Before.depositBalance, spotMarket1Before, SpotBalanceType.DEPOSIT ).toString(), '->', getTokenAmount( spotMarket1.depositBalance, spotMarket1, SpotBalanceType.DEPOSIT ).toString() ); const netBalance0Before = spotMarketBefore.depositBalance.sub( spotMarketBefore.borrowBalance ); const netBalance0After = spotMarket0.depositBalance.sub( spotMarket0.borrowBalance ); console.log( 'netBalance usd:', netBalance0Before.toString(), '->', netBalance0After.toString() ); console.log( 'cumulative deposit interest usd:', spotMarketBefore.cumulativeDepositInterest.toString(), '->', spotMarket0.cumulativeDepositInterest.toString() ); console.log( 'cumulative borrow interest usd:', spotMarketBefore.cumulativeBorrowInterest.toString(), '->', spotMarket0.cumulativeBorrowInterest.toString() ); assert(netBalance0Before.eq(netBalance0After)); const netBalanceBefore = spotMarket1Before.depositBalance.sub( spotMarket1Before.borrowBalance ); const netBalanceAfter = spotMarket1.depositBalance.sub( spotMarket1.borrowBalance ); console.log( 'netBalance sol:', netBalanceBefore.toString(), '->', netBalanceAfter.toString() ); console.log( 'cumulative deposit interest sol:', spotMarket1Before.cumulativeDepositInterest.toString(), '->', spotMarket1.cumulativeDepositInterest.toString() ); console.log( 'cumulative borrow interest sol:', spotMarket1Before.cumulativeBorrowInterest.toString(), '->', spotMarket1.cumulativeBorrowInterest.toString() ); // no usd balance or interest changes assert( spotMarketBefore.cumulativeBorrowInterest.eq( spotMarket0.cumulativeBorrowInterest ) ); assert( spotMarketBefore.cumulativeDepositInterest.eq( spotMarket0.cumulativeDepositInterest ) ); assert(netBalance0Before.eq(netBalance0After)); // sol deposit interest goes down changes (due to social loss) assert( spotMarket1Before.cumulativeBorrowInterest.eq( spotMarket1.cumulativeBorrowInterest ) ); assert( spotMarket1Before.cumulativeDepositInterest.gt( spotMarket1.cumulativeDepositInterest ) ); // sol net balances goes up by socialized (borrow has been forgiven) assert(netBalanceBefore.lt(netBalanceAfter)); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/placeAndMakeSwiftPerp.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { ComputeBudgetProgram, Keypair, PublicKey, SendTransactionError, Transaction, TransactionMessage, VersionedTransaction, } from '@solana/web3.js'; import { BN, PRICE_PRECISION, TestClient, PositionDirection, User, Wallet, EventSubscriber, BASE_PRECISION, getLimitOrderParams, OracleSource, BulkAccountLoader, SwiftOrderParamsMessage, SwiftServerMessage, loadKeypair, getMarketOrderParams, MarketType, DriftClient, ANCHOR_TEST_SWIFT_ID, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracle, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpersLocalValidator'; import { PEG_PRECISION, PostOnlyParams } from '../sdk/src'; import dotenv from 'dotenv'; import { digest } from '../sdk/src/util/digest'; import { nanoid } from 'nanoid'; dotenv.config(); describe('place and make swift order', () => { if (!process.env.SWIFT_PRIVATE_KEY) { throw new Error('SWIFT_PRIVATE_KEY not set'); } if (!process.env.ANCHOR_WALLET) { throw new Error('ANCHOR_WALLET not set'); } const swiftKeypair = loadKeypair(process.env.SWIFT_PRIVATE_KEY); const provider = anchor.AnchorProvider.local(undefined, { commitment: 'confirmed', preflightCommitment: 'confirmed', }); const connection = provider.connection; anchor.setProvider(provider); const chProgram = anchor.workspace.Drift as Program; let makerDriftClient: TestClient; let makerDriftClientUser: User; //@ts-ignore const eventSubscriber = new EventSubscriber(connection, chProgram, { commitment: 'recent', }); eventSubscriber.subscribe(); const bulkAccountLoader = new BulkAccountLoader(connection, 'confirmed', 0); // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); let usdcMint; let userUSDCAccount; const usdcAmount = new BN(100 * 10 ** 6); let solUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const makerWallet = new Wallet(loadKeypair(process.env.ANCHOR_WALLET)); await provider.connection.requestAirdrop( provider.wallet.publicKey, 10 ** 9 ); await provider.connection.requestAirdrop(makerWallet.publicKey, 10 ** 9); usdcMint = await mockUSDCMint(provider); userUSDCAccount = await mockUserUSDCAccount(usdcMint, usdcAmount, provider); solUsd = await mockOracle(32.821); marketIndexes = [0]; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; makerDriftClient = new TestClient({ connection, //@ts-ignore wallet: new Wallet(loadKeypair(process.env.ANCHOR_WALLET)), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, swiftID: new PublicKey(ANCHOR_TEST_SWIFT_ID), }); await makerDriftClient.initialize(usdcMint.publicKey, true); await makerDriftClient.subscribe(); await initializeQuoteSpotMarket(makerDriftClient, usdcMint.publicKey); const periodicity = new BN(0); await makerDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(32 * PEG_PRECISION.toNumber()) ); await makerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); makerDriftClientUser = new User({ driftClient: makerDriftClient, userAccountPublicKey: await makerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClientUser.subscribe(); }); after(async () => { await makerDriftClient.unsubscribe(); await makerDriftClientUser.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('should succeed on correct sig', 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, }, swiftID: new PublicKey(ANCHOR_TEST_SWIFT_ID), }); 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, takeProfitOrderParams: null, stopLossOrderParams: null, }; await takerDriftClientUser.fetchAccounts(); const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount: BASE_PRECISION, price: new BN(33).mul(PRICE_PRECISION), userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, immediateOrCancel: true, }); const takerOrderParamsSig = takerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage ); const swiftServerMessage: SwiftServerMessage = { slot: new BN(await connection.getSlot()), swiftOrderSignature: takerOrderParamsSig, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const encodedSwiftServerMessage = makerDriftClient.encodeSwiftServerMessage(swiftServerMessage); const swiftSignature = makerDriftClient.signMessage( digest(encodedSwiftServerMessage), swiftKeypair ); let ixs = await makerDriftClient.getPlaceAndMakeSwiftPerpOrderIxs( encodedSwiftServerMessage, swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, swiftServerMessage.uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), }, makerOrderParams ); ixs = [ ComputeBudgetProgram.setComputeUnitLimit({ units: 10_000_000, }), ...ixs, ]; const message = new TransactionMessage({ instructions: ixs, payerKey: makerDriftClient.wallet.payer.publicKey, recentBlockhash: (await connection.getLatestBlockhash()).blockhash, }).compileToV0Message(); const tx = new VersionedTransaction(message); const simResult = await provider.connection.simulateTransaction(tx); console.log(simResult.value.logs); assert(simResult.value.err === null); const normalTx = new Transaction(); normalTx.add(...ixs); await makerDriftClient.sendTransaction(normalTx); }); it('should fail on bad order params sig', 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 DriftClient({ 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, 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, }); await takerDriftClientUser.fetchAccounts(); const makerOrderParams = getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, price: new BN(33).mul(PRICE_PRECISION), userOrderId: 1, postOnly: PostOnlyParams.MUST_POST_ONLY, immediateOrCancel: true, }); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, takeProfitOrderParams: null, subAccountId: 0, stopLossOrderParams: null, }; const takerOrderParamsSig = makerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage ); const swiftServerMessage: SwiftServerMessage = { slot: new BN(await connection.getSlot()), swiftOrderSignature: takerOrderParamsSig, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const encodedSwiftServerMessage = makerDriftClient.encodeSwiftServerMessage(swiftServerMessage); const swiftSignature = makerDriftClient.signMessage( digest(encodedSwiftServerMessage), swiftKeypair ); try { let ixs = await makerDriftClient.getPlaceAndMakeSwiftPerpOrderIxs( encodedSwiftServerMessage, swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, swiftServerMessage.uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), }, makerOrderParams ); ixs = [ ComputeBudgetProgram.setComputeUnitLimit({ units: 10_000_000, }), ...ixs, ]; await makerDriftClient.sendTransaction(new Transaction().add(...ixs)); assert.fail('Should have failed'); } catch (error) { assert.equal( error.transactionMessage, 'Transaction precompile verification failure InvalidAccountIndex' ); } }); it('should fail on swift impersonator', 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 = getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, 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, }); await takerDriftClientUser.fetchAccounts(); // Auth part begins const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, takeProfitOrderParams: null, stopLossOrderParams: null, }; const takerOrderParamsSig = takerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage ); const swiftServerMessage: SwiftServerMessage = { slot: new BN(await connection.getSlot()), swiftOrderSignature: takerOrderParamsSig, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const encodedSwiftServerMessage = takerDriftClient.encodeSwiftServerMessage(swiftServerMessage); const swiftSignature = takerDriftClient.signMessage( digest(encodedSwiftServerMessage) ); try { let ixs = await makerDriftClient.getPlaceSwiftTakerPerpOrderIxs( encodedSwiftServerMessage, swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, marketIndex, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), } ); ixs = [ ComputeBudgetProgram.setComputeUnitLimit({ units: 10_000_000, }), ...ixs, ]; await makerDriftClient.sendTransaction(new Transaction().add(...ixs)); assert.fail('Should have failed'); } catch (error) { assert.equal( error.transactionMessage, 'Transaction precompile verification failure InvalidAccountIndex' ); } }); 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, }, swiftID: new PublicKey(ANCHOR_TEST_SWIFT_ID), }); 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, takeProfitOrderParams: null, stopLossOrderParams: null, }; await takerDriftClientUser.fetchAccounts(); // Auth for legit order const takerOrderParamsSig = takerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage ); const swiftServerMessage: SwiftServerMessage = { slot: new BN(await connection.getSlot()), swiftOrderSignature: takerOrderParamsSig, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const encodedSwiftServerMessage = makerDriftClient.encodeSwiftServerMessage(swiftServerMessage); const swiftSignature = makerDriftClient.signMessage( digest(encodedSwiftServerMessage), swiftKeypair ); // 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, }; const takerOrderParamsSig2 = takerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage2 ); const swiftServerMessage2: SwiftServerMessage = { slot: new BN(await connection.getSlot()), swiftOrderSignature: takerOrderParamsSig2, uuid: Uint8Array.from(Buffer.from(nanoid(8))), }; const encodedSwiftServerMessage2 = makerDriftClient.encodeSwiftServerMessage(swiftServerMessage2); const swiftSignature2 = makerDriftClient.signMessage( digest(encodedSwiftServerMessage2), swiftKeypair ); const computeBudgetIx = ComputeBudgetProgram.setComputeUnitLimit({ units: 10_000_000, }); const ixs = await makerDriftClient.getPlaceSwiftTakerPerpOrderIxs( encodedSwiftServerMessage, swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, 0, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), takerStats: takerDriftClient.getUserStatsAccountPublicKey(), } ); const ixsForOrder2 = await makerDriftClient.getPlaceSwiftTakerPerpOrderIxs( encodedSwiftServerMessage2, swiftSignature2, 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], ixsForOrder2[2]] ); 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], ixsForOrder2[2]] ); 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') ) ); } }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/pythLazerData.ts
export const PYTH_STORAGE_DATA = '0XX/ucSvRAkL/td28gTUmmjn6CkzKyvYXJOMcup4pEKu3cXcP7cvDAH2UhC+5Pz1sc7h5Tf6vP2VAQKXZTuUrwTUVPxHPpSDT+g2BnoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=='; export const PYTH_LAZER_HEX_STRING_BTC = 'b9011a82cb2701fd7ef39a113d32e1f8e5b759e1a0d41aa2f587521979d3ff10178b34b56bb9e2c0bdbc5a55fe2162ed81e90b5d0d36bd43286f9e99e49e242a00dd860ef65210bee4fcf5b1cee1e537fabcfd95010297653b94af04d454fc473e94834f1c0075d3c79340d732d48f2806000301010000000100daa8b56fe2080000'; export const PYTH_LAZER_HEX_STRING_SOL = 'b9011a8286e4219d980a176145b777aff894df914947c33855028f2b993a8963b131270c9cbcccd282685eb24bdeffcb8bec8c5203f6c882ad2e8b9adb0d1ba6f89b3e09f65210bee4fcf5b1cee1e537fabcfd95010297653b94af04d454fc473e94834f1c0075d3c79340e90513da2806000301060000000100fd09283605000000'; export const PYTH_LAZER_HEX_STRING_MULTI = 'b9011a82bc4fe2aed6fb554f6724c98b49d0f3d7de89cb1ec95e536331dafd6da8db486610ac5d2f7d3e3156397f7f3f1adcf017b927c2f5b6128ea9b92362e20ee19a0df65210bee4fcf5b1cee1e537fabcfd95010297653b94af04d454fc473e94834f380075d3c79380f34c30172906000303010000000100d325584031090000020000000100d0cd67855b000000060000000100a026ea6505000000';
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/triggerOrders.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair } from '@solana/web3.js'; import { TestClient, BN, PRICE_PRECISION, PositionDirection, User, Wallet, getMarketOrderParams, OrderTriggerCondition, getTriggerMarketOrderParams, getTriggerLimitOrderParams, OracleGuardRails, } from '../sdk/src'; import { mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, initializeQuoteSpotMarket, } from './testHelpers'; import { BASE_PRECISION, convertToNumber, OracleSource, PERCENTAGE_PRECISION, QUOTE_PRECISION, ZERO, } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('trigger orders', () => { const chProgram = anchor.workspace.Drift as Program; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let fillerDriftClient: TestClient; let fillerDriftClientUser: User; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); let solUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); marketIndexes = [0]; spotMarketIndexes = [0]; oracleInfos = [ { publicKey: solUsd, source: OracleSource.PYTH, }, ]; fillerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClient.initialize(usdcMint.publicKey, true); await fillerDriftClient.subscribe(); await initializeQuoteSpotMarket(fillerDriftClient, usdcMint.publicKey); await fillerDriftClient.updatePerpAuctionDuration(new BN(0)); const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: PERCENTAGE_PRECISION.mul(new BN(10)), oracleTwap5MinPercentDivergence: PERCENTAGE_PRECISION.mul(new BN(10)), }, validity: { slotsBeforeStaleForAmm: new BN(100), slotsBeforeStaleForMargin: new BN(100), confidenceIntervalMaxSize: new BN(100000), tooVolatileRatio: new BN(55), // allow 55x change }, }; await fillerDriftClient.updateOracleGuardRails(oracleGuardRails); const periodicity = new BN(60 * 60); // 1 HOUR await fillerDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await fillerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); fillerDriftClientUser = new User({ driftClient: fillerDriftClient, userAccountPublicKey: await fillerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClientUser.subscribe(); }); beforeEach(async () => { await fillerDriftClient.moveAmmPrice( 0, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve ); await setFeedPriceNoProgram(bankrunContextWrapper, 1, solUsd); }); after(async () => { await fillerDriftClient.unsubscribe(); await fillerDriftClientUser.unsubscribe(); }); it('stop market for long', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const marketOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, }); await driftClient.placeAndTakePerpOrder(marketOrderParams); const stopOrderParams = getTriggerMarketOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, triggerPrice: PRICE_PRECISION.div(new BN(2)), triggerCondition: OrderTriggerCondition.BELOW, userOrderId: 1, }); await driftClient.placePerpOrder(stopOrderParams); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); assert(false); } catch (e) { // no op } const newOraclePrice = 0.49; await fillerDriftClient.moveAmmToPrice( marketIndex, new BN(newOraclePrice * PRICE_PRECISION.toNumber()) ); await setFeedPriceNoProgram(bankrunContextWrapper, newOraclePrice, solUsd); await fillerDriftClient.triggerOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await driftClientUser.fetchAccounts(); assert( driftClientUser.getUserAccount().perpPositions[0].baseAssetAmount.eq(ZERO) ); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('stop limit for long', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION.mul(new BN(10)); const marketOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, }); await driftClient.placeAndTakePerpOrder(marketOrderParams); const stopLimitOrderParams = getTriggerLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, price: PRICE_PRECISION.div(new BN(2)).sub( PRICE_PRECISION.div(new BN(50)) ), triggerPrice: PRICE_PRECISION.div(new BN(2)), triggerCondition: OrderTriggerCondition.BELOW, userOrderId: 1, }); await driftClient.placePerpOrder(stopLimitOrderParams); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); assert(false); } catch (e) { // no op } const newOraclePrice = 0.49; await fillerDriftClient.moveAmmToPrice( marketIndex, new BN(newOraclePrice * PRICE_PRECISION.toNumber()) ); await setFeedPriceNoProgram(bankrunContextWrapper, newOraclePrice, solUsd); await fillerDriftClient.triggerOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await driftClientUser.fetchAccounts(); assert( driftClientUser.getUserAccount().perpPositions[0].baseAssetAmount.eq(ZERO) ); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('stop market for short', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const marketOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, }); await driftClient.placeAndTakePerpOrder(marketOrderParams); const stopOrderParams = getTriggerMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, triggerPrice: PRICE_PRECISION.mul(new BN(2)), triggerCondition: OrderTriggerCondition.ABOVE, userOrderId: 1, }); await driftClient.placePerpOrder(stopOrderParams); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); assert(false); } catch (e) { // no op } const newOraclePrice = 2.01; await fillerDriftClient.moveAmmToPrice( marketIndex, new BN(newOraclePrice * PRICE_PRECISION.toNumber()) ); await setFeedPriceNoProgram(bankrunContextWrapper, newOraclePrice, solUsd); await fillerDriftClient.triggerOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await driftClientUser.fetchAccounts(); assert( driftClientUser.getUserAccount().perpPositions[0].baseAssetAmount.eq(ZERO) ); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('stop limit for short', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION.mul(new BN(10)); const marketOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, }); await driftClient.placeAndTakePerpOrder(marketOrderParams); const triggerPrice = PRICE_PRECISION.mul(new BN(6)).div(new BN(5)); const limitPrice = triggerPrice.add(PRICE_PRECISION.div(new BN(50))); const stopLimitOrderParams = getTriggerLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, price: limitPrice, triggerPrice, triggerCondition: OrderTriggerCondition.ABOVE, userOrderId: 1, }); await driftClient.placePerpOrder(stopLimitOrderParams); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); assert(false); } catch (e) { // no op } await driftClientUser.fetchAccounts(); const totalCollateral0 = driftClientUser.getTotalCollateral(); console.log( 'user total collateral 0:', convertToNumber(totalCollateral0, QUOTE_PRECISION) ); const newOraclePrice = 1.201; await fillerDriftClient.moveAmmToPrice( marketIndex, new BN(newOraclePrice * PRICE_PRECISION.toNumber()) ); await setFeedPriceNoProgram(bankrunContextWrapper, newOraclePrice, solUsd); await driftClientUser.fetchAccounts(); const totalCollateral = driftClientUser.getTotalCollateral(); console.log( 'user total collateral after:', convertToNumber(totalCollateral, QUOTE_PRECISION) ); await fillerDriftClient.triggerOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); // await printTxLogs(connection, txSig); await driftClientUser.fetchAccounts(); assert( driftClientUser.getUserAccount().perpPositions[0].baseAssetAmount.eq(ZERO) ); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('take profit for long', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const marketOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, }); await driftClient.placeAndTakePerpOrder(marketOrderParams); const stopOrderParams = getTriggerMarketOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, triggerPrice: PRICE_PRECISION.mul(new BN(2)), triggerCondition: OrderTriggerCondition.ABOVE, userOrderId: 1, }); await driftClient.placePerpOrder(stopOrderParams); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); assert(false); } catch (e) { // no op } await fillerDriftClient.moveAmmPrice( marketIndex, ammInitialBaseAssetReserve.div(new BN(10)), ammInitialQuoteAssetReserve ); await setFeedPriceNoProgram(bankrunContextWrapper, 2.01, solUsd); await fillerDriftClient.triggerOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await driftClientUser.fetchAccounts(); assert( driftClientUser.getUserAccount().perpPositions[0].baseAssetAmount.eq(ZERO) ); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('take profit limit for long', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION.mul(new BN(10)); const marketOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, }); await driftClient.placeAndTakePerpOrder(marketOrderParams); const triggerPrice = PRICE_PRECISION.mul(new BN(2)); const limitPrice = triggerPrice.sub(PRICE_PRECISION.div(new BN(50))); const stopLimitOrderParams = getTriggerLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, price: limitPrice, triggerPrice: triggerPrice, triggerCondition: OrderTriggerCondition.ABOVE, userOrderId: 1, }); await driftClient.placePerpOrder(stopLimitOrderParams); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); assert(false); } catch (e) { // no op } const newOraclePrice = 2.01; await fillerDriftClient.moveAmmToPrice( marketIndex, new BN(newOraclePrice * PRICE_PRECISION.toNumber()) ); await setFeedPriceNoProgram(bankrunContextWrapper, newOraclePrice, solUsd); await fillerDriftClient.triggerOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await driftClientUser.fetchAccounts(); assert( driftClientUser.getUserAccount().perpPositions[0].baseAssetAmount.eq(ZERO) ); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('take profit for short', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION; const marketOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, }); await driftClient.placeAndTakePerpOrder(marketOrderParams); const stopOrderParams = getTriggerMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, triggerPrice: PRICE_PRECISION.div(new BN(2)), triggerCondition: OrderTriggerCondition.BELOW, userOrderId: 1, }); await driftClient.placePerpOrder(stopOrderParams); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); assert(false); } catch (e) { // no op } await fillerDriftClient.moveAmmPrice( marketIndex, ammInitialBaseAssetReserve.mul(new BN(10)), ammInitialQuoteAssetReserve ); await setFeedPriceNoProgram(bankrunContextWrapper, 0.49, solUsd); await fillerDriftClient.triggerOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await driftClientUser.fetchAccounts(); assert( driftClientUser.getUserAccount().perpPositions[0].baseAssetAmount.eq(ZERO) ); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); it('take profit limit for short', async () => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const marketIndex = 0; const baseAssetAmount = BASE_PRECISION.mul(new BN(10)); const marketOrderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, }); await driftClient.placeAndTakePerpOrder(marketOrderParams); const triggerPrice = PRICE_PRECISION.div(new BN(2)); const limitPrice = triggerPrice.add(PRICE_PRECISION.div(new BN(50))); const stopLimitOrderParams = getTriggerLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, price: limitPrice, triggerPrice: triggerPrice, triggerCondition: OrderTriggerCondition.BELOW, userOrderId: 1, }); await driftClient.placePerpOrder(stopLimitOrderParams); await driftClientUser.fetchAccounts(); const order = driftClientUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); assert(false); } catch (e) { // no op } const newOraclePrice = 0.49; await fillerDriftClient.moveAmmToPrice( marketIndex, new BN(newOraclePrice * PRICE_PRECISION.toNumber()) ); await setFeedPriceNoProgram(bankrunContextWrapper, newOraclePrice, solUsd); await fillerDriftClient.triggerOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await fillerDriftClient.fillPerpOrder( await driftClientUser.getUserAccountPublicKey(), driftClientUser.getUserAccount(), order ); await driftClientUser.fetchAccounts(); assert( driftClientUser.getUserAccount().perpPositions[0].baseAssetAmount.eq(ZERO) ); await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/serumTest.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair, PublicKey, Transaction } from '@solana/web3.js'; import { listMarket, makePlaceOrderTransaction, SERUM } from './serumHelper'; import { BN, TestClient, EventSubscriber, OracleSource, OracleInfo, PositionDirection, castNumberToSpotPrecision, getLimitOrderParams, getTokenAmount, isVariant, PRICE_PRECISION, SpotBalanceType, } from '../sdk/src'; import { createUserWithUSDCAndWSOLAccount, createWSolTokenAccountForUser, initializeQuoteSpotMarket, initializeSolSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } from './testHelpers'; import { NATIVE_MINT } from '@solana/spl-token'; import { Market } from '@project-serum/serum'; import { getMarketOrderParams, ZERO } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('serum spot market', () => { const chProgram = anchor.workspace.Drift as Program; let makerDriftClient: TestClient; let makerWSOL: PublicKey; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let solOracle: PublicKey; let serumMarketPublicKey: PublicKey; let usdcMint; let makerUSDC; let takerDriftClient: TestClient; let _takerWSOL: PublicKey; let takerUSDC: PublicKey; const usdcAmount = new BN(200 * 10 ** 6); const solAmount = new BN(2 * 10 ** 9); let marketIndexes: number[]; let spotMarketIndexes: number[]; let oracleInfos: OracleInfo[]; const solSpotMarketIndex = 1; let openOrdersAccount: PublicKey; before(async () => { const context = await startAnchor( '', [ { name: 'serum_dex', programId: new PublicKey( 'srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX' ), }, ], [] ); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); makerUSDC = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); makerWSOL = await createWSolTokenAccountForUser( bankrunContextWrapper, // @ts-ignore bankrunContextWrapper.provider.wallet, solAmount ); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 100); marketIndexes = []; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solOracle, source: OracleSource.PYTH }]; makerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClient.initialize(usdcMint.publicKey, true); await makerDriftClient.subscribe(); await makerDriftClient.initializeUserAccount(); await initializeQuoteSpotMarket(makerDriftClient, usdcMint.publicKey); await initializeSolSpotMarket(makerDriftClient, solOracle); await makerDriftClient.updateSpotMarketStepSizeAndTickSize( 1, new BN(100000000), new BN(100) ); await makerDriftClient.updateSpotAuctionDuration(0); [takerDriftClient, _takerWSOL, takerUSDC] = await createUserWithUSDCAndWSOLAccount( bankrunContextWrapper, usdcMint, chProgram, solAmount, usdcAmount, [], [0, 1], [ { publicKey: solOracle, source: OracleSource.PYTH, }, ], bulkAccountLoader ); await takerDriftClient.deposit(usdcAmount, 0, takerUSDC); }); after(async () => { await takerDriftClient.unsubscribe(); await makerDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('Add Serum Market', async () => { serumMarketPublicKey = await listMarket({ context: bankrunContextWrapper, wallet: bankrunContextWrapper.provider.wallet, baseMint: NATIVE_MINT, quoteMint: usdcMint.publicKey, baseLotSize: 100000000, quoteLotSize: 100, dexProgramId: SERUM, feeRateBps: 0, }); await Market.load( bankrunContextWrapper.connection.toConnection(), serumMarketPublicKey, { commitment: 'confirmed' }, SERUM ); await makerDriftClient.initializeSerumFulfillmentConfig( solSpotMarketIndex, serumMarketPublicKey, SERUM ); }); 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('Fill bid', async () => { const baseAssetAmount = castNumberToSpotPrecision( 1, makerDriftClient.getSpotMarketAccount(solSpotMarketIndex) ); await takerDriftClient.placeSpotOrder( getLimitOrderParams({ marketIndex: solSpotMarketIndex, direction: PositionDirection.LONG, baseAssetAmount, userOrderId: 1, price: new BN(100).mul(PRICE_PRECISION), }) ); await takerDriftClient.fetchAccounts(); const spotOrder = takerDriftClient.getOrderByUserId(1); assert(isVariant(spotOrder.marketType, 'spot')); assert(spotOrder.baseAssetAmount.eq(baseAssetAmount)); const market = await Market.load( bankrunContextWrapper.connection.toConnection(), serumMarketPublicKey, { commitment: 'recent' }, SERUM ); // @ts-ignore const { transaction, signers } = await makePlaceOrderTransaction( bankrunContextWrapper.connection.toConnection(), market, { // @ts-ignore owner: bankrunContextWrapper.provider.wallet, payer: makerWSOL, side: 'sell', price: 100, size: 1, orderType: 'postOnly', clientId: undefined, // todo? openOrdersAddressKey: undefined, openOrdersAccount: undefined, feeDiscountPubkey: null, selfTradeBehavior: 'abortTransaction', } ); openOrdersAccount = signers[0].publicKey; const signerKeypairs = signers.map((signer) => { return Keypair.fromSecretKey(signer.secretKey); }); await bankrunContextWrapper.sendTransaction(transaction, signerKeypairs); // await provider.sendAndConfirm(transaction, signers); const serumFulfillmentConfigAccount = await makerDriftClient.getSerumV3FulfillmentConfig(serumMarketPublicKey); const txSig = await makerDriftClient.fillSpotOrder( await takerDriftClient.getUserAccountPublicKey(), takerDriftClient.getUserAccount(), takerDriftClient.getOrderByUserId(1), serumFulfillmentConfigAccount ); await eventSubscriber.awaitTx(txSig); bankrunContextWrapper.printTxLogs(txSig); // await printTxLogs(connection, txSig); await takerDriftClient.fetchAccounts(); const takerQuoteSpotBalance = takerDriftClient.getSpotPosition(0); const takerBaseSpotBalance = takerDriftClient.getSpotPosition(1); const quoteTokenAmount = getTokenAmount( takerQuoteSpotBalance.scaledBalance, takerDriftClient.getQuoteSpotMarketAccount(), takerQuoteSpotBalance.balanceType ); console.log(quoteTokenAmount.toString()); assert(quoteTokenAmount.eq(new BN(99899999))); const baseTokenAmount = getTokenAmount( takerBaseSpotBalance.scaledBalance, takerDriftClient.getSpotMarketAccount(1), takerBaseSpotBalance.balanceType ); assert(baseTokenAmount.eq(new BN(1000000000))); const takerOrder = takerDriftClient.getUserAccount().orders[0]; assert(isVariant(takerOrder.status, 'init')); const orderActionRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert(isVariant(orderActionRecord.action, 'fill')); assert(orderActionRecord.baseAssetAmountFilled.eq(new BN(1000000000))); assert(orderActionRecord.quoteAssetAmountFilled.eq(new BN(100000000))); assert(orderActionRecord.takerFee.eq(new BN(100000))); await makerDriftClient.fetchAccounts(); assert(makerDriftClient.getQuoteAssetTokenAmount().eq(new BN(11800))); const solSpotMarket = takerDriftClient.getSpotMarketAccount(solSpotMarketIndex); const spotFeePoolAmount = getTokenAmount( solSpotMarket.spotFeePool.scaledBalance, takerDriftClient.getQuoteSpotMarketAccount(), SpotBalanceType.DEPOSIT ); assert(spotFeePoolAmount.eq(new BN(48200))); await crankMarkets(); }); it('Fill ask', async () => { const baseAssetAmount = castNumberToSpotPrecision( 1, makerDriftClient.getSpotMarketAccount(solSpotMarketIndex) ); await takerDriftClient.placeSpotOrder( getLimitOrderParams({ marketIndex: solSpotMarketIndex, direction: PositionDirection.SHORT, baseAssetAmount, userOrderId: 1, price: new BN(100).mul(PRICE_PRECISION), }) ); await takerDriftClient.fetchAccounts(); const spotOrder = takerDriftClient.getOrderByUserId(1); assert(isVariant(spotOrder.marketType, 'spot')); assert(spotOrder.baseAssetAmount.eq(baseAssetAmount)); const market = await Market.load( bankrunContextWrapper.connection.toConnection(), serumMarketPublicKey, { commitment: 'recent' }, SERUM ); // @ts-ignore const { transaction, signers } = await makePlaceOrderTransaction( bankrunContextWrapper.connection.toConnection(), market, { // @ts-ignore owner: bankrunContextWrapper.provider.wallet, payer: makerUSDC.publicKey, side: 'buy', price: 100, size: 1, orderType: 'postOnly', clientId: undefined, // todo? openOrdersAddressKey: undefined, openOrdersAccount: undefined, feeDiscountPubkey: null, selfTradeBehavior: 'abortTransaction', } ); const signerKeypairs = signers.map((signer) => { return Keypair.fromSecretKey(signer.secretKey); }); await bankrunContextWrapper.sendTransaction(transaction, signerKeypairs); const serumFulfillmentConfigAccount = await makerDriftClient.getSerumV3FulfillmentConfig(serumMarketPublicKey); const txSig = await makerDriftClient.fillSpotOrder( await takerDriftClient.getUserAccountPublicKey(), takerDriftClient.getUserAccount(), takerDriftClient.getOrderByUserId(1), serumFulfillmentConfigAccount ); await eventSubscriber.awaitTx(txSig); bankrunContextWrapper.printTxLogs(txSig); // await printTxLogs(connection, txSig); await takerDriftClient.fetchAccounts(); const takerQuoteSpotBalance = takerDriftClient.getSpotPosition(0); const takerBaseSpotBalance = takerDriftClient.getSpotPosition(1); const quoteTokenAmount = getTokenAmount( takerQuoteSpotBalance.scaledBalance, takerDriftClient.getQuoteSpotMarketAccount(), takerQuoteSpotBalance.balanceType ); console.log(quoteTokenAmount.toString()); assert(quoteTokenAmount.eq(new BN(199799999))); const baseTokenAmount = getTokenAmount( takerBaseSpotBalance.scaledBalance, takerDriftClient.getSpotMarketAccount(1), takerBaseSpotBalance.balanceType ); assert(baseTokenAmount.eq(new BN(0))); const takerOrder = takerDriftClient.getUserAccount().orders[0]; assert(isVariant(takerOrder.status, 'init')); const orderActionRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert(isVariant(orderActionRecord.action, 'fill')); assert(orderActionRecord.baseAssetAmountFilled.eq(new BN(1000000000))); assert(orderActionRecord.quoteAssetAmountFilled.eq(new BN(100000000))); assert(orderActionRecord.takerFee.eq(new BN(100000))); assert(makerDriftClient.getQuoteAssetTokenAmount().eq(new BN(23600))); const solSpotMarket = takerDriftClient.getSpotMarketAccount(solSpotMarketIndex); assert(solSpotMarket.totalSpotFee.eq(new BN(136400))); const spotFeePoolAmount = getTokenAmount( solSpotMarket.spotFeePool.scaledBalance, takerDriftClient.getQuoteSpotMarketAccount(), SpotBalanceType.DEPOSIT ); console.log(spotFeePoolAmount.toString()); assert(spotFeePoolAmount.eq(new BN(116400))); await crankMarkets(); }); // check that moving referrer rebates works properly it('Fill bid second time', async () => { const baseAssetAmount = castNumberToSpotPrecision( 1, makerDriftClient.getSpotMarketAccount(solSpotMarketIndex) ); await takerDriftClient.placeSpotOrder( getLimitOrderParams({ marketIndex: solSpotMarketIndex, direction: PositionDirection.LONG, baseAssetAmount, userOrderId: 1, price: new BN(100).mul(PRICE_PRECISION), }) ); await takerDriftClient.fetchAccounts(); const spotOrder = takerDriftClient.getOrderByUserId(1); assert(isVariant(spotOrder.marketType, 'spot')); assert(spotOrder.baseAssetAmount.eq(baseAssetAmount)); const market = await Market.load( bankrunContextWrapper.connection.toConnection(), serumMarketPublicKey, { commitment: 'recent' }, SERUM ); // @ts-ignore const { transaction, signers } = await makePlaceOrderTransaction( bankrunContextWrapper.connection.toConnection(), market, { // @ts-ignore owner: bankrunContextWrapper.provider.wallet, payer: makerWSOL, side: 'sell', price: 100, size: 1, orderType: 'postOnly', clientId: undefined, // todo? openOrdersAddressKey: undefined, openOrdersAccount: undefined, feeDiscountPubkey: null, selfTradeBehavior: 'abortTransaction', } ); const signerKeypairs = signers.map((signer) => { return Keypair.fromSecretKey(signer.secretKey); }); await bankrunContextWrapper.sendTransaction(transaction, signerKeypairs); // await provider.sendAndConfirm(transaction, signers); const serumFulfillmentConfigAccount = await makerDriftClient.getSerumV3FulfillmentConfig(serumMarketPublicKey); const txSig = await makerDriftClient.fillSpotOrder( await takerDriftClient.getUserAccountPublicKey(), takerDriftClient.getUserAccount(), takerDriftClient.getOrderByUserId(1), serumFulfillmentConfigAccount ); bankrunContextWrapper.printTxLogs(txSig); // await printTxLogs(connection, txSig); await eventSubscriber.awaitTx(txSig); await takerDriftClient.fetchAccounts(); const takerQuoteSpotBalance = takerDriftClient.getSpotPosition(0); const takerBaseSpotBalance = takerDriftClient.getSpotPosition(1); const quoteTokenAmount = getTokenAmount( takerQuoteSpotBalance.scaledBalance, takerDriftClient.getQuoteSpotMarketAccount(), takerQuoteSpotBalance.balanceType ); console.log(quoteTokenAmount.toString()); assert(quoteTokenAmount.eq(new BN(99699999))); // paid ~$.30 const baseTokenAmount = getTokenAmount( takerBaseSpotBalance.scaledBalance, takerDriftClient.getSpotMarketAccount(1), takerBaseSpotBalance.balanceType ); assert(baseTokenAmount.eq(new BN(1000000000))); const takerOrder = takerDriftClient.getUserAccount().orders[0]; assert(isVariant(takerOrder.status, 'init')); const orderActionRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert(isVariant(orderActionRecord.action, 'fill')); assert(orderActionRecord.baseAssetAmountFilled.eq(new BN(1000000000))); assert(orderActionRecord.quoteAssetAmountFilled.eq(new BN(100000000))); assert(orderActionRecord.takerFee.eq(new BN(100000))); const solSpotMarket = takerDriftClient.getSpotMarketAccount(solSpotMarketIndex); assert(solSpotMarket.totalSpotFee.eq(new BN(204600))); // const spotFeePoolAmount = getTokenAmount( // solSpotMarket.spotFeePool.scaledBalance, // takerDriftClient.getQuoteSpotMarketAccount(), // SpotBalanceType.DEPOSIT // ); console.log(`${orderActionRecord.fillerReward}`); console.log(`${solSpotMarket.cumulativeDepositInterest.toString()}`); console.log(`${orderActionRecord.makerFee.toString()}`); console.log(solSpotMarket.depositBalance.toString()); console.log(`${solSpotMarket.borrowBalance.toString()}`); // TODO: Figure out why this value comes out as 164600 // assert(spotFeePoolAmount.eq(new BN(184600))); assert(orderActionRecord.fillerReward.eq(new BN(11800))); assert(orderActionRecord.makerFee.eq(new BN(0))); assert(solSpotMarket.depositBalance.eq(new BN(1_000_000_000))); await crankMarkets(); }); // check that moving referrer rebates works properly it('Place and take', async () => { const market = await Market.load( bankrunContextWrapper.connection.toConnection(), serumMarketPublicKey, { commitment: 'recent' }, SERUM ); // @ts-ignore const { transaction, signers } = await makePlaceOrderTransaction( bankrunContextWrapper.connection.toConnection(), market, { // @ts-ignore owner: bankrunContextWrapper.provider.wallet, payer: makerUSDC.publicKey, side: 'buy', price: 100, size: 1, orderType: 'postOnly', clientId: undefined, // todo? openOrdersAddressKey: undefined, openOrdersAccount: undefined, feeDiscountPubkey: null, selfTradeBehavior: 'abortTransaction', } ); const signerKeypairs = signers.map((signer) => { return Keypair.fromSecretKey(signer.secretKey); }); await bankrunContextWrapper.sendTransaction(transaction, signerKeypairs); // await provider.sendAndConfirm(transaction, signers); const baseAssetAmount = castNumberToSpotPrecision( 1, makerDriftClient.getSpotMarketAccount(solSpotMarketIndex) ); const serumFulfillmentConfigAccount = await makerDriftClient.getSerumV3FulfillmentConfig(serumMarketPublicKey); const txSig = await takerDriftClient.placeAndTakeSpotOrder( getMarketOrderParams({ marketIndex: solSpotMarketIndex, direction: PositionDirection.SHORT, baseAssetAmount, userOrderId: 1, }), serumFulfillmentConfigAccount ); bankrunContextWrapper.printTxLogs(txSig); // await printTxLogs(connection, txSig); await eventSubscriber.awaitTx(txSig); await takerDriftClient.fetchAccounts(); const takerQuoteSpotBalance = takerDriftClient.getSpotPosition(0); const takerBaseSpotBalance = takerDriftClient.getSpotPosition(1); const quoteTokenAmount = getTokenAmount( takerQuoteSpotBalance.scaledBalance, takerDriftClient.getQuoteSpotMarketAccount(), takerQuoteSpotBalance.balanceType ); console.log(quoteTokenAmount.toString()); assert(quoteTokenAmount.eq(new BN(199599999))); // paid ~$.40 const baseTokenAmount = getTokenAmount( takerBaseSpotBalance.scaledBalance, takerDriftClient.getSpotMarketAccount(1), takerBaseSpotBalance.balanceType ); assert(baseTokenAmount.eq(ZERO)); const takerOrder = takerDriftClient.getUserAccount().orders[0]; assert(isVariant(takerOrder.status, 'init')); const orderActionRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert(isVariant(orderActionRecord.action, 'fill')); assert(orderActionRecord.baseAssetAmountFilled.eq(new BN(1000000000))); assert(orderActionRecord.quoteAssetAmountFilled.eq(new BN(100000000))); assert(orderActionRecord.takerFee.eq(new BN(100000))); const solSpotMarket = takerDriftClient.getSpotMarketAccount(solSpotMarketIndex); console.log(solSpotMarket.totalSpotFee.toString()); assert(solSpotMarket.totalSpotFee.eq(new BN(284600))); // const spotFeePoolAmount = getTokenAmount( // solSpotMarket.spotFeePool.scaledBalance, // takerDriftClient.getQuoteSpotMarketAccount(), // SpotBalanceType.DEPOSIT // ); console.log(`${orderActionRecord.fillerReward.toString()}`); console.log(`${solSpotMarket.cumulativeDepositInterest.toString()}`); console.log(`${orderActionRecord.makerFee.toString()}`); console.log(`${solSpotMarket.borrowBalance.toString()}`); assert(orderActionRecord.fillerReward.eq(new BN(0))); assert(orderActionRecord.makerFee.eq(new BN(0))); assert(solSpotMarket.depositBalance.eq(new BN(0))); // TODO: Figure out why this value comes out as 224000 // assert(spotFeePoolAmount.eq(new BN(264600))); await crankMarkets(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/govStakeDevnet.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { TestClient, EventSubscriber, User, ANCHOR_TEST_SWIFT_ID, OracleSource, PEG_PRECISION, PRICE_PRECISION, } from '../sdk/src'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; import dotenv from 'dotenv'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, } from './testHelpers'; import { PublicKey } from '@solana/web3.js'; dotenv.config(); describe('gov stake increase on devnet', () => { const chProgram = anchor.workspace.Drift as Program; let makerDriftClient: TestClient; let makerDriftClientUser: User; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; // ammInvariant == k == x * y const mantissaSqrtScale = new anchor.BN( Math.sqrt(PRICE_PRECISION.toNumber()) ); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); let usdcMint; let userUSDCAccount; const usdcAmount = new anchor.BN(100 * 10 ** 6); let solUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor('', [], []); // @ts-ignore bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), // @ts-ignore chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 32.821); marketIndexes = [0]; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; makerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, swiftID: new PublicKey(ANCHOR_TEST_SWIFT_ID), }); await makerDriftClient.initialize(usdcMint.publicKey, true); await makerDriftClient.subscribe(); await initializeQuoteSpotMarket(makerDriftClient, usdcMint.publicKey); const periodicity = new anchor.BN(0); await makerDriftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new anchor.BN(33 * PEG_PRECISION.toNumber()) ); await makerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); makerDriftClientUser = new User({ driftClient: makerDriftClient, userAccountPublicKey: await makerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClientUser.subscribe(); }); after(async () => { await makerDriftClient.unsubscribe(); await makerDriftClientUser.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('should update gov stake without error', async () => { await makerDriftClient.updateUserGovTokenInsuranceStake( makerDriftClient.authority, undefined, 'devnet' ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/testHelpersLocalValidator.ts
import * as anchor from '@coral-xyz/anchor'; import { AnchorProvider, Program, Provider } from '@coral-xyz/anchor'; import { AccountLayout, MintLayout, NATIVE_MINT, TOKEN_PROGRAM_ID, getMinimumBalanceForRentExemptMint, getMinimumBalanceForRentExemptAccount, createInitializeMintInstruction, createInitializeAccountInstruction, createMintToInstruction, createWrappedNativeAccount, } from '@solana/spl-token'; import { Connection, Keypair, PublicKey, sendAndConfirmTransaction, SystemProgram, Transaction, TransactionSignature, } from '@solana/web3.js'; import { assert } from 'chai'; import buffer from 'buffer'; import { BN, Wallet, OraclePriceData, OracleInfo, BulkAccountLoader, } from '../sdk'; import { TestClient, SPOT_MARKET_RATE_PRECISION, SPOT_MARKET_WEIGHT_PRECISION, PRICE_PRECISION, QUOTE_PRECISION, User, OracleSource, } from '../sdk/src'; export async function mockOracle( price: number = 50 * 10e7, expo = -7, confidence?: number ): Promise<PublicKey> { // default: create a $50 coin oracle const program = anchor.workspace.Pyth; anchor.setProvider( anchor.AnchorProvider.local(undefined, { commitment: 'confirmed', preflightCommitment: 'confirmed', }) ); const priceFeedAddress = await createPriceFeed({ oracleProgram: program, initPrice: price, expo: expo, confidence, }); const feedData = await getFeedData(program, priceFeedAddress); if (feedData.price !== price) { console.log('mockOracle precision error:', feedData.price, '!=', price); } assert.ok(Math.abs(feedData.price - price) < 1e-10); return priceFeedAddress; } export async function mockUSDCMint(provider: Provider): Promise<Keypair> { const fakeUSDCMint = anchor.web3.Keypair.generate(); const createUSDCMintAccountIx = SystemProgram.createAccount({ fromPubkey: provider.publicKey, newAccountPubkey: fakeUSDCMint.publicKey, lamports: await getMinimumBalanceForRentExemptMint(provider.connection), space: MintLayout.span, programId: TOKEN_PROGRAM_ID, }); const initCollateralMintIx = createInitializeMintInstruction( fakeUSDCMint.publicKey, 6, // @ts-ignore provider.publicKey, // @ts-ignore provider.publicKey ); const fakeUSDCTx = new Transaction(); fakeUSDCTx.add(createUSDCMintAccountIx); fakeUSDCTx.add(initCollateralMintIx); await sendAndConfirmTransaction( provider.connection, fakeUSDCTx, // @ts-ignore [provider.wallet.payer, fakeUSDCMint], { skipPreflight: false, commitment: 'recent', preflightCommitment: 'recent', } ); return fakeUSDCMint; } export async function mockUserUSDCAccount( fakeUSDCMint: Keypair, usdcMintAmount: BN, provider: Provider, owner?: PublicKey ): Promise<Keypair> { const userUSDCAccount = anchor.web3.Keypair.generate(); const fakeUSDCTx = new Transaction(); if (owner === undefined) { owner = provider.publicKey; } const createUSDCTokenAccountIx = SystemProgram.createAccount({ fromPubkey: provider.publicKey, newAccountPubkey: userUSDCAccount.publicKey, lamports: await getMinimumBalanceForRentExemptAccount(provider.connection), space: AccountLayout.span, programId: TOKEN_PROGRAM_ID, }); fakeUSDCTx.add(createUSDCTokenAccountIx); const initUSDCTokenAccountIx = createInitializeAccountInstruction( userUSDCAccount.publicKey, fakeUSDCMint.publicKey, owner ); fakeUSDCTx.add(initUSDCTokenAccountIx); const mintToUserAccountTx = await createMintToInstruction( fakeUSDCMint.publicKey, userUSDCAccount.publicKey, // @ts-ignore provider.publicKey, usdcMintAmount.toNumber() ); fakeUSDCTx.add(mintToUserAccountTx); const _fakeUSDCTxResult = await sendAndConfirmTransaction( provider.connection, fakeUSDCTx, // @ts-ignore [provider.wallet.payer, userUSDCAccount], { skipPreflight: false, commitment: 'recent', preflightCommitment: 'recent', } ); return userUSDCAccount; } export async function mintUSDCToUser( fakeUSDCMint: Keypair, userUSDCAccount: PublicKey, usdcMintAmount: BN, provider: Provider ): Promise<void> { const tx = new Transaction(); const mintToUserAccountTx = await createMintToInstruction( fakeUSDCMint.publicKey, userUSDCAccount, // @ts-ignore provider.publicKey, usdcMintAmount.toNumber() ); tx.add(mintToUserAccountTx); await sendAndConfirmTransaction( provider.connection, tx, // @ts-ignore [provider.wallet.payer], { skipPreflight: false, commitment: 'recent', preflightCommitment: 'recent', } ); } export async function createFundedKeyPair( connection: Connection ): Promise<Keypair> { const userKeyPair = new Keypair(); await connection.requestAirdrop(userKeyPair.publicKey, 10 ** 9); return userKeyPair; } export async function createUSDCAccountForUser( provider: AnchorProvider, userKeyPair: Keypair, usdcMint: Keypair, usdcAmount: BN ): Promise<PublicKey> { const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, provider, userKeyPair.publicKey ); return userUSDCAccount.publicKey; } export async function initializeAndSubscribeDriftClient( connection: Connection, program: Program, userKeyPair: Keypair, marketIndexes: number[], bankIndexes: number[], oracleInfos: OracleInfo[] = [], accountLoader?: BulkAccountLoader ): Promise<TestClient> { const driftClient = new TestClient({ connection, wallet: new Wallet(userKeyPair), programID: program.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: bankIndexes, oracleInfos, accountSubscription: accountLoader ? { type: 'polling', accountLoader, } : { type: 'websocket', }, }); await driftClient.subscribe(); await driftClient.initializeUserAccount(); return driftClient; } export async function createUserWithUSDCAccount( provider: AnchorProvider, usdcMint: Keypair, chProgram: Program, usdcAmount: BN, marketIndexes: number[], bankIndexes: number[], oracleInfos: OracleInfo[] = [], accountLoader?: BulkAccountLoader ): Promise<[TestClient, PublicKey, Keypair]> { const userKeyPair = await createFundedKeyPair(provider.connection); const usdcAccount = await createUSDCAccountForUser( provider, userKeyPair, usdcMint, usdcAmount ); const driftClient = await initializeAndSubscribeDriftClient( provider.connection, chProgram, userKeyPair, marketIndexes, bankIndexes, oracleInfos, accountLoader ); return [driftClient, usdcAccount, userKeyPair]; } export async function createWSolTokenAccountForUser( provider: AnchorProvider, userKeypair: Keypair | Wallet, amount: BN ): Promise<PublicKey> { await provider.connection.requestAirdrop( userKeypair.publicKey, amount.toNumber() + (await getMinimumBalanceForRentExemptAccount(provider.connection)) ); return await createWrappedNativeAccount( provider.connection, // @ts-ignore provider.wallet.payer, userKeypair.publicKey, amount.toNumber() ); } export async function createUserWithUSDCAndWSOLAccount( provider: AnchorProvider, usdcMint: Keypair, chProgram: Program, solAmount: BN, usdcAmount: BN, marketIndexes: number[], bankIndexes: number[], oracleInfos: OracleInfo[] = [], accountLoader?: BulkAccountLoader ): Promise<[TestClient, PublicKey, PublicKey, Keypair]> { const userKeyPair = await createFundedKeyPair(provider.connection); const solAccount = await createWSolTokenAccountForUser( provider, userKeyPair, solAmount ); const usdcAccount = await createUSDCAccountForUser( provider, userKeyPair, usdcMint, usdcAmount ); const driftClient = await initializeAndSubscribeDriftClient( provider.connection, chProgram, userKeyPair, marketIndexes, bankIndexes, oracleInfos, accountLoader ); return [driftClient, solAccount, usdcAccount, userKeyPair]; } export async function printTxLogs( connection: Connection, txSig: TransactionSignature ): Promise<void> { console.log( 'tx logs', (await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta .logMessages ); } export async function mintToInsuranceFund( chInsuranceAccountPubkey: PublicKey, fakeUSDCMint: Keypair, amount: BN, provider: Provider ): Promise<TransactionSignature> { const mintToUserAccountTx = await createMintToInstruction( fakeUSDCMint.publicKey, chInsuranceAccountPubkey, // @ts-ignore provider.publicKey, amount.toNumber() ); const fakeUSDCTx = new Transaction(); fakeUSDCTx.add(mintToUserAccountTx); return await sendAndConfirmTransaction( provider.connection, fakeUSDCTx, // @ts-ignore [provider.wallet.payer], { skipPreflight: false, commitment: 'recent', preflightCommitment: 'recent', } ); } export async function initUserAccounts( NUM_USERS: number, usdcMint: Keypair, usdcAmount: BN, provider: Provider, marketIndexes: number[], bankIndexes: number[], oracleInfos: OracleInfo[], accountLoader?: BulkAccountLoader ) { const user_keys = []; const userUSDCAccounts = []; const driftClients = []; const userAccountInfos = []; let userAccountPublicKey: PublicKey; for (let i = 0; i < NUM_USERS; i++) { console.log('user', i, 'initialize'); const owner = anchor.web3.Keypair.generate(); const ownerWallet = new anchor.Wallet(owner); await provider.connection.requestAirdrop(ownerWallet.publicKey, 100000000); const newUserAcct = await mockUserUSDCAccount( usdcMint, usdcAmount, provider, ownerWallet.publicKey ); const chProgram = anchor.workspace.Drift as anchor.Program; // this.program-ify const driftClient1 = new TestClient({ connection: provider.connection, //@ts-ignore wallet: ownerWallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: bankIndexes, oracleInfos, accountSubscription: accountLoader ? { type: 'polling', accountLoader, } : { type: 'websocket', }, }); // await driftClient1.initialize(usdcMint.publicKey, false); await driftClient1.subscribe(); userUSDCAccounts.push(newUserAcct); driftClients.push(driftClient1); // var last_idx = userUSDCAccounts.length - 1; // try { [, userAccountPublicKey] = await driftClient1.initializeUserAccountAndDepositCollateral( // marketPublicKey, usdcAmount, newUserAcct.publicKey ); // const userAccount = 0; const userAccount = new User({ driftClient: driftClient1, userAccountPublicKey: await driftClient1.getUserAccountPublicKey(), }); await userAccount.subscribe(); userAccountInfos.push(userAccount); // } catch (e) { // assert(true); // } user_keys.push(userAccountPublicKey); } return [userUSDCAccounts, user_keys, driftClients, userAccountInfos]; } const empty32Buffer = buffer.Buffer.alloc(32); const PKorNull = (data) => data.equals(empty32Buffer) ? null : new anchor.web3.PublicKey(data); export const createPriceFeed = async ({ oracleProgram, initPrice, confidence = undefined, expo = -4, }: { oracleProgram: Program; initPrice: number; confidence?: number; expo?: number; }): Promise<PublicKey> => { const conf = new BN(confidence) || new BN((initPrice / 10) * 10 ** -expo); const collateralTokenFeed = new anchor.web3.Account(); await oracleProgram.rpc.initialize( new BN(initPrice * 10 ** -expo), expo, conf, { accounts: { price: collateralTokenFeed.publicKey }, signers: [collateralTokenFeed], instructions: [ anchor.web3.SystemProgram.createAccount({ fromPubkey: oracleProgram.provider.publicKey, newAccountPubkey: collateralTokenFeed.publicKey, space: 3312, lamports: await oracleProgram.provider.connection.getMinimumBalanceForRentExemption( 3312 ), programId: oracleProgram.programId, }), ], } ); return collateralTokenFeed.publicKey; }; export const setFeedPrice = async ( oracleProgram: Program, newPrice: number, priceFeed: PublicKey ) => { const info = await oracleProgram.provider.connection.getAccountInfo( priceFeed ); const data = parsePriceData(info.data); await oracleProgram.rpc.setPrice(new BN(newPrice * 10 ** -data.exponent), { accounts: { price: priceFeed }, }); }; export const setFeedTwap = async ( oracleProgram: Program, newTwap: number, priceFeed: PublicKey ) => { const info = await oracleProgram.provider.connection.getAccountInfo( priceFeed ); const data = parsePriceData(info.data); await oracleProgram.rpc.setTwap(new BN(newTwap * 10 ** -data.exponent), { accounts: { price: priceFeed }, }); }; export const getFeedData = async ( oracleProgram: Program, priceFeed: PublicKey ) => { const info = await oracleProgram.provider.connection.getAccountInfo( priceFeed ); return parsePriceData(info.data); }; export const getOraclePriceData = async ( oracleProgram: Program, priceFeed: PublicKey ): Promise<OraclePriceData> => { const info = await oracleProgram.provider.connection.getAccountInfo( priceFeed ); const interData = parsePriceData(info.data); const oraclePriceData: OraclePriceData = { price: new BN(interData.price * PRICE_PRECISION.toNumber()), slot: new BN(interData.currentSlot.toString()), confidence: new BN(interData.confidence * PRICE_PRECISION.toNumber()), hasSufficientNumberOfDataPoints: true, }; return oraclePriceData; }; // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L758 const ERR_BUFFER_OUT_OF_BOUNDS = () => new Error('Attempt to access memory outside buffer bounds'); // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L968 const ERR_INVALID_ARG_TYPE = (name, expected, actual) => new Error( `The "${name}" argument must be of type ${expected}. Received ${actual}` ); // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L1262 const ERR_OUT_OF_RANGE = (str, range, received) => new Error( `The value of "${str} is out of range. It must be ${range}. Received ${received}` ); // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/validators.js#L127-L130 function validateNumber(value, name) { if (typeof value !== 'number') throw ERR_INVALID_ARG_TYPE(name, 'number', value); } // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/buffer.js#L68-L80 function boundsError(value, length) { if (Math.floor(value) !== value) { validateNumber(value, 'offset'); throw ERR_OUT_OF_RANGE('offset', 'an integer', value); } if (length < 0) throw ERR_BUFFER_OUT_OF_BOUNDS(); throw ERR_OUT_OF_RANGE('offset', `>= 0 and <= ${length}`, value); } function readBigInt64LE(buffer, offset = 0) { validateNumber(offset, 'offset'); const first = buffer[offset]; const last = buffer[offset + 7]; if (first === undefined || last === undefined) boundsError(offset, buffer.length - 8); const val = buffer[offset + 4] + buffer[offset + 5] * 2 ** 8 + buffer[offset + 6] * 2 ** 16 + (last << 24); // Overflow return ( (BigInt(val) << BigInt(32)) + BigInt( first + buffer[++offset] * 2 ** 8 + buffer[++offset] * 2 ** 16 + buffer[++offset] * 2 ** 24 ) ); } // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/buffer.js#L89-L107 function readBigUInt64LE(buffer, offset = 0) { validateNumber(offset, 'offset'); const first = buffer[offset]; const last = buffer[offset + 7]; if (first === undefined || last === undefined) boundsError(offset, buffer.length - 8); const lo = first + buffer[++offset] * 2 ** 8 + buffer[++offset] * 2 ** 16 + buffer[++offset] * 2 ** 24; const hi = buffer[++offset] + buffer[++offset] * 2 ** 8 + buffer[++offset] * 2 ** 16 + last * 2 ** 24; return BigInt(lo) + (BigInt(hi) << BigInt(32)); // tslint:disable-line:no-bitwise } const parsePriceData = (data) => { // Pyth magic number. const magic = data.readUInt32LE(0); // Program version. const version = data.readUInt32LE(4); // Account type. const type = data.readUInt32LE(8); // Price account size. const size = data.readUInt32LE(12); // Price or calculation type. const priceType = data.readUInt32LE(16); // Price exponent. const exponent = data.readInt32LE(20); // Number of component prices. const numComponentPrices = data.readUInt32LE(24); // unused // const unused = accountInfo.data.readUInt32LE(28) // Currently accumulating price slot. const currentSlot = readBigUInt64LE(data, 32); // Valid on-chain slot of aggregate price. const validSlot = readBigUInt64LE(data, 40); // Time-weighted average price. const twapComponent = readBigInt64LE(data, 48); const twap = Number(twapComponent) * 10 ** exponent; // Annualized price volatility. const avolComponent = readBigUInt64LE(data, 56); const avol = Number(avolComponent) * 10 ** exponent; // Space for future derived values. const drv0Component = readBigInt64LE(data, 64); const drv0 = Number(drv0Component) * 10 ** exponent; const drv1Component = readBigInt64LE(data, 72); const drv1 = Number(drv1Component) * 10 ** exponent; const drv2Component = readBigInt64LE(data, 80); const drv2 = Number(drv2Component) * 10 ** exponent; const drv3Component = readBigInt64LE(data, 88); const drv3 = Number(drv3Component) * 10 ** exponent; const drv4Component = readBigInt64LE(data, 96); const drv4 = Number(drv4Component) * 10 ** exponent; const drv5Component = readBigInt64LE(data, 104); const drv5 = Number(drv5Component) * 10 ** exponent; // Product id / reference account. const productAccountKey = new anchor.web3.PublicKey(data.slice(112, 144)); // Next price account in list. const nextPriceAccountKey = PKorNull(data.slice(144, 176)); // Aggregate price updater. const aggregatePriceUpdaterAccountKey = new anchor.web3.PublicKey( data.slice(176, 208) ); const aggregatePriceInfo = parsePriceInfo(data.slice(208, 240), exponent); // Price components - up to 32. const priceComponents = []; let offset = 240; let shouldContinue = true; while (offset < data.length && shouldContinue) { const publisher = PKorNull(data.slice(offset, offset + 32)); offset += 32; if (publisher) { const aggregate = parsePriceInfo( data.slice(offset, offset + 32), exponent ); offset += 32; const latest = parsePriceInfo(data.slice(offset, offset + 32), exponent); offset += 32; priceComponents.push({ publisher, aggregate, latest }); } else { shouldContinue = false; } } return Object.assign( Object.assign( { magic, version, type, size, priceType, exponent, numComponentPrices, currentSlot, validSlot, twapComponent, twap, avolComponent, avol, drv0Component, drv0, drv1Component, drv1, drv2Component, drv2, drv3Component, drv3, drv4Component, drv4, drv5Component, drv5, productAccountKey, nextPriceAccountKey, aggregatePriceUpdaterAccountKey, }, aggregatePriceInfo ), { priceComponents } ); }; const _parseProductData = (data) => { // Pyth magic number. const magic = data.readUInt32LE(0); // Program version. const version = data.readUInt32LE(4); // Account type. const type = data.readUInt32LE(8); // Price account size. const size = data.readUInt32LE(12); // First price account in list. const priceAccountBytes = data.slice(16, 48); const priceAccountKey = new anchor.web3.PublicKey(priceAccountBytes); const product = {}; let idx = 48; while (idx < data.length) { const keyLength = data[idx]; idx++; if (keyLength) { const key = data.slice(idx, idx + keyLength).toString(); idx += keyLength; const valueLength = data[idx]; idx++; const value = data.slice(idx, idx + valueLength).toString(); idx += valueLength; product[key] = value; } } return { magic, version, type, size, priceAccountKey, product }; }; const parsePriceInfo = (data, exponent) => { // Aggregate price. const priceComponent = data.readBigUInt64LE(0); const price = Number(priceComponent) * 10 ** exponent; // Aggregate confidence. const confidenceComponent = data.readBigUInt64LE(8); const confidence = Number(confidenceComponent) * 10 ** exponent; // Aggregate status. const status = data.readUInt32LE(16); // Aggregate corporate action. const corporateAction = data.readUInt32LE(20); // Aggregate publish slot. const publishSlot = data.readBigUInt64LE(24); return { priceComponent, price, confidenceComponent, confidence, status, corporateAction, publishSlot, }; }; export function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } export async function getTokenAmountAsBN( connection: Connection, tokenAccount: PublicKey ): Promise<BN> { return new BN( (await connection.getTokenAccountBalance(tokenAccount)).value.amount ); } export async function initializeQuoteSpotMarket( admin: TestClient, usdcMint: PublicKey ): Promise<void> { const optimalUtilization = SPOT_MARKET_RATE_PRECISION.div( new BN(2) ).toNumber(); // 50% utilization const optimalRate = SPOT_MARKET_RATE_PRECISION.toNumber(); const maxRate = SPOT_MARKET_RATE_PRECISION.toNumber(); const initialAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const initialLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const maintenanceLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.toNumber(); const imfFactor = 0; const marketIndex = admin.getStateAccount().numberOfSpotMarkets; await admin.initializeSpotMarket( usdcMint, optimalUtilization, optimalRate, maxRate, PublicKey.default, OracleSource.QUOTE_ASSET, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight, imfFactor ); await admin.updateWithdrawGuardThreshold( marketIndex, new BN(10 ** 10).mul(QUOTE_PRECISION) ); } export async function initializeSolSpotMarket( admin: TestClient, solOracle: PublicKey, solMint = NATIVE_MINT ): Promise<string> { const optimalUtilization = SPOT_MARKET_RATE_PRECISION.div( new BN(2) ).toNumber(); // 50% utilization const optimalRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(20)).toNumber(); // 2000% APR const maxRate = SPOT_MARKET_RATE_PRECISION.mul(new BN(50)).toNumber(); // 5000% APR const initialAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(8)) .div(new BN(10)) .toNumber(); const maintenanceAssetWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(9)) .div(new BN(10)) .toNumber(); const initialLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.mul(new BN(12)) .div(new BN(10)) .toNumber(); const maintenanceLiabilityWeight = SPOT_MARKET_WEIGHT_PRECISION.mul( new BN(11) ) .div(new BN(10)) .toNumber(); const marketIndex = admin.getStateAccount().numberOfSpotMarkets; const txSig = await admin.initializeSpotMarket( solMint, optimalUtilization, optimalRate, maxRate, solOracle, OracleSource.PYTH, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight ); await admin.updateWithdrawGuardThreshold( marketIndex, new BN(10 ** 10).mul(QUOTE_PRECISION) ); return txSig; }
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/stopLimits.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair, PublicKey, Transaction } from '@solana/web3.js'; import { TestClient, BN, PRICE_PRECISION, PositionDirection, User, Wallet, getMarketOrderParams, OrderTriggerCondition, getTriggerLimitOrderParams, EventSubscriber, MarketStatus, } from '../sdk/src'; import { initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, } from './testHelpers'; import { AMM_RESERVE_PRECISION, OracleSource, ZERO, isVariant } from '../sdk'; import { createAssociatedTokenAccountIdempotentInstruction, createMintToInstruction, getAssociatedTokenAddressSync, } from '@solana/spl-token'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('stop limit', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let driftClientUser: User; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let userAccountPublicKey: PublicKey; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(100000); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); let discountMint: PublicKey; const fillerKeyPair = new Keypair(); let fillerUSDCAccount: Keypair; let fillerDriftClient: TestClient; let fillerUser: User; const marketIndex = 0; let solUsd; let btcUsd; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); btcUsd = await mockOracleNoProgram(bankrunContextWrapper, 60000); const marketIndexes = [marketIndex]; const spotMarketIndexes = [0]; const oracleInfos = [ { publicKey: solUsd, source: OracleSource.PYTH, }, { publicKey: btcUsd, source: OracleSource.PYTH, }, ]; driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(60 * 60); // 1 HOUR await driftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await driftClient.updatePerpMarketStatus(0, MarketStatus.ACTIVE); await driftClient.initializePerpMarket( 1, btcUsd, ammInitialBaseAssetReserve.div(new BN(3000)), ammInitialQuoteAssetReserve.div(new BN(3000)), periodicity, new BN(60000000) // btc-ish price level ); await driftClient.updatePerpMarketStatus(1, MarketStatus.ACTIVE); [, userAccountPublicKey] = await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); driftClientUser = new User({ driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClientUser.subscribe(); const discountMintKeypair = await mockUSDCMint(bankrunContextWrapper); discountMint = discountMintKeypair.publicKey; await driftClient.updateDiscountMint(discountMint); const discountMintAta = getAssociatedTokenAddressSync( discountMint, bankrunContextWrapper.provider.wallet.publicKey ); const ix = createAssociatedTokenAccountIdempotentInstruction( bankrunContextWrapper.context.payer.publicKey, discountMintAta, bankrunContextWrapper.provider.wallet.publicKey, discountMint ); const mintToIx = createMintToInstruction( discountMint, discountMintAta, bankrunContextWrapper.provider.wallet.publicKey, 1000 * 10 ** 6 ); await bankrunContextWrapper.sendTransaction( new Transaction().add(ix, mintToIx) ); await bankrunContextWrapper.fundKeypair(fillerKeyPair, 10 ** 9); fillerUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, fillerKeyPair.publicKey ); fillerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(fillerKeyPair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClient.subscribe(); await fillerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, fillerUSDCAccount.publicKey ); fillerUser = new User({ driftClient: fillerDriftClient, userAccountPublicKey: await fillerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerUser.subscribe(); }); after(async () => { await driftClient.unsubscribe(); await driftClientUser.unsubscribe(); await fillerUser.unsubscribe(); await fillerDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('Fill stop limit short order', async () => { const direction = PositionDirection.SHORT; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const triggerPrice = PRICE_PRECISION; const limitPrice = PRICE_PRECISION.sub( driftClient.getPerpMarketAccount(marketIndex).amm.orderTickSize ); const triggerCondition = OrderTriggerCondition.ABOVE; await driftClient.placeAndTakePerpOrder( getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, }) ); const orderParams = getTriggerLimitOrderParams({ marketIndex, direction, baseAssetAmount, price: limitPrice, triggerPrice, triggerCondition, }); await driftClient.placePerpOrder(orderParams); const orderId = 2; const orderIndex = new BN(0); await driftClientUser.fetchAccounts(); let order = driftClientUser.getOrder(orderId); await setFeedPriceNoProgram(bankrunContextWrapper, 1.01, solUsd); await driftClient.moveAmmToPrice( marketIndex, new BN(1.01 * PRICE_PRECISION.toNumber()) ); await driftClient.triggerOrder( userAccountPublicKey, driftClientUser.getUserAccount(), order ); await fillerDriftClient.fillPerpOrder( userAccountPublicKey, driftClientUser.getUserAccount(), order ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); await fillerUser.fetchAccounts(); order = driftClientUser.getUserAccount().orders[orderIndex.toString()]; assert(order.baseAssetAmount.eq(new BN(0))); assert(order.price.eq(new BN(0))); assert(order.marketIndex === 0); assert(isVariant(order.status, 'init')); assert(isVariant(order.direction, 'long')); const firstPosition = driftClientUser.getUserAccount().perpPositions[0]; const expectedBaseAssetAmount = new BN(0); assert(firstPosition.baseAssetAmount.eq(expectedBaseAssetAmount)); const expectedQuoteAssetAmount = new BN(0); assert(firstPosition.quoteBreakEvenAmount.eq(expectedQuoteAssetAmount)); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderRecord.baseAssetAmountFilled.eq(baseAssetAmount)); const expectedTradeQuoteAssetAmount = new BN(1010000); assert.ok( orderRecord.quoteAssetAmountFilled.eq(expectedTradeQuoteAssetAmount) ); const expectedOrderId = 2; const expectedFillRecordId = new BN(2); assert(orderRecord.ts.gt(ZERO)); assert(orderRecord.takerOrderId === expectedOrderId); assert(isVariant(orderRecord.action, 'fill')); assert( orderRecord.taker.equals(await driftClientUser.getUserAccountPublicKey()) ); assert( orderRecord.filler.equals(await fillerUser.getUserAccountPublicKey()) ); assert(orderRecord.fillRecordId.eq(expectedFillRecordId)); }); it('Fill stop limit long order', async () => { const direction = PositionDirection.LONG; const baseAssetAmount = new BN(AMM_RESERVE_PRECISION); const triggerPrice = PRICE_PRECISION; const limitPrice = PRICE_PRECISION.add( driftClient.getPerpMarketAccount(marketIndex).amm.orderTickSize ); const triggerCondition = OrderTriggerCondition.BELOW; await driftClient.placeAndTakePerpOrder( getMarketOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, }) ); const orderParams = getTriggerLimitOrderParams({ marketIndex, direction, baseAssetAmount, price: limitPrice, triggerPrice, triggerCondition, }); await driftClient.placePerpOrder(orderParams); const orderId = 4; const orderIndex = new BN(0); driftClientUser.getUserAccount(); let order = driftClientUser.getOrder(orderId); await setFeedPriceNoProgram(bankrunContextWrapper, 0.99, solUsd); await driftClient.moveAmmToPrice( marketIndex, new BN(0.99 * PRICE_PRECISION.toNumber()) ); await driftClient.triggerOrder( userAccountPublicKey, driftClientUser.getUserAccount(), order ); await fillerDriftClient.fillPerpOrder( userAccountPublicKey, driftClientUser.getUserAccount(), order ); await driftClient.fetchAccounts(); await driftClientUser.fetchAccounts(); await fillerUser.fetchAccounts(); order = driftClientUser.getUserAccount().orders[orderIndex.toString()]; assert(order.baseAssetAmount.eq(new BN(0))); assert(order.price.eq(new BN(0))); assert(order.marketIndex === 0); assert(isVariant(order.status, 'init')); assert(isVariant(order.direction, 'long')); const firstPosition = driftClientUser.getUserAccount().perpPositions[0]; const expectedBaseAssetAmount = new BN(0); assert(firstPosition.baseAssetAmount.eq(expectedBaseAssetAmount)); const expectedQuoteAssetAmount = new BN(0); assert(firstPosition.quoteBreakEvenAmount.eq(expectedQuoteAssetAmount)); const expectedTradeQuoteAssetAmount = new BN(990001); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; const expectedOrderId = 4; const expectedFillRecord = new BN(4); assert(orderRecord.ts.gt(ZERO)); assert(orderRecord.takerOrderId === expectedOrderId); assert(isVariant(orderRecord.action, 'fill')); assert( orderRecord.taker.equals(await driftClientUser.getUserAccountPublicKey()) ); assert( orderRecord.filler.equals(await fillerUser.getUserAccountPublicKey()) ); assert(orderRecord.baseAssetAmountFilled.eq(baseAssetAmount)); assert( orderRecord.quoteAssetAmountFilled.eq(expectedTradeQuoteAssetAmount) ); assert(orderRecord.fillRecordId.eq(expectedFillRecord)); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/marketOrderBaseAssetAmount.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { BN, getMarketOrderParams, OracleSource, ZERO } from '../sdk'; import { Program } from '@coral-xyz/anchor'; import { PublicKey } from '@solana/web3.js'; import { TestClient, PositionDirection, EventSubscriber } from '../sdk/src'; import { mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, mockOracleNoProgram, } from './testHelpers'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('market orders', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let userAccountPublicKey: PublicKey; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(100000); const ammInitialQuoteAssetAmount = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetAmount = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); let marketIndexes; let spotMarketIndexes; let oracleInfos; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection, chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); const solUsd = await mockOracleNoProgram(bankrunContextWrapper, 1); marketIndexes = [0]; spotMarketIndexes = [0]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(60 * 60); // 1 HOUR await driftClient.initializePerpMarket( 0, solUsd, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity ); [, userAccountPublicKey] = await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); }); after(async () => { await driftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('Long from 0 position', async () => { const marketIndex = 0; const baseAssetAmount = new BN(48000000000); const orderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, }); await driftClient.placeAndTakePerpOrder(orderParams); const txSig = await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); bankrunContextWrapper.printTxLogs(txSig); console.log( driftClient.getQuoteAssetTokenAmount().toString(), driftClient .getUserStats() .getAccountAndSlot() .data.fees.totalFeePaid.toString(), driftClient .getUserAccount() .perpPositions[0].quoteBreakEvenAmount.toString() ); assert(driftClient.getQuoteAssetTokenAmount().eq(new BN(9951998))); assert( driftClient .getUserStats() .getAccountAndSlot() .data.fees.totalFeePaid.eq(new BN(48001)) ); console.log( driftClient .getUserAccount() .perpPositions[0].quoteBreakEvenAmount.toString() ); assert.ok( driftClient .getUserAccount() .perpPositions[0].quoteEntryAmount.eq(new BN(-48000001)) ); assert.ok( driftClient .getUserAccount() .perpPositions[0].quoteBreakEvenAmount.eq(new BN(-48048002)) ); console.log(driftClient.getUserAccount().perpPositions[0].baseAssetAmount); assert.ok( driftClient .getUserAccount() .perpPositions[0].baseAssetAmount.eq(baseAssetAmount) ); const market = driftClient.getPerpMarketAccount(0); assert.ok(market.amm.baseAssetAmountWithAmm.eq(new BN(48000000000))); assert.ok(market.amm.baseAssetAmountLong.eq(new BN(48000000000))); assert.ok(market.amm.baseAssetAmountShort.eq(ZERO)); assert.ok(market.numberOfUsersWithBase === 1); assert.ok(market.amm.totalFee.eq(new BN(48001))); assert.ok(market.amm.totalFeeMinusDistributions.eq(new BN(48001))); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderRecord.taker.equals(userAccountPublicKey)); assert.ok(orderRecord.fillRecordId.eq(new BN(1))); assert.ok(orderRecord.baseAssetAmountFilled.eq(new BN(48000000000))); assert.ok(orderRecord.quoteAssetAmountFilled.eq(new BN(48000001))); assert.ok(orderRecord.marketIndex === marketIndex); }); it('Reduce long position', async () => { const marketIndex = 0; const baseAssetAmount = new BN(24000000000); const orderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, }); const txSig = await driftClient.placeAndTakePerpOrder(orderParams); bankrunContextWrapper.printTxLogs(txSig); await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); console.log( driftClient .getUserAccount() .perpPositions[0].quoteBreakEvenAmount.toString() ); assert.ok( driftClient .getUserAccount() .perpPositions[0].quoteEntryAmount.eq(new BN(-24000001)) ); assert.ok( driftClient .getUserAccount() .perpPositions[0].quoteBreakEvenAmount.eq(new BN(-24048001)) ); console.log( driftClient.getUserAccount().perpPositions[0].baseAssetAmount.toNumber() ); assert.ok( driftClient .getUserAccount() .perpPositions[0].baseAssetAmount.eq(new BN(24000000000)) ); console.log(driftClient.getQuoteAssetTokenAmount().toString()); assert.ok(driftClient.getQuoteAssetTokenAmount().eq(new BN(9927998))); assert( driftClient .getUserStats() .getAccount() .fees.totalFeePaid.eq(new BN(72001)) ); const market = driftClient.getPerpMarketAccount(0); console.log(market.amm.baseAssetAmountWithAmm.toString()); assert.ok(market.amm.baseAssetAmountWithAmm.eq(new BN(24000000000))); assert.ok(market.amm.baseAssetAmountLong.eq(new BN(24000000000))); assert.ok(market.amm.baseAssetAmountShort.eq(ZERO)); assert.ok(market.numberOfUsersWithBase === 1); assert.ok(market.amm.totalFee.eq(new BN(72001))); assert.ok(market.amm.totalFeeMinusDistributions.eq(new BN(72001))); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderRecord.taker.equals(userAccountPublicKey)); assert.ok(orderRecord.fillRecordId.eq(new BN(2))); console.log(orderRecord.baseAssetAmountFilled.toNumber()); assert.ok(orderRecord.baseAssetAmountFilled.eq(new BN(24000000000))); assert.ok(orderRecord.quoteAssetAmountFilled.eq(new BN(24000000))); assert.ok(orderRecord.marketIndex === 0); }); it('Reverse long position', async () => { const marketIndex = 0; const baseAssetAmount = new BN(48000000000); const orderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, }); await driftClient.placeAndTakePerpOrder(orderParams); await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); await driftClient.fetchAccounts(); console.log(driftClient.getQuoteAssetTokenAmount().toString()); assert.ok(driftClient.getQuoteAssetTokenAmount().eq(new BN(9879998))); assert( driftClient .getUserStats() .getAccount() .fees.totalFeePaid.eq(new BN(120001)) ); console.log( driftClient .getUserAccount() .perpPositions[0].quoteBreakEvenAmount.toString() ); assert.ok( driftClient .getUserAccount() .perpPositions[0].quoteEntryAmount.eq(new BN(24000000)) ); assert.ok( driftClient .getUserAccount() .perpPositions[0].quoteBreakEvenAmount.eq(new BN(23952000)) ); console.log( driftClient.getUserAccount().perpPositions[0].baseAssetAmount.toString() ); assert.ok( driftClient .getUserAccount() .perpPositions[0].baseAssetAmount.eq(new BN(-24000000000)) ); const market = driftClient.getPerpMarketAccount(0); assert.ok(market.amm.baseAssetAmountWithAmm.eq(new BN(-24000000000))); assert.ok(market.amm.baseAssetAmountLong.eq(ZERO)); assert.ok(market.amm.baseAssetAmountShort.eq(new BN(-24000000000))); assert.ok(market.numberOfUsersWithBase === 1); assert.ok(market.amm.totalFee.eq(new BN(120001))); assert.ok(market.amm.totalFeeMinusDistributions.eq(new BN(120001))); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderRecord.taker.equals(userAccountPublicKey)); assert.ok(orderRecord.fillRecordId.eq(new BN(3))); console.log(orderRecord.baseAssetAmountFilled.toNumber()); assert.ok(orderRecord.baseAssetAmountFilled.eq(new BN(48000000000))); console.log(orderRecord.quoteAssetAmountFilled.toString()); assert.ok(orderRecord.quoteAssetAmountFilled.eq(new BN(48000000))); assert.ok(orderRecord.marketIndex === 0); }); it('Close position', async () => { const marketIndex = 0; const baseAssetAmount = new BN(24000000000); const orderParams = getMarketOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, reduceOnly: true, }); await driftClient.placeAndTakePerpOrder(orderParams); await driftClient.settlePNL( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), marketIndex ); console.log( driftClient .getUserAccount() .perpPositions[0].quoteBreakEvenAmount.toString() ); assert.ok( driftClient .getUserAccount() .perpPositions[0].quoteBreakEvenAmount.eq(new BN(0)) ); assert.ok( driftClient .getUserAccount() .perpPositions[0].baseAssetAmount.eq(new BN(0)) ); console.log(driftClient.getQuoteAssetTokenAmount().toString()); assert.ok(driftClient.getQuoteAssetTokenAmount().eq(new BN(9855998))); assert( driftClient .getUserStats() .getAccount() .fees.totalFeePaid.eq(new BN(144001)) ); const market = driftClient.getPerpMarketAccount(0); assert.ok(market.amm.baseAssetAmountWithAmm.eq(new BN(0))); assert.ok(market.amm.totalFee.eq(new BN(144001))); assert.ok(market.amm.totalFeeMinusDistributions.eq(new BN(144001))); const orderRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert.ok(orderRecord.taker.equals(userAccountPublicKey)); assert.ok(orderRecord.fillRecordId.eq(new BN(4))); assert.ok(orderRecord.baseAssetAmountFilled.eq(new BN(24000000000))); assert.ok(orderRecord.quoteAssetAmountFilled.eq(new BN(24000000))); assert.ok(orderRecord.marketIndex === 0); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/liquidatePerpWithFill.ts
import * as anchor from '@coral-xyz/anchor'; import { Program } from '@coral-xyz/anchor'; import { BASE_PRECISION, BN, EventSubscriber, isVariant, LIQUIDATION_PCT_PRECISION, OracleGuardRails, OracleSource, PositionDirection, PRICE_PRECISION, QUOTE_PRECISION, TestClient, Wallet, } from '../sdk/src'; import { assert } from 'chai'; import { Keypair, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js'; import { createUserWithUSDCAccount, initializeQuoteSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, setFeedPriceNoProgram, } from './testHelpers'; import { OrderType, PERCENTAGE_PRECISION, PerpOperation } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('liquidate perp (no open orders)', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; const liquidatorKeyPair = new Keypair(); let liquidatorUSDCAccount: Keypair; let liquidatorDriftClient: TestClient; let makerDriftClient: TestClient; let makerUSDCAccount: PublicKey; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); const makerUsdcAmount = new BN(1000 * 10 ** 6); let oracle: PublicKey; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), //@ts-ignore chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); oracle = await mockOracleNoProgram(bankrunContextWrapper, 1); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [ { publicKey: oracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await driftClient.updateInitialPctToLiquidate( LIQUIDATION_PCT_PRECISION.toNumber() ); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); const oracleGuardRails: OracleGuardRails = { priceDivergence: { markOraclePercentDivergence: PERCENTAGE_PRECISION.muln(100), oracleTwap5MinPercentDivergence: PERCENTAGE_PRECISION.muln(100), }, validity: { slotsBeforeStaleForAmm: new BN(100), slotsBeforeStaleForMargin: new BN(100), confidenceIntervalMaxSize: new BN(100000), tooVolatileRatio: new BN(11), // allow 11x change }, }; await driftClient.updateOracleGuardRails(oracleGuardRails); const periodicity = new BN(0); await driftClient.initializePerpMarket( 0, oracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); await driftClient.openPosition( PositionDirection.LONG, new BN(175).mul(BASE_PRECISION).div(new BN(10)), // 17.5 SOL 0, new BN(0) ); bankrunContextWrapper.fundKeypair(liquidatorKeyPair, LAMPORTS_PER_SOL); liquidatorUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, liquidatorKeyPair.publicKey ); liquidatorDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(liquidatorKeyPair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [ { publicKey: oracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await liquidatorDriftClient.subscribe(); await liquidatorDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, liquidatorUSDCAccount.publicKey ); [makerDriftClient, makerUSDCAccount] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, makerUsdcAmount, [0], [0], [ { publicKey: oracle, source: OracleSource.PYTH, }, ], bulkAccountLoader ); await makerDriftClient.deposit(makerUsdcAmount, 0, makerUSDCAccount); }); after(async () => { await driftClient.unsubscribe(); await liquidatorDriftClient.unsubscribe(); await makerDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('liquidate', async () => { await setFeedPriceNoProgram(bankrunContextWrapper, 0.1, oracle); await driftClient.updatePerpMarketPausedOperations( 0, PerpOperation.AMM_FILL ); try { const failToPlaceTxSig = await driftClient.placePerpOrder({ direction: PositionDirection.SHORT, baseAssetAmount: BASE_PRECISION, price: PRICE_PRECISION.divn(10), orderType: OrderType.LIMIT, reduceOnly: true, marketIndex: 0, }); bankrunContextWrapper.connection.printTxLogs(failToPlaceTxSig); throw new Error('Expected placePerpOrder to throw an error'); } catch (error) { if ( error.message !== 'Error processing Instruction 1: custom program error: 0x1773' ) { throw new Error(`Unexpected error message: ${error.message}`); } } await makerDriftClient.placePerpOrder({ direction: PositionDirection.LONG, baseAssetAmount: new BN(175).mul(BASE_PRECISION), price: PRICE_PRECISION.divn(10), orderType: OrderType.LIMIT, marketIndex: 0, }); const makerInfos = [ { maker: await makerDriftClient.getUserAccountPublicKey(), makerStats: makerDriftClient.getUserStatsAccountPublicKey(), makerUserAccount: makerDriftClient.getUserAccount(), }, ]; const txSig = await liquidatorDriftClient.liquidatePerpWithFill( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0, makerInfos ); bankrunContextWrapper.connection.printTxLogs(txSig); for (let i = 0; i < 32; i++) { assert(isVariant(driftClient.getUserAccount().orders[i].status, 'init')); } assert( liquidatorDriftClient .getUserAccount() .perpPositions[0].quoteAssetAmount.eq(new BN(175)) ); assert( driftClient .getUserAccount() .perpPositions[0].baseAssetAmount.eq(new BN(0)) ); assert( driftClient .getUserAccount() .perpPositions[0].quoteAssetAmount.eq(new BN(-15769403)) ); assert( liquidatorDriftClient.getPerpMarketAccount(0).ifLiquidationFee === 10000 ); assert( makerDriftClient .getUserAccount() .perpPositions[0].baseAssetAmount.eq(new BN(17500000000)) ); assert( makerDriftClient .getUserAccount() .perpPositions[0].quoteAssetAmount.eq(new BN(-1749650)) ); assert( liquidatorDriftClient.getPerpMarketAccount(0).ifLiquidationFee === 10000 ); await makerDriftClient.liquidatePerpPnlForDeposit( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0, 0, QUOTE_PRECISION.muln(20) ); await makerDriftClient.resolvePerpBankruptcy( await driftClient.getUserAccountPublicKey(), driftClient.getUserAccount(), 0 ); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/fillSpot.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js'; import { TestClient, BN, PRICE_PRECISION, PositionDirection, User, Wallet, BASE_PRECISION, getLimitOrderParams, OracleSource, } from '../sdk/src'; import { initializeQuoteSpotMarket, initializeSolSpotMarket, mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, sleep, } from './testHelpers'; import { MARGIN_PRECISION, PostOnlyParams, ReferrerInfo, ZERO } from '../sdk'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('place and fill spot order', () => { const chProgram = anchor.workspace.Drift as Program; let fillerDriftClient: TestClient; let fillerDriftClientUser: User; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let userUSDCAccount; const usdcAmount = new BN(100 * 10 ** 6); let solUsd; let marketIndexes; let spotMarketIndexes; let oracleInfos; const createTestClient = async ( referrerInfo?: ReferrerInfo ): Promise<TestClient> => { const keypair = new Keypair(); await bankrunContextWrapper.fundKeypair(keypair, 10 ** 9); await sleep(1000); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, keypair.publicKey ); const driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey, 0, 0, undefined, undefined, referrerInfo ); await driftClient.updateUserMarginTradingEnabled([ { subAccountId: 0, marginTradingEnabled: true }, ]); return driftClient; }; before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solUsd = await mockOracleNoProgram(bankrunContextWrapper, 32.821); marketIndexes = []; spotMarketIndexes = [0, 1]; oracleInfos = [{ publicKey: solUsd, source: OracleSource.PYTH }]; fillerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClient.initialize(usdcMint.publicKey, true); await fillerDriftClient.subscribe(); await initializeQuoteSpotMarket(fillerDriftClient, usdcMint.publicKey); await initializeSolSpotMarket(fillerDriftClient, solUsd); await fillerDriftClient.updatePerpAuctionDuration(new BN(0)); await fillerDriftClient.updateSpotMarketMarginWeights( 1, MARGIN_PRECISION.toNumber() * 0.75, MARGIN_PRECISION.toNumber() * 0.8, MARGIN_PRECISION.toNumber() * 1.25, MARGIN_PRECISION.toNumber() * 1.2 ); await fillerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const oneSol = new BN(LAMPORTS_PER_SOL); await fillerDriftClient.deposit( oneSol, 1, bankrunContextWrapper.provider.wallet.publicKey ); fillerDriftClientUser = new User({ driftClient: fillerDriftClient, userAccountPublicKey: await fillerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await fillerDriftClientUser.subscribe(); }); after(async () => { await fillerDriftClient.unsubscribe(); await fillerDriftClientUser.unsubscribe(); }); it('fill via match', async () => { const takerDriftClient = await createTestClient({ referrer: fillerDriftClientUser.getUserAccount().authority, referrerStats: fillerDriftClient.getUserStatsAccountPublicKey(), }); const takerDriftClientUser = new User({ driftClient: takerDriftClient, userAccountPublicKey: await takerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await takerDriftClientUser.subscribe(); const makerDriftClient = await createTestClient(); const makerDriftClientUser = new User({ driftClient: makerDriftClient, userAccountPublicKey: await makerDriftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await makerDriftClientUser.subscribe(); const marketIndex = 1; const baseAssetAmount = BASE_PRECISION; await makerDriftClient.placeSpotOrder( getLimitOrderParams({ marketIndex, direction: PositionDirection.SHORT, baseAssetAmount, price: new BN(40).mul(PRICE_PRECISION), userOrderId: 2, postOnly: PostOnlyParams.NONE, }) ); await makerDriftClientUser.fetchAccounts(); assert(!makerDriftClientUser.getOrderByUserOrderId(2).postOnly); await takerDriftClient.placeSpotOrder( getLimitOrderParams({ marketIndex, direction: PositionDirection.LONG, baseAssetAmount, price: new BN(41).mul(PRICE_PRECISION), // auctionStartPrice: null, // auctionEndPrice: null, // auctionDuration: 0, userOrderId: 1, postOnly: PostOnlyParams.NONE, }) ); await takerDriftClientUser.fetchAccounts(); const takerOrder = takerDriftClientUser.getOrderByUserOrderId(1); assert(!takerOrder.postOnly); const fillTx = await fillerDriftClient.fillSpotOrder( takerDriftClientUser.getUserAccountPublicKey(), takerDriftClientUser.getUserAccount(), takerOrder, null, { maker: makerDriftClientUser.getUserAccountPublicKey(), makerStats: makerDriftClient.getUserStatsAccountPublicKey(), makerUserAccount: makerDriftClientUser.getUserAccount(), // order: makerDriftClientUser.getOrderByUserOrderId(2), }, { referrer: fillerDriftClientUser.getUserAccount().authority, referrerStats: fillerDriftClient.getUserStatsAccountPublicKey(), } ); bankrunContextWrapper.connection.printTxLogs(fillTx); // const makerUSDCAmount = makerDriftClient.getQuoteAssetTokenAmount(); // const makerSolAmount = makerDriftClient.getTokenAmount(1); // assert(makerUSDCAmount.eq(new BN(140008000))); // assert(makerSolAmount.eq(new BN(0))); // const takerUSDCAmount = takerDriftClient.getQuoteAssetTokenAmount(); // const takerSolAmount = takerDriftClient.getTokenAmount(1); // assert(takerUSDCAmount.eq(new BN(59960000))); // assert(takerSolAmount.eq(new BN(1000000000))); console.log(fillerDriftClient.getQuoteAssetTokenAmount().toNumber()); // successful fill assert(fillerDriftClient.getQuoteAssetTokenAmount().gt(ZERO)); await takerDriftClientUser.unsubscribe(); await takerDriftClient.unsubscribe(); await makerDriftClient.unsubscribe(); await makerDriftClientUser.unsubscribe(); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/cancelAllOrders.ts
import * as anchor from '@coral-xyz/anchor'; import { BASE_PRECISION, BN, getLimitOrderParams, OracleSource, TestClient, PRICE_PRECISION, PositionDirection, } from '../sdk/src'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, mockOracleNoProgram, } from './testHelpers'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; import { isVariant } from '../sdk'; describe('cancel all orders', () => { const chProgram = anchor.workspace.Drift as Program; let driftClient: TestClient; let bankrunContextWrapper: BankrunContextWrapper; let bulkAccountLoader: TestBulkAccountLoader; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); usdcMint = await mockUSDCMint(bankrunContextWrapper); userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); const oracle = await mockOracleNoProgram(bankrunContextWrapper, 1); driftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, perpMarketIndexes: [0], spotMarketIndexes: [0], subAccountIds: [], oracleInfos: [ { publicKey: oracle, source: OracleSource.PYTH, }, ], accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.initialize(usdcMint.publicKey, true); await driftClient.subscribe(); await initializeQuoteSpotMarket(driftClient, usdcMint.publicKey); await driftClient.updatePerpAuctionDuration(new BN(0)); const periodicity = new BN(0); await driftClient.initializePerpMarket( 0, oracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await driftClient.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); }); after(async () => { await driftClient.unsubscribe(); }); it('cancel all orders', async () => { for (let i = 0; i < 32; i++) { await driftClient.placePerpOrder( getLimitOrderParams({ baseAssetAmount: BASE_PRECISION, marketIndex: 0, direction: PositionDirection.LONG, price: PRICE_PRECISION, }) ); } await driftClient.cancelOrders(null, null, null); // await printTxLogs(connection, txSig); for (let i = 0; i < 32; i++) { assert(isVariant(driftClient.getUserAccount().orders[i].status, 'init')); } }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/tests/referrer.ts
import * as anchor from '@coral-xyz/anchor'; import { assert } from 'chai'; import { Program } from '@coral-xyz/anchor'; import { Keypair, PublicKey } from '@solana/web3.js'; import { TestClient, BN, OracleSource, EventSubscriber, Wallet, PRICE_PRECISION, ReferrerStatus, } from '../sdk/src'; import { mockOracleNoProgram, mockUSDCMint, mockUserUSDCAccount, initializeQuoteSpotMarket, createFundedKeyPair, createUserWithUSDCAccount, } from './testHelpers'; import { BASE_PRECISION, getMarketOrderParams, PEG_PRECISION, PositionDirection, } from '../sdk/src'; import { decodeName } from '../sdk/src/userName'; import { startAnchor } from 'solana-bankrun'; import { TestBulkAccountLoader } from '../sdk/src/accounts/testBulkAccountLoader'; import { BankrunContextWrapper } from '../sdk/src/bankrun/bankrunConnection'; describe('referrer', () => { const chProgram = anchor.workspace.Drift as Program; let referrerDriftClient: TestClient; let refereeKeyPair: Keypair; let refereeDriftClient: TestClient; let refereeUSDCAccount: Keypair; let fillerDriftClient: TestClient; let eventSubscriber: EventSubscriber; let bulkAccountLoader: TestBulkAccountLoader; let bankrunContextWrapper: BankrunContextWrapper; let usdcMint; let referrerUSDCAccount; let solOracle: PublicKey; // ammInvariant == k == x * y const ammReservePrecision = new BN(Math.sqrt(PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( ammReservePrecision ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( ammReservePrecision ); const usdcAmount = new BN(100 * 10 ** 6); before(async () => { const context = await startAnchor('', [], []); bankrunContextWrapper = new BankrunContextWrapper(context); bulkAccountLoader = new TestBulkAccountLoader( bankrunContextWrapper.connection, 'processed', 1 ); eventSubscriber = new EventSubscriber( bankrunContextWrapper.connection.toConnection(), chProgram ); await eventSubscriber.subscribe(); usdcMint = await mockUSDCMint(bankrunContextWrapper); referrerUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper ); solOracle = await mockOracleNoProgram(bankrunContextWrapper, 100); const marketIndexes = [0]; const spotMarketIndexes = [0]; const oracleInfos = [ { publicKey: solOracle, source: OracleSource.PYTH, }, ]; referrerDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: bankrunContextWrapper.provider.wallet, programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await referrerDriftClient.initialize(usdcMint.publicKey, true); await referrerDriftClient.subscribe(); await referrerDriftClient.updatePerpAuctionDuration(0); const periodicity = new BN(60 * 60); // 1 HOUR await referrerDriftClient.initializePerpMarket( 0, solOracle, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity, new BN(100).mul(PEG_PRECISION) ); await initializeQuoteSpotMarket(referrerDriftClient, usdcMint.publicKey); await referrerDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, referrerUSDCAccount.publicKey ); refereeKeyPair = await createFundedKeyPair(bankrunContextWrapper); refereeUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, bankrunContextWrapper, refereeKeyPair.publicKey ); refereeDriftClient = new TestClient({ connection: bankrunContextWrapper.connection.toConnection(), wallet: new Wallet(refereeKeyPair), programID: chProgram.programId, opts: { commitment: 'confirmed', }, activeSubAccountId: 0, perpMarketIndexes: marketIndexes, spotMarketIndexes: spotMarketIndexes, subAccountIds: [], oracleInfos, userStats: true, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await refereeDriftClient.subscribe(); [fillerDriftClient] = await createUserWithUSDCAccount( bankrunContextWrapper, usdcMint, chProgram, usdcAmount, marketIndexes, spotMarketIndexes, oracleInfos, bulkAccountLoader ); }); after(async () => { await referrerDriftClient.unsubscribe(); await refereeDriftClient.unsubscribe(); await fillerDriftClient.unsubscribe(); await eventSubscriber.unsubscribe(); }); it('initialize referrer name account', async () => { await referrerDriftClient.initializeReferrerName('crisp'); const referrerNameAccount = await referrerDriftClient.fetchReferrerNameAccount('crisp'); assert(decodeName(referrerNameAccount.name) === 'crisp'); assert(referrerNameAccount.authority.equals(referrerDriftClient.authority)); assert( referrerNameAccount.user.equals( await referrerDriftClient.getUserAccountPublicKey() ) ); }); it('initialize with referrer', async () => { const [txSig] = await refereeDriftClient.initializeUserAccountAndDepositCollateral( usdcAmount, refereeUSDCAccount.publicKey, 0, 0, 'crisp', undefined, { referrer: await referrerDriftClient.getUserAccountPublicKey(), referrerStats: referrerDriftClient.getUserStatsAccountPublicKey(), } ); await eventSubscriber.awaitTx(txSig); const newUserRecord = eventSubscriber.getEventsArray('NewUserRecord')[0]; assert( newUserRecord.referrer.equals( bankrunContextWrapper.provider.wallet.publicKey ) ); await refereeDriftClient.fetchAccounts(); const refereeStats = refereeDriftClient.getUserStats().getAccount(); assert( refereeStats.referrer.equals( bankrunContextWrapper.provider.wallet.publicKey ) ); assert((refereeStats.referrerStatus & ReferrerStatus.IsReferred) > 0); const referrerStats = referrerDriftClient.getUserStats().getAccount(); assert((referrerStats.referrerStatus & ReferrerStatus.IsReferrer) > 0); }); it('fill order', async () => { const txSig = await refereeDriftClient.placeAndTakePerpOrder( getMarketOrderParams({ baseAssetAmount: BASE_PRECISION, direction: PositionDirection.LONG, marketIndex: 0, }), undefined, refereeDriftClient.getUserStats().getReferrerInfo() ); await eventSubscriber.awaitTx(txSig); const eventRecord = eventSubscriber.getEventsArray('OrderActionRecord')[0]; assert(eventRecord.takerFee.eq(new BN(95001))); assert(eventRecord.referrerReward === 15000); await referrerDriftClient.fetchAccounts(); const referrerStats = referrerDriftClient.getUserStats().getAccount(); assert(referrerStats.fees.totalReferrerReward.eq(new BN(15000))); const referrerPosition = referrerDriftClient.getUser().getUserAccount() .perpPositions[0]; assert(referrerPosition.quoteAssetAmount.eq(new BN(15000))); const refereeStats = refereeDriftClient.getUserStats().getAccount(); assert(refereeStats.fees.totalRefereeDiscount.eq(new BN(5000))); const txSig2 = await refereeDriftClient.placeAndTakePerpOrder( getMarketOrderParams({ baseAssetAmount: BASE_PRECISION, direction: PositionDirection.SHORT, marketIndex: 0, }), undefined, refereeDriftClient.getUserStats().getReferrerInfo() ); bankrunContextWrapper.printTxLogs(txSig2); }); it('withdraw', async () => { const txSig = await refereeDriftClient.withdraw( usdcAmount.div(new BN(2)), 0, refereeUSDCAccount.publicKey ); await eventSubscriber.awaitTx(txSig); }); });
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/deploy-scripts/deploy-devnet.sh
#!/bin/sh anchor upgrade --program-id dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH --provider.cluster devnet --provider.wallet $SOLANA_PATH/$DEVNET_ADMIN target/deploy/drift.so
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/deploy-scripts/build-devnet.sh
#!/bin/sh anchor build -- --no-default-features
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/deploy-scripts/verified-build.sh
#!/bin/sh solana-verify build --library-name drift
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/cli/cli.ts
#!/usr/bin/env node import { Command, OptionValues, program } from 'commander'; const promptly = require('promptly'); const colors = require('colors'); import os from 'os'; import fs from 'fs'; import log from 'loglevel'; import { Admin, User, initialize, Markets, Wallet } from '@drift-labs/sdk'; import { Connection, Keypair, PublicKey } from '@solana/web3.js'; import { BN } from '@drift-labs/sdk'; import { ASSOCIATED_TOKEN_PROGRAM_ID, Token, TOKEN_PROGRAM_ID, } from '@solana/spl-token'; log.setLevel(log.levels.INFO); function commandWithDefaultOption(commandName: string): Command { return program .command(commandName) .option('-e, --env <env>', 'environment e.g devnet, mainnet-beta') .option('-k, --keypair <path>', 'Solana wallet') .option('-u, --url <url>', 'rpc url e.g. https://api.devnet.solana.com'); } export function loadKeypair(keypairPath: string): Keypair { if (!keypairPath || keypairPath == '') { throw new Error('Keypair is required!'); } const loaded = Keypair.fromSecretKey( new Uint8Array(JSON.parse(fs.readFileSync(keypairPath).toString())) ); log.info(`wallet public key: ${loaded.publicKey}`); return loaded; } function adminFromOptions(options: OptionValues): Admin { let { env, keypair, url } = options; const config = getConfig(); if (!env) { env = config.env; } log.info(`env: ${env}`); const sdkConfig = initialize({ env: env }); if (!url) { url = config.url; } log.info(`url: ${url}`); const connection = new Connection(url); if (!keypair) { keypair = config.keypair; } const wallet = new Wallet(loadKeypair(keypair)); return Admin.from( connection, wallet, new PublicKey(sdkConfig.DRIFT_PROGRAM_ID) ); } async function wrapActionInAdminSubscribeUnsubscribe( options: OptionValues, action: (admin: Admin) => Promise<void> ): Promise<void> { const admin = adminFromOptions(options); log.info(`DriftClient subscribing`); await admin.subscribe(); log.info(`DriftClient subscribed`); try { await action(admin); } catch (e) { log.error(e); } log.info(`DriftClient unsubscribing`); await admin.unsubscribe(); log.info(`DriftClient unsubscribed`); } async function wrapActionInUserSubscribeUnsubscribe( options: OptionValues, action: (user: User) => Promise<void> ): Promise<void> { const admin = adminFromOptions(options); log.info(`DriftClient subscribing`); await admin.subscribe(); log.info(`DriftClient subscribed`); const driftUser = User.from(admin, admin.wallet.publicKey); log.info(`User subscribing`); await driftUser.subscribe(); log.info(`User subscribed`); try { await action(driftUser); } catch (e) { log.error(e); } log.info(`User unsubscribing`); await driftUser.unsubscribe(); log.info(`User unsubscribed`); log.info(`DriftClient unsubscribing`); await admin.unsubscribe(); log.info(`DriftClient unsubscribed`); } function logError(msg: string) { log.error(colors.red(msg)); } function marketIndexFromSymbol(symbol: string): BN { const market = Markets.filter( (market) => market.baseAssetSymbol === symbol )[0]; if (!market) { const msg = `Could not find market index for ${symbol}`; logError(msg); throw Error(msg); } return market.marketIndex; } commandWithDefaultOption('initialize') .argument('<collateral mint>', 'The collateral mint') .argument( '<admin controls prices>', 'Whether the admin should control prices' ) .action( async (collateralMint, adminControlsPrices, options: OptionValues) => { await wrapActionInAdminSubscribeUnsubscribe( options, async (admin: Admin) => { log.info(`collateralMint: ${collateralMint}`); log.info(`adminControlsPrices: ${adminControlsPrices}`); const collateralMintPublicKey = new PublicKey(collateralMint); log.info(`DriftClient initializing`); await admin.initialize(collateralMintPublicKey, adminControlsPrices); } ); } ); commandWithDefaultOption('initialize-market') .argument( '<market index>', 'Where the market will be initialized in the markets account' ) .argument('<price oracle>', 'The public key for the oracle') .argument('<base asset reserve>', 'AMM base asset reserve') .argument('<quote asset reserve>', 'AMM quote asset reserve') .argument('<periodicity>', 'AMM quote asset reserve') .argument('<peg multiplier>', 'AMM peg multiplier') .action( async ( marketIndex, priceOracle, baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier, options: OptionValues ) => { await wrapActionInAdminSubscribeUnsubscribe( options, async (admin: Admin) => { log.info(`marketIndex: ${marketIndex}`); marketIndex = new BN(marketIndex); log.info(`priceOracle: ${priceOracle}`); priceOracle = new PublicKey(priceOracle); log.info(`baseAssetReserve: ${baseAssetReserve}`); baseAssetReserve = new BN(baseAssetReserve); log.info(`quoteAssetReserve: ${quoteAssetReserve}`); quoteAssetReserve = new BN(quoteAssetReserve); log.info(`periodicity: ${periodicity}`); periodicity = new BN(periodicity); log.info(`pegMultiplier: ${pegMultiplier}`); pegMultiplier = new BN(pegMultiplier); log.info(`Initializing market`); await admin.initializeMarket( priceOracle, baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier ); } ); } ); commandWithDefaultOption('update-discount-mint') .argument('<discount mint>', 'New discount mint') .action(async (discountMint, options: OptionValues) => { await wrapActionInAdminSubscribeUnsubscribe( options, async (admin: Admin) => { log.info(`discountMint: ${discountMint}`); discountMint = new PublicKey(discountMint); await admin.updateDiscountMint(discountMint); } ); }); commandWithDefaultOption('increase-k') .argument('<market>', 'The market to adjust k for') .argument('<numerator>', 'Numerator to multiply k by') .argument('<denominator>', 'Denominator to divide k by') .option('--force', 'Skip percent change check') .action(async (market, numerator, denominator, options: OptionValues) => { await wrapActionInAdminSubscribeUnsubscribe( options, async (admin: Admin) => { log.info(`market: ${market}`); log.info(`numerator: ${numerator}`); log.info(`denominator: ${denominator}`); market = marketIndexFromSymbol(market); numerator = new BN(numerator); denominator = new BN(denominator); if (numerator.lt(denominator)) { logError('To increase k, numerator must be larger than denominator'); return; } const percentChange = Math.abs( (numerator.toNumber() / denominator.toNumber()) * 100 - 100 ); if (percentChange > 10 && options.force !== true) { logError( `Specified input would lead to ${percentChange.toFixed(2)}% change` ); return; } const answer = await promptly.prompt( `You are increasing k by ${percentChange}%. Are you sure you want to do this? y/n` ); if (answer !== 'y') { log.info('Canceling'); return; } const amm = admin.getMarketsAccount().markets[market.toNumber()].amm; const oldSqrtK = amm.sqrtK; log.info(`Current sqrt k: ${oldSqrtK.toString()}`); const newSqrtK = oldSqrtK.mul(numerator).div(denominator); log.info(`New sqrt k: ${newSqrtK.toString()}`); log.info(`Updating K`); await admin.updateK(market, newSqrtK); log.info(`Updated K`); } ); }); commandWithDefaultOption('decrease-k') .argument('<market>', 'The market to adjust k for') .argument('<numerator>', 'Numerator to multiply k by') .argument('<denominator>', 'Denominator to divide k by') .option('--force', 'Skip percent change check') .action(async (market, numerator, denominator, options: OptionValues) => { await wrapActionInAdminSubscribeUnsubscribe( options, async (admin: Admin) => { log.info(`market: ${market}`); log.info(`numerator: ${numerator}`); log.info(`denominator: ${denominator}`); market = marketIndexFromSymbol(market); numerator = new BN(numerator); denominator = new BN(denominator); if (numerator.gt(denominator)) { logError('To decrease k, numerator must be less than denominator'); return; } const percentChange = Math.abs( (numerator.toNumber() / denominator.toNumber()) * 100 - 100 ); if (percentChange > 2) { logError( `Specified input would lead to ${percentChange.toFixed(2)}% change` ); return; } const answer = await promptly.prompt( `You are decreasing k by ${percentChange}%. Are you sure you want to do this? y/n` ); if (answer !== 'y' && options.force !== true) { log.info('Canceling'); return; } const amm = admin.getMarketsAccount().markets[market.toNumber()].amm; const oldSqrtK = amm.sqrtK; log.info(`Current sqrt k: ${oldSqrtK.toString()}`); const newSqrtK = oldSqrtK.mul(numerator).div(denominator); log.info(`New sqrt k: ${newSqrtK.toString()}`); log.info(`Updating K`); await admin.updateK(market, newSqrtK); log.info(`Updated K`); } ); }); commandWithDefaultOption('repeg') .argument('<market>', 'The market to adjust k for') .argument('<peg>', 'New Peg') .action(async (market, peg, options: OptionValues) => { await wrapActionInAdminSubscribeUnsubscribe( options, async (admin: Admin) => { log.info(`market: ${market}`); log.info(`peg: ${peg}`); market = marketIndexFromSymbol(market); peg = new BN(peg); const amm = admin.getMarketsAccount().markets[market.toNumber()].amm; const oldPeg = amm.pegMultiplier; log.info(`Current peg: ${oldPeg.toString()}`); log.info(`Updating peg`); await admin.repegAmmCurve(peg, market); log.info(`Updated peg`); } ); }); commandWithDefaultOption('pause-exchange').action( async (options: OptionValues) => { await wrapActionInAdminSubscribeUnsubscribe( options, async (admin: Admin) => { const answer = await promptly.prompt( `Are you sure you want to 'pause' the exchange? y/n` ); if (answer !== 'y') { log.info('Canceling'); return; } await admin.updateExchangePaused(true); log.info(`Exchange was paused`); } ); } ); commandWithDefaultOption('unpause-exchange').action( async (options: OptionValues) => { await wrapActionInAdminSubscribeUnsubscribe( options, async (admin: Admin) => { const answer = await promptly.prompt( `Are you sure you want to 'unpause' the exchange? y/n` ); if (answer !== 'y') { log.info('Canceling'); return; } await admin.updateExchangePaused(false); log.info(`Exchange was unpaused`); } ); } ); commandWithDefaultOption('pause-funding').action( async (options: OptionValues) => { await wrapActionInAdminSubscribeUnsubscribe( options, async (admin: Admin) => { const answer = await promptly.prompt( `Are you sure you want to 'pause' funding? y/n` ); if (answer !== 'y') { log.info('Canceling'); return; } await admin.updateFundingPaused(true); log.info(`Funding was paused`); } ); } ); commandWithDefaultOption('unpause-funding').action( async (options: OptionValues) => { await wrapActionInAdminSubscribeUnsubscribe( options, async (admin: Admin) => { const answer = await promptly.prompt( `Are you sure you want to 'unpause' funding? y/n` ); if (answer !== 'y') { log.info('Canceling'); return; } await admin.updateFundingPaused(false); log.info(`Funding was unpaused`); } ); } ); commandWithDefaultOption('update-oracle-twap') .argument('<market>', 'The market to update oracle twap for') .action(async (market, options: OptionValues) => { await wrapActionInAdminSubscribeUnsubscribe( options, async (admin: Admin) => { log.info(`market: ${market}`); market = marketIndexFromSymbol(market); log.info(`Updating amm oracle twap`); await admin.updateAmmOracleTwap(market); log.info(`Updated oracle twap`); } ); }); commandWithDefaultOption('reset-oracle-twap') .argument('<market>', 'The market to reset oracle twap for') .action(async (market, options: OptionValues) => { await wrapActionInAdminSubscribeUnsubscribe( options, async (admin: Admin) => { log.info(`market: ${market}`); market = marketIndexFromSymbol(market); log.info(`Resetting amm oracle twap`); await admin.resetAmmOracleTwap(market); log.info(`Reset oracle twap`); } ); }); commandWithDefaultOption('deposit') .argument('<amount>', 'The amount to deposit') .action(async (amount, options: OptionValues) => { await wrapActionInUserSubscribeUnsubscribe(options, async (user: User) => { log.info(`amount: ${amount}`); amount = new BN(amount); const associatedTokenPublicKey = await Token.getAssociatedTokenAddress( ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID, user.driftClient.getStateAccount().collateralMint, user.authority ); await user.driftClient.depositCollateral( amount, associatedTokenPublicKey ); }); }); function getConfigFileDir(): string { return os.homedir() + `/.config/drift-v1`; } function getConfigFilePath(): string { return `${getConfigFileDir()}/config.json`; } function getConfig() { if (!fs.existsSync(getConfigFilePath())) { console.error('drfit-v1 config does not exit. Run `drift-v1 config init`'); return; } return JSON.parse(fs.readFileSync(getConfigFilePath(), 'utf8')); } const config = program.command('config'); config.command('init').action(async () => { const defaultConfig = { env: 'devnet', url: 'https://api.devnet.solana.com', keypair: `${os.homedir()}/.config/solana/id.json`, }; const dir = getConfigFileDir(); if (!fs.existsSync(getConfigFileDir())) { fs.mkdirSync(dir, { recursive: true }); } fs.writeFileSync(getConfigFilePath(), JSON.stringify(defaultConfig)); }); config .command('set') .argument('<key>', 'the config key e.g. env, url, keypair') .argument('<value>') .action(async (key, value) => { if (key !== 'env' && key !== 'url' && key !== 'keypair') { console.error(`Key must be env, url or keypair`); return; } const config = JSON.parse(fs.readFileSync(getConfigFilePath(), 'utf8')); config[key] = value; fs.writeFileSync(getConfigFilePath(), JSON.stringify(config)); }); config.command('get').action(async () => { const config = getConfig(); console.log(JSON.stringify(config, null, 4)); }); program.parse(process.argv);
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/cli/package.json
{ "name": "drift-v1-cli", "version": "0.0.0", "description": "", "bin": { "drift": "./build/cli.js" }, "scripts": {}, "author": "crispheaney", "license": "ISC", "dependencies": { "@drift-labs/sdk": "file:../sdk", "@project-serum/anchor": "0.24.2", "@solana/spl-token": "^0.1.8", "@solana/web3.js": "^1.30.2", "@types/node": "^16.7.10", "colors": "^1.4.0", "commander": "8.1.0", "loglevel": "^1.7.1", "promptly": "^3.2.0" } }
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/cli/tsconfig.json
{ "compilerOptions": { "module": "commonjs", "target": "es6", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "./build", "resolveJsonModule": true } }
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/.devcontainer/Dockerfile
# # Docker image to generate deterministic, verifiable builds of Anchor programs. # This must be run *after* a given ANCHOR_CLI version is published and a git tag # is released on GitHub. # FROM rust:1.75 ARG DEBIAN_FRONTEND=noninteractive ARG SOLANA_CLI="1.14.7" ARG ANCHOR_CLI="0.26.0" ARG NODE_VERSION="v18.16.0" ENV HOME="/root" ENV PATH="${HOME}/.cargo/bin:${PATH}" ENV PATH="${HOME}/.local/share/solana/install/active_release/bin:${PATH}" ENV PATH="${HOME}/.nvm/versions/node/${NODE_VERSION}/bin:${PATH}" # Install base utilities. RUN mkdir -p /workdir && mkdir -p /tmp && \ apt-get update -qq && apt-get upgrade -qq && apt-get install -qq \ build-essential git curl wget jq pkg-config python3-pip \ libssl-dev libudev-dev RUN wget http://nz2.archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2_amd64.deb RUN dpkg -i libssl1.1_1.1.1f-1ubuntu2_amd64.deb # Install rust. RUN curl "https://sh.rustup.rs" -sfo rustup.sh && \ sh rustup.sh -y && \ rustup component add rustfmt clippy # Install node / npm / yarn. RUN curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash ENV NVM_DIR="${HOME}/.nvm" RUN . $NVM_DIR/nvm.sh && \ nvm install ${NODE_VERSION} && \ nvm use ${NODE_VERSION} && \ nvm alias default node && \ npm install -g yarn && \ yarn add ts-mocha # Install Solana tools. RUN sh -c "$(curl -sSfL https://release.solana.com/v${SOLANA_CLI}/install)" # Install anchor. RUN cargo install --git https://github.com/coral-xyz/anchor avm --locked --force RUN avm install ${ANCHOR_CLI} && avm use ${ANCHOR_CLI} RUN solana-keygen new --no-bip39-passphrase WORKDIR /workdir #be sure to add `/root/.avm/bin` to your PATH to be able to run the installed binaries
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/.devcontainer/devcontainer.json
{ "build": { "dockerfile": "Dockerfile" }, }
0
solana_public_repos/drift-labs/protocol-v2
solana_public_repos/drift-labs/protocol-v2/.cargo/audit.toml
# RUSTSEC-2022-0013 ignores as upstream dependency [advisories] ignore = [ "RUSTSEC-2022-0013", "RUSTSEC-2022-0093", # Double Public Key Signing Function Oracle Attack on `ed25519-dalek` ] informational_warnings = ["unmaintained"] # warn for categories of informational advisories severity_threshold = "high" # CVSS severity ("none", "low", "medium", "high", "critical") # Advisory Database Configuration [database] path = "~/.cargo/advisory-db" # Path where advisory git repo will be cloned url = "https://github.com/RustSec/advisory-db.git" # URL to git repo fetch = true # Perform a `git fetch` before auditing (default: true) stale = false # Allow stale advisory DB (i.e. no commits for 90 days, default: false) # Output Configuration [output] deny = [] # exit on error if unmaintained dependencies are found format = "terminal" # "terminal" (human readable report) or "json" quiet = false # Only print information on error show_tree = true # Show inverse dependency trees along with advisories (default: true) # Target Configuration [target] arch = "x86_64" # Ignore advisories for CPU architectures other than this one os = "linux" # Ignore advisories for operating systems other than this one [yanked] enabled = false # Warn for yanked crates in Cargo.lock (default: true) update_index = true # Auto-update the crates.io index (default: true)
0
solana_public_repos/drift-labs/protocol-v2/programs
solana_public_repos/drift-labs/protocol-v2/programs/token_faucet/Cargo.toml
[package] name = "token-faucet" version = "0.1.0" description = "Created with Anchor" edition = "2018" [lib] crate-type = ["cdylib", "lib"] name = "token_faucet" [features] no-entrypoint = [] cpi = ["no-entrypoint"] mainnet-beta=[] anchor-test= [] [dependencies] anchor-lang = "0.29.0" solana-program = "1.16" anchor-spl = "0.29.0" bytemuck = { version = "1.4.0" }
0
solana_public_repos/drift-labs/protocol-v2/programs
solana_public_repos/drift-labs/protocol-v2/programs/token_faucet/Xargo.toml
[target.bpfel-unknown-unknown.dependencies.std] features = []
0
solana_public_repos/drift-labs/protocol-v2/programs/token_faucet
solana_public_repos/drift-labs/protocol-v2/programs/token_faucet/src/lib.rs
use anchor_lang::prelude::*; use anchor_spl::token::{self, Mint, Token, TokenAccount}; #[cfg(feature = "mainnet-beta")] declare_id!("AmNeSW4UMPFBodCjEJD22G3kA8EraUGkhxr3GmdyEF4f"); #[cfg(not(feature = "mainnet-beta"))] declare_id!("V4v1mQiAdLz4qwckEb45WqHYceYizoib39cDBHSWfaB"); #[program] pub mod token_faucet { use super::*; use anchor_spl::token::spl_token::instruction::AuthorityType; use anchor_spl::token::MintTo; use anchor_spl::token::SetAuthority; pub fn initialize(ctx: Context<InitializeFaucet>) -> Result<()> { let mint_account_key = ctx.accounts.mint_account.to_account_info().key; let (mint_authority, mint_authority_nonce) = Pubkey::find_program_address( &[b"mint_authority".as_ref(), mint_account_key.as_ref()], ctx.program_id, ); let cpi_accounts = SetAuthority { current_authority: ctx.accounts.admin.to_account_info(), account_or_mint: ctx.accounts.mint_account.to_account_info(), }; let cpi_program = ctx.accounts.token_program.to_account_info(); let cpi_context = CpiContext::new(cpi_program, cpi_accounts); token::set_authority(cpi_context, AuthorityType::MintTokens, Some(mint_authority)).unwrap(); **ctx.accounts.faucet_config = FaucetConfig { admin: *ctx.accounts.admin.key, mint: *mint_account_key, mint_authority, mint_authority_nonce, }; Ok(()) } pub fn mint_to_user(ctx: Context<MintToUser>, amount: u64) -> Result<()> { let mint_signature_seeds = [ b"mint_authority".as_ref(), ctx.accounts.faucet_config.mint.as_ref(), bytemuck::bytes_of(&ctx.accounts.faucet_config.mint_authority_nonce), ]; let signers = &[&mint_signature_seeds[..]]; let cpi_accounts = MintTo { mint: ctx.accounts.mint_account.to_account_info(), to: ctx.accounts.user_token_account.to_account_info(), authority: ctx.accounts.mint_authority.clone(), }; let cpi_program = ctx.accounts.token_program.to_account_info(); let cpi_context = CpiContext::new_with_signer(cpi_program, cpi_accounts, signers); token::mint_to(cpi_context, amount).unwrap(); Ok(()) } pub fn transfer_mint_authority(ctx: Context<TransferMintAuthority>) -> Result<()> { let mint_signature_seeds = [ b"mint_authority".as_ref(), ctx.accounts.faucet_config.mint.as_ref(), bytemuck::bytes_of(&ctx.accounts.faucet_config.mint_authority_nonce), ]; let signers = &[&mint_signature_seeds[..]]; let cpi_accounts = SetAuthority { current_authority: ctx.accounts.mint_authority.to_account_info(), account_or_mint: ctx.accounts.mint_account.to_account_info(), }; let cpi_program = ctx.accounts.token_program.to_account_info(); let cpi_context = CpiContext::new_with_signer(cpi_program, cpi_accounts, signers); token::set_authority( cpi_context, AuthorityType::MintTokens, Some(ctx.accounts.admin.key()), ) .unwrap(); Ok(()) } } #[derive(Accounts)] pub struct InitializeFaucet<'info> { #[account( init, seeds = [b"faucet_config".as_ref(), mint_account.key().as_ref()], space = std::mem::size_of::<FaucetConfig>() + 8, bump, payer = admin )] pub faucet_config: Box<Account<'info, FaucetConfig>>, #[account(mut)] pub admin: Signer<'info>, #[account(mut)] pub mint_account: Box<Account<'info, Mint>>, pub rent: Sysvar<'info, Rent>, pub system_program: Program<'info, System>, pub token_program: Program<'info, Token>, } #[account] #[derive(Default)] pub struct FaucetConfig { pub admin: Pubkey, pub mint: Pubkey, pub mint_authority: Pubkey, pub mint_authority_nonce: u8, } #[derive(Accounts)] pub struct MintToUser<'info> { pub faucet_config: Box<Account<'info, FaucetConfig>>, #[account(mut)] pub mint_account: Box<Account<'info, Mint>>, #[account(mut)] pub user_token_account: Box<Account<'info, TokenAccount>>, /// CHECK: Checked by spl_token pub mint_authority: AccountInfo<'info>, pub token_program: Program<'info, Token>, } #[derive(Accounts)] pub struct TransferMintAuthority<'info> { #[account( seeds = [b"faucet_config".as_ref(), mint_account.key().as_ref()], bump, has_one = admin )] pub faucet_config: Box<Account<'info, FaucetConfig>>, #[account(mut)] pub admin: Signer<'info>, #[account(mut)] pub mint_account: Box<Account<'info, Mint>>, /// CHECK: Checked by spl_token pub mint_authority: AccountInfo<'info>, pub token_program: Program<'info, Token>, } #[error_code] pub enum ErrorCode { #[msg("Program not mint authority")] InvalidMintAccountAuthority, }
0
solana_public_repos/drift-labs/protocol-v2/programs
solana_public_repos/drift-labs/protocol-v2/programs/switchboard-on-demand/Cargo.toml
[package] name = "switchboard-on-demand" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib", "lib"] name = "switchboard_on_demand" [features] no-entrypoint = [] no-idl = [] cpi = ["no-entrypoint"] default = ["mainnet-beta"] mainnet-beta=[] anchor-test= [] [dependencies] anchor-lang = "0.29.0" bytemuck = { version = "1.4.0" } solana-program = "1.16" [dev-dependencies] base64 = "0.13.0"
0
solana_public_repos/drift-labs/protocol-v2/programs/switchboard-on-demand
solana_public_repos/drift-labs/protocol-v2/programs/switchboard-on-demand/src/lib.rs
use anchor_lang::declare_id; use anchor_lang::prelude::*; use anchor_lang::program; use anchor_lang::AnchorDeserialize; use solana_program::pubkey::Pubkey; #[cfg(feature = "mainnet-beta")] declare_id!("SBondMDrcV3K4kxZR1HNVT7osZxAHVHgYXL5Ze1oMUv"); #[cfg(not(feature = "mainnet-beta"))] declare_id!("Aio4gaXjXzJNVLtzwtNVmSqGKpANtXhybbkhtAC94ji2"); #[program] pub mod switchboard_on_demand {} pub const SB_ON_DEMAND_PRECISION: u32 = 18; #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct CompactResult { pub std_dev: f32, pub mean: f32, pub slot: u64, } #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct CurrentResult { /// The median value of the submissions needed for quorom size pub value: i128, /// The standard deviation of the submissions needed for quorom size pub std_dev: i128, /// The mean of the submissions needed for quorom size pub mean: i128, /// The range of the submissions needed for quorom size pub range: i128, /// The minimum value of the submissions needed for quorom size pub min_value: i128, /// The maximum value of the submissions needed for quorom size pub max_value: i128, /// The number of samples used to calculate this result pub num_samples: u8, /// The index of the submission that was used to calculate this result pub submission_idx: u8, pub padding1: [u8; 6], /// The slot at which this value was signed. pub slot: u64, /// The slot at which the first considered submission was made pub min_slot: u64, /// The slot at which the last considered submission was made pub max_slot: u64, } impl CurrentResult { /// The median value of the submissions needed for quorom size pub fn value(&self) -> Option<i128> { if self.slot == 0 { return None; } Some(self.value) } /// The standard deviation of the submissions needed for quorom size pub fn std_dev(&self) -> Option<i128> { if self.slot == 0 { return None; } Some(self.std_dev) } /// The mean of the submissions needed for quorom size pub fn mean(&self) -> Option<i128> { if self.slot == 0 { return None; } Some(self.mean) } /// The range of the submissions needed for quorom size pub fn range(&self) -> Option<i128> { if self.slot == 0 { return None; } Some(self.range) } /// The minimum value of the submissions needed for quorom size pub fn min_value(&self) -> Option<i128> { if self.slot == 0 { return None; } Some(self.min_value) } /// The maximum value of the submissions needed for quorom size pub fn max_value(&self) -> Option<i128> { if self.slot == 0 { return None; } Some(self.max_value) } pub fn result_slot(&self) -> Option<u64> { if self.slot == 0 { return None; } Some(self.slot) } pub fn min_slot(&self) -> Option<u64> { if self.slot == 0 { return None; } Some(self.min_slot) } pub fn max_slot(&self) -> Option<u64> { if self.slot == 0 { return None; } Some(self.max_slot) } } #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct OracleSubmission { /// The public key of the oracle that submitted this value. pub oracle: Pubkey, /// The slot at which this value was signed. pub slot: u64, /// The slot at which this value was landed on chain. pub landed_at: u64, /// The value that was submitted. pub value: i128, } impl OracleSubmission { pub fn is_empty(&self) -> bool { self.slot == 0 } pub fn value(&self) -> i128 { self.value } } /// A representation of the data in a pull feed account. #[repr(C)] #[account(zero_copy)] pub struct PullFeedAccountData { /// The oracle submissions for this feed. pub submissions: [OracleSubmission; 32], /// The public key of the authority that can update the feed hash that /// this account will use for registering updates. pub authority: Pubkey, /// The public key of the queue which oracles must be bound to in order to /// submit data to this feed. pub queue: Pubkey, /// SHA-256 hash of the job schema oracles will execute to produce data /// for this feed. pub feed_hash: [u8; 32], /// The slot at which this account was initialized. pub initialized_at: i64, pub permissions: u64, pub max_variance: u64, pub min_responses: u32, pub name: [u8; 32], _padding1: [u8; 2], pub historical_result_idx: u8, pub min_sample_size: u8, pub last_update_timestamp: i64, pub lut_slot: u64, _reserved1: [u8; 32], // deprecated pub result: CurrentResult, pub max_staleness: u32, _padding2: [u8; 12], pub historical_results: [CompactResult; 32], _ebuf4: [u8; 8], _ebuf3: [u8; 24], _ebuf2: [u8; 256], } impl PullFeedAccountData { pub fn discriminator() -> [u8; 8] { [196, 27, 108, 196, 10, 215, 219, 40] } /// The median value of the submissions needed for quorom size pub fn median_value(&self) -> Option<i128> { self.result.value() } /// The standard deviation of the submissions needed for quorom size pub fn std_dev(&self) -> Option<i128> { self.result.std_dev() } /// The mean of the submissions needed for quorom size pub fn mean(&self) -> Option<i128> { self.result.mean() } /// The range of the submissions needed for quorom size pub fn range(&self) -> Option<i128> { self.result.range() } /// The minimum value of the submissions needed for quorom size pub fn min_value(&self) -> Option<i128> { self.result.min_value() } /// The maximum value of the submissions needed for quorom size pub fn max_value(&self) -> Option<i128> { self.result.max_value() } pub fn median_result_land_slot(&self) -> u64 { let submission: OracleSubmission = self.submissions[self.result.submission_idx as usize]; submission.landed_at } pub fn latest_submissions(&self) -> Vec<OracleSubmission> { let max_landed_at = self .submissions .iter() .map(|s| s.landed_at) .max() .unwrap_or(0); self.submissions .iter() .filter(|submission| submission.landed_at == max_landed_at) .cloned() .collect() } }
0
solana_public_repos/drift-labs/protocol-v2/programs
solana_public_repos/drift-labs/protocol-v2/programs/pyth/Cargo.toml
[package] name = "pyth" version = "0.1.0" description = "Created with Anchor" edition = "2018" [lib] crate-type = ["cdylib", "lib"] name = "pyth" [features] no-entrypoint = [] no-idl = [] cpi = ["no-entrypoint"] default = ["mainnet-beta"] mainnet-beta=[] anchor-test= [] [dependencies] anchor-lang = "0.29.0" arrayref = "0.3.6" bytemuck = { version = "1.4.0" }
0
solana_public_repos/drift-labs/protocol-v2/programs
solana_public_repos/drift-labs/protocol-v2/programs/pyth/Xargo.toml
[target.bpfel-unknown-unknown.dependencies.std] features = []
0
solana_public_repos/drift-labs/protocol-v2/programs/pyth
solana_public_repos/drift-labs/protocol-v2/programs/pyth/src/lib.rs
use anchor_lang::prelude::*; pub mod pc; use pc::Price; #[cfg(feature = "mainnet-beta")] declare_id!("FsJ3A3u2vn5cTVofAjvy6y5kwABJAqYWpe4975bi2epH"); #[cfg(not(feature = "mainnet-beta"))] declare_id!("gSbePebfvPy7tRqimPoVecS2UsBvYv46ynrzWocc92s"); #[program] pub mod pyth { use super::*; pub fn initialize(ctx: Context<Initialize>, price: i64, expo: i32, conf: u64) -> Result<()> { let oracle = &ctx.accounts.price; let mut price_oracle = Price::load(oracle).unwrap(); price_oracle.magic = 2712847316; price_oracle.agg.price = price; price_oracle.agg.conf = conf; price_oracle.agg.conf = 0; price_oracle.valid_slot = 228506959; //todo just turned 1->2 for negative delay price_oracle.ver = 2; price_oracle.atype = 3; price_oracle.size = 3216; price_oracle.twap = price; price_oracle.expo = expo; price_oracle.ptype = pc::PriceType::Price; Ok(()) } pub fn set_price(ctx: Context<SetPrice>, price: i64) -> Result<()> { let oracle = &ctx.accounts.price; let mut price_oracle = Price::load(oracle).unwrap(); price_oracle.twap = price_oracle .twap .checked_add(price) .unwrap() .checked_div(2) .unwrap(); //todo price_oracle.agg.price = price; Ok(()) } pub fn set_price_info(ctx: Context<SetPrice>, price: i64, conf: u64, slot: u64) -> Result<()> { let oracle = &ctx.accounts.price; let mut price_oracle = Price::load(oracle).unwrap(); price_oracle.twap = price_oracle .twap .checked_add(price) .unwrap() .checked_div(2) .unwrap(); //todo price_oracle.agg.price = price; price_oracle.agg.conf = conf; price_oracle.valid_slot = slot; Ok(()) } pub fn set_twap(ctx: Context<SetPrice>, twap: i64) -> Result<()> { let oracle = &ctx.accounts.price; let mut price_oracle = Price::load(oracle).unwrap(); price_oracle.twap = twap; Ok(()) } } #[derive(Accounts)] pub struct SetPrice<'info> { /// CHECK: this program is just for testing #[account(mut)] pub price: AccountInfo<'info>, } #[derive(Accounts)] pub struct Initialize<'info> { /// CHECK: this program is just for testing #[account(mut)] pub price: AccountInfo<'info>, }
0
solana_public_repos/drift-labs/protocol-v2/programs/pyth
solana_public_repos/drift-labs/protocol-v2/programs/pyth/src/pc.rs
use crate::*; use anchor_lang::prelude::AccountInfo; use bytemuck::{cast_slice_mut, from_bytes_mut, try_cast_slice_mut, Pod, Zeroable}; use std::cell::RefMut; #[derive(Default, Copy, Clone)] #[repr(C)] pub struct AccKey { pub val: [u8; 32], } #[derive(Copy, Clone, Default)] #[repr(C)] #[allow(dead_code)] pub enum PriceStatus { Unknown, #[default] Trading, Halted, Auction, } #[derive(Copy, Clone, Default)] #[repr(C)] pub enum CorpAction { #[default] NoCorpAct, } #[derive(Default, Copy, Clone)] #[repr(C)] pub struct PriceInfo { pub price: i64, pub conf: u64, pub status: PriceStatus, pub corp_act: CorpAction, pub pub_slot: u64, } #[derive(Default, Copy, Clone)] #[repr(C)] pub struct PriceComp { publisher: AccKey, agg: PriceInfo, latest: PriceInfo, } #[derive(Copy, Clone, Default)] #[repr(C)] #[allow(dead_code, clippy::upper_case_acronyms)] pub enum PriceType { Unknown, #[default] Price, TWAP, Volatility, } #[derive(Default, Copy, Clone)] #[repr(C)] pub struct Price { pub magic: u32, // Pyth magic number. pub ver: u32, // Program version. pub atype: u32, // Account type. pub size: u32, // Price account size. pub ptype: PriceType, // Price or calculation type. pub expo: i32, // Price exponent. pub num: u32, // Number of component prices. pub unused: u32, pub curr_slot: u64, // Currently accumulating price slot. pub valid_slot: u64, // Valid slot-time of agg. price. pub twap: i64, // Time-weighted average price. pub avol: u64, // Annualized price volatility. pub drv0: i64, // Space for future derived values. pub drv1: i64, // Space for future derived values. pub drv2: i64, // Space for future derived values. pub drv3: i64, // Space for future derived values. pub drv4: i64, // Space for future derived values. pub drv5: i64, // Space for future derived values. pub prod: AccKey, // Product account key. pub next: AccKey, // Next Price account in linked list. pub agg_pub: AccKey, // Quoter who computed last aggregate price. pub agg: PriceInfo, // Aggregate price info. pub comp: [PriceComp; 32], // Price components one per quoter. } impl Price { #[inline] pub fn load<'a>( price_feed: &'a AccountInfo, ) -> std::result::Result<RefMut<'a, Price>, ProgramError> { let account_data: RefMut<'a, [u8]> = RefMut::map(price_feed.try_borrow_mut_data().unwrap(), |data| *data); let state: RefMut<'a, Self> = RefMut::map(account_data, |data| { from_bytes_mut(cast_slice_mut::<u8, u8>(try_cast_slice_mut(data).unwrap())) }); Ok(state) } } #[cfg(target_endian = "little")] unsafe impl Zeroable for Price {} #[cfg(target_endian = "little")] unsafe impl Pod for Price {}
0
solana_public_repos/drift-labs/protocol-v2/programs
solana_public_repos/drift-labs/protocol-v2/programs/drift/Cargo.toml
[package] name = "drift" version = "2.103.0" description = "Created with Anchor" edition = "2018" [lib] crate-type = ["cdylib", "lib"] name = "drift" path = "src/lib.rs" [features] no-entrypoint = [] cpi = ["no-entrypoint"] mainnet-beta=[] anchor-test= [] default=["mainnet-beta"] drift-rs=[] [dependencies] anchor-lang = "0.29.0" solana-program = "1.16" anchor-spl = "0.29.0" pyth-client = "0.2.2" pyth-lazer-sdk = { git = "https://github.com/drift-labs/pyth-crosschain", rev = "776b6f772ba8ae49f26d16d04649073c3d6f77cf"} pythnet-sdk = { git = "https://github.com/drift-labs/pyth-crosschain", rev = "3e8a24ecd0bcf22b787313e2020f4186bb22c729"} pyth-solana-receiver-sdk = { git = "https://github.com/drift-labs/pyth-crosschain", rev = "3e8a24ecd0bcf22b787313e2020f4186bb22c729"} bytemuck = { version = "1.4.0" } borsh = "0.10.3" hex = "0.4.3" num-traits = "0.2" uint = { version = "0.9.1", default-features = false } num-derive = "0.3" thiserror = "1.0" num-integer = "0.1.44" arrayref = "0.3.6" base64 = "0.13.0" serum_dex = { git = "https://github.com/project-serum/serum-dex", rev = "85b4f14", version = "0.5.6", features = ["no-entrypoint"] } enumflags2 = "0.6.4" phoenix-v1 = { git = "https://github.com/drift-labs/phoenix-v1", rev = "7703c5", version = "0.2.4", features = ["no-entrypoint"] } solana-security-txt = "1.1.0" static_assertions = "1.1.0" drift-macros = { git = "https://github.com/drift-labs/drift-macros.git", rev = "c57d87" } switchboard = { path = "../switchboard", features = ["no-entrypoint"] } openbook-v2-light = { path = "../openbook_v2", features = ["no-entrypoint"] } ahash = "=0.8.6" switchboard-on-demand = { path = "../switchboard-on-demand", features = ["no-entrypoint"] } byteorder = "1.4.3" [dev-dependencies] bytes = "1.2.0" pyth = { path = "../pyth", features = ["no-entrypoint"]} base64 = "0.13.0"
0