taurus-api 0.1.13

Taurus helper for Cosmos-SDK
Documentation
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use crate::config::Wallet;
use anyhow::bail;
use reqwest::blocking::Client;
use serde::{Deserialize, Serialize};
use serde_aux::prelude::*;
use std::time::Duration;

#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct NodeInfo {
    pub name: String,
    pub version: String,
    pub runtime_environment: String,
    pub id: String,
    pub commit: String,
}

#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Score {
    id: String,
    provider: String,
    #[serde(rename(deserialize = "type"))]
    score_type: String,
    score: String,
    update_date: String,
}

#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CurrencyInfo {
    name: String,
    symbol: String,
    blockchain: String,
    decimals: String,
    contract_address: Option<String>,
    is_u_t_x_o_based: Option<bool>,
    enabled: bool,
    id: String,
    display_name: String,
    #[serde(rename(deserialize = "type"))]
    currency_type: String,
}

#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct WalletInfo {
    pub id: String,
    pub balance: Balance,
    pub currency: String,
    pub coin: String,
    pub name: String,
    pub container: Option<String>,
    pub account_path: String,
    pub is_omnibus: Option<bool>,
    pub creation_date: String,
    pub update_date: String,
    pub blockchain: String,
    pub currency_info: CurrencyInfo,
}

#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Attributes {
    key: String,
    value: String,
    id: String,
    content_type: String,
    owner: String,
    #[serde(rename(deserialize = "type"))]
    attribute_type: String,
    subtype: String,
    isfile: bool,
}

#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Balance {
    #[serde(deserialize_with = "deserialize_number_from_string")]
    pub total_confirmed: u128,
    #[serde(deserialize_with = "deserialize_number_from_string")]
    pub total_unconfirmed: u128,
    #[serde(deserialize_with = "deserialize_number_from_string")]
    pub available_confirmed: u128,
    #[serde(deserialize_with = "deserialize_number_from_string")]
    pub available_unconfirmed: u128,
    #[serde(deserialize_with = "deserialize_number_from_string")]
    pub reserved_confirmed: u128,
    #[serde(deserialize_with = "deserialize_number_from_string")]
    pub reserved_unconfirmed: u128,
}

#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Addresses {
    pub id: String,
    pub wallet_id: String,
    pub address_path: String,
    pub address: String,
    pub label: String,
    pub signature: String,
}

#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct WalletResponse {
    pub result: Option<Vec<WalletInfo>>,
    pub total_items: Option<String>,
}

#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct AddressesResponse {
    pub result: Option<Vec<Addresses>>,
    pub total_items: Option<String>,
}

#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct Token {
    pub result: String,
}

#[derive(Serialize, Clone, Debug, Eq, PartialEq, Default)]
pub struct TokenParams {
    pub email: String,
    pub password: String,
    pub totp: Option<String>,
    pub username: Option<String>,
}

#[derive(Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct AccountInfo {
    pub sequence: String,
    pub account_number: String,
}

#[derive(Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct RequestParams {
    pub chain_id: String,
    pub signers: Vec<u16>,
    pub broadcast_kind: String,
    pub fee_denom: String,
    pub gas_limit: String,
    pub fee: String,
    pub accounts_info: Vec<AccountInfo>,
    pub messages: Vec<crate::payload::Message>,
}

#[derive(Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct ValueParams {
    pub primitive: String,
}

#[derive(Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct EthArgsParams {
    pub name: String,
    #[serde(rename(serialize = "type"))]
    pub attribute_type: String,
    pub value: ValueParams,
}

#[derive(Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct EthParams {
    pub function_signature: String,
    pub args: Vec<EthArgsParams>,
}

#[derive(Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct CallParams {
    pub blockchain: String,
    pub eth: EthParams,
}

#[derive(Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct ApproveParams {
    pub from_address_id: String,
    pub to_whitelisted_address_id: String,
    pub contract_type: String,
    pub call: CallParams,
}

#[derive(Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct WhitelistParams {
    pub blockchain: Option<String>,
    pub label: String,
    pub address: String,
    pub address_type: String,
    pub contract_type: Option<String>,
}

#[derive(Deserialize, Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct SignedRequests {
    pub id: String,
    pub signed_request: String,
    pub status: String,
    pub creation_date: String,
    pub update_date: String,
}

#[derive(Deserialize, Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct Trails {
    pub user_id: String,
    pub external_user_id: String,
    pub action: String,
    pub date: Option<String>,
    pub request_status: String,
}

#[derive(Deserialize, Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
    pub column: String,
    pub key: String,
    #[serde(rename(deserialize = "type"))]
    pub payload_type: String,
    pub value: serde_json::Value,
}

#[derive(Deserialize, Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct Metadata {
    pub hash: String,
    pub payload: Vec<Payload>,
}

