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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use std::fmt;
use std::ops;

use candid::CandidType;
use ciborium::tag::Captured;
use ex3_crypto::sha256;
use ex3_node_error::OtherError;
use ex3_payload_derive::Ex3Payload;
use ex3_serde::{bincode, cbor};
use num_bigint::BigUint;
use serde::de::{Deserializer, SeqAccess, Visitor};
use serde::ser::{SerializeSeq, Serializer};
use serde::{Deserialize, Serialize};
use serde_bytes::ByteBuf;

pub use asset::{
    AssetRegistration, UpdateAssetWithdrawalFeeTo, UpdateChainConfirmationTimes,
    UpdateGlobalWithdrawalFeeTo,
};
pub use deposit::{
    CandidConfirmedDeposit, CandidDeposit, CandidDepositIdentifier, ConfirmedDeposit, Deposit,
    DepositIdentifier, OriginalDeposit,
};
pub use market::{
    SpotMarketRegistration, UpdateSpotMarketFeeTo, UpdateSpotMarketInitialFeeTo,
    UpdateSpotMarketInitialTradingFee, UpdateSpotMarketTradingFee, UpdateSpotMarketTradingSettings,
};
pub use order::{
    AddAmmV2Liquidity, AmmV2ExactTokens, AmmV2OrderDetail, CancelSpotOrder, OrderScope, OrderSide,
    RemoveAmmV2Liquidity, SpotOrder, SpotOrderDetail, SubmitSpotOrder,
};
pub use secret::{CreateApiSecret, DestroyApiSecret, ResetMainSecret};
pub use transfer::{BatchTransfer, TransferDetail};
pub use types::TransactionType;
pub use withdrawal::{ForceWithdrawal, Withdrawal};

use crate::{Nonce, TransactionHash, Version, WalletRegisterId};

mod asset;
mod deposit;
mod market;
mod order;
mod secret;
mod transfer;
mod types;
mod withdrawal;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Transaction {
    // Version of the transaction.
    pub version: Version,
    // Type of transaction.
    pub r#type: TransactionType,
    // Wallet register ID of the sender.
    pub from: WalletRegisterId,
    /// Nonce is a number that is used only once for every transaction per wallet.
    /// If the transaction type is Deposit, Wallet Register, or Reset Main Secret, this field is 0.
    /// Otherwise, this field starts from 1.
    pub nonce: Nonce,
    // Payload information of the transaction.
    pub payload: ByteBuf,
    // Signature of the transaction.
    pub signature: ByteBuf,
}

#[derive(Debug, Clone, PartialEq, Eq, Ex3Payload)]
struct TxData {
    #[index(0)]
    version: u8,
    #[index(1)]
    r#type: BigUint,
    #[index(2)]
    from: BigUint,
    #[index(3)]
    nonce: BigUint,
    #[index(4)]
    payload: ByteBuf,
}

impl Transaction {
    pub fn hash(&self, external_payload: Option<ByteBuf>) -> TransactionHash {
        let bytes = bincode::serialize(&(
            &self.version,
            &self.r#type,
            &self.from,
            &self.nonce,
            &external_payload.map_or(self.payload.clone(), |p| p),
        ))
        .unwrap();
        sha256(&bytes)
    }

    pub fn tx_data_bytes(&self) -> Vec<u8> {
        let tx_data = TxData {
            version: self.version.encode(),
            r#type: self.r#type.clone().into(),
            from: self.from.clone().into(),
            nonce: self.nonce.clone().into(),
            payload: self.payload.clone(),
        };
        let bytes = cbor::serialize(&tx_data).unwrap();
        bytes
    }

    /// Self-encode the transaction into bytes.
    pub fn encode(&self) -> Vec<u8> {
        let data_bytes = bincode::serialize(&(
            &self.r#type,
            &self.from,
            &self.nonce,
            &self.payload,
            &self.signature,
        ))
        .unwrap();

        let mut bytes = vec![self.version.encode()];
        bytes.extend_from_slice(&data_bytes);
        bytes
    }

