1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
use anchor_lang::prelude::*;
use static_assertions::const_assert_eq;
use std::mem::size_of;

// TODO: Assuming we allow up to 65536 different tokens
pub type TokenIndex = u16;

/// This token index is supposed to be the token that oracles quote in.
///
/// In practice this is set to the USDC token index, and that is wrong: actually
/// oracles quote in USD. Any use of this constant points to a potentially
/// incorrect assumption.
pub const QUOTE_TOKEN_INDEX: TokenIndex = 0;

/// The token index used for the insurance fund.
///
/// We should eventually generalize insurance funds.
pub const INSURANCE_TOKEN_INDEX: TokenIndex = 0;

/// The token index used for settling perp markets.
///
/// We should eventually generalize to make the whole perp quote (and settle) token
/// configurable.
pub const PERP_SETTLE_TOKEN_INDEX: TokenIndex = 0;

/// The token index used in AccountBuybackFeesWithMngo to exchange for MNGO
pub const FEE_BUYBACK_QUOTE_TOKEN_INDEX: TokenIndex = 0;

#[account(zero_copy(safe_bytemuck_derives))]
#[derive(Debug)]
pub struct Group {
    // ABI: Clients rely on this being at offset 8
    pub creator: Pubkey,

    // ABI: Clients rely on this being at offset 40
    pub group_num: u32,

    pub admin: Pubkey,

    // TODO: unused, use case - listing shit tokens with conservative parameters (mostly defaults)
    pub fast_listing_admin: Pubkey,

    // This is the token index of the mngo token listed on the group
    pub mngo_token_index: TokenIndex,
    pub padding: [u8; 2],

    pub insurance_vault: Pubkey,
    pub insurance_mint: Pubkey,

    pub bump: u8,

    pub testing: u8,

    pub version: u8,

    // Buyback fees with Mngo: allow exchanging fees with mngo at a bonus
    pub buyback_fees: u8,
    // Buyback fees with Mngo: how much should the bonus be,
    // e.g. a bonus factor of 1.2 means 120$ worth fees could be swapped for mngo worth 100$ at current market price
    pub buyback_fees_mngo_bonus_factor: f32,

    pub address_lookup_tables: [Pubkey; 20],

    pub security_admin: Pubkey,

    // Deposit limit for a mango account in quote native, enforced on quote value of account assets
    // Set to 0 to disable, which also means by default there is no limit
    pub deposit_limit_quote: u64,

    // Map of ixs and their state of gating
    // 0 is chosen as enabled, becase we want to start out with all ixs enabled, 1 is disabled
    pub ix_gate: u128,

    // Buyback fees with Mngo:
    // A mango account which would be counter party for settling fees with mngo
    // This ensures that the system doesn't have a net deficit of tokens
    // The workflow should be something like this
    // - the dao deposits quote tokens in its respective mango account
    // - the user deposits some mngo tokens in his mango account
    // - the user then claims quote for mngo at a bonus rate
    pub buyback_fees_swap_mango_account: Pubkey,

    /// Number of seconds after which fees that could be used with the fees buyback feature expire.
    ///
    /// The actual expiry is staggered such that the fees users accumulate are always
    /// available for at least this interval - but may be available for up to twice this time.
    ///
    /// When set to 0, there's no expiry of buyback fees.
    pub buyback_fees_expiry_interval: u64,

    pub reserved: [u8; 1824],
}
const_assert_eq!(
    size_of::<Group>(),
    32 + 4 + 32 * 2 + 4 + 32 * 2 + 4 + 4 + 20 * 32 + 32 + 8 + 16 + 32 + 8 + 1824
);
const_assert_eq!(size_of::<Group>(), 2736);
const_assert_eq!(size_of::<Group>() % 8, 0);

impl Group {
    pub fn buyback_fees(&self) -> bool {
        self.buyback_fees == 1
    }

    pub fn is_testing(&self) -> bool {
        self.testing == 1
    }

    pub fn multiple_banks_supported(&self) -> bool {
        self.is_testing() || self.version > 1
    }

    pub fn serum3_supported(&self) -> bool {
        self.is_testing() || self.version > 0
    }

    pub fn perps_supported(&self) -> bool {
        self.is_testing() || self.version > 1
    }

    pub fn is_ix_enabled(&self, ix: IxGate) -> bool {
        self.ix_gate & (1 << ix as u128) == 0
    }
}

/// Enum for lookup into ix gate
/// note:
/// total ix files 56,
/// ix files included 48,
/// ix files not included 8,
/// - Benchmark,
/// - ComputeAccountData,
/// - GroupCreate
/// - GroupEdit
/// - IxGateSet,
/// - PerpZeroOut,
/// - PerpEditMarket,
/// - TokenEdit,
#[derive(Copy, Clone, Debug)]
pub enum IxGate {
    AccountClose = 0,
    AccountCreate = 1,
    AccountEdit = 2,
    AccountExpand = 3,
    AccountToggleFreeze = 4,
    AltExtend = 5,
    AltSet = 6,
    FlashLoan = 7,
    GroupClose = 8,
    GroupCreate = 9,
    HealthRegion = 10,
    PerpCancelAllOrders = 11,
    PerpCancelAllOrdersBySide = 12,
    PerpCancelOrder = 13,
    PerpCancelOrderByClientOrderId = 14,
    PerpCloseMarket = 15,
    PerpConsumeEvents = 16,
    PerpCreateMarket = 17,
    PerpDeactivatePosition = 18,
    PerpLiqBaseOrPositivePnl = 19,
    PerpLiqForceCancelOrders = 20,
    PerpLiqNegativePnlOrBankruptcy = 21,
    PerpPlaceOrder = 22,
    PerpSettleFees = 23,
    PerpSettlePnl = 24,
    PerpUpdateFunding = 25,
    Serum3CancelAllOrders = 26,
    Serum3CancelOrder = 27,
    Serum3CloseOpenOrders = 28,
    Serum3CreateOpenOrders = 29,
    Serum3DeregisterMarket = 30,
    Serum3EditMarket = 31,
    Serum3LiqForceCancelOrders = 32,
    Serum3PlaceOrder = 33,
    Serum3RegisterMarket = 34,
    Serum3SettleFunds = 35,
    StubOracleClose = 36,
    StubOracleCreate = 37,
    StubOracleSet = 38,
    TokenAddBank = 39,
    TokenDeposit = 40,
    TokenDeregister = 41,
    TokenLiqBankruptcy = 42,
    TokenLiqWithToken = 43,
    TokenRegister = 44,
    TokenRegisterTrustless = 45,
    TokenUpdateIndexAndRate = 46,
    TokenWithdraw = 47,
    AccountBuybackFeesWithMngo = 48,
    TokenForceCloseBorrowsWithToken = 49,
    PerpForceClosePosition = 50,
    GroupWithdrawInsuranceFund = 51,
    // NOTE: Adding new variants requires matching changes in ts and the ix_gate_set instruction.
}

// note: using creator instead of admin, since admin can be changed
#[macro_export]
macro_rules! group_seeds {
    ( $group:expr ) => {
        &[
            b"Group".as_ref(),
            $group.creator.as_ref(),
            &$group.group_num.to_le_bytes(),
            &[$group.bump],
        ]
    };
}

pub use group_seeds;