Skip to content

Commit

Permalink
Merge branch 'master' into feature/anchor-29
Browse files Browse the repository at this point in the history
  • Loading branch information
skrrb committed Feb 4, 2024
2 parents 2e83992 + 59cbaba commit 591c193
Show file tree
Hide file tree
Showing 9 changed files with 474 additions and 161 deletions.
114 changes: 114 additions & 0 deletions idl/openbook_v2.json
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,120 @@
"option": "u128"
}
},
{
"name": "placeOrders",
"docs": [
"Place multiple orders"
],
"accounts": [
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "openOrdersAccount",
"isMut": true,
"isSigner": false
},
{
"name": "openOrdersAdmin",
"isMut": false,
"isSigner": true,
"isOptional": true
},
{
"name": "userQuoteAccount",
"isMut": true,
"isSigner": false
},
{
"name": "userBaseAccount",
"isMut": true,
"isSigner": false
},
{
"name": "market",
"isMut": true,
"isSigner": false
},
{
"name": "bids",
"isMut": true,
"isSigner": false
},
{
"name": "asks",
"isMut": true,
"isSigner": false
},
{
"name": "eventHeap",
"isMut": true,
"isSigner": false
},
{
"name": "marketQuoteVault",
"isMut": true,
"isSigner": false
},
{
"name": "marketBaseVault",
"isMut": true,
"isSigner": false
},
{
"name": "oracleA",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "oracleB",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "ordersType",
"type": {
"defined": "PlaceOrderType"
}
},
{
"name": "bids",
"type": {
"vec": {
"defined": "PlaceMultipleOrdersArgs"
}
}
},
{
"name": "asks",
"type": {
"vec": {
"defined": "PlaceMultipleOrdersArgs"
}
}
},
{
"name": "limit",
"type": "u8"
}
],
"returns": {
"vec": {
"option": "u128"
}
}
},
{
"name": "cancelAllAndPlaceOrders",
"docs": [
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@openbook-dex/openbook-v2",
"version": "0.1.7",
"version": "0.1.9",
"description": "Typescript Client for openbook-v2 program.",
"repository": "https://github.com/openbook-dex/openbook-v2/",
"author": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::token_utils::*;
#[allow(clippy::too_many_arguments)]
pub fn cancel_all_and_place_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelAllAndPlaceOrders<'info>>,
cancel: bool,
mut orders: Vec<Order>,
limit: u8,
) -> Result<Vec<Option<u128>>> {
Expand Down Expand Up @@ -39,7 +40,9 @@ pub fn cancel_all_and_place_orders<'c: 'info, 'info>(
clock.slot,
)?;

book.cancel_all_orders(&mut open_orders_account, *market, u8::MAX, None)?;
if cancel {
book.cancel_all_orders(&mut open_orders_account, *market, u8::MAX, None)?;
}

let mut base_amount = 0_u64;
let mut quote_amount = 0_u64;
Expand Down
50 changes: 49 additions & 1 deletion programs/openbook-v2/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,54 @@ pub mod openbook_v2 {
Ok(None)
}

/// Place multiple orders
pub fn place_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelAllAndPlaceOrders<'info>>,
orders_type: PlaceOrderType,
bids: Vec<PlaceMultipleOrdersArgs>,
asks: Vec<PlaceMultipleOrdersArgs>,
limit: u8,
) -> Result<Vec<Option<u128>>> {
let n_bids = bids.len();

let mut orders = vec![];
for (i, order) in bids.into_iter().chain(asks).enumerate() {
require_gte!(order.price_lots, 1, OpenBookError::InvalidInputPriceLots);

let time_in_force = match Order::tif_from_expiry(order.expiry_timestamp) {
Some(t) => t,
None => {
msg!("Order is already expired");
continue;
}
};
orders.push(Order {
side: if i < n_bids { Side::Bid } else { Side::Ask },
max_base_lots: i64::MIN, // this will be overriden to max_base_lots
max_quote_lots_including_fees: order.max_quote_lots_including_fees,
client_order_id: i as u64,
time_in_force,
self_trade_behavior: SelfTradeBehavior::CancelProvide,
params: match orders_type {
PlaceOrderType::Market => OrderParams::Market,
PlaceOrderType::ImmediateOrCancel => OrderParams::ImmediateOrCancel {
price_lots: order.price_lots,
},
_ => OrderParams::Fixed {
price_lots: order.price_lots,
order_type: orders_type.to_post_order_type()?,
},
},
});
}

#[cfg(feature = "enable-gpl")]
return instructions::cancel_all_and_place_orders(ctx, false, orders, limit);

#[cfg(not(feature = "enable-gpl"))]
Ok(vec![])
}

