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
use num_enum::{FromPrimitive, IntoPrimitive};
use solana_program::program_error::ProgramError;
use thiserror::Error;

pub type DexResult<T = ()> = Result<T, DexError>;

#[derive(Debug)]
pub struct AssertionError {
    pub line: u16,
    pub file_id: SourceFileId,
}

impl From<AssertionError> for u32 {
    fn from(err: AssertionError) -> u32 {
        (err.line as u32) + ((err.file_id as u8 as u32) << 24)
    }
}

impl From<AssertionError> for DexError {
    fn from(err: AssertionError) -> DexError {
        let err: u32 = err.into();
        DexError::ProgramError(ProgramError::Custom(err.into()))
    }
}

#[derive(Error, Debug, PartialEq, Eq)]
pub enum DexError {
    #[error(transparent)]
    ProgramError(#[from] ProgramError),
    #[error("{0:?}")]
    ErrorCode(#[from] DexErrorCode),
}

#[derive(Debug, IntoPrimitive, FromPrimitive, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum DexErrorCode {
    InvalidMarketFlags = 0,
    InvalidAskFlags,
    InvalidBidFlags,
    InvalidQueueLength,
    OwnerAccountNotProvided,

    ConsumeEventsQueueFailure,
    WrongCoinVault,
    WrongPcVault,
    WrongCoinMint,
    WrongPcMint,

    CoinVaultProgramId = 10,
    PcVaultProgramId,
    CoinMintProgramId,
    PcMintProgramId,

    WrongCoinMintSize,
    WrongPcMintSize,
    WrongCoinVaultSize,
    WrongPcVaultSize,

    UninitializedVault,
    UninitializedMint,

    CoinMintUninitialized = 20,
    PcMintUninitialized,
    WrongMint,
    WrongVaultOwner,
    VaultHasDelegate,

    AlreadyInitialized,
    WrongAccountDataAlignment,
    WrongAccountDataPaddingLength,
    WrongAccountHeadPadding,
    WrongAccountTailPadding,

    RequestQueueEmpty = 30,
    EventQueueTooSmall,
    SlabTooSmall,
    BadVaultSignerNonce,
    InsufficientFunds,

    SplAccountProgramId,
    SplAccountLen,
    WrongFeeDiscountAccountOwner,
    WrongFeeDiscountMint,

    CoinPayerProgramId,
    PcPayerProgramId = 40,
    ClientIdNotFound,
    TooManyOpenOrders,

    FakeErrorSoWeDontChangeNumbers,
    BorrowError,

    WrongOrdersAccount,
    WrongBidsAccount,
    WrongAsksAccount,
    WrongRequestQueueAccount,
    WrongEventQueueAccount,

    RequestQueueFull = 50,
    EventQueueFull,
    MarketIsDisabled,
    WrongSigner,
    TransferFailed,
    ClientOrderIdIsZero,

    WrongRentSysvarAccount,
    RentNotProvided,
    OrdersNotRentExempt,
    OrderNotFound,
    OrderNotYours,

    WouldSelfTrade,
    InvalidOpenOrdersAuthority,

    Unknown = 1000,

    // This contains the line number in the lower 16 bits,
    // and the source file id in the upper 8 bits
    #[num_enum(default)]
    AssertionError,
}

#[repr(u8)]
#[derive(Error, Debug)]
pub enum SourceFileId {
    #[error("src/state.rs")]
    State = 1,
    #[error("src/matching.rs")]
    Matching = 2,
    #[error("src/critbit.rs")]
    Critbit = 3,
}

#[macro_export]
macro_rules! declare_check_assert_macros {
    ($source_file_id:expr) => {
        macro_rules! assertion_error {
            () => {{
                let file_id: SourceFileId = $source_file_id;
                $crate::error::AssertionError {
                    line: line!() as u16,
                    file_id,
                }
            }};
        }

        #[allow(unused_macros)]
        macro_rules! check_assert {
            ($val:expr) => {{
                if $val {
                    Ok(())
                } else {
                    Err(assertion_error!())
                }
            }};
        }

        #[allow(unused_macros)]
        macro_rules! check_assert_eq {
            ($a:expr, $b:expr) => {{
                if $a == $b {
                    Ok(())
                } else {
                    Err(assertion_error!())
                }
            }};
        }

        #[allow(unused_macros)]
        macro_rules! check_unreachable {
            () => {{
                Err(assertion_error!())
            }};
        }
    };
}

impl std::fmt::Display for DexErrorCode {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        <Self as std::fmt::Debug>::fmt(self, fmt)
    }
}

impl std::error::Error for DexErrorCode {}

impl std::convert::From<DexError> for ProgramError {
    fn from(e: DexError) -> ProgramError {
        match e {
            DexError::ProgramError(e) => e,
            DexError::ErrorCode(c) => ProgramError::Custom(c.into()),
        }
    }
}

impl std::convert::From<std::cell::BorrowError> for DexError {
    fn from(_: std::cell::BorrowError) -> Self {
        DexError::ErrorCode(DexErrorCode::BorrowError)
    }
}