Giter VIP home page Giter VIP logo

mango-v3's Introduction

Mango Markets V3 - Decentralized Margin Trading

⚠️ Warning

Any content produced by Blockworks, or developer resources that Blockworks provides, are for educational and inspiration purposes only. Blockworks does not encourage, induce or sanction the deployment of any such applications in violation of applicable laws or regulations.

Contribute

Significant contributions to the source code may be compensated with a grant from the Blockworks Foundation.

Security

Mango has been audited by Neodyme, you can find the report here.

You will be compensated by the Mango DAO for privately reporting vulnerabilities to the maintainers of this repo. Email [email protected]

Branches and Tags

  • New development happens on main. Pull requests should always target main by default.

  • Release branches have names like release/3.3.0 and are branched off of main or a parent release branch.

    • Bugfixes for releases should usually be merged into main and then be cherry-picked to the release branch.
    • Only push to release branches after talking to the release owner.
    • When a release is done, the released version is tagged and the release branch is deleted.
  • Release tags have names like v3.3.1.

  • To know what is deployed on mainnet, check the Anchor Builds.

mango-v3's People

Contributors

acamill avatar bonedaddy avatar ckamm avatar cryptosupu avatar dafyddd avatar godmodegalactus avatar jkbpvsc avatar josephdunn avatar lagzda avatar microwavedcola1 avatar mschneider avatar muneebmohammed avatar nicholasgodfreyclarke avatar riordanp avatar silas-x avatar tlrjs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mango-v3's Issues

Can't built main on M1

Sup mango team.

I can't build on main right now, seems like something wrong with switchboard dependency. This only happens on M1. If I sync to a build server + build, its okay

   Compiling switchboard-utils v0.1.29
error[E0080]: evaluation of constant value failed
  --> /Users/.../.cargo/registry/src/github.com-1ecc6299db9ec823/switchboard-utils-0.1.29/src/lib.rs:19:18
   |
