Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Export import avax #49

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 35 additions & 3 deletions crates/ash_sdk/src/avalanche.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,15 @@ use crate::{
use async_std::task;
use avalanche_types::{
ids::short::Id as ShortId,
jsonrpc::{avm::GetBalanceResult, platformvm::ApiOwner},
jsonrpc::{
avm::GetBalanceResult as AvmGetBalanceResult,
platformvm::{ApiOwner, GetBalanceResult as PlatformvmGetBalanceResult},
},
key::secp256k1::address::avax_address_to_short_bytes,
txs::utxo,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Avalanche Primary Network ID
/// This Subnet contains the P-Chain that is used for all Subnet operations
Expand Down Expand Up @@ -344,15 +348,43 @@ pub struct AvalancheXChainBalance {
pub utxos_ids: Vec<utxo::Id>,
}

impl From<GetBalanceResult> for AvalancheXChainBalance {
fn from(result: GetBalanceResult) -> Self {
impl From<AvmGetBalanceResult> for AvalancheXChainBalance {
fn from(result: AvmGetBalanceResult) -> Self {
Self {
balance: result.balance,
utxos_ids: result.utxo_ids.unwrap_or_default(),
}
}
}

/// Avalanche P-Chain balance
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AvalanchePChainBalance {
pub balance: u64,
pub unlocked: u64,
pub locked_stakeable: u64,
pub balances: HashMap<String, u64>,
pub unlockeds: HashMap<String, u64>,
pub locked_not_stakeable: u64,
#[serde(rename = "utxoIDs")]
pub utxo_ids: Vec<utxo::Id>,
}

impl From<PlatformvmGetBalanceResult> for AvalanchePChainBalance {
fn from(result: PlatformvmGetBalanceResult) -> Self {
Self {
balance: result.balance,
unlocked: result.unlocked,
locked_stakeable: result.locked_stakeable.unwrap_or_default(),
balances: result.balances.unwrap_or_default(),
unlockeds: result.unlockeds.unwrap_or_default(),
locked_not_stakeable: result.locked_not_stakeable.unwrap_or_default(),
utxo_ids: result.utxo_ids.unwrap_or_default(),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
16 changes: 16 additions & 0 deletions crates/ash_sdk/src/avalanche/jsonrpc/platformvm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::avalanche::{
blockchains::AvalancheBlockchain,
jsonrpc::{get_json_rpc_req_result, JsonRpcResponse},
subnets::{AvalancheSubnet, AvalancheSubnetValidator},
AvalanchePChainBalance,
};
use crate::{errors::*, impl_json_rpc_response};
use avalanche_types::{
Expand Down Expand Up @@ -53,6 +54,7 @@ impl_json_rpc_response!(
);
impl_json_rpc_response!(GetBlockchainsResponse, GetBlockchainsResult);
impl_json_rpc_response!(GetCurrentValidatorsResponse, GetCurrentValidatorsResult);
impl_json_rpc_response!(GetBalanceResponse, GetBalanceResult);

/// Get the Subnets of the network by querying the P-Chain API
pub fn get_network_subnets(
Expand Down Expand Up @@ -131,6 +133,20 @@ pub fn get_current_validators(
Ok(current_validators)
}

/// Get the balance of an address by querying the X-Chain API
pub fn get_balance(rpc_url: &str, address: &str) -> Result<AvalanchePChainBalance, RpcError> {
let balance = get_json_rpc_req_result::<GetBalanceResponse, GetBalanceResult>(
rpc_url,
"platform.getBalance",
Some(ureq::json!({
"addresses": vec![address],
})),
)?
.into();

Ok(balance)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
1 change: 1 addition & 0 deletions crates/ash_sdk/src/avalanche/txs.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2023, E36 Knots

pub mod p;
pub mod x;

// Module that contains code to issue transactions
28 changes: 28 additions & 0 deletions crates/ash_sdk/src/avalanche/txs/p.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2023, E36 Knots

// Module that contains code to issue transactions on the X-Chain

use crate::{avalanche::wallets::AvalancheWallet, errors::*};
use avalanche_types::{ids::Id, wallet::p::import};

/// Import AVAX from another chain (to the P-Chain)
// See https://github.com/ava-labs/avalanche-types-rs/blob/0f499e038ca01af09c5be207b6d144262222e659/src/wallet/p/import.rs#L98
pub async fn import_avax(
wallet: &AvalancheWallet,
source_chain_id: Id,
check_acceptance: bool,
) -> Result<Id, AshError> {
let tx_id = import::Tx::new(&wallet.pchain_wallet.p())
.source_blockchain_id(source_chain_id)
.check_acceptance(check_acceptance)
.issue()
.await
.map_err(|e| AvalancheWalletError::IssueTx {
blockchain_name: "P-Chain".to_string(),
tx_type: "import".to_string(),
msg: e.to_string(),
})?;

Ok(tx_id)
}
33 changes: 28 additions & 5 deletions crates/ash_sdk/src/avalanche/txs/x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use crate::{avalanche::wallets::AvalancheWallet, errors::*};
use avalanche_types::{
ids::{short::Id as ShortId, Id},
wallet::x::transfer,
wallet::x::{export, transfer},
};

/// Transfer AVAX from a wallet to the receiver
Expand All @@ -31,6 +31,29 @@ pub async fn transfer_avax(
Ok(tx_id)
}

/// Export AVAX to another chain (from the X-Chain)
// See https://github.com/ava-labs/avalanche-types-rs/blob/0f499e038ca01af09c5be207b6d144262222e659/src/wallet/p/import.rs#L98
pub async fn export_avax(
wallet: &AvalancheWallet,
dest_chain_id: Id,
amount: u64,
check_acceptance: bool,
) -> Result<Id, AshError> {
let tx_id = export::Tx::new(&wallet.xchain_wallet.x())
.destination_blockchain_id(dest_chain_id)
.amount(amount)
.check_acceptance(check_acceptance)
.issue()
.await
.map_err(|e| AvalancheWalletError::IssueTx {
blockchain_name: "X-Chain".to_string(),
tx_type: "export".to_string(),
msg: e.to_string(),
})?;

Ok(tx_id)
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -39,7 +62,7 @@ mod tests {

const AVAX_EWOQ_PRIVATE_KEY: &str =
"PrivateKey-ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN";
const AVAX_LOCAL_XCHAIN_ADDR: &str = "X-custom1w44zzlzf68gwaskce2s4r82t5u08pje5mhq2en";
const AVAX_DEST_XCHAIN_ADDR: &str = "X-custom1w44zzlzf68gwaskce2s4r82t5u08pje5mhq2en";

// Load the test network using avalanche-network-runner
fn load_test_network() -> AvalancheNetwork {
Expand All @@ -54,18 +77,18 @@ mod tests {
.create_wallet_from_cb58(AVAX_EWOQ_PRIVATE_KEY)
.unwrap();
let rpc_url = &local_network.get_xchain().unwrap().rpc_url;
let init_balance = get_balance(rpc_url, AVAX_LOCAL_XCHAIN_ADDR, "AVAX").unwrap();
let init_balance = get_balance(rpc_url, AVAX_DEST_XCHAIN_ADDR, "AVAX").unwrap();

transfer_avax(
&local_wallet,
address_to_short_id(AVAX_LOCAL_XCHAIN_ADDR, "X"),
address_to_short_id(AVAX_DEST_XCHAIN_ADDR, "X"),
100000000,
true,
)
.await
.unwrap();

let final_balance = get_balance(rpc_url, AVAX_LOCAL_XCHAIN_ADDR, "AVAX").unwrap();
let final_balance = get_balance(rpc_url, AVAX_DEST_XCHAIN_ADDR, "AVAX").unwrap();

assert_eq!(init_balance.balance + 100000000, final_balance.balance)
}
Expand Down
73 changes: 73 additions & 0 deletions crates/ash_sdk/tests/txs_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2023, E36 Knots

// Module that contains code to test transactions

// Not testing as the underlying code is not working
// See https://github.com/ava-labs/avalanche-types-rs/blob/0f499e038ca01af09c5be207b6d144262222e659/src/wallet/p/import.rs#L98

use ash_sdk::avalanche::{
jsonrpc::{avm, platformvm},
txs::{p, x},
AvalancheNetwork,
};
use async_std;

const AVAX_EWOQ_PRIVATE_KEY: &str = "PrivateKey-ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN";

// Load the test network using avalanche-network-runner
fn load_test_network() -> AvalancheNetwork {
AvalancheNetwork::load("local", Some("tests/conf/avalanche-network-runner.yml")).unwrap()
}

#[async_std::test]
#[ignore]
async fn test_txs_export_import_avax_to_pchain() {
let local_network = load_test_network();
let local_wallet = local_network
.create_wallet_from_cb58(AVAX_EWOQ_PRIVATE_KEY)
.unwrap();

let xchain_rpc_url = &local_network.get_xchain().unwrap().rpc_url;
let pchain_rpc_url = &local_network.get_pchain().unwrap().rpc_url;

let init_xchain_balance = avm::get_balance(
xchain_rpc_url,
&local_wallet.xchain_wallet.x_address,
"AVAX",
)
.unwrap();
let init_pchain_balance =
platformvm::get_balance(pchain_rpc_url, &local_wallet.pchain_wallet.p_address).unwrap();

x::export_avax(
&local_wallet,
local_network.get_pchain().unwrap().id,
100000000,
true,
)
.await
.unwrap();

p::import_avax(&local_wallet, local_network.get_xchain().unwrap().id, true)
.await
.unwrap();

let final_xchain_balance = avm::get_balance(
xchain_rpc_url,
&local_wallet.xchain_wallet.x_address,
"AVAX",
)
.unwrap();
let final_pchain_balance =
platformvm::get_balance(pchain_rpc_url, &local_wallet.pchain_wallet.p_address).unwrap();

assert_eq!(
init_xchain_balance.balance + 100000000 - local_wallet.xchain_wallet.tx_fee,
final_xchain_balance.balance
);
assert_eq!(
init_pchain_balance.balance - 100000000 - local_wallet.pchain_wallet.tx_fee,
final_pchain_balance.balance
);
}