avalanche-sdk 0.93.1

Avalanche API/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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
pub mod eth;
pub mod p;
pub mod x;

/// Implements EVM wallet using "ethers" dependencies.
#[cfg(feature = "evm_ethers")]
pub mod evm_ethers;

use std::{
    fmt, io,
    sync::{Arc, Mutex},
};

#[cfg(feature = "evm_ethers")]
use std::io::{Error, ErrorKind};

use crate::{info as api_info, x as api_x};
use avalanche_types::{
    ids::{self, short},
    key, units,
};

#[cfg(feature = "evm_ethers")]
use ethers::prelude::*;

#[cfg(feature = "evm_ethers")]
use ethers_providers::{Middleware, Provider};

#[derive(Debug, Clone)]
pub struct Builder<T: key::secp256k1::ReadOnly + key::secp256k1::SignOnly + Clone> {
    pub key: T,

    pub http_rpcs: Vec<String>,

    #[cfg(feature = "evm_ethers")]
    pub subnet_evm_blockchain_id: Option<String>,
}

impl<T> Builder<T>
where
    T: key::secp256k1::ReadOnly + key::secp256k1::SignOnly + Clone,
{
    pub fn new(key: &T) -> Self {
        Self {
            http_rpcs: Vec::new(),
            key: key.clone(),

            #[cfg(feature = "evm_ethers")]
            subnet_evm_blockchain_id: None,
        }
    }

    /// Adds an HTTP rpc endpoint to the `http_rpcs` field in the Builder.
    #[must_use]
    pub fn http_rpc(mut self, http_rpc: String) -> Self {
        if self.http_rpcs.is_empty() {
            self.http_rpcs = vec![http_rpc];
        } else {
            self.http_rpcs.push(http_rpc);
        }
        self
    }

    /// Overwrites the HTTP rpc endpoints to the `http_rpcs` field in the Builder.
    #[must_use]
    pub fn http_rpcs(mut self, http_rpcs: Vec<String>) -> Self {
        self.http_rpcs = http_rpcs;
        self
    }

    /// Sets the `subnet_evm_blockchain_id` field in the Builder to the provided value.
    #[cfg(feature = "evm_ethers")]
    #[must_use]
    pub fn subnet_evm_blockchain_id(mut self, id: String) -> Self {
        self.subnet_evm_blockchain_id = Some(id);
        self
    }

    #[cfg(feature = "evm_ethers")]
    pub async fn build(&self) -> io::Result<Wallet<T>> {
        log::info!("building wallet with {} endpoints", self.http_rpcs.len());

        let keychain = key::secp256k1::keychain::Keychain::new(vec![self.key.clone()]);
        let ethers_signing_key = keychain.keys[0].ethers_signing_key()?;
        let local_wallet: LocalWallet = ethers_signing_key.clone().into();

        let resp = api_info::get_network_id(&self.http_rpcs[0]).await?;
        let network_id = resp.result.unwrap().network_id;
        let resp = api_info::get_network_name(&self.http_rpcs[0]).await?;
        let network_name = resp.result.unwrap().network_name;

        let c_url_path = String::from("/ext/bc/C/rpc");

        let mut c_providers = Vec::new();
        for ep in self.http_rpcs.iter() {
            let c_provider =
                Provider::<Http>::try_from(ep.clone() + c_url_path.as_str()).map_err(|e| {
                    Error::new(
                        ErrorKind::Other,
                        format!("failed to create provider '{}'", e),
                    )
                })?;
            c_providers.push(c_provider);
        }
        let c_chain_id_u256 = c_providers[0].get_chainid().await.map_err(|e| {
            Error::new(
                ErrorKind::Other,
                format!("failed to get chainId for C-chain '{}'", e),
            )
        })?;

        let (subnet_evm_url_path, subnet_evm_providers, subnet_evm_chain_id_u256) =
            if let Some(sv) = &self.subnet_evm_blockchain_id {
                let subnet_evm_url_path = format!("/ext/bc/{}/rpc", sv).to_string();

                let mut subnet_evm_providers = Vec::new();
                for ep in self.http_rpcs.iter() {
                    let subnet_evm_provider =
                        Provider::<Http>::try_from(ep.clone() + subnet_evm_url_path.as_str())
                            .map_err(|e| {
                                Error::new(
                                    ErrorKind::Other,
                                    format!("failed to create provider '{}'", e),
                                )
                            })?;
                    subnet_evm_providers.push(subnet_evm_provider);
                }
                let subnet_evm_chain_id_u256 =
                    subnet_evm_providers[0].get_chainid().await.map_err(|e| {
                        Error::new(
                            ErrorKind::Other,
                            format!("failed to get chainId for subnet-evm '{}'", e),
                        )
                    })?;
                (
                    Some(subnet_evm_url_path),
                    Some(subnet_evm_providers),
                    Some(subnet_evm_chain_id_u256),
                )
            } else {
                (None, None, None)
            };

        let resp = api_info::get_blockchain_id(&self.http_rpcs[0], "X").await?;
        let x_chain_id = resp.result.unwrap().blockchain_id;

        let resp = api_info::get_blockchain_id(&self.http_rpcs[0], "P").await?;
        let p_chain_id = resp.result.unwrap().blockchain_id;

        let resp = api_info::get_blockchain_id(&self.http_rpcs[0], "C").await?;
        let c_chain_id = resp.result.unwrap().blockchain_id;

        let resp = api_x::get_asset_description(&self.http_rpcs[0], "AVAX").await?;
        let resp = resp
            .result
            .expect("unexpected None GetAssetDescriptionResult");
        let avax_asset_id = resp.asset_id;

        let resp = api_info::get_tx_fee(&self.http_rpcs[0]).await?;
        let tx_fee = resp.result.unwrap().tx_fee;

        let (create_subnet_tx_fee, create_blockchain_tx_fee) = if network_id == 1 {
            // ref. "genesi/genesis_mainnet.go"
            (1 * units::AVAX, 1 * units::AVAX)
        } else {
            // ref. "genesi/genesis_fuji.go"
            // ref. "genesi/genesis_local.go"
            (100 * units::MILLI_AVAX, 100 * units::MILLI_AVAX)
        };

        let h160_address = keychain.keys[0].get_h160_address();
        let h160_address = ethers::prelude::H160::from(h160_address.as_fixed_bytes());

        let w = Wallet {
            keychain,
            ethers_signing_key,
            local_wallet,

            http_rpcs: self.http_rpcs.clone(),
            http_rpc_idx: Arc::new(Mutex::new(0)),

            network_id,
            network_name,

            c_url_path,
            subnet_evm_url_path,

            c_providers,
            subnet_evm_providers,

            h160_address,
            x_address: self.key.get_address(network_id, "X").unwrap(),
            p_address: self.key.get_address(network_id, "P").unwrap(),
            c_address: self.key.get_address(network_id, "C").unwrap(),
            short_address: self.key.get_short_address().unwrap(),
            eth_address: self.key.get_eth_address(),

            x_chain_id,
            p_chain_id,
            c_chain_id,

            c_chain_id_u256,
            subnet_evm_chain_id_u256,

            avax_asset_id,

            tx_fee,
            add_primary_network_validator_fee: ADD_PRIMARY_NETWORK_VALIDATOR_FEE,
            create_subnet_tx_fee,
            create_blockchain_tx_fee,
        };
        log::info!("initiated the wallet:\n{}", w);

        Ok(w)
    }

    #[cfg(not(feature = "evm_ethers"))]
    pub async fn build(&self) -> io::Result<Wallet<T>> {
        log::info!("building wallet with {} endpoints", self.http_rpcs.len());

        let keychain = key::secp256k1::keychain::Keychain::new(vec![self.key.clone()]);

        let resp = api_info::get_network_id(&self.http_rpcs[0]).await?;
        let network_id = resp
            .result
            .expect("unexpected None GetNetworkIdResponse")
            .network_id;
        let resp = api_info::get_network_name(&self.http_rpcs[0]).await?;
        let network_name = resp
            .result
            .expect("unexpected None GetNetworkNameResponse")
            .network_name;

        let c_url_path = String::from("/ext/bc/C/rpc");

        let resp = api_info::get_blockchain_id(&self.http_rpcs[0], "X").await?;
        let x_chain_id = resp
            .result
            .expect("unexpected None GetBlockchainIdResponse")
            .blockchain_id;

        let resp = api_info::get_blockchain_id(&self.http_rpcs[0], "P").await?;
        let p_chain_id = resp
            .result
            .expect("unexpected None GetBlockchainIdResponse")
            .blockchain_id;

        let resp = api_info::get_blockchain_id(&self.http_rpcs[0], "C").await?;
        let c_chain_id = resp
            .result
            .expect("unexpected None GetBlockchainIdResponse")
            .blockchain_id;

        let resp = api_x::get_asset_description(&self.http_rpcs[0], "AVAX").await?;
        let resp = resp
            .result
            .expect("unexpected None GetAssetDescriptionResult");
        let avax_asset_id = resp.asset_id;

        let resp = api_info::get_tx_fee(&self.http_rpcs[0]).await?;
        let tx_fee = resp.result.unwrap().tx_fee;

        let (create_subnet_tx_fee, create_blockchain_tx_fee) = if network_id == 1 {
            // ref. "genesi/genesis_mainnet.go"
            (1 * units::AVAX, 1 * units::AVAX)
        } else {
            // ref. "genesi/genesis_fuji.go"
            // ref. "genesi/genesis_local.go"
            (100 * units::MILLI_AVAX, 100 * units::MILLI_AVAX)
        };

        let h160_address = keychain.keys[0].get_h160_address();
        let w = Wallet {
            keychain,

            http_rpcs: self.http_rpcs.clone(),
            http_rpc_idx: Arc::new(Mutex::new(0)),

            network_id,
            network_name,

            c_url_path,

            h160_address,
            x_address: self.key.get_address(network_id, "X").unwrap(),
            p_address: self.key.get_address(network_id, "P").unwrap(),
            c_address: self.key.get_address(network_id, "C").unwrap(),
            short_address: self.key.get_short_address().unwrap(),
            eth_address: self.key.get_eth_address(),

            x_chain_id,
            p_chain_id,
            c_chain_id,

            avax_asset_id,

            tx_fee,
            add_primary_network_validator_fee: ADD_PRIMARY_NETWORK_VALIDATOR_FEE,
            create_subnet_tx_fee,
            create_blockchain_tx_fee,
        };
        log::info!("initiated the wallet:\n{}", w);

        Ok(w)
    }
}

