From 541fd3bbb7fc1246b686ddb0ac51b4d016bf9eda Mon Sep 17 00:00:00 2001 From: "Jean Marchand (Exotic Markets)" Date: Wed, 14 Dec 2022 15:40:51 +0100 Subject: [PATCH] add rust and js lints (#21) * fix js lint * Add prettier in package.json * Add lints check in github actions * Cargo clippy * Fix latest lints * Split Rust and Js lint * Fix test.yml * Split into two workflows --- .github/workflows/js-lint.yml | 35 +++++ .github/workflows/test.yml | 21 +++ assert-owner/src/lib.rs | 4 +- common/src/client/rpc.rs | 4 +- dex/crank/src/lib.rs | 69 ++++---- dex/permissioned/src/middleware.rs | 2 +- dex/permissioned/src/proxy.rs | 2 +- dex/tests/permissioned/.prettierrc.json | 6 + dex/tests/permissioned/package.json | 7 +- .../tests/permissioned-markets.js | 148 +++++++++--------- dex/tests/permissioned/tests/utils/common.js | 72 +-------- dex/tests/permissioned/tests/utils/faucet.js | 24 +-- dex/tests/permissioned/tests/utils/index.js | 24 +-- .../permissioned/tests/utils/market-lister.js | 106 +++---------- .../permissioned/tests/utils/market-maker.js | 94 ++--------- .../permissioned/tests/utils/market-proxy.js | 16 +- 16 files changed, 257 insertions(+), 377 deletions(-) create mode 100644 .github/workflows/js-lint.yml create mode 100644 dex/tests/permissioned/.prettierrc.json diff --git a/.github/workflows/js-lint.yml b/.github/workflows/js-lint.yml new file mode 100644 index 0000000..b9a6e7c --- /dev/null +++ b/.github/workflows/js-lint.yml @@ -0,0 +1,35 @@ +name: Js Lint + +on: + push: + branches: + - master + paths: + - '**.ts' + - '**.js' + + pull_request: + branches: + - master + paths: + - '**.ts' + - '**.js' + +jobs: + js-lint: + name: Prettier check + runs-on: ubuntu-20.04 + defaults: + run: + working-directory: ./dex/tests/permissioned + steps: + - uses: actions/checkout@v3 + - name: Use Node.js + uses: actions/setup-node@v3 + with: + node-version: 18 + - run: corepack enable + shell: bash + - run: yarn + - name: Run prettier + run: yarn prettier '*/**/*{.js,.ts}' --check \ No newline at end of file diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 3487b57..453478b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -9,6 +9,27 @@ on: - master jobs: + rust-lint: + name: Cargo fmt, cargo clippy + runs-on: ubuntu-20.04 + steps: + - name: Checkout sources + uses: actions/checkout@v3 + - name: Cache Cargo and target + uses: actions/cache@v3 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + dex/target/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + - name: Run cargo fmt + run: cargo fmt --all -- --check + - name: Run cargo clippy + run: cargo clippy -- -D warnings test: runs-on: ubuntu-20.04 steps: diff --git a/assert-owner/src/lib.rs b/assert-owner/src/lib.rs index 74a4c7f..6b1d164 100644 --- a/assert-owner/src/lib.rs +++ b/assert-owner/src/lib.rs @@ -1,5 +1,5 @@ use solana_program::{ - account_info::AccountInfo, entrypoint, entrypoint::ProgramResult, info, + account_info::AccountInfo, entrypoint, entrypoint::ProgramResult, msg, program_error::ProgramError, pubkey::Pubkey, }; @@ -11,7 +11,7 @@ fn entry(_program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8] } let expected_owner = Pubkey::new(instruction_data); if expected_owner != *account.owner { - info!("Account owner mismatch"); + msg!("Account owner mismatch"); return Err(ProgramError::Custom(0x100)); } Ok(()) diff --git a/common/src/client/rpc.rs b/common/src/client/rpc.rs index d83e7fa..126c9c0 100644 --- a/common/src/client/rpc.rs +++ b/common/src/client/rpc.rs @@ -96,8 +96,8 @@ pub fn create_token_account_instructions( let init_account_instr = token_instruction::initialize_account( &spl_token::ID, &spl_account, - &mint_pubkey, - &owner_pubkey, + mint_pubkey, + owner_pubkey, )?; let instructions = vec![create_account_instr, init_account_instr]; diff --git a/dex/crank/src/lib.rs b/dex/crank/src/lib.rs index d33315f..1048111 100644 --- a/dex/crank/src/lib.rs +++ b/dex/crank/src/lib.rs @@ -1,5 +1,6 @@ #![deny(unaligned_references)] #![allow(dead_code)] +#![allow(clippy::too_many_arguments)] use std::borrow::Cow; use std::cmp::{max, min}; @@ -14,7 +15,6 @@ use std::{thread, time}; use anyhow::{format_err, Result}; use clap::Parser; use debug_print::debug_println; -use enumflags2::BitFlags; use log::{error, info}; use rand::rngs::OsRng; use safe_transmute::{ @@ -248,10 +248,10 @@ pub fn start(opts: Opts) -> Result<()> { ref coin_wallet, ref pc_wallet, } => { - let payer = read_keypair_file(&payer)?; + let payer = read_keypair_file(payer)?; debug_println!("Getting market keys ..."); - let market_keys = get_keys_for_market(&client, dex_program_id, &market)?; + let market_keys = get_keys_for_market(&client, dex_program_id, market)?; debug_println!("{:#?}", market_keys); match_orders( &client, @@ -278,11 +278,11 @@ pub fn start(opts: Opts) -> Result<()> { init_logger(log_directory); consume_events_loop( &opts, - &dex_program_id, - &payer, - &market, - &coin_wallet, - &pc_wallet, + dex_program_id, + payer, + market, + coin_wallet, + pc_wallet, num_workers, events_per_worker, num_accounts.unwrap_or(32), @@ -308,7 +308,7 @@ pub fn start(opts: Opts) -> Result<()> { ref dex_program_id, ref market, } => { - let market_keys = get_keys_for_market(&client, dex_program_id, &market)?; + let market_keys = get_keys_for_market(&client, dex_program_id, market)?; let event_q_data = client.get_account_data(&market_keys.event_q)?; let inner: Cow<[u64]> = remove_dex_account_padding(&event_q_data)?; let (header, events_seg0, events_seg1) = parse_event_queue(&inner)?; @@ -333,8 +333,8 @@ pub fn start(opts: Opts) -> Result<()> { ref signer, } => { let payer = read_keypair_file(payer)?; - let signer = signer.as_ref().map(|s| read_keypair_file(&s)).transpose()?; - let market_keys = get_keys_for_market(&client, dex_program_id, &market)?; + let signer = signer.as_ref().map(|s| read_keypair_file(s)).transpose()?; + let market_keys = get_keys_for_market(&client, dex_program_id, market)?; settle_funds( &client, dex_program_id, @@ -425,7 +425,7 @@ fn get_keys_for_market<'a>( program_id: &'a Pubkey, market: &'a Pubkey, ) -> Result { - let account_data: Vec = client.get_account_data(&market)?; + let account_data: Vec = client.get_account_data(market)?; let words: Cow<[u64]> = remove_dex_account_padding(&account_data)?; let market_state: MarketState = { let account_flags = Market::account_flags(&account_data)?; @@ -515,7 +515,7 @@ fn init_logger(log_directory: &str) { fn consume_events_loop( opts: &Opts, program_id: &Pubkey, - payer_path: &String, + payer_path: &str, market: &Pubkey, coin_wallet: &Pubkey, pc_wallet: &Pubkey, @@ -527,21 +527,21 @@ fn consume_events_loop( ) -> Result<()> { info!("Getting market keys ..."); let client = opts.client(); - let market_keys = get_keys_for_market(&client, &program_id, &market)?; + let market_keys = get_keys_for_market(&client, program_id, market)?; info!("{:#?}", market_keys); let pool = threadpool::ThreadPool::new(num_workers); let max_slot_height_mutex = Arc::new(Mutex::new(0_u64)); let mut last_cranked_at = std::time::Instant::now() .checked_sub(std::time::Duration::from_secs(max_wait_for_events_delay)) - .unwrap_or(std::time::Instant::now()); + .unwrap_or_else(std::time::Instant::now); loop { thread::sleep(time::Duration::from_millis(1000)); let loop_start = std::time::Instant::now(); let start_time = std::time::Instant::now(); - let event_q_value_and_context = - client.get_account_with_commitment(&market_keys.event_q, CommitmentConfig::recent())?; + let event_q_value_and_context = client + .get_account_with_commitment(&market_keys.event_q, CommitmentConfig::processed())?; let event_q_slot = event_q_value_and_context.context.slot; let max_slot_height = max_slot_height_mutex.lock().unwrap(); if event_q_slot <= *max_slot_height { @@ -554,12 +554,12 @@ fn consume_events_loop( drop(max_slot_height); let event_q_data = event_q_value_and_context .value - .ok_or(format_err!("Failed to retrieve account"))? + .ok_or_else(|| format_err!("Failed to retrieve account"))? .data; let req_q_data = client - .get_account_with_commitment(&market_keys.req_q, CommitmentConfig::recent())? + .get_account_with_commitment(&market_keys.req_q, CommitmentConfig::processed())? .value - .ok_or(format_err!("Failed to retrieve account"))? + .ok_or_else(|| format_err!("Failed to retrieve account"))? .data; let inner: Cow<[u64]> = remove_dex_account_padding(&event_q_data)?; let (_header, seg0, seg1) = parse_event_queue(&inner)?; @@ -639,8 +639,8 @@ fn consume_events_loop( end_time.duration_since(start_time).as_millis() ); for thread_num in 0..min(num_workers, 2 * event_q_len / events_per_worker + 1) { - let payer = read_keypair_file(&payer_path)?; - let program_id = program_id.clone(); + let payer = read_keypair_file(payer_path)?; + let program_id = *program_id; let client = opts.client(); let account_metas = account_metas.clone(); let event_q = *market_keys.event_q; @@ -682,9 +682,9 @@ fn consume_events_wrapper( ) { let start = std::time::Instant::now(); let result = consume_events_once( - &client, + client, program_id, - &payer, + payer, account_metas, to_consume, thread_num, @@ -714,7 +714,7 @@ pub fn consume_events_once( account_metas: Vec, to_consume: usize, _thread_number: usize, - event_q: Pubkey, + _event_q: Pubkey, ) -> Result { let _start = std::time::Instant::now(); let instruction_data: Vec = MarketInstruction::ConsumeEvents(to_consume as u16).pack(); @@ -885,7 +885,7 @@ fn whole_shebang(client: &RpcClient, program_id: &Pubkey, payer: &Keypair) -> Re max_coin_qty: NonZeroU64::new(1_000).unwrap(), max_native_pc_qty_including_fees: NonZeroU64::new(500_000).unwrap(), order_type: OrderType::Limit, - client_order_id: 019269, + client_order_id: 19269, self_trade_behavior: SelfTradeBehavior::DecrementTake, limit: std::u16::MAX, max_ts: now + 20, @@ -909,7 +909,7 @@ fn whole_shebang(client: &RpcClient, program_id: &Pubkey, payer: &Keypair) -> Re max_coin_qty: NonZeroU64::new(1_000).unwrap(), max_native_pc_qty_including_fees: NonZeroU64::new(500_000).unwrap(), order_type: OrderType::Limit, - client_order_id: 019269, + client_order_id: 19269, self_trade_behavior: SelfTradeBehavior::DecrementTake, limit: std::u16::MAX, max_ts: now - 5, @@ -1241,7 +1241,7 @@ fn settle_funds( i += 1; assert!(i < 10); debug_println!("Simulating SettleFunds instruction ..."); - let result = simulate_transaction(client, &txn, true, CommitmentConfig::single())?; + let result = simulate_transaction(client, &txn, true, CommitmentConfig::confirmed())?; if let Some(e) = result.value.err { return Err(format_err!("simulate_transaction error: {:?}", e)); } @@ -1329,7 +1329,7 @@ pub fn list_market( ); debug_println!("txn:\n{:#x?}", txn); - let result = simulate_transaction(client, &txn, true, CommitmentConfig::single())?; + let result = simulate_transaction(client, &txn, true, CommitmentConfig::confirmed())?; if let Some(e) = result.value.err { return Err(format_err!("simulate_transaction error: {:?}", e)); } @@ -1451,7 +1451,7 @@ pub fn match_orders( ); debug_println!("Simulating order matching ..."); - let result = simulate_transaction(&client, &txn, true, CommitmentConfig::single())?; + let result = simulate_transaction(client, &txn, true, CommitmentConfig::confirmed())?; if let Some(e) = result.value.err { return Err(format_err!("simulate_transaction error: {:?}", e)); } @@ -1485,8 +1485,8 @@ fn create_account( let init_account_instr = token_instruction::initialize_account( &spl_token::ID, &spl_account.pubkey(), - &mint_pubkey, - &owner_pubkey, + mint_pubkey, + owner_pubkey, )?; let instructions = vec![create_account_instr, init_account_instr]; @@ -1581,7 +1581,7 @@ async fn read_queue_length_loop( let client = client.clone(); let market_keys = get_keys_for_market(&client, &program_id, &market).unwrap(); let event_q_data = client - .get_account_with_commitment(&market_keys.event_q, CommitmentConfig::recent()) + .get_account_with_commitment(&market_keys.event_q, CommitmentConfig::processed()) .unwrap() .value .expect("Failed to retrieve account") @@ -1592,5 +1592,6 @@ async fn read_queue_length_loop( format!("{{ \"length\": {} }}", len) }); - Ok(warp::serve(get_data).run(([127, 0, 0, 1], port)).await) + warp::serve(get_data).run(([127, 0, 0, 1], port)).await; + Ok(()) } diff --git a/dex/permissioned/src/middleware.rs b/dex/permissioned/src/middleware.rs index 694b2b1..e85fccd 100644 --- a/dex/permissioned/src/middleware.rs +++ b/dex/permissioned/src/middleware.rs @@ -187,7 +187,7 @@ impl MarketMiddleware for OpenOrdersPda { }); // Chop off the first two accounts needed for initializing the PDA. - ctx.accounts = (&ctx.accounts[2..]).to_vec(); + ctx.accounts = (ctx.accounts[2..]).to_vec(); // Set PDAs. ctx.accounts[1] = Self::prepare_pda(&ctx.accounts[0]); diff --git a/dex/permissioned/src/proxy.rs b/dex/permissioned/src/proxy.rs index 5185efb..b17393f 100644 --- a/dex/permissioned/src/proxy.rs +++ b/dex/permissioned/src/proxy.rs @@ -44,7 +44,7 @@ impl<'a> MarketProxy<'a> { // First account is the Serum DEX executable--used for CPI. let dex = &accounts[0]; require!(dex.key == &dex::ID, ErrorCode::InvalidTargetProgram); - let acc_infos = (&accounts[1..]).to_vec(); + let acc_infos = (accounts[1..]).to_vec(); // Process the instruction data. for mw in &mut self.middlewares { diff --git a/dex/tests/permissioned/.prettierrc.json b/dex/tests/permissioned/.prettierrc.json new file mode 100644 index 0000000..843d866 --- /dev/null +++ b/dex/tests/permissioned/.prettierrc.json @@ -0,0 +1,6 @@ +{ + "trailingComma": "all", + "tabWidth": 2, + "semi": true, + "singleQuote": true +} \ No newline at end of file diff --git a/dex/tests/permissioned/package.json b/dex/tests/permissioned/package.json index f5b9f92..1fba292 100644 --- a/dex/tests/permissioned/package.json +++ b/dex/tests/permissioned/package.json @@ -10,7 +10,9 @@ "test": "anchor test", "localnet": "./scripts/localnet.sh", "build": "yarn build:dex && anchor build", - "build:dex": "cd ../../ && cargo build-bpf && cd tests/permissioned/" + "build:dex": "cd ../../ && cargo build-bpf && cd tests/permissioned/", + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" }, "repository": { "type": "git", @@ -28,6 +30,7 @@ "@project-serum/common": "^0.0.1-beta.3", "@project-serum/serum": "^0.13.61", "@solana/spl-token": "^0.1.6", - "mocha": "^9.0.3" + "mocha": "^9.0.3", + "prettier": "^2.8.1" } } diff --git a/dex/tests/permissioned/tests/permissioned-markets.js b/dex/tests/permissioned/tests/permissioned-markets.js index 4b53210..9ac1e49 100644 --- a/dex/tests/permissioned/tests/permissioned-markets.js +++ b/dex/tests/permissioned/tests/permissioned-markets.js @@ -1,7 +1,7 @@ -const assert = require("assert"); -const { Token, TOKEN_PROGRAM_ID } = require("@solana/spl-token"); -const anchor = require("@project-serum/anchor"); -const serum = require("@project-serum/serum"); +const assert = require('assert'); +const { Token, TOKEN_PROGRAM_ID } = require('@solana/spl-token'); +const anchor = require('@project-serum/anchor'); +const serum = require('@project-serum/serum'); const { BN } = anchor; const { Keypair, @@ -19,14 +19,14 @@ const { ReferralFees, MarketProxyBuilder, } = serum; -const { genesis, sleep } = require("./utils"); +const { genesis, sleep } = require('./utils'); -const DEX_PID = new PublicKey("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"); +const DEX_PID = new PublicKey('9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin'); const REFERRAL_AUTHORITY = new PublicKey( - "3oSfkjQZKCneYvsCTZc9HViGAPqR8pYr4h9YeGB5ZxHf" + '3oSfkjQZKCneYvsCTZc9HViGAPqR8pYr4h9YeGB5ZxHf', ); -describe("permissioned-markets", () => { +describe('permissioned-markets', () => { // Anchor client setup. const provider = anchor.Provider.env(); anchor.setProvider(provider); @@ -41,7 +41,7 @@ describe("permissioned-markets", () => { let usdcPosted; let referralTokenAddress; - it("BOILERPLATE: Initializes an orderbook", async () => { + it('BOILERPLATE: Initializes an orderbook', async () => { const { marketProxyClient, godA, godUsdc, usdc } = await genesis({ provider, proxyProgramId: program.programId, @@ -54,33 +54,31 @@ describe("permissioned-markets", () => { provider.connection, usdc, TOKEN_PROGRAM_ID, - provider.wallet.payer + provider.wallet.payer, ); referral = await usdcClient.createAccount(REFERRAL_AUTHORITY); }); - it("BOILERPLATE: Calculates open orders addresses", async () => { + it('BOILERPLATE: Calculates open orders addresses', async () => { const [_openOrders, bump] = await PublicKey.findProgramAddress( [ - anchor.utils.bytes.utf8.encode("open-orders"), + anchor.utils.bytes.utf8.encode('open-orders'), DEX_PID.toBuffer(), marketProxy.market.address.toBuffer(), program.provider.wallet.publicKey.toBuffer(), ], - program.programId - ); - const [ - _openOrdersInitAuthority, - bumpInit, - ] = await PublicKey.findProgramAddress( - [ - anchor.utils.bytes.utf8.encode("open-orders-init"), - DEX_PID.toBuffer(), - marketProxy.market.address.toBuffer(), - ], - program.programId + program.programId, ); + const [_openOrdersInitAuthority, bumpInit] = + await PublicKey.findProgramAddress( + [ + anchor.utils.bytes.utf8.encode('open-orders-init'), + DEX_PID.toBuffer(), + marketProxy.market.address.toBuffer(), + ], + program.programId, + ); // Save global variables re-used across tests. openOrders = _openOrders; @@ -89,15 +87,15 @@ describe("permissioned-markets", () => { openOrdersBumpInit = bumpInit; }); - it("Creates an open orders account", async () => { + it('Creates an open orders account', async () => { const tx = new Transaction(); tx.add( await marketProxy.instruction.initOpenOrders( program.provider.wallet.publicKey, marketProxy.market.address, marketProxy.market.address, // Dummy. Replaced by middleware. - marketProxy.market.address // Dummy. Replaced by middleware. - ) + marketProxy.market.address, // Dummy. Replaced by middleware. + ), ); await provider.send(tx); @@ -105,15 +103,15 @@ describe("permissioned-markets", () => { assert.ok(account.owner.toString() === DEX_PID.toString()); }); - it("Posts a bid on the orderbook", async () => { + it('Posts a bid on the orderbook', async () => { const size = 1; const price = 1; usdcPosted = new BN( - marketProxy.market._decoded.quoteLotSize.toNumber() + marketProxy.market._decoded.quoteLotSize.toNumber(), ).mul( marketProxy.market .baseSizeNumberToLots(size) - .mul(marketProxy.market.priceNumberToLots(price)) + .mul(marketProxy.market.priceNumberToLots(price)), ); const tx = new Transaction(); @@ -121,24 +119,24 @@ describe("permissioned-markets", () => { marketProxy.instruction.newOrderV3({ owner: program.provider.wallet.publicKey, payer: usdcAccount, - side: "buy", + side: 'buy', price, size, - orderType: "postOnly", + orderType: 'postOnly', clientId: new BN(999), openOrdersAddressKey: openOrders, - selfTradeBehavior: "abortTransaction", - }) + selfTradeBehavior: 'abortTransaction', + }), ); await provider.send(tx); }); - it("Cancels a bid on the orderbook", async () => { + it('Cancels a bid on the orderbook', async () => { // Given. const beforeOoAccount = await OpenOrders.load( provider.connection, openOrders, - DEX_PID + DEX_PID, ); // When. @@ -147,8 +145,8 @@ describe("permissioned-markets", () => { await marketProxy.instruction.cancelOrderByClientId( program.provider.wallet.publicKey, openOrders, - new BN(999) - ) + new BN(999), + ), ); await provider.send(tx); @@ -156,7 +154,7 @@ describe("permissioned-markets", () => { const afterOoAccount = await OpenOrders.load( provider.connection, openOrders, - DEX_PID + DEX_PID, ); assert.ok(beforeOoAccount.quoteTokenFree.eq(new BN(0))); assert.ok(beforeOoAccount.quoteTokenTotal.eq(usdcPosted)); @@ -164,7 +162,7 @@ describe("permissioned-markets", () => { assert.ok(afterOoAccount.quoteTokenTotal.eq(usdcPosted)); }); - it("Settles funds on the orderbook", async () => { + it('Settles funds on the orderbook', async () => { // Given. const beforeTokenAccount = await usdcClient.getAccountInfo(usdcAccount); @@ -176,8 +174,8 @@ describe("permissioned-markets", () => { provider.wallet.publicKey, tokenAccount, usdcAccount, - referral - ) + referral, + ), ); await provider.send(tx); @@ -185,19 +183,19 @@ describe("permissioned-markets", () => { const afterTokenAccount = await usdcClient.getAccountInfo(usdcAccount); assert.ok( afterTokenAccount.amount.sub(beforeTokenAccount.amount).toNumber() === - usdcPosted.toNumber() + usdcPosted.toNumber(), ); }); // Need to crank the cancel so that we can close later. - it("Cranks the cancel transaction", async () => { + it('Cranks the cancel transaction', async () => { await crankEventQueue(provider, marketProxy); }); - it("Closes an open orders account", async () => { + it('Closes an open orders account', async () => { // Given. const beforeAccount = await program.provider.connection.getAccountInfo( - program.provider.wallet.publicKey + program.provider.wallet.publicKey, ); // When. @@ -206,31 +204,31 @@ describe("permissioned-markets", () => { marketProxy.instruction.closeOpenOrders( openOrders, provider.wallet.publicKey, - provider.wallet.publicKey - ) + provider.wallet.publicKey, + ), ); await provider.send(tx); // Then. const afterAccount = await program.provider.connection.getAccountInfo( - program.provider.wallet.publicKey + program.provider.wallet.publicKey, ); const closedAccount = await program.provider.connection.getAccountInfo( - openOrders + openOrders, ); assert.ok(23352768 === afterAccount.lamports - beforeAccount.lamports); assert.ok(closedAccount === null); }); - it("Re-opens an open orders account", async () => { + it('Re-opens an open orders account', async () => { const tx = new Transaction(); tx.add( await marketProxy.instruction.initOpenOrders( program.provider.wallet.publicKey, marketProxy.market.address, marketProxy.market.address, // Dummy. Replaced by middleware. - marketProxy.market.address // Dummy. Replaced by middleware. - ) + marketProxy.market.address, // Dummy. Replaced by middleware. + ), ); await provider.send(tx); @@ -238,7 +236,7 @@ describe("permissioned-markets", () => { assert.ok(account.owner.toString() === DEX_PID.toString()); }); - it("Posts several bids and asks on the orderbook", async () => { + it('Posts several bids and asks on the orderbook', async () => { const size = 10; const price = 2; for (let k = 0; k < 10; k += 1) { @@ -247,14 +245,14 @@ describe("permissioned-markets", () => { marketProxy.instruction.newOrderV3({ owner: program.provider.wallet.publicKey, payer: usdcAccount, - side: "buy", + side: 'buy', price, size, - orderType: "postOnly", + orderType: 'postOnly', clientId: new BN(999), openOrdersAddressKey: openOrders, - selfTradeBehavior: "abortTransaction", - }) + selfTradeBehavior: 'abortTransaction', + }), ); await provider.send(tx); } @@ -268,28 +266,28 @@ describe("permissioned-markets", () => { marketProxy.instruction.newOrderV3({ owner: program.provider.wallet.publicKey, payer: tokenAccount, - side: "sell", + side: 'sell', price: priceAsk, size: sizeAsk, - orderType: "postOnly", + orderType: 'postOnly', clientId: new BN(1000), openOrdersAddressKey: openOrders, - selfTradeBehavior: "abortTransaction", - }) + selfTradeBehavior: 'abortTransaction', + }), ); await provider.send(txAsk); } }); - it("Prunes the orderbook", async () => { + it('Prunes the orderbook', async () => { const tx = new Transaction(); tx.add( - marketProxy.instruction.prune(openOrders, provider.wallet.publicKey) + marketProxy.instruction.prune(openOrders, provider.wallet.publicKey), ); await provider.send(tx); }); - it("Settles the account", async () => { + it('Settles the account', async () => { const tx = new Transaction(); tx.add( await marketProxy.instruction.settleFunds( @@ -297,20 +295,20 @@ describe("permissioned-markets", () => { provider.wallet.publicKey, tokenAccount, usdcAccount, - referral - ) + referral, + ), ); await provider.send(tx); }); - it("Cranks the prune transaction", async () => { + it('Cranks the prune transaction', async () => { await crankEventQueue(provider, marketProxy); }); - it("Closes an open orders account", async () => { + it('Closes an open orders account', async () => { // Given. const beforeAccount = await program.provider.connection.getAccountInfo( - program.provider.wallet.publicKey + program.provider.wallet.publicKey, ); // When. @@ -319,17 +317,17 @@ describe("permissioned-markets", () => { marketProxy.instruction.closeOpenOrders( openOrders, provider.wallet.publicKey, - provider.wallet.publicKey - ) + provider.wallet.publicKey, + ), ); await provider.send(tx); // Then. const afterAccount = await program.provider.connection.getAccountInfo( - program.provider.wallet.publicKey + program.provider.wallet.publicKey, ); const closedAccount = await program.provider.connection.getAccountInfo( - openOrders + openOrders, ); assert.ok(23352768 === afterAccount.lamports - beforeAccount.lamports); assert.ok(closedAccount === null); @@ -343,7 +341,7 @@ async function crankEventQueue(provider, marketProxy) { while (eq.length > 0) { const tx = new Transaction(); tx.add( - marketProxy.instruction.consumeEventsPermissioned([eq[0].openOrders], 1) + marketProxy.instruction.consumeEventsPermissioned([eq[0].openOrders], 1), ); await provider.send(tx); eq = await marketProxy.market.loadEventQueue(provider.connection); diff --git a/dex/tests/permissioned/tests/utils/common.js b/dex/tests/permissioned/tests/utils/common.js index f99fbff..22a9280 100644 --- a/dex/tests/permissioned/tests/utils/common.js +++ b/dex/tests/permissioned/tests/utils/common.js @@ -1,73 +1,13 @@ -const { PublicKey, Account } = require("@project-serum/anchor").web3; +const { PublicKey, Account } = require('@project-serum/anchor').web3; -const DEX_PID = new PublicKey("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"); +const DEX_PID = new PublicKey('9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin'); // This msut be kept in sync with `scripts/localnet.sh`. const PROGRAM_KP = new Account([ - 168, - 86, - 206, - 125, - 127, - 105, - 201, - 250, - 37, - 102, - 161, - 124, - 80, - 181, - 60, - 2, - 166, - 123, - 176, - 161, - 228, - 188, - 134, - 186, - 158, - 68, - 197, - 240, - 202, - 193, - 174, - 234, - 167, - 123, - 252, - 186, - 72, - 51, - 203, - 70, - 153, - 234, - 190, - 2, - 134, - 184, - 197, - 156, - 113, - 8, - 65, - 1, - 83, - 220, - 152, - 62, - 200, - 174, - 40, - 180, - 218, - 61, - 224, - 6, + 168, 86, 206, 125, 127, 105, 201, 250, 37, 102, 161, 124, 80, 181, 60, 2, 166, + 123, 176, 161, 228, 188, 134, 186, 158, 68, 197, 240, 202, 193, 174, 234, 167, + 123, 252, 186, 72, 51, 203, 70, 153, 234, 190, 2, 134, 184, 197, 156, 113, 8, + 65, 1, 83, 220, 152, 62, 200, 174, 40, 180, 218, 61, 224, 6, ]); function sleep(ms) { diff --git a/dex/tests/permissioned/tests/utils/faucet.js b/dex/tests/permissioned/tests/utils/faucet.js index d0693db..156a729 100644 --- a/dex/tests/permissioned/tests/utils/faucet.js +++ b/dex/tests/permissioned/tests/utils/faucet.js @@ -1,8 +1,8 @@ -const anchor = require("@project-serum/anchor"); +const anchor = require('@project-serum/anchor'); const BN = anchor.BN; const { Account, Transaction, SystemProgram } = anchor.web3; -const serumCmn = require("@project-serum/common"); -const { TOKEN_PROGRAM_ID, Token } = require("@solana/spl-token"); +const serumCmn = require('@project-serum/common'); +const { TOKEN_PROGRAM_ID, Token } = require('@solana/spl-token'); const DECIMALS = 6; @@ -14,9 +14,9 @@ async function createMintGods(provider, mintCount) { for (let k = 0; k < mintCount; k += 1) { const [mint, god] = await serumCmn.createMintAndVault( provider, - new BN("1000000000000000000"), + new BN('1000000000000000000'), undefined, - DECIMALS + DECIMALS, ); mintGods.push({ mint, god }); } @@ -43,10 +43,10 @@ async function createFundedAccount(provider, mints, newAccount) { fromPubkey: provider.wallet.publicKey, toPubkey: newAccount.publicKey, lamports: 100000000000, - }) + }), ); return tx; - })() + })(), ); // Transfer SPL tokens to the market maker. @@ -59,10 +59,10 @@ async function createFundedAccount(provider, mints, newAccount) { provider.connection, MINT_A, TOKEN_PROGRAM_ID, - provider.wallet.payer // node only + provider.wallet.payer, // node only ); const marketMakerTokenA = await mintAClient.createAccount( - newAccount.publicKey + newAccount.publicKey, ); await provider.send( @@ -77,11 +77,11 @@ async function createFundedAccount(provider, mints, newAccount) { provider.wallet.publicKey, [], amount, - DECIMALS - ) + DECIMALS, + ), ); return tx; - })() + })(), ); marketMaker.tokens[mint.toString()] = marketMakerTokenA; diff --git a/dex/tests/permissioned/tests/utils/index.js b/dex/tests/permissioned/tests/utils/index.js index 13e77d9..1d32806 100644 --- a/dex/tests/permissioned/tests/utils/index.js +++ b/dex/tests/permissioned/tests/utils/index.js @@ -1,10 +1,10 @@ -const { BN } = require("@project-serum/anchor"); -const { PublicKey } = require("@project-serum/anchor").web3; -const marketProxy = require("./market-proxy"); -const marketLister = require("./market-lister"); -const faucet = require("./faucet"); -const { DEX_PID } = require("./common"); -const marketMaker = require("./market-maker"); +const { BN } = require('@project-serum/anchor'); +const { PublicKey } = require('@project-serum/anchor').web3; +const marketProxy = require('./market-proxy'); +const marketLister = require('./market-lister'); +const faucet = require('./faucet'); +const { DEX_PID } = require('./common'); +const marketMaker = require('./market-maker'); // Initializes the genesis state for the tests and localnetwork. async function genesis({ provider, proxyProgramId }) { @@ -22,10 +22,10 @@ async function genesis({ provider, proxyProgramId }) { mintGods.map((mintGod) => { return { ...mintGod, - amount: new BN("10000000000000").muln(10 ** faucet.DECIMALS), + amount: new BN('10000000000000').muln(10 ** faucet.DECIMALS), }; }), - marketMaker.KEYPAIR + marketMaker.KEYPAIR, ); // @@ -59,7 +59,7 @@ async function genesis({ provider, proxyProgramId }) { provider.connection, proxyProgramId, DEX_PID, - marketAPublicKey + marketAPublicKey, ); // @@ -68,7 +68,7 @@ async function genesis({ provider, proxyProgramId }) { await marketMaker.initOpenOrders( provider, marketProxyClient, - marketMakerAccounts + marketMakerAccounts, ); // @@ -77,7 +77,7 @@ async function genesis({ provider, proxyProgramId }) { await marketMaker.postOrders( provider, marketProxyClient, - marketMakerAccounts + marketMakerAccounts, ); // diff --git a/dex/tests/permissioned/tests/utils/market-lister.js b/dex/tests/permissioned/tests/utils/market-lister.js index 3bbf9db..ecc07a8 100644 --- a/dex/tests/permissioned/tests/utils/market-lister.js +++ b/dex/tests/permissioned/tests/utils/market-lister.js @@ -1,21 +1,17 @@ -const anchor = require("@project-serum/anchor"); +const anchor = require('@project-serum/anchor'); const { BN } = anchor; -const { - Account, - PublicKey, - Transaction, - SystemProgram, -} = require("@project-serum/anchor").web3; -const { TOKEN_PROGRAM_ID } = require("@solana/spl-token"); -const serum = require("@project-serum/serum"); +const { Account, PublicKey, Transaction, SystemProgram } = + require('@project-serum/anchor').web3; +const { TOKEN_PROGRAM_ID } = require('@solana/spl-token'); +const serum = require('@project-serum/serum'); const { DexInstructions, TokenInstructions, OpenOrdersPda, MARKET_STATE_LAYOUT_V3, } = serum; -const { Identity } = require("./market-proxy"); -const { DEX_PID } = require("./common"); +const { Identity } = require('./market-proxy'); +const { DEX_PID } = require('./common'); // Creates a market on the dex. async function list({ @@ -40,7 +36,7 @@ async function list({ const [vaultOwner, vaultSignerNonce] = await getVaultOwnerAndNonce( market.publicKey, - dexProgramId + dexProgramId, ); const tx1 = new Transaction(); @@ -68,7 +64,7 @@ async function list({ account: quoteVault.publicKey, mint: quoteMint, owner: vaultOwner, - }) + }), ); const tx2 = new Transaction(); @@ -77,7 +73,7 @@ async function list({ fromPubkey: wallet.publicKey, newAccountPubkey: market.publicKey, lamports: await connection.getMinimumBalanceForRentExemption( - MARKET_STATE_LAYOUT_V3.span + MARKET_STATE_LAYOUT_V3.span, ), space: MARKET_STATE_LAYOUT_V3.span, programId: dexProgramId, @@ -129,19 +125,19 @@ async function list({ authority: await OpenOrdersPda.marketAuthority( market.publicKey, DEX_PID, - proxyProgramId + proxyProgramId, ), pruneAuthority: await Identity.pruneAuthority( market.publicKey, DEX_PID, - proxyProgramId + proxyProgramId, ), crankAuthority: await Identity.consumeEventsAuthority( market.publicKey, DEX_PID, - proxyProgramId + proxyProgramId, ), - }) + }), ); const transactions = [ @@ -164,84 +160,24 @@ async function getVaultOwnerAndNonce(marketPublicKey, dexProgramId = DEX_PID) { while (nonce.toNumber() < 255) { try { const vaultOwner = await PublicKey.createProgramAddress( - [marketPublicKey.toBuffer(), nonce.toArrayLike(Buffer, "le", 8)], - dexProgramId + [marketPublicKey.toBuffer(), nonce.toArrayLike(Buffer, 'le', 8)], + dexProgramId, ); return [vaultOwner, nonce]; } catch (e) { nonce.iaddn(1); } } - throw new Error("Unable to find nonce"); + throw new Error('Unable to find nonce'); } // Dummy keypair for a consistent market address. Helpful when doing UI work. // Don't use in production. const MARKET_KP = new Account([ - 13, - 174, - 53, - 150, - 78, - 228, - 12, - 98, - 170, - 254, - 212, - 211, - 125, - 193, - 2, - 241, - 97, - 137, - 49, - 209, - 189, - 199, - 27, - 215, - 220, - 65, - 57, - 203, - 215, - 93, - 105, - 203, - 217, - 32, - 5, - 194, - 157, - 118, - 162, - 47, - 102, - 126, - 235, - 65, - 99, - 80, - 56, - 231, - 217, - 114, - 25, - 225, - 239, - 140, - 169, - 92, - 150, - 146, - 211, - 218, - 183, - 139, - 9, - 104, + 13, 174, 53, 150, 78, 228, 12, 98, 170, 254, 212, 211, 125, 193, 2, 241, 97, + 137, 49, 209, 189, 199, 27, 215, 220, 65, 57, 203, 215, 93, 105, 203, 217, 32, + 5, 194, 157, 118, 162, 47, 102, 126, 235, 65, 99, 80, 56, 231, 217, 114, 25, + 225, 239, 140, 169, 92, 150, 146, 211, 218, 183, 139, 9, 104, ]); module.exports = { diff --git a/dex/tests/permissioned/tests/utils/market-maker.js b/dex/tests/permissioned/tests/utils/market-maker.js index e92943e..27a9479 100644 --- a/dex/tests/permissioned/tests/utils/market-maker.js +++ b/dex/tests/permissioned/tests/utils/market-maker.js @@ -1,72 +1,12 @@ -const { Account, Transaction } = require("@project-serum/anchor").web3; -const { OpenOrdersPda } = require("@project-serum/serum"); +const { Account, Transaction } = require('@project-serum/anchor').web3; +const { OpenOrdersPda } = require('@project-serum/serum'); // Dummy keypair. const KEYPAIR = new Account([ - 54, - 213, - 91, - 255, - 163, - 120, - 88, - 183, - 223, - 23, - 220, - 204, - 82, - 117, - 212, - 214, - 118, - 184, - 2, - 29, - 89, - 149, - 22, - 233, - 108, - 177, - 60, - 249, - 218, - 166, - 30, - 221, - 59, - 168, - 233, - 123, - 204, - 37, - 123, - 124, - 86, - 176, - 214, - 12, - 63, - 195, - 231, - 15, - 1, - 143, - 7, - 7, - 232, - 38, - 69, - 214, - 45, - 58, - 115, - 55, - 129, - 25, - 228, - 30, + 54, 213, 91, 255, 163, 120, 88, 183, 223, 23, 220, 204, 82, 117, 212, 214, + 118, 184, 2, 29, 89, 149, 22, 233, 108, 177, 60, 249, 218, 166, 30, 221, 59, + 168, 233, 123, 204, 37, 123, 124, 86, 176, 214, 12, 63, 195, 231, 15, 1, 143, + 7, 7, 232, 38, 69, 214, 45, 58, 115, 55, 129, 25, 228, 30, ]); async function initOpenOrders(provider, marketProxy, marketMakerAccounts) { @@ -76,8 +16,8 @@ async function initOpenOrders(provider, marketProxy, marketMakerAccounts) { marketMakerAccounts.account.publicKey, marketProxy.market.address, marketProxy.market.address, // Dummy. Replaced by middleware. - marketProxy.market.address // Dummy. Replaced by middleware. - ) + marketProxy.market.address, // Dummy. Replaced by middleware. + ), ); let signers = [marketMakerAccounts.account]; await provider.send(tx, signers); @@ -107,7 +47,7 @@ async function postOrders(provider, marketProxy, marketMakerAccounts) { marketProxy.market.address, marketMakerAccounts.account.publicKey, marketProxy.dexProgramId, - marketProxy.proxyProgramId + marketProxy.proxyProgramId, ); // Use an explicit signer because the provider wallet, which pays for // the tx, is different from the market maker wallet. @@ -119,15 +59,15 @@ async function postOrders(provider, marketProxy, marketMakerAccounts) { await marketProxy.instruction.newOrderV3({ owner: marketMakerAccounts.account.publicKey, payer: marketMakerAccounts.baseToken, - side: "sell", + side: 'sell', price: ask[0], size: ask[1], - orderType: "postOnly", + orderType: 'postOnly', clientId: undefined, openOrdersAddressKey, feeDiscountPubkey: null, - selfTradeBehavior: "abortTransaction", - }) + selfTradeBehavior: 'abortTransaction', + }), ); await provider.send(tx, signers); } @@ -139,15 +79,15 @@ async function postOrders(provider, marketProxy, marketMakerAccounts) { await marketProxy.instruction.newOrderV3({ owner: marketMakerAccounts.account.publicKey, payer: marketMakerAccounts.quoteToken, - side: "buy", + side: 'buy', price: bid[0], size: bid[1], - orderType: "postOnly", + orderType: 'postOnly', clientId: undefined, openOrdersAddressKey, feeDiscountPubkey: null, - selfTradeBehavior: "abortTransaction", - }) + selfTradeBehavior: 'abortTransaction', + }), ); await provider.send(tx, signers); } diff --git a/dex/tests/permissioned/tests/utils/market-proxy.js b/dex/tests/permissioned/tests/utils/market-proxy.js index c6a9a78..948f33f 100644 --- a/dex/tests/permissioned/tests/utils/market-proxy.js +++ b/dex/tests/permissioned/tests/utils/market-proxy.js @@ -1,9 +1,9 @@ -const anchor = require("@project-serum/anchor"); +const anchor = require('@project-serum/anchor'); const { PublicKey, SYSVAR_RENT_PUBKEY, SYSVAR_CLOCK_PUBKEY, -} = require("@solana/web3.js"); +} = require('@solana/web3.js'); const { OpenOrders, OpenOrdersPda, @@ -11,7 +11,7 @@ const { ReferralFees, PermissionedCrank, MarketProxyBuilder, -} = require("@project-serum/serum"); +} = require('@project-serum/serum'); // Returns a client for the market proxy. // @@ -23,7 +23,7 @@ async function load(connection, proxyProgramId, dexProgramId, market) { new OpenOrdersPda({ proxyProgramId, dexProgramId, - }) + }), ) .middleware(new ReferralFees()) .middleware(new Identity()) @@ -33,7 +33,7 @@ async function load(connection, proxyProgramId, dexProgramId, market) { market, dexProgramId, proxyProgramId, - options: { commitment: "recent" }, + options: { commitment: 'recent' }, }); } @@ -78,16 +78,16 @@ class Identity { ...ix.keys, ]; // PDA: so ensure the signer is false. - ix.keys[ix.keys.length-1].isSigner = false; + ix.keys[ix.keys.length - 1].isSigner = false; } static async pruneAuthority(market, dexProgramId, proxyProgramId) { const [addr] = await PublicKey.findProgramAddress( [ - anchor.utils.bytes.utf8.encode("prune"), + anchor.utils.bytes.utf8.encode('prune'), dexProgramId.toBuffer(), market.toBuffer(), ], - proxyProgramId + proxyProgramId, ); return addr; }