Skip to content
Merged
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
16 changes: 16 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion src/dfx/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,15 @@ candid = { version = "0.6.20", features = [ "random" ] }
chrono = "0.4.9"
clap = "3.0.0-beta.2"
console = "0.7.7"
crc32fast = "1.2.0"
crossbeam = "0.7.3"
ctrlc = { version = "3.1.6", features = [ "termination" ] }
delay = "0.3.1"
dialoguer = "0.6.2"
erased-serde = "0.3.10"
flate2 = "1.0.11"
futures = "0.3.5"
hex = "0.4.2"
hex = {version = "0.4.2", features = ["serde"] }
indicatif = "0.13.0"
lazy-init = "0.5.0"
lazy_static = "1.4.0"
Expand All @@ -51,6 +52,7 @@ regex = "1.3.1"
ring = "0.16.11"
reqwest = { version = "0.10.4", features = [ "blocking", "json", "rustls-tls" ] }
rustls = "0.18.0"
rust_decimal = "1.10.3"
semver = "0.9.0"
serde = "1.0"
serde_bytes = "0.11.2"
Expand Down
17 changes: 17 additions & 0 deletions src/dfx/src/commands/ledger/account_id.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use crate::lib::environment::Environment;
use crate::lib::error::DfxResult;
use crate::lib::nns_types::account_identifier::AccountIdentifier;

use clap::Clap;

/// Prints the selected identity's AccountIdentifier.
#[derive(Clap)]
pub struct AccountIdOpts {}

pub async fn exec(env: &dyn Environment, _opts: AccountIdOpts) -> DfxResult {
let sender = env
.get_selected_identity_principal()
.expect("Selected identity not instantiated.");
println!("{}", AccountIdentifier::new(sender, None));
Ok(())
}
52 changes: 52 additions & 0 deletions src/dfx/src/commands/ledger/balance.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use crate::lib::environment::Environment;
use crate::lib::error::DfxResult;
use crate::lib::nns_types::account_identifier::AccountIdentifier;
use crate::lib::nns_types::icpts::ICPTs;
use crate::lib::nns_types::AccountBalanceArgs;
use crate::lib::nns_types::LEDGER_CANISTER_ID;

use anyhow::anyhow;
use candid::{Decode, Encode};
use clap::Clap;
use ic_types::principal::Principal;
use std::str::FromStr;

const ACCOUNT_BALANCE_METHOD: &str = "account_balance_dfx";

/// Prints the account balance of the user
#[derive(Clap)]
pub struct BalanceOpts {
/// Specifies an AccountIdentifier to get the balance of
of: Option<String>,
}

pub async fn exec(env: &dyn Environment, opts: BalanceOpts) -> DfxResult {
let sender = env
.get_selected_identity_principal()
.expect("Selected identity not instantiated.");
let acc_id = opts
.of
.map_or_else(
|| Ok(AccountIdentifier::new(sender, None)),
|v| AccountIdentifier::from_str(&v),
)
.map_err(|err| anyhow!(err))?;
let agent = env
.get_agent()
.ok_or_else(|| anyhow!("Cannot get HTTP client from environment."))?;
let canister_id = Principal::from_text(LEDGER_CANISTER_ID)?;

let result = agent
.query(&canister_id, ACCOUNT_BALANCE_METHOD)
.with_arg(Encode!(&AccountBalanceArgs {
account: acc_id.to_string()
})?)
.call()
.await?;

let balance = Decode!(&result, ICPTs)?;

println!("{}", balance);

Ok(())
}
76 changes: 76 additions & 0 deletions src/dfx/src/commands/ledger/create_canister.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use crate::commands::ledger::{get_icpts_from_args, send_and_notify};
use crate::lib::environment::Environment;
use crate::lib::error::DfxResult;
use crate::lib::nns_types::account_identifier::Subaccount;
use crate::lib::nns_types::icpts::{ICPTs, TRANSACTION_FEE};
use crate::lib::nns_types::{CyclesResponse, Memo};