#[derive(Deserialize, Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct RequestInfos {
    pub id: String,
    pub tenant_id: String,
    pub currency: String,
    pub envelope: String,
    pub status: String,
    #[serde(rename(deserialize = "type"))]
    pub type_request: String,
    pub signed_requests: Option<Vec<SignedRequests>>,
    pub trails: Vec<Trails>,
    pub metadata: Option<Metadata>,
}

#[derive(Deserialize, Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct RequestResponse {
    pub result: RequestInfos,
}

#[derive(Deserialize, Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct WhitelistInfos {
    pub id: String,
}

#[derive(Deserialize, Serialize, Clone, Debug, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct WhitelistResponse {
    pub result: WhitelistInfos,
}

pub struct Taurus {
    address: String,
    client: Client,
    token: Option<String>,
}

impl Taurus {
    pub fn new(cfg: &crate::config::Taurus) -> Result<Self, anyhow::Error> {
        let client = Client::builder()
            .timeout(Duration::from_secs(120))
            .build()?;

        let mut taurus = Taurus {
            address: cfg.api_url.clone(),
            client,
            token: None,
        };

        taurus.login(cfg.mail.as_str(), cfg.passwd.as_str())?;

        Ok(taurus)
    }

    pub fn login(&mut self, email: &str, password: &str) -> Result<(), anyhow::Error> {
        let token = self.token(TokenParams {
            email: email.to_string(),
            password: password.to_string(),
            ..Default::default()
        })?;

        log::info!("Token generated");

        self.token = Some(format!("Bearer {}", token.result));

        Ok(())
    }

    fn get<T: serde::de::DeserializeOwned + Clone>(
        &self,
        endpoint: &str,
    ) -> Result<T, anyhow::Error> {
        log::debug!("GET {}", endpoint);
        let mut request_builder = self.client.get(format!("{}{}", self.address, endpoint));

        if let Some(bearer) = self.token.clone() {
            request_builder = request_builder.header("Authorization", bearer);
        }
        let request = request_builder.send()?;

        let data = &request.text()?;
        log::trace!("-> payload\n{}", data);

        let output = serde_json::from_str::<T>(data);

        Ok(output.unwrap())
    }

    fn post<T: serde::de::DeserializeOwned + Clone, U: serde::ser::Serialize + Clone>(
        &self,
        endpoint: &str,
        data: &U,
    ) -> Result<T, anyhow::Error> {
        log::debug!("POST {}", endpoint);
        let body = serde_json::to_string(data)?;
        log::debug!("\t Body {}", body);
        let mut request_builder = self
            .client
            .post(format!("{}{}", self.address, endpoint))
            .body(body)
            .header("Content-Type", "application/json");
        if let Some(bearer) = self.token.clone() {
            request_builder = request_builder.header("Authorization", bearer);
        }

        let request = request_builder.send()?;

        let data = &request.text()?;
        log::trace!("-> payload\n{}", data);

        let output = serde_json::from_str::<T>(data);

        Ok(output.unwrap())
    }

    fn token(&self, params: TokenParams) -> Result<Token, anyhow::Error> {
        self.post("/api/rest/v1/authentication/token", &params)
    }

    pub fn addresses(&self) -> Result<AddressesResponse, anyhow::Error> {
        self.get("/api/rest/v1/addresses")
    }

    pub fn addresses_by_address(&self, wallet: Wallet) -> Result<Addresses, anyhow::Error> {
        let addresses = self.addresses()?;

        if addresses.result.is_none() {
            bail!("no matching addresses");
        }

        let addresses = addresses.result.unwrap();
        let pos = addresses.iter().position(|x| x.address == wallet.address);

        if pos.is_none() {
            bail!("no matching addresses");
        }

        Ok(addresses[pos.unwrap()].clone())
    }

    pub fn request(&self, params: RequestParams) -> Result<RequestResponse, anyhow::Error> {
        self.post(
            "/api/rest/v1/requests/outgoing/cosmos/generic_request",
            &params,
        )
    }

    pub fn add_contract_whitelist(
        &self,
        params: WhitelistParams,
    ) -> Result<WhitelistResponse, anyhow::Error> {
        self.post("/api/rest/v1/whitelists/addresses", &params)
    }

    pub fn add_addr_whitelist(
        &self,
        params: WhitelistParams,
    ) -> Result<WhitelistResponse, anyhow::Error> {
        self.post("/api/rest/v1/whitelists/addresses", &params)
    }

    pub fn ethereum_approve(
        &self,
        params: ApproveParams,
    ) -> Result<RequestResponse, anyhow::Error> {
        self.post("/api/rest/v1/requests/outgoing/contracts/call", &params)
    }

    pub fn request_by_id(&self, id: u64) -> Result<RequestResponse, anyhow::Error> {
        self.get(format!("/api/rest/v1/requests/{}", id).as_str())
    }
}