repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/deploy_contract/initialize_mode/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/deploy_contract/initialize_mode/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, EnumDiscriminants, interactive_clap_derive::InteractiveClap)] #[interactive_clap(context = super::super::super::super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select the need for initialization: pub enum InitializeMode { /// Add an initialize #[strum_discriminants(strum(message = "with-init-call - Add an initialize"))] WithInitCall(super::super::call_function::FunctionCallAction), /// Don't add an initialize #[strum_discriminants(strum(message = "without-init-call - Don't add an initialize"))] WithoutInitCall(NoInitialize), } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::super::ConstructTransactionContext)] pub struct NoInitialize { #[interactive_clap(subcommand)] next_action: super::super::super::super::add_action_last::NextAction, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/delete_account/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/delete_account/mod.rs
use color_eyre::owo_colors::OwoColorize; use inquire::Select; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = DeleteAccountActionContext)] pub struct DeleteAccountAction { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] /// Enter the beneficiary ID to delete this account ID: beneficiary_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_last::NextAction, } #[derive(Debug, Clone)] pub struct DeleteAccountActionContext(super::super::super::ConstructTransactionContext); impl DeleteAccountActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<DeleteAccountAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let beneficiary_id: near_primitives::types::AccountId = scope.beneficiary_id.clone().into(); let action = near_primitives::transaction::Action::DeleteAccount( near_primitives::transaction::DeleteAccountAction { beneficiary_id }, ); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<DeleteAccountActionContext> for super::super::super::ConstructTransactionContext { fn from(item: DeleteAccountActionContext) -> Self { item.0 } } impl DeleteAccountAction { pub fn input_beneficiary_id( context: &super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { loop { let beneficiary_account_id = if let Some(account_id) = crate::common::input_non_signer_account_id_from_used_account_list( &context.global_context.config.credentials_home_dir, "What is the beneficiary account ID?", )? { account_id } else { return Ok(None); }; if beneficiary_account_id.0 == context.signer_account_id { eprintln!("{}", "You have selected a beneficiary account ID that will now be deleted. This will result in the loss of your funds. So make your choice again.".red()); continue; } if context.global_context.offline { return Ok(Some(beneficiary_account_id)); } #[derive(derive_more::Display)] enum ConfirmOptions { #[display("Yes, I want to check if account <{account_id}> exists. (It is free of charge, and only requires Internet access)")] Yes { account_id: crate::types::account_id::AccountId, }, #[display("No, I know this account exists and want to continue.")] No, } let select_choose_input = Select::new("\nDo you want to check the existence of the specified account so that you don't lose tokens?", vec![ConfirmOptions::Yes{account_id: beneficiary_account_id.clone()}, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes { account_id } = select_choose_input { if crate::common::find_network_where_account_exist( &context.global_context, account_id.clone().into(), )? .is_none() { eprintln!( "\nHeads up! You will lose remaining NEAR tokens on the account you delete if you specify the account <{}> as the beneficiary as it does not exist on [{}] networks.", account_id, context.global_context.config.network_names().join(", ") ); if !crate::common::ask_if_different_account_id_wanted()? { return Ok(Some(account_id)); } } else { return Ok(Some(account_id)); }; } else { return Ok(Some(beneficiary_account_id)); }; } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/add_key/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/add_key/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod access_key_type; mod use_manually_provided_seed_phrase; mod use_public_key; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] pub struct AddKeyAction { #[interactive_clap(subcommand)] permission: AccessKeyPermission, } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select a permission that you want to add to the access key: pub enum AccessKeyPermission { #[strum_discriminants(strum( message = "grant-full-access - A permission with full access" ))] /// Provide data for a full access key GrantFullAccess(self::access_key_type::FullAccessType), #[strum_discriminants(strum( message = "grant-function-call-access - A permission with function call" ))] /// Provide data for a function-call access key GrantFunctionCallAccess(self::access_key_type::FunctionCallType), } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = self::access_key_type::AccessKeyPermissionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Add an access key for this account: pub enum AccessKeyMode { #[strum_discriminants(strum( message = "use-manually-provided-seed-prase - Use the provided seed phrase manually" ))] /// Use the provided seed phrase manually UseManuallyProvidedSeedPhrase( self::use_manually_provided_seed_phrase::AddAccessWithSeedPhraseAction, ), #[strum_discriminants(strum( message = "use-manually-provided-public-key - Use the provided public key manually" ))] /// Use the provided public key manually UseManuallyProvidedPublicKey(self::use_public_key::AddAccessKeyAction), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/add_key/access_key_type/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/add_key/access_key_type/mod.rs
use std::str::FromStr; use inquire::{CustomType, Select, Text}; #[derive(Debug, Clone)] pub struct AccessKeyPermissionContext { pub global_context: crate::GlobalContext, pub signer_account_id: near_primitives::types::AccountId, pub receiver_account_id: near_primitives::types::AccountId, pub actions: Vec<near_primitives::transaction::Action>, pub access_key_permission: near_primitives::account::AccessKeyPermission, } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = FullAccessTypeContext)] pub struct FullAccessType { #[interactive_clap(subcommand)] access_key_mode: super::AccessKeyMode, } #[derive(Debug, Clone)] pub struct FullAccessTypeContext(AccessKeyPermissionContext); impl FullAccessTypeContext { pub fn from_previous_context( previous_context: super::super::super::super::ConstructTransactionContext, _scope: &<FullAccessType as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(AccessKeyPermissionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions: previous_context.actions, access_key_permission: near_primitives::account::AccessKeyPermission::FullAccess, })) } } impl From<FullAccessTypeContext> for AccessKeyPermissionContext { fn from(item: FullAccessTypeContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = FunctionCallTypeContext)] pub struct FunctionCallType { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] allowance: crate::types::near_allowance::NearAllowance, #[interactive_clap(long)] /// Enter the contract account ID that this access key can be used to sign call function transactions for: contract_account_id: crate::types::account_id::AccountId, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] function_names: crate::types::vec_string::VecString, #[interactive_clap(subcommand)] access_key_mode: super::AccessKeyMode, } #[derive(Debug, Clone)] pub struct FunctionCallTypeContext(AccessKeyPermissionContext); impl FunctionCallTypeContext { pub fn from_previous_context( previous_context: super::super::super::super::ConstructTransactionContext, scope: &<FunctionCallType as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let access_key_permission = near_primitives::account::AccessKeyPermission::FunctionCall( near_primitives::account::FunctionCallPermission { allowance: scope.allowance.optional_near_token().map(Into::into), receiver_id: scope.contract_account_id.to_string(), method_names: scope.function_names.clone().into(), }, ); Ok(Self(AccessKeyPermissionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions: previous_context.actions, access_key_permission, })) } } impl From<FunctionCallTypeContext> for AccessKeyPermissionContext { fn from(item: FunctionCallTypeContext) -> Self { item.0 } } impl FunctionCallType { pub fn input_function_names( _context: &super::super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::vec_string::VecString>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum( to_string = "Yes, I want to input a list of function names that can be called when transaction is signed by this access key" )] Yes, #[strum(to_string = "No, I allow it to call any functions on the specified contract")] No, } let select_choose_input = Select::new( "Would you like the access key to be valid exclusively for calling specific functions on the contract?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { let mut input_function_names = Text::new("Enter a comma-separated list of function names that will be allowed to be called in a transaction signed by this access key:") .prompt()?; if input_function_names.contains('\"') { input_function_names.clear() }; if input_function_names.is_empty() { Ok(Some(crate::types::vec_string::VecString(vec![]))) } else { Ok(Some(crate::types::vec_string::VecString::from_str( &input_function_names, )?)) } } else { Ok(Some(crate::types::vec_string::VecString(vec![]))) } } pub fn input_allowance( _context: &super::super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::near_allowance::NearAllowance>> { let allowance_near_balance: crate::types::near_allowance::NearAllowance = CustomType::new("Enter the allowance, a budget this access key can use to pay for transaction fees (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear):") .with_starting_input("unlimited") .prompt()?; Ok(Some(allowance_near_balance)) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/add_key/use_manually_provided_seed_phrase/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/add_key/use_manually_provided_seed_phrase/mod.rs
use std::str::FromStr; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::access_key_type::AccessKeyPermissionContext)] #[interactive_clap(output_context = AddAccessWithSeedPhraseActionContext)] pub struct AddAccessWithSeedPhraseAction { /// Enter the seed_phrase: master_seed_phrase: String, #[interactive_clap(subcommand)] next_action: super::super::super::super::add_action_last::NextAction, } #[derive(Debug, Clone)] pub struct AddAccessWithSeedPhraseActionContext( super::super::super::super::ConstructTransactionContext, ); impl AddAccessWithSeedPhraseActionContext { pub fn from_previous_context( previous_context: super::access_key_type::AccessKeyPermissionContext, scope: &<AddAccessWithSeedPhraseAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let seed_phrase_hd_path_default = slipped10::BIP32Path::from_str("m/44'/397'/0'").unwrap(); let public_key = crate::common::get_public_key_from_seed_phrase( seed_phrase_hd_path_default, &scope.master_seed_phrase, )?; let access_key = near_primitives::account::AccessKey { nonce: 0, permission: previous_context.access_key_permission, }; let action = near_primitives::transaction::Action::AddKey(Box::new( near_primitives::transaction::AddKeyAction { public_key, access_key, }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self( super::super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, }, )) } } impl From<AddAccessWithSeedPhraseActionContext> for super::super::super::super::ConstructTransactionContext { fn from(item: AddAccessWithSeedPhraseActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/add_key/use_public_key/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/add_key/use_public_key/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::access_key_type::AccessKeyPermissionContext)] #[interactive_clap(output_context = AddAccessKeyActionContext)] pub struct AddAccessKeyAction { /// Enter the public key: public_key: crate::types::public_key::PublicKey, #[interactive_clap(subcommand)] next_action: super::super::super::super::add_action_last::NextAction, } #[derive(Debug, Clone)] pub struct AddAccessKeyActionContext(super::super::super::super::ConstructTransactionContext); impl AddAccessKeyActionContext { pub fn from_previous_context( previous_context: super::access_key_type::AccessKeyPermissionContext, scope: &<AddAccessKeyAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let access_key = near_primitives::account::AccessKey { nonce: 0, permission: previous_context.access_key_permission, }; let action = near_primitives::transaction::Action::AddKey(Box::new( near_primitives::transaction::AddKeyAction { public_key: scope.public_key.clone().into(), access_key, }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self( super::super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, }, )) } } impl From<AddAccessKeyActionContext> for super::super::super::super::ConstructTransactionContext { fn from(item: AddAccessKeyActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/stake/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/stake/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = StakeActionContext)] pub struct StakeAction { /// Enter the amount to stake: (example: 10000NEAR) stake_amount: crate::types::near_token::NearToken, /// Enter the public key of the validator key pair used on your NEAR node (see validator_key.json): public_key: crate::types::public_key::PublicKey, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_last::NextAction, } #[derive(Debug, Clone)] pub struct StakeActionContext(super::super::super::ConstructTransactionContext); impl StakeActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<StakeAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::Stake(Box::new( near_primitives::transaction::StakeAction { stake: scope.stake_amount.into(), public_key: scope.public_key.clone().into(), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<StakeActionContext> for super::super::super::ConstructTransactionContext { fn from(item: StakeActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/deploy_global_contract/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/deploy_global_contract/mod.rs
use color_eyre::eyre::Context; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = DeployGlobalContractActionContext)] pub struct DeployGlobalContractAction { /// What is the file location of the contract? pub file_path: crate::types::path_buf::PathBuf, #[interactive_clap(subcommand)] mode: DeployGlobalMode, } #[derive(Debug, Clone)] pub struct DeployGlobalContractActionContext { pub context: super::super::super::ConstructTransactionContext, pub code: Vec<u8>, } impl DeployGlobalContractActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<DeployGlobalContractAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let code = std::fs::read(&scope.file_path).wrap_err_with(|| { format!("Failed to open or read the file: {:?}.", &scope.file_path.0,) })?; Ok(Self { context: previous_context, code, }) } } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = DeployGlobalContractActionContext)] #[interactive_clap(output_context = DeployGlobalModeContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] #[non_exhaustive] /// Choose a global contract deploy mode: pub enum DeployGlobalMode { #[strum_discriminants(strum( message = "as-global-hash - Deploy code as a global contract code hash (immutable)" ))] /// Deploy code as a global contract code hash (immutable) AsGlobalHash(NextCommand), #[strum_discriminants(strum( message = "as-global-account-id - Deploy code as a global contract account ID (mutable)" ))] /// Deploy code as a global contract account ID (mutable) AsGlobalAccountId(NextCommand), } #[derive(Debug, Clone)] pub struct DeployGlobalModeContext(super::super::super::ConstructTransactionContext); impl DeployGlobalModeContext { pub fn from_previous_context( previous_context: DeployGlobalContractActionContext, scope: &<DeployGlobalMode as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::DeployGlobalContract( near_primitives::action::DeployGlobalContractAction { code: previous_context.code.into(), deploy_mode: match scope { DeployGlobalModeDiscriminants::AsGlobalHash => { near_primitives::action::GlobalContractDeployMode::CodeHash } DeployGlobalModeDiscriminants::AsGlobalAccountId => { near_primitives::action::GlobalContractDeployMode::AccountId } }, }, ); let mut actions = previous_context.context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.context.global_context, signer_account_id: previous_context.context.signer_account_id, receiver_account_id: previous_context.context.receiver_account_id, actions, })) } } impl From<DeployGlobalModeContext> for super::super::super::ConstructTransactionContext { fn from(item: DeployGlobalModeContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = DeployGlobalModeContext)] pub struct NextCommand { #[interactive_clap(subcommand)] next_action: super::super::super::add_action_last::NextAction, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/use_global_contract/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/use_global_contract/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] pub struct UseGlobalContractAction { #[interactive_clap(subcommand)] mode: UseGlobalActionMode, } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] #[non_exhaustive] /// Choose a global contract deploy mode: pub enum UseGlobalActionMode { #[strum_discriminants(strum( message = "use-global-hash - Use a global contract code hash pre-deployed on-chain (immutable)" ))] /// Use a global contract code hash (immutable) UseGlobalHash(UseHashAction), #[strum_discriminants(strum( message = "use-global-account-id - Use a global contract account ID pre-deployed on-chain (mutable)" ))] /// Use a global contract account ID (mutable) UseGlobalAccountId(UseAccountIdAction), } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = UseHashActionContext)] pub struct UseHashAction { /// What is the hash of the global contract? pub hash: crate::types::crypto_hash::CryptoHash, #[interactive_clap(subcommand)] initialize: super::deploy_contract::initialize_mode::InitializeMode, } #[derive(Debug, Clone)] pub struct UseHashActionContext(super::super::super::ConstructTransactionContext); impl UseHashActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<UseHashAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::UseGlobalContract(Box::new( near_primitives::action::UseGlobalContractAction { contract_identifier: near_primitives::action::GlobalContractIdentifier::CodeHash( scope.hash.into(), ), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<UseHashActionContext> for super::super::super::ConstructTransactionContext { fn from(item: UseHashActionContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = UseAccountIdActionContext)] pub struct UseAccountIdAction { #[interactive_clap(skip_default_input_arg)] /// What is the account ID of the global contract? pub account_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] initialize: super::deploy_contract::initialize_mode::InitializeMode, } impl UseAccountIdAction { pub fn input_account_id( context: &super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_non_signer_account_id_from_used_account_list( &context.global_context.config.credentials_home_dir, "What is the account ID of the global contract?", ) } } #[derive(Debug, Clone)] pub struct UseAccountIdActionContext(super::super::super::ConstructTransactionContext); impl UseAccountIdActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<UseAccountIdAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::UseGlobalContract(Box::new( near_primitives::action::UseGlobalContractAction { contract_identifier: near_primitives::action::GlobalContractIdentifier::AccountId( scope.account_id.clone().into(), ), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<UseAccountIdActionContext> for super::super::super::ConstructTransactionContext { fn from(item: UseAccountIdActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/call_function/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/call_function/mod.rs
use inquire::CustomType; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = FunctionCallActionContext)] pub struct FunctionCallAction { #[interactive_clap(skip_default_input_arg)] /// What is the name of the function? function_name: String, #[interactive_clap(value_enum)] #[interactive_clap(skip_default_input_arg)] /// How do you want to pass the function call arguments? function_args_type: crate::commands::contract::call_function::call_function_args_type::FunctionArgsType, /// Enter the arguments to this function: function_args: String, #[interactive_clap(named_arg)] /// Enter gas for function call prepaid_gas: PrepaidGas, } #[derive(Debug, Clone)] pub struct FunctionCallActionContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, receiver_account_id: near_primitives::types::AccountId, actions: Vec<near_primitives::transaction::Action>, function_name: String, function_args: Vec<u8>, } impl FunctionCallActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<FunctionCallAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let function_args = crate::commands::contract::call_function::call_function_args_type::function_args( scope.function_args.clone(), scope.function_args_type.clone(), )?; Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions: previous_context.actions, function_name: scope.function_name.clone(), function_args, }) } } impl FunctionCallAction { fn input_function_args_type( _context: &super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result< Option<crate::commands::contract::call_function::call_function_args_type::FunctionArgsType>, > { crate::commands::contract::call_function::call_function_args_type::input_function_args_type( ) } fn input_function_name( context: &super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<String>> { crate::commands::contract::call_function::input_call_function_name( &context.global_context, &context.receiver_account_id, ) } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = FunctionCallActionContext)] #[interactive_clap(output_context = PrepaidGasContext)] pub struct PrepaidGas { #[interactive_clap(skip_default_input_arg)] /// Enter gas for function call: gas: crate::common::NearGas, #[interactive_clap(named_arg)] /// Enter deposit for a function call attached_deposit: Deposit, } #[derive(Debug, Clone)] pub struct PrepaidGasContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, receiver_account_id: near_primitives::types::AccountId, actions: Vec<near_primitives::transaction::Action>, function_name: String, function_args: Vec<u8>, gas: crate::common::NearGas, } impl PrepaidGasContext { pub fn from_previous_context( previous_context: FunctionCallActionContext, scope: &<PrepaidGas as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions: previous_context.actions, function_name: previous_context.function_name, function_args: previous_context.function_args, gas: scope.gas, }) } } impl PrepaidGas { fn input_gas( _context: &FunctionCallActionContext, ) -> color_eyre::eyre::Result<Option<crate::common::NearGas>> { Ok(Some( CustomType::new("Enter gas for function call:") .with_starting_input("100 TeraGas") .with_validator(move |gas: &crate::common::NearGas| { if gas > &near_gas::NearGas::from_tgas(300) { Ok(inquire::validator::Validation::Invalid( inquire::validator::ErrorMessage::Custom( "You need to enter a value of no more than 300 TeraGas".to_string(), ), )) } else { Ok(inquire::validator::Validation::Valid) } }) .prompt()?, )) } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = PrepaidGasContext)] #[interactive_clap(output_context = DepositContext)] pub struct Deposit { #[interactive_clap(skip_default_input_arg)] /// Enter deposit for a function call: deposit: crate::types::near_token::NearToken, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_last::NextAction, } #[derive(Debug, Clone)] pub struct DepositContext(super::super::super::ConstructTransactionContext); impl DepositContext { pub fn from_previous_context( previous_context: PrepaidGasContext, scope: &<Deposit as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::FunctionCall(Box::new( near_primitives::transaction::FunctionCallAction { method_name: previous_context.function_name, args: previous_context.function_args, gas: near_primitives::gas::Gas::from_gas(previous_context.gas.as_gas()), deposit: scope.deposit.into(), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<DepositContext> for super::super::super::ConstructTransactionContext { fn from(item: DepositContext) -> Self { item.0 } } impl Deposit { fn input_deposit( _context: &PrepaidGasContext, ) -> color_eyre::eyre::Result<Option<crate::types::near_token::NearToken>> { Ok(Some( CustomType::new("Enter deposit for a function call (example: 10 NEAR or 0.5 near or 10000 yoctonear):") .with_starting_input("0 NEAR") .prompt()? )) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/mod.rs
src/commands/transaction/construct_transaction/add_action_1/mod.rs
#![allow(clippy::enum_variant_names, clippy::large_enum_variant)] use strum::{EnumDiscriminants, EnumIter, EnumMessage}; pub mod add_action; #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select an action that you want to add to the action: pub enum NextAction { #[strum_discriminants(strum(message = "add-action - Select a new action"))] /// Choose next action AddAction(self::add_action::AddAction), #[strum_discriminants(strum(message = "skip - Skip adding a new action"))] /// Go to transaction signing Skip(super::skip_action::SkipAction), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; pub mod add_key; pub mod call_function; pub mod create_account; pub mod delete_account; pub mod delete_key; pub mod deploy_contract; pub mod deploy_global_contract; pub mod stake; pub mod transfer; pub mod use_global_contract; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::ConstructTransactionContext)] pub struct AddAction { #[interactive_clap(subcommand)] pub action: ActionSubcommand, } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select an action that you want to add to the action: pub enum ActionSubcommand { #[strum_discriminants(strum( message = "transfer - The transfer is carried out in NEAR tokens" ))] /// Specify data for transfer tokens Transfer(self::transfer::TransferAction), #[strum_discriminants(strum( message = "function-call - Execute function (contract method)" ))] /// Specify data to call the function FunctionCall(self::call_function::FunctionCallAction), #[strum_discriminants(strum(message = "stake - Stake NEAR Tokens"))] /// Specify data to stake NEAR Tokens Stake(self::stake::StakeAction), #[strum_discriminants(strum(message = "create-account - Create a new sub-account"))] /// Specify data to create a sub-account CreateAccount(self::create_account::CreateAccountAction), #[strum_discriminants(strum(message = "delete-account - Delete an account"))] /// Specify data to delete an account DeleteAccount(self::delete_account::DeleteAccountAction), #[strum_discriminants(strum( message = "add-key - Add an access key to an account" ))] /// Specify the data to add an access key to the account AddKey(self::add_key::AddKeyAction), #[strum_discriminants(strum( message = "delete-key - Delete an access key from an account" ))] /// Specify the data to delete the access key to the account DeleteKey(self::delete_key::DeleteKeyAction), #[strum_discriminants(strum(message = "deploy - Add a new contract code"))] /// Specify the details to deploy the contract code DeployContract(self::deploy_contract::DeployContractAction), #[strum_discriminants(strum( message = "deploy-global-contract - Add a new global contract code" ))] /// Specify the details to deploy the global contract code DeployGlobalContract(self::deploy_global_contract::DeployGlobalContractAction), #[strum_discriminants(strum( message = "use-global-contract - Use a global contract to re-use the pre-deployed on-chain code" ))] /// Specify the details to use the global contract UseGlobalContract(self::use_global_contract::UseGlobalContractAction), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/transfer/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/transfer/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = TransferActionContext)] pub struct TransferAction { /// How many NEAR Tokens do you want to transfer? (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear) pub amount_in_near: crate::types::near_token::NearToken, #[interactive_clap(subcommand)] pub next_action: super::super::super::add_action_2::NextAction, } #[derive(Debug, Clone)] pub struct TransferActionContext(super::super::super::ConstructTransactionContext); impl TransferActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<TransferAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::Transfer( near_primitives::transaction::TransferAction { deposit: scope.amount_in_near.into(), }, ); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<TransferActionContext> for super::super::super::ConstructTransactionContext { fn from(item: TransferActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/delete_key/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/delete_key/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = DeleteKeyActionContext)] pub struct DeleteKeyAction { /// Enter the public key You wish to delete: public_key: crate::types::public_key::PublicKey, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_2::NextAction, } #[derive(Debug, Clone)] pub struct DeleteKeyActionContext(super::super::super::ConstructTransactionContext); impl DeleteKeyActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<DeleteKeyAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::DeleteKey(Box::new( near_primitives::transaction::DeleteKeyAction { public_key: scope.public_key.clone().into(), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<DeleteKeyActionContext> for super::super::super::ConstructTransactionContext { fn from(item: DeleteKeyActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/create_account/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/create_account/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = CreateAccountActionContext)] pub struct CreateAccountAction { #[interactive_clap(subcommand)] next_action: super::super::super::add_action_2::NextAction, } #[derive(Debug, Clone)] pub struct CreateAccountActionContext(super::super::super::ConstructTransactionContext); impl CreateAccountActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, _scope: &<CreateAccountAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::CreateAccount( near_primitives::transaction::CreateAccountAction {}, ); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<CreateAccountActionContext> for super::super::super::ConstructTransactionContext { fn from(item: CreateAccountActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/deploy_contract/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/deploy_contract/mod.rs
use color_eyre::eyre::Context; pub mod initialize_mode; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] pub struct DeployContractAction { #[interactive_clap(named_arg)] /// Specify a path to wasm file use_file: ContractFile, } #[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = ContractFileContext)] pub struct ContractFile { /// What is the file location of the contract? pub file_path: crate::types::path_buf::PathBuf, #[interactive_clap(subcommand)] initialize: self::initialize_mode::InitializeMode, } #[derive(Debug, Clone)] pub struct ContractFileContext(super::super::super::ConstructTransactionContext); impl ContractFileContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<ContractFile as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let code = std::fs::read(&scope.file_path).wrap_err_with(|| { format!("Failed to open or read the file: {:?}.", &scope.file_path.0,) })?; let action = near_primitives::transaction::Action::DeployContract( near_primitives::transaction::DeployContractAction { code }, ); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<ContractFileContext> for super::super::super::ConstructTransactionContext { fn from(item: ContractFileContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/deploy_contract/initialize_mode/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/deploy_contract/initialize_mode/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, EnumDiscriminants, interactive_clap_derive::InteractiveClap)] #[interactive_clap(context = super::super::super::super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select the need for initialization: pub enum InitializeMode { /// Add an initialize #[strum_discriminants(strum(message = "with-init-call - Add an initialize"))] WithInitCall(super::super::call_function::FunctionCallAction), /// Don't add an initialize #[strum_discriminants(strum(message = "without-init-call - Don't add an initialize"))] WithoutInitCall(NoInitialize), } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::super::ConstructTransactionContext)] pub struct NoInitialize { #[interactive_clap(subcommand)] next_action: super::super::super::super::add_action_2::NextAction, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/delete_account/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/delete_account/mod.rs
use color_eyre::owo_colors::OwoColorize; use inquire::Select; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = DeleteAccountActionContext)] pub struct DeleteAccountAction { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] /// Enter the beneficiary ID to delete this account ID: beneficiary_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_2::NextAction, } #[derive(Debug, Clone)] pub struct DeleteAccountActionContext(super::super::super::ConstructTransactionContext); impl DeleteAccountActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<DeleteAccountAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let beneficiary_id: near_primitives::types::AccountId = scope.beneficiary_id.clone().into(); let action = near_primitives::transaction::Action::DeleteAccount( near_primitives::transaction::DeleteAccountAction { beneficiary_id }, ); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<DeleteAccountActionContext> for super::super::super::ConstructTransactionContext { fn from(item: DeleteAccountActionContext) -> Self { item.0 } } impl DeleteAccountAction { pub fn input_beneficiary_id( context: &super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { loop { let beneficiary_account_id = if let Some(account_id) = crate::common::input_non_signer_account_id_from_used_account_list( &context.global_context.config.credentials_home_dir, "What is the beneficiary account ID?", )? { account_id } else { return Ok(None); }; if beneficiary_account_id.0 == context.signer_account_id { eprintln!("{}", "You have selected a beneficiary account ID that will now be deleted. This will result in the loss of your funds. So make your choice again.".red()); continue; } if context.global_context.offline { return Ok(Some(beneficiary_account_id)); } #[derive(derive_more::Display)] enum ConfirmOptions { #[display("Yes, I want to check if account <{account_id}> exists. (It is free of charge, and only requires Internet access)")] Yes { account_id: crate::types::account_id::AccountId, }, #[display("No, I know this account exists and want to continue.")] No, } let select_choose_input = Select::new("\nDo you want to check the existence of the specified account so that you don't lose tokens?", vec![ConfirmOptions::Yes{account_id: beneficiary_account_id.clone()}, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes { account_id } = select_choose_input { if crate::common::find_network_where_account_exist( &context.global_context, account_id.clone().into(), )? .is_none() { eprintln!( "\nHeads up! You will lose remaining NEAR tokens on the account you delete if you specify the account <{}> as the beneficiary as it does not exist on [{}] networks.", account_id, context.global_context.config.network_names().join(", ") ); if !crate::common::ask_if_different_account_id_wanted()? { return Ok(Some(account_id)); } } else { return Ok(Some(account_id)); }; } else { return Ok(Some(beneficiary_account_id)); }; } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/add_key/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/add_key/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; pub mod access_key_type; pub mod use_manually_provided_seed_phrase; pub mod use_public_key; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] pub struct AddKeyAction { #[interactive_clap(subcommand)] permission: AccessKeyPermission, } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select a permission that you want to add to the access key: pub enum AccessKeyPermission { #[strum_discriminants(strum( message = "grant-full-access - A permission with full access" ))] /// Provide data for a full access key GrantFullAccess(self::access_key_type::FullAccessType), #[strum_discriminants(strum( message = "grant-function-call-access - A permission with function call" ))] /// Provide data for a function-call access key GrantFunctionCallAccess(self::access_key_type::FunctionCallType), } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = self::access_key_type::AccessKeyPermissionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Add an access key for this account: pub enum AccessKeyMode { #[strum_discriminants(strum( message = "use-manually-provided-seed-prase - Use the provided seed phrase manually" ))] /// Use the provided seed phrase manually UseManuallyProvidedSeedPhrase( self::use_manually_provided_seed_phrase::AddAccessWithSeedPhraseAction, ), #[strum_discriminants(strum( message = "use-manually-provided-public-key - Use the provided public key manually" ))] /// Use the provided public key manually UseManuallyProvidedPublicKey(self::use_public_key::AddAccessKeyAction), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/add_key/access_key_type/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/add_key/access_key_type/mod.rs
use std::str::FromStr; use inquire::{CustomType, Select, Text}; #[derive(Debug, Clone)] pub struct AccessKeyPermissionContext { pub global_context: crate::GlobalContext, pub signer_account_id: near_primitives::types::AccountId, pub receiver_account_id: near_primitives::types::AccountId, pub actions: Vec<near_primitives::transaction::Action>, pub access_key_permission: near_primitives::account::AccessKeyPermission, } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = FullAccessTypeContext)] pub struct FullAccessType { #[interactive_clap(subcommand)] access_key_mode: super::AccessKeyMode, } #[derive(Debug, Clone)] pub struct FullAccessTypeContext(AccessKeyPermissionContext); impl FullAccessTypeContext { pub fn from_previous_context( previous_context: super::super::super::super::ConstructTransactionContext, _scope: &<FullAccessType as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(AccessKeyPermissionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions: previous_context.actions, access_key_permission: near_primitives::account::AccessKeyPermission::FullAccess, })) } } impl From<FullAccessTypeContext> for AccessKeyPermissionContext { fn from(item: FullAccessTypeContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = FunctionCallTypeContext)] pub struct FunctionCallType { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] allowance: crate::types::near_allowance::NearAllowance, #[interactive_clap(long)] /// Enter the contract account ID that this access key can be used to sign call function transactions for: contract_account_id: crate::types::account_id::AccountId, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] function_names: crate::types::vec_string::VecString, #[interactive_clap(subcommand)] access_key_mode: super::AccessKeyMode, } #[derive(Debug, Clone)] pub struct FunctionCallTypeContext(AccessKeyPermissionContext); impl FunctionCallTypeContext { pub fn from_previous_context( previous_context: super::super::super::super::ConstructTransactionContext, scope: &<FunctionCallType as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let access_key_permission = near_primitives::account::AccessKeyPermission::FunctionCall( near_primitives::account::FunctionCallPermission { allowance: scope.allowance.optional_near_token().map(Into::into), receiver_id: scope.contract_account_id.to_string(), method_names: scope.function_names.clone().into(), }, ); Ok(Self(AccessKeyPermissionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions: previous_context.actions, access_key_permission, })) } } impl From<FunctionCallTypeContext> for AccessKeyPermissionContext { fn from(item: FunctionCallTypeContext) -> Self { item.0 } } impl FunctionCallType { pub fn input_function_names( _context: &super::super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::vec_string::VecString>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum( to_string = "Yes, I want to input a list of function names that can be called when transaction is signed by this access key" )] Yes, #[strum(to_string = "No, I allow it to call any functions on the specified contract")] No, } let select_choose_input = Select::new( "Would you like the access key to be valid exclusively for calling specific functions on the contract?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { let mut input_function_names = Text::new("Enter a comma-separated list of function names that will be allowed to be called in a transaction signed by this access key:") .prompt()?; if input_function_names.contains('\"') { input_function_names.clear() }; if input_function_names.is_empty() { Ok(Some(crate::types::vec_string::VecString(vec![]))) } else { Ok(Some(crate::types::vec_string::VecString::from_str( &input_function_names, )?)) } } else { Ok(Some(crate::types::vec_string::VecString(vec![]))) } } pub fn input_allowance( _context: &super::super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::near_allowance::NearAllowance>> { let allowance_near_balance: crate::types::near_allowance::NearAllowance = CustomType::new("Enter the allowance, a budget this access key can use to pay for transaction fees (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear):") .with_starting_input("unlimited") .prompt()?; Ok(Some(allowance_near_balance)) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/add_key/use_manually_provided_seed_phrase/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/add_key/use_manually_provided_seed_phrase/mod.rs
use std::str::FromStr; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::access_key_type::AccessKeyPermissionContext)] #[interactive_clap(output_context = AddAccessWithSeedPhraseActionContext)] pub struct AddAccessWithSeedPhraseAction { /// Enter the seed_phrase: master_seed_phrase: String, #[interactive_clap(subcommand)] next_action: super::super::super::super::add_action_2::NextAction, } #[derive(Debug, Clone)] pub struct AddAccessWithSeedPhraseActionContext( super::super::super::super::ConstructTransactionContext, ); impl AddAccessWithSeedPhraseActionContext { pub fn from_previous_context( previous_context: super::access_key_type::AccessKeyPermissionContext, scope: &<AddAccessWithSeedPhraseAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let seed_phrase_hd_path_default = slipped10::BIP32Path::from_str("m/44'/397'/0'").unwrap(); let public_key = crate::common::get_public_key_from_seed_phrase( seed_phrase_hd_path_default, &scope.master_seed_phrase, )?; let access_key = near_primitives::account::AccessKey { nonce: 0, permission: previous_context.access_key_permission, }; let action = near_primitives::transaction::Action::AddKey(Box::new( near_primitives::transaction::AddKeyAction { public_key, access_key, }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self( super::super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, }, )) } } impl From<AddAccessWithSeedPhraseActionContext> for super::super::super::super::ConstructTransactionContext { fn from(item: AddAccessWithSeedPhraseActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/add_key/use_public_key/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/add_key/use_public_key/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::access_key_type::AccessKeyPermissionContext)] #[interactive_clap(output_context = AddAccessKeyActionContext)] pub struct AddAccessKeyAction { /// Enter the public key: public_key: crate::types::public_key::PublicKey, #[interactive_clap(subcommand)] next_action: super::super::super::super::add_action_2::NextAction, } #[derive(Debug, Clone)] pub struct AddAccessKeyActionContext(super::super::super::super::ConstructTransactionContext); impl AddAccessKeyActionContext { pub fn from_previous_context( previous_context: super::access_key_type::AccessKeyPermissionContext, scope: &<AddAccessKeyAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let access_key = near_primitives::account::AccessKey { nonce: 0, permission: previous_context.access_key_permission, }; let action = near_primitives::transaction::Action::AddKey(Box::new( near_primitives::transaction::AddKeyAction { public_key: scope.public_key.clone().into(), access_key, }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self( super::super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, }, )) } } impl From<AddAccessKeyActionContext> for super::super::super::super::ConstructTransactionContext { fn from(item: AddAccessKeyActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/stake/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/stake/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = StakeActionContext)] pub struct StakeAction { /// Enter the amount to stake: (example: 10000NEAR) stake_amount: crate::types::near_token::NearToken, /// Enter the public key of the validator key pair used on your NEAR node (see validator_key.json): public_key: crate::types::public_key::PublicKey, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_2::NextAction, } #[derive(Debug, Clone)] pub struct StakeActionContext(super::super::super::ConstructTransactionContext); impl StakeActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<StakeAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::Stake(Box::new( near_primitives::transaction::StakeAction { stake: scope.stake_amount.into(), public_key: scope.public_key.clone().into(), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<StakeActionContext> for super::super::super::ConstructTransactionContext { fn from(item: StakeActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/deploy_global_contract/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/deploy_global_contract/mod.rs
use color_eyre::eyre::Context; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = DeployGlobalContractActionContext)] pub struct DeployGlobalContractAction { /// What is the file location of the contract? pub file_path: crate::types::path_buf::PathBuf, #[interactive_clap(subcommand)] mode: DeployGlobalMode, } #[derive(Debug, Clone)] pub struct DeployGlobalContractActionContext { pub context: super::super::super::ConstructTransactionContext, pub code: Vec<u8>, } impl DeployGlobalContractActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<DeployGlobalContractAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let code = std::fs::read(&scope.file_path).wrap_err_with(|| { format!("Failed to open or read the file: {:?}.", &scope.file_path.0,) })?; Ok(Self { context: previous_context, code, }) } } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = DeployGlobalContractActionContext)] #[interactive_clap(output_context = DeployGlobalModeContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] #[non_exhaustive] /// Choose a global contract deploy mode: pub enum DeployGlobalMode { #[strum_discriminants(strum( message = "as-global-hash - Deploy code as a global contract code hash (immutable)" ))] /// Deploy code as a global contract code hash (immutable) AsGlobalHash(NextCommand), #[strum_discriminants(strum( message = "as-global-account-id - Deploy code as a global contract account ID (mutable)" ))] /// Deploy code as a global contract account ID (mutable) AsGlobalAccountId(NextCommand), } #[derive(Debug, Clone)] pub struct DeployGlobalModeContext(super::super::super::ConstructTransactionContext); impl DeployGlobalModeContext { pub fn from_previous_context( previous_context: DeployGlobalContractActionContext, scope: &<DeployGlobalMode as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::DeployGlobalContract( near_primitives::action::DeployGlobalContractAction { code: previous_context.code.into(), deploy_mode: match scope { DeployGlobalModeDiscriminants::AsGlobalHash => { near_primitives::action::GlobalContractDeployMode::CodeHash } DeployGlobalModeDiscriminants::AsGlobalAccountId => { near_primitives::action::GlobalContractDeployMode::AccountId } }, }, ); let mut actions = previous_context.context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.context.global_context, signer_account_id: previous_context.context.signer_account_id, receiver_account_id: previous_context.context.receiver_account_id, actions, })) } } impl From<DeployGlobalModeContext> for super::super::super::ConstructTransactionContext { fn from(item: DeployGlobalModeContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = DeployGlobalModeContext)] pub struct NextCommand { #[interactive_clap(subcommand)] next_action: super::super::super::add_action_2::NextAction, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/use_global_contract/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/use_global_contract/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] pub struct UseGlobalContractAction { #[interactive_clap(subcommand)] mode: UseGlobalActionMode, } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] #[non_exhaustive] /// Choose a global contract deploy mode: pub enum UseGlobalActionMode { #[strum_discriminants(strum( message = "use-global-hash - Use a global contract code hash pre-deployed on-chain (immutable)" ))] /// Use a global contract code hash (immutable) UseGlobalHash(UseHashAction), #[strum_discriminants(strum( message = "use-global-account-id - Use a global contract account ID pre-deployed on-chain (mutable)" ))] /// Use a global contract account ID (mutable) UseGlobalAccountId(UseAccountIdAction), } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = UseHashActionContext)] pub struct UseHashAction { /// What is the hash of the global contract? pub hash: crate::types::crypto_hash::CryptoHash, #[interactive_clap(subcommand)] initialize: super::deploy_contract::initialize_mode::InitializeMode, } #[derive(Debug, Clone)] pub struct UseHashActionContext(super::super::super::ConstructTransactionContext); impl UseHashActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<UseHashAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::UseGlobalContract(Box::new( near_primitives::action::UseGlobalContractAction { contract_identifier: near_primitives::action::GlobalContractIdentifier::CodeHash( scope.hash.into(), ), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<UseHashActionContext> for super::super::super::ConstructTransactionContext { fn from(item: UseHashActionContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = UseAccountIdActionContext)] pub struct UseAccountIdAction { #[interactive_clap(skip_default_input_arg)] /// What is the account ID of the global contract? pub account_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] initialize: super::deploy_contract::initialize_mode::InitializeMode, } impl UseAccountIdAction { pub fn input_account_id( context: &super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_non_signer_account_id_from_used_account_list( &context.global_context.config.credentials_home_dir, "What is the account ID of the global contract?", ) } } #[derive(Debug, Clone)] pub struct UseAccountIdActionContext(super::super::super::ConstructTransactionContext); impl UseAccountIdActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<UseAccountIdAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::UseGlobalContract(Box::new( near_primitives::action::UseGlobalContractAction { contract_identifier: near_primitives::action::GlobalContractIdentifier::AccountId( scope.account_id.clone().into(), ), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<UseAccountIdActionContext> for super::super::super::ConstructTransactionContext { fn from(item: UseAccountIdActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_1/add_action/call_function/mod.rs
src/commands/transaction/construct_transaction/add_action_1/add_action/call_function/mod.rs
use inquire::CustomType; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = FunctionCallActionContext)] pub struct FunctionCallAction { #[interactive_clap(skip_default_input_arg)] /// What is the name of the function? function_name: String, #[interactive_clap(value_enum)] #[interactive_clap(skip_default_input_arg)] /// How do you want to pass the function call arguments? function_args_type: crate::commands::contract::call_function::call_function_args_type::FunctionArgsType, /// Enter the arguments to this function: function_args: String, #[interactive_clap(named_arg)] /// Enter gas for function call prepaid_gas: PrepaidGas, } #[derive(Debug, Clone)] pub struct FunctionCallActionContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, receiver_account_id: near_primitives::types::AccountId, actions: Vec<near_primitives::transaction::Action>, function_name: String, function_args: Vec<u8>, } impl FunctionCallActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<FunctionCallAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let function_args = crate::commands::contract::call_function::call_function_args_type::function_args( scope.function_args.clone(), scope.function_args_type.clone(), )?; Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions: previous_context.actions, function_name: scope.function_name.clone(), function_args, }) } } impl FunctionCallAction { fn input_function_args_type( _context: &super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result< Option<crate::commands::contract::call_function::call_function_args_type::FunctionArgsType>, > { crate::commands::contract::call_function::call_function_args_type::input_function_args_type( ) } fn input_function_name( context: &super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<String>> { crate::commands::contract::call_function::input_call_function_name( &context.global_context, &context.receiver_account_id, ) } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = FunctionCallActionContext)] #[interactive_clap(output_context = PrepaidGasContext)] pub struct PrepaidGas { #[interactive_clap(skip_default_input_arg)] /// Enter gas for function call: gas: crate::common::NearGas, #[interactive_clap(named_arg)] /// Enter deposit for a function call attached_deposit: Deposit, } #[derive(Debug, Clone)] pub struct PrepaidGasContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, receiver_account_id: near_primitives::types::AccountId, actions: Vec<near_primitives::transaction::Action>, function_name: String, function_args: Vec<u8>, gas: crate::common::NearGas, } impl PrepaidGasContext { pub fn from_previous_context( previous_context: FunctionCallActionContext, scope: &<PrepaidGas as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions: previous_context.actions, function_name: previous_context.function_name, function_args: previous_context.function_args, gas: scope.gas, }) } } impl PrepaidGas { fn input_gas( _context: &FunctionCallActionContext, ) -> color_eyre::eyre::Result<Option<crate::common::NearGas>> { Ok(Some( CustomType::new("Enter gas for function call:") .with_starting_input("100 TeraGas") .with_validator(move |gas: &crate::common::NearGas| { if gas > &near_gas::NearGas::from_tgas(300) { Ok(inquire::validator::Validation::Invalid( inquire::validator::ErrorMessage::Custom( "You need to enter a value of no more than 300 TeraGas".to_string(), ), )) } else { Ok(inquire::validator::Validation::Valid) } }) .prompt()?, )) } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = PrepaidGasContext)] #[interactive_clap(output_context = DepositContext)] pub struct Deposit { #[interactive_clap(skip_default_input_arg)] /// Enter deposit for a function call: deposit: crate::types::near_token::NearToken, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_2::NextAction, } #[derive(Debug, Clone)] pub struct DepositContext(super::super::super::ConstructTransactionContext); impl DepositContext { pub fn from_previous_context( previous_context: PrepaidGasContext, scope: &<Deposit as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::FunctionCall(Box::new( near_primitives::transaction::FunctionCallAction { method_name: previous_context.function_name, args: previous_context.function_args, gas: near_primitives::gas::Gas::from_gas(previous_context.gas.as_gas()), deposit: scope.deposit.into(), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<DepositContext> for super::super::super::ConstructTransactionContext { fn from(item: DepositContext) -> Self { item.0 } } impl Deposit { fn input_deposit( _context: &PrepaidGasContext, ) -> color_eyre::eyre::Result<Option<crate::types::near_token::NearToken>> { Ok(Some( CustomType::new("Enter deposit for a function call (example: 10 NEAR or 0.5 near or 10000 yoctonear):") .with_starting_input("0 NEAR") .prompt()? )) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_last/mod.rs
src/commands/transaction/construct_transaction/add_action_last/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select an action that you want to add to the action: pub enum NextAction { #[strum_discriminants(strum(message = "skip - Skip adding a new action"))] /// Go to transaction signing Skip(super::skip_action::SkipAction), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/skip_action/mod.rs
src/commands/transaction/construct_transaction/skip_action/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::ConstructTransactionContext)] #[interactive_clap(output_context = SkipActionContext)] pub struct SkipAction { #[interactive_clap(named_arg)] /// Select network pub network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Debug, Clone)] pub struct SkipActionContext(super::ConstructTransactionContext); impl SkipActionContext { pub fn from_previous_context( previous_context: super::ConstructTransactionContext, _scope: &<SkipAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(previous_context)) } } impl From<SkipActionContext> for crate::commands::ActionContext { fn from(item: SkipActionContext) -> Self { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_account_id = item.0.signer_account_id.clone(); let receiver_account_id = item.0.receiver_account_id.clone(); move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_account_id.clone(), receiver_id: receiver_account_id.clone(), actions: item.0.actions.clone(), }) } }); Self { global_context: item.0.global_context, interacting_with_account_ids: vec![ item.0.signer_account_id, item.0.receiver_account_id, ], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback: std::sync::Arc::new( |_outcome_view, _network_config| Ok(()), ), } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/print_transaction/mod.rs
src/commands/transaction/print_transaction/mod.rs
#![allow(clippy::enum_variant_names, clippy::large_enum_variant)] use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod signed; mod unsigned; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] pub struct PrintTransactionCommands { #[interactive_clap(subcommand)] show_transaction_actions: PrintTransactionActions, } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select signed or unsigned transaction to print: pub enum PrintTransactionActions { #[strum_discriminants(strum( message = "unsigned - Print all fields of previously prepared unsigned transaction without modification" ))] /// Print previously prepared unsigned transaction without modification Unsigned(self::unsigned::PrintTransaction), #[strum_discriminants(strum( message = "signed - Print all fields of previously prepared signed transaction without modification" ))] /// Send a signed transaction Signed(self::signed::PrintTransaction), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/print_transaction/signed/mod.rs
src/commands/transaction/print_transaction/signed/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = PrintContext)] pub struct PrintTransaction { /// Enter the signed transaction encoded in base64: signed_transaction: crate::types::signed_transaction::SignedTransactionAsBase64, } #[derive(Debug, Clone)] pub struct PrintContext; impl PrintContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<PrintTransaction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let signed_transaction: near_primitives::transaction::SignedTransaction = scope.signed_transaction.clone().into(); let info_str = crate::common::print_full_signed_transaction(signed_transaction); if let crate::Verbosity::Quiet = previous_context.verbosity { println!("Signed transaction (full):{info_str}") }; tracing::info!( parent: &tracing::Span::none(), "Signed transaction (full):{}", crate::common::indent_payload(&info_str) ); Ok(Self) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/print_transaction/unsigned/mod.rs
src/commands/transaction/print_transaction/unsigned/mod.rs
use near_primitives::transaction::Transaction; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = PrintContext)] pub struct PrintTransaction { /// Enter the unsigned transaction encoded in base64: unsigned_transaction: crate::types::transaction::TransactionAsBase64, } #[derive(Debug, Clone)] pub struct PrintContext; impl PrintContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<PrintTransaction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let unsigned_transaction: near_primitives::transaction::TransactionV0 = scope.unsigned_transaction.clone().into(); let info_str = crate::common::print_full_unsigned_transaction(Transaction::V0(unsigned_transaction)); if let crate::Verbosity::Quiet = previous_context.verbosity { println!("Unsigned transaction (full):{info_str}"); } tracing::info!( parent: &tracing::Span::none(), "Unsigned transaction (full):{}", crate::common::indent_payload(&info_str) ); Ok(Self) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/sign_transaction/mod.rs
src/commands/transaction/sign_transaction/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = SignTransactionContext)] pub struct SignTransaction { /// Enter the transaction encoded in base64: unsigned_transaction: crate::types::transaction::TransactionAsBase64, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Clone)] pub struct SignTransactionContext(crate::commands::ActionContext); impl SignTransactionContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<SignTransaction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let unsigned_transaction: near_primitives::transaction::TransactionV0 = scope.unsigned_transaction.clone().into(); move |_network_config| { Ok(crate::commands::PrepopulatedTransaction::from( unsigned_transaction.clone(), )) } }); Ok(Self(crate::commands::ActionContext { global_context: previous_context, interacting_with_account_ids: vec![ scope.unsigned_transaction.inner.signer_id.clone(), scope.unsigned_transaction.inner.receiver_id.clone(), ], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback: std::sync::Arc::new( |_outcome_view, _network_config| Ok(()), ), })) } } impl From<SignTransactionContext> for crate::commands::ActionContext { fn from(item: SignTransactionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/view_status/mod.rs
src/commands/transaction/view_status/mod.rs
use color_eyre::eyre::Context; use tracing_indicatif::span_ext::IndicatifSpanExt; use crate::common::JsonRpcClientExt; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = TransactionInfoContext)] pub struct TransactionInfo { /// Enter the hash of the transaction you need to view: transaction_hash: crate::types::crypto_hash::CryptoHash, #[interactive_clap(named_arg)] /// Select network network_config: crate::network::Network, } #[derive(Clone)] pub struct TransactionInfoContext(crate::network::NetworkContext); impl TransactionInfoContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<TransactionInfo as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback = std::sync::Arc::new({ let tx_hash: near_primitives::hash::CryptoHash = scope.transaction_hash.into(); move |network_config| { let query_view_transaction_status = get_transaction_info(network_config, tx_hash)?; if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = previous_context.verbosity { eprintln!("Transaction status:"); println!("{query_view_transaction_status:#?}"); } else { println!("{query_view_transaction_status:?}"); } Ok(()) } }); Ok(Self(crate::network::NetworkContext { config: previous_context.config, interacting_with_account_ids: vec![], on_after_getting_network_callback, })) } } impl From<TransactionInfoContext> for crate::network::NetworkContext { fn from(item: TransactionInfoContext) -> Self { item.0 } } #[tracing::instrument(name = "Getting information about transaction", skip_all)] pub fn get_transaction_info( network_config: &crate::config::NetworkConfig, tx_hash: near_primitives::hash::CryptoHash, ) -> color_eyre::eyre::Result<near_jsonrpc_client::methods::tx::RpcTransactionResponse> { tracing::Span::current().pb_set_message(&format!("{tx_hash} ...")); tracing::info!(target: "near_teach_me", "Getting information about transaction {tx_hash} ..."); network_config .json_rpc_client() .blocking_call( near_jsonrpc_client::methods::tx::RpcTransactionStatusRequest { transaction_info: near_jsonrpc_client::methods::tx::TransactionInfo::TransactionId { tx_hash, sender_account_id: "near".parse::<near_primitives::types::AccountId>()?, }, wait_until: near_primitives::views::TxExecutionStatus::Final, }, ) .wrap_err_with(|| { format!( "Failed to fetch query for view transaction on network <{}>", network_config.network_name ) }) }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/reconstruct_transaction/mod.rs
src/commands/transaction/reconstruct_transaction/mod.rs
use color_eyre::eyre::{Context, ContextCompat}; use inquire::CustomType; use interactive_clap::ToCliArgs; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = TransactionInfoContext)] pub struct TransactionInfo { /// Enter the hash of the transaction you want to use as a template: transaction_hash: crate::types::crypto_hash::CryptoHash, #[interactive_clap(named_arg)] /// Select network network_config: crate::network::Network, } #[derive(Clone)] pub struct TransactionInfoContext(crate::network::NetworkContext); impl TransactionInfoContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<TransactionInfo as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { use super::construct_transaction::{add_action_1, skip_action, CliConstructTransaction}; use super::{CliTransactionActions, CliTransactionCommands}; let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback = std::sync::Arc::new({ let tx_hash: near_primitives::hash::CryptoHash = scope.transaction_hash.into(); move |network_config: &crate::config::NetworkConfig| { let query_view_transaction_status = super::view_status::get_transaction_info(network_config, tx_hash)? .final_execution_outcome .wrap_err_with(|| { format!( "Failed to get the final execution outcome for the transaction {tx_hash}" ) })? .into_outcome(); let mut prepopulated_transaction = crate::commands::PrepopulatedTransaction { signer_id: query_view_transaction_status.transaction.signer_id, receiver_id: query_view_transaction_status.transaction.receiver_id, actions: query_view_transaction_status .transaction .actions .into_iter() .map(near_primitives::transaction::Action::try_from) .collect::<Result<Vec<near_primitives::transaction::Action>, _>>() .expect("Internal error: can not convert the action_view to action."), }; tracing::info!( parent: &tracing::Span::none(), "Transaction {}:{}", query_view_transaction_status.transaction.hash, crate::common::indent_payload(&crate::common::print_unsigned_transaction( &prepopulated_transaction, )) ); if prepopulated_transaction.actions.len() == 1 { if let near_primitives::transaction::Action::Delegate( signed_delegate_action, ) = &prepopulated_transaction.actions[0] { prepopulated_transaction = crate::commands::PrepopulatedTransaction { signer_id: signed_delegate_action.delegate_action.sender_id.clone(), receiver_id: signed_delegate_action .delegate_action .receiver_id .clone(), actions: signed_delegate_action.delegate_action.get_actions(), }; } } let cmd = crate::commands::CliTopLevelCommand::Transaction(CliTransactionCommands { transaction_actions: Some(CliTransactionActions::ConstructTransaction( CliConstructTransaction { sender_account_id: Some( prepopulated_transaction.signer_id.into(), ), receiver_account_id: Some( prepopulated_transaction.receiver_id.clone().into(), ), next_actions: None, }, )), }); let mut cmd_cli_args = cmd.to_cli_args(); for transaction_action in prepopulated_transaction.actions { let next_actions = add_action_1::CliNextAction::AddAction( add_action_1::add_action::CliAddAction { action: action_transformation( transaction_action, prepopulated_transaction.receiver_id.clone(), network_config, near_primitives::types::BlockReference::BlockId( near_primitives::types::BlockId::Hash( query_view_transaction_status .transaction_outcome .block_hash, ), ), )?, }, ); cmd_cli_args.extend(next_actions.to_cli_args()); } let skip_action = add_action_1::CliNextAction::Skip(skip_action::CliSkipAction { network_config: Some( skip_action::ClapNamedArgNetworkForTransactionArgsForSkipAction::NetworkConfig( crate::network_for_transaction::CliNetworkForTransactionArgs { network_name: Some(network_config.network_name.clone()), transaction_signature_options: None, }, ), ), }); cmd_cli_args.extend(skip_action.to_cli_args()); let near_cli_exec_path = crate::common::get_near_exec_path(); if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = previous_context.verbosity { eprintln!("Here is your console command to run archive transaction. You can to edit it or re-run (printed to stdout):") } println!( "{}", shell_words::join(std::iter::once(near_cli_exec_path).chain(cmd_cli_args)) ); Ok(()) } }); Ok(Self(crate::network::NetworkContext { config: previous_context.config, interacting_with_account_ids: vec![], on_after_getting_network_callback, })) } } impl From<TransactionInfoContext> for crate::network::NetworkContext { fn from(item: TransactionInfoContext) -> Self { item.0 } } fn action_transformation( archival_action: near_primitives::transaction::Action, receiver_id: near_primitives::types::AccountId, network_config: &crate::config::NetworkConfig, block_reference: near_primitives::types::BlockReference, ) -> color_eyre::eyre::Result< Option<super::construct_transaction::add_action_1::add_action::CliActionSubcommand>, > { use near_primitives::transaction::Action; use super::construct_transaction::add_action_1::add_action; match archival_action { Action::CreateAccount(_) => { Ok(Some(add_action::CliActionSubcommand::CreateAccount( add_action::create_account::CliCreateAccountAction { next_action: None } ))) } Action::DeleteAccount(delete_account_action) => { Ok(Some(add_action::CliActionSubcommand::DeleteAccount( add_action::delete_account::CliDeleteAccountAction { beneficiary_id: Some(delete_account_action.beneficiary_id.into()), next_action: None } ))) } Action::AddKey(add_key_action) => { Ok(Some(add_action::CliActionSubcommand::AddKey( add_action::add_key::CliAddKeyAction { permission: get_access_key_permission(add_key_action.public_key, add_key_action.access_key.permission)? } ))) } Action::DeleteKey(delete_key_action) => { Ok(Some(add_action::CliActionSubcommand::DeleteKey( add_action::delete_key::CliDeleteKeyAction { public_key: Some(delete_key_action.public_key.into()), next_action: None } ))) } Action::Transfer(transfer_action) => { Ok(Some(add_action::CliActionSubcommand::Transfer( add_action::transfer::CliTransferAction { amount_in_near: Some(transfer_action.deposit.into()), next_action: None } ))) } Action::DeployContract(deploy_contract_action) => { let file_path = CustomType::<crate::types::path_buf::PathBuf>::new("Enter the file path where to save the contract:") .with_starting_input("reconstruct-transaction-deploy-code.wasm") .prompt()?; download_code( &crate::commands::contract::download_wasm::ContractType::Regular(receiver_id), network_config, block_reference, &file_path, &near_primitives::hash::CryptoHash::hash_bytes(&deploy_contract_action.code) )?; Ok(Some(add_action::CliActionSubcommand::DeployContract( add_action::deploy_contract::CliDeployContractAction { use_file: Some(add_action::deploy_contract::ClapNamedArgContractFileForDeployContractAction::UseFile( add_action::deploy_contract::CliContractFile { file_path: Some(file_path), initialize: Some(add_action::deploy_contract::initialize_mode::CliInitializeMode::WithoutInitCall( add_action::deploy_contract::initialize_mode::CliNoInitialize { next_action: None } )) } )), } ))) } Action::FunctionCall(function_call_action) => { Ok(Some(add_action::CliActionSubcommand::FunctionCall( add_action::call_function::CliFunctionCallAction { function_name: Some(function_call_action.method_name), function_args_type: Some(crate::commands::contract::call_function::call_function_args_type::FunctionArgsType::TextArgs), function_args: Some(String::from_utf8(function_call_action.args)?), prepaid_gas: Some(add_action::call_function::ClapNamedArgPrepaidGasForFunctionCallAction::PrepaidGas( add_action::call_function::CliPrepaidGas { gas: Some(near_gas::NearGas::from_gas(function_call_action.gas.as_gas())), attached_deposit: Some(add_action::call_function::ClapNamedArgDepositForPrepaidGas::AttachedDeposit( add_action::call_function::CliDeposit { deposit: Some(function_call_action.deposit.into()), next_action: None } )) } )) } ))) } Action::Stake(stake_action) => { Ok(Some(add_action::CliActionSubcommand::Stake( add_action::stake::CliStakeAction { stake_amount: Some(stake_action.stake.into()), public_key: Some(stake_action.public_key.into()), next_action: None } ))) } Action::Delegate(_) => { panic!("Internal error: Delegate action should have been handled before calling action_transformation."); } Action::DeployGlobalContract(action) => { let file_path = CustomType::<crate::types::path_buf::PathBuf>::new("Enter the file path where to save the contract:") .with_starting_input("reconstruct-transaction-deploy-code.wasm") .prompt()?; let code_hash = near_primitives::hash::CryptoHash::try_from(action.code.as_ref()).map_err(|_| { color_eyre::Report::msg("Internal error: Failed to calculate code hash from the deploy global contract action code.".to_string()) })?; let contract_type = match action.deploy_mode { near_primitives::action::GlobalContractDeployMode::AccountId => { &crate::commands::contract::download_wasm::ContractType::GlobalContractByAccountId { account_id: receiver_id.clone(), code_hash: Some(code_hash) } } near_primitives::action::GlobalContractDeployMode::CodeHash => { &crate::commands::contract::download_wasm::ContractType::GlobalContractByCodeHash(code_hash) } }; download_code( contract_type, network_config, block_reference, &file_path, &code_hash )?; let mode = match action.deploy_mode { near_primitives::action::GlobalContractDeployMode::AccountId => add_action::deploy_global_contract::CliDeployGlobalMode::AsGlobalAccountId( add_action::deploy_global_contract::CliNextCommand { next_action: None } ), near_primitives::action::GlobalContractDeployMode::CodeHash => add_action::deploy_global_contract::CliDeployGlobalMode::AsGlobalHash( add_action::deploy_global_contract::CliNextCommand { next_action: None } ), }; Ok(Some(add_action::CliActionSubcommand::DeployGlobalContract( add_action::deploy_global_contract::CliDeployGlobalContractAction { file_path: Some(file_path), mode: Some(mode) } ))) } Action::UseGlobalContract(use_global_contract_action) => { let mode = match use_global_contract_action.contract_identifier { near_primitives::action::GlobalContractIdentifier::CodeHash(hash) => add_action::use_global_contract::CliUseGlobalActionMode::UseGlobalHash( add_action::use_global_contract::CliUseHashAction { hash: Some(crate::types::crypto_hash::CryptoHash(hash)), initialize: Some(add_action::deploy_contract::initialize_mode::CliInitializeMode::WithoutInitCall( add_action::deploy_contract::initialize_mode::CliNoInitialize { next_action: None } )) } ), near_primitives::action::GlobalContractIdentifier::AccountId(account_id) => add_action::use_global_contract::CliUseGlobalActionMode::UseGlobalAccountId( add_action::use_global_contract::CliUseAccountIdAction { account_id: Some(crate::types::account_id::AccountId(account_id)), initialize: Some(add_action::deploy_contract::initialize_mode::CliInitializeMode::WithoutInitCall( add_action::deploy_contract::initialize_mode::CliNoInitialize { next_action: None } )) } ), }; Ok(Some(add_action::CliActionSubcommand::UseGlobalContract( add_action::use_global_contract::CliUseGlobalContractAction { mode: Some(mode) } ))) } Action::DeterministicStateInit(_deterministic_state_action) => { // TODO: impl Err(color_eyre::eyre::eyre!("Deterministic state init is not yet implemented")) } } } fn get_access_key_permission( public_key: near_crypto::PublicKey, access_key_permission: near_primitives::account::AccessKeyPermission, ) -> color_eyre::eyre::Result< Option<super::construct_transaction::add_action_1::add_action::add_key::CliAccessKeyPermission>, > { use super::construct_transaction::add_action_1::add_action::add_key; match access_key_permission { near_primitives::account::AccessKeyPermission::FullAccess => { Ok(Some(add_key::CliAccessKeyPermission::GrantFullAccess( add_key::access_key_type::CliFullAccessType { access_key_mode: Some(add_key::CliAccessKeyMode::UseManuallyProvidedPublicKey( add_key::use_public_key::CliAddAccessKeyAction { public_key: Some(public_key.into()), next_action: None, }, )), }, ))) } near_primitives::account::AccessKeyPermission::FunctionCall( near_primitives::account::FunctionCallPermission { allowance, receiver_id, method_names, }, ) => Ok(Some( add_key::CliAccessKeyPermission::GrantFunctionCallAccess( add_key::access_key_type::CliFunctionCallType { allowance: { match allowance { Some(allowance) => { Some(crate::types::near_allowance::NearAllowance::from_near( allowance.into(), )) } None => Some(crate::types::near_allowance::NearAllowance::unlimited()), } }, contract_account_id: Some(receiver_id.parse()?), function_names: Some(crate::types::vec_string::VecString(method_names)), access_key_mode: Some(add_key::CliAccessKeyMode::UseManuallyProvidedPublicKey( add_key::use_public_key::CliAddAccessKeyAction { public_key: Some(public_key.into()), next_action: None, }, )), }, ), )), } } fn download_code( contract_type: &crate::commands::contract::download_wasm::ContractType, network_config: &crate::config::NetworkConfig, block_reference: near_primitives::types::BlockReference, file_path: &crate::types::path_buf::PathBuf, hash_to_match: &near_primitives::hash::CryptoHash, ) -> color_eyre::eyre::Result<()> { // Unfortunately, RPC doesn't return the code for the deployed contract. Only the hash. // So we need to fetch it from archive node. let code = crate::commands::contract::download_wasm::get_code( contract_type, network_config, block_reference, ).map_err(|e| { color_eyre::Report::msg(format!("Couldn't fetch the code. Please verify that you are using the archival node in the `network_connection.*.rpc_url` field of the `config.toml` file. You can see the list of RPC providers at https://docs.near.org/api/rpc/providers.\nError: {e}")) })?; let code_hash = near_primitives::hash::CryptoHash::hash_bytes(&code); tracing::info!( parent: &tracing::Span::none(), "The code for <{}> was downloaded successfully with hash <{}>", contract_type, code_hash, ); if &code_hash != hash_to_match { return Err(color_eyre::Report::msg("The code hash of the contract deploy action does not match the code that we retrieved from the archive node.".to_string())); } std::fs::write(file_path, code).wrap_err(format!( "Failed to write the deploy command code to file: '{file_path}' in the current folder" ))?; tracing::info!( parent: &tracing::Span::none(), "The file `{}` with contract code of `{}` was downloaded successfully", file_path, contract_type, ); Ok(()) }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/extensions/mod.rs
src/commands/extensions/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; pub mod self_update; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] pub struct ExtensionsCommands { #[interactive_clap(subcommand)] pub extensions_actions: ExtensionsActions, } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] #[non_exhaustive] /// What do you want to do with a near CLI? pub enum ExtensionsActions { #[strum_discriminants(strum(message = "self-update - Self update near CLI"))] /// Self update near CLI SelfUpdate(self::self_update::SelfUpdateCommand), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/extensions/self_update/mod.rs
src/commands/extensions/self_update/mod.rs
#[cfg(windows)] const BIN_NAME: &str = "near.exe"; #[cfg(not(windows))] const BIN_NAME: &str = "near"; use color_eyre::{eyre::WrapErr, owo_colors::OwoColorize}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = SelfUpdateCommandContext)] pub struct SelfUpdateCommand; #[derive(Debug, Clone)] pub struct SelfUpdateCommandContext; impl SelfUpdateCommandContext { pub fn from_previous_context( _previous_context: crate::GlobalContext, _scope: &<SelfUpdateCommand as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let status = self_update::backends::github::Update::configure() .repo_owner("near") .repo_name("near-cli-rs") .bin_path_in_archive( format!("near-cli-rs-{}/{}", self_update::get_target(), BIN_NAME).as_str(), ) .bin_name(BIN_NAME) .show_download_progress(true) .current_version(self_update::cargo_crate_version!()) .build() .wrap_err("Failed to build self_update")? .update() .wrap_err("Failed to update near CLI")?; if let self_update::Status::Updated(release) = status { println!( "\n{}{}{}\n", "Welcome to `near` CLI v".green().bold(), release.green().bold(), "!".green().bold() ); println!("Report any bugs:\n"); println!("\thttps://github.com/near/near-cli-rs/issues\n"); println!("What's new:\n"); println!( "\t{}{}\n", "https://github.com/near/near-cli-rs/releases/tag/v".truecolor(0, 160, 150), release.truecolor(0, 160, 150) ); } Ok(Self) } } pub fn get_latest_version() -> color_eyre::eyre::Result<String> { Ok(self_update::backends::github::Update::configure() .repo_owner("near") .repo_name("near-cli-rs") .bin_name("near") .current_version(self_update::cargo_crate_version!()) .build() .wrap_err("Failed to build self_update")? .get_latest_release() .wrap_err("Failed to get latest release")? .version) }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/staking/mod.rs
src/commands/staking/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; pub mod delegate; mod validator_list; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] pub struct Staking { #[interactive_clap(subcommand)] stake: StakingType, } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] #[non_exhaustive] /// Select the type of stake: pub enum StakingType { #[strum_discriminants(strum( message = "validator-list - View the list of validators to delegate" ))] /// View the list of validators to delegate ValidatorList(self::validator_list::ValidatorList), #[strum_discriminants(strum(message = "delegation - Delegation management"))] /// Delegation management Delegation(self::delegate::StakeDelegation), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/staking/validator_list/mod.rs
src/commands/staking/validator_list/mod.rs
use prettytable::Table; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = ValidatorListContext)] pub struct ValidatorList { #[interactive_clap(named_arg)] /// Select network network_config: crate::network::Network, } #[derive(Clone)] pub struct ValidatorListContext(crate::network::NetworkContext); impl ValidatorListContext { pub fn from_previous_context( previous_context: crate::GlobalContext, _scope: &<ValidatorList as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback = std::sync::Arc::new(display_validators_info); Ok(Self(crate::network::NetworkContext { config: previous_context.config, interacting_with_account_ids: vec![], on_after_getting_network_callback, })) } } impl From<ValidatorListContext> for crate::network::NetworkContext { fn from(item: ValidatorListContext) -> Self { item.0 } } #[tracing::instrument(name = "View the list of validators for delegation ...", skip_all)] fn display_validators_info(network_config: &crate::config::NetworkConfig) -> crate::CliResult { tracing::info!(target: "near_teach_me", "View the list of validators for delegation ..."); let mut table = Table::new(); table.set_titles(prettytable::row![Fg=>"#", "Validator Id", "Fee", "Delegators", "Stake"]); for (index, validator) in crate::common::get_validator_list(network_config)? .into_iter() .enumerate() { let fee = if let Some(fee) = validator.fee { format!("{:>6.2} %", fee.numerator * 100 / fee.denominator) } else { format!("{:>6}", "N/A") }; let delegators = if let Some(num) = validator.delegators { format!("{num:>8}") } else { format!("{:>8}", "N/A") }; table.add_row(prettytable::row![ Fg->index + 1, validator.validator_id, fee, delegators, validator.stake, ]); } table.set_format(*prettytable::format::consts::FORMAT_NO_LINESEP_WITH_TITLE); table.printstd(); let validators_url: url::Url = network_config.wallet_url.join("staking/validators")?; eprintln!( "This is not a complete list of validators. To see the full list of validators visit Explorer:\n{}\n", &validators_url.as_str() ); Ok(()) }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/staking/delegate/withdraw.rs
src/commands/staking/delegate/withdraw.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::StakeDelegationContext)] #[interactive_clap(output_context = WithdrawContext)] pub struct Withdraw { /// Enter the amount to withdraw from the non staked balance (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear): amount: crate::types::near_token::NearToken, #[interactive_clap(skip_default_input_arg)] /// What is validator account ID? validator_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Clone)] pub struct WithdrawContext(crate::commands::ActionContext); impl WithdrawContext { pub fn from_previous_context( previous_context: super::StakeDelegationContext, scope: &<Withdraw as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_account_id: near_primitives::types::AccountId = scope.validator_account_id.clone().into(); let amount = scope.amount; move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_id.clone(), receiver_id: validator_account_id.clone(), actions: vec![near_primitives::transaction::Action::FunctionCall( Box::new(near_primitives::transaction::FunctionCallAction { method_name: "withdraw".to_string(), args: serde_json::to_vec(&serde_json::json!({ "amount": amount, }))?, gas: near_primitives::gas::Gas::from_teragas(50), deposit: near_token::NearToken::ZERO, }), )], }) } }); let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_id = scope.validator_account_id.clone(); let amount = scope.amount; let verbosity = previous_context.global_context.verbosity; move |outcome_view, _network_config| { if let near_primitives::views::FinalExecutionStatus::SuccessValue(_) = outcome_view.status { if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = verbosity { tracing_indicatif::suspend_tracing_indicatif(|| { eprintln!("<{signer_id}> has successfully withdrawn {amount} from <{validator_id}>."); }) } } Ok(()) } }); Ok(Self(crate::commands::ActionContext { global_context: previous_context.global_context, interacting_with_account_ids: vec![ previous_context.account_id, scope.validator_account_id.clone().into(), ], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback, })) } } impl From<WithdrawContext> for crate::commands::ActionContext { fn from(item: WithdrawContext) -> Self { item.0 } } impl Withdraw { pub fn input_validator_account_id( context: &super::StakeDelegationContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_staking_pool_validator_account_id(&context.global_context.config) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/staking/delegate/unstake_all.rs
src/commands/staking/delegate/unstake_all.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::StakeDelegationContext)] #[interactive_clap(output_context = UnstakeAllContext)] pub struct UnstakeAll { #[interactive_clap(skip_default_input_arg)] /// What is validator account ID? validator_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Clone)] pub struct UnstakeAllContext(crate::commands::ActionContext); impl UnstakeAllContext { pub fn from_previous_context( previous_context: super::StakeDelegationContext, scope: &<UnstakeAll as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_account_id: near_primitives::types::AccountId = scope.validator_account_id.clone().into(); move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_id.clone(), receiver_id: validator_account_id.clone(), actions: vec![near_primitives::transaction::Action::FunctionCall( Box::new(near_primitives::transaction::FunctionCallAction { method_name: "unstake_all".to_string(), args: serde_json::to_vec(&serde_json::json!({}))?, gas: near_primitives::gas::Gas::from_teragas(50), deposit: near_token::NearToken::ZERO, }), )], }) } }); let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_id = scope.validator_account_id.clone(); let verbosity = previous_context.global_context.verbosity; move |outcome_view, _network_config| { if let near_primitives::views::FinalExecutionStatus::SuccessValue(_) = outcome_view.status { if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = verbosity { tracing_indicatif::suspend_tracing_indicatif(|| { eprintln!("<{signer_id}> has successfully unstaked the entire available amount from <{validator_id}>."); }) } } Ok(()) } }); Ok(Self(crate::commands::ActionContext { global_context: previous_context.global_context, interacting_with_account_ids: vec![ previous_context.account_id, scope.validator_account_id.clone().into(), ], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback, })) } } impl From<UnstakeAllContext> for crate::commands::ActionContext { fn from(item: UnstakeAllContext) -> Self { item.0 } } impl UnstakeAll { pub fn input_validator_account_id( context: &super::StakeDelegationContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_staking_pool_validator_account_id(&context.global_context.config) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/staking/delegate/withdraw_all.rs
src/commands/staking/delegate/withdraw_all.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::StakeDelegationContext)] #[interactive_clap(output_context = WithdrawAllContext)] pub struct WithdrawAll { #[interactive_clap(skip_default_input_arg)] /// What is validator account ID? validator_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Clone)] pub struct WithdrawAllContext(crate::commands::ActionContext); impl WithdrawAllContext { pub fn from_previous_context( previous_context: super::StakeDelegationContext, scope: &<WithdrawAll as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_account_id: near_primitives::types::AccountId = scope.validator_account_id.clone().into(); move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_id.clone(), receiver_id: validator_account_id.clone(), actions: vec![near_primitives::transaction::Action::FunctionCall( Box::new(near_primitives::transaction::FunctionCallAction { method_name: "withdraw_all".to_string(), args: serde_json::to_vec(&serde_json::json!({}))?, gas: near_primitives::gas::Gas::from_teragas(50), deposit: near_token::NearToken::ZERO, }), )], }) } }); let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_id = scope.validator_account_id.clone(); let verbosity = previous_context.global_context.verbosity; move |outcome_view, _network_config| { if let near_primitives::views::FinalExecutionStatus::SuccessValue(_) = outcome_view.status { if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = verbosity { tracing_indicatif::suspend_tracing_indicatif(|| { eprintln!("<{signer_id}> has successfully withdrawn the entire available amount from <{validator_id}>."); }) } } Ok(()) } }); Ok(Self(crate::commands::ActionContext { global_context: previous_context.global_context, interacting_with_account_ids: vec![ previous_context.account_id, scope.validator_account_id.clone().into(), ], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback, })) } } impl From<WithdrawAllContext> for crate::commands::ActionContext { fn from(item: WithdrawAllContext) -> Self { item.0 } } impl WithdrawAll { pub fn input_validator_account_id( context: &super::StakeDelegationContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_staking_pool_validator_account_id(&context.global_context.config) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/staking/delegate/unstake.rs
src/commands/staking/delegate/unstake.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::StakeDelegationContext)] #[interactive_clap(output_context = UnstakeContext)] pub struct Unstake { /// Enter the amount to unstake from the inner account of the predecessor (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear): amount: crate::types::near_token::NearToken, #[interactive_clap(skip_default_input_arg)] /// What is validator account ID? validator_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Clone)] pub struct UnstakeContext(crate::commands::ActionContext); impl UnstakeContext { pub fn from_previous_context( previous_context: super::StakeDelegationContext, scope: &<Unstake as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_account_id: near_primitives::types::AccountId = scope.validator_account_id.clone().into(); let amount = scope.amount; move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_id.clone(), receiver_id: validator_account_id.clone(), actions: vec![near_primitives::transaction::Action::FunctionCall( Box::new(near_primitives::transaction::FunctionCallAction { method_name: "unstake".to_string(), args: serde_json::to_vec(&serde_json::json!({ "amount": amount, }))?, gas: near_primitives::gas::Gas::from_teragas(50), deposit: near_token::NearToken::ZERO, }), )], }) } }); let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_id = scope.validator_account_id.clone(); let amount = scope.amount; let verbosity = previous_context.global_context.verbosity; move |outcome_view, _network_config| { if let near_primitives::views::FinalExecutionStatus::SuccessValue(_) = outcome_view.status { if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = verbosity { tracing_indicatif::suspend_tracing_indicatif(|| { eprintln!("<{signer_id}> has successfully unstaked {amount} from <{validator_id}>."); }) } } Ok(()) } }); Ok(Self(crate::commands::ActionContext { global_context: previous_context.global_context, interacting_with_account_ids: vec![ previous_context.account_id, scope.validator_account_id.clone().into(), ], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback, })) } } impl From<UnstakeContext> for crate::commands::ActionContext { fn from(item: UnstakeContext) -> Self { item.0 } } impl Unstake { pub fn input_validator_account_id( context: &super::StakeDelegationContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_staking_pool_validator_account_id(&context.global_context.config) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/staking/delegate/stake.rs
src/commands/staking/delegate/stake.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::StakeDelegationContext)] #[interactive_clap(output_context = StakeContext)] pub struct Stake { /// Enter the amount to stake from the inner account of the predecessor (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear): amount: crate::types::near_token::NearToken, #[interactive_clap(skip_default_input_arg)] /// What is validator account ID? validator_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Clone)] pub struct StakeContext(crate::commands::ActionContext); impl StakeContext { pub fn from_previous_context( previous_context: super::StakeDelegationContext, scope: &<Stake as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_account_id: near_primitives::types::AccountId = scope.validator_account_id.clone().into(); let amount = scope.amount; move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_id.clone(), receiver_id: validator_account_id.clone(), actions: vec![near_primitives::transaction::Action::FunctionCall( Box::new(near_primitives::transaction::FunctionCallAction { method_name: "stake".to_string(), args: serde_json::to_vec(&serde_json::json!({ "amount": amount, }))?, gas: near_primitives::gas::Gas::from_teragas(50), deposit: near_token::NearToken::ZERO, }), )], }) } }); let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_id = scope.validator_account_id.clone(); let amount = scope.amount; let verbosity = previous_context.global_context.verbosity; move |outcome_view, _network_config| { if let near_primitives::views::FinalExecutionStatus::SuccessValue(_) = outcome_view.status { if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = verbosity { tracing_indicatif::suspend_tracing_indicatif(|| { eprintln!("<{signer_id}> has successfully delegated {amount} to stake with <{validator_id}>."); }) } } Ok(()) } }); Ok(Self(crate::commands::ActionContext { global_context: previous_context.global_context, interacting_with_account_ids: vec![ previous_context.account_id, scope.validator_account_id.clone().into(), ], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback, })) } } impl From<StakeContext> for crate::commands::ActionContext { fn from(item: StakeContext) -> Self { item.0 } } impl Stake { pub fn input_validator_account_id( context: &super::StakeDelegationContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_staking_pool_validator_account_id(&context.global_context.config) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/staking/delegate/deposit_and_stake.rs
src/commands/staking/delegate/deposit_and_stake.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::StakeDelegationContext)] #[interactive_clap(output_context = DepositAndStakeContext)] pub struct DepositAndStake { /// Enter the attached amount to be deposited and then staked into the predecessor's internal account (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear): amount: crate::types::near_token::NearToken, #[interactive_clap(skip_default_input_arg)] /// What is validator account ID? validator_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Clone)] pub struct DepositAndStakeContext(crate::commands::ActionContext); impl DepositAndStakeContext { pub fn from_previous_context( previous_context: super::StakeDelegationContext, scope: &<DepositAndStake as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_account_id: near_primitives::types::AccountId = scope.validator_account_id.clone().into(); let amount = scope.amount; move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_id.clone(), receiver_id: validator_account_id.clone(), actions: vec![near_primitives::transaction::Action::FunctionCall( Box::new(near_primitives::transaction::FunctionCallAction { method_name: "deposit_and_stake".to_string(), args: serde_json::to_vec(&serde_json::json!({}))?, gas: near_primitives::gas::Gas::from_teragas(50), deposit: amount.into(), }), )], }) } }); let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_id = scope.validator_account_id.clone(); let amount = scope.amount; let verbosity = previous_context.global_context.verbosity; move |outcome_view, _network_config| { if let near_primitives::views::FinalExecutionStatus::SuccessValue(_) = outcome_view.status { if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = verbosity { tracing_indicatif::suspend_tracing_indicatif(|| { eprintln!("<{signer_id}> has successfully delegated {amount} to stake with <{validator_id}>."); }) } } Ok(()) } }); Ok(Self(crate::commands::ActionContext { global_context: previous_context.global_context, interacting_with_account_ids: vec![ previous_context.account_id, scope.validator_account_id.clone().into(), ], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback, })) } } impl From<DepositAndStakeContext> for crate::commands::ActionContext { fn from(item: DepositAndStakeContext) -> Self { item.0 } } impl DepositAndStake { pub fn input_validator_account_id( context: &super::StakeDelegationContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_staking_pool_validator_account_id(&context.global_context.config) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/staking/delegate/view_balance.rs
src/commands/staking/delegate/view_balance.rs
use color_eyre::eyre::WrapErr; use crate::common::{CallResultExt, JsonRpcClientExt}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::StakeDelegationContext)] #[interactive_clap(output_context = ViewBalanceContext)] pub struct ViewBalance { #[interactive_clap(skip_default_input_arg)] /// What is validator account ID? validator_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_view_at_block::NetworkViewAtBlockArgs, } #[derive(Clone)] pub struct ViewBalanceContext(crate::network_view_at_block::ArgsForViewContext); impl ViewBalanceContext { pub fn from_previous_context( previous_context: super::StakeDelegationContext, scope: &<ViewBalance as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let account_id = previous_context.account_id.clone(); let validator_account_id: near_primitives::types::AccountId = scope.validator_account_id.clone().into(); let interacting_with_account_ids = vec![account_id.clone(), validator_account_id.clone()]; let on_after_getting_block_reference_callback: crate::network_view_at_block::OnAfterGettingBlockReferenceCallback = std::sync::Arc::new({ move |network_config: &crate::config::NetworkConfig, block_reference: &near_primitives::types::BlockReference| { calculation_delegated_stake_balance( &account_id, &validator_account_id, network_config, block_reference, ) } }); Ok(Self(crate::network_view_at_block::ArgsForViewContext { config: previous_context.global_context.config, interacting_with_account_ids, on_after_getting_block_reference_callback, })) } } impl From<ViewBalanceContext> for crate::network_view_at_block::ArgsForViewContext { fn from(item: ViewBalanceContext) -> Self { item.0 } } impl ViewBalance { pub fn input_validator_account_id( context: &super::StakeDelegationContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_staking_pool_validator_account_id(&context.global_context.config) } } #[tracing::instrument( name = "Calculation of the delegated stake balance for your account ...", skip_all )] fn calculation_delegated_stake_balance( account_id: &near_primitives::types::AccountId, validator_account_id: &near_primitives::types::AccountId, network_config: &crate::config::NetworkConfig, block_reference: &near_primitives::types::BlockReference, ) -> crate::CliResult { tracing::info!(target: "near_teach_me", "Calculation of the delegated stake balance for your account ..."); let user_staked_balance: u128 = get_user_staked_balance( network_config, block_reference, validator_account_id, account_id, )?; let user_unstaked_balance: u128 = get_user_unstaked_balance( network_config, block_reference, validator_account_id, account_id, )?; let user_total_balance: u128 = get_user_total_balance( network_config, block_reference, validator_account_id, account_id, )?; let withdrawal_availability_message = match is_account_unstaked_balance_available_for_withdrawal( network_config, validator_account_id, account_id, )? { true if user_unstaked_balance > 0 => "(available for withdrawal)", false if user_unstaked_balance > 0 => { "(not available for withdrawal in the current epoch)" } _ => "", }; let mut info_str = String::new(); info_str.push_str(&format!( "\n Staked balance: {:>38}", near_token::NearToken::from_yoctonear(user_staked_balance).to_string() )); info_str.push_str(&format!( "\n Unstaked balance: {:>38} {withdrawal_availability_message}", near_token::NearToken::from_yoctonear(user_unstaked_balance).to_string() )); info_str.push_str(&format!( "\n Total balance: {:>38}", near_token::NearToken::from_yoctonear(user_total_balance).to_string() )); tracing_indicatif::suspend_tracing_indicatif(|| { println!( "Delegated stake balance with validator <{validator_account_id}> by <{account_id}>:{info_str}" ); }); Ok(()) } #[tracing::instrument(name = "Getting the staked balance for the user ...", skip_all)] pub fn get_user_staked_balance( network_config: &crate::config::NetworkConfig, block_reference: &near_primitives::types::BlockReference, validator_account_id: &near_primitives::types::AccountId, account_id: &near_primitives::types::AccountId, ) -> color_eyre::eyre::Result<u128> { tracing::info!(target: "near_teach_me", "Getting the staked balance for the user ..."); Ok(network_config .json_rpc_client() .blocking_call_view_function( validator_account_id, "get_account_staked_balance", serde_json::to_vec(&serde_json::json!({ "account_id": account_id, }))?, block_reference.clone(), ) .wrap_err_with(||{ format!("Failed to fetch query for view method: 'get_account_staked_balance' (contract <{}> on network <{}>)", validator_account_id, network_config.network_name ) })? .parse_result_from_json::<String>() .wrap_err("Failed to parse return value of view function call for String.")? .parse::<u128>()?) } #[tracing::instrument(name = "Getting the unstaked balance for the user ...", skip_all)] pub fn get_user_unstaked_balance( network_config: &crate::config::NetworkConfig, block_reference: &near_primitives::types::BlockReference, validator_account_id: &near_primitives::types::AccountId, account_id: &near_primitives::types::AccountId, ) -> color_eyre::eyre::Result<u128> { tracing::info!(target: "near_teach_me", "Getting the unstaked balance for the user ..."); Ok(network_config .json_rpc_client() .blocking_call_view_function( validator_account_id, "get_account_unstaked_balance", serde_json::to_vec(&serde_json::json!({ "account_id": account_id, }))?, block_reference.clone(), ) .wrap_err_with(||{ format!("Failed to fetch query for view method: 'get_account_unstaked_balance' (contract <{}> on network <{}>)", validator_account_id, network_config.network_name ) })? .parse_result_from_json::<String>() .wrap_err("Failed to parse return value of view function call for String.")? .parse::<u128>()?) } #[tracing::instrument(name = "Getting the total balance for the user ...", skip_all)] pub fn get_user_total_balance( network_config: &crate::config::NetworkConfig, block_reference: &near_primitives::types::BlockReference, validator_account_id: &near_primitives::types::AccountId, account_id: &near_primitives::types::AccountId, ) -> color_eyre::eyre::Result<u128> { tracing::info!(target: "near_teach_me", "Getting the total balance for the user ..."); Ok(network_config .json_rpc_client() .blocking_call_view_function( validator_account_id, "get_account_total_balance", serde_json::to_vec(&serde_json::json!({ "account_id": account_id, }))?, block_reference.clone(), ) .wrap_err_with(||{ format!("Failed to fetch query for view method: 'get_account_total_balance' (contract <{}> on network <{}>)", validator_account_id, network_config.network_name ) })? .parse_result_from_json::<String>() .wrap_err("Failed to parse return value of view function call for String.")? .parse::<u128>()?) } #[tracing::instrument( name = "Getting account unstaked balance available for withdrawal ...", skip_all )] pub fn is_account_unstaked_balance_available_for_withdrawal( network_config: &crate::config::NetworkConfig, validator_account_id: &near_primitives::types::AccountId, account_id: &near_primitives::types::AccountId, ) -> color_eyre::eyre::Result<bool> { tracing::info!(target: "near_teach_me", "Getting account unstaked balance available for withdrawal ..."); network_config .json_rpc_client() .blocking_call_view_function( validator_account_id, "is_account_unstaked_balance_available", serde_json::to_vec(&serde_json::json!({ "account_id": account_id.to_string(), }))?, near_primitives::types::BlockReference::Finality( near_primitives::types::Finality::Final, ), ) .wrap_err_with(||{ format!("Failed to fetch query for view method: 'is_account_unstaked_balance_available' (contract <{}> on network <{}>)", validator_account_id, network_config.network_name ) })? .parse_result_from_json::<bool>() .wrap_err("Failed to parse return value of view function call for bool value.") }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/staking/delegate/mod.rs
src/commands/staking/delegate/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod deposit_and_stake; mod stake; mod stake_all; mod unstake; mod unstake_all; pub mod view_balance; mod withdraw; mod withdraw_all; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = StakeDelegationContext)] pub struct StakeDelegation { #[interactive_clap(skip_default_input_arg)] /// Enter the account that you want to manage delegated stake for: account_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] delegate_stake_command: StakeDelegationCommand, } #[derive(Debug, Clone)] pub struct StakeDelegationContext { global_context: crate::GlobalContext, account_id: near_primitives::types::AccountId, } impl StakeDelegationContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<StakeDelegation as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context, account_id: scope.account_id.clone().into(), }) } } impl StakeDelegation { pub fn input_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_non_signer_account_id_from_used_account_list( &context.config.credentials_home_dir, "Enter the account that you want to manage delegated stake for:", ) } } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = StakeDelegationContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] #[non_exhaustive] /// Select actions with delegated staking: pub enum StakeDelegationCommand { #[strum_discriminants(strum( message = "view-balance - View the delegated stake balance for a given account" ))] /// View the delegated stake balance for a given account ViewBalance(self::view_balance::ViewBalance), #[strum_discriminants(strum( message = "deposit-and-stake - Delegate NEAR tokens to a validator's staking pool" ))] /// Delegate NEAR tokens to a validator's staking pool DepositAndStake(self::deposit_and_stake::DepositAndStake), #[strum_discriminants(strum( message = "stake - Delegate a certain amount of previously deposited or unstaked NEAR tokens to a validator's staking pool" ))] /// Delegate a certain amount of previously deposited or unstaked NEAR tokens to a validator's staking pool Stake(self::stake::Stake), #[strum_discriminants(strum( message = "stake-all - Delegate all previously deposited or unstaked NEAR tokens to a validator's staking pool" ))] /// Delegate all previously deposited or unstaked NEAR tokens to a validator's staking pool StakeAll(self::stake_all::StakeAll), #[strum_discriminants(strum( message = "unstake - Unstake a certain amount of delegated NEAR tokens from a validator's staking pool" ))] /// Unstake a certain amount of delegated NEAR tokens from a validator's staking pool Unstake(self::unstake::Unstake), #[strum_discriminants(strum( message = "unstake-all - Unstake all delegated NEAR tokens from a validator's staking pool" ))] /// Unstake all delegated NEAR tokens from a validator's staking pool UnstakeAll(self::unstake_all::UnstakeAll), #[strum_discriminants(strum( message = "withdraw - Withdraw a certain amount of unstaked NEAR tokens from a validator's staking pool" ))] /// Withdraw a certain amount of unstaked NEAR tokens from a validator's staking pool Withdraw(self::withdraw::Withdraw), #[strum_discriminants(strum( message = "withdraw-all - Withdraw all unstaked NEAR tokens from a validator's staking pool" ))] /// Withdraw all unstaked NEAR tokens from a validator's staking pool WithdrawAll(self::withdraw_all::WithdrawAll), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/staking/delegate/stake_all.rs
src/commands/staking/delegate/stake_all.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::StakeDelegationContext)] #[interactive_clap(output_context = StakeAllContext)] pub struct StakeAll { #[interactive_clap(skip_default_input_arg)] /// What is validator account ID? validator_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Clone)] pub struct StakeAllContext(crate::commands::ActionContext); impl StakeAllContext { pub fn from_previous_context( previous_context: super::StakeDelegationContext, scope: &<StakeAll as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_account_id: near_primitives::types::AccountId = scope.validator_account_id.clone().into(); move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_id.clone(), receiver_id: validator_account_id.clone(), actions: vec![near_primitives::transaction::Action::FunctionCall( Box::new(near_primitives::transaction::FunctionCallAction { method_name: "stake_all".to_string(), args: serde_json::to_vec(&serde_json::json!({}))?, gas: near_primitives::gas::Gas::from_teragas(50), deposit: near_token::NearToken::ZERO, }), )], }) } }); let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = std::sync::Arc::new({ let signer_id = previous_context.account_id.clone(); let validator_id = scope.validator_account_id.clone(); let verbosity = previous_context.global_context.verbosity; move |outcome_view, _network_config| { if let near_primitives::views::FinalExecutionStatus::SuccessValue(_) = outcome_view.status { if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = verbosity { tracing_indicatif::suspend_tracing_indicatif(|| { eprintln!("<{signer_id}> has successfully delegated to stake with <{validator_id}>."); }) } } Ok(()) } }); Ok(Self(crate::commands::ActionContext { global_context: previous_context.global_context, interacting_with_account_ids: vec![ previous_context.account_id, scope.validator_account_id.clone().into(), ], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback, })) } } impl From<StakeAllContext> for crate::commands::ActionContext { fn from(item: StakeAllContext) -> Self { item.0 } } impl StakeAll { pub fn input_validator_account_id( context: &super::StakeDelegationContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_staking_pool_validator_account_id(&context.global_context.config) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/mod.rs
src/commands/account/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod add_key; pub mod create_account; mod delete_account; mod delete_key; pub mod export_account; mod get_public_key; mod import_account; mod list_keys; pub mod storage_management; pub mod update_social_profile; pub mod view_account_summary; pub const MIN_ALLOWED_TOP_LEVEL_ACCOUNT_LENGTH: usize = 32; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] pub struct AccountCommands { #[interactive_clap(subcommand)] account_actions: AccountActions, } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] #[non_exhaustive] /// What do you want to do with an account? pub enum AccountActions { #[strum_discriminants(strum( message = "view-account-summary - View properties for an account" ))] /// View properties for an account ViewAccountSummary(self::view_account_summary::ViewAccountSummary), #[strum_discriminants(strum( message = "import-account - Import existing account (a.k.a. \"sign in\")" ))] /// Import existing account (a.k.a. "sign in") ImportAccount(self::import_account::ImportAccountCommand), #[strum_discriminants(strum(message = "export-account - Export existing account"))] /// Export existing account ExportAccount(self::export_account::ExportAccount), #[strum_discriminants(strum(message = "create-account - Create a new account"))] /// Create a new account CreateAccount(self::create_account::CreateAccount), #[strum_discriminants(strum( message = "update-social-profile - Update NEAR Social profile" ))] /// Update NEAR Social profile UpdateSocialProfile(self::update_social_profile::UpdateSocialProfile), #[strum_discriminants(strum(message = "delete-account - Delete an account"))] /// Delete an account DeleteAccount(self::delete_account::DeleteAccount), #[strum_discriminants(strum( message = "list-keys - View a list of access keys of an account" ))] /// View a list of access keys of an account ListKeys(self::list_keys::ViewListKeys), #[strum_discriminants(strum( message = "get-public-key - Get the public key to your account" ))] /// Get the public key to your account GetPublicKey(self::get_public_key::GetPublicKey), #[strum_discriminants(strum( message = "add-key - Add an access key to an account" ))] /// Add an access key to an account AddKey(self::add_key::AddKeyCommand), #[strum_discriminants(strum( message = "delete-keys - Delete access keys from an account" ))] /// Delete access keys from an account DeleteKeys(self::delete_key::DeleteKeysCommand), #[strum_discriminants(strum( message = "manage-storage-deposit - Storage management: deposit, withdrawal, balance review" ))] /// Storage management for contract: deposit, withdrawal, balance review ManageStorageDeposit(self::storage_management::Contract), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/import_account/mod.rs
src/commands/account/import_account/mod.rs
#![allow(clippy::enum_variant_names, clippy::large_enum_variant)] use std::{str::FromStr, vec}; use color_eyre::eyre::Context; use inquire::{CustomType, Select}; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; use near_primitives::account::id::AccountType; mod using_private_key; mod using_seed_phrase; mod using_web_wallet; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] pub struct ImportAccountCommand { #[interactive_clap(subcommand)] import_account_actions: ImportAccountActions, } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// How would you like to import the account? pub enum ImportAccountActions { #[strum_discriminants(strum( message = "using-web-wallet - Import existing account using NEAR Wallet (a.k.a. \"sign in\")" ))] /// Import existing account using NEAR Wallet (a.k.a. "sign in") UsingWebWallet(self::using_web_wallet::LoginFromWebWallet), #[strum_discriminants(strum( message = "using-seed-phrase - Import existing account using a seed phrase" ))] /// Import existing account using a seed phrase UsingSeedPhrase(self::using_seed_phrase::LoginFromSeedPhrase), #[strum_discriminants(strum( message = "using-private-key - Import existing account using a private key" ))] /// Import existing account using a private key UsingPrivateKey(self::using_private_key::LoginFromPrivateKey), } pub fn login( network_config: crate::config::NetworkConfig, credentials_home_dir: std::path::PathBuf, key_pair_properties_buf: &str, public_key_str: &str, error_message: &str, ) -> crate::CliResult { let public_key: near_crypto::PublicKey = near_crypto::PublicKey::from_str(public_key_str)?; let account_id = loop { let account_id_from_cli = input_account_id()?; // If the implicit account does not exist on the network, it will still be imported. if let AccountType::NearImplicitAccount = account_id_from_cli.get_account_type() { let pk_implicit_account = near_crypto::PublicKey::from_near_implicit_account(&account_id_from_cli)?; if public_key_str == pk_implicit_account.to_string() { break account_id_from_cli; } }; let access_key_view = crate::common::verify_account_access_key( account_id_from_cli.clone(), public_key.clone(), network_config.clone(), ); if let Err(crate::common::AccountStateError::Cancel) = access_key_view { return color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!( "Operation was canceled by the user" )); } if access_key_view.is_err() { tracing::warn!( parent: &tracing::Span::none(), "{}", crate::common::indent_payload(error_message) ); #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum(to_string = "Yes, I want to re-enter the account_id.")] Yes, #[strum(to_string = "No, I want to save the access key information.")] No, } let select_choose_input = Select::new( "Would you like to re-enter the account_id?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::No = select_choose_input { break account_id_from_cli; } } else { break account_id_from_cli; } }; crate::common::update_used_account_list_as_signer(&credentials_home_dir, &account_id); save_access_key( account_id, key_pair_properties_buf, public_key_str, network_config, credentials_home_dir, )?; Ok(()) } fn input_account_id() -> color_eyre::eyre::Result<near_primitives::types::AccountId> { Ok(CustomType::new("Enter account ID:").prompt()?) } fn save_access_key( account_id: near_primitives::types::AccountId, key_pair_properties_buf: &str, public_key_str: &str, network_config: crate::config::NetworkConfig, credentials_home_dir: std::path::PathBuf, ) -> crate::CliResult { #[derive(strum_macros::Display)] enum SelectStorage { #[strum(to_string = "Store the access key in my keychain")] SaveToKeychain, #[strum( to_string = "Store the access key in my legacy keychain (compatible with the old near CLI)" )] SaveToLegacyKeychain, } let selection = Select::new( "Select a keychain to save the access key to:", vec![ SelectStorage::SaveToKeychain, SelectStorage::SaveToLegacyKeychain, ], ) .prompt()?; if let SelectStorage::SaveToKeychain = selection { let storage_message = crate::common::save_access_key_to_keychain_or_save_to_legacy_keychain( network_config, credentials_home_dir, key_pair_properties_buf, public_key_str, account_id.as_ref(), )?; eprintln!("{storage_message}"); return Ok(()); } let storage_message = crate::common::save_access_key_to_legacy_keychain( network_config, credentials_home_dir, key_pair_properties_buf, public_key_str, account_id.as_ref(), ) .wrap_err_with(|| format!("Failed to save a file with access key: {public_key_str}"))?; eprintln!("{storage_message}"); Ok(()) }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/import_account/using_web_wallet/mod.rs
src/commands/account/import_account/using_web_wallet/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = LoginFromWebWalletContext)] pub struct LoginFromWebWallet { #[interactive_clap(named_arg)] /// Select network network_config: crate::network::Network, } #[derive(Clone)] pub struct LoginFromWebWalletContext(crate::network::NetworkContext); impl LoginFromWebWalletContext { pub fn from_previous_context( previous_context: crate::GlobalContext, _scope: &<LoginFromWebWallet as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback = std::sync::Arc::new({ let config = previous_context.config.clone(); move |network_config| { let key_pair_properties: crate::common::KeyPairProperties = crate::common::generate_keypair()?; let mut url: url::Url = network_config.wallet_url.join("login/")?; url.query_pairs_mut() .append_pair("title", "NEAR CLI") .append_pair("public_key", &key_pair_properties.public_key_str); // Use `success_url` once capture mode is implemented //.append_pair("success_url", "http://127.0.0.1:8080"); eprintln!( "If your browser doesn't automatically open, please visit this URL:\n {}\n", &url.as_str() ); // url.open(); open::that(url.as_ref()).ok(); let key_pair_properties_buf = serde_json::to_string(&key_pair_properties)?; let error_message = format!("\nIt is currently not possible to verify the account access key.\nYou may not be logged in to {} or you may have entered an incorrect account_id.\nYou have the option to reconfirm your account or save your access key information.\n", &url.as_str()); super::login( network_config.clone(), config.credentials_home_dir.clone(), &key_pair_properties_buf, &key_pair_properties.public_key_str, &error_message, ) } }); Ok(Self(crate::network::NetworkContext { config: previous_context.config, interacting_with_account_ids: Vec::new(), on_after_getting_network_callback, })) } } impl From<LoginFromWebWalletContext> for crate::network::NetworkContext { fn from(item: LoginFromWebWalletContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/import_account/using_private_key/mod.rs
src/commands/account/import_account/using_private_key/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = LoginFromPrivateKeyContext)] pub struct LoginFromPrivateKey { /// Enter your private (secret) key: private_key: crate::types::secret_key::SecretKey, #[interactive_clap(named_arg)] /// Select network network_config: crate::network::Network, } #[derive(Clone)] pub struct LoginFromPrivateKeyContext(crate::network::NetworkContext); impl LoginFromPrivateKeyContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<LoginFromPrivateKey as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let private_key: near_crypto::SecretKey = scope.private_key.clone().into(); let public_key = private_key.public_key(); let key_pair_properties = KeyPairProperties { public_key: public_key.clone(), private_key, }; let key_pair_properties_buf = serde_json::to_string(&key_pair_properties).unwrap(); let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback = std::sync::Arc::new({ let config = previous_context.config.clone(); move |network_config| { super::login( network_config.clone(), config.credentials_home_dir.clone(), &key_pair_properties_buf, &public_key.to_string(), &format!("\nIt is currently not possible to verify the account access key on network <{}>.\nYou may have entered an incorrect account_id.\nYou have the option to reconfirm your account or save your access key information.\n", network_config.network_name ) ) } }); Ok(Self(crate::network::NetworkContext { config: previous_context.config, interacting_with_account_ids: Vec::new(), on_after_getting_network_callback, })) } } impl From<LoginFromPrivateKeyContext> for crate::network::NetworkContext { fn from(item: LoginFromPrivateKeyContext) -> Self { item.0 } } #[derive(Debug, serde::Serialize)] struct KeyPairProperties { public_key: near_crypto::PublicKey, private_key: near_crypto::SecretKey, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/import_account/using_seed_phrase/mod.rs
src/commands/account/import_account/using_seed_phrase/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = LoginFromSeedPhraseContext)] pub struct LoginFromSeedPhrase { /// Enter the seed-phrase for this account: master_seed_phrase: String, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] seed_phrase_hd_path: crate::types::slip10::BIP32Path, #[interactive_clap(named_arg)] /// Select network network_config: crate::network::Network, } #[derive(Clone)] pub struct LoginFromSeedPhraseContext(crate::network::NetworkContext); impl LoginFromSeedPhraseContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<LoginFromSeedPhrase as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let key_pair_properties = crate::common::get_key_pair_properties_from_seed_phrase( scope.seed_phrase_hd_path.clone(), scope.master_seed_phrase.clone(), )?; let key_pair_properties_buf = serde_json::to_string(&key_pair_properties).unwrap(); let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback = std::sync::Arc::new({ let config = previous_context.config.clone(); move |network_config| { super::login( network_config.clone(), config.credentials_home_dir.clone(), &key_pair_properties_buf, &key_pair_properties.public_key_str, &format!("\nIt is currently not possible to verify the account access key on network <{}>.\nYou may have entered an incorrect account_id.\nYou have the option to reconfirm your account or save your access key information.\n", network_config.network_name ) ) } }); Ok(Self(crate::network::NetworkContext { config: previous_context.config, interacting_with_account_ids: Vec::new(), on_after_getting_network_callback, })) } } impl From<LoginFromSeedPhraseContext> for crate::network::NetworkContext { fn from(item: LoginFromSeedPhraseContext) -> Self { item.0 } } impl LoginFromSeedPhrase { pub fn input_seed_phrase_hd_path( _context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::slip10::BIP32Path>> { crate::transaction_signature_options::sign_with_seed_phrase::input_seed_phrase_hd_path() } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/update_social_profile/sign_as.rs
src/commands/account/update_social_profile/sign_as.rs
use std::collections::HashMap; use std::sync::Arc; use color_eyre::eyre::WrapErr; use inquire::{CustomType, Select}; use crate::common::{CallResultExt, JsonRpcClientExt}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::profile_args_type::ArgsContext)] #[interactive_clap(output_context = SignerContext)] pub struct Signer { #[interactive_clap(skip_default_input_arg)] /// What is the signer account ID? signer_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Clone)] pub struct SignerContext { pub global_context: crate::GlobalContext, pub account_id: near_primitives::types::AccountId, pub data: Vec<u8>, pub signer_account_id: near_primitives::types::AccountId, } impl SignerContext { pub fn from_previous_context( previous_context: super::profile_args_type::ArgsContext, scope: &<Signer as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, account_id: previous_context.account_id, data: previous_context.data, signer_account_id: scope.signer_account_id.clone().into(), }) } } impl From<SignerContext> for crate::commands::ActionContext { fn from(item: SignerContext) -> Self { let account_id = item.account_id.clone(); let signer_id = item.signer_account_id.clone(); let data = item.data; let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = Arc::new({ move |network_config| { get_prepopulated_transaction(network_config, &account_id, &signer_id, &data) } }); let on_before_signing_callback: crate::commands::OnBeforeSigningCallback = Arc::new({ let signer_account_id = item.signer_account_id.clone(); let account_id = item.account_id.clone(); move |prepopulated_unsigned_transaction, network_config| { let json_rpc_client = network_config.json_rpc_client(); let public_key = prepopulated_unsigned_transaction.public_key.clone(); let receiver_id = prepopulated_unsigned_transaction.receiver_id.clone(); if let Some(near_primitives::transaction::Action::FunctionCall(action)) = prepopulated_unsigned_transaction.actions.first_mut() { action.deposit = get_deposit( &json_rpc_client, &signer_account_id, &public_key, &account_id, "profile", &receiver_id, action.deposit, )?; Ok(()) } else { color_eyre::eyre::bail!("Unexpected action to change components",); } } }); let account_id = item.account_id.clone(); let verbosity = item.global_context.verbosity; let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = Arc::new({ move |transaction_info, _network_config| { if let near_primitives::views::FinalExecutionStatus::SuccessValue(_) = transaction_info.status { if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = verbosity { eprintln!("Profile for {account_id} updated successfully"); } } else { color_eyre::eyre::bail!("Failed to update profile!"); }; Ok(()) } }); Self { global_context: item.global_context, interacting_with_account_ids: vec![item.account_id], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback, on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback, } } } impl Signer { fn input_signer_account_id( context: &super::profile_args_type::ArgsContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { loop { let signer_account_id: crate::types::account_id::AccountId = CustomType::new("What is the signer account ID?") .with_default(context.account_id.clone().into()) .prompt()?; if !crate::common::is_account_exist( &context.global_context.config.network_connection, signer_account_id.clone().into(), )? { eprintln!( "\nThe account <{signer_account_id}> does not exist on [{}] networks.", context.global_context.config.network_names().join(", ") ); #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum(to_string = "Yes, I want to enter a new account name.")] Yes, #[strum(to_string = "No, I want to use this account name.")] No, } let select_choose_input = Select::new( "Do you want to enter another signer account id?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::No = select_choose_input { return Ok(Some(signer_account_id)); } } else { return Ok(Some(signer_account_id)); } } } } #[tracing::instrument( name = "Creating a pre-populated transaction for signature ...", skip_all )] fn get_prepopulated_transaction( network_config: &crate::config::NetworkConfig, account_id: &near_primitives::types::AccountId, signer_id: &near_primitives::types::AccountId, data: &[u8], ) -> color_eyre::eyre::Result<crate::commands::PrepopulatedTransaction> { tracing::info!(target: "near_teach_me", "Creating a pre-populated transaction for signature ..."); let contract_account_id = network_config.get_near_social_account_id_from_network()?; let mut prepopulated_transaction = crate::commands::PrepopulatedTransaction { signer_id: signer_id.clone(), receiver_id: contract_account_id.clone(), actions: vec![], }; let local_profile: serde_json::Value = serde_json::from_slice(data)?; let remote_profile = get_remote_profile(network_config, &contract_account_id, account_id.clone())?; let deposit = required_deposit( &network_config.json_rpc_client(), &contract_account_id, account_id, &local_profile, Some(&remote_profile), )?; let new_social_db_state = near_socialdb_client::types::socialdb_types::SocialDb { accounts: HashMap::from([( account_id.clone(), near_socialdb_client::types::socialdb_types::AccountProfile { profile: serde_json::from_value(local_profile)?, }, )]), }; let args = serde_json::to_string(&super::TransactionFunctionArgs { data: new_social_db_state, })? .into_bytes(); prepopulated_transaction.actions = vec![near_primitives::transaction::Action::FunctionCall( Box::new(near_primitives::transaction::FunctionCallAction { method_name: "set".to_string(), args, gas: near_primitives::gas::Gas::from_teragas(300), deposit, }), )]; Ok(prepopulated_transaction) } #[tracing::instrument(name = "Calculation of the required deposit ...", skip_all)] fn required_deposit( json_rpc_client: &near_jsonrpc_client::JsonRpcClient, near_social_account_id: &near_primitives::types::AccountId, account_id: &near_primitives::types::AccountId, data: &serde_json::Value, prev_data: Option<&serde_json::Value>, ) -> color_eyre::eyre::Result<near_token::NearToken> { tracing::info!(target: "near_teach_me", "Calculation of the required deposit ..."); tokio::runtime::Runtime::new() .unwrap() .block_on(near_socialdb_client::required_deposit( json_rpc_client, near_social_account_id, account_id, data, prev_data, )) } #[tracing::instrument(name = "Update the required deposit ...", skip_all)] fn get_deposit( json_rpc_client: &near_jsonrpc_client::JsonRpcClient, signer_account_id: &near_primitives::types::AccountId, signer_public_key: &near_crypto::PublicKey, account_id: &near_primitives::types::AccountId, key: &str, near_social_account_id: &near_primitives::types::AccountId, required_deposit: near_token::NearToken, ) -> color_eyre::eyre::Result<near_token::NearToken> { tracing::info!(target: "near_teach_me", "Update the required deposit ..."); tokio::runtime::Runtime::new() .unwrap() .block_on(near_socialdb_client::get_deposit( json_rpc_client, signer_account_id, signer_public_key, account_id, key, near_social_account_id, required_deposit, )) } #[tracing::instrument(name = "Getting data about a remote profile ...", skip_all)] fn get_remote_profile( network_config: &crate::config::NetworkConfig, near_social_account_id: &near_primitives::types::AccountId, account_id: near_primitives::types::AccountId, ) -> color_eyre::eyre::Result<serde_json::Value> { tracing::info!(target: "near_teach_me", "Getting data about a remote profile ..."); match network_config .json_rpc_client() .blocking_call_view_function( near_social_account_id, "get", serde_json::to_vec(&serde_json::json!({ "keys": vec![format!("{account_id}/profile/**")], }))?, near_primitives::types::Finality::Final.into(), ) .wrap_err_with(|| { format!("Failed to fetch query for view method: 'get {account_id}/profile/**' (contract <{}> on network <{}>)", near_social_account_id, network_config.network_name ) })? .parse_result_from_json::<near_socialdb_client::types::socialdb_types::SocialDb>() .wrap_err_with(|| { format!("Failed to parse view function call return value for {account_id}/profile.") })? .accounts .get(&account_id) { Some(account_profile) => Ok(serde_json::to_value(account_profile.profile.clone())?), None => Ok(serde_json::Value::Null) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/update_social_profile/mod.rs
src/commands/account/update_social_profile/mod.rs
mod profile_args_type; mod sign_as; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct TransactionFunctionArgs { pub data: near_socialdb_client::types::socialdb_types::SocialDb, } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = UpdateSocialProfileContext)] pub struct UpdateSocialProfile { #[interactive_clap(skip_default_input_arg)] account_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] profile_args_type: self::profile_args_type::ProfileArgsType, } #[derive(Clone)] pub struct UpdateSocialProfileContext { pub global_context: crate::GlobalContext, pub account_id: near_primitives::types::AccountId, } impl UpdateSocialProfileContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<UpdateSocialProfile as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context, account_id: scope.account_id.clone().into(), }) } } impl UpdateSocialProfile { pub fn input_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_non_signer_account_id_from_used_account_list( &context.config.credentials_home_dir, "Which account do you want to update the profile for?", ) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/update_social_profile/profile_args_type/manually.rs
src/commands/account/update_social_profile/profile_args_type/manually.rs
use std::collections::HashMap; use inquire::{CustomType, Select, Text}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::UpdateSocialProfileContext)] #[interactive_clap(output_context = ManuallyContext)] pub struct Manually { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] name: Option<String>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] image_url: Option<crate::types::url::Url>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] image_ipfs_cid: Option<String>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] background_image_url: Option<crate::types::url::Url>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] background_image_ipfs_cid: Option<String>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] description: Option<String>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] twitter: Option<String>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] github: Option<String>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] telegram: Option<String>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] website: Option<crate::types::url::Url>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] tags: Option<crate::types::vec_string::VecString>, #[interactive_clap(named_arg)] /// Specify signer account ID sign_as: super::super::sign_as::Signer, } #[derive(Clone)] pub struct ManuallyContext(super::ArgsContext); impl ManuallyContext { pub fn from_previous_context( previous_context: super::super::UpdateSocialProfileContext, scope: &<Manually as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let profile = near_socialdb_client::types::socialdb_types::Profile { name: scope.name.clone(), image: if scope.image_url.is_none() && scope.image_ipfs_cid.is_none() { None } else { Some(near_socialdb_client::types::socialdb_types::ProfileImage { url: scope.image_url.clone().map(|url| url.into()), ipfs_cid: scope.image_ipfs_cid.clone(), }) }, background_image: if scope.background_image_url.is_none() && scope.background_image_ipfs_cid.is_none() { None } else { Some(near_socialdb_client::types::socialdb_types::ProfileImage { url: scope.background_image_url.clone().map(|url| url.into()), ipfs_cid: scope.background_image_ipfs_cid.clone(), }) }, description: scope.description.clone(), linktree: if scope.twitter.is_none() && scope.github.is_none() && scope.telegram.is_none() && scope.website.is_none() { None } else { let mut linktree_map: HashMap<String, Option<String>> = HashMap::new(); if scope.twitter.is_some() { linktree_map.insert("twitter".to_string(), scope.twitter.clone()); } if scope.telegram.is_some() { linktree_map.insert("telegram".to_string(), scope.telegram.clone()); } if scope.github.is_some() { linktree_map.insert("github".to_string(), scope.github.clone()); } if scope.website.is_some() { linktree_map.insert( "website".to_string(), scope.website.as_ref().map(|website| website.to_string()), ); } Some(linktree_map) }, tags: if let Some(tags) = scope.tags.clone() { let mut tags_map: HashMap<String, String> = HashMap::new(); for tag in tags.0.iter() { tags_map.insert(tag.clone(), "".to_string()); } Some(tags_map) } else { None }, }; Ok(Self(super::ArgsContext { global_context: previous_context.global_context, account_id: previous_context.account_id, data: serde_json::to_vec(&profile)?, })) } } impl From<ManuallyContext> for super::ArgsContext { fn from(item: ManuallyContext) -> Self { item.0 } } impl Manually { fn input_name( _context: &super::super::UpdateSocialProfileContext, ) -> color_eyre::eyre::Result<Option<String>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum(to_string = "Yes, I want to enter a name for the account profile")] Yes, #[strum(to_string = "No, I don't want to enter a name for the account profile")] No, } let select_choose_input = Select::new( "Do you want to enter a name for the account profile?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { Ok(Some( Text::new("Enter a name for the account profile:").prompt()?, )) } else { Ok(None) } } fn input_image_url( _context: &super::super::UpdateSocialProfileContext, ) -> color_eyre::eyre::Result<Option<crate::types::url::Url>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum(to_string = "Yes, I want to enter the URL for the account profile image")] Yes, #[strum(to_string = "No, I don't want to enter the URL of the account profile image")] No, } let select_choose_input = Select::new( "Do you want to enter an account profile image URL?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { let url: crate::types::url::Url = CustomType::new("What is the account profile image URL?").prompt()?; Ok(Some(url)) } else { Ok(None) } } fn input_image_ipfs_cid( _context: &super::super::UpdateSocialProfileContext, ) -> color_eyre::eyre::Result<Option<String>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum(to_string = "Yes, I want to enter ipfs_cid for the account profile image")] Yes, #[strum( to_string = "No, I don't want to enter ipfs_cid for the account profile image" )] No, } let select_choose_input = Select::new( "Do you want to enter ipfs_cid for the account profile image?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { Ok(Some( Text::new("Enter ipfs_cid for the account's profile image:").prompt()?, )) } else { Ok(None) } } fn input_background_image_url( _context: &super::super::UpdateSocialProfileContext, ) -> color_eyre::eyre::Result<Option<crate::types::url::Url>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum( to_string = "Yes, I want to enter the URL for the account profile background image" )] Yes, #[strum( to_string = "No, I don't want to enter the URL of the account profile background image" )] No, } let select_choose_input = Select::new( "Do you want to enter an account profile background image URL?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { let url: crate::types::url::Url = CustomType::new("What is the account profile background image URL?").prompt()?; Ok(Some(url)) } else { Ok(None) } } fn input_background_image_ipfs_cid( _context: &super::super::UpdateSocialProfileContext, ) -> color_eyre::eyre::Result<Option<String>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum( to_string = "Yes, I want to enter ipfs_cid for the account profile background image" )] Yes, #[strum( to_string = "No, I don't want to enter ipfs_cid for the account profile background image" )] No, } let select_choose_input = Select::new( "Do you want to enter ipfs_cid for the account profile background image?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { Ok(Some( Text::new("Enter ipfs_cid for the account profile background image:").prompt()?, )) } else { Ok(None) } } fn input_description( _context: &super::super::UpdateSocialProfileContext, ) -> color_eyre::eyre::Result<Option<String>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum(to_string = "Yes, I want to enter a description for the account profile")] Yes, #[strum(to_string = "No, I don't want to enter a description for the account profile")] No, } let select_choose_input = Select::new( "Do you want to enter a description for the account profile?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { Ok(Some( Text::new("Enter a description for the account profile:").prompt()?, )) } else { Ok(None) } } fn input_twitter( _context: &super::super::UpdateSocialProfileContext, ) -> color_eyre::eyre::Result<Option<String>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum(to_string = "Yes, I want to enter a Twitter nickname for the account profile")] Yes, #[strum( to_string = "No, I don't want to enter a Twitter nickname for the account profile" )] No, } let select_choose_input = Select::new( "Do you want to enter a Twitter nickname for the account profile?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { Ok(Some( Text::new("Enter a Twitter nickname for the account profile:").prompt()?, )) } else { Ok(None) } } fn input_github( _context: &super::super::UpdateSocialProfileContext, ) -> color_eyre::eyre::Result<Option<String>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum(to_string = "Yes, I want to enter a Github nickname for the account profile")] Yes, #[strum( to_string = "No, I don't want to enter a Github nickname for the account profile" )] No, } let select_choose_input = Select::new( "Do you want to enter a Github nickname for the account profile?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { Ok(Some( Text::new("Enter a Github nickname for the account profile:").prompt()?, )) } else { Ok(None) } } fn input_telegram( _context: &super::super::UpdateSocialProfileContext, ) -> color_eyre::eyre::Result<Option<String>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum( to_string = "Yes, I want to enter a Telegram nickname for the account profile" )] Yes, #[strum( to_string = "No, I don't want to enter a Telegram nickname for the account profile" )] No, } let select_choose_input = Select::new( "Do you want to enter a Telegram nickname for the account profile?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { Ok(Some( Text::new("Enter a Telegram nickname for the account profile:").prompt()?, )) } else { Ok(None) } } fn input_website( _context: &super::super::UpdateSocialProfileContext, ) -> color_eyre::eyre::Result<Option<crate::types::url::Url>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum(to_string = "Yes, I want to enter the website URL for the account profile")] Yes, #[strum( to_string = "No, I don't want to enter the website URL for the account profile" )] No, } let select_choose_input = Select::new( "Do you want to enter the website URL for the account profile?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { let url: crate::types::url::Url = CustomType::new("Enter the website URL for the account profile:").prompt()?; Ok(Some(url)) } else { Ok(None) } } fn input_tags( _context: &super::super::UpdateSocialProfileContext, ) -> color_eyre::eyre::Result<Option<crate::types::vec_string::VecString>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum(to_string = "Yes, I want to enter tags for an account profile")] Yes, #[strum(to_string = "No, I don't want to enter tags for an account profile")] No, } let select_choose_input = Select::new( "Do you want to enter tags for the account profile?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { let tags: crate::types::vec_string::VecString = CustomType::new("Enter a comma-separated list of tags for the account profile:") .prompt()?; Ok(Some(tags)) } else { Ok(None) } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/update_social_profile/profile_args_type/file_args.rs
src/commands/account/update_social_profile/profile_args_type/file_args.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::UpdateSocialProfileContext)] #[interactive_clap(output_context = FileArgsContext)] pub struct FileArgs { /// Enter the path to the input data file: data_path: crate::types::file_bytes::FileBytes, #[interactive_clap(named_arg)] /// Specify signer account ID sign_as: super::super::sign_as::Signer, } #[derive(Clone)] pub struct FileArgsContext(super::ArgsContext); impl FileArgsContext { pub fn from_previous_context( previous_context: super::super::UpdateSocialProfileContext, scope: &<FileArgs as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(super::ArgsContext { global_context: previous_context.global_context, account_id: previous_context.account_id, data: scope.data_path.read_bytes()?, })) } } impl From<FileArgsContext> for super::ArgsContext { fn from(item: FileArgsContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/update_social_profile/profile_args_type/json_args.rs
src/commands/account/update_social_profile/profile_args_type/json_args.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::UpdateSocialProfileContext)] #[interactive_clap(output_context = JsonArgsContext)] pub struct JsonArgs { /// Enter valid JSON arguments (e.g. {"name": "NEAR", "description": "NEAR is fun"}): data: crate::types::json::Json, #[interactive_clap(named_arg)] /// Specify signer account ID sign_as: super::super::sign_as::Signer, } #[derive(Clone)] pub struct JsonArgsContext(super::ArgsContext); impl JsonArgsContext { pub fn from_previous_context( previous_context: super::super::UpdateSocialProfileContext, scope: &<JsonArgs as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(super::ArgsContext { global_context: previous_context.global_context, account_id: previous_context.account_id, data: scope.data.try_into_bytes()?, })) } } impl From<JsonArgsContext> for super::ArgsContext { fn from(item: JsonArgsContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/update_social_profile/profile_args_type/mod.rs
src/commands/account/update_social_profile/profile_args_type/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod base64_args; mod file_args; mod json_args; mod manually; #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::UpdateSocialProfileContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// How do you want to pass profile arguments? pub enum ProfileArgsType { #[strum_discriminants(strum(message = "manually - Interactive input of arguments"))] /// Interactive input of arguments Manually(self::manually::Manually), #[strum_discriminants(strum( message = "json-args - Valid JSON arguments (e.g. {\"name\": \"NEAR\", \"description\": \"NEAR is fun\"})" ))] /// Valid JSON arguments (e.g. {"token_id": "42"}) JsonArgs(self::json_args::JsonArgs), #[strum_discriminants(strum(message = "base64-args - Base64-encoded string (e.g. e30=)"))] /// Base64-encoded string (e.g. e30=) Base64Args(self::base64_args::Base64Args), #[strum_discriminants(strum(message = "file-args - Read from JSON file"))] /// Read from JSON file FileArgs(self::file_args::FileArgs), } #[derive(Clone)] pub struct ArgsContext { pub global_context: crate::GlobalContext, pub account_id: near_primitives::types::AccountId, pub data: Vec<u8>, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/update_social_profile/profile_args_type/base64_args.rs
src/commands/account/update_social_profile/profile_args_type/base64_args.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::UpdateSocialProfileContext)] #[interactive_clap(output_context = Base64ArgsContext)] pub struct Base64Args { /// Enter valid Base64-encoded string (e.g. e30=): data: crate::types::base64_bytes::Base64Bytes, #[interactive_clap(named_arg)] /// Specify signer account ID sign_as: super::super::sign_as::Signer, } #[derive(Clone)] pub struct Base64ArgsContext(super::ArgsContext); impl Base64ArgsContext { pub fn from_previous_context( previous_context: super::super::UpdateSocialProfileContext, scope: &<Base64Args as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(super::ArgsContext { global_context: previous_context.global_context, account_id: previous_context.account_id, data: scope.data.clone().into_bytes(), })) } } impl From<Base64ArgsContext> for super::ArgsContext { fn from(item: Base64ArgsContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/export_account/mod.rs
src/commands/account/export_account/mod.rs
use color_eyre::eyre::{ContextCompat, WrapErr}; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; use crate::common::JsonRpcClientExt; use crate::common::RpcQueryResponseExt; mod using_private_key; mod using_seed_phrase; mod using_web_wallet; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = ExportAccountContext)] pub struct ExportAccount { #[interactive_clap(skip_default_input_arg)] /// Which account ID should be exported? account_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] export_account_actions: ExportAccountActions, } #[derive(Debug, Clone)] pub struct ExportAccountContext { global_context: crate::GlobalContext, account_id: near_primitives::types::AccountId, } impl ExportAccountContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<ExportAccount as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context, account_id: scope.account_id.clone().into(), }) } } impl ExportAccount { pub fn input_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_signer_account_id_from_used_account_list( &context.config.credentials_home_dir, "Which account ID should be exported?", ) } } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = ExportAccountContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// How would you like to export the account? pub enum ExportAccountActions { #[strum_discriminants(strum( message = "using-web-wallet - Export existing account using NEAR Wallet" ))] /// Export existing account using NEAR Wallet UsingWebWallet(self::using_web_wallet::ExportAccountFromWebWallet), #[strum_discriminants(strum( message = "using-seed-phrase - Export existing account using a seed phrase" ))] /// Export existing account using a seed phrase UsingSeedPhrase(self::using_seed_phrase::ExportAccountFromSeedPhrase), #[strum_discriminants(strum( message = "using-private-key - Export existing account using a private key" ))] /// Export existing account using a private key UsingPrivateKey(self::using_private_key::ExportAccountFromPrivateKey), } pub fn get_account_key_pair_from_keychain( network_config: &crate::config::NetworkConfig, account_id: &near_primitives::types::AccountId, ) -> color_eyre::eyre::Result<crate::transaction_signature_options::AccountKeyPair> { let password = get_password_from_keychain(network_config, account_id)?; let account_key_pair = serde_json::from_str(&password); account_key_pair.wrap_err("Error reading data") } #[tracing::instrument( name = "Receiving the account key pair from the keychain ...", skip_all )] pub fn get_password_from_keychain( network_config: &crate::config::NetworkConfig, account_id: &near_primitives::types::AccountId, ) -> color_eyre::eyre::Result<String> { tracing::info!(target: "near_teach_me", "Receiving the account key pair from the keychain ..."); let service_name: std::borrow::Cow<'_, str> = std::borrow::Cow::Owned(format!( "near-{}-{}", network_config.network_name, account_id.as_str() )); let password = { let access_key_list = network_config .json_rpc_client() .blocking_call_view_access_key_list( account_id, near_primitives::types::Finality::Final.into(), ) .wrap_err_with(|| format!("Failed to fetch access key list for {account_id}"))? .access_key_list_view()?; access_key_list .keys .into_iter() .filter(|key| { matches!( key.access_key.permission, near_primitives::views::AccessKeyPermissionView::FullAccess ) }) .map(|key| key.public_key) .find_map(|public_key| { let keyring = keyring::Entry::new(&service_name, &format!("{account_id}:{public_key}")) .ok()?; keyring.get_password().ok() }) .wrap_err("No access keys found in keychain")? }; Ok(password) } pub fn get_account_key_pair_from_legacy_keychain( network_config: &crate::config::NetworkConfig, account_id: &near_primitives::types::AccountId, credentials_home_dir: &std::path::Path, ) -> color_eyre::eyre::Result<crate::transaction_signature_options::AccountKeyPair> { let data_path = get_account_key_pair_data_path(network_config, account_id, credentials_home_dir)?; let data = std::fs::read_to_string(&data_path).wrap_err("Access key file not found!")?; let account_key_pair: crate::transaction_signature_options::AccountKeyPair = serde_json::from_str(&data) .wrap_err_with(|| format!("Error reading data from file: {:?}", &data_path))?; Ok(account_key_pair) } fn get_account_key_pair_data_path( network_config: &crate::config::NetworkConfig, account_id: &near_primitives::types::AccountId, credentials_home_dir: &std::path::Path, ) -> color_eyre::eyre::Result<std::path::PathBuf> { let check_if_seed_phrase_exists = false; get_account_properties_data_path( network_config, account_id, credentials_home_dir, check_if_seed_phrase_exists, ) } #[tracing::instrument( name = "Receiving the account key pair from a legacy keychain ...", skip_all )] pub fn get_account_properties_data_path( network_config: &crate::config::NetworkConfig, account_id: &near_primitives::types::AccountId, credentials_home_dir: &std::path::Path, check_if_seed_phrase_exists: bool, ) -> color_eyre::eyre::Result<std::path::PathBuf> { tracing::info!(target: "near_teach_me", "Receiving the account key pair from a legacy keychain ..."); let file_name = format!("{account_id}.json"); let mut path = std::path::PathBuf::from(credentials_home_dir); let dir_name = network_config.network_name.clone(); path.push(&dir_name); path.push(file_name); if path.exists() { if !check_if_seed_phrase_exists { return Ok(path); } let data = std::fs::read_to_string(&path).wrap_err_with(|| { format!( "Access key file for account <{}> on network <{}> not found!", account_id, network_config.network_name ) })?; if serde_json::from_str::<crate::common::KeyPairProperties>(&data).is_ok() { return Ok(path); } } let access_key_list = network_config .json_rpc_client() .blocking_call_view_access_key_list( account_id, near_primitives::types::Finality::Final.into(), ) .wrap_err_with(|| format!("Failed to fetch access KeyList for {account_id}"))? .access_key_list_view()?; let mut path = std::path::PathBuf::from(credentials_home_dir); path.push(dir_name); path.push(account_id.to_string()); let mut data_path = std::path::PathBuf::new(); for access_key in access_key_list.keys { let account_public_key = access_key.public_key.to_string().replace(':', "_"); match &access_key.access_key.permission { near_primitives::views::AccessKeyPermissionView::FullAccess => {} near_primitives::views::AccessKeyPermissionView::FunctionCall { .. } => { continue; } } let dir = path .read_dir() .wrap_err("There are no access keys found in the keychain for the account.")?; for entry in dir.flatten() { if entry .path() .file_stem() .unwrap() .to_str() .unwrap() .contains(&account_public_key) { data_path.push(entry.path()); if !check_if_seed_phrase_exists { return Ok(data_path); } let data = std::fs::read_to_string(&data_path).wrap_err("Access key file not found!")?; serde_json::from_str::<crate::common::KeyPairProperties>(&data).wrap_err_with(|| format!( "There are no master seed phrase in keychain to export for account <{account_id}>." ))?; return Ok(data_path); } } } Err(color_eyre::eyre::Report::msg(format!( "There are no access keys in keychain to export for account <{account_id}> on network <{}>.", network_config.network_name ))) }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/export_account/using_web_wallet/mod.rs
src/commands/account/export_account/using_web_wallet/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::ExportAccountContext)] #[interactive_clap(output_context = ExportAccountFromWebWalletContext)] pub struct ExportAccountFromWebWallet { #[interactive_clap(named_arg)] /// Select network network_config: crate::network::Network, } #[derive(Clone)] pub struct ExportAccountFromWebWalletContext(crate::network::NetworkContext); impl ExportAccountFromWebWalletContext { pub fn from_previous_context( previous_context: super::ExportAccountContext, _scope: &<ExportAccountFromWebWallet as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let config = previous_context.global_context.config.clone(); let account_id = previous_context.account_id.clone(); let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback = std::sync::Arc::new({ move |network_config| { if let Ok(account_key_pair) = super::get_account_key_pair_from_keychain(network_config, &account_id) { return auto_import_secret_key( network_config, &account_id, &account_key_pair.private_key, ); } let account_key_pair = super::get_account_key_pair_from_legacy_keychain( network_config, &account_id, &config.credentials_home_dir, )?; auto_import_secret_key( network_config, &account_id, &account_key_pair.private_key, ) } }); Ok(Self(crate::network::NetworkContext { config: previous_context.global_context.config, interacting_with_account_ids: vec![previous_context.account_id], on_after_getting_network_callback, })) } } impl From<ExportAccountFromWebWalletContext> for crate::network::NetworkContext { fn from(item: ExportAccountFromWebWalletContext) -> Self { item.0 } } fn auto_import_secret_key( network_config: &crate::config::NetworkConfig, account_id: &near_primitives::types::AccountId, private_key: &near_crypto::SecretKey, ) -> crate::CliResult { let mut url: url::Url = network_config.wallet_url.join("auto-import-secret-key")?; let fragment = format!("{account_id}/{private_key}"); url.set_fragment(Some(&fragment)); eprintln!( "If your browser doesn't automatically open, please visit this URL:\n {}\n", &url.as_str() ); // url.open(); open::that(url.as_ref()).ok(); Ok(()) }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/export_account/using_private_key/mod.rs
src/commands/account/export_account/using_private_key/mod.rs
use color_eyre::eyre::WrapErr; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::ExportAccountContext)] #[interactive_clap(output_context = ExportAccountFromPrivateKeyContext)] pub struct ExportAccountFromPrivateKey { #[interactive_clap(named_arg)] /// Select network network_config: crate::network::Network, } #[derive(Clone)] pub struct ExportAccountFromPrivateKeyContext(crate::network::NetworkContext); impl ExportAccountFromPrivateKeyContext { pub fn from_previous_context( previous_context: super::ExportAccountContext, _scope: &<ExportAccountFromPrivateKey as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let config = previous_context.global_context.config.clone(); let account_id = previous_context.account_id.clone(); let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback = std::sync::Arc::new({ move |network_config| { if let Ok(account_key_pair) = super::get_account_key_pair_from_keychain(network_config, &account_id) { println!( "Here is the private key for account <{}>: {}", account_id, account_key_pair.private_key, ); return Ok(()); } let account_key_pair = super::get_account_key_pair_from_legacy_keychain( network_config, &account_id, &config.credentials_home_dir, ) .wrap_err_with(|| { format!("There are no access keys in keychain to export for account <{account_id}>.") })?; println!( "Here is the private key for account <{}>: {}", account_id, account_key_pair.private_key, ); Ok(()) } }); Ok(Self(crate::network::NetworkContext { config: previous_context.global_context.config, interacting_with_account_ids: vec![previous_context.account_id], on_after_getting_network_callback, })) } } impl From<ExportAccountFromPrivateKeyContext> for crate::network::NetworkContext { fn from(item: ExportAccountFromPrivateKeyContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/export_account/using_seed_phrase/mod.rs
src/commands/account/export_account/using_seed_phrase/mod.rs
use color_eyre::eyre::WrapErr; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::ExportAccountContext)] #[interactive_clap(output_context = ExportAccountFromSeedPhraseContext)] pub struct ExportAccountFromSeedPhrase { #[interactive_clap(named_arg)] /// Select network network_config: crate::network::Network, } #[derive(Clone)] pub struct ExportAccountFromSeedPhraseContext(crate::network::NetworkContext); impl ExportAccountFromSeedPhraseContext { pub fn from_previous_context( previous_context: super::ExportAccountContext, _scope: &<ExportAccountFromSeedPhrase as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let config = previous_context.global_context.config.clone(); let account_id = previous_context.account_id.clone(); let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback = std::sync::Arc::new({ move |network_config| { if let Ok(password) = super::get_password_from_keychain(network_config, &account_id) { if let Ok(key_pair_properties) = serde_json::from_str::<crate::common::KeyPairProperties>(&password) { println!( "Here is the secret recovery seed phrase for account <{}>: \"{}\" (HD Path: {}).", account_id, key_pair_properties.master_seed_phrase, key_pair_properties.seed_phrase_hd_path ); return Ok(()); } } let data_path = get_seed_phrase_data_path( network_config, &account_id, &config.credentials_home_dir, )?; let data = std::fs::read_to_string(&data_path) .wrap_err("Access key file not found!")?; let key_pair_properties: crate::common::KeyPairProperties = serde_json::from_str(&data).wrap_err_with(|| { format!("Error reading data from file: {:?}", &data_path) })?; println!( "Here is the secret recovery seed phrase for account <{}>: \"{}\" (HD Path: {}).", account_id, key_pair_properties.master_seed_phrase, key_pair_properties.seed_phrase_hd_path ); Ok(()) } }); Ok(Self(crate::network::NetworkContext { config: previous_context.global_context.config, interacting_with_account_ids: vec![previous_context.account_id], on_after_getting_network_callback, })) } } impl From<ExportAccountFromSeedPhraseContext> for crate::network::NetworkContext { fn from(item: ExportAccountFromSeedPhraseContext) -> Self { item.0 } } fn get_seed_phrase_data_path( network_config: &crate::config::NetworkConfig, account_id: &near_primitives::types::AccountId, credentials_home_dir: &std::path::Path, ) -> color_eyre::eyre::Result<std::path::PathBuf> { let check_if_seed_phrase_exists = true; super::get_account_properties_data_path( network_config, account_id, credentials_home_dir, check_if_seed_phrase_exists, ) }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/delete_key/public_keys_to_delete.rs
src/commands/account/delete_key/public_keys_to_delete.rs
use color_eyre::owo_colors::OwoColorize; use inquire::ui::{Color, RenderConfig, Styled}; use inquire::{formatter::MultiOptionFormatter, CustomType, MultiSelect}; use crate::common::JsonRpcClientExt; use crate::common::RpcQueryResponseExt; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::DeleteKeysCommandContext)] #[interactive_clap(output_context = PublicKeyListContext)] pub struct PublicKeyList { #[interactive_clap(skip_default_input_arg)] /// Enter the public keys you wish to delete (separated by comma): public_keys: crate::types::public_key_list::PublicKeyList, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Debug, Clone)] pub struct PublicKeyListContext { global_context: crate::GlobalContext, owner_account_id: near_primitives::types::AccountId, public_keys: Vec<near_crypto::PublicKey>, } impl PublicKeyListContext { pub fn from_previous_context( previous_context: super::DeleteKeysCommandContext, scope: &<PublicKeyList as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, owner_account_id: previous_context.owner_account_id, public_keys: scope.public_keys.clone().into(), }) } } impl From<PublicKeyListContext> for crate::commands::ActionContext { fn from(item: PublicKeyListContext) -> Self { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let owner_account_id = item.owner_account_id.clone(); move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: owner_account_id.clone(), receiver_id: owner_account_id.clone(), actions: item .public_keys .clone() .into_iter() .map(|public_key| { near_primitives::transaction::Action::DeleteKey(Box::new( near_primitives::transaction::DeleteKeyAction { public_key }, )) }) .collect(), }) } }); Self { global_context: item.global_context, interacting_with_account_ids: vec![item.owner_account_id], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback: std::sync::Arc::new( |_outcome_view, _network_config| Ok(()), ), } } } impl PublicKeyList { fn input_public_keys_manually( ) -> color_eyre::eyre::Result<Option<crate::types::public_key_list::PublicKeyList>> { Ok(Some( CustomType::new("Enter a comma-separated list of public keys you want to delete (for example, ed25519:FAXX...RUQa, ed25519:FgVF...oSWJ, ...):") .prompt()?, )) } pub fn input_public_keys( context: &super::DeleteKeysCommandContext, ) -> color_eyre::eyre::Result<Option<crate::types::public_key_list::PublicKeyList>> { if context.global_context.offline { return Self::input_public_keys_manually(); } let mut access_key_list: Vec<AccessKeyInfo> = vec![]; let mut processed_network: Vec<String> = vec![]; let mut errors: Vec<String> = vec![]; for (_, network_config) in context.global_context.config.network_connection.iter() { if processed_network.contains(&network_config.network_name) { continue; } match network_config .json_rpc_client() .blocking_call_view_access_key_list( &context.owner_account_id, near_primitives::types::Finality::Final.into(), ) { Ok(rpc_query_response) => { let access_key_list_for_network = rpc_query_response.access_key_list_view()?; access_key_list.extend(access_key_list_for_network.keys.iter().map( |access_key_info_view| AccessKeyInfo { public_key: access_key_info_view.public_key.clone(), permission: access_key_info_view.access_key.permission.clone(), network_name: network_config.network_name.clone(), }, )); processed_network.push(network_config.network_name.to_string()); } Err(err) => { errors.push(err.to_string()); } } } if access_key_list.is_empty() { for error in errors { println!("WARNING! {error}"); } println!("Automatic search of access keys for <{}> is not possible on [{}] network(s).\nYou can enter access keys to remove manually.", context.owner_account_id, context.global_context.config.network_names().join(", ")); return Self::input_public_keys_manually(); } let formatter: MultiOptionFormatter<'_, AccessKeyInfo> = &|a| { let public_key_list = a .iter() .map(|list_option| list_option.value.to_string()) .collect::<Vec<_>>(); public_key_list.join("\n").to_string() }; let selected_public_keys = MultiSelect::new( "Select the public keys you want to delete:", access_key_list, ) .with_render_config(get_multi_select_render_config()) .with_formatter(formatter) .with_validator( |list: &[inquire::list_option::ListOption<&AccessKeyInfo>]| { if list.is_empty() { Ok(inquire::validator::Validation::Invalid( inquire::validator::ErrorMessage::Custom( "At least one key must be selected (use space to select)".to_string(), ), )) } else { Ok(inquire::validator::Validation::Valid) } }, ) .prompt()? .iter() .map(|access_key_info| access_key_info.public_key.clone()) .collect::<Vec<_>>(); Ok(Some(selected_public_keys.into())) } } #[derive(Debug, Clone)] struct AccessKeyInfo { public_key: near_crypto::PublicKey, permission: near_primitives::views::AccessKeyPermissionView, network_name: String, } impl std::fmt::Display for AccessKeyInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.permission { near_primitives::views::AccessKeyPermissionView::FullAccess => { write!( f, "{} {}\t{}", self.network_name.blue(), self.public_key.yellow(), "full access".yellow() ) } near_primitives::views::AccessKeyPermissionView::FunctionCall { allowance, receiver_id, method_names, } => { let allowance_message = match allowance { Some(amount) => format!("with a remaining fee allowance of {}", amount), None => "with no limit".to_string(), }; if method_names.is_empty() { write!( f, "{} {}\t{} {} {}", self.network_name.blue(), self.public_key.green(), "call any function on".green(), receiver_id.green(), allowance_message.green() ) } else { write!( f, "{} {}\t{} {:?} {} {} {}", self.network_name.blue(), self.public_key.green(), "call".green(), method_names.green(), "function(s) on".green(), receiver_id.green(), allowance_message.green() ) } } } } } fn get_multi_select_render_config() -> RenderConfig<'static> { let mut render_config = crate::get_global_render_config(); render_config.highlighted_option_prefix = Styled::new(">").with_fg(Color::DarkGreen); render_config.unhighlighted_option_prefix = Styled::new(" ").with_fg(Color::DarkGrey); render_config.scroll_up_prefix = Styled::new("↑").with_fg(Color::DarkGrey); render_config.scroll_down_prefix = Styled::new("↓").with_fg(Color::DarkGrey); render_config }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/delete_key/mod.rs
src/commands/account/delete_key/mod.rs
mod public_keys_to_delete; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = DeleteKeysCommandContext)] pub struct DeleteKeysCommand { #[interactive_clap(skip_default_input_arg)] /// Which account should you delete the access key for? owner_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Specify public keys you wish to delete public_keys: self::public_keys_to_delete::PublicKeyList, } #[derive(Debug, Clone)] pub struct DeleteKeysCommandContext { global_context: crate::GlobalContext, owner_account_id: near_primitives::types::AccountId, } impl DeleteKeysCommandContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<DeleteKeysCommand as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context, owner_account_id: scope.owner_account_id.clone().into(), }) } } impl DeleteKeysCommand { pub fn input_owner_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_signer_account_id_from_used_account_list( &context.config.credentials_home_dir, "Which account should you delete the access key for?", ) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/mod.rs
src/commands/account/create_account/mod.rs
#![allow(clippy::enum_variant_names, clippy::large_enum_variant)] use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod create_implicit_account; mod fund_myself_create_account; pub mod sponsor_by_faucet_service; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] pub struct CreateAccount { #[interactive_clap(subcommand)] account_actions: CoverCostsCreateAccount, } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = CoverCostsCreateAccountContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// How do you cover the costs of account creation? pub enum CoverCostsCreateAccount { #[strum_discriminants(strum( message = "sponsor-by-faucet-service - I would like the faucet service sponsor to cover the cost of creating an account (testnet only for now)" ))] /// I would like the faucet service sponsor to cover the cost of creating an account (testnet only for now) SponsorByFaucetService(self::sponsor_by_faucet_service::NewAccount), #[strum_discriminants(strum( message = "fund-myself - I would like fund myself to cover the cost of creating an account" ))] /// I would like fund myself to cover the cost of creating an account FundMyself(self::fund_myself_create_account::NewAccount), #[strum_discriminants(strum( message = "fund-later - Create an implicit-account" ))] /// Create an implicit-account FundLater(self::create_implicit_account::ImplicitAccount), } #[derive(Debug, Clone)] pub struct CoverCostsCreateAccountContext(crate::GlobalContext); impl CoverCostsCreateAccountContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<CoverCostsCreateAccount as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { match scope { CoverCostsCreateAccountDiscriminants::SponsorByFaucetService => { if previous_context.offline { Err(color_eyre::Report::msg( "Error: Creating an account with a faucet sponsor is not possible offline.", )) } else { Ok(Self(previous_context)) } } _ => Ok(Self(previous_context)), } } } impl From<CoverCostsCreateAccountContext> for crate::GlobalContext { fn from(item: CoverCostsCreateAccountContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/fund_myself_create_account/mod.rs
src/commands/account/create_account/fund_myself_create_account/mod.rs
use inquire::{CustomType, Select}; use crate::commands::account::MIN_ALLOWED_TOP_LEVEL_ACCOUNT_LENGTH; mod add_key; mod sign_as; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = NewAccountContext)] pub struct NewAccount { #[interactive_clap(skip_default_input_arg)] /// What is the new account ID? new_account_id: crate::types::account_id::AccountId, #[interactive_clap(skip_default_input_arg)] /// Enter the amount for the account: initial_balance: crate::types::near_token::NearToken, #[interactive_clap(subcommand)] access_key_mode: add_key::AccessKeyMode, } #[derive(Debug, Clone)] pub struct NewAccountContext { global_context: crate::GlobalContext, new_account_id: near_primitives::types::AccountId, initial_balance: crate::types::near_token::NearToken, } impl NewAccountContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<NewAccount as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context, new_account_id: scope.new_account_id.clone().into(), initial_balance: scope.initial_balance, }) } } impl NewAccount { pub fn input_new_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { loop { let new_account_id: crate::types::account_id::AccountId = CustomType::new("What is the new account ID?").prompt()?; if context.offline { return Ok(Some(new_account_id)); } #[derive(derive_more::Display)] enum ConfirmOptions { #[display("Yes, I want to check that <{account_id}> account does not exist. (It is free of charge, and only requires Internet access)")] Yes { account_id: crate::types::account_id::AccountId, }, #[display("No, I know that this account does not exist and I want to proceed.")] No, } let select_choose_input = Select::new("\nDo you want to check the existence of the specified account so that you don’t waste tokens with sending a transaction that won't succeed?", vec![ConfirmOptions::Yes{account_id: new_account_id.clone()}, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes { account_id } = select_choose_input { let network = crate::common::find_network_where_account_exist( context, account_id.clone().into(), )?; if let Some(network_config) = network { eprintln!( "\nHeads up! You will only waste tokens if you proceed creating <{}> account on <{}> as the account already exists.", &account_id, network_config.network_name ); if !crate::common::ask_if_different_account_id_wanted()? { return Ok(Some(account_id)); }; } else if account_id.0.as_str().chars().count() < MIN_ALLOWED_TOP_LEVEL_ACCOUNT_LENGTH && account_id.0.is_top_level() { eprintln!( "\nAccount <{}> has <{}> character count. Only the registrar account can create new top level accounts that are shorter than {} characters. Read more about it in nomicon: https://nomicon.io/DataStructures/Account#top-level-accounts", &account_id, &account_id.0.as_str().chars().count(), MIN_ALLOWED_TOP_LEVEL_ACCOUNT_LENGTH, ); if !crate::common::ask_if_different_account_id_wanted()? { return Ok(Some(account_id)); }; } else { let parent_account_id = account_id.clone().get_parent_account_id_from_sub_account(); if !near_primitives::types::AccountId::from(parent_account_id.clone()) .is_top_level() { if crate::common::find_network_where_account_exist( context, parent_account_id.clone().into(), )? .is_none() { eprintln!("\nThe parent account <{}> does not exist on [{}] networks. Therefore, you cannot create an account <{}>.", parent_account_id, context.config.network_names().join(", "), account_id ); if !crate::common::ask_if_different_account_id_wanted()? { return Ok(Some(account_id)); }; } else { return Ok(Some(account_id)); } } else { return Ok(Some(account_id)); } }; } else { return Ok(Some(new_account_id)); }; } } fn input_initial_balance( _context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::near_token::NearToken>> { Ok(Some( CustomType::new("Enter the amount of NEAR tokens you want to fund the new account with (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear):") .with_starting_input("0.1 NEAR") .prompt()? )) } } #[derive(Clone)] pub struct AccountPropertiesContext { pub global_context: crate::GlobalContext, pub account_properties: AccountProperties, pub on_before_sending_transaction_callback: crate::transaction_signature_options::OnBeforeSendingTransactionCallback, } #[derive(Debug, Clone)] pub struct AccountProperties { pub new_account_id: near_primitives::types::AccountId, pub public_key: near_crypto::PublicKey, pub initial_balance: crate::types::near_token::NearToken, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/fund_myself_create_account/add_key/mod.rs
src/commands/account/create_account/fund_myself_create_account/add_key/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; pub mod autogenerate_new_keypair; #[cfg(feature = "ledger")] mod use_ledger; mod use_manually_provided_seed_phrase; mod use_public_key; #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::NewAccountContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Add an access key for this account: pub enum AccessKeyMode { #[strum_discriminants(strum( message = "autogenerate-new-keypair - Automatically generate a key pair" ))] /// Automatically generate a key pair AutogenerateNewKeypair(self::autogenerate_new_keypair::GenerateKeypair), #[strum_discriminants(strum( message = "use-manually-provided-seed-prase - Use the provided seed phrase manually" ))] /// Use the provided seed phrase manually UseManuallyProvidedSeedPhrase( self::use_manually_provided_seed_phrase::AddAccessWithSeedPhraseAction, ), #[strum_discriminants(strum( message = "use-manually-provided-public-key - Use the provided public key manually" ))] /// Use the provided public key manually UseManuallyProvidedPublicKey(self::use_public_key::AddPublicKeyAction), #[cfg(feature = "ledger")] #[strum_discriminants(strum(message = "use-ledger - Use a ledger"))] /// Use a ledger UseLedger(self::use_ledger::AddAccessWithLedger), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/fund_myself_create_account/add_key/use_manually_provided_seed_phrase/mod.rs
src/commands/account/create_account/fund_myself_create_account/add_key/use_manually_provided_seed_phrase/mod.rs
use std::str::FromStr; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::NewAccountContext)] #[interactive_clap(output_context = AddAccessWithSeedPhraseActionContext)] pub struct AddAccessWithSeedPhraseAction { /// Enter the seed-phrase for this sub-account: master_seed_phrase: String, #[interactive_clap(named_arg)] /// What is the signer account ID? sign_as: super::super::sign_as::SignerAccountId, } #[derive(Clone)] struct AddAccessWithSeedPhraseActionContext(super::super::AccountPropertiesContext); impl AddAccessWithSeedPhraseActionContext { pub fn from_previous_context( previous_context: super::super::NewAccountContext, scope: &<AddAccessWithSeedPhraseAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { // This is the HD path that is used in NEAR Wallet for plaintext seed phrase generation and, subsequently, for account recovery by a seed phrase. let near_wallet_seed_phrase_hd_path_default = slipped10::BIP32Path::from_str("m/44'/397'/0'").unwrap(); let public_key = crate::common::get_public_key_from_seed_phrase( near_wallet_seed_phrase_hd_path_default, &scope.master_seed_phrase, )?; let account_properties = super::super::AccountProperties { new_account_id: previous_context.new_account_id, initial_balance: previous_context.initial_balance, public_key, }; Ok(Self(super::super::AccountPropertiesContext { global_context: previous_context.global_context, account_properties, on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), })) } } impl From<AddAccessWithSeedPhraseActionContext> for super::super::AccountPropertiesContext { fn from(item: AddAccessWithSeedPhraseActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/fund_myself_create_account/add_key/autogenerate_new_keypair/mod.rs
src/commands/account/create_account/fund_myself_create_account/add_key/autogenerate_new_keypair/mod.rs
use std::str::FromStr; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::super::NewAccountContext)] #[interactive_clap(output_context = GenerateKeypairContext)] pub struct GenerateKeypair { #[interactive_clap(subcommand)] save_mode: SaveMode, } #[derive(Debug, Clone)] pub struct GenerateKeypairContext { global_context: crate::GlobalContext, account_properties: super::super::AccountProperties, key_pair_properties: crate::common::KeyPairProperties, } impl GenerateKeypairContext { pub fn from_previous_context( previous_context: super::super::NewAccountContext, _scope: &<GenerateKeypair as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let key_pair_properties: crate::common::KeyPairProperties = crate::common::generate_keypair()?; let public_key = near_crypto::PublicKey::from_str(&key_pair_properties.public_key_str)?; let account_properties = super::super::AccountProperties { new_account_id: previous_context.new_account_id, initial_balance: previous_context.initial_balance, public_key, }; Ok(Self { global_context: previous_context.global_context, account_properties, key_pair_properties, }) } } impl From<GenerateKeypairContext> for super::super::AccountPropertiesContext { fn from(item: GenerateKeypairContext) -> Self { Self { global_context: item.global_context, account_properties: item.account_properties, on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), } } } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = GenerateKeypairContext)] #[interactive_clap(output_context = SaveModeContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Save an access key for this account: pub enum SaveMode { #[strum_discriminants(strum( message = "save-to-keychain - Save automatically generated key pair to keychain" ))] /// Save automatically generated key pair to keychain SaveToKeychain(SignAs), #[strum_discriminants(strum( message = "save-to-legacy-keychain - Save automatically generated key pair to the legacy keychain (compatible with JS CLI)" ))] /// Save automatically generated key pair to the legacy keychain (compatible with JS CLI) SaveToLegacyKeychain(SignAs), #[strum_discriminants(strum( message = "print-to-terminal - Print automatically generated key pair in terminal" ))] /// Print automatically generated key pair in terminal PrintToTerminal(SignAs), } #[derive(Clone)] pub struct SaveModeContext(super::super::AccountPropertiesContext); impl SaveModeContext { pub fn from_previous_context( previous_context: GenerateKeypairContext, scope: &<SaveMode as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let scope = *scope; let on_before_sending_transaction_callback: crate::transaction_signature_options::OnBeforeSendingTransactionCallback = std::sync::Arc::new({ let new_account_id = previous_context.account_properties.new_account_id.clone(); let key_pair_properties = previous_context.key_pair_properties.clone(); let credentials_home_dir = previous_context.global_context.config.credentials_home_dir.clone(); move |_transaction, network_config| { match scope { SaveModeDiscriminants::SaveToKeychain => { let key_pair_properties_buf = serde_json::to_string(&key_pair_properties)?; crate::common::save_access_key_to_keychain_or_save_to_legacy_keychain( network_config.clone(), credentials_home_dir.clone(), &key_pair_properties_buf, &key_pair_properties.public_key_str, new_account_id.as_ref(), ) } SaveModeDiscriminants::SaveToLegacyKeychain => { let key_pair_properties_buf = serde_json::to_string(&key_pair_properties)?; crate::common::save_access_key_to_legacy_keychain( network_config.clone(), credentials_home_dir.clone(), &key_pair_properties_buf, &key_pair_properties.public_key_str, new_account_id.as_ref(), ) } SaveModeDiscriminants::PrintToTerminal => { Ok(format!( "\n-------------------- Access key info ------------------ \nMaster Seed Phrase: {}\nSeed Phrase HD Path: {}\nImplicit Account ID: {}\nPublic Key: {}\nSECRET KEYPAIR: {} \n--------------------------------------------------------", key_pair_properties.master_seed_phrase, key_pair_properties.seed_phrase_hd_path, key_pair_properties.implicit_account_id, key_pair_properties.public_key_str, key_pair_properties.secret_keypair_str, )) } } } }); Ok(Self(super::super::AccountPropertiesContext { global_context: previous_context.global_context, account_properties: previous_context.account_properties, on_before_sending_transaction_callback, })) } } impl From<SaveModeContext> for super::super::AccountPropertiesContext { fn from(item: SaveModeContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::AccountPropertiesContext)] pub struct SignAs { #[interactive_clap(named_arg)] /// What is the signer account ID? sign_as: super::super::sign_as::SignerAccountId, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/fund_myself_create_account/add_key/use_public_key/mod.rs
src/commands/account/create_account/fund_myself_create_account/add_key/use_public_key/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::NewAccountContext)] #[interactive_clap(output_context = AddPublicKeyActionContext)] pub struct AddPublicKeyAction { /// Enter the public key for this account: public_key: crate::types::public_key::PublicKey, #[interactive_clap(named_arg)] /// What is the signer account ID? sign_as: super::super::sign_as::SignerAccountId, } #[derive(Clone)] pub struct AddPublicKeyActionContext(super::super::AccountPropertiesContext); impl AddPublicKeyActionContext { pub fn from_previous_context( previous_context: super::super::NewAccountContext, scope: &<AddPublicKeyAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let account_properties = super::super::AccountProperties { new_account_id: previous_context.new_account_id, initial_balance: previous_context.initial_balance, public_key: scope.public_key.clone().into(), }; Ok(Self(super::super::AccountPropertiesContext { global_context: previous_context.global_context, account_properties, on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), })) } } impl From<AddPublicKeyActionContext> for super::super::AccountPropertiesContext { fn from(item: AddPublicKeyActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/fund_myself_create_account/add_key/use_ledger/mod.rs
src/commands/account/create_account/fund_myself_create_account/add_key/use_ledger/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::NewAccountContext)] #[interactive_clap(output_context = AddAccessWithLedgerContext)] pub struct AddAccessWithLedger { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] seed_phrase_hd_path: crate::types::slip10::BIP32Path, #[interactive_clap(named_arg)] /// What is the signer account ID? sign_as: super::super::sign_as::SignerAccountId, } #[derive(Clone)] pub struct AddAccessWithLedgerContext(super::super::AccountPropertiesContext); impl AddAccessWithLedgerContext { pub fn from_previous_context( previous_context: super::super::NewAccountContext, scope: &<AddAccessWithLedger as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let seed_phrase_hd_path = scope.seed_phrase_hd_path.clone(); eprintln!("Opening the NEAR application... Please approve opening the application"); near_ledger::open_near_application().map_err(|ledger_error| { color_eyre::Report::msg(format!("An error happened while trying to open the NEAR application on the ledger: {ledger_error:?}")) })?; std::thread::sleep(std::time::Duration::from_secs(1)); eprintln!( "Please allow getting the PublicKey on Ledger device (HD Path: {seed_phrase_hd_path})" ); let public_key = near_ledger::get_public_key(seed_phrase_hd_path.into()).map_err( |near_ledger_error| { color_eyre::Report::msg(format!( "An error occurred while trying to get PublicKey from Ledger device: {near_ledger_error:?}" )) }, )?; let public_key = near_crypto::PublicKey::ED25519(near_crypto::ED25519PublicKey::from( public_key.to_bytes(), )); let account_properties = super::super::AccountProperties { new_account_id: previous_context.new_account_id, initial_balance: previous_context.initial_balance, public_key, }; Ok(Self(super::super::AccountPropertiesContext { global_context: previous_context.global_context, account_properties, on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), })) } } impl From<AddAccessWithLedgerContext> for super::super::AccountPropertiesContext { fn from(item: AddAccessWithLedgerContext) -> Self { item.0 } } impl AddAccessWithLedger { pub fn input_seed_phrase_hd_path( _context: &super::super::NewAccountContext, ) -> color_eyre::eyre::Result<Option<crate::types::slip10::BIP32Path>> { crate::transaction_signature_options::sign_with_ledger::input_seed_phrase_hd_path() } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/fund_myself_create_account/sign_as/mod.rs
src/commands/account/create_account/fund_myself_create_account/sign_as/mod.rs
use serde_json::json; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::AccountPropertiesContext)] #[interactive_clap(output_context = SignerAccountIdContext)] pub struct SignerAccountId { #[interactive_clap(skip_default_input_arg)] /// What is the signer account ID? signer_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Clone)] pub struct SignerAccountIdContext { global_context: crate::GlobalContext, account_properties: super::AccountProperties, signer_account_id: near_primitives::types::AccountId, on_before_sending_transaction_callback: crate::transaction_signature_options::OnBeforeSendingTransactionCallback, } impl SignerAccountIdContext { pub fn from_previous_context( previous_context: super::AccountPropertiesContext, scope: &<SignerAccountId as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, account_properties: previous_context.account_properties, signer_account_id: scope.signer_account_id.clone().into(), on_before_sending_transaction_callback: previous_context .on_before_sending_transaction_callback, }) } } impl From<SignerAccountIdContext> for crate::commands::ActionContext { fn from(item: SignerAccountIdContext) -> Self { let global_context = item.global_context.clone(); let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let new_account_id = item.account_properties.new_account_id.clone(); let signer_id = item.signer_account_id.clone(); move |network_config| { if new_account_id.as_str().chars().count() < super::MIN_ALLOWED_TOP_LEVEL_ACCOUNT_LENGTH && new_account_id.is_top_level() { return color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!( "\nAccount <{}> has <{}> character count. Only REGISTRAR_ACCOUNT_ID account can create new top level accounts that are shorter than MIN_ALLOWED_TOP_LEVEL_ACCOUNT_LENGTH (32) characters.", new_account_id, new_account_id.as_str().chars().count() )); } if !item.global_context.offline { validate_new_account_id(network_config, &new_account_id)?; } let (actions, receiver_id) = if new_account_id.is_sub_account_of(&signer_id) { (vec![ near_primitives::transaction::Action::CreateAccount( near_primitives::transaction::CreateAccountAction {}, ), near_primitives::transaction::Action::Transfer( near_primitives::transaction::TransferAction { deposit: item.account_properties.initial_balance.into(), }, ), near_primitives::transaction::Action::AddKey( Box::new(near_primitives::transaction::AddKeyAction { public_key: item.account_properties.public_key.clone(), access_key: near_primitives::account::AccessKey { nonce: 0, permission: near_primitives::account::AccessKeyPermission::FullAccess, }, }), ), ], new_account_id.clone()) } else { let args = serde_json::to_vec(&json!({ "new_account_id": new_account_id.clone().to_string(), "new_public_key": item.account_properties.public_key.to_string() }))?; if let Some(linkdrop_account_id) = &network_config.linkdrop_account_id { if new_account_id.is_sub_account_of(linkdrop_account_id) || new_account_id.is_top_level() { ( vec![near_primitives::transaction::Action::FunctionCall( Box::new( near_primitives::transaction::FunctionCallAction { method_name: "create_account".to_string(), args, gas: near_primitives::gas::Gas::from_teragas(30), deposit: item .account_properties .initial_balance.into(), }, ), )], linkdrop_account_id.clone(), ) } else { return color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!( "\nSigner account <{}> does not have permission to create account <{}>.", signer_id, new_account_id )); } } else { return color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!( "\nAccount <{}> cannot be created on network <{}> because a <linkdrop_account_id> is not specified in the configuration file.\nYou can learn about working with the configuration file: https://github.com/near/near-cli-rs/blob/master/docs/README.en.md#config. \nExample <linkdrop_account_id> in configuration file: https://github.com/near/near-cli-rs/blob/master/docs/media/linkdrop account_id.png", new_account_id, network_config.network_name )); } }; Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_id.clone(), receiver_id, actions, }) } }); let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = std::sync::Arc::new({ let credentials_home_dir = global_context.config.credentials_home_dir.clone(); move |outcome_view, _network_config| { crate::common::update_used_account_list_as_signer( &credentials_home_dir, &outcome_view.transaction.receiver_id, ); Ok(()) } }); Self { global_context, interacting_with_account_ids: vec![ item.signer_account_id, item.account_properties.new_account_id, ], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: item.on_before_sending_transaction_callback, on_after_sending_transaction_callback, } } } impl SignerAccountId { fn input_signer_account_id( context: &super::AccountPropertiesContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { let parent_account_id = crate::types::account_id::AccountId::get_parent_account_id_from_sub_account( context.account_properties.new_account_id.clone().into(), ); if !parent_account_id.0.is_top_level() { Ok(Some(parent_account_id)) } else { crate::common::input_signer_account_id_from_used_account_list( &context.global_context.config.credentials_home_dir, "What is the signer account ID?", ) } } } #[tracing::instrument(name = "Validation new account_id ...", skip_all)] fn validate_new_account_id( network_config: &crate::config::NetworkConfig, account_id: &near_primitives::types::AccountId, ) -> crate::CliResult { tracing::info!(target: "near_teach_me", "Validation new account_id ..."); let account_state = tokio::runtime::Runtime::new() .unwrap() .block_on(crate::common::get_account_state( network_config, account_id, near_primitives::types::BlockReference::latest(), )); match account_state { Ok(_) => { color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!( "\nAccount <{}> already exists in network <{}>. Therefore, it is not possible to create an account with this name.", account_id, network_config.network_name )) } Err(crate::common::AccountStateError::Cancel) => { color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!("Operation was canceled by the user")) } Err(crate::common::AccountStateError::JsonRpcError(near_jsonrpc_client::errors::JsonRpcError::ServerError( near_jsonrpc_client::errors::JsonRpcServerError::HandlerError( near_jsonrpc_primitives::types::query::RpcQueryError::UnknownAccount { .. }, )), )) => Ok(()), Err(crate::common::AccountStateError::JsonRpcError(near_jsonrpc_client::errors::JsonRpcError::TransportError(_))) => { tracing::warn!( parent: &tracing::Span::none(), "Transport error.{}", crate::common::indent_payload( "\nIt is currently possible to continue creating an account offline.\nYou can sign and send the created transaction later.\n" ) ); Ok(()) } Err(err) => { color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!("{:?}", err)) } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/create_implicit_account/use_ledger.rs
src/commands/account/create_account/create_implicit_account/use_ledger.rs
use std::io::Write; use color_eyre::eyre::Context; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = SaveWithLedgerContext)] pub struct SaveWithLedger { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] seed_phrase_hd_path: crate::types::slip10::BIP32Path, #[interactive_clap(named_arg)] /// Specify a folder to save the implicit account file save_to_folder: super::SaveToFolder, } #[derive(Clone)] pub struct SaveWithLedgerContext(super::SaveImplicitAccountContext); impl SaveWithLedgerContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<SaveWithLedger as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let on_after_getting_folder_path_callback: super::OnAfterGettingFolderPathCallback = std::sync::Arc::new({ let seed_phrase_hd_path = scope.seed_phrase_hd_path.clone(); move |folder_path| { eprintln!( "Opening the NEAR application... Please approve opening the application" ); near_ledger::open_near_application().map_err(|ledger_error| { color_eyre::Report::msg(format!("An error happened while trying to open the NEAR application on the ledger: {ledger_error:?}")) })?; std::thread::sleep(std::time::Duration::from_secs(1)); eprintln!( "Please allow getting the PublicKey on Ledger device (HD Path: {seed_phrase_hd_path})" ); let public_key = near_ledger::get_public_key(seed_phrase_hd_path.clone().into()) .map_err(|near_ledger_error| { color_eyre::Report::msg(format!( "An error occurred while trying to get PublicKey from Ledger device: {near_ledger_error:?}" )) })?; let public_key_str = format!("ed25519:{}", bs58::encode(&public_key).into_string()); let implicit_account_id = near_primitives::types::AccountId::try_from(hex::encode(public_key))?; let buf = serde_json::json!({ "seed_phrase_hd_path": seed_phrase_hd_path.to_string(), "implicit_account_id": implicit_account_id.to_string(), "public_key": public_key_str, }) .to_string(); let file_name: std::path::PathBuf = format!("{implicit_account_id}.json").into(); let mut file_path = std::path::PathBuf::new(); file_path.push(folder_path); std::fs::create_dir_all(&file_path)?; file_path.push(file_name); std::fs::File::create(&file_path) .wrap_err_with(|| format!("Failed to create file: {file_path:?}"))? .write(buf.as_bytes()) .wrap_err_with(|| format!("Failed to write to file: {file_path:?}"))?; if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = previous_context.verbosity { eprintln!("\nThe file {file_path:?} was saved successfully"); } Ok(()) } }); Ok(Self(super::SaveImplicitAccountContext { config: previous_context.config, on_after_getting_folder_path_callback, })) } } impl From<SaveWithLedgerContext> for super::SaveImplicitAccountContext { fn from(item: SaveWithLedgerContext) -> Self { item.0 } } impl SaveWithLedger { pub fn input_seed_phrase_hd_path( _context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::slip10::BIP32Path>> { crate::transaction_signature_options::sign_with_ledger::input_seed_phrase_hd_path() } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/create_implicit_account/use_auto_generation.rs
src/commands/account/create_account/create_implicit_account/use_auto_generation.rs
use std::io::Write; use color_eyre::eyre::Context; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = SaveWithUseAutoGenerationContext)] pub struct SaveWithUseAutoGeneration { #[interactive_clap(named_arg)] /// Specify a folder to save the implicit account file save_to_folder: super::SaveToFolder, } #[derive(Clone)] struct SaveWithUseAutoGenerationContext(super::SaveImplicitAccountContext); impl SaveWithUseAutoGenerationContext { pub fn from_previous_context( previous_context: crate::GlobalContext, _scope: &<SaveWithUseAutoGeneration as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let on_after_getting_folder_path_callback: super::OnAfterGettingFolderPathCallback = std::sync::Arc::new({ move |folder_path| { let key_pair_properties = crate::common::generate_keypair()?; let buf = serde_json::json!({ "master_seed_phrase": key_pair_properties.master_seed_phrase, "seed_phrase_hd_path": key_pair_properties.seed_phrase_hd_path, "implicit_account_id": key_pair_properties.implicit_account_id, "public_key": key_pair_properties.public_key_str, "private_key": key_pair_properties.secret_keypair_str, }) .to_string(); let mut file_path = std::path::PathBuf::new(); let mut file_name = std::path::PathBuf::new(); file_name.push(format!("{}.json", key_pair_properties.implicit_account_id)); file_path.push(folder_path); std::fs::create_dir_all(&file_path)?; file_path.push(file_name); std::fs::File::create(&file_path) .wrap_err_with(|| format!("Failed to create file: {file_path:?}"))? .write(buf.as_bytes()) .wrap_err_with(|| format!("Failed to write to file: {folder_path:?}"))?; if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = previous_context.verbosity { eprintln!("\nThe file {file_path:?} was saved successfully"); } Ok(()) } }); Ok(Self(super::SaveImplicitAccountContext { config: previous_context.config, on_after_getting_folder_path_callback, })) } } impl From<SaveWithUseAutoGenerationContext> for super::SaveImplicitAccountContext { fn from(item: SaveWithUseAutoGenerationContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/create_implicit_account/mod.rs
src/commands/account/create_account/create_implicit_account/mod.rs
use inquire::CustomType; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod use_auto_generation; #[cfg(feature = "ledger")] mod use_ledger; mod use_seed_phrase; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] pub struct ImplicitAccount { #[interactive_clap(subcommand)] mode: Mode, } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap_derive::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Choose a mode to create an implicit account: pub enum Mode { #[strum_discriminants(strum( message = "use-auto-generation - Use auto-generation to create an implicit account" ))] /// Use auto-generation to create an implicit account UseAutoGeneration(self::use_auto_generation::SaveWithUseAutoGeneration), #[cfg(feature = "ledger")] #[strum_discriminants(strum( message = "use-ledger - Use ledger to create an implicit account" ))] /// Use ledger to create an implicit account UseLedger(self::use_ledger::SaveWithLedger), #[strum_discriminants(strum( message = "use-seed-phrase - Use seed phrase to create an implicit account" ))] /// Use seed phrase to create an implicit account UseSeedPhrase(self::use_seed_phrase::SaveWithSeedPhrase), } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = SaveImplicitAccountContext)] #[interactive_clap(output_context = SaveToFolderContext)] pub struct SaveToFolder { #[interactive_clap(skip_default_input_arg)] /// Enter the file path where to save the implicit account: folder_path: crate::types::path_buf::PathBuf, } #[derive(Clone)] struct SaveToFolderContext; impl SaveToFolderContext { pub fn from_previous_context( previous_context: SaveImplicitAccountContext, scope: &<SaveToFolder as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { (previous_context.on_after_getting_folder_path_callback)( &scope.folder_path.clone().into(), )?; Ok(Self) } } impl SaveToFolder { fn input_folder_path( context: &SaveImplicitAccountContext, ) -> color_eyre::eyre::Result<Option<crate::types::path_buf::PathBuf>> { Ok(Some( CustomType::new("Enter the file path where to save the implicit account:") .with_starting_input(&format!( "{}/implicit", context.config.credentials_home_dir.to_string_lossy() )) .prompt()?, )) } } pub type OnAfterGettingFolderPathCallback = std::sync::Arc<dyn Fn(&std::path::PathBuf) -> crate::CliResult>; #[derive(Clone)] pub struct SaveImplicitAccountContext { config: crate::config::Config, on_after_getting_folder_path_callback: OnAfterGettingFolderPathCallback, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/create_implicit_account/use_seed_phrase.rs
src/commands/account/create_account/create_implicit_account/use_seed_phrase.rs
use std::io::Write; use color_eyre::eyre::Context; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = SaveWithSeedPhraseContext)] pub struct SaveWithSeedPhrase { /// Enter the seed-phrase for this account: master_seed_phrase: String, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] seed_phrase_hd_path: crate::types::slip10::BIP32Path, #[interactive_clap(named_arg)] /// Specify a folder to save the implicit account file save_to_folder: super::SaveToFolder, } #[derive(Clone)] struct SaveWithSeedPhraseContext(super::SaveImplicitAccountContext); impl SaveWithSeedPhraseContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<SaveWithSeedPhrase as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let key_pair_properties: crate::common::KeyPairProperties = crate::common::get_key_pair_properties_from_seed_phrase( scope.seed_phrase_hd_path.clone(), scope.master_seed_phrase.clone(), )?; let on_after_getting_folder_path_callback: super::OnAfterGettingFolderPathCallback = std::sync::Arc::new({ move |folder_path| { let mut file_path = std::path::PathBuf::new(); let mut file_name = std::path::PathBuf::new(); let buf = serde_json::json!({ "master_seed_phrase": key_pair_properties.master_seed_phrase, "seed_phrase_hd_path": key_pair_properties.seed_phrase_hd_path, "implicit_account_id": key_pair_properties.implicit_account_id, "public_key": key_pair_properties.public_key_str, "private_key": key_pair_properties.secret_keypair_str, }) .to_string(); file_name.push(format!("{}.json", key_pair_properties.implicit_account_id)); file_path.push(folder_path); std::fs::create_dir_all(&file_path)?; file_path.push(file_name); std::fs::File::create(&file_path) .wrap_err_with(|| format!("Failed to create file: {file_path:?}"))? .write(buf.as_bytes()) .wrap_err_with(|| format!("Failed to write to file: {file_path:?}"))?; if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = previous_context.verbosity { eprintln!("\nThe file {file_path:?} was saved successfully"); } Ok(()) } }); Ok(Self(super::SaveImplicitAccountContext { config: previous_context.config, on_after_getting_folder_path_callback, })) } } impl From<SaveWithSeedPhraseContext> for super::SaveImplicitAccountContext { fn from(item: SaveWithSeedPhraseContext) -> Self { item.0 } } impl SaveWithSeedPhrase { pub fn input_seed_phrase_hd_path( _context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::slip10::BIP32Path>> { crate::transaction_signature_options::sign_with_seed_phrase::input_seed_phrase_hd_path() } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/sponsor_by_faucet_service/mod.rs
src/commands/account/create_account/sponsor_by_faucet_service/mod.rs
use tracing_indicatif::span_ext::IndicatifSpanExt; pub mod add_key; pub mod network; #[derive(Clone)] pub struct SponsorServiceContext { pub config: crate::config::Config, pub new_account_id: crate::types::account_id::AccountId, pub public_key: near_crypto::PublicKey, pub on_after_getting_network_callback: self::network::OnAfterGettingNetworkCallback, pub on_before_creating_account_callback: self::network::OnBeforeCreatingAccountCallback, } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = NewAccountContext)] pub struct NewAccount { #[interactive_clap(skip_default_input_arg)] /// What is the new account ID? new_account_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] access_key_mode: add_key::AccessKeyMode, } #[derive(Clone)] pub struct NewAccountContext { pub config: crate::config::Config, pub new_account_id: crate::types::account_id::AccountId, pub on_before_creating_account_callback: self::network::OnBeforeCreatingAccountCallback, } impl NewAccountContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<NewAccount as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let credentials_home_dir = previous_context.config.credentials_home_dir.clone(); let on_before_creating_account_callback: self::network::OnBeforeCreatingAccountCallback = std::sync::Arc::new({ move |network_config, new_account_id, public_key, storage_message| { before_creating_account( network_config, new_account_id, public_key, &credentials_home_dir, storage_message, previous_context.verbosity, ) } }); Ok(Self { config: previous_context.config, new_account_id: scope.new_account_id.clone(), on_before_creating_account_callback, }) } } impl NewAccount { fn input_new_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { super::fund_myself_create_account::NewAccount::input_new_account_id(context) } } #[tracing::instrument(name = "Receiving request via faucet service", skip_all)] pub fn before_creating_account( network_config: &crate::config::NetworkConfig, new_account_id: &crate::types::account_id::AccountId, public_key: &near_crypto::PublicKey, credentials_home_dir: &std::path::Path, storage_message: String, verbosity: crate::Verbosity, ) -> crate::CliResult { let faucet_service_url = match &network_config.faucet_url { Some(url) => url, None => return Err(color_eyre::Report::msg(format!( "The <{}> network does not have a faucet (helper service) that can sponsor the creation of an account.", &network_config.network_name ))) }; tracing::Span::current().pb_set_message(faucet_service_url.as_str()); tracing::info!(target: "near_teach_me", "Receiving request via faucet service {}", faucet_service_url.as_str()); let mut data = std::collections::HashMap::new(); data.insert("newAccountId", new_account_id.to_string()); data.insert("newAccountPublicKey", public_key.to_string()); let client = reqwest::blocking::Client::new(); tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "I am making HTTP call to create an account" ); tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "HTTP POST {}", faucet_service_url.as_str() ); tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "JSON Body:\n{}", crate::common::indent_payload(&format!("{data:#?}")) ); let result = client.post(faucet_service_url.clone()).json(&data).send(); print_account_creation_status( result, network_config, new_account_id, credentials_home_dir, storage_message, verbosity, ) } fn print_account_creation_status( result: Result<reqwest::blocking::Response, reqwest::Error>, network_config: &crate::config::NetworkConfig, new_account_id: &crate::types::account_id::AccountId, credentials_home_dir: &std::path::Path, storage_message: String, verbosity: crate::Verbosity, ) -> crate::CliResult { match result { Ok(response) => { tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "JSON RPC Response:\n{}", crate::common::indent_payload(&format!("{response:#?}")) ); if response.status() >= reqwest::StatusCode::BAD_REQUEST { tracing::warn!( parent: &tracing::Span::none(), "{}", crate::common::indent_payload(&format!( "\nThe new account <{new_account_id}> could not be created successfully.\n{storage_message}\n " )) ); return Err(color_eyre::Report::msg(format!( "The faucet (helper service) server failed with status code <{}>", response.status() ))); } let account_creation_transaction = response .json::<near_jsonrpc_client::methods::tx::RpcTransactionResponse>()? .final_execution_outcome .map(|outcome| outcome.into_outcome()) .ok_or_else(|| { color_eyre::Report::msg( "The faucet (helper service) server did not return a transaction response.", ) })?; match account_creation_transaction.status { near_primitives::views::FinalExecutionStatus::SuccessValue(ref value) => { tracing::info!( parent: &tracing::Span::none(), "Transaction Execution Info:\n{}", crate::common::indent_payload(&format!( "Transaction ID: {id}\nTo see the transaction in the transaction explorer, please open this url in your browser:\n{path}{id}\n", id=account_creation_transaction.transaction_outcome.id, path=network_config.explorer_transaction_url )) ); if value == b"false" { tracing::warn!( parent: &tracing::Span::none(), "{}", crate::common::indent_payload(&format!( "\nThe new account <{new_account_id}> could not be created successfully.\n{storage_message}\n " )) ); } else { crate::common::update_used_account_list_as_signer( credentials_home_dir, new_account_id.as_ref(), ); if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = verbosity { tracing_indicatif::suspend_tracing_indicatif(|| { eprintln!( "New account <{new_account_id}> created successfully.\n{storage_message}" ) }); } } } near_primitives::views::FinalExecutionStatus::NotStarted | near_primitives::views::FinalExecutionStatus::Started => unreachable!(), near_primitives::views::FinalExecutionStatus::Failure(tx_execution_error) => { tracing::warn!( parent: &tracing::Span::none(), "{}", crate::common::indent_payload(&format!( "\nThe new account <{new_account_id}> could not be created successfully.\n{storage_message}\n " )) ); match tx_execution_error { near_primitives::errors::TxExecutionError::ActionError(action_error) => { return crate::common::convert_action_error_to_cli_result( &action_error, ); } near_primitives::errors::TxExecutionError::InvalidTxError( invalid_tx_error, ) => { return crate::common::convert_invalid_tx_error_to_cli_result( &invalid_tx_error, ); } } } } Ok(()) } Err(err) => { tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "JSON RPC Response:\n{}", crate::common::indent_payload(&err.to_string()) ); tracing::warn!( parent: &tracing::Span::none(), "{}", crate::common::indent_payload(&format!( "\nThe new account <{new_account_id}> could not be created successfully.\n{storage_message}\n " )) ); Err(color_eyre::Report::msg(err.to_string())) } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/sponsor_by_faucet_service/add_key/mod.rs
src/commands/account/create_account/sponsor_by_faucet_service/add_key/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; pub mod autogenerate_new_keypair; #[cfg(feature = "ledger")] mod use_ledger; mod use_manually_provided_seed_phrase; mod use_public_key; #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::NewAccountContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Add an access key for this account: pub enum AccessKeyMode { #[strum_discriminants(strum( message = "autogenerate-new-keypair - Automatically generate a key pair" ))] /// Automatically generate a key pair AutogenerateNewKeypair(self::autogenerate_new_keypair::GenerateKeypair), #[strum_discriminants(strum( message = "use-manually-provided-seed-prase - Use the provided seed phrase manually" ))] /// Use the provided seed phrase manually UseManuallyProvidedSeedPhrase( self::use_manually_provided_seed_phrase::AddAccessWithSeedPhraseAction, ), #[strum_discriminants(strum( message = "use-manually-provided-public-key - Use the provided public key manually" ))] /// Use the provided public key manually UseManuallyProvidedPublicKey(self::use_public_key::AddPublicKeyAction), #[cfg(feature = "ledger")] #[strum_discriminants(strum(message = "use-ledger - Use a ledger"))] /// Use a ledger UseLedger(self::use_ledger::AddAccessWithLedger), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/sponsor_by_faucet_service/add_key/use_manually_provided_seed_phrase/mod.rs
src/commands/account/create_account/sponsor_by_faucet_service/add_key/use_manually_provided_seed_phrase/mod.rs
use std::str::FromStr; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::NewAccountContext)] #[interactive_clap(output_context = AddAccessWithSeedPhraseActionContext)] pub struct AddAccessWithSeedPhraseAction { /// Enter the seed-phrase for this account: master_seed_phrase: String, #[interactive_clap(named_arg)] /// Select network network_config: super::super::network::Network, } #[derive(Clone)] struct AddAccessWithSeedPhraseActionContext(super::super::SponsorServiceContext); impl AddAccessWithSeedPhraseActionContext { pub fn from_previous_context( previous_context: super::super::NewAccountContext, scope: &<AddAccessWithSeedPhraseAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { // This is the HD path that is used in NEAR Wallet for plaintext seed phrase generation and, subsequently, for account recovery by a seed phrase. let near_wallet_seed_phrase_hd_path_default = slipped10::BIP32Path::from_str("m/44'/397'/0'").unwrap(); let public_key = crate::common::get_public_key_from_seed_phrase( near_wallet_seed_phrase_hd_path_default, &scope.master_seed_phrase, )?; Ok(Self(super::super::SponsorServiceContext { config: previous_context.config, new_account_id: previous_context.new_account_id, public_key, on_after_getting_network_callback: std::sync::Arc::new(|_network_config| { Ok(String::new()) }), on_before_creating_account_callback: previous_context .on_before_creating_account_callback, })) } } impl From<AddAccessWithSeedPhraseActionContext> for super::super::SponsorServiceContext { fn from(item: AddAccessWithSeedPhraseActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/sponsor_by_faucet_service/add_key/autogenerate_new_keypair/mod.rs
src/commands/account/create_account/sponsor_by_faucet_service/add_key/autogenerate_new_keypair/mod.rs
use std::str::FromStr; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::super::NewAccountContext)] #[interactive_clap(output_context = GenerateKeypairContext)] pub struct GenerateKeypair { #[interactive_clap(subcommand)] save_mode: SaveMode, } #[derive(Clone)] pub struct GenerateKeypairContext { config: crate::config::Config, new_account_id: crate::types::account_id::AccountId, public_key: near_crypto::PublicKey, key_pair_properties: crate::common::KeyPairProperties, on_before_creating_account_callback: super::super::network::OnBeforeCreatingAccountCallback, } impl GenerateKeypairContext { pub fn from_previous_context( previous_context: super::super::NewAccountContext, _scope: &<GenerateKeypair as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let key_pair_properties: crate::common::KeyPairProperties = crate::common::generate_keypair()?; let public_key = near_crypto::PublicKey::from_str(&key_pair_properties.public_key_str)?; Ok(Self { config: previous_context.config, new_account_id: previous_context.new_account_id, public_key, key_pair_properties, on_before_creating_account_callback: previous_context .on_before_creating_account_callback, }) } } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = GenerateKeypairContext)] #[interactive_clap(output_context = SaveModeContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Save an access key for this account: pub enum SaveMode { #[strum_discriminants(strum( message = "save-to-keychain - Save automatically generated key pair to keychain" ))] /// Save automatically generated key pair to keychain SaveToKeychain(SaveKeyPair), #[strum_discriminants(strum( message = "save-to-legacy-keychain - Save automatically generated key pair to the legacy keychain (compatible with JS CLI)" ))] /// Save automatically generated key pair to the legacy keychain (compatible with JS CLI) SaveToLegacyKeychain(SaveKeyPair), #[strum_discriminants(strum( message = "print-to-terminal - Print automatically generated key pair in terminal" ))] /// Print automatically generated key pair in terminal PrintToTerminal(SaveKeyPair), } #[derive(Clone)] pub struct SaveModeContext(super::super::SponsorServiceContext); impl SaveModeContext { pub fn from_previous_context( previous_context: GenerateKeypairContext, scope: &<SaveMode as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let scope = *scope; let on_after_getting_network_callback: super::super::network::OnAfterGettingNetworkCallback = std::sync::Arc::new({ let new_account_id_str = previous_context.new_account_id.to_string(); let key_pair_properties = previous_context.key_pair_properties.clone(); let credentials_home_dir = previous_context.config.credentials_home_dir.clone(); move |network_config| { match scope { SaveModeDiscriminants::SaveToKeychain => { let key_pair_properties_buf = serde_json::to_string(&key_pair_properties)?; crate::common::save_access_key_to_keychain_or_save_to_legacy_keychain( network_config.clone(), credentials_home_dir.clone(), &key_pair_properties_buf, &key_pair_properties.public_key_str, &new_account_id_str, ) } SaveModeDiscriminants::SaveToLegacyKeychain => { let key_pair_properties_buf = serde_json::to_string(&key_pair_properties)?; crate::common::save_access_key_to_legacy_keychain( network_config.clone(), credentials_home_dir.clone(), &key_pair_properties_buf, &key_pair_properties.public_key_str, &new_account_id_str, ) } SaveModeDiscriminants::PrintToTerminal => { Ok(format!( "\n-------------------- Access key info ------------------ \nMaster Seed Phrase: {}\nSeed Phrase HD Path: {}\nImplicit Account ID: {}\nPublic Key: {}\nSECRET KEYPAIR: {} \n--------------------------------------------------------", key_pair_properties.master_seed_phrase, key_pair_properties.seed_phrase_hd_path, key_pair_properties.implicit_account_id, key_pair_properties.public_key_str, key_pair_properties.secret_keypair_str, )) } } } }); Ok(Self(super::super::SponsorServiceContext { config: previous_context.config, new_account_id: previous_context.new_account_id, public_key: previous_context.public_key, on_after_getting_network_callback, on_before_creating_account_callback: previous_context .on_before_creating_account_callback, })) } } impl From<SaveModeContext> for super::super::SponsorServiceContext { fn from(item: SaveModeContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::SponsorServiceContext)] pub struct SaveKeyPair { #[interactive_clap(named_arg)] /// Select network network_config: super::super::network::Network, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/sponsor_by_faucet_service/add_key/use_public_key/mod.rs
src/commands/account/create_account/sponsor_by_faucet_service/add_key/use_public_key/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::NewAccountContext)] #[interactive_clap(output_context = AddPublicKeyActionContext)] pub struct AddPublicKeyAction { /// Enter the public key for this account: public_key: crate::types::public_key::PublicKey, #[interactive_clap(named_arg)] /// Select network network_config: super::super::network::Network, } #[derive(Clone)] pub struct AddPublicKeyActionContext(super::super::SponsorServiceContext); impl AddPublicKeyActionContext { pub fn from_previous_context( previous_context: super::super::NewAccountContext, scope: &<AddPublicKeyAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(super::super::SponsorServiceContext { config: previous_context.config, new_account_id: previous_context.new_account_id, public_key: scope.public_key.clone().into(), on_after_getting_network_callback: std::sync::Arc::new(|_network_config| { Ok(String::new()) }), on_before_creating_account_callback: previous_context .on_before_creating_account_callback, })) } } impl From<AddPublicKeyActionContext> for super::super::SponsorServiceContext { fn from(item: AddPublicKeyActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/sponsor_by_faucet_service/add_key/use_ledger/mod.rs
src/commands/account/create_account/sponsor_by_faucet_service/add_key/use_ledger/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::NewAccountContext)] #[interactive_clap(output_context = AddAccessWithLedgerContext)] pub struct AddAccessWithLedger { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] seed_phrase_hd_path: crate::types::slip10::BIP32Path, #[interactive_clap(named_arg)] /// Select network network_config: super::super::network::Network, } #[derive(Clone)] pub struct AddAccessWithLedgerContext(super::super::SponsorServiceContext); impl AddAccessWithLedgerContext { pub fn from_previous_context( previous_context: super::super::NewAccountContext, scope: &<AddAccessWithLedger as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { eprintln!("Opening the NEAR application... Please approve opening the application"); near_ledger::open_near_application().map_err(|ledger_error| { color_eyre::Report::msg(format!("An error happened while trying to open the NEAR application on the ledger: {ledger_error:?}")) })?; std::thread::sleep(std::time::Duration::from_secs(1)); let seed_phrase_hd_path = scope.seed_phrase_hd_path.clone(); eprintln!( "Please allow getting the PublicKey on Ledger device (HD Path: {seed_phrase_hd_path})" ); let public_key = near_ledger::get_public_key(seed_phrase_hd_path.into()).map_err( |near_ledger_error| { color_eyre::Report::msg(format!( "An error occurred while trying to get PublicKey from Ledger device: {near_ledger_error:?}" )) }, )?; let public_key = near_crypto::PublicKey::ED25519(near_crypto::ED25519PublicKey::from( public_key.to_bytes(), )); Ok(Self(super::super::SponsorServiceContext { config: previous_context.config, new_account_id: previous_context.new_account_id, public_key, on_after_getting_network_callback: std::sync::Arc::new(|_network_config| { Ok(String::new()) }), on_before_creating_account_callback: previous_context .on_before_creating_account_callback, })) } } impl From<AddAccessWithLedgerContext> for super::super::SponsorServiceContext { fn from(item: AddAccessWithLedgerContext) -> Self { item.0 } } impl AddAccessWithLedger { pub fn input_seed_phrase_hd_path( _context: &super::super::NewAccountContext, ) -> color_eyre::eyre::Result<Option<crate::types::slip10::BIP32Path>> { crate::transaction_signature_options::sign_with_ledger::input_seed_phrase_hd_path() } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/create_account/sponsor_by_faucet_service/network/mod.rs
src/commands/account/create_account/sponsor_by_faucet_service/network/mod.rs
use color_eyre::eyre::ContextCompat; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::SponsorServiceContext)] #[interactive_clap(output_context = NetworkContext)] pub struct Network { /// What is the name of the network? #[interactive_clap(skip_default_input_arg)] network_name: String, #[interactive_clap(subcommand)] pub submit: Submit, } #[derive(Clone)] pub struct NetworkContext { new_account_id: crate::types::account_id::AccountId, public_key: near_crypto::PublicKey, network_config: crate::config::NetworkConfig, on_after_getting_network_callback: OnAfterGettingNetworkCallback, on_before_creating_account_callback: OnBeforeCreatingAccountCallback, } impl NetworkContext { pub fn from_previous_context( previous_context: super::SponsorServiceContext, scope: &<Network as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let networks = previous_context.config.network_connection.clone(); let network_config = networks .get(&scope.network_name) .wrap_err("Failed to get network config!")? .clone(); let mut info_str: String = String::new(); info_str.push_str(&format!( "\n{:<13} {}", "signer_id:", &network_config.network_name )); info_str.push_str("\nactions:"); info_str.push_str(&format!( "\n{:>5} {:<20} {}", "--", "create account:", &previous_context.new_account_id )); info_str.push_str(&format!("\n{:>5} {:<20}", "--", "add access key:")); info_str.push_str(&format!( "\n{:>18} {:<13} {}", "", "public key:", &previous_context.public_key )); info_str.push_str(&format!("\n{:>18} {:<13} FullAccess", "", "permission:")); info_str.push_str("\n "); tracing::info!( "Your transaction:{}", crate::common::indent_payload(&info_str) ); Ok(Self { new_account_id: previous_context.new_account_id, public_key: previous_context.public_key, network_config, on_after_getting_network_callback: previous_context.on_after_getting_network_callback, on_before_creating_account_callback: previous_context .on_before_creating_account_callback, }) } } impl Network { fn input_network_name( context: &super::SponsorServiceContext, ) -> color_eyre::eyre::Result<Option<String>> { crate::common::input_network_name(&context.config, &[context.new_account_id.clone().into()]) } } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = NetworkContext)] #[interactive_clap(output_context = SubmitContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// How would you like to proceed? pub enum Submit { #[strum_discriminants(strum(message = "create - Create a new account"))] Create, } #[derive(Debug, Clone)] pub struct SubmitContext; impl SubmitContext { #[tracing::instrument(name = "Creating a new account ...", skip_all)] pub fn from_previous_context( previous_context: NetworkContext, _scope: &<Submit as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { tracing::info!(target: "near_teach_me", "Creating a new account ..."); let storage_message = (previous_context.on_after_getting_network_callback)(&previous_context.network_config)?; (previous_context.on_before_creating_account_callback)( &previous_context.network_config, &previous_context.new_account_id, &previous_context.public_key, storage_message, )?; Ok(Self) } } pub type OnAfterGettingNetworkCallback = std::sync::Arc<dyn Fn(&crate::config::NetworkConfig) -> color_eyre::eyre::Result<String>>; pub type OnBeforeCreatingAccountCallback = std::sync::Arc< dyn Fn( &crate::config::NetworkConfig, &crate::types::account_id::AccountId, &near_crypto::PublicKey, String, ) -> crate::CliResult, >;
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/delete_account/mod.rs
src/commands/account/delete_account/mod.rs
use color_eyre::owo_colors::OwoColorize; use inquire::Select; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = DeleteAccountContext)] pub struct DeleteAccount { #[interactive_clap(skip_default_input_arg)] /// What Account ID to be deleted? account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Enter the beneficiary ID to delete this account ID beneficiary: BeneficiaryAccount, } #[derive(Debug, Clone)] pub struct DeleteAccountContext { global_context: crate::GlobalContext, account_id: near_primitives::types::AccountId, } impl DeleteAccountContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<DeleteAccount as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context, account_id: scope.account_id.clone().into(), }) } } impl DeleteAccount { pub fn input_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_signer_account_id_from_used_account_list( &context.config.credentials_home_dir, "What Account ID to be deleted?", ) } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = DeleteAccountContext)] #[interactive_clap(output_context = BeneficiaryAccountContext)] pub struct BeneficiaryAccount { #[interactive_clap(skip_default_input_arg)] /// Specify a beneficiary: beneficiary_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Debug, Clone)] pub struct BeneficiaryAccountContext { global_context: crate::GlobalContext, account_id: near_primitives::types::AccountId, beneficiary_account_id: near_primitives::types::AccountId, } impl BeneficiaryAccountContext { pub fn from_previous_context( previous_context: DeleteAccountContext, scope: &<BeneficiaryAccount as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, account_id: previous_context.account_id, beneficiary_account_id: scope.beneficiary_account_id.clone().into(), }) } } impl From<BeneficiaryAccountContext> for crate::commands::ActionContext { fn from(item: BeneficiaryAccountContext) -> Self { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let account_id = item.account_id.clone(); move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: account_id.clone(), receiver_id: account_id.clone(), actions: vec![near_primitives::transaction::Action::DeleteAccount( near_primitives::transaction::DeleteAccountAction { beneficiary_id: item.beneficiary_account_id.clone(), }, )], }) } }); Self { global_context: item.global_context, interacting_with_account_ids: vec![item.account_id], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback: std::sync::Arc::new( |_outcome_view, _network_config| Ok(()), ), } } } impl BeneficiaryAccount { pub fn input_beneficiary_account_id( context: &DeleteAccountContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { loop { let beneficiary_account_id = if let Some(account_id) = crate::common::input_non_signer_account_id_from_used_account_list( &context.global_context.config.credentials_home_dir, "What is the beneficiary account ID?", )? { account_id } else { return Ok(None); }; if beneficiary_account_id.0 == context.account_id { eprintln!("{}", "You have selected a beneficiary account ID that will now be deleted. This will result in the loss of your funds. So make your choice again.".red()); continue; } if context.global_context.offline { return Ok(Some(beneficiary_account_id)); } #[derive(derive_more::Display)] enum ConfirmOptions { #[display("Yes, I want to check if account <{account_id}> exists. (It is free of charge, and only requires Internet access)")] Yes { account_id: crate::types::account_id::AccountId, }, #[display("No, I know this account exists and want to continue.")] No, } let select_choose_input = Select::new("Do you want to check the existence of the specified account so that you don't lose tokens?", vec![ConfirmOptions::Yes{account_id: beneficiary_account_id.clone()}, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes { account_id } = select_choose_input { if crate::common::find_network_where_account_exist( &context.global_context, account_id.clone().into(), )? .is_none() { eprintln!("\nHeads up! You will lose remaining NEAR tokens on the account you delete if you specify the account <{}> as the beneficiary as it does not exist on [{}] networks.", account_id, context.global_context.config.network_names().join(", ") ); if !crate::common::ask_if_different_account_id_wanted()? { return Ok(Some(account_id)); } } else { return Ok(Some(account_id)); }; } else { return Ok(Some(beneficiary_account_id)); }; } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/add_key/mod.rs
src/commands/account/add_key/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod access_key_type; mod autogenerate_new_keypair; #[cfg(feature = "ledger")] mod use_ledger; mod use_manually_provided_seed_phrase; mod use_mpc; mod use_public_key; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = AddKeyCommandContext)] pub struct AddKeyCommand { #[interactive_clap(skip_default_input_arg)] /// Which account do you want to add an access key to? owner_account_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] permission: AccessKeyPermission, } #[derive(Debug, Clone)] pub struct AddKeyCommandContext { global_context: crate::GlobalContext, owner_account_id: crate::types::account_id::AccountId, } impl AddKeyCommandContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<AddKeyCommand as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context, owner_account_id: scope.owner_account_id.clone(), }) } } impl AddKeyCommand { pub fn input_owner_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_signer_account_id_from_used_account_list( &context.config.credentials_home_dir, "Which account do you want to add an access key to?", ) } } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = AddKeyCommandContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select a permission that you want to add to the access key: pub enum AccessKeyPermission { #[strum_discriminants(strum( message = "grant-full-access - A permission with full access" ))] /// Provide data for a full access key GrantFullAccess(self::access_key_type::FullAccessType), #[strum_discriminants(strum( message = "grant-function-call-access - A permission with function call" ))] /// Provide data for a function-call access key GrantFunctionCallAccess(self::access_key_type::FunctionCallType), } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = self::access_key_type::AccessTypeContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Add an access key for this account: pub enum AccessKeyMode { #[strum_discriminants(strum( message = "autogenerate-new-keypair - Automatically generate a key pair" ))] /// Automatically generate a key pair AutogenerateNewKeypair(self::autogenerate_new_keypair::GenerateKeypair), #[strum_discriminants(strum( message = "use-manually-provided-seed-prase - Use the provided seed phrase manually" ))] /// Use the provided seed phrase manually UseManuallyProvidedSeedPhrase( self::use_manually_provided_seed_phrase::AddAccessWithSeedPhraseAction, ), #[strum_discriminants(strum( message = "use-manually-provided-public-key - Use the provided public key manually" ))] /// Use the provided public key manually UseManuallyProvidedPublicKey(self::use_public_key::AddAccessKeyAction), #[strum_discriminants(strum( message = "use-mpc-contract - Use MPC contract to derive key" ))] /// Use MPC contract to derive key UseMpcContract(self::use_mpc::AddKeyWithMpcDerivedKey), #[cfg(feature = "ledger")] #[strum_discriminants(strum(message = "use-ledger - Use a ledger"))] /// Use the Ledger Hardware wallet UseLedger(self::use_ledger::AddLedgerKeyAction), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/add_key/access_key_type/mod.rs
src/commands/account/add_key/access_key_type/mod.rs
use std::str::FromStr; use inquire::{CustomType, Select, Text}; #[derive(Debug, Clone)] pub struct AccessTypeContext { pub global_context: crate::GlobalContext, pub signer_account_id: near_primitives::types::AccountId, pub permission: near_primitives::account::AccessKeyPermission, } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::AddKeyCommandContext)] #[interactive_clap(output_context = FullAccessTypeContext)] pub struct FullAccessType { #[interactive_clap(subcommand)] pub access_key_mode: super::AccessKeyMode, } #[derive(Debug, Clone)] pub struct FullAccessTypeContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, permission: near_primitives::account::AccessKeyPermission, } impl FullAccessTypeContext { pub fn from_previous_context( previous_context: super::AddKeyCommandContext, _scope: &<FullAccessType as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.owner_account_id.into(), permission: near_primitives::account::AccessKeyPermission::FullAccess, }) } } impl From<FullAccessTypeContext> for AccessTypeContext { fn from(item: FullAccessTypeContext) -> Self { Self { global_context: item.global_context, signer_account_id: item.signer_account_id, permission: item.permission, } } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::AddKeyCommandContext)] #[interactive_clap(output_context = FunctionCallTypeContext)] pub struct FunctionCallType { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] allowance: crate::types::near_allowance::NearAllowance, #[interactive_clap(long)] /// Enter the contract account ID that this access key can be used to sign call function transactions for: contract_account_id: crate::types::account_id::AccountId, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] function_names: crate::types::vec_string::VecString, #[interactive_clap(subcommand)] access_key_mode: super::AccessKeyMode, } #[derive(Debug, Clone)] pub struct FunctionCallTypeContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, allowance: Option<crate::types::near_token::NearToken>, contract_account_id: crate::types::account_id::AccountId, function_names: crate::types::vec_string::VecString, } impl FunctionCallTypeContext { pub fn from_previous_context( previous_context: super::AddKeyCommandContext, scope: &<FunctionCallType as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.owner_account_id.into(), allowance: scope.allowance.optional_near_token(), contract_account_id: scope.contract_account_id.clone(), function_names: scope.function_names.clone(), }) } } impl From<FunctionCallTypeContext> for AccessTypeContext { fn from(item: FunctionCallTypeContext) -> Self { Self { global_context: item.global_context, signer_account_id: item.signer_account_id, permission: near_primitives::account::AccessKeyPermission::FunctionCall( near_primitives::account::FunctionCallPermission { allowance: item.allowance.map(Into::into), receiver_id: item.contract_account_id.to_string(), method_names: item.function_names.into(), }, ), } } } impl FunctionCallType { pub fn input_function_names( _context: &super::AddKeyCommandContext, ) -> color_eyre::eyre::Result<Option<crate::types::vec_string::VecString>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum( to_string = "Yes, I want to input a list of function names that can be called when transaction is signed by this access key" )] Yes, #[strum(to_string = "No, I allow it to call any functions on the specified contract")] No, } let select_choose_input = Select::new( "Would you like the access key to be valid exclusively for calling specific functions on the contract?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { let mut input_function_names = Text::new("Enter a comma-separated list of function names that will be allowed to be called in a transaction signed by this access key:") .prompt()?; if input_function_names.contains('\"') { input_function_names.clear() }; if input_function_names.is_empty() { Ok(Some(crate::types::vec_string::VecString(vec![]))) } else { Ok(Some(crate::types::vec_string::VecString::from_str( &input_function_names, )?)) } } else { Ok(Some(crate::types::vec_string::VecString(vec![]))) } } pub fn input_allowance( _context: &super::AddKeyCommandContext, ) -> color_eyre::eyre::Result<Option<crate::types::near_allowance::NearAllowance>> { let allowance_near_balance: crate::types::near_allowance::NearAllowance = CustomType::new("Enter the allowance, a budget this access key can use to pay for transaction fees (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear):") .with_starting_input("unlimited") .prompt()?; Ok(Some(allowance_near_balance)) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/add_key/use_manually_provided_seed_phrase/mod.rs
src/commands/account/add_key/use_manually_provided_seed_phrase/mod.rs
use std::str::FromStr; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::access_key_type::AccessTypeContext)] #[interactive_clap(output_context = AddAccessWithSeedPhraseActionContext)] pub struct AddAccessWithSeedPhraseAction { /// Enter the seed-phrase: master_seed_phrase: String, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Debug, Clone)] pub struct AddAccessWithSeedPhraseActionContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, permission: near_primitives::account::AccessKeyPermission, public_key: near_crypto::PublicKey, } impl AddAccessWithSeedPhraseActionContext { pub fn from_previous_context( previous_context: super::access_key_type::AccessTypeContext, scope: &<AddAccessWithSeedPhraseAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let seed_phrase_hd_path_default = slipped10::BIP32Path::from_str("m/44'/397'/0'").unwrap(); let public_key = crate::common::get_public_key_from_seed_phrase( seed_phrase_hd_path_default, &scope.master_seed_phrase, )?; Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, permission: previous_context.permission, public_key, }) } } impl From<AddAccessWithSeedPhraseActionContext> for crate::commands::ActionContext { fn from(item: AddAccessWithSeedPhraseActionContext) -> Self { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_account_id = item.signer_account_id.clone(); move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_account_id.clone(), receiver_id: signer_account_id.clone(), actions: vec![near_primitives::transaction::Action::AddKey(Box::new( near_primitives::transaction::AddKeyAction { public_key: item.public_key.clone(), access_key: near_primitives::account::AccessKey { nonce: 0, permission: item.permission.clone(), }, }, ))], }) } }); Self { global_context: item.global_context, interacting_with_account_ids: vec![item.signer_account_id], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback: std::sync::Arc::new( |_outcome_view, _network_config| Ok(()), ), } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/add_key/autogenerate_new_keypair/mod.rs
src/commands/account/add_key/autogenerate_new_keypair/mod.rs
use std::str::FromStr; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod print_keypair_to_terminal; mod save_keypair_to_keychain; mod save_keypair_to_legacy_keychain; #[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::access_key_type::AccessTypeContext)] #[interactive_clap(output_context = GenerateKeypairContext)] pub struct GenerateKeypair { #[interactive_clap(subcommand)] save_mode: SaveMode, } #[derive(Debug, Clone)] pub struct GenerateKeypairContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, permission: near_primitives::account::AccessKeyPermission, key_pair_properties: crate::common::KeyPairProperties, public_key: near_crypto::PublicKey, } impl GenerateKeypairContext { pub fn from_previous_context( previous_context: super::access_key_type::AccessTypeContext, _scope: &<GenerateKeypair as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let key_pair_properties: crate::common::KeyPairProperties = crate::common::generate_keypair()?; let public_key = near_crypto::PublicKey::from_str(&key_pair_properties.public_key_str)?; Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, permission: previous_context.permission, key_pair_properties, public_key, }) } } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = GenerateKeypairContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Save an access key for this account: pub enum SaveMode { #[strum_discriminants(strum( message = "save-to-keychain - Save automatically generated key pair to keychain" ))] /// Save automatically generated key pair to keychain SaveToKeychain(self::save_keypair_to_keychain::SaveKeypairToKeychain), #[strum_discriminants(strum( message = "save-to-legacy-keychain - Save automatically generated key pair to the legacy keychain (compatible with JS CLI)" ))] /// Save automatically generated key pair to the legacy keychain (compatible with JS CLI) SaveToLegacyKeychain(self::save_keypair_to_legacy_keychain::SaveKeypairToLegacyKeychain), #[strum_discriminants(strum( message = "print-to-terminal - Print automatically generated key pair in terminal" ))] /// Print automatically generated key pair in terminal PrintToTerminal(self::print_keypair_to_terminal::PrintKeypairToTerminal), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/add_key/autogenerate_new_keypair/print_keypair_to_terminal/mod.rs
src/commands/account/add_key/autogenerate_new_keypair/print_keypair_to_terminal/mod.rs
#[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::GenerateKeypairContext)] #[interactive_clap(output_context = PrintKeypairToTerminalContext)] pub struct PrintKeypairToTerminal { #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Debug, Clone)] pub struct PrintKeypairToTerminalContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, permission: near_primitives::account::AccessKeyPermission, key_pair_properties: crate::common::KeyPairProperties, public_key: near_crypto::PublicKey, } impl PrintKeypairToTerminalContext { pub fn from_previous_context( previous_context: super::GenerateKeypairContext, _scope: &<PrintKeypairToTerminal as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, permission: previous_context.permission, key_pair_properties: previous_context.key_pair_properties, public_key: previous_context.public_key, }) } } impl From<PrintKeypairToTerminalContext> for crate::commands::ActionContext { fn from(item: PrintKeypairToTerminalContext) -> Self { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_account_id = item.signer_account_id.clone(); move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_account_id.clone(), receiver_id: signer_account_id.clone(), actions: vec![near_primitives::transaction::Action::AddKey(Box::new( near_primitives::transaction::AddKeyAction { public_key: item.public_key.clone(), access_key: near_primitives::account::AccessKey { nonce: 0, permission: item.permission.clone(), }, }, ))], }) } }); Self { global_context: item.global_context, interacting_with_account_ids: vec![item.signer_account_id], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( move |_transaction, _network_config| { Ok(format!( "\n-------------------- Access key info ------------------ \nMaster Seed Phrase: {}\nSeed Phrase HD Path: {}\nImplicit Account ID: {}\nPublic Key: {}\nSECRET KEYPAIR: {} \n--------------------------------------------------------", item.key_pair_properties.master_seed_phrase, item.key_pair_properties.seed_phrase_hd_path, item.key_pair_properties.implicit_account_id, item.key_pair_properties.public_key_str, item.key_pair_properties.secret_keypair_str, )) }, ), on_after_sending_transaction_callback: std::sync::Arc::new( move |_outcome_view, _network_config| Ok(()), ), } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/add_key/autogenerate_new_keypair/save_keypair_to_keychain/mod.rs
src/commands/account/add_key/autogenerate_new_keypair/save_keypair_to_keychain/mod.rs
#[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::GenerateKeypairContext)] #[interactive_clap(output_context = SaveKeypairToKeychainContext)] pub struct SaveKeypairToKeychain { #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Debug, Clone)] pub struct SaveKeypairToKeychainContext(super::GenerateKeypairContext); impl SaveKeypairToKeychainContext { pub fn from_previous_context( previous_context: super::GenerateKeypairContext, _scope: &<SaveKeypairToKeychain as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(previous_context)) } } impl From<SaveKeypairToKeychainContext> for crate::commands::ActionContext { fn from(item: SaveKeypairToKeychainContext) -> Self { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_account_id = item.0.signer_account_id.clone(); move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_account_id.clone(), receiver_id: signer_account_id.clone(), actions: vec![near_primitives::transaction::Action::AddKey(Box::new( near_primitives::transaction::AddKeyAction { public_key: item.0.public_key.clone(), access_key: near_primitives::account::AccessKey { nonce: 0, permission: item.0.permission.clone(), }, }, ))], }) } }); let on_before_sending_transaction_callback: crate::transaction_signature_options::OnBeforeSendingTransactionCallback = std::sync::Arc::new({ let credentials_home_dir = item.0.global_context.config.credentials_home_dir.clone(); move |transaction, network_config| { let account_id = match transaction { crate::transaction_signature_options::SignedTransactionOrSignedDelegateAction::SignedTransaction( signed_transaction, ) => signed_transaction.transaction.signer_id().clone(), crate::transaction_signature_options::SignedTransactionOrSignedDelegateAction::SignedDelegateAction( signed_delegate_action, ) => signed_delegate_action.delegate_action.sender_id.clone() }; crate::common::save_access_key_to_keychain_or_save_to_legacy_keychain( network_config.clone(), credentials_home_dir.clone(), &serde_json::to_string(&item.0.key_pair_properties)?, &item.0.key_pair_properties.public_key_str, account_id.as_ref(), ) } }); Self { global_context: item.0.global_context, interacting_with_account_ids: vec![item.0.signer_account_id], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback, on_after_sending_transaction_callback: std::sync::Arc::new( |_outcome_view, _network_config| Ok(()), ), } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/add_key/autogenerate_new_keypair/save_keypair_to_legacy_keychain/mod.rs
src/commands/account/add_key/autogenerate_new_keypair/save_keypair_to_legacy_keychain/mod.rs
use color_eyre::eyre::Context; #[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::GenerateKeypairContext)] #[interactive_clap(output_context = SaveKeypairToLegacyKeychainContext)] pub struct SaveKeypairToLegacyKeychain { #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Debug, Clone)] pub struct SaveKeypairToLegacyKeychainContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, permission: near_primitives::account::AccessKeyPermission, key_pair_properties: crate::common::KeyPairProperties, public_key: near_crypto::PublicKey, } impl SaveKeypairToLegacyKeychainContext { pub fn from_previous_context( previous_context: super::GenerateKeypairContext, _scope: &<SaveKeypairToLegacyKeychain as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, permission: previous_context.permission, key_pair_properties: previous_context.key_pair_properties, public_key: previous_context.public_key, }) } } impl From<SaveKeypairToLegacyKeychainContext> for crate::commands::ActionContext { fn from(item: SaveKeypairToLegacyKeychainContext) -> Self { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_account_id = item.signer_account_id.clone(); move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_account_id.clone(), receiver_id: signer_account_id.clone(), actions: vec![near_primitives::transaction::Action::AddKey(Box::new( near_primitives::transaction::AddKeyAction { public_key: item.public_key.clone(), access_key: near_primitives::account::AccessKey { nonce: 0, permission: item.permission.clone(), }, }, ))], }) } }); let on_before_sending_transaction_callback: crate::transaction_signature_options::OnBeforeSendingTransactionCallback = std::sync::Arc::new({ let credentials_home_dir = item.global_context.config.credentials_home_dir.clone(); move |transaction, network_config| { let account_id = match transaction { crate::transaction_signature_options::SignedTransactionOrSignedDelegateAction::SignedTransaction( signed_transaction, ) => signed_transaction.transaction.signer_id().clone(), crate::transaction_signature_options::SignedTransactionOrSignedDelegateAction::SignedDelegateAction( signed_delegate_action, ) => signed_delegate_action.delegate_action.sender_id.clone() }; let key_pair_properties_buf = serde_json::to_string(&item.key_pair_properties)?; crate::common::save_access_key_to_legacy_keychain( network_config.clone(), credentials_home_dir.clone(), &key_pair_properties_buf, &item.key_pair_properties.public_key_str, account_id.as_ref(), ) .wrap_err_with(|| { format!( "Failed to save a file with access key: {}", &item.key_pair_properties.public_key_str ) }) } }); Self { global_context: item.global_context, interacting_with_account_ids: vec![item.signer_account_id], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback, on_after_sending_transaction_callback: std::sync::Arc::new( |_outcome_view, _network_config| Ok(()), ), } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/add_key/use_public_key/mod.rs
src/commands/account/add_key/use_public_key/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::access_key_type::AccessTypeContext)] #[interactive_clap(output_context = AddAccessKeyActionContext)] pub struct AddAccessKeyAction { /// Enter the public key: public_key: crate::types::public_key::PublicKey, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Debug, Clone)] pub struct AddAccessKeyActionContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, permission: near_primitives::account::AccessKeyPermission, public_key: crate::types::public_key::PublicKey, } impl AddAccessKeyActionContext { pub fn from_previous_context( previous_context: super::access_key_type::AccessTypeContext, scope: &<AddAccessKeyAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, permission: previous_context.permission, public_key: scope.public_key.clone(), }) } } impl From<AddAccessKeyActionContext> for crate::commands::ActionContext { fn from(item: AddAccessKeyActionContext) -> Self { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_account_id = item.signer_account_id.clone(); move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_account_id.clone(), receiver_id: signer_account_id.clone(), actions: vec![near_primitives::transaction::Action::AddKey(Box::new( near_primitives::transaction::AddKeyAction { public_key: item.public_key.clone().into(), access_key: near_primitives::account::AccessKey { nonce: 0, permission: item.permission.clone(), }, }, ))], }) } }); Self { global_context: item.global_context, interacting_with_account_ids: vec![item.signer_account_id], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback: std::sync::Arc::new( |_outcome_view, _network_config| Ok(()), ), } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/add_key/use_mpc/mod.rs
src/commands/account/add_key/use_mpc/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::access_key_type::AccessTypeContext)] #[interactive_clap(output_context = AddKeyWithMpcDerivedKeyContext)] pub struct AddKeyWithMpcDerivedKey { #[interactive_clap(skip_default_input_arg)] /// What is the Admin account address? admin_account_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] /// What is key type for deriving key? mpc_key_type: MpcKeyType, } #[derive(Debug, Clone)] pub struct AddKeyWithMpcDerivedKeyContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, key_permission: near_primitives::account::AccessKeyPermission, admin_account_id: near_primitives::types::AccountId, } impl AddKeyWithMpcDerivedKeyContext { pub fn from_previous_context( previous_context: super::access_key_type::AccessTypeContext, scope: &<AddKeyWithMpcDerivedKey as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { if previous_context.global_context.offline { eprintln!("\nInternet connection is required to derive key from MPC contract!"); return Err(color_eyre::eyre::eyre!( "Internet connection is required to derive key from MPC contract!" )); } Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, key_permission: previous_context.permission, admin_account_id: scope.admin_account_id.clone().into(), }) } } impl AddKeyWithMpcDerivedKey { pub fn input_admin_account_id( context: &super::access_key_type::AccessTypeContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_non_signer_account_id_from_used_account_list( &context.global_context.config.credentials_home_dir, "What is the Admin account address?", ) } } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = AddKeyWithMpcDerivedKeyContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// What is the key type for derivation (if unsure choose Ed25519)? pub enum MpcKeyType { #[strum_discriminants(strum(message = "ed25519 - use Ed25519 key derivation"))] /// Use Ed25519 key Ed25519(MpcKeyTypeEd), #[strum_discriminants(strum(message = "secp256k1 - use Secp256K1 key derivation"))] /// Use Secp256K1 key Secp256k1(MpcKeyTypeSecp), } #[derive(Clone)] pub struct MpcKeyTypeContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, key_permission: near_primitives::account::AccessKeyPermission, admin_account_id: near_primitives::types::AccountId, key_type: near_crypto::KeyType, } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = AddKeyWithMpcDerivedKeyContext)] #[interactive_clap(output_context = MpcKeyTypeSecpContext)] pub struct MpcKeyTypeSecp { #[interactive_clap(named_arg)] /// What is the derivation path? derivation_path: MpcDeriveKeyToAdd, } #[derive(Clone)] pub struct MpcKeyTypeSecpContext(MpcKeyTypeContext); impl MpcKeyTypeSecpContext { fn from_previous_context( previous_context: AddKeyWithMpcDerivedKeyContext, _scope: &<MpcKeyTypeSecp as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(MpcKeyTypeContext { global_context: previous_context.global_context, admin_account_id: previous_context.admin_account_id, signer_account_id: previous_context.signer_account_id, key_permission: previous_context.key_permission, key_type: near_crypto::KeyType::SECP256K1, })) } } impl From<MpcKeyTypeSecpContext> for MpcKeyTypeContext { fn from(item: MpcKeyTypeSecpContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = AddKeyWithMpcDerivedKeyContext)] #[interactive_clap(output_context = MpcKeyTypeEdContext)] pub struct MpcKeyTypeEd { #[interactive_clap(named_arg)] /// What is the derivation path? derivation_path: MpcDeriveKeyToAdd, } #[derive(Clone)] pub struct MpcKeyTypeEdContext(MpcKeyTypeContext); impl MpcKeyTypeEdContext { fn from_previous_context( previous_context: AddKeyWithMpcDerivedKeyContext, _scope: &<MpcKeyTypeEd as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(MpcKeyTypeContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, key_permission: previous_context.key_permission, admin_account_id: previous_context.admin_account_id, key_type: near_crypto::KeyType::ED25519, })) } } impl From<MpcKeyTypeEdContext> for MpcKeyTypeContext { fn from(item: MpcKeyTypeEdContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = MpcKeyTypeContext)] #[interactive_clap(output_context = MpcDeriveKeyToAddContext)] pub struct MpcDeriveKeyToAdd { #[interactive_clap(skip_default_input_arg, always_quote)] /// What is the derivation path? derivation_path: String, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Debug, Clone)] pub struct MpcDeriveKeyToAddContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, admin_account_id: near_primitives::types::AccountId, key_permission: near_primitives::account::AccessKeyPermission, key_type: near_crypto::KeyType, derivation_path: String, } impl MpcDeriveKeyToAdd { pub fn input_derivation_path( context: &MpcKeyTypeContext, ) -> color_eyre::eyre::Result<Option<String>> { let derivation_path = inquire::Text::new("What is the derivation path?") .with_initial_value(&format!( "{}-{}", context.admin_account_id, context.signer_account_id )) .prompt()?; Ok(Some(derivation_path)) } } impl MpcDeriveKeyToAddContext { pub fn from_previous_context( previous_context: MpcKeyTypeContext, scope: &<MpcDeriveKeyToAdd as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, admin_account_id: previous_context.admin_account_id, key_permission: previous_context.key_permission, key_type: previous_context.key_type, derivation_path: scope.derivation_path.clone(), }) } } impl From<MpcDeriveKeyToAddContext> for crate::commands::ActionContext { fn from(item: MpcDeriveKeyToAddContext) -> Self { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_account_id = item.signer_account_id.clone(); move |network_config| { let derived_public_key = crate::transaction_signature_options::sign_with_mpc::derive_public_key( &network_config.get_mpc_contract_account_id()?, &item.admin_account_id, &item.derivation_path, &item.key_type, network_config, )?; Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_account_id.clone(), receiver_id: signer_account_id.clone(), actions: vec![near_primitives::transaction::Action::AddKey(Box::new( near_primitives::transaction::AddKeyAction { public_key: derived_public_key, access_key: near_primitives::account::AccessKey { nonce: 0, permission: item.key_permission.clone(), }, }, ))], }) } }); Self { global_context: item.global_context, // NOTE: We cannot determine MPC contract AccountId until we get NetworkConfig where // it's stored, resulting in passing only signer AccountId interacting_with_account_ids: vec![item.signer_account_id], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback: std::sync::Arc::new( |_outcome_view, _network_config| Ok(()), ), } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/add_key/use_ledger/mod.rs
src/commands/account/add_key/use_ledger/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::access_key_type::AccessTypeContext)] #[interactive_clap(output_context = AddLedgerKeyActionContext)] pub struct AddLedgerKeyAction { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] seed_phrase_hd_path: crate::types::slip10::BIP32Path, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Debug, Clone)] pub struct AddLedgerKeyActionContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, permission: near_primitives::account::AccessKeyPermission, public_key: crate::types::public_key::PublicKey, } impl AddLedgerKeyActionContext { pub fn from_previous_context( previous_context: super::access_key_type::AccessTypeContext, scope: &<AddLedgerKeyAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let seed_phrase_hd_path = scope.seed_phrase_hd_path.clone(); eprintln!("Opening the NEAR application... Please approve opening the application"); near_ledger::open_near_application().map_err(|ledger_error| { color_eyre::Report::msg(format!("An error happened while trying to open the NEAR application on the ledger: {ledger_error:?}")) })?; std::thread::sleep(std::time::Duration::from_secs(1)); eprintln!( "Please allow getting the PublicKey on Ledger device (HD Path: {seed_phrase_hd_path})" ); let public_key = near_ledger::get_public_key(seed_phrase_hd_path.into()).map_err( |near_ledger_error| { color_eyre::Report::msg(format!( "An error occurred while trying to get PublicKey from Ledger device: {near_ledger_error:?}" )) }, )?; let public_key = near_crypto::PublicKey::ED25519(near_crypto::ED25519PublicKey::from( public_key.to_bytes(), )); Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, permission: previous_context.permission, public_key: public_key.into(), }) } } impl From<AddLedgerKeyActionContext> for crate::commands::ActionContext { fn from(item: AddLedgerKeyActionContext) -> Self { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_account_id = item.signer_account_id.clone(); move |_network_config| { Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_account_id.clone(), receiver_id: signer_account_id.clone(), actions: vec![near_primitives::transaction::Action::AddKey(Box::new( near_primitives::transaction::AddKeyAction { public_key: item.public_key.clone().into(), access_key: near_primitives::account::AccessKey { nonce: 0, permission: item.permission.clone(), }, }, ))], }) } }); Self { global_context: item.global_context, interacting_with_account_ids: vec![item.signer_account_id], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback: std::sync::Arc::new( |_outcome_view, _network_config| Ok(()), ), } } } impl AddLedgerKeyAction { pub fn input_seed_phrase_hd_path( _context: &super::access_key_type::AccessTypeContext, ) -> color_eyre::eyre::Result<Option<crate::types::slip10::BIP32Path>> { crate::transaction_signature_options::sign_with_ledger::input_seed_phrase_hd_path() } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/list_keys/mod.rs
src/commands/account/list_keys/mod.rs
use color_eyre::eyre::Context; use crate::common::JsonRpcClientExt; use crate::common::RpcQueryResponseExt; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = ViewListKeysContext)] pub struct ViewListKeys { #[interactive_clap(skip_default_input_arg)] /// What Account ID do you need to view? account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_view_at_block::NetworkViewAtBlockArgs, } #[derive(Clone)] pub struct ViewListKeysContext(crate::network_view_at_block::ArgsForViewContext); impl ViewListKeysContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<ViewListKeys as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let on_after_getting_block_reference_callback: crate::network_view_at_block::OnAfterGettingBlockReferenceCallback = std::sync::Arc::new({ let account_id: near_primitives::types::AccountId = scope.account_id.clone().into(); move |network_config, block_reference| { let access_key_list = network_config .json_rpc_client() .blocking_call_view_access_key_list( &account_id, block_reference.clone(), ) .wrap_err_with(|| { format!( "Failed to fetch query AccessKeyList for {}", &account_id ) })? .access_key_list_view()?; crate::common::display_access_key_list(&access_key_list.keys); Ok(()) } }); Ok(Self(crate::network_view_at_block::ArgsForViewContext { config: previous_context.config, interacting_with_account_ids: vec![scope.account_id.clone().into()], on_after_getting_block_reference_callback, })) } } impl From<ViewListKeysContext> for crate::network_view_at_block::ArgsForViewContext { fn from(item: ViewListKeysContext) -> Self { item.0 } } impl ViewListKeys { pub fn input_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_non_signer_account_id_from_used_account_list( &context.config.credentials_home_dir, "What Account ID do you need to view?", ) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/get_public_key/mod.rs
src/commands/account/get_public_key/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod from_keychain; #[cfg(feature = "ledger")] mod from_ledger; mod from_legacy_keychain; mod from_mpc; mod from_plaintext_private_key; mod from_seed_phrase; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] pub struct GetPublicKey { #[interactive_clap(subcommand)] get_public_key_mode: GetPublicKeyMode, } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Where do you want to get the public key from? pub enum GetPublicKeyMode { #[cfg(feature = "ledger")] #[strum_discriminants(strum( message = "from-ledger - Get the public key stored on your Ledger Nano device" ))] /// Get the public key stored on your Ledger Nano device FromLedger(self::from_ledger::PublicKeyFromLedger), #[strum_discriminants(strum( message = "from-seed-phrase - Get the public key with the seed phrase" ))] /// Get the public key with the seed phrase FromSeedPhrase(self::from_seed_phrase::PublicKeyFromSeedPhrase), #[strum_discriminants(strum( message = "from-plaintext-private-key - Get the public key from the plaintext private key" ))] /// Get the public key from the plaintext private key FromPlaintextPrivateKey(self::from_plaintext_private_key::PublicKeyFromPlaintextPrivateKey), #[strum_discriminants(strum( message = "from-keychain - Get the public key stored in a secure keychain" ))] /// Get the public key (full access key) stored in a secure keychain FromKeychain(self::from_keychain::PublicKeyFromKeychain), #[strum_discriminants(strum( message = "from-legacy-keychain - Get the public key stored in the legacy keychain (compatible with the old near CLI)" ))] /// Get the public key (full access key) stored in the legacy keychain (compatible with the old near CLI) FromLegacyKeychain(self::from_legacy_keychain::PublicKeyFromKeychain), #[strum_discriminants(strum( message = "from-mpc - Get the public key by deriving it from AccountIds and derivation path with MPC contract" ))] /// Get the public key by deriving it from AccountIds and derivation path with MPC contract FromMpc(self::from_mpc::PublicKeyFromMpc), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/get_public_key/from_seed_phrase/mod.rs
src/commands/account/get_public_key/from_seed_phrase/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = PublicKeyFromSeedPhraseContext)] pub struct PublicKeyFromSeedPhrase { /// Enter the seed-phrase: master_seed_phrase: String, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] seed_phrase_hd_path: crate::types::slip10::BIP32Path, } #[derive(Debug, Clone)] pub struct PublicKeyFromSeedPhraseContext; impl PublicKeyFromSeedPhraseContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<PublicKeyFromSeedPhrase as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let public_key = crate::common::get_public_key_from_seed_phrase( scope.seed_phrase_hd_path.clone().into(), &scope.master_seed_phrase, )?; if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = previous_context.verbosity { eprint!("Public key (printed to stdout): "); } println!("{public_key}"); Ok(Self) } } impl PublicKeyFromSeedPhrase { pub fn input_seed_phrase_hd_path( _context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::slip10::BIP32Path>> { crate::transaction_signature_options::sign_with_seed_phrase::input_seed_phrase_hd_path() } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/get_public_key/from_mpc/mod.rs
src/commands/account/get_public_key/from_mpc/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = PublicKeyFromMpcContext)] pub struct PublicKeyFromMpc { #[interactive_clap(skip_default_input_arg)] /// What is the controllable account address (where public key would've been published)? controllable_account_id: crate::types::account_id::AccountId, #[interactive_clap(skip_default_input_arg)] /// What is the admin account address? admin_account_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] /// What is key type for deriving key? mpc_key_type: MpcKeyType, } #[derive(Clone)] pub struct PublicKeyFromMpcContext { global_context: crate::GlobalContext, controllable_account_id: near_primitives::types::AccountId, admin_account_id: near_primitives::types::AccountId, } impl PublicKeyFromMpcContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<PublicKeyFromMpc as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { if previous_context.offline { eprintln!("\nInternet connection is required to derive key from MPC contract!"); return Err(color_eyre::eyre::eyre!( "Internet connection is required to derive key from MPC contract!" )); } Ok(Self { global_context: previous_context, controllable_account_id: scope.controllable_account_id.clone().into(), admin_account_id: scope.admin_account_id.clone().into(), }) } } impl PublicKeyFromMpc { fn input_controllable_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_non_signer_account_id_from_used_account_list( &context.config.credentials_home_dir, "What is the controllable account address (where public key would've been published)?", ) } fn input_admin_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_non_signer_account_id_from_used_account_list( &context.config.credentials_home_dir, "What is the admin account address?", ) } } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = PublicKeyFromMpcContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// What is the key type for derivation (if unsure choose Ed25519)? pub enum MpcKeyType { #[strum_discriminants(strum(message = "ed25519 - use Ed25519 key derivation"))] /// Use Ed25519 key Ed25519(MpcKeyTypeEd), #[strum_discriminants(strum(message = "secp256k1 - use Secp256K1 key derivation"))] /// Use Secp256K1 key Secp256k1(MpcKeyTypeSecp), } #[derive(Clone)] pub struct MpcKeyTypeContext { global_context: crate::GlobalContext, controllable_account_id: near_primitives::types::AccountId, admin_account_id: near_primitives::types::AccountId, key_type: near_crypto::KeyType, } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = PublicKeyFromMpcContext)] #[interactive_clap(output_context = MpcKeyTypeSecpContext)] pub struct MpcKeyTypeSecp { #[interactive_clap(named_arg)] /// What is the derivation path? derivation_path: MpcDerivationPath, } #[derive(Clone)] struct MpcKeyTypeSecpContext(MpcKeyTypeContext); impl MpcKeyTypeSecpContext { fn from_previous_context( previous_context: PublicKeyFromMpcContext, _scope: &<MpcKeyTypeSecp as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(MpcKeyTypeContext { global_context: previous_context.global_context, controllable_account_id: previous_context.controllable_account_id, admin_account_id: previous_context.admin_account_id, key_type: near_crypto::KeyType::SECP256K1, })) } } impl From<MpcKeyTypeSecpContext> for MpcKeyTypeContext { fn from(item: MpcKeyTypeSecpContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = PublicKeyFromMpcContext)] #[interactive_clap(output_context = MpcKeyTypeEdContext)] pub struct MpcKeyTypeEd { #[interactive_clap(named_arg)] /// What is the derivation path? derivation_path: MpcDerivationPath, } #[derive(Clone)] struct MpcKeyTypeEdContext(MpcKeyTypeContext); impl MpcKeyTypeEdContext { fn from_previous_context( previous_context: PublicKeyFromMpcContext, _scope: &<MpcKeyTypeEd as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(MpcKeyTypeContext { global_context: previous_context.global_context, controllable_account_id: previous_context.controllable_account_id, admin_account_id: previous_context.admin_account_id, key_type: near_crypto::KeyType::ED25519, })) } } impl From<MpcKeyTypeEdContext> for MpcKeyTypeContext { fn from(item: MpcKeyTypeEdContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = MpcKeyTypeContext)] #[interactive_clap(output_context = MpcDerivationPathContext)] pub struct MpcDerivationPath { #[interactive_clap(skip_default_input_arg, always_quote)] /// What is the derivation path? derivation_path: String, #[interactive_clap(named_arg)] /// Select network network_config: crate::network::Network, } #[derive(Clone)] pub struct MpcDerivationPathContext { global_context: crate::GlobalContext, admin_account_id: near_primitives::types::AccountId, key_type: near_crypto::KeyType, derivation_path: String, } impl MpcDerivationPathContext { fn from_previous_context( previous_context: MpcKeyTypeContext, scope: &<MpcDerivationPath as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, admin_account_id: previous_context.admin_account_id, key_type: previous_context.key_type, derivation_path: scope.derivation_path.clone(), }) } } impl MpcDerivationPath { fn input_derivation_path( context: &MpcKeyTypeContext, ) -> color_eyre::eyre::Result<Option<String>> { let derivation_path = inquire::Text::new("What is the derivation path?") .with_initial_value(&format!( "{}-{}", context.admin_account_id, context.controllable_account_id, )) .prompt()?; Ok(Some(derivation_path)) } } impl From<MpcDerivationPathContext> for crate::network::NetworkContext { fn from(item: MpcDerivationPathContext) -> Self { let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback = std::sync::Arc::new({ move |network_config| { let derived_public_key = crate::transaction_signature_options::sign_with_mpc::derive_public_key( &network_config.get_mpc_contract_account_id()?, &item.admin_account_id, &item.derivation_path, &item.key_type, network_config, )?; if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = item.global_context.verbosity { eprint!("Public key (printed to stdout): "); } println!("{derived_public_key}"); Ok(()) } }); Self { config: item.global_context.config, // NOTE: We cannot determine MPC contract AccountId until we get NetworkConfig where // it's stored, resulting in passing only signer AccountId interacting_with_account_ids: vec![], on_after_getting_network_callback, } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/account/get_public_key/from_keychain/mod.rs
src/commands/account/get_public_key/from_keychain/mod.rs
use color_eyre::eyre::WrapErr; use crate::common::JsonRpcClientExt; use crate::common::RpcQueryResponseExt; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = PublicKeyFromKeychainContext)] pub struct PublicKeyFromKeychain { #[interactive_clap(skip_default_input_arg)] /// For which account do you need to view the public key? owner_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network::Network, } #[derive(Clone)] pub struct PublicKeyFromKeychainContext(crate::network::NetworkContext); impl PublicKeyFromKeychainContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<PublicKeyFromKeychain as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let account_id = scope.owner_account_id.clone(); let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback = std::sync::Arc::new({ move |network_config| { if previous_context.offline { eprintln!( "\nThe signer's public key cannot be verified and retrieved offline." ); return Ok(()); } let service_name = std::borrow::Cow::Owned(format!( "near-{}-{}", network_config.network_name, &account_id )); let password = { let access_key_list = network_config .json_rpc_client() .blocking_call_view_access_key_list( &account_id.clone().into(), near_primitives::types::Finality::Final.into(), ) .wrap_err_with(|| { format!("Failed to fetch access key list for {account_id}") })? .access_key_list_view()?; let res = access_key_list .keys .into_iter() .filter(|key| { matches!( key.access_key.permission, near_primitives::views::AccessKeyPermissionView::FullAccess ) }) .map(|key| key.public_key) .find_map(|public_key| { let keyring = keyring::Entry::new( &service_name, &format!("{account_id}:{public_key}"), ) .ok()?; keyring.get_password().ok() }); match res { Some(password) => password, None => { // no access keys found eprintln!("\nNo access keys found in keychain",); return Ok(()); } } }; let account_key_pair: crate::transaction_signature_options::AccountKeyPair = serde_json::from_str(&password).wrap_err("Error reading data")?; if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = previous_context.verbosity { eprint!("Public key (printed to stdout): "); } println!("{}", account_key_pair.public_key); Ok(()) } }); Ok(Self(crate::network::NetworkContext { config: previous_context.config, interacting_with_account_ids: vec![scope.owner_account_id.clone().into()], on_after_getting_network_callback, })) } } impl PublicKeyFromKeychain { pub fn input_owner_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_signer_account_id_from_used_account_list( &context.config.credentials_home_dir, "For which account do you need to view the public key?", ) } } impl From<PublicKeyFromKeychainContext> for crate::network::NetworkContext { fn from(item: PublicKeyFromKeychainContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false