    /// Decode the transaction from bytes.
    pub fn decode(bytes: &[u8]) -> Result<Self, OtherError> {
        let version = Version::decode(bytes[0..1].try_into().unwrap())
            .map_err(|_| OtherError::new("failed to decode transaction version".to_string()))?;

        if version != Version::V0 {
            return Err(OtherError::new(
                format!(
                    "unsupported transaction version, expected 0, but {}",
                    version.encode()
                )
                .to_string(),
            ));
        }

        let (r#type, from, nonce, payload, signature) = bincode::deserialize(&bytes[1..]).unwrap();

        Ok(Transaction {
            version,
            r#type,
            from,
            nonce,
            payload,
            signature,
        })
    }
}

#[derive(CandidType, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(transparent)]
pub struct EncodedTransaction(ByteBuf);

impl From<Transaction> for EncodedTransaction {
    fn from(tx: Transaction) -> Self {
        let bytes = tx.encode();
        EncodedTransaction(ByteBuf::from(bytes))
    }
}

impl From<&Transaction> for EncodedTransaction {
    fn from(tx: &Transaction) -> Self {
        let bytes = tx.encode();
        EncodedTransaction(ByteBuf::from(bytes))
    }
}

impl From<EncodedTransaction> for Transaction {
    fn from(tx: EncodedTransaction) -> Self {
        Transaction::decode(tx.0.as_ref()).expect("failed to decode transaction")
    }
}

impl From<&EncodedTransaction> for Transaction {
    fn from(tx: &EncodedTransaction) -> Self {
        Transaction::decode(tx.0.as_ref()).expect("failed to decode transaction")
    }
}

impl ops::Deref for EncodedTransaction {
    type Target = ByteBuf;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[derive(CandidType, Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub enum TransactionRejectionReason {
    InsufficientBalance,
    DuplicateSecretKey,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RejectedTransaction {
    pub tx: Transaction,
    pub reason: TransactionRejectionReason,
}

impl RejectedTransaction {
    pub fn encode(&self) -> Vec<u8> {
        bincode::serialize(&(&self.tx.encode(), &self.reason)).unwrap()
    }

    pub fn decode(bytes: &[u8]) -> Result<Self, OtherError> {
        let (tx_bytes, reason): (Vec<u8>, TransactionRejectionReason) =
            bincode::deserialize(bytes).map_err(|e| OtherError::new(format!("{:?}", e)))?;
        Ok(Self {
            tx: Transaction::decode(&tx_bytes).map_err(|e| OtherError::new(format!("{:?}", e)))?,
            reason,
        })
    }
}

#[derive(CandidType, Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct EncodedRejectedTransaction(ByteBuf);

impl ops::Deref for EncodedRejectedTransaction {
    type Target = ByteBuf;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<EncodedRejectedTransaction> for RejectedTransaction {
    fn from(encoded: EncodedRejectedTransaction) -> Self {
        RejectedTransaction::decode(encoded.as_ref()).expect("failed to decode")
    }
}

impl From<&EncodedRejectedTransaction> for RejectedTransaction {
    fn from(encoded: &EncodedRejectedTransaction) -> Self {
        RejectedTransaction::decode(encoded.as_ref()).expect("failed to decode")
    }
}

impl From<RejectedTransaction> for EncodedRejectedTransaction {
    fn from(rejected: RejectedTransaction) -> Self {
        let bytes = rejected.encode();
        EncodedRejectedTransaction(ByteBuf::from(bytes))
    }
}

impl From<&RejectedTransaction> for EncodedRejectedTransaction {
    fn from(rejected: &RejectedTransaction) -> Self {
        let bytes = rejected.encode();
        EncodedRejectedTransaction(ByteBuf::from(bytes))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_encode_decode_with_empty_signature() {
        let tx = Transaction {
            version: Version::V0,
            r#type: TransactionType::Deposit,
            from: WalletRegisterId::from(1000000u32),
            nonce: Nonce::from(1u32),
            payload: ByteBuf::from(vec![1u8, 2u8, 3u8]),
            signature: ByteBuf::from(vec![]),
        };

        let bytes = tx.encode();
        let tx2 = Transaction::decode(&bytes).unwrap();
        assert_eq!(tx, tx2);
    }

    #[test]
    fn test_encode_decode_with_non_empty_signature() {
        let tx = Transaction {
            version: Version::V0,
            r#type: TransactionType::Deposit,
            from: WalletRegisterId::from(1000000u32),
            nonce: Nonce::from(1u32),
            payload: ByteBuf::from(vec![1u8, 2u8, 3u8]),
            // 65 bytes
            signature: ByteBuf::from(vec![1u8; 65]),
        };

        let bytes = tx.encode();
        let tx2 = Transaction::decode(&bytes).unwrap();
        assert_eq!(tx, tx2);
    }
}