avalanche-sdk 0.43.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
pub mod evm;
pub mod p;
pub mod x;

use std::{
    fmt,
    io::{self, Error, ErrorKind},
    time::SystemTime,
};

use crate::{info as api_info, p as api_p, x as api_x};
use avalanche_types::{
    avax,
    ids::{self, node, short},
    key::{self, keychain},
    platformvm, secp256k1fx,
};
use ethers::prelude::*;
use ethers_providers::{Middleware, Provider};

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

    pub network_id: u32,
    pub network_name: String,

    pub keychain: keychain::Keychain<T>,
    pub ethers_signing_key: ethers_core::k256::ecdsa::SigningKey,
    pub local_wallet: LocalWallet,

    pub evm_provider: Provider<Http>,

    pub h160_address: 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,
    pub c_chain_id_u256: U256,

    pub tx_fee: u64,
    pub avax_asset_id: ids::Id,
}

/// 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::ReadOnly + key::SignOnly + Clone,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "http_rpc: {}\n", self.http_rpc)?;
        write!(f, "network_id: {}\n", self.network_id)?;
        write!(f, "network_name: {}\n", self.network_name)?;
        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)?;
        write!(f, "c_chain_id_u256: {}\n", self.c_chain_id_u256)?;
        write!(f, "tx_fee: {}\n", self.tx_fee)?;
        write!(f, "avax_asset_id: {}", self.avax_asset_id)
    }
}

