Skip to content

Commit cbb9762

Browse files
wphanjackwallerlowkeyniccgithub-actions[bot]LukasDeco
authored
Wphan/merge-master-devnet (#1897)
* chore: add laserstream client * add hlmm to decodeUser (#1881) * add hlmm to decodeUser * throw if unrecognized margin mode * fallback to default margin mode * sdk: release v2.138.0-beta.2 * fix: update to correct naming * sdk: release v2.138.0-beta.3 * chore: rename lazer -> laser * sdk: release v2.138.0-beta.4 * Revert "chore: rename lazer -> laser" This reverts commit f6d8530. * Revert "fix: update to correct naming" This reverts commit 42c8b10. * Revert "chore: add laserstream client" This reverts commit 8da91cb. * sdk: release v2.138.0-beta.5 * feat: pin deps away from mal packages (#1858) * feat: pin deps away from mal packages * fix: chalk deps break lint * fix: linter unix format * try fix broken anchor tests --------- Co-authored-by: Nick Caradonna <[email protected]> * sdk: release v2.138.0-beta.6 * Revert "Crispeaney/revert swift max margin ratio" (#1877) * Revert "program: revert swift max margin ratio (#1874)" This reverts commit 87bfe72. * add SignedMsgExtensions enum struct variant * Revert "add SignedMsgExtensions enum struct variant" This reverts commit 9dbe65c. * add extended SignedMsgOrderParamsMessage variant * zero pad short swift messages when decoding * revert to single sdk decode function * cargo fmt * comments * use fixed padding for sdk swift decode fn * fix comments * sdk: release v2.138.0-beta.7 * add lp events for evnet subscriber (#1892) * add lp events for evnet subscriber * idl build * sdk: release v2.138.0-beta.8 * CHANGELOG * sdk: fix idl * program: token 22 scaled ui support (#1894) * init * program: scaled ui working * cargo fmt -- * ts lint * sdk: release v2.138.0-beta.9 * fix build --------- Co-authored-by: Jack Waller <[email protected]> Co-authored-by: lowkeynicc <[email protected]> Co-authored-by: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: LukasDeco <[email protected]> Co-authored-by: Nick Caradonna <[email protected]> Co-authored-by: moosecat <[email protected]> Co-authored-by: Chris Heaney <[email protected]>
1 parent 07b8b1f commit cbb9762

File tree

12 files changed

+925
-21
lines changed

12 files changed

+925
-21
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99

1010
### Features
1111

12+
- program: support scaled ui extension ([#1894](https://github.com/drift-labs/protocol-v2/pull/1894))
13+
1214
### Fixes
1315

1416
### Breaking

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
"prettify:fix": "prettier --write './sdk/src/**/*.ts' './tests/**.ts' './cli/**.ts'",
5151
"lint": "eslint . --ext ts --quiet --format unix",
5252
"lint:fix": "eslint . --ext ts --fix",
53-
"update-idl": "cp target/idl/drift.json sdk/src/idl/drift.json"
53+
"update-idl": "anchor build -- --features anchor-test && cp target/idl/drift.json sdk/src/idl/drift.json"
5454
},
5555
"engines": {
5656
"node": ">=12"
@@ -95,4 +95,4 @@
9595
"supports-hyperlinks": "<4.1.1",
9696
"has-ansi": "<6.0.1"
9797
}
98-
}
98+
}

programs/drift/src/controller/token.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,3 +273,21 @@ pub fn transfer_checked_with_transfer_hook<'info>(
273273

274274
solana_program::program::invoke_signed(&ix, &account_infos, signer_seeds).map_err(Into::into)
275275
}
276+
277+
pub fn initialize_token_account<'info>(
278+
token_program: &Interface<'info, TokenInterface>,
279+
account: &AccountInfo<'info>,
280+
owner: &AccountInfo<'info>,
281+
mint: &InterfaceAccount<'info, Mint>,
282+
) -> Result<()> {
283+
let cpi_program = token_program.to_account_info();
284+
let accounts = ::anchor_spl::token_interface::InitializeAccount3 {
285+
account: account.to_account_info(),
286+
mint: mint.to_account_info(),
287+
authority: owner.to_account_info(),
288+
};
289+
let cpi_ctx = anchor_lang::context::CpiContext::new(cpi_program, accounts);
290+
::anchor_spl::token_interface::initialize_account3(cpi_ctx)?;
291+
292+
Ok(())
293+
}

