-
Notifications
You must be signed in to change notification settings - Fork 98
feat: add ledger subcommand #1640
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
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
a90965c
feat: add ledger subcommand
7ea7083
Merge branch 'master' of github.com:dfinity/sdk into pshahi/ledger-cr…
ad8589e
Merge branch 'master' of github.com:dfinity/sdk into pshahi/ledger-cr…
ad7d876
update error message
9d8948e
convert to eprint
cd0634f
update transaction notification result type
d04627d
top up
fbe1ad7
Merge branch 'master' into pshahi/ledger
p-shahi 479dc84
incorporate review comments
d30ce8c
Merge branch 'pshahi/ledger' of github.com:dfinity/sdk into pshahi/le…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(()) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(()) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"))] | ||
| 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(()) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
icpande8sbeing validated bye8s_validator. Would it make sense to call it something else, or is it really true that the same range constraints (none?) apply to both?There was a problem hiding this comment.
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