impl<T> Wallet<T>
where
    T: key::ReadOnly + key::SignOnly + Clone,
{
    pub async fn new(http_rpc: &str, key: &T) -> io::Result<Self> {
        let resp = api_info::get_network_id(http_rpc).await?;
        let network_id = resp
            .result
            .expect("unexpected None GetNetworkIdResponse")
            .network_id;

        let resp = api_info::get_network_name(http_rpc).await?;
        let network_name = resp
            .result
            .expect("unexpected None GetNetworkNameResponse")
            .network_name;

        let evm_provider = Provider::<Http>::try_from(http_rpc.to_string() + "/ext/bc/C/rpc")
            .map_err(|e| Error::new(ErrorKind::Other, format!("failed to create c_ '{}'", e)))?;
        let c_chain_id_u256 = evm_provider
            .get_chainid()
            .await
            .map_err(|e| Error::new(ErrorKind::Other, format!("failed to get chainId '{}'", e)))?;

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

        let h160_address = keychain.keys[0].get_h160_address();

        let resp = api_info::get_blockchain_id(http_rpc, "X").await?;
        let x_chain_id = resp
            .result
            .expect("unexpected None GetBlockchainIdResponse")
            .blockchain_id;

        let resp = api_info::get_blockchain_id(http_rpc, "P").await?;
        let p_chain_id = resp
            .result
            .expect("unexpected None GetBlockchainIdResponse")
            .blockchain_id;

        let resp = api_info::get_blockchain_id(http_rpc, "C").await?;
        let c_chain_id = resp
            .result
            .expect("unexpected None GetBlockchainIdResponse")
            .blockchain_id;

        let resp = api_x::get_asset_description(http_rpc, "AVAX").await?;
        let resp = resp
            .result
            .expect("unexpected None GetAssetDescriptionResult");
        let avax_asset_id = resp.asset_id;

        let resp = api_info::get_tx_fee(http_rpc).await?;
        let tx_fee = resp.result.unwrap().tx_fee;

        let w = Self {
            http_rpc: http_rpc.to_string(),

            network_id,
            network_name,

            keychain,
            ethers_signing_key,
            local_wallet,

            evm_provider,

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

            x_chain_id,
            p_chain_id,
            c_chain_id,
            c_chain_id_u256,

            tx_fee,
            avax_asset_id,
        };

        log::info!("initiated the wallet\n{}", w);

        Ok(w)
    }

    /// Fetches UTXOs for "X" chain.
    /// TODO: cache this like avalanchego
    pub async fn get_utxos_x(&self) -> io::Result<Vec<avax::Utxo>> {
        // ref. https://github.com/ava-labs/avalanchego/blob/v1.7.9/wallet/chain/p/builder.go
        // ref. https://github.com/ava-labs/avalanchego/blob/v1.7.9/vms/platformvm/add_validator_tx.go#L263
        // ref. https://github.com/ava-labs/avalanchego/blob/v1.7.9/vms/platformvm/spend.go#L39 "stake"
        // ref. https://github.com/ava-labs/subnet-cli/blob/6bbe9f4aff353b812822af99c08133af35dbc6bd/client/p.go#L355 "AddValidator"
        // ref. https://github.com/ava-labs/subnet-cli/blob/6bbe9f4aff353b812822af99c08133af35dbc6bd/client/p.go#L614 "stake"
        let resp = api_x::get_utxos(&self.http_rpc, &self.p_address).await?;
        let utxos = resp
            .result
            .expect("unexpected None GetUtxosResult")
            .utxos
            .expect("unexpected None Utxos");
        Ok(utxos)
    }

    pub async fn get_balance_x(&self) -> io::Result<u64> {
        let resp = api_x::get_balance(&self.http_rpc, &self.x_address).await?;
        let cur_balance = resp
            .result
            .expect("unexpected None GetBalanceResult")
            .balance;
        Ok(cur_balance)
    }

    /// Fetches UTXOs for "P" chain.
    /// TODO: cache this like avalanchego
    pub async fn get_utxos_p(&self) -> io::Result<Vec<avax::Utxo>> {
        // ref. https://github.com/ava-labs/avalanchego/blob/v1.7.9/wallet/chain/p/builder.go
        // ref. https://github.com/ava-labs/avalanchego/blob/v1.7.9/vms/platformvm/add_validator_tx.go#L263
        // ref. https://github.com/ava-labs/avalanchego/blob/v1.7.9/vms/platformvm/spend.go#L39 "stake"
        // ref. https://github.com/ava-labs/subnet-cli/blob/6bbe9f4aff353b812822af99c08133af35dbc6bd/client/p.go#L355 "AddValidator"
        // ref. https://github.com/ava-labs/subnet-cli/blob/6bbe9f4aff353b812822af99c08133af35dbc6bd/client/p.go#L614 "stake"
        let resp = api_p::get_utxos(&self.http_rpc, &self.p_address).await?;
        let utxos = resp
            .result
            .expect("unexpected None GetUtxosResult")
            .utxos
            .expect("unexpected None Utxos");
        Ok(utxos)
    }

    pub async fn get_balance_p(&self) -> io::Result<u64> {
        let resp = api_p::get_balance(&self.http_rpc, &self.p_address).await?;
        let cur_balance = resp
            .result
            .expect("unexpected None GetBalanceResult")
            .balance
            .expect("unexpected None balance");
        Ok(cur_balance)
    }

    pub async fn get_balance_c_u256(&self) -> io::Result<U256> {
        self.evm_provider
            .get_balance(self.h160_address, None)
            .await
            .map_err(|e| Error::new(ErrorKind::Other, format!("failed to get_balance '{}'", e)))
    }

    /// Returns "true" if the node_id is a currente validator.
    async fn is_validator(&self, node_id: &node::Id) -> io::Result<bool> {
        let resp = api_p::get_current_validators(&self.http_rpc).await?;
        let resp = resp
            .result
            .expect("unexpected None GetCurrentValidatorResult");
        let validators = resp.validators.expect("unexpected None vaidators");
        for validator in validators.iter() {
            let val_id = validator.node_id.unwrap();
            if val_id.eq(node_id) {
                return Ok(true);
            }
            log::info!("current validator: {}", node_id);
        }
        Ok(false)
    }

    /// "stake_amount" and "fee" are denominated in nano-AVAX.
    /// ref. https://github.com/ava-labs/avalanchego/blob/v1.7.9/vms/platformvm/spend.go#L39 "stake"
    /// ref. https://github.com/ava-labs/avalanchego/blob/v1.7.9/wallet/chain/p/builder.go "spend"
    async fn stake(
        &self,
        stake_amount: u64,
        fee: u64,
    ) -> io::Result<(
        Vec<avax::TransferableInput>,
        Vec<avax::TransferableOutput>,
        Vec<avax::TransferableOutput>,
        Vec<Vec<T>>,
    )> {
        let utxos = self.get_utxos_p().await?;

        let now_unix = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .expect("unexpected None duration_since")
            .as_secs();

        // ref. https://github.com/ava-labs/avalanchego/blob/v1.7.9/vms/platformvm/spend.go#L65
        let mut transferable_inputs: Vec<avax::TransferableInput> = Vec::new();
        let mut unlocked_outputs: Vec<avax::TransferableOutput> = Vec::new();
        let mut locked_outputs: Vec<avax::TransferableOutput> = Vec::new();
        let mut signers: Vec<Vec<T>> = Vec::new();

        // ref. https://github.com/ava-labs/avalanchego/blob/v1.7.9/vms/platformvm/spend.go#L71
        // ref. https://github.com/ava-labs/subnet-cli/blob/6bbe9f4aff353b812822af99c08133af35dbc6bd/client/p.go#L650
        let mut amount_staked: u64 = 0_u64;
        for utxo in utxos.iter() {
            // no need to consume more locked AVAX
            // because it already has consumed more than the target stake amount
            if amount_staked >= stake_amount {
                break;
            }
            // ignore other assets
            if utxo.asset_id != self.avax_asset_id {
                continue;
            }

            // check "*platformvm.StakeableLockOut"
            if utxo.stakeable_lock_out.is_none() {
                // output is not locked, thus handle this in the next iteration
                continue;
            }

            // check locktime
            let stakeable_lock_out = utxo.stakeable_lock_out.clone().unwrap();
            if stakeable_lock_out.locktime <= now_unix {
                // output is no longer locked, thus handle in the next iteration
                continue;
            }

            // check "*secp256k1fx.TransferOutpu"
            let transfer_output = stakeable_lock_out.clone().transfer_output;
            let res = self.keychain.spend(&transfer_output, now_unix);
            if res.is_none() {
                // cannot spend the output, move onto next
                continue;
            }
            let (transfer_input, input_signers) = res.unwrap();

            // ref. https://github.com/ava-labs/avalanchego/blob/v1.7.9/vms/platformvm/spend.go#L117
            let mut remaining_value = transfer_input.amount;
            let amount_to_stake = (stake_amount - amount_staked) // amount we still need to stake
                .min(
                    remaining_value, // amount available to stake
                );
            amount_staked += amount_to_stake;
            remaining_value -= amount_to_stake;

            // add input to the consumed inputs
            transferable_inputs.push(avax::TransferableInput {
                utxo_id: utxo.utxo_id.clone(),
                asset_id: utxo.asset_id,
                stakeable_lock_in: Some(platformvm::StakeableLockIn {
                    locktime: stakeable_lock_out.locktime,
                    transfer_input,
                }),
                ..avax::TransferableInput::default()
            });

            // add output to the staked outputs
            unlocked_outputs.push(avax::TransferableOutput {
                asset_id: utxo.asset_id,
                stakeable_lock_out: Some(platformvm::StakeableLockOut {
                    locktime: stakeable_lock_out.clone().locktime,
                    transfer_output: secp256k1fx::TransferOutput {
                        amount: amount_to_stake,
                        output_owners: stakeable_lock_out.clone().transfer_output.output_owners,
                    },
                }),
                ..avax::TransferableOutput::default()
            });

            if remaining_value > 0 {
                // this input provided more value than was needed to be locked
                // some must be returned
                locked_outputs.push(avax::TransferableOutput {
                    asset_id: utxo.asset_id,
                    stakeable_lock_out: Some(platformvm::StakeableLockOut {
                        locktime: stakeable_lock_out.clone().locktime,
                        transfer_output: secp256k1fx::TransferOutput {
                            amount: remaining_value,
                            output_owners: stakeable_lock_out.clone().transfer_output.output_owners,
                        },
                    }),
                    ..avax::TransferableOutput::default()
                });
            }

            signers.push(input_signers);
        }

        // ref. https://github.com/ava-labs/avalanchego/blob/v1.7.9/vms/platformvm/spend.go#L166
        // ref. https://github.com/ava-labs/subnet-cli/blob/6bbe9f4aff353b812822af99c08133af35dbc6bd/client/p.go#L732
        let mut amount_burned = 0_u64;
        for utxo in utxos.iter() {
            // have staked more AVAX then we need to
            // have burned more AVAX then we need to
            // no need to consume more AVAX
            if amount_staked >= stake_amount && amount_burned >= fee {
                break;
            }
            // ignore other assets
            if utxo.asset_id != self.avax_asset_id {
                continue;
            }

            let (skip, transfer_output) = {
                if utxo.transfer_output.is_some() {
                    let transfer_output = utxo.transfer_output.clone().unwrap();
                    (false, transfer_output)
                } else {
                    let stakeable_lock_out = utxo.stakeable_lock_out.clone().unwrap();
                    (
                        stakeable_lock_out.locktime > now_unix,
                        stakeable_lock_out.transfer_output,
                    )
                }
            };
            // output is currently locked, so this output cannot be burned
            // or it may have already been consumed above
            if skip {
                continue;
            }

            let res = self.keychain.spend(&transfer_output, now_unix);
            if res.is_none() {
                // cannot spend the output, move onto next
                continue;
            }
            let (transfer_input, input_signers) = res.unwrap();

            // ref. https://github.com/ava-labs/avalanchego/blob/v1.7.9/vms/platformvm/spend.go#L205
            // ref. https://github.com/ava-labs/subnet-cli/blob/6bbe9f4aff353b812822af99c08133af35dbc6bd/client/p.go#L763
            let mut remaining_value = transfer_input.amount;
            let amount_to_burn = (fee - amount_burned) // amount we still need to burn
                .min(
                    remaining_value, // amount available to burn
                );
            amount_burned += amount_to_burn;
            remaining_value -= amount_to_burn;

            let amount_to_stake = (stake_amount - amount_staked) // amount we still need to stake
                .min(
                    remaining_value, // amount available to stake
                );
            amount_staked += amount_to_stake;
            remaining_value -= amount_to_stake;

            transferable_inputs.push(avax::TransferableInput {
                utxo_id: utxo.utxo_id.clone(),
                asset_id: utxo.asset_id,
                transfer_input: Some(transfer_input),
                ..avax::TransferableInput::default()
            });

            if amount_to_stake > 0 {
                unlocked_outputs.push(avax::TransferableOutput {
                    asset_id: utxo.asset_id,
                    transfer_output: Some(secp256k1fx::TransferOutput {
                        amount: amount_to_stake,
                        output_owners: secp256k1fx::OutputOwners {
                            locktime: 0,
                            threshold: 1,
                            addrs: vec![self.short_address.clone()],
                        },
                    }),
                    ..avax::TransferableOutput::default()
                });
            }

            if remaining_value > 0 {
                locked_outputs.push(avax::TransferableOutput {
                    asset_id: utxo.asset_id,
                    transfer_output: Some(secp256k1fx::TransferOutput {
                        amount: remaining_value,
                        output_owners: secp256k1fx::OutputOwners {
                            locktime: 0,
                            threshold: 1,
                            addrs: vec![self.short_address.clone()],
                        },
                    }),
                    ..avax::TransferableOutput::default()
                });
            }

            signers.push(input_signers);
        }

        if amount_staked > 0 && amount_staked < stake_amount {
            return Err(Error::new(
                ErrorKind::Other,
                "insufficient balance for stake amount",
            ));
        }
        if amount_burned > 0 && amount_burned < fee {
            return Err(Error::new(
                ErrorKind::Other,
                "insufficient balance for gas fee",
            ));
        }

        // TODO: for now just ignore "signers" in the sorting
        // since the wallet currently only supports one soft key
        transferable_inputs.sort();
        unlocked_outputs.sort();
        locked_outputs.sort();

        Ok((
            transferable_inputs,
            unlocked_outputs,
            locked_outputs,
            signers,
        ))
    }
}