use crate::util::clap::validators::{e8s_validator, icpts_amount_validator};

use anyhow::anyhow;
use clap::{ArgSettings, Clap};
use ic_types::principal::Principal;
use std::str::FromStr;

const MEMO_CREATE_CANISTER: u64 = 1095062083_u64;

/// Create a canister from ICP
#[derive(Clap)]
pub struct CreateCanisterOpts {
/// ICP to mint into cycles and deposit into destination canister
/// Can be specified as a Decimal with the fractional portion up to 8 decimal places
/// i.e. 100.012
#[clap(long, validator(icpts_amount_validator))]
amount: Option<String>,

/// Specify ICP as a whole number, helpful for use in conjunction with `--e8s`
#[clap(long, validator(e8s_validator), conflicts_with("amount"))]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was a bit puzzled by both icp and e8s being validated by e8s_validator. Would it make sense to call it something else, or is it really true that the same range constraints (none?) apply to both?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The same range constraints apply to both

pub struct ICPTs {
    e8s: u64,
}

icp: Option<String>,

/// Specify e8s as a whole number, helpful for use in conjunction with `--icp`
#[clap(long, validator(e8s_validator), conflicts_with("amount"))]
e8s: Option<String>,

/// Transaction fee, default is 10000 Doms.
#[clap(long, validator(icpts_amount_validator), setting = ArgSettings::Hidden)]
fee: Option<String>,

/// Specify the controller of the new canister
#[clap(long)]
controller: String,

/// Max fee
#[clap(long, validator(icpts_amount_validator), setting = ArgSettings::Hidden)]
max_fee: Option<String>,
}

pub async fn exec(env: &dyn Environment, opts: CreateCanisterOpts) -> DfxResult {
let amount = get_icpts_from_args(opts.amount, opts.icp, opts.e8s)?;

let fee = opts.fee.map_or(Ok(TRANSACTION_FEE), |v| {
ICPTs::from_str(&v).map_err(|err| anyhow!(err))
})?;

// validated by memo_validator
let memo = Memo(MEMO_CREATE_CANISTER);

let to_subaccount = Some(Subaccount::from(&Principal::from_text(opts.controller)?));

let max_fee = opts
.max_fee
.map_or(ICPTs::new(0, 0), |v| ICPTs::from_str(&v))
.map_err(|err| anyhow!(err))?;

let result = send_and_notify(env, memo, amount, fee, to_subaccount, max_fee).await?;

match result {
CyclesResponse::CanisterCreated(v) => {
println!("Canister created with id: {:?}", v.to_text());
}
CyclesResponse::Refunded(msg, maybe_block_height) => {
println!("Refunded with message: {} at {:?}", msg, maybe_block_height);
}
CyclesResponse::ToppedUp(()) => unreachable!(),
};
Ok(())
}
145 changes: 145 additions & 0 deletions src/dfx/src/commands/ledger/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
use crate::lib::environment::Environment;
use crate::lib::error::DfxResult;
use crate::lib::nns_types::account_identifier::{AccountIdentifier, Subaccount};
use crate::lib::nns_types::icpts::ICPTs;
use crate::lib::nns_types::{
BlockHeight, CyclesResponse, Memo, NotifyCanisterArgs, SendArgs, CYCLE_MINTER_CANISTER_ID,
LEDGER_CANISTER_ID,
};
use crate::lib::provider::create_agent_environment;
use crate::lib::root_key::fetch_root_key_if_needed;
use crate::lib::waiter::waiter_with_timeout;
use crate::util::expiry_duration;

use anyhow::anyhow;
use candid::{Decode, Encode};
use clap::Clap;
use ic_types::principal::Principal;
use std::str::FromStr;
use tokio::runtime::Runtime;

const SEND_METHOD: &str = "send_dfx";
const NOTIFY_METHOD: &str = "notify_dfx";