programs/drift/src/instructions/admin.rs

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use serum_dex::state::ToAlignedBytes;
99
use std::convert::{identity, TryInto};
1010
use std::mem::size_of;
1111

12-
use crate::controller::token::close_vault;
12+
use crate::controller::token::{close_vault, initialize_token_account};
1313
use crate::error::ErrorCode;
1414
use crate::ids::{admin_hot_wallet, amm_spread_adjust_wallet, mm_oracle_crank_wallet};
1515
use crate::instructions::constraints::*;
@@ -150,15 +150,19 @@ pub fn handle_initialize_spot_market(
150150
let state = &mut ctx.accounts.state;
151151
let spot_market_pubkey = ctx.accounts.spot_market.key();
152152

153-
// protocol must be authority of collateral vault
154-
if ctx.accounts.spot_market_vault.owner != state.signer {
155-
return Err(ErrorCode::InvalidSpotMarketAuthority.into());
156-
}
153+
initialize_token_account(
154+
&ctx.accounts.token_program,
155+
&ctx.accounts.spot_market_vault,
156+
&ctx.accounts.drift_signer,
157+
&ctx.accounts.spot_market_mint,
158+
)?;
157159

158-
// protocol must be authority of collateral vault
159-
if ctx.accounts.insurance_fund_vault.owner != state.signer {
160-
return Err(ErrorCode::InvalidInsuranceFundAuthority.into());
161-
}
160+
initialize_token_account(
161+
&ctx.accounts.token_program,
162+
&ctx.accounts.insurance_fund_vault,
163+
&ctx.accounts.drift_signer,
164+
&ctx.accounts.spot_market_mint,
165+
)?;
162166

163167
validate_borrow_rate(optimal_utilization, optimal_borrow_rate, max_borrow_rate, 0)?;
164168

@@ -284,7 +288,7 @@ pub fn handle_initialize_spot_market(
284288
historical_oracle_data: historical_oracle_data_default,
285289
historical_index_data: historical_index_data_default,
286290
mint: ctx.accounts.spot_market_mint.key(),
287-
vault: *ctx.accounts.spot_market_vault.to_account_info().key,
291+
vault: ctx.accounts.spot_market_vault.key(),
288292
revenue_pool: PoolBalance {
289293
scaled_balance: 0,
290294
market_index: spot_market_index,
@@ -341,7 +345,7 @@ pub fn handle_initialize_spot_market(
341345
pool_id: 0,
342346
padding: [0; 40],
343347
insurance_fund: InsuranceFund {
344-
vault: *ctx.accounts.insurance_fund_vault.to_account_info().key,
348+
vault: ctx.accounts.insurance_fund_vault.key(),
345349
unstaking_period: THIRTEEN_DAY,
346350
total_factor: if_total_factor,
347351
user_factor: if_total_factor / 2,
@@ -5099,25 +5103,30 @@ pub struct InitializeSpotMarket<'info> {
50995103
payer = admin
51005104
)]
51015105
pub spot_market: AccountLoader<'info, SpotMarket>,
5106+
#[account(
5107+
mint::token_program = token_program,
5108+
)]
51025109
pub spot_market_mint: Box<InterfaceAccount<'info, Mint>>,
51035110
#[account(
51045111
init,
51055112
seeds = [b"spot_market_vault".as_ref(), state.number_of_spot_markets.to_le_bytes().as_ref()],
51065113
bump,
51075114
payer = admin,
5108-
token::mint = spot_market_mint,
5109-
token::authority = drift_signer
5115+
space = get_vault_len(&spot_market_mint)?,
5116+
owner = token_program.key()
51105117
)]
5111-
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
5118+
/// CHECK: checked in `initialize_spot_market`
5119+
pub spot_market_vault: AccountInfo<'info>,
51125120
#[account(
51135121
init,
51145122
seeds = [b"insurance_fund_vault".as_ref(), state.number_of_spot_markets.to_le_bytes().as_ref()],
51155123
bump,
51165124
payer = admin,
5117-
token::mint = spot_market_mint,
5118-
token::authority = drift_signer
5125+
space = get_vault_len(&spot_market_mint)?,
5126+
owner = token_program.key()
51195127
)]
5120-
pub insurance_fund_vault: Box<InterfaceAccount<'info, TokenAccount>>,
5128+
/// CHECK: checked in `initialize_spot_market`
5129+
pub insurance_fund_vault: AccountInfo<'info>,
51215130
#[account(
51225131
constraint = state.signer.eq(&drift_signer.key())
51235132
)]