// ref. https://docs.avax.network/learn/platform-overview/transaction-fees/#fee-schedule
pub const ADD_PRIMARY_NETWORK_VALIDATOR_FEE: u64 = 0;

#[derive(Debug, Clone)]
pub struct Wallet<T: key::secp256k1::ReadOnly + key::secp256k1::SignOnly + Clone> {
    pub keychain: key::secp256k1::keychain::Keychain<T>,

    #[cfg(feature = "evm_ethers")]
    pub ethers_signing_key: ethers_core::k256::ecdsa::SigningKey,
    #[cfg(feature = "evm_ethers")]
    pub local_wallet: LocalWallet,

    pub http_rpcs: Vec<String>,
    pub http_rpc_idx: Arc<Mutex<usize>>,

    pub network_id: u32,
    pub network_name: String,

    pub c_url_path: String,

    #[cfg(feature = "evm_ethers")]
    pub subnet_evm_url_path: Option<String>,

    /// C-chain providers for each HTTP RPC endpoint in the same order.
    #[cfg(feature = "evm_ethers")]
    pub c_providers: Vec<Provider<Http>>,
    /// subnet-evm providers for each HTTP RPC endpoint in the same order.
    #[cfg(feature = "evm_ethers")]
    pub subnet_evm_providers: Option<Vec<Provider<Http>>>,

