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
use ex3_canister_types::chain::Chain;
use std::ops;

use ex3_crypto::sha256;
use ex3_serde::bincode::{deserialize, serialize};
use ex3_serde::{bincode, cbor};
use serde::{Deserialize, Serialize};
use serde_bytes::ByteBuf;

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

pub type TransactionHash = [u8; 32];
pub type r#Type = u32;

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Transaction {
    pub r#type: r#Type,
    pub version: Version,
    pub from: WalletRegisterId,
    /// if the transaction type is [Deposit, WALLET_REGISTER, RESET_MAIN_SECRET], this field is None
    pub nonce: Nonce,
    pub payload: ByteBuf,
    pub signature: ByteBuf,
}

impl Transaction {
    pub fn hash(&self) -> TransactionHash {
        let bytes = bincode::serialize(&self).unwrap();
        sha256!(&bytes)
    }
}

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

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

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

impl From<EncodedTransaction> for Transaction {
    fn from(tx: EncodedTransaction) -> Self {
        bincode::deserialize(tx.0.as_ref()).unwrap()
    }
}

impl From<&EncodedTransaction> for Transaction {
    fn from(tx: &EncodedTransaction) -> Self {
        bincode::deserialize(tx.0.as_ref()).unwrap()
    }
}

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

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

/// Transaction type
/// | type                    | code              | remark                               |
/// | ----------------------- | ----------------- | ------------------------------------ |
/// | WALLET_REGISTER         | 100u32            | Wallet register.                     |
/// | DEPOSIT                 | 200u32            | Deposit transaction.                 |
/// | WITHDRAWAL              | 201u32            | Withdraw transaction.                |
/// | TRANSFER                | 300u32            | Transfer transaction.                |
/// | RESET_MAIN_SECRET       | 400u32            | Create main secret transaction.      |
/// | CREATE_API_SECRET       | 401u32            | Create api secret transaction.       |
/// | DESTROY_API_SECRET      | 402u32            | Destroy api secret transaction.      |
/// | CREATE_SPOT_ORDER       | 500u32            | Submit spot order.                   |
/// | CANCEL_SPOT_ORDER       | 501u32            | Cancel spot order.                   |
/// | ADD_AMM_V2_LIQUIDITY    | 600u32            | Add AMM-V2 liquidity.                |
/// | REMOVE_AMM_V2_LIQUIDITY | 601u32            | Remove AMM-V2 liquidity.             |
#[allow(dead_code)]
pub mod transaction_type {
    pub const WALLET_REGISTER: u32 = 100u32;
    pub const DEPOSIT: u32 = 200u32;
    pub const WITHDRAWAL: u32 = 201u32;
    pub const TRANSFER: u32 = 300u32;
    pub const RESET_MAIN_SECRET: u32 = 400u32;
    pub const CREATE_API_SECRET: u32 = 401u32;
    pub const DESTROY_API_SECRET: u32 = 402u32;
    pub const CREATE_SPOT_ORDER: u32 = 500u32;
    pub const CANCEL_SPOT_ORDER: u32 = 501u32;
    pub const ADD_AMM_V2_LIQUIDITY: u32 = 600u32;
    pub const REMOVE_AMM_V2_LIQUIDITY: u32 = 601u32;
}

#[derive(Clone, Deserialize, Serialize, Debug, Eq, PartialEq)]
pub struct WalletRegisterRequest {
    pub chain: Chain,
    pub network: u8,
    pub pub_key: PublicKey,
}

impl WalletRegisterRequest {
    pub fn encode(&self) -> Vec<u8> {
        serialize(&(&self.chain, &self.network, &self.pub_key)).unwrap()
    }

    pub fn decode(bytes: &[u8]) -> Result<Self, String> {
        let (chain, network, pub_key) = deserialize(bytes)
            .map_err(|e| format!("Failed to deserialize WalletRegisterRequest: {}", e))?;

        Ok(Self {
            chain,
            network,
            pub_key,
        })
    }

    pub fn cbor_encode(&self) -> Vec<u8> {
        cbor::serialize(&(&self.chain, &self.network, &self.pub_key)).unwrap()
    }

    pub fn cbor_decode(bytes: &[u8]) -> Result<Self, String> {
        let (chain, network, pub_key) = cbor::deserialize(bytes)
            .map_err(|e| format!("Failed to deserialize WalletRegisterRequest: {}", e))?;

        Ok(Self {
            chain,
            network,
            pub_key,
        })
    }
}

#[derive(Clone, Deserialize, Serialize, Debug, Eq, PartialEq)]
pub struct ResetMainSecretRequest {
    pub encrypted_pri_key: ByteBuf,
    pub l2_pub_key: PublicKey,
}

impl ResetMainSecretRequest {
    pub fn encode(&self) -> Vec<u8> {
        serialize(&(&self.encrypted_pri_key, &self.l2_pub_key)).unwrap()
    }

    pub fn decode(bytes: &[u8]) -> Result<Self, String> {
        let (encrypted_pri_key, l2_pub_key) = deserialize(bytes)
            .map_err(|e| format!("Failed to deserialize ResetMainSecretRequest: {}", e))?;

        Ok(Self {
            encrypted_pri_key,
            l2_pub_key,
        })
    }

    pub fn cbor_encode(&self) -> Vec<u8> {
        cbor::serialize(&(&self.encrypted_pri_key, &self.l2_pub_key)).unwrap()
    }

    pub fn cbor_decode(bytes: &[u8]) -> Result<Self, String> {
        let (encrypted_pri_key, l2_pub_key) = cbor::deserialize(bytes)
            .map_err(|e| format!("Failed to deserialize ResetMainSecretRequest: {}", e))?;

        Ok(Self {
            encrypted_pri_key,
            l2_pub_key,
        })
    }
}