programs/drift/src/instructions/constraints.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
use anchor_lang::accounts::account::Account;
22
use anchor_lang::accounts::account_loader::AccountLoader;
33
use anchor_lang::accounts::signer::Signer;
4+
use anchor_lang::prelude::*;
45
use anchor_lang::prelude::{AccountInfo, Pubkey};
6+
use anchor_spl::token_interface::Mint;
57

68
use crate::error::ErrorCode;
79
use crate::msg;
@@ -145,3 +147,28 @@ pub fn exchange_not_paused(state: &Account<State>) -> anchor_lang::Result<()> {
145147
}
146148
Ok(())
147149
}
150+
151+
pub fn get_vault_len(mint: &InterfaceAccount<Mint>) -> anchor_lang::Result<usize> {
152+
let mint_info = mint.to_account_info();
153+
let len = if *mint_info.owner == ::anchor_spl::token_2022::Token2022::id() {
154+
use ::anchor_spl::token_2022::spl_token_2022::extension::{
155+
BaseStateWithExtensions, ExtensionType, StateWithExtensions,
156+
};
157+
use ::anchor_spl::token_2022::spl_token_2022::state::{Account, Mint};
158+
let mint_data = mint_info.try_borrow_data()?;
159+
let mint_state = StateWithExtensions::<Mint>::unpack(&mint_data)?;
160+
let mint_extensions = match mint_state.get_extension_types() {
161+
Ok(extensions) => extensions,
162+
// If we cant deserialize the mint, we use the default token account length
163+
// Init token will fail if this size doesnt work, so worst case init account just fails
164+
Err(_) => return Ok(::anchor_spl::token::TokenAccount::LEN),
165+
};
166+
let required_extensions =
167+
ExtensionType::get_required_init_account_extensions(&mint_extensions);
168+
ExtensionType::try_calculate_account_len::<Account>(&required_extensions)?
169+
} else {
170+
::anchor_spl::token::TokenAccount::LEN
171+
};
172+
173+
Ok(len)
174+
}

sdk/VERSION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
2.138.0-beta.8
1+
2.138.0-beta.9