/// Cancel orders and place multiple orders.
pub fn cancel_all_and_place_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelAllAndPlaceOrders<'info>>,
Expand Down Expand Up @@ -301,7 +349,7 @@ pub mod openbook_v2 {
}

#[cfg(feature = "enable-gpl")]
return instructions::cancel_all_and_place_orders(ctx, orders, limit);
return instructions::cancel_all_and_place_orders(ctx, true, orders, limit);

#[cfg(not(feature = "enable-gpl"))]
Ok(vec![])
Expand Down
79 changes: 76 additions & 3 deletions ts/client/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ import {
} from '@solana/web3.js';
import { IDL, type OpenbookV2 } from './openbook_v2';
import { sendTransaction } from './utils/rpc';
import { Side } from './utils/utils';
import { SideUtils } from './utils/utils';

export type IdsSource = 'api' | 'static' | 'get-program-accounts';
export type PlaceOrderArgs = IdlTypes<OpenbookV2>['PlaceOrderArgs'];
export type PlaceOrderType = IdlTypes<OpenbookV2>['PlaceOrderType'];
export type Side = IdlTypes<OpenbookV2>['Side'];
export type PlaceOrderPeggedArgs = IdlTypes<OpenbookV2>['PlaceOrderPeggedArgs'];
export type PlaceMultipleOrdersArgs =
IdlTypes<OpenbookV2>['PlaceMultipleOrdersArgs'];
Expand Down Expand Up @@ -627,7 +628,9 @@ export class OpenBookV2Client {
openOrdersDelegate?: Keypair,
): Promise<[TransactionInstruction, Signer[]]> {
const marketVault =
args.side === Side.Bid ? market.marketQuoteVault : market.marketBaseVault;
args.side === SideUtils.Bid
? market.marketQuoteVault
: market.marketBaseVault;
const accountsMeta: AccountMeta[] = remainingAccounts.map((remaining) => ({
pubkey: remaining,
isSigner: false,
Expand Down Expand Up @@ -673,7 +676,9 @@ export class OpenBookV2Client {
openOrdersDelegate?: Keypair,
): Promise<[TransactionInstruction, Signer[]]> {
const marketVault =
args.side === Side.Bid ? market.marketQuoteVault : market.marketBaseVault;
args.side === SideUtils.Bid
? market.marketQuoteVault
: market.marketBaseVault;
const accountsMeta: AccountMeta[] = remainingAccounts.map((remaining) => ({
pubkey: remaining,
isSigner: false,
Expand Down Expand Up @@ -798,6 +803,49 @@ export class OpenBookV2Client {
return [ix, signers];
}

// Use OrderType from './utils/utils' for orderType
public async placeOrdersIx(
openOrdersPublicKey: PublicKey,
marketPublicKey: PublicKey,
market: MarketAccount,
userBaseAccount: PublicKey,
userQuoteAccount: PublicKey,
openOrdersAdmin: PublicKey | null,
orderType: PlaceOrderType,
bids: PlaceMultipleOrdersArgs[],
asks: PlaceMultipleOrdersArgs[],
limit: number = 12,
openOrdersDelegate?: Keypair,
): Promise<[TransactionInstruction, Signer[]]> {
const ix = await this.program.methods
.placeOrders(orderType, bids, asks, limit)
.accounts({
signer:
openOrdersDelegate != null
? openOrdersDelegate.publicKey
: this.walletPk,
asks: market.asks,
bids: market.bids,
marketQuoteVault: market.marketQuoteVault,
marketBaseVault: market.marketBaseVault,
eventHeap: market.eventHeap,
market: marketPublicKey,
openOrdersAccount: openOrdersPublicKey,
oracleA: market.oracleA.key,
oracleB: market.oracleB.key,
userBaseAccount,
userQuoteAccount,
tokenProgram: TOKEN_PROGRAM_ID,
openOrdersAdmin,
})
.instruction();
const signers: Signer[] = [];
if (openOrdersDelegate != null) {
signers.push(openOrdersDelegate);
}
return [ix, signers];
}

public async cancelOrderById(
openOrdersPublicKey: PublicKey,
openOrdersAccount: OpenOrdersAccount,
Expand Down Expand Up @@ -846,6 +894,31 @@ export class OpenBookV2Client {
return [ix, signers];
}

public async cancelAllOrders(
openOrdersPublicKey: PublicKey,
openOrdersAccount: OpenOrdersAccount,
market: MarketAccount,
limit: number,
side: Side | null,
openOrdersDelegate?: Keypair,
): Promise<[TransactionInstruction, Signer[]]> {
const ix = await this.program.methods
.cancelAllOrders(side, limit)
.accounts({
signer: openOrdersAccount.owner,
asks: market.asks,
bids: market.bids,
market: openOrdersAccount.market,
openOrdersAccount: openOrdersPublicKey,
})
.instruction();
const signers: Signer[] = [];
if (openOrdersDelegate != null) {
signers.push(openOrdersDelegate);
}
return [ix, signers];
}

public async closeOpenOrdersIndexerIx(
owner: Keypair,
market: MarketAccount,
Expand Down
10 changes: 5 additions & 5 deletions ts/client/src/market.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
getProvider,
BN,
} from '@coral-xyz/anchor';
import { QUOTE_DECIMALS, toNative, toUiDecimals } from './utils/utils';
import { toNative, toUiDecimals } from './utils/utils';
import Big from 'big.js';
import { IDL, type OpenbookV2 } from './openbook_v2';
const BATCH_TX_SIZE = 50;
Expand Down Expand Up @@ -124,7 +124,7 @@ export async function findAllMarkets(

function priceLotsToUiConverter(market: MarketAccount): number {
return new Big(10)
.pow(market.baseDecimals - QUOTE_DECIMALS)
.pow(market.baseDecimals - market.quoteDecimals)
.mul(new Big(market.quoteLotSize.toString()))
.div(new Big(market.baseLotSize.toString()))
.toNumber();
Expand All @@ -142,7 +142,7 @@ function quoteLotsToUiConverter(market: MarketAccount): number {
}

export function uiPriceToLots(market: MarketAccount, price: number): BN {
return toNative(price, QUOTE_DECIMALS)
return toNative(price, market.quoteDecimals)
.mul(market.baseLotSize)
.div(market.quoteLotSize.mul(new BN(Math.pow(10, market.baseDecimals))));
}
Expand All @@ -152,7 +152,7 @@ export function uiBaseToLots(market: MarketAccount, quantity: number): BN {
}

export function uiQuoteToLots(market: MarketAccount, uiQuote: number): BN {
return toNative(uiQuote, QUOTE_DECIMALS).div(market.quoteLotSize);
return toNative(uiQuote, market.quoteDecimals).div(market.quoteLotSize);
}

export function priceLotsToNative(market: MarketAccount, price: BN): BN {
Expand All @@ -164,7 +164,7 @@ export function priceLotsToUi(market: MarketAccount, price: BN): number {
}

export function priceNativeToUi(market: MarketAccount, price: number): number {
return toUiDecimals(price, QUOTE_DECIMALS - market.baseDecimals);
return toUiDecimals(price, market.quoteDecimals - market.baseDecimals);
}

export function baseLotsToUi(market: MarketAccount, quantity: BN): number {
Expand Down
Loading

0 comments on commit 591c193

Please sign in to comment.