mod account_id;
mod balance;
mod create_canister;
mod top_up;
mod transfer;

/// Ledger commands.
#[derive(Clap)]
#[clap(name("ledger"))]
pub struct LedgerOpts {
/// Override the compute network to connect to. By default, the local network is used.
#[clap(long)]
network: Option<String>,

#[clap(subcommand)]
subcmd: SubCommand,
}

#[derive(Clap)]
enum SubCommand {
AccountId(account_id::AccountIdOpts),
Balance(balance::BalanceOpts),
CreateCanister(create_canister::CreateCanisterOpts),
TopUp(top_up::TopUpOpts),
Transfer(transfer::TransferOpts),
}

pub fn exec(env: &dyn Environment, opts: LedgerOpts) -> DfxResult {
let agent_env = create_agent_environment(env, opts.network.clone())?;
let runtime = Runtime::new().expect("Unable to create a runtime");
runtime.block_on(async {
match opts.subcmd {
SubCommand::AccountId(v) => account_id::exec(&agent_env, v).await,
SubCommand::Balance(v) => balance::exec(&agent_env, v).await,
SubCommand::CreateCanister(v) => create_canister::exec(&agent_env, v).await,
SubCommand::TopUp(v) => top_up::exec(&agent_env, v).await,
SubCommand::Transfer(v) => transfer::exec(&agent_env, v).await,
}
})
}

fn get_icpts_from_args(
amount: Option<String>,
icp: Option<String>,
e8s: Option<String>,
) -> DfxResult<ICPTs> {
if amount.is_none() {
let icp = match icp {
Some(s) => {
// validated by e8s_validator
let icps = s.parse::<u64>().unwrap();
ICPTs::from_icpts(icps).map_err(|err| anyhow!(err))?
}
None => ICPTs::from_e8s(0),
};
let icp_from_e8s = match e8s {
Some(s) => {
// validated by e8s_validator
let e8s = s.parse::<u64>().unwrap();
ICPTs::from_e8s(e8s)
}
None => ICPTs::from_e8s(0),
};
let amount = icp + icp_from_e8s;
Ok(amount.map_err(|err| anyhow!(err))?)
} else {
Ok(ICPTs::from_str(&amount.unwrap())
.map_err(|err| anyhow!("Could not add ICPs and e8s: {}", err))?)
}
}

async fn send_and_notify(
env: &dyn Environment,
memo: Memo,
amount: ICPTs,
fee: ICPTs,
to_subaccount: Option<Subaccount>,
max_fee: ICPTs,
) -> DfxResult<CyclesResponse> {
let ledger_canister_id = Principal::from_text(LEDGER_CANISTER_ID)?;

let cycle_minter_id = Principal::from_text(CYCLE_MINTER_CANISTER_ID)?;

let agent = env
.get_agent()
.ok_or_else(|| anyhow!("Cannot get HTTP client from environment."))?;

fetch_root_key_if_needed(env).await?;

let to = AccountIdentifier::new(cycle_minter_id.clone(), to_subaccount);

let result = agent
.update(&ledger_canister_id, SEND_METHOD)
.with_arg(Encode!(&SendArgs {
memo,
amount,
fee,
from_subaccount: None,
to,
created_at_time: None,
})?)
.call_and_wait(waiter_with_timeout(expiry_duration()))
.await?;

let block_height = Decode!(&result, BlockHeight)?;
println!("Transfer sent at BlockHeight: {}", block_height);

let result = agent
.update(&ledger_canister_id, NOTIFY_METHOD)
.with_arg(Encode!(&NotifyCanisterArgs {
block_height,
max_fee,
from_subaccount: None,
to_canister: cycle_minter_id,
to_subaccount,
})?)
.call_and_wait(waiter_with_timeout(expiry_duration()))
.await?;

let result = Decode!(&result, CyclesResponse)?;
Ok(result)
}
Loading