sdk/encode_swift_message.ts

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import { BASE_PRECISION, BN, getMarketOrderParams, getOrderParams, MarketType, PositionDirection } from '@drift-labs/sdk';
2+
import {
3+
DriftClient,
4+
Wallet,
5+
SignedMsgOrderParams,
6+
SignedMsgOrderParamsDelegateMessage,
7+
OrderParams,
8+
// SignedMsgExtensions,
9+
} from './src/';
10+
import {
11+
Connection,
12+
Keypair,
13+
PublicKey,
14+
} from '@solana/web3.js';
15+
import { nanoid } from 'nanoid';
16+
17+
async function main() {
18+
const keypair = Keypair.generate();
19+
console.log(keypair.publicKey.toString());
20+
const driftClient = new DriftClient({
21+
wallet: new Wallet(keypair),
22+
connection: new Connection('https://api.mainnet-beta.solana.com'),
23+
});
24+
const slot = new BN(2345);
25+
26+
// test_deserialize_into_verified_message_delegate_with_max_margin_ratio
27+
// const e0 = driftClient.encodeSignedMsgOrderParamsMessage(
28+
// {
29+
// signedMsgOrderParams: getOrderParams(getMarketOrderParams(
30+
// {
31+
// marketIndex: 0,
32+
// userOrderId: 2,
33+
// price: new BN("237000000"),
34+
// marketType: MarketType.PERP,
35+
// baseAssetAmount: new BN("1000000000"),
36+
// direction: PositionDirection.SHORT,
37+
// reduceOnly: false,
38+
// auctionDuration: 10,
39+
// auctionStartPrice: new BN("240000000"),
40+
// auctionEndPrice: new BN("238000000"),
41+
// }
42+
// )),
43+
// takerPubkey: new PublicKey('HG2iQKnRkkasrLptwMZewV6wT7KPstw9wkA8yyu8Nx3m'),
44+
// slot,
45+
// uuid: Buffer.from([67, 82, 79, 51, 105, 114, 71, 49]),
46+
// takeProfitOrderParams: {
47+
// baseAssetAmount: new BN("1000000000"),
48+
// triggerPrice: new BN("230000000"),
49+
// },
50+
// stopLossOrderParams: {
51+
// baseAssetAmount: new BN("1000000000"),
52+
// triggerPrice: new BN("250000000"),
53+
// },
54+
// ext: SignedMsgExtensions.V1({ maxMarginRatio: 1 }),
55+
// },
56+
// true,
57+
// )
58+
// console.log(JSON.stringify(Array.from(e0)));
59+
60+
// test_deserialize_into_verified_message_non_delegate_with_max_margin_ratio
61+
const delegateSigner = false;
62+
const e0 = driftClient.encodeSignedMsgOrderParamsMessage(
63+
{
64+
signedMsgOrderParams: getOrderParams(getMarketOrderParams(
65+
{
66+
marketIndex: 0,
67+
userOrderId: 3,
68+
price: new BN("237000000"),
69+
marketType: MarketType.PERP,
70+
baseAssetAmount: new BN("3456000000"),
71+
direction: PositionDirection.LONG,
72+
reduceOnly: false,
73+
auctionDuration: 10,
74+
auctionStartPrice: new BN("230000000"),
75+
auctionEndPrice: new BN("237000000"),
76+
}
77+
)),
78+
subAccountId: 2,
79+
slot,
80+
uuid: Buffer.from([67, 82, 79, 51, 105, 114, 71, 49]),
81+
takeProfitOrderParams: {
82+
baseAssetAmount: new BN("3456000000"),
83+
triggerPrice: new BN("240000000"),
84+
},
85+
stopLossOrderParams: {
86+
baseAssetAmount: new BN("3456000000"),
87+
triggerPrice: new BN("225000000"),
88+
},
89+
// ext: SignedMsgExtensions.V0,
90+
// ext: SignedMsgExtensions.V1({ maxMarginRatio: 65535 }),
91+
// ext: SignedMsgExtensions.V2({ maxMarginRatio: 65535, newField: 1, newField2: 2 }),
92+
},
93+
delegateSigner,
94+
);
95+
// console.log('encoded: ', JSON.stringify(Array.from(e0)));
96+
97+
// const messageToDecode = e0;
98+
99+
// v0 message
100+
// const messageToDecode = Buffer.from([200,213,166,94,34,52,245,93,0,1,0,3,0,96,254,205,0,0,0,0,64,85,32,14,0,0,0,0,0,0,0,0,0,0,0,0,0,1,10,1,128,133,181,13,0,0,0,0,1,64,85,32,14,0,0,0,0,2,0,41,9,0,0,0,0,0,0,67,82,79,51,105,114,71,49,1,0,28,78,14,0,0,0,0,0,96,254,205,0,0,0,0,1,64,58,105,13,0,0,0,0,0,96,254,205,0,0,0,0,0]);
101+
102+
// the v1 message
103+
// const messageToDecode = Buffer.from([200,213,166,94,34,52,245,93,0,1,0,3,0,96,254,205,0,0,0,0,64,85,32,14,0,0,0,0,0,0,0,0,0,0,0,0,0,1,10,1,128,133,181,13,0,0,0,0,1,64,85,32,14,0,0,0,0,2,0,41,9,0,0,0,0,0,0,67,82,79,51,105,114,71,49,1,0,28,78,14,0,0,0,0,0,96,254,205,0,0,0,0,1,64,58,105,13,0,0,0,0,0,96,254,205,0,0,0,0,1,1,255,255]);
104+
105+
// the v2 message
106+
const messageToDecode = Buffer.from([200,213,166,94,34,52,245,93,0,1,0,3,0,96,254,205,0,0,0,0,64,85,32,14,0,0,0,0,0,0,0,0,0,0,0,0,0,1,10,1,128,133,181,13,0,0,0,0,1,64,85,32,14,0,0,0,0,2,0,41,9,0,0,0,0,0,0,67,82,79,51,105,114,71,49,1,0,28,78,14,0,0,0,0,0,96,254,205,0,0,0,0,1,64,58,105,13,0,0,0,0,0,96,254,205,0,0,0,0,2,1,255,255,1,1,0,1,2,0]);
107+
108+
console.log('decoding:', JSON.stringify(Array.from((messageToDecode))));
109+
const d0 = driftClient.decodeSignedMsgOrderParamsMessage(messageToDecode, delegateSigner)
110+
console.log(d0)
111+
}
112+
113+
main();

sdk/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@drift-labs/sdk",
3-
"version": "2.138.0-beta.8",
3+
"version": "2.138.0-beta.9",
44
"main": "lib/node/index.js",
55
"types": "lib/node/index.d.ts",
66
"browser": "./lib/browser/index.js",

0 commit comments

Comments
 (0)