19 | #[derive(Default,AsBytes,FromBytes,Clone,Debug)]
   |                  ^^^^^^^ attempt to divide `1_usize` by zero
   |
   = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0080`.
error: could not compile `switchboard-utils` due to previous error
warning: build failed, waiting for other jobs to finish...
error: build failed

mango-v3 % rustup --version
rustup 1.24.3 (ce5817a94 2021-05-31)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: The currently active `rustc` version is `rustc 1.59.0-nightly (207c80f10 2021-11-30)`

% rustc --version
rustc 1.59.0-nightly (207c80f10 2021-11-30)

script, document, and setup a proper devnet setup

Hey @dafyddd could you please document what would be desired here - what needs to be done, and in what shape should this devnet group always maintain (so that people can rely it for testing/integration/etc.) ? Also I have never done this before, so any helpful pointers (e.g. commands dump/shell scripts) might be good

state of mango program, thoughts on refactoring/clean-up in 2022

placeholder issue, will update with some thoughts later, some pain points I recently encountered

  • having to figure out yet another low level component e.g. bincode
  • need to constantly scroll across 5k lines of processor.rs while working on anything every few mins
  • new contributors would prefer contributing to an anchor codebase, Update: anchor seems to have a fallback function thingy, which could help gradual migration
  • tests are not covering whole program
  • should we keep on pushing features irrespective of when/if we rewrite/gradually migrate to anchor?

would be great if people could add their own suggestions, we can consolidate, prioritize and start chopping them off

Add ChangeSpotMarket Instruction

We currently have no way to change a spot market's interest rate params once it's deployed. Can you add this instruction? It should be similar to ChangePerpMarket2.

You can look at my branch v3.3 (not to be ocnfused with v3.3.0). It already has this implemented, but I was also trying to implement the two tier interest rate function at the same time. That's cool to add, but not strictly necessary. If you add the two tier rates, then client has to be changed as well and we'd have to coordinate with @tjshipe on stats services.

Invalid Price Cache

Problem statement:
As a trader on the mangos DEX I need to be able to place orders into the book timely so that I can protect my capital and earn profits to pay the DEX and increase revenue for mango holders.

Impact
This issue is making it borderline impossible to place orders or perform other actions on mangos v3. Even when Solana network is hovering above 1700TPS. Other Dapps/smart contracts on Solana are functioning flawlessly at these speeds.
image
image

Anecdotally: I have tried over 200 times to write a SOL-PERP order ( of type Stop Loss ) while Solana is hovering above 1700 TPS (4/3/22 4-5AM MST) and haven't gotten a single order through in the last hour. TOW there are multiple people complaining about the issue in the discord. It is becoming a common theme which may be costing mangos holders.

Dev considerations

  1. Research into why pyth/Switchboard are having such an issue inserting price data into blocks.
    image

  2. Research an estimated Solana Txn/s speed above which it will be safe to use Mangos.
    I suggest implementing a warning or some sort of user facing message stating orders have a very high likelihood of failing to confirm below XXXXTPS. This will ensure users are educated about the REAL risk they may be taking on, at least until the research items (1 & 2 ) can be completed.

  3. From: IwillNotSaveYou On what the issue may be.
    The bottom line is there's probably some asset whose oracle is bad (i'm not sure which one), and if you hold that asset in your account it effectively siezes the whole account.

Acceptance Criteria:
The issue in item 1 is fully understood and the partners pyth/switchboard are aware and incentivized to work with mango on a resolution.
Users should be able to reliably place and remove orders, deposit and withdraw assets on mangos.v3 when Solana TPS are above the TPS researched in item 2.

Unable to close accounts owned by a PDA

Problem

When a Mango account is created and owned by a Program Derived Address (PDA), it is unable to be closed using the following mango client function:

await mangoClient.closeMangoAccount(mg, ma, mangoAccountOwner);

where mangoAccountOwner is a PDA.

Steps to Reproduce

  1. Create a PDA which is supposed to represent the account owner.
  2. Create a Mango account and specify the PDA as the owner (in this case, I did this using a CPI call).
  3. Attempt to close the account by specifying the PDA as the owner.

Error (transaction):

> Program log: Mango: CloseMangoAccount
> Program log: MangoErrorCode::InvalidOwner; src/processor.rs:225
> Program 4skJ85cdxQAFVKbcGgfun8iZPL7BadVYXG3kGEGkufqA consumed 2700 of 1400000 compute units
> Program returned error: custom program error: 0x1
> Runtime error: custom program error: 1

add_asset is wrong

are indexes correct if we add BTC, then TSLA/USDC perp market, then add ETH

In that case, num_tokens = 2 and tokens array looks like [BTC, ETH], but it should actually look like [BTC, empty, ETH] because the perp market doesn't match with any of these tokens

Add stop loss to spot trade

Not having stop loss really limits how useful the spot trade market is.

Apologies if this is already on the roadmap. Please let me know where to look if so.

Using crate or version

I assume this is the most up to date repository for Mango, but there is no version nor crate that I found. Did I overlook something or is that something up for grabs

anchor_mango_v3

I've made a little wrapper on my side to have idiomatic anchor calls to mango, like below :

        // Call Mango CPI
        mango_program::place_perp_order(
            ctx.accounts
                .into_open_mango_short_perp_context()
                .with_signer(depository_signer_seeds),
            price.to_num::<i64>(),
            execution_quantity.to_num::<i64>(),
            0,
            mango::matching::Side::Ask,
            mango::matching::OrderType::ImmediateOrCancel,
            false,
        )?;

with the wrapper for place_perp_order being (it's not the best example cause I skipped the order as I only do immediates one, would patch that for sure 😅 ) :

use anchor_lang::prelude::{AccountInfo, AccountMeta, Accounts, ProgramResult};
use anchor_lang::CpiContext;
use mango::matching::{OrderType, Side};
use mango::state::MAX_PAIRS;
use solana_program::instruction::Instruction;
use solana_program::program_error::ProgramError;
use solana_program::pubkey::Pubkey;

use super::utils::check_program_account;

#[derive(Accounts)]
pub struct PlacePerpOrder<'info> {
    pub mango_group: AccountInfo<'info>,
    pub mango_account: AccountInfo<'info>,
    pub owner: AccountInfo<'info>,
    pub mango_cache: AccountInfo<'info>,
    pub mango_perp_market: AccountInfo<'info>,
    pub mango_bids: AccountInfo<'info>,
    pub mango_asks: AccountInfo<'info>,
    pub mango_event_queue: AccountInfo<'info>,
}

/// Creates a `place_perp_order` instruction.
/// / Place an order on a perp market
/// Accounts expected by this instruction (8):
/// 0. `[]` mango_group_ai - MangoGroup
/// 1. `[writable]` mango_account_ai - the MangoAccount of owner
/// 2. `[signer]` owner_ai - owner of MangoAccount
/// 3. `[]` mango_cache_ai - MangoCache for this MangoGroup
/// 4. `[writable]` perp_market_ai
/// 5. `[writable]` bids_ai - bids account for this PerpMarket
/// 6. `[writable]` asks_ai - asks account for this PerpMarket
/// 7. `[writable]` event_queue_ai - EventQueue for this PerpMarket
fn place_perp_order_instruction(
    mango_program_id: &Pubkey,
    mango_group_pubkey: &Pubkey,
    mango_account_pubkey: &Pubkey,
    owner_pubkey: &Pubkey,
    mango_cache_pubkey: &Pubkey,
    mango_perp_market_pubkey: &Pubkey,
    mango_bids_pubkey: &Pubkey,
    mango_asks_pubkey: &Pubkey,
    mango_event_queue_pubkey: &Pubkey,
    signer_pubkeys: &[&Pubkey],
    price: i64,
    quantity: i64,
    client_order_id: u64,
    side: Side,
    order_type: OrderType,
    reduce_only: bool,
) -> Result<Instruction, ProgramError> {
    check_program_account(mango_program_id)?;
    let data = mango::instruction::MangoInstruction::PlacePerpOrder {
        price,
        quantity,
        client_order_id,
        side,
        order_type,
        reduce_only,
    }
    .pack();

    // use a vec directly cause it seems to take some computing?
    // let mut accounts = Vec::with_capacity(8 + MAX_PAIRS + signer_pubkeys.len());
    let mut accounts = vec![
        AccountMeta::new_readonly(*mango_group_pubkey, false),
        AccountMeta::new(*mango_account_pubkey, false),
        AccountMeta::new_readonly(*owner_pubkey, signer_pubkeys.is_empty()),
        AccountMeta::new_readonly(*mango_cache_pubkey, false),
        AccountMeta::new(*mango_perp_market_pubkey, false),
        AccountMeta::new(*mango_bids_pubkey, false),
        AccountMeta::new(*mango_asks_pubkey, false),
        AccountMeta::new(*mango_event_queue_pubkey, false),
    ];
    accounts.extend(
        signer_pubkeys
            .iter()
            .map(|signer_pubkey| AccountMeta::new_readonly(**signer_pubkey, true)),
    );
    accounts.extend(
        [Pubkey::default(); MAX_PAIRS]
            .iter()
            .map(|default_open_order_pubkey| {
                AccountMeta::new_readonly(*default_open_order_pubkey, false)
            }),
    );
    Ok(Instruction {
        program_id: *mango_program_id,
        accounts,
        data,
    })
}

pub fn place_perp_order<'a, 'b, 'c, 'info>(
    ctx: CpiContext<'a, 'b, 'c, 'info, PlacePerpOrder<'info>>,
    price: i64,
    quantity: i64,
    client_order_id: u64,
    side: Side,
    order_type: OrderType,
    reduce_only: bool,
) -> ProgramResult {
    let ix = place_perp_order_instruction(
        ctx.program.key,
        ctx.accounts.mango_group.key,
        ctx.accounts.mango_account.key,
        ctx.accounts.owner.key,
        ctx.accounts.mango_cache.key,
        ctx.accounts.mango_perp_market.key,
        ctx.accounts.mango_bids.key,
        ctx.accounts.mango_asks.key,
        ctx.accounts.mango_event_queue.key,
        &[ctx.accounts.owner.key],
        price,
        quantity,
        client_order_id,
        side,
        order_type,
        reduce_only,
    )?;
    solana_program::program::invoke_signed(
        &ix,
        &[
            ctx.program.clone(),
            ctx.accounts.mango_group.clone(),
            ctx.accounts.mango_account.clone(),
            ctx.accounts.owner.clone(),
            ctx.accounts.mango_cache.clone(),
            ctx.accounts.mango_perp_market.clone(),
            ctx.accounts.mango_bids.clone(),
            ctx.accounts.mango_asks.clone(),
            ctx.accounts.mango_event_queue.clone(),
        ],
        ctx.signer_seeds,
    )
}

Currently it sits in my projet, and I have init/deposit/placeperporder, but I could do them all slowly.

Is that something you guys would like me to contribute to? I think it can help people integrating mango CPI.

Also I'm not sure where to drop these in the current project.
I'm not even sure it should site with this project. It could be similar to anchor_spl, that's what I got inspiration from for the wrapping

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.