    #[cfg(feature = "evm_ethers")]
    pub h160_address: ethers::prelude::H160,
    #[cfg(not(feature = "evm_ethers"))]
    pub h160_address: primitive_types::H160,

    pub x_address: String,
    pub p_address: String,
    pub c_address: String,
    pub short_address: short::Id,
    pub eth_address: String,

    pub x_chain_id: ids::Id,
    pub p_chain_id: ids::Id,
    pub c_chain_id: ids::Id,

    #[cfg(feature = "evm_ethers")]
    pub c_chain_id_u256: U256,
    #[cfg(feature = "evm_ethers")]
    pub subnet_evm_chain_id_u256: Option<U256>,

    pub avax_asset_id: ids::Id,

    /// Fee that is burned by every non-state creating transaction.
    pub tx_fee: u64,
    /// Transaction fee for adding a primary network validator.
    pub add_primary_network_validator_fee: u64,
    /// Transaction fee to create a new subnet.
    pub create_subnet_tx_fee: u64,
    /// Transaction fee to create a new blockchain.
    pub create_blockchain_tx_fee: u64,
}

/// ref. https://doc.rust-lang.org/std/string/trait.ToString.html
/// ref. https://doc.rust-lang.org/std/fmt/trait.Display.html
/// Use "Self.to_string()" to directly invoke this
impl<T> fmt::Display for Wallet<T>
where
    T: key::secp256k1::ReadOnly + key::secp256k1::SignOnly + Clone,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "http_rpcs: {:?}\n", self.http_rpcs)?;
        write!(f, "network_id: {}\n", self.network_id)?;
        write!(f, "network_name: {}\n", self.network_name)?;

        write!(f, "c_url_path: {}\n", self.c_url_path)?;

        #[cfg(feature = "evm_ethers")]
        if let Some(v) = &self.subnet_evm_url_path {
            write!(f, "subnet_evm_url_path: {}\n", v)?;
        } else {
            write!(f, "subnet_evm_url_path: None\n")?;
        }

        write!(f, "h160_address: {}\n", self.h160_address)?;
        write!(f, "x_address: {}\n", self.x_address)?;
        write!(f, "p_address: {}\n", self.p_address)?;
        write!(f, "c_address: {}\n", self.c_address)?;
        write!(f, "short_address: {}\n", self.short_address)?;
        write!(f, "eth_address: {}\n", self.eth_address)?;
        write!(f, "x_chain_id: {}\n", self.x_chain_id)?;
        write!(f, "p_chain_id: {}\n", self.p_chain_id)?;
        write!(f, "c_chain_id: {}\n", self.c_chain_id)?;

        #[cfg(feature = "evm_ethers")]
        write!(f, "c_chain_id_u256: {}\n", self.c_chain_id_u256)?;
        #[cfg(feature = "evm_ethers")]
        if let Some(v) = self.subnet_evm_chain_id_u256 {
            #[cfg(feature = "evm_ethers")]
            write!(f, "subnet_evm_chain_id_u256: {}\n", v)?;
        } else {
            write!(f, "subnet_evm_chain_id_u256: None\n")?;
        }

        write!(f, "avax_asset_id: {}\n", self.avax_asset_id)?;

        write!(f, "tx_fee: {}\n", self.tx_fee)?;
        write!(
            f,
            "add_primary_network_validator_fee: {}\n",
            self.add_primary_network_validator_fee
        )?;
        write!(f, "create_subnet_tx_fee: {}\n", self.create_subnet_tx_fee)?;
        write!(
            f,
            "create_blockchain_tx_fee: {}\n",
            self.create_blockchain_tx_fee
        )
    }
}

impl<T> Wallet<T>
where
    T: key::secp256k1::ReadOnly + key::secp256k1::SignOnly + Clone,
{
    /// Picks one endpoint in roundrobin, and updates the cursor for next calls.
    /// Returns the pair of an index and its corresponding endpoint.
    pub fn pick_http_rpc(&self) -> (usize, String) {
        let mut idx = self.http_rpc_idx.lock().unwrap();

        let picked = *idx;
        let http_rpc = self.http_rpcs[picked].clone();
        *idx = (picked + 1) % self.http_rpcs.len();

        log::debug!("picked http rpc {} at index {}", http_rpc, picked);
        (picked, http_rpc)
    }

    #[must_use]
    pub fn x(&self) -> x::X<T> {
        x::X {
            inner: self.clone(),
        }
    }

    #[must_use]
    pub fn p(&self) -> p::P<T> {
        p::P {
            inner: self.clone(),
        }
    }

    /// Set "chain_id_alias" to either "C" or subnet_evm chain Id.
    /// e.g., "/ext/bc/C/rpc"
    #[must_use]
    pub fn eth(&self, chain_id_alias: String) -> eth::Eth<T> {
        let chain_rpc_url_path = format!("/ext/bc/{}/rpc", chain_id_alias).to_string();
        eth::Eth {
            inner: self.clone(),
            chain_id_alias,
            chain_rpc_url_path,
        }
    }

    #[cfg(feature = "evm_ethers")]
    #[must_use]
    pub fn evm_ethers_c(&self) -> evm_ethers::c::C<T> {
        evm_ethers::c::C {
            inner: self.clone(),
        }
    }

    #[cfg(feature = "evm_ethers")]
    #[must_use]
    pub fn evm_ethers_subnet_evm(&self) -> evm_ethers::subnet_evm::SubnetEvm<T> {
        assert!(
            self.subnet_evm_url_path.is_some(),
            "subnet-evm URL path is None"
        );
        assert!(
            self.subnet_evm_providers.is_some(),
            "subnet-evm providers is None"
        );
        assert!(
            !self.subnet_evm_providers.clone().unwrap().is_empty(),
            "subnet-evm providers are empty"
        );
        assert!(
            self.subnet_evm_chain_id_u256.is_some(),
            "subnet-evm chain Id is None"
        );

        evm_ethers::subnet_evm::SubnetEvm {
            inner: self.clone(),
        }
    }
}