Merge branch 'dev'

This commit is contained in:
microwavedcola1 2022-04-12 21:23:27 +02:00
commit 30714fb0dc
44 changed files with 3588 additions and 650 deletions

3554
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,6 @@
[workspace]
members = [
"programs/*",
"keeper",
"lib/*"
]

22
keeper/Cargo.toml Normal file
View File

@ -0,0 +1,22 @@
[package]
name = "keeper"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anchor-client = "0.22.0"
anchor-lang = "0.22.0"
anyhow = "1.0"
mango-v4 = { path = "../programs/mango-v4" }
solana-account-decoder = "1.9.5"
solana-client = "1.9.5"
solana-program = "1.9.5"
solana-rpc = "1.9.5"
solana-sdk = "1.9.5"
solana-transaction-status = "1.9.5"
tokio = { version = "1.17", features = ["rt-multi-thread", "time", "macros", "sync"] }
shellexpand = "2.1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

66
keeper/src/main.rs Normal file
View File

@ -0,0 +1,66 @@
use std::{rc::Rc, str::FromStr, time::Duration};
use solana_sdk::{instruction::Instruction, signature::Keypair};
use tokio::time;
// TODO:
// cmd line args with defaults
// make keypair, rpc server, net, etc. configurable
// expand to various tasks e.g. crank event queue, crank banks, run liquidators
// support multiple workers
// logging facility
// robust error handling
fn main() {
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(update_index_runner())
.expect("Something went wrong here...");
}
pub async fn update_index_runner() -> anyhow::Result<()> {
let mut interval = time::interval(Duration::from_millis(10));
loop {
interval.tick().await;
update_index().await?;
}
}
pub async fn update_index() -> anyhow::Result<()> {
let keypair = load_default_keypair()?;
let rpc = "https://mango.devnet.rpcpool.com".to_owned();
let wss = rpc.replace("https", "wss");
let connection =
anchor_client::Client::new(anchor_client::Cluster::Custom(rpc, wss), Rc::new(keypair));
let client = connection.program(mango_v4::ID);
let update_index_ix = Instruction {
program_id: mango_v4::id(),
accounts: anchor_lang::ToAccountMetas::to_account_metas(
&mango_v4::accounts::UpdateIndex {
bank: anchor_lang::prelude::Pubkey::from_str(
"9xmZdkWbYNYsBshr7PwjhU8c7mmrvzmocu8dSQeNCKTG",
)?,
},
None,
),
data: anchor_lang::InstructionData::data(&mango_v4::instruction::UpdateIndex {}),
};
let sig = client.request().instruction(update_index_ix).send()?;
println!("update_index: {:?}", sig);
Ok(())
}
fn load_default_keypair() -> anyhow::Result<Keypair> {
let keypair_path = shellexpand::tilde("~/.config/solana/mango-devnet.json");
let keypair_data = std::fs::read_to_string(keypair_path.to_string())?;
let keypair_bytes: Vec<u8> = serde_json::from_str(&keypair_data)?;
let keypair = Keypair::from_bytes(&keypair_bytes)?;
Ok(keypair)
}

View File

@ -2,6 +2,7 @@ use anchor_lang::prelude::*;
use crate::error::*;
use crate::state::*;
use crate::util::fill32_from_str;
#[derive(Accounts)]
#[instruction(account_num: u8)]
@ -25,10 +26,11 @@ pub struct CreateAccount<'info> {
pub system_program: Program<'info, System>,
}
pub fn create_account(ctx: Context<CreateAccount>, account_num: u8) -> Result<()> {
pub fn create_account(ctx: Context<CreateAccount>, account_num: u8, name: String) -> Result<()> {
let mut account = ctx.accounts.account.load_init()?;
// TODO: dont init on stack
*account = MangoAccount {
name: fill32_from_str(name)?,
group: ctx.accounts.group.key(),
owner: ctx.accounts.owner.key(),
delegate: Pubkey::default(),

View File

@ -8,6 +8,7 @@ use fixed_macro::types::I80F48;
// TODO: ALTs are unavailable
//use crate::address_lookup_table;
use crate::state::*;
use crate::util::fill16_from_str;
const INDEX_START: I80F48 = I80F48!(1_000_000);
@ -74,17 +75,23 @@ pub struct RegisterToken<'info> {
pub rent: Sysvar<'info, Rent>,
}
#[derive(AnchorSerialize, AnchorDeserialize, Default)]
pub struct InterestRateParams {
pub util0: f32,
pub rate0: f32,
pub util1: f32,
pub rate1: f32,
pub max_rate: f32,
}
// TODO: should this be "configure_mint", we pass an explicit index, and allow
// overwriting config as long as the mint account stays the same?
#[allow(clippy::too_many_arguments)]
pub fn register_token(
ctx: Context<RegisterToken>,
token_index: TokenIndex,
util0: f32,
rate0: f32,
util1: f32,
rate1: f32,
max_rate: f32,
name: String,
interest_rate_params: InterestRateParams,
maint_asset_weight: f32,
init_asset_weight: f32,
maint_liab_weight: f32,
@ -95,6 +102,7 @@ pub fn register_token(
let mut bank = ctx.accounts.bank.load_init()?;
*bank = Bank {
name: fill16_from_str(name)?,
group: ctx.accounts.group.key(),
mint: ctx.accounts.mint.key(),
vault: ctx.accounts.vault.key(),
@ -104,11 +112,12 @@ pub fn register_token(
indexed_total_deposits: I80F48::ZERO,
indexed_total_borrows: I80F48::ZERO,
last_updated: Clock::get()?.unix_timestamp,
util0: I80F48::from_num(util0),
rate0: I80F48::from_num(rate0),
util1: I80F48::from_num(util1),
rate1: I80F48::from_num(rate1),
max_rate: I80F48::from_num(max_rate),
// TODO: add a require! verifying relation between the parameters
util0: I80F48::from_num(interest_rate_params.util0),
rate0: I80F48::from_num(interest_rate_params.rate0),
util1: I80F48::from_num(interest_rate_params.util1),
rate1: I80F48::from_num(interest_rate_params.rate1),
max_rate: I80F48::from_num(interest_rate_params.max_rate),
maint_asset_weight: I80F48::from_num(maint_asset_weight),
init_asset_weight: I80F48::from_num(init_asset_weight),
maint_liab_weight: I80F48::from_num(maint_liab_weight),

View File

@ -3,6 +3,7 @@ use anchor_lang::prelude::*;
use crate::error::MangoError;
use crate::serum3_cpi::{load_market_state, pubkey_from_u64_array};
use crate::state::*;
use crate::util::fill16_from_str;
#[derive(Accounts)]
pub struct Serum3RegisterMarket<'info> {
@ -42,6 +43,7 @@ pub struct Serum3RegisterMarket<'info> {
pub fn serum3_register_market(
ctx: Context<Serum3RegisterMarket>,
market_index: Serum3MarketIndex,
name: String,
) -> Result<()> {
// TODO: must guard against accidentally using the same market_index twice!
@ -62,6 +64,7 @@ pub fn serum3_register_market(
let mut serum_market = ctx.accounts.serum_market.load_init()?;
*serum_market = Serum3Market {
name: fill16_from_str(name)?,
group: ctx.accounts.group.key(),
serum_program: ctx.accounts.serum_program.key(),
serum_market_external: ctx.accounts.serum_market_external.key(),

View File

@ -4,10 +4,13 @@ use crate::state::Bank;
#[derive(Accounts)]
pub struct UpdateIndex<'info> {
// TODO: should we support arbitrary number of banks with remaining accounts?
// ix - consumed 17641 of 101000 compute units, so we have a lot of compute
#[account(mut)]
pub bank: AccountLoader<'info, Bank>,
}
pub fn update_index(ctx: Context<UpdateIndex>) -> Result<()> {
// TODO: should we enforce a minimum window between 2 update_index ix calls?
let now_ts = Clock::get()?.unix_timestamp;
let mut bank = ctx.accounts.bank.load_mut()?;

View File

@ -37,11 +37,8 @@ pub mod mango_v4 {
pub fn register_token(
ctx: Context<RegisterToken>,
token_index: TokenIndex,
util0: f32,
rate0: f32,
util1: f32,
rate1: f32,
max_rate: f32,
name: String,
interest_rate_params: InterestRateParams,
maint_asset_weight: f32,
init_asset_weight: f32,
maint_liab_weight: f32,
@ -51,11 +48,8 @@ pub mod mango_v4 {
instructions::register_token(
ctx,
token_index,
util0,
rate0,
util1,
rate1,
max_rate,
name,
interest_rate_params,
maint_asset_weight,
init_asset_weight,
maint_liab_weight,
@ -68,8 +62,12 @@ pub mod mango_v4 {
instructions::update_index(ctx)
}
pub fn create_account(ctx: Context<CreateAccount>, account_num: u8) -> Result<()> {
instructions::create_account(ctx, account_num)
pub fn create_account(
ctx: Context<CreateAccount>,
account_num: u8,
name: String,
) -> Result<()> {
instructions::create_account(ctx, account_num, name)
}
pub fn close_account(ctx: Context<CloseAccount>) -> Result<()> {
@ -112,8 +110,9 @@ pub mod mango_v4 {
pub fn serum3_register_market(
ctx: Context<Serum3RegisterMarket>,
market_index: Serum3MarketIndex,
name: String,
) -> Result<()> {
instructions::serum3_register_market(ctx, market_index)
instructions::serum3_register_market(ctx, market_index, name)
}
pub fn serum3_create_open_orders(ctx: Context<Serum3CreateOpenOrders>) -> Result<()> {

View File

@ -10,6 +10,8 @@ pub const YEAR: I80F48 = I80F48!(31536000);
#[account(zero_copy)]
pub struct Bank {
pub name: [u8; 16],
pub group: Pubkey,
pub mint: Pubkey,
pub vault: Pubkey,
@ -52,7 +54,7 @@ pub struct Bank {
pub reserved: [u8; 6],
}
const_assert_eq!(size_of::<Bank>(), 32 * 4 + 8 + 16 * 15 + 2 + 6);
const_assert_eq!(size_of::<Bank>(), 16 + 32 * 4 + 8 + 16 * 15 + 2 + 6);
const_assert_eq!(size_of::<Bank>() % 8, 0);
impl Bank {
@ -165,17 +167,20 @@ impl Bank {
}
pub fn update_index(&mut self, now_ts: i64) -> Result<()> {
let utilization = cm!(self.native_total_borrows() / self.native_total_deposits());
let utilization = if self.native_total_deposits() == I80F48::ZERO {
I80F48::ZERO
} else {
cm!(self.native_total_borrows() / self.native_total_deposits())
};
let interest_rate = self.compute_interest_rate(utilization);
let diff_ts = I80F48::from_num(now_ts - self.last_updated);
self.last_updated = now_ts;
let borrow_interest: I80F48 = cm!(interest_rate * diff_ts);
let deposit_interest = cm!(borrow_interest * utilization);
self.last_updated = Clock::get()?.unix_timestamp;
if borrow_interest <= I80F48::ZERO || deposit_interest <= I80F48::ZERO {
return Ok(());
}
@ -219,9 +224,9 @@ impl Bank {
let slope = cm!((rate1 - rate0) / (util1 - util0));
cm!(rate0 + slope * extra_util)
} else {
let extra_util = utilization - util1;
let slope = (max_rate - rate1) / (I80F48::ONE - util1);
rate1 + slope * extra_util
let extra_util = cm!(utilization - util1);
let slope = cm!((max_rate - rate1) / (I80F48::ONE - util1));
cm!(rate1 + slope * extra_util)
}
}
}

View File

@ -512,6 +512,8 @@ impl Default for MangoAccountPerps {
#[account(zero_copy)]
pub struct MangoAccount {
pub name: [u8; 32],
pub group: Pubkey,
pub owner: Pubkey,
@ -542,7 +544,7 @@ pub struct MangoAccount {
}
const_assert_eq!(
size_of::<MangoAccount>(),
3 * 32
32 + 3 * 32
+ size_of::<MangoAccountTokens>()
+ size_of::<MangoAccountSerum3>()
+ size_of::<MangoAccountPerps>()

View File

@ -8,6 +8,7 @@ pub type Serum3MarketIndex = u16;
#[account(zero_copy)]
pub struct Serum3Market {
pub name: [u8; 16],
pub group: Pubkey,
pub serum_program: Pubkey,
pub serum_market_external: Pubkey,
@ -19,7 +20,7 @@ pub struct Serum3Market {
pub bump: u8,
pub reserved: [u8; 1],
}
const_assert_eq!(size_of::<Serum3Market>(), 32 * 3 + 3 * 2 + 1 + 1);
const_assert_eq!(size_of::<Serum3Market>(), 16 + 32 * 3 + 3 * 2 + 1 + 1);
const_assert_eq!(size_of::<Serum3Market>() % 8, 0);
#[macro_export]

View File

@ -1,7 +1,7 @@
use crate::error::MangoError;
use anchor_lang::prelude::*;
use anchor_lang::ZeroCopy;
use arrayref::array_ref;
use fixed::types::I80F48;
use std::cell::RefMut;
use std::{cell::Ref, mem};
@ -90,10 +90,20 @@ impl<'info> LoadZeroCopy for AccountInfo<'info> {
}
}
// Returns asset_weight and liab_weight
pub fn get_leverage_weights(leverage: I80F48) -> (I80F48, I80F48) {
(
(leverage - I80F48::ONE).checked_div(leverage).unwrap(),
(leverage + I80F48::ONE).checked_div(leverage).unwrap(),
)
pub fn fill16_from_str(name: String) -> Result<[u8; 16]> {
let name_bytes = name.as_bytes();
msg!("{}", name);
require!(name_bytes.len() < 16, MangoError::SomeError);
let mut name_ = [0u8; 16];
name_[..name_bytes.len()].copy_from_slice(name_bytes);
Ok(name_)
}
pub fn fill32_from_str(name: String) -> Result<[u8; 32]> {
let name_bytes = name.as_bytes();
msg!("{}", name);
require!(name_bytes.len() < 32, MangoError::SomeError);
let mut name_ = [0u8; 32];
name_[..name_bytes.len()].copy_from_slice(name_bytes);
Ok(name_)
}

View File

@ -5,11 +5,14 @@ use anchor_lang::solana_program::sysvar::{self, SysvarId};
use anchor_spl::token::{Token, TokenAccount};
use fixed::types::I80F48;
use itertools::Itertools;
use mango_v4::instructions::{Serum3OrderType, Serum3SelfTradeBehavior, Serum3Side};
use mango_v4::instructions::{
InterestRateParams, Serum3OrderType, Serum3SelfTradeBehavior, Serum3Side,
};
use solana_program::instruction::Instruction;
use solana_program_test::BanksClientError;
use solana_sdk::instruction;
use solana_sdk::signature::{Keypair, Signer};
use solana_sdk::transport::TransportError;
use std::str::FromStr;
use super::solana::SolanaCookie;
@ -35,7 +38,7 @@ impl ClientAccountLoader for &SolanaCookie {
pub async fn send_tx<CI: ClientInstruction>(
solana: &SolanaCookie,
ix: CI,
) -> std::result::Result<CI::Accounts, TransportError> {
) -> std::result::Result<CI::Accounts, BanksClientError> {
let (accounts, instruction) = ix.to_instruction(solana).await;
let signers = ix.signers();
let instructions = vec![instruction];
@ -471,12 +474,15 @@ impl<'keypair> ClientInstruction for RegisterTokenInstruction<'keypair> {
) -> (Self::Accounts, instruction::Instruction) {
let program_id = mango_v4::id();
let instruction = Self::Instruction {
name: "some_ticker".to_string(),
token_index: self.token_index,
util0: self.util0,
rate0: self.rate0,
util1: self.util1,
rate1: self.rate1,
max_rate: self.max_rate,
interest_rate_params: InterestRateParams {
util0: self.util0,
rate0: self.rate0,
util1: self.util1,
rate1: self.rate1,
max_rate: self.max_rate,
},
maint_asset_weight: self.maint_asset_weight,
init_asset_weight: self.init_asset_weight,
maint_liab_weight: self.maint_liab_weight,
@ -699,6 +705,7 @@ impl<'keypair> ClientInstruction for CreateAccountInstruction<'keypair> {
let program_id = mango_v4::id();
let instruction = mango_v4::instruction::CreateAccount {
account_num: self.account_num,
name: "my_mango_account".to_string(),
};
let account = Pubkey::find_program_address(
@ -785,6 +792,7 @@ impl<'keypair> ClientInstruction for Serum3RegisterMarketInstruction<'keypair> {
let program_id = mango_v4::id();
let instruction = Self::Instruction {
market_index: self.market_index,
name: "UUU/usdc".to_string(),
};
let serum_market = Pubkey::find_program_address(

View File

@ -72,10 +72,10 @@ impl<'a> GroupWithTokensConfig<'a> {
RegisterTokenInstruction {
token_index,
decimals: mint.decimals,
util0: 0.50,
rate0: 0.06,
util1: 0.70,
rate1: 1.3,
util0: 0.40,
rate0: 0.07,
util1: 0.80,
rate1: 0.9,
max_rate: 1.50,
maint_asset_weight: 0.8,
init_asset_weight: 0.6,

View File

@ -3,7 +3,6 @@ use std::sync::{Arc, RwLock};
use anchor_lang::AccountDeserialize;
use anchor_spl::token::TokenAccount;
use solana_program::clock::UnixTimestamp;
use solana_program::{program_pack::Pack, rent::*, system_instruction};
use solana_program_test::*;
use solana_sdk::{
@ -12,12 +11,9 @@ use solana_sdk::{
pubkey::Pubkey,
signature::{Keypair, Signer},
transaction::Transaction,
transport::TransportError,
};
use spl_token::*;
use super::mango_client::ClientAccountLoader;
pub struct SolanaCookie {
pub context: RefCell<ProgramTestContext>,
pub rent: Rent,
@ -30,7 +26,7 @@ impl SolanaCookie {
&self,
instructions: &[Instruction],
signers: Option<&[&Keypair]>,
) -> Result<(), TransportError> {
) -> Result<(), BanksClientError> {
self.program_log.write().unwrap().clear();
let mut context = self.context.borrow_mut();

View File

@ -2,7 +2,7 @@
use fixed::types::I80F48;
use solana_program_test::*;
use solana_sdk::{signature::Keypair, signature::Signer, transport::TransportError};
use solana_sdk::{signature::Keypair, signature::Signer};
use mango_v4::state::*;
use program_test::*;
@ -12,7 +12,7 @@ mod program_test;
// This is an unspecific happy-case test that just runs a few instructions to check
// that they work in principle. It should be split up / renamed.
#[tokio::test]
async fn test_basic() -> Result<(), TransportError> {
async fn test_basic() -> Result<(), BanksClientError> {
let context = TestContext::new().await;
let solana = &context.solana.clone();

View File

@ -2,11 +2,11 @@
use program_test::*;
use solana_program_test::*;
use solana_sdk::transport::TransportError;
mod program_test;
#[tokio::test]
async fn test_benchmark() -> Result<(), TransportError> {
async fn test_benchmark() -> Result<(), BanksClientError> {
let context = TestContext::new().await;
let solana = &context.solana.clone();

View File

@ -1,7 +1,7 @@
#![cfg(feature = "test-bpf")]
use solana_program_test::*;
use solana_sdk::{signature::Keypair, transport::TransportError};
use solana_sdk::signature::Keypair;
use program_test::*;
@ -9,7 +9,7 @@ mod program_test;
// Try to reach compute limits in health checks by having many different tokens in an account
#[tokio::test]
async fn test_health_compute_tokens() -> Result<(), TransportError> {
async fn test_health_compute_tokens() -> Result<(), BanksClientError> {
let context = TestContext::new().await;
let solana = &context.solana.clone();
@ -72,7 +72,7 @@ async fn test_health_compute_tokens() -> Result<(), TransportError> {
// Try to reach compute limits in health checks by having many serum markets in an account
#[tokio::test]
async fn test_health_compute_serum() -> Result<(), TransportError> {
async fn test_health_compute_serum() -> Result<(), BanksClientError> {
let context = TestContext::new().await;
let solana = &context.solana.clone();

View File

@ -2,7 +2,7 @@
use fixed::types::I80F48;
use solana_program_test::*;
use solana_sdk::{signature::Keypair, transport::TransportError};
use solana_sdk::signature::Keypair;
use mango_v4::{
instructions::{Serum3OrderType, Serum3SelfTradeBehavior, Serum3Side},
@ -13,7 +13,7 @@ use program_test::*;
mod program_test;
#[tokio::test]
async fn test_liq_tokens_force_cancel() -> Result<(), TransportError> {
async fn test_liq_tokens_force_cancel() -> Result<(), BanksClientError> {
let context = TestContext::new().await;
let solana = &context.solana.clone();
@ -216,7 +216,7 @@ async fn test_liq_tokens_force_cancel() -> Result<(), TransportError> {
}
#[tokio::test]
async fn test_liq_tokens_with_token() -> Result<(), TransportError> {
async fn test_liq_tokens_with_token() -> Result<(), BanksClientError> {
let context = TestContext::new().await;
let solana = &context.solana.clone();

View File

@ -3,8 +3,8 @@
use anchor_lang::InstructionData;
use fixed::types::I80F48;
use solana_program_test::*;
use solana_sdk::signature::Keypair;
use solana_sdk::signature::Signer;
use solana_sdk::{signature::Keypair, transport::TransportError};
use mango_v4::state::*;
use program_test::*;
@ -14,7 +14,7 @@ mod program_test;
// This is an unspecific happy-case test that just runs a few instructions to check
// that they work in principle. It should be split up / renamed.
#[tokio::test]
async fn test_margin_trade() -> Result<(), TransportError> {
async fn test_margin_trade() -> Result<(), BanksClientError> {
let mut builder = TestContextBuilder::new();
let margin_trade = builder.add_margin_trade_program();
let context = builder.start_default().await;

View File

@ -2,14 +2,14 @@
use mango_v4::state::*;
use solana_program_test::*;
use solana_sdk::{signature::Keypair, transport::TransportError};
use solana_sdk::signature::Keypair;
use program_test::*;
mod program_test;
#[tokio::test]
async fn test_perp() -> Result<(), TransportError> {
async fn test_perp() -> Result<(), BanksClientError> {
let context = TestContext::new().await;
let solana = &context.solana.clone();

View File

@ -1,7 +1,7 @@
#![cfg(feature = "test-bpf")]
use solana_program_test::*;
use solana_sdk::{signature::Keypair, transport::TransportError};
use solana_sdk::signature::Keypair;
use mango_v4::{
instructions::{Serum3OrderType, Serum3SelfTradeBehavior, Serum3Side},
@ -12,7 +12,7 @@ use program_test::*;
mod program_test;
#[tokio::test]
async fn test_serum() -> Result<(), TransportError> {
async fn test_serum() -> Result<(), BanksClientError> {
let context = TestContext::new().await;
let solana = &context.solana.clone();

View File

@ -2,14 +2,14 @@
use mango_v4::state::Bank;
use solana_program_test::*;
use solana_sdk::{signature::Keypair, transport::TransportError};
use solana_sdk::signature::Keypair;
use program_test::*;
mod program_test;
#[tokio::test]
async fn test_update_index() -> Result<(), TransportError> {
async fn test_update_index() -> Result<(), BanksClientError> {
let context = TestContext::new().await;
let solana = &context.solana.clone();

View File

@ -8,9 +8,8 @@
"scripts": {
"build": "tsc",
"clean": "rm -rf dist",
"example0": "ts-node ts/example0.ts",
"example1-user": "ts-node ts/example1-user.ts",
"example1-admin": "ts-node ts/example1-admin.ts",
"example1-user": "ts-node src/example1-user.ts",
"example1-admin": "ts-node src/example1-admin.ts",
"format": "prettier --check .",
"lint": "eslint . --ext ts --ext tsx --ext js --quiet",
"type-check": "tsc --pretty --noEmit"

View File

@ -1,15 +1,18 @@
import { utf8 } from '@project-serum/anchor/dist/cjs/utils/bytes';
import { PublicKey } from '@solana/web3.js';
import bs58 from 'bs58';
import { MangoClient } from '../../client';
import { MangoClient } from '../client';
import { I80F48, I80F48Dto } from './I80F48';
export class Bank {
public name: string;
public depositIndex: I80F48;
public borrowIndex: I80F48;
static from(
publicKey: PublicKey,
obj: {
name: number[];
group: PublicKey;
mint: PublicKey;
vault: PublicKey;
@ -29,6 +32,7 @@ export class Bank {
) {
return new Bank(
publicKey,
obj.name,
obj.group,
obj.mint,
obj.vault,
@ -49,6 +53,7 @@ export class Bank {
constructor(
public publicKey: PublicKey,
name: number[],
public group: PublicKey,
public mint: PublicKey,
public vault: PublicKey,
@ -65,6 +70,7 @@ export class Bank {
dust: Object,
public tokenIndex: number,
) {
this.name = utf8.decode(new Uint8Array(name)).split('\x00')[0];
this.depositIndex = I80F48.from(depositIndex);
this.borrowIndex = I80F48.from(borrowIndex);
}

View File

@ -1,9 +1,5 @@
import { PublicKey } from '@solana/web3.js';
import { MangoClient } from '../../client';
import {
DEVNET_MINTS_REVERSE,
DEVNET_SERUM3_MARKETS_REVERSE,
} from '../../constants';
import { MangoClient } from '../client';
import { Bank } from './bank';
import { Serum3Market } from './serum3';
@ -32,20 +28,13 @@ export class Group {
public async reloadBanks(client: MangoClient) {
const banks = await client.getBanksForGroup(this);
this.banksMap = new Map(
banks.map((bank) => [DEVNET_MINTS_REVERSE[bank.mint.toBase58()], bank]),
);
this.banksMap = new Map(banks.map((bank) => [bank.name, bank]));
}
public async reloadSerum3Markets(client: MangoClient) {
const serum3Markets = await client.serum3GetMarket(this);
this.serum3MarketsMap = new Map(
serum3Markets.map((serum3Market) => [
DEVNET_SERUM3_MARKETS_REVERSE[
serum3Market.serumMarketExternal.toBase58()
],
serum3Market,
]),
serum3Markets.map((serum3Market) => [serum3Market.name, serum3Market]),
);
}
}

View File

@ -1,14 +1,16 @@
import { utf8 } from '@project-serum/anchor/dist/cjs/utils/bytes';
import { PublicKey } from '@solana/web3.js';
import { Bank } from './bank';
import { I80F48, I80F48Dto } from './I80F48';
export class MangoAccount {
public tokens: TokenAccount[];
public serum3: Serum3Account[];
public name: string;
static from(
publicKey: PublicKey,
obj: {
name: number[];
group: PublicKey;
owner: PublicKey;
delegate: PublicKey;
@ -24,6 +26,7 @@ export class MangoAccount {
) {
return new MangoAccount(
publicKey,
obj.name,
obj.group,
obj.owner,
obj.delegate,
@ -40,6 +43,7 @@ export class MangoAccount {
constructor(
public publicKey: PublicKey,
name: number[],
public group: PublicKey,
public owner: PublicKey,
public delegate: PublicKey,
@ -52,6 +56,7 @@ export class MangoAccount {
bump: number,
reserved: number[],
) {
this.name = utf8.decode(new Uint8Array(name)).split('\x00')[0];
this.tokens = tokens.values.map((dto) => TokenAccount.from(dto));
this.serum3 = serum3.values.map((dto) => Serum3Account.from(dto));
}

View File

@ -1,6 +1,6 @@
import { PublicKey, TransactionSignature } from '@solana/web3.js';
import BN from 'bn.js';
import { MangoClient } from '../../client';
import { MangoClient } from '../client';
import { I80F48, I80F48Dto } from './I80F48';
export class StubOracle {

View File

@ -1,9 +1,12 @@
import { utf8 } from '@project-serum/anchor/dist/cjs/utils/bytes';
import { PublicKey } from '@solana/web3.js';
export class Serum3Market {
public name: string;
static from(
publicKey: PublicKey,
obj: {
name: number[];
group: PublicKey;
serumProgram: PublicKey;
serumMarketExternal: PublicKey;
@ -16,6 +19,7 @@ export class Serum3Market {
): Serum3Market {
return new Serum3Market(
publicKey,
obj.name,
obj.group,
obj.serumProgram,
obj.serumMarketExternal,
@ -27,13 +31,16 @@ export class Serum3Market {
constructor(
public publicKey: PublicKey,
name: number[],
public group: PublicKey,
public serumProgram: PublicKey,
public serumMarketExternal: PublicKey,
public marketIndex: number,
public baseTokenIndex: number,
public quoteTokenIndex: number,
) {}
) {
this.name = utf8.decode(new Uint8Array(name)).split('\x00')[0];
}
}
export class Serum3SelfTradeBehavior {

View File

@ -10,17 +10,17 @@ import {
TransactionSignature,
} from '@solana/web3.js';
import bs58 from 'bs58';
import { Bank, getMintInfoForTokenIndex } from './accounts/types/bank';
import { Group } from './accounts/types/group';
import { I80F48 } from './accounts/types/I80F48';
import { MangoAccount } from './accounts/types/mangoAccount';
import { StubOracle } from './accounts/types/oracle';
import { Bank, getMintInfoForTokenIndex } from './accounts/bank';
import { Group } from './accounts/group';
import { I80F48 } from './accounts/I80F48';
import { MangoAccount } from './accounts/mangoAccount';
import { StubOracle } from './accounts/oracle';
import {
Serum3Market,
Serum3OrderType,
Serum3SelfTradeBehavior,
Serum3Side,
} from './accounts/types/serum3';
} from './accounts/serum3';
import { IDL, MangoV4 } from './mango_v4';
export const MANGO_V4_ID = new PublicKey(
@ -76,15 +76,28 @@ export class MangoClient {
mintPk: PublicKey,
oraclePk: PublicKey,
tokenIndex: number,
name: string,
util0: number,
rate0: number,
util1: number,
rate1: number,
maxRate: number,
maintAssetWeight: number,
initAssetWeight: number,
maintLiabWeight: number,
initLiabWeight: number,
liquidationFee: number,
): Promise<TransactionSignature> {
return await this.program.methods
.registerToken(
tokenIndex,
0.8,
0.6,
1.2,
1.4,
0.02 /*TODO expose as args*/,
name,
{ util0, rate0, util1, rate1, maxRate },
maintAssetWeight,
initAssetWeight,
maintLiabWeight,
initLiabWeight,
liquidationFee,
)
.accounts({
group: group.publicKey,
@ -103,7 +116,7 @@ export class MangoClient {
{
memcmp: {
bytes: group.publicKey.toBase58(),
offset: 8,
offset: 24,
},
},
])
@ -173,10 +186,11 @@ export class MangoClient {
group: Group,
ownerPk: PublicKey,
accountNumber?: number,
name?: string,
): Promise<MangoAccount> {
let mangoAccounts = await this.getMangoAccountForOwner(group, ownerPk);
if (mangoAccounts.length === 0) {
await this.createMangoAccount(group, accountNumber ?? 0);
await this.createMangoAccount(group, accountNumber ?? 0, name ?? '');
mangoAccounts = await this.getMangoAccountForOwner(group, ownerPk);
}
return mangoAccounts[0];
@ -185,9 +199,10 @@ export class MangoClient {
public async createMangoAccount(
group: Group,
accountNumber: number,
name?: string,
): Promise<TransactionSignature> {
return await this.program.methods
.createAccount(accountNumber)
.createAccount(accountNumber, name ?? '')
.accounts({
group: group.publicKey,
owner: this.program.provider.wallet.publicKey,
@ -212,13 +227,13 @@ export class MangoClient {
{
memcmp: {
bytes: group.publicKey.toBase58(),
offset: 8,
offset: 24,
},
},
{
memcmp: {
bytes: ownerPk.toBase58(),
offset: 40,
offset: 56,
},
},
])
@ -320,9 +335,10 @@ export class MangoClient {
baseBank: Bank,
quoteBank: Bank,
marketIndex: number,
name: string,
): Promise<TransactionSignature> {
return await this.program.methods
.serum3RegisterMarket(marketIndex)
.serum3RegisterMarket(marketIndex, name)
.accounts({
group: group.publicKey,
admin: this.program.provider.wallet.publicKey,
@ -347,7 +363,7 @@ export class MangoClient {
{
memcmp: {
bytes: group.publicKey.toBase58(),
offset: 8,
offset: 24,
},
},
];
@ -358,7 +374,7 @@ export class MangoClient {
filters.push({
memcmp: {
bytes: bs58.encode(bbuf),
offset: 106,
offset: 122,
},
});
}
@ -369,7 +385,7 @@ export class MangoClient {
filters.push({
memcmp: {
bytes: bs58.encode(qbuf),
offset: 108,
offset: 124,
},
});
}

View File

@ -1,6 +1,6 @@
import { PublicKey } from '@solana/web3.js';
export const DEVNET_GROUP = 'Fwhv1B7yysktAqmoKbV6f1p25ap26Q81NKvd4jApmiB2';
export const DEVNET_GROUP = '4Fv4jWsd9kYZjCMvkpcXnS63x9cHHHTqCDHTTTB5MbQt';
export const DEVNET_MINTS = new Map([
['USDC', '8FRFC6MoGGkMFQwngccyu69VnYbzykGeez7ignHVAFSN'],

View File

@ -42,7 +42,23 @@ async function main() {
const btcDevnetMint = new PublicKey(DEVNET_MINTS.get('BTC')!);
const btcDevnetOracle = new PublicKey(DEVNET_ORACLES.get('BTC')!);
try {
await client.registerToken(group, btcDevnetMint, btcDevnetOracle, 0);
await client.registerToken(
group,
btcDevnetMint,
btcDevnetOracle,
0,
'BTC',
0.4,
0.07,
0.8,
0.9,
1.5,
0.8,
0.6,
1.2,
1.4,
0.02,
);
} catch (error) {}
// stub oracle + register token 1
@ -58,6 +74,17 @@ async function main() {
usdcDevnetMint,
usdcDevnetOracle.publicKey,
1,
'USDC',
0.4,
0.07,
0.8,
0.9,
1.5,
0.8,
0.6,
1.2,
1.4,
0.02,
);
} catch (error) {}
@ -82,6 +109,7 @@ async function main() {
banks[0],
banks[1],
0,
'BTC/USDC',
);
} catch (error) {}
const markets = await client.serum3GetMarket(

View File

@ -5,7 +5,7 @@ import {
Serum3OrderType,
Serum3SelfTradeBehavior,
Serum3Side,
} from './accounts/types/serum3';
} from './accounts/serum3';
import { MangoClient } from './client';
import { DEVNET_GROUP, DEVNET_SERUM3_PROGRAM_ID } from './constants';
@ -33,11 +33,16 @@ async function main() {
const group = await client.getGroup(new PublicKey(DEVNET_GROUP));
console.log(`Group ${group.publicKey.toBase58()}`);
for (const bank of group.banksMap.values()) {
console.log(bank.publicKey.toBase58());
}
// create + fetch account
const mangoAccount = await client.getOrCreateMangoAccount(
group,
user.publicKey,
0,
'my_mango_account',
);
console.log(`MangoAccount ${mangoAccount.publicKey}`);

10
ts/client/src/index.ts Normal file
View File

@ -0,0 +1,10 @@
export { Group } from './client/accounts/group';
export * from './client/accounts/I80F48';
export {
MangoAccount,
TokenAccount,
TokenAccountDto,
} from './client/accounts/mangoAccount';
export { StubOracle } from './client/accounts/oracle';
export { Serum3Market } from './client/accounts/serum3';
export * from './client/client';

View File

@ -164,6 +164,16 @@ export type MangoV4 = {
"name": "tokenIndex",
"type": "u16"
},
{
"name": "name",
"type": "string"
},
{
"name": "interestRateParams",
"type": {
"defined": "InterestRateParams"
}
},
{
"name": "maintAssetWeight",
"type": "f32"
@ -186,6 +196,17 @@ export type MangoV4 = {
}
]
},
{
"name": "updateIndex",
"accounts": [
{
"name": "bank",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "createAccount",
"accounts": [
@ -243,6 +264,10 @@ export type MangoV4 = {
{
"name": "accountNum",
"type": "u8"
},
{
"name": "name",
"type": "string"
}
]
},
@ -568,6 +593,10 @@ export type MangoV4 = {
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "name",
"type": "string"
}
]
},
@ -1315,6 +1344,15 @@ export type MangoV4 = {
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": {
"array": [
"u8",
16
]
}
},
{
"name": "group",
"type": "publicKey"
@ -1355,6 +1393,40 @@ export type MangoV4 = {
"defined": "I80F48"
}
},
{
"name": "lastUpdated",
"type": "i64"
},
{
"name": "util0",
"type": {
"defined": "I80F48"
}
},
{
"name": "rate0",
"type": {
"defined": "I80F48"
}
},
{
"name": "util1",
"type": {
"defined": "I80F48"
}
},
{
"name": "rate1",
"type": {
"defined": "I80F48"
}
},
{
"name": "maxRate",
"type": {
"defined": "I80F48"
}
},
{
"name": "maintAssetWeight",
"type": {
@ -1492,6 +1564,15 @@ export type MangoV4 = {
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": {
"array": [
"u8",
16
]
}
},
{
"name": "group",
"type": "publicKey"
@ -1802,6 +1883,15 @@ export type MangoV4 = {
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": {
"array": [
"u8",
16
]
}
},
{
"name": "group",
"type": "publicKey"
@ -2050,6 +2140,34 @@ export type MangoV4 = {
]
}
},
{
"name": "InterestRateParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "util0",
"type": "f32"
},
{
"name": "rate0",
"type": "f32"
},
{
"name": "util1",
"type": "f32"
},
{
"name": "rate1",
"type": "f32"
},
{
"name": "maxRate",
"type": "f32"
}
]
}
},
{
"name": "TokenIndex",
"type": {
@ -2562,6 +2680,16 @@ export const IDL: MangoV4 = {
"name": "tokenIndex",
"type": "u16"
},
{
"name": "name",
"type": "string"
},
{
"name": "interestRateParams",
"type": {
"defined": "InterestRateParams"
}
},
{
"name": "maintAssetWeight",
"type": "f32"
@ -2584,6 +2712,17 @@ export const IDL: MangoV4 = {
}
]
},
{
"name": "updateIndex",
"accounts": [
{
"name": "bank",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "createAccount",
"accounts": [
@ -2641,6 +2780,10 @@ export const IDL: MangoV4 = {
{
"name": "accountNum",
"type": "u8"
},
{
"name": "name",
"type": "string"
}
]
},
@ -2966,6 +3109,10 @@ export const IDL: MangoV4 = {
{
"name": "marketIndex",
"type": "u16"
},
{
"name": "name",
"type": "string"
}
]
},
@ -3713,6 +3860,15 @@ export const IDL: MangoV4 = {
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": {
"array": [
"u8",
16
]
}
},
{
"name": "group",
"type": "publicKey"
@ -3753,6 +3909,40 @@ export const IDL: MangoV4 = {
"defined": "I80F48"
}
},
{
"name": "lastUpdated",
"type": "i64"
},
{
"name": "util0",
"type": {
"defined": "I80F48"
}
},
{
"name": "rate0",
"type": {
"defined": "I80F48"
}
},
{
"name": "util1",
"type": {
"defined": "I80F48"
}
},
{
"name": "rate1",
"type": {
"defined": "I80F48"
}
},
{
"name": "maxRate",
"type": {
"defined": "I80F48"
}
},
{
"name": "maintAssetWeight",
"type": {
@ -3890,6 +4080,15 @@ export const IDL: MangoV4 = {
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": {
"array": [
"u8",
16
]
}
},
{
"name": "group",
"type": "publicKey"
@ -4200,6 +4399,15 @@ export const IDL: MangoV4 = {
"type": {
"kind": "struct",
"fields": [
{
"name": "name",
"type": {
"array": [
"u8",
16
]
}
},
{
"name": "group",
"type": "publicKey"
@ -4448,6 +4656,34 @@ export const IDL: MangoV4 = {
]
}
},
{
"name": "InterestRateParams",
"type": {
"kind": "struct",
"fields": [
{
"name": "util0",
"type": "f32"
},
{
"name": "rate0",
"type": "f32"
},
{
"name": "util1",
"type": "f32"
},
{
"name": "rate1",
"type": "f32"
},
{
"name": "maxRate",
"type": "f32"
}
]
}
},
{
"name": "TokenIndex",
"type": {

View File

@ -1,10 +0,0 @@
export { Group } from './accounts/types/group';
export * from './accounts/types/I80F48';
export {
MangoAccount,
TokenAccount,
TokenAccountDto,
} from './accounts/types/mangoAccount';
export { StubOracle } from './accounts/types/oracle';
export { Serum3Market } from './accounts/types/serum3';
export * from './client';

8
update-local-idl.sh Executable file
View File

@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -e pipefail
anchor build --skip-lint
./idl-fixup.sh
cp -v ./target/types/mango_v4.ts ./ts/mango_v4.ts
tsc