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/account/get_public_key/from_ledger/mod.rs | src/commands/account/get_public_key/from_ledger/mod.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = PublicKeyFromLedgerContext)]
pub struct PublicKeyFromLedger {
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
seed_phrase_hd_path: crate::types::slip10::BIP32Path,
}
#[derive(Debug, Clone)]
pub struct PublicKeyFromLedgerContext {}
impl PublicKeyFromLedgerContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<PublicKeyFromLedger 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 verifying_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(
verifying_key.to_bytes(),
));
if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe =
previous_context.verbosity
{
eprint!("Public key (printed to stdout): ");
}
println!("{public_key}");
Ok(Self {})
}
}
impl PublicKeyFromLedger {
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/get_public_key/from_plaintext_private_key/mod.rs | src/commands/account/get_public_key/from_plaintext_private_key/mod.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = PublicKeyFromPlaintextPrivateKeyContext)]
pub struct PublicKeyFromPlaintextPrivateKey {
/// Enter your private (secret) key:
private_key: crate::types::secret_key::SecretKey,
}
#[derive(Debug, Clone)]
pub struct PublicKeyFromPlaintextPrivateKeyContext {}
impl PublicKeyFromPlaintextPrivateKeyContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<PublicKeyFromPlaintextPrivateKey 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();
if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe =
previous_context.verbosity
{
eprint!("Public key (printed to stdout): ");
}
println!("{public_key}");
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/account/get_public_key/from_legacy_keychain/mod.rs | src/commands/account/get_public_key/from_legacy_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 = PublicKeyFromLegacyKeychainContext)]
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 PublicKeyFromLegacyKeychainContext(crate::network::NetworkContext);
impl PublicKeyFromLegacyKeychainContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<PublicKeyFromKeychain as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let config = previous_context.config.clone();
let account_id = scope.owner_account_id.clone();
let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback =
std::sync::Arc::new({
move |network_config| {
let keychain_folder = config
.credentials_home_dir
.join(&network_config.network_name);
let signer_keychain_folder = keychain_folder.join(account_id.to_string());
let signer_access_key_file_path: std::path::PathBuf = {
if previous_context.offline {
eprintln!(
"\nThe signer's public key cannot be verified and retrieved offline."
);
return Ok(());
}
if signer_keychain_folder.exists() {
let full_access_key_filenames = 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 KeyList for {account_id}"
)
})?
.access_key_list_view()?
.keys
.iter()
.filter(
|access_key_info| match access_key_info.access_key.permission {
near_primitives::views::AccessKeyPermissionView::FullAccess => true,
near_primitives::views::AccessKeyPermissionView::FunctionCall {
..
} => false,
},
)
.map(|access_key_info| {
format!(
"{}.json",
access_key_info.public_key.to_string().replace(":", "_")
)
.into()
})
.collect::<std::collections::HashSet<std::ffi::OsString>>();
signer_keychain_folder
.read_dir()
.wrap_err("There are no access keys found in the keychain for the signer account. Import an access key for an account before signing transactions with keychain.")?
.filter_map(Result::ok)
.find(|entry| full_access_key_filenames.contains(&entry.file_name()))
.map(|signer_access_key| signer_access_key.path())
.unwrap_or_else(|| keychain_folder.join(format!(
"{account_id}.json"
)))
} else {
keychain_folder.join(format!("{account_id}.json"))
}
};
let signer_access_key_json =
std::fs::read(&signer_access_key_file_path).wrap_err_with(|| {
format!(
"Access key file for account <{}> on network <{}> not found! \nSearch location: {:?}",
account_id,
network_config.network_name, signer_access_key_file_path
)
})?;
let account_key_pair: crate::transaction_signature_options::AccountKeyPair =
serde_json::from_slice(&signer_access_key_json).wrap_err_with(|| {
format!(
"Error reading data from file: {:?}",
&signer_access_key_file_path
)
})?;
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<PublicKeyFromLegacyKeychainContext> for crate::network::NetworkContext {
fn from(item: PublicKeyFromLegacyKeychainContext) -> 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/view_account_summary/mod.rs | src/commands/account/view_account_summary/mod.rs | use color_eyre::eyre::Context;
use futures::{StreamExt, TryStreamExt};
use tracing_indicatif::span_ext::IndicatifSpanExt;
use crate::common::{CallResultExt, JsonRpcClientExt, RpcQueryResponseExt};
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = ViewAccountSummaryContext)]
pub struct ViewAccountSummary {
#[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 ViewAccountSummaryContext(crate::network_view_at_block::ArgsForViewContext);
impl ViewAccountSummaryContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<ViewAccountSummary 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| {
get_account_inquiry(&account_id, network_config, block_reference)
}
});
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<ViewAccountSummaryContext> for crate::network_view_at_block::ArgsForViewContext {
fn from(item: ViewAccountSummaryContext) -> Self {
item.0
}
}
impl ViewAccountSummary {
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?",
)
}
}
#[tracing::instrument(name = "Receiving an inquiry about your account ...", skip_all)]
pub fn get_account_inquiry(
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", "Receiving an inquiry about your account ...");
let json_rpc_client = network_config.json_rpc_client();
let rpc_query_response = json_rpc_client
.blocking_call_view_account(account_id, block_reference.clone())
.wrap_err_with(|| {
format!(
"Failed to fetch query ViewAccount for account <{}> on network <{}>",
account_id, network_config.network_name
)
})?;
let account_view = rpc_query_response.account_view()?;
let access_key_list = network_config
.json_rpc_client()
.blocking_call_view_access_key_list(account_id, block_reference.clone())
.map_err(|err| {
tracing::warn!(
"Failed to fetch query ViewAccessKeyList for account <{}> on network <{}>: {:#}",
account_id,
network_config.network_name,
err
);
})
.ok()
.and_then(|query_response| {
query_response
.access_key_list_view()
.map_err(|err| {
tracing::warn!(
"Failed to parse ViewAccessKeyList for account <{}> on network <{}>: {:#}",
account_id,
network_config.network_name,
err
);
})
.ok()
});
let historically_delegated_validators =
network_config
.fastnear_url
.as_ref()
.and_then(|fastnear_url| {
crate::common::fetch_historically_delegated_staking_pools(fastnear_url, account_id)
.ok()
});
let pools_to_query = if let Some(user_staked_pools) = historically_delegated_validators {
Ok(user_staked_pools)
} else if let Some(staking_pools_factory_account_id) =
&network_config.staking_pools_factory_account_id
{
crate::common::fetch_currently_active_staking_pools(
&json_rpc_client,
staking_pools_factory_account_id,
)
} else {
Ok(Default::default())
};
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?;
// Staring from Feb 2025, the rate limit is 150 requests per 30 seconds for mainnet.
// We will limit the number of requests per batch to 140 to be conservative.
let batch_size = 140;
let batch_cooldown = tokio::time::Duration::from_secs(30);
let concurrency = 10; // Process 10 requests concurrently within each batch
let delegated_stake: color_eyre::Result<
std::collections::BTreeMap<near_primitives::types::AccountId, near_token::NearToken>,
> = match pools_to_query {
Ok(validators) => {
let mut all_results = Ok(std::collections::BTreeMap::new());
let validators: Vec<_> = validators.into_iter().collect();
for (batch_index, validator_batch) in validators
.chunks(batch_size)
.map(|x| x.to_vec())
.enumerate()
{
if batch_index > 0 {
// Wait 30 seconds before starting next batch
tracing::info!(
"Waiting for 30 seconds before fetching next batch of stake information"
);
runtime.block_on(async { tokio::time::sleep(batch_cooldown).await });
}
let batch_results = runtime.block_on(
futures::stream::iter(validator_batch)
.map(|validator_account_id| async {
let balance = get_delegated_staked_balance(
&json_rpc_client,
block_reference,
&validator_account_id,
account_id,
)
.await?;
Ok::<_, color_eyre::eyre::Report>((validator_account_id, balance))
})
.buffer_unordered(concurrency)
.filter(|balance_result| {
futures::future::ready(if let Ok((_, balance)) = balance_result {
!balance.is_zero()
} else {
true
})
})
.try_collect::<std::collections::BTreeMap<_, _>>(),
);
match batch_results {
Ok(batch_results) => {
let _ = all_results.as_mut().map(|all_results| {
all_results.extend(batch_results);
});
}
Err(err) => {
all_results = Err(err);
break;
}
};
}
all_results
}
Err(err) => Err(err),
};
let optional_account_profile = get_account_profile(account_id, network_config, block_reference)
.ok()
.flatten();
crate::common::display_account_info(
&rpc_query_response.block_hash,
&rpc_query_response.block_height,
account_id,
delegated_stake,
&account_view,
access_key_list.as_ref(),
optional_account_profile.as_ref(),
);
Ok(())
}
#[tracing::instrument(
name = "Receiving the delegated staked balance from validator",
skip_all
)]
async fn get_delegated_staked_balance(
json_rpc_client: &near_jsonrpc_client::JsonRpcClient,
block_reference: &near_primitives::types::BlockReference,
staking_pool_account_id: &near_primitives::types::AccountId,
account_id: &near_primitives::types::AccountId,
) -> color_eyre::eyre::Result<near_token::NearToken> {
tracing::Span::current().pb_set_message(staking_pool_account_id.as_str());
tracing::info!(target: "near_teach_me", "Receiving the delegated staked balance from validator {staking_pool_account_id}");
let account_staked_balance_response = json_rpc_client
.call(near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference: block_reference.clone(),
request: near_primitives::views::QueryRequest::CallFunction {
account_id: staking_pool_account_id.clone(),
method_name: "get_account_staked_balance".to_string(),
args: near_primitives::types::FunctionArgs::from(serde_json::to_vec(
&serde_json::json!({
"account_id": account_id,
}),
)?),
},
})
.await;
match account_staked_balance_response {
Ok(response) => Ok(near_token::NearToken::from_yoctonear(
response
.call_result()?
.parse_result_from_json::<String>()
.wrap_err("Failed to parse return value of view function call for String.")?
.parse::<u128>()?,
)),
Err(near_jsonrpc_client::errors::JsonRpcError::ServerError(
near_jsonrpc_client::errors::JsonRpcServerError::HandlerError(
near_jsonrpc_client::methods::query::RpcQueryError::NoContractCode { .. }
| near_jsonrpc_client::methods::query::RpcQueryError::ContractExecutionError {
..
},
),
)) => Ok(near_token::NearToken::from_yoctonear(0)),
Err(err) => Err(err.into()),
}
}
#[tracing::instrument(name = "Getting an account profile ...", skip_all)]
fn get_account_profile(
account_id: &near_primitives::types::AccountId,
network_config: &crate::config::NetworkConfig,
block_reference: &near_primitives::types::BlockReference,
) -> color_eyre::Result<Option<near_socialdb_client::types::socialdb_types::AccountProfile>> {
tracing::info!(target: "near_teach_me", "Getting an account profile ...");
if let Ok(contract_account_id) = network_config.get_near_social_account_id_from_network() {
let mut social_db = network_config
.json_rpc_client()
.blocking_call_view_function(
&contract_account_id,
"get",
serde_json::to_vec(&serde_json::json!({
"keys": vec![format!("{account_id}/profile/**")],
}))?,
block_reference.clone(),
)
.wrap_err_with(|| {
format!("Failed to fetch query for view method: 'get {account_id}/profile/**' (contract <{}> on network <{}>)",
contract_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.")
})?;
Ok(social_db.accounts.remove(account_id))
} 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/storage_management/storage_deposit.rs | src/commands/account/storage_management/storage_deposit.rs | use inquire::Select;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::ContractContext)]
#[interactive_clap(output_context = DepositArgsContext)]
pub struct DepositArgs {
#[interactive_clap(skip_default_input_arg)]
/// Which account ID do you want to add a deposit to?
receiver_account_id: crate::types::account_id::AccountId,
/// Enter the amount to deposit into the storage (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear):
deposit: crate::types::near_token::NearToken,
#[interactive_clap(named_arg)]
/// What is the signer account ID?
sign_as: SignerAccountId,
}
#[derive(Clone)]
pub struct DepositArgsContext {
global_context: crate::GlobalContext,
get_contract_account_id: super::GetContractAccountId,
receiver_account_id: near_primitives::types::AccountId,
deposit: crate::types::near_token::NearToken,
}
impl DepositArgsContext {
pub fn from_previous_context(
previous_context: super::ContractContext,
scope: &<DepositArgs as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context.global_context,
get_contract_account_id: previous_context.get_contract_account_id,
receiver_account_id: scope.receiver_account_id.clone().into(),
deposit: scope.deposit,
})
}
}
impl DepositArgs {
fn input_receiver_account_id(
context: &super::ContractContext,
) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> {
loop {
let receiver_account_id = if let Some(account_id) =
crate::common::input_signer_account_id_from_used_account_list(
&context.global_context.config.credentials_home_dir,
"Which account ID do you want to add a deposit to?",
)? {
account_id
} else {
return Ok(None);
};
if context.global_context.offline {
return Ok(Some(receiver_account_id));
}
if !crate::common::is_account_exist(
&context.global_context.config.network_connection,
receiver_account_id.clone().into(),
)? {
eprintln!(
"\nThe account <{receiver_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 receiver account id?",
vec![ConfirmOptions::Yes, ConfirmOptions::No],
)
.prompt()?;
if let ConfirmOptions::No = select_choose_input {
return Ok(Some(receiver_account_id));
}
} else {
return Ok(Some(receiver_account_id));
}
}
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = DepositArgsContext)]
#[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(crate::commands::ActionContext);
impl SignerAccountIdContext {
pub fn from_previous_context(
previous_context: DepositArgsContext,
scope: &<SignerAccountId 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_account_id: near_primitives::types::AccountId =
scope.signer_account_id.clone().into();
let receiver_account_id = previous_context.receiver_account_id.clone();
let get_contract_account_id = previous_context.get_contract_account_id.clone();
let deposit = previous_context.deposit;
move |network_config| {
Ok(crate::commands::PrepopulatedTransaction {
signer_id: signer_account_id.clone(),
receiver_id: get_contract_account_id(network_config)?,
actions: vec![near_primitives::transaction::Action::FunctionCall(
Box::new(near_primitives::transaction::FunctionCallAction {
method_name: "storage_deposit".to_string(),
args: serde_json::to_vec(&serde_json::json!({
"account_id": &receiver_account_id
}))?,
gas: near_primitives::gas::Gas::from_teragas(50),
deposit: deposit.into(),
}),
)],
})
}
});
let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = std::sync::Arc::new({
let signer_account_id: near_primitives::types::AccountId = scope.signer_account_id.clone().into();
let receiver_account_id = previous_context.receiver_account_id.clone();
let verbosity = previous_context.global_context.verbosity;
move |outcome_view, network_config| {
let contract_account_id = (previous_context.get_contract_account_id)(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_account_id}> has successfully added a deposit of {deposit} to <{receiver_account_id}> on contract <{contract_account_id}>.",
deposit = previous_context.deposit
);
});
}
}
Ok(())
}
});
Ok(Self(crate::commands::ActionContext {
global_context: previous_context.global_context,
interacting_with_account_ids: vec![
scope.signer_account_id.clone().into(),
previous_context.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,
}))
}
}
impl From<SignerAccountIdContext> for crate::commands::ActionContext {
fn from(item: SignerAccountIdContext) -> Self {
item.0
}
}
impl SignerAccountId {
fn input_signer_account_id(
context: &DepositArgsContext,
) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> {
crate::common::input_signer_account_id_from_used_account_list(
&context.global_context.config.credentials_home_dir,
"What is the signer 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/storage_management/storage_withdraw.rs | src/commands/account/storage_management/storage_withdraw.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::ContractContext)]
#[interactive_clap(output_context = WithdrawArgsContext)]
pub struct WithdrawArgs {
/// Enter the amount to withdraw from the storage (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear):
amount: crate::types::near_token::NearToken,
#[interactive_clap(named_arg)]
/// What is the signer account ID?
sign_as: SignerAccountId,
}
#[derive(Clone)]
pub struct WithdrawArgsContext {
global_context: crate::GlobalContext,
get_contract_account_id: super::GetContractAccountId,
amount: crate::types::near_token::NearToken,
}
impl WithdrawArgsContext {
pub fn from_previous_context(
previous_context: super::ContractContext,
scope: &<WithdrawArgs as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context.global_context,
get_contract_account_id: previous_context.get_contract_account_id,
amount: scope.amount,
})
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = WithdrawArgsContext)]
#[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(crate::commands::ActionContext);
impl SignerAccountIdContext {
pub fn from_previous_context(
previous_context: WithdrawArgsContext,
scope: &<SignerAccountId 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_account_id: near_primitives::types::AccountId =
scope.signer_account_id.clone().into();
let get_contract_account_id = previous_context.get_contract_account_id.clone();
let amount = previous_context.amount;
move |network_config| {
Ok(crate::commands::PrepopulatedTransaction {
signer_id: signer_account_id.clone(),
receiver_id: get_contract_account_id(network_config)?,
actions: vec![near_primitives::transaction::Action::FunctionCall(
Box::new(near_primitives::transaction::FunctionCallAction {
method_name: "storage_withdraw".to_string(),
args: serde_json::to_vec(&serde_json::json!({
"amount": amount.clone().as_yoctonear().to_string()
}))?,
gas: near_primitives::gas::Gas::from_teragas(50),
deposit: near_token::NearToken::from_yoctonear(1),
}),
)],
})
}
});
let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = std::sync::Arc::new({
let signer_account_id: near_primitives::types::AccountId = scope.signer_account_id.clone().into();
let verbosity = previous_context.global_context.verbosity;
move |outcome_view, network_config| {
let contract_account_id = (previous_context.get_contract_account_id)(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_account_id}> has successfully withdraw {amount} from <{contract_account_id}>.",
amount = previous_context.amount,
);
});
}
}
Ok(())
}
});
Ok(Self(crate::commands::ActionContext {
global_context: previous_context.global_context,
interacting_with_account_ids: vec![scope.signer_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<SignerAccountIdContext> for crate::commands::ActionContext {
fn from(item: SignerAccountIdContext) -> Self {
item.0
}
}
impl SignerAccountId {
pub fn input_signer_account_id(
context: &WithdrawArgsContext,
) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> {
crate::common::input_signer_account_id_from_used_account_list(
&context.global_context.config.credentials_home_dir,
"What is the signer 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/storage_management/mod.rs | src/commands/account/storage_management/mod.rs | use strum::{EnumDiscriminants, EnumIter, EnumMessage};
mod storage_deposit;
mod storage_withdraw;
mod view_storage_balance;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = ContractContext)]
pub struct Contract {
#[interactive_clap(skip_default_input_arg)]
/// Which contract account ID do you want to manage the storage deposit for?
contract_account_id: crate::types::account_id::AccountId,
#[interactive_clap(subcommand)]
storage_actions: StorageActions,
}
#[derive(Clone)]
pub struct ContractContext {
pub global_context: crate::GlobalContext,
pub get_contract_account_id: GetContractAccountId,
}
impl ContractContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<Contract as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let contract_account_id = scope.contract_account_id.clone();
let get_contract_account_id: GetContractAccountId =
std::sync::Arc::new(move |_network_config| Ok(contract_account_id.clone().into()));
Ok(Self {
global_context: previous_context,
get_contract_account_id,
})
}
}
pub type GetContractAccountId = std::sync::Arc<
dyn Fn(
&crate::config::NetworkConfig,
) -> color_eyre::eyre::Result<near_primitives::types::AccountId>,
>;
impl Contract {
pub fn input_contract_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 contract account ID do you want to manage the storage deposit for?",
)
}
}
#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = ContractContext)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
/// What do you want to do with the storage?
pub enum StorageActions {
#[strum_discriminants(strum(
message = "view-balance - View storage balance for an account"
))]
/// View storage balance for an account
ViewBalance(self::view_storage_balance::Account),
#[strum_discriminants(strum(
message = "deposit - Make a storage deposit for the account"
))]
/// Make a storage deposit for the account
Deposit(self::storage_deposit::DepositArgs),
#[strum_discriminants(strum(
message = "withdraw - Withdraw a deposit from storage for an account ID"
))]
/// Withdraw a deposit from storage for an account ID
Withdraw(self::storage_withdraw::WithdrawArgs),
}
| 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/storage_management/view_storage_balance.rs | src/commands/account/storage_management/view_storage_balance.rs | use color_eyre::eyre::WrapErr;
use tracing_indicatif::span_ext::IndicatifSpanExt;
use crate::common::{CallResultExt, JsonRpcClientExt};
const STORAGE_COST_PER_BYTE: u128 = 10u128.pow(19);
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::ContractContext)]
#[interactive_clap(output_context = AccountContext)]
pub struct Account {
#[interactive_clap(skip_default_input_arg)]
/// What is your account ID?
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 AccountContext(crate::network_view_at_block::ArgsForViewContext);
impl AccountContext {
pub fn from_previous_context(
previous_context: super::ContractContext,
scope: &<Account 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 = scope.account_id.clone();
move |network_config, block_reference| {
let contract_account_id = (previous_context.get_contract_account_id)(network_config)?;
let storage_balance = get_storage_balance(network_config, &contract_account_id, &account_id, block_reference)?;
eprintln!("storage balance for <{account_id}>:");
eprintln!(" {:<13} {:>10} ({} [{:>28} yoctoNEAR])",
"available:",
bytesize::ByteSize(u64::try_from(storage_balance.available / STORAGE_COST_PER_BYTE).unwrap()),
near_token::NearToken::from_yoctonear(storage_balance.available),
storage_balance.available
);
eprintln!(" {:<13} {:>10} ({} [{:>28} yoctoNEAR])",
"total:",
bytesize::ByteSize(u64::try_from(storage_balance.total / STORAGE_COST_PER_BYTE).unwrap()),
near_token::NearToken::from_yoctonear(storage_balance.total),
storage_balance.total
);
Ok(())
}
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
config: previous_context.global_context.config,
interacting_with_account_ids: vec![scope.account_id.clone().into()],
on_after_getting_block_reference_callback,
}))
}
}
impl From<AccountContext> for crate::network_view_at_block::ArgsForViewContext {
fn from(item: AccountContext) -> Self {
item.0
}
}
impl Account {
pub fn input_account_id(
context: &super::ContractContext,
) -> 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 your account ID?",
)
}
}
#[tracing::instrument(name = "Getting storage balance for", skip_all)]
fn get_storage_balance(
network_config: &crate::config::NetworkConfig,
contract_account_id: &near_primitives::types::AccountId,
account_id: &crate::types::account_id::AccountId,
block_reference: &near_primitives::types::BlockReference,
) -> color_eyre::eyre::Result<near_socialdb_client::StorageBalance> {
tracing::Span::current().pb_set_message(account_id.as_ref());
tracing::info!(target: "near_teach_me", "Getting storage balance for {account_id}");
network_config
.json_rpc_client()
.blocking_call_view_function(
contract_account_id,
"storage_balance_of",
serde_json::to_vec(&serde_json::json!({
"account_id": account_id.to_string(),
}))?,
block_reference.clone(),
)
.wrap_err_with(|| {
format!("Failed to fetch query for view method: 'storage_balance_of' (contract <{}> on network <{}>)",
contract_account_id,
network_config.network_name
)
})?
.parse_result_from_json::<near_socialdb_client::StorageBalance>()
.wrap_err("Failed to parse return value of view function call for StorageBalance.")
}
| 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/tokens/mod.rs | src/commands/tokens/mod.rs | use strum::{EnumDiscriminants, EnumIter, EnumMessage};
mod send_ft;
mod send_near;
mod send_nft;
mod view_ft_balance;
mod view_near_balance;
mod view_nft_assets;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = TokensCommandsContext)]
pub struct TokensCommands {
#[interactive_clap(skip_default_input_arg)]
/// What is your account ID?
owner_account_id: crate::types::account_id::AccountId,
#[interactive_clap(subcommand)]
tokens_actions: TokensActions,
}
#[derive(Debug, Clone)]
pub struct TokensCommandsContext {
global_context: crate::GlobalContext,
owner_account_id: near_primitives::types::AccountId,
}
impl TokensCommandsContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<TokensCommands 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 TokensCommands {
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,
"What is your account ID?",
)
}
}
#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = TokensCommandsContext)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
#[non_exhaustive]
/// Select actions with tokens:
pub enum TokensActions {
#[strum_discriminants(strum(
message = "send-near - The transfer is carried out in NEAR tokens"
))]
/// The transfer is carried out in NEAR tokens
SendNear(self::send_near::SendNearCommand),
#[strum_discriminants(strum(
message = "send-ft - The transfer is carried out in FT tokens"
))]
/// The transfer is carried out in FT tokens
SendFt(self::send_ft::SendFtCommand),
#[strum_discriminants(strum(
message = "send-nft - The transfer is carried out in NFT tokens"
))]
/// The transfer is carried out in NFT tokens
SendNft(self::send_nft::SendNftCommand),
#[strum_discriminants(strum(message = "view-near-balance - View the balance of Near tokens"))]
/// View the balance of Near tokens
ViewNearBalance(self::view_near_balance::ViewNearBalance),
#[strum_discriminants(strum(message = "view-ft-balance - View the balance of FT tokens"))]
/// View the balance of FT tokens
ViewFtBalance(self::view_ft_balance::ViewFtBalance),
#[strum_discriminants(strum(message = "view-nft-assets - View the balance of NFT tokens"))]
/// View the balance of NFT tokens
ViewNftAssets(self::view_nft_assets::ViewNftAssets),
}
| 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/tokens/view_nft_assets/mod.rs | src/commands/tokens/view_nft_assets/mod.rs | use color_eyre::eyre::Context;
use serde_json::json;
use crate::common::CallResultExt;
use crate::common::JsonRpcClientExt;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::TokensCommandsContext)]
#[interactive_clap(output_context = ViewNftAssetsContext)]
pub struct ViewNftAssets {
#[interactive_clap(skip_default_input_arg)]
/// What is the nft-contract account ID?
nft_contract_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 ViewNftAssetsContext(crate::network_view_at_block::ArgsForViewContext);
impl ViewNftAssetsContext {
pub fn from_previous_context(
previous_context: super::TokensCommandsContext,
scope: &<ViewNftAssets 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 owner_account_id = previous_context.owner_account_id.clone();
let nft_contract_account_id: near_primitives::types::AccountId =
scope.nft_contract_account_id.clone().into();
move |network_config, block_reference| {
let args = serde_json::to_vec(&json!({
"account_id": owner_account_id.to_string(),
}))?;
let call_result = get_nft_balance(network_config, &nft_contract_account_id, args, block_reference.clone())?;
call_result.print_logs();
let serde_call_result: serde_json::Value = call_result.parse_result_from_json()?;
if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = previous_context.global_context.verbosity {
eprintln!("\n{} account has NFT tokens (printed to stdout):", owner_account_id);
}
println!("{}", serde_json::to_string_pretty(&serde_call_result)?);
Ok(())
}
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
config: previous_context.global_context.config,
on_after_getting_block_reference_callback,
interacting_with_account_ids: vec![
scope.nft_contract_account_id.clone().into(),
previous_context.owner_account_id,
],
}))
}
}
impl From<ViewNftAssetsContext> for crate::network_view_at_block::ArgsForViewContext {
fn from(item: ViewNftAssetsContext) -> Self {
item.0
}
}
impl ViewNftAssets {
pub fn input_nft_contract_account_id(
context: &super::TokensCommandsContext,
) -> 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 nft-contract account ID?",
)
}
}
#[tracing::instrument(name = "Getting NFT balance ...", skip_all)]
fn get_nft_balance(
network_config: &crate::config::NetworkConfig,
nft_contract_account_id: &near_primitives::types::AccountId,
args: Vec<u8>,
block_reference: near_primitives::types::BlockReference,
) -> color_eyre::eyre::Result<near_primitives::views::CallResult> {
tracing::info!(target: "near_teach_me", "Getting NFT balance ...");
network_config
.json_rpc_client()
.blocking_call_view_function(
nft_contract_account_id,
"nft_tokens_for_owner",
args,
block_reference,
)
.wrap_err_with(||{
format!("Failed to fetch query for view method: 'nft_tokens_for_owner' (contract <{}> on network <{}>)",
nft_contract_account_id,
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/tokens/send_near/mod.rs | src/commands/tokens/send_near/mod.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::TokensCommandsContext)]
#[interactive_clap(output_context = SendNearCommandContext)]
pub struct SendNearCommand {
#[interactive_clap(skip_default_input_arg)]
/// What is the receiver account ID?
receiver_account_id: crate::types::account_id::AccountId,
/// How many NEAR Tokens do you want to transfer? (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear)
amount_in_near: crate::types::near_token::NearToken,
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_for_transaction::NetworkForTransactionArgs,
}
#[derive(Debug, Clone)]
pub struct SendNearCommandContext {
global_context: crate::GlobalContext,
signer_account_id: near_primitives::types::AccountId,
receiver_account_id: near_primitives::types::AccountId,
amount_in_near: crate::types::near_token::NearToken,
}
impl SendNearCommandContext {
pub fn from_previous_context(
previous_context: super::TokensCommandsContext,
scope: &<SendNearCommand 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,
receiver_account_id: scope.receiver_account_id.clone().into(),
amount_in_near: scope.amount_in_near,
})
}
}
impl From<SendNearCommandContext> for crate::commands::ActionContext {
fn from(item: SendNearCommandContext) -> 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();
let receiver_account_id = item.receiver_account_id.clone();
move |_network_config| {
Ok(crate::commands::PrepopulatedTransaction {
signer_id: signer_account_id.clone(),
receiver_id: receiver_account_id.clone(),
actions: vec![near_primitives::transaction::Action::Transfer(
near_primitives::transaction::TransferAction {
deposit: item.amount_in_near.into(),
},
)],
})
}
});
Self {
global_context: item.global_context,
interacting_with_account_ids: vec![item.signer_account_id, item.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(()),
),
}
}
}
impl SendNearCommand {
pub fn input_receiver_account_id(
context: &super::TokensCommandsContext,
) -> 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 receiver 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/tokens/view_ft_balance/mod.rs | src/commands/tokens/view_ft_balance/mod.rs | use color_eyre::eyre::Context;
use serde_json::json;
use crate::common::CallResultExt;
use crate::common::JsonRpcClientExt;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::TokensCommandsContext)]
#[interactive_clap(output_context = ViewFtBalanceContext)]
pub struct ViewFtBalance {
#[interactive_clap(skip_default_input_arg)]
/// What is the ft-contract account ID?
ft_contract_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 ViewFtBalanceContext(crate::network_view_at_block::ArgsForViewContext);
impl ViewFtBalanceContext {
pub fn from_previous_context(
previous_context: super::TokensCommandsContext,
scope: &<ViewFtBalance 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 owner_account_id = previous_context.owner_account_id.clone();
let ft_contract_account_id: near_primitives::types::AccountId =
scope.ft_contract_account_id.clone().into();
move |network_config, block_reference| {
let crate::types::ft_properties::FtMetadata { decimals, symbol } = crate::types::ft_properties::params_ft_metadata(
ft_contract_account_id.clone(),
network_config,
block_reference.clone(),
)?;
let args = serde_json::to_vec(&json!({
"account_id": owner_account_id.to_string(),
}))?;
let call_result = get_ft_balance(network_config, &ft_contract_account_id, args, block_reference.clone())?;
call_result.print_logs();
let amount: String = call_result.parse_result_from_json()?;
let fungible_token = crate::types::ft_properties::FungibleToken::from_params_ft(
amount.parse::<u128>()?,
decimals,
symbol
);
println!("<{owner_account_id}> account has {fungible_token} (FT-contract: {ft_contract_account_id})");
Ok(())
}
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
config: previous_context.global_context.config,
on_after_getting_block_reference_callback,
interacting_with_account_ids: vec![
scope.ft_contract_account_id.clone().into(),
previous_context.owner_account_id,
],
}))
}
}
impl From<ViewFtBalanceContext> for crate::network_view_at_block::ArgsForViewContext {
fn from(item: ViewFtBalanceContext) -> Self {
item.0
}
}
impl ViewFtBalance {
pub fn input_ft_contract_account_id(
context: &super::TokensCommandsContext,
) -> 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 ft-contract account ID?",
)
}
}
#[tracing::instrument(name = "Getting FT balance ...", skip_all, parent = None)]
pub fn get_ft_balance(
network_config: &crate::config::NetworkConfig,
ft_contract_account_id: &near_primitives::types::AccountId,
args: Vec<u8>,
block_reference: near_primitives::types::BlockReference,
) -> color_eyre::eyre::Result<near_primitives::views::CallResult> {
tracing::info!(target: "near_teach_me", "Getting FT balance ...");
network_config
.json_rpc_client()
.blocking_call_view_function(
ft_contract_account_id,
"ft_balance_of",
args,
block_reference,
)
.wrap_err_with(||{
format!("Failed to fetch query for view method: 'ft_balance_of' (contract <{}> on network <{}>)",
ft_contract_account_id,
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/tokens/send_nft/mod.rs | src/commands/tokens/send_nft/mod.rs | use serde_json::json;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::TokensCommandsContext)]
#[interactive_clap(output_context = SendNftCommandContext)]
pub struct SendNftCommand {
#[interactive_clap(skip_default_input_arg)]
/// What is the nft-contract account ID?
nft_contract_account_id: crate::types::account_id::AccountId,
#[interactive_clap(skip_default_input_arg)]
/// What is the receiver account ID?
receiver_account_id: crate::types::account_id::AccountId,
/// Enter an token_id for NFT:
token_id: String,
#[interactive_clap(long = "prepaid-gas")]
#[interactive_clap(skip_interactive_input)]
gas: Option<crate::common::NearGas>,
#[interactive_clap(long = "attached-deposit")]
#[interactive_clap(skip_interactive_input)]
deposit: Option<crate::types::near_token::NearToken>,
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_for_transaction::NetworkForTransactionArgs,
}
#[derive(Debug, Clone)]
pub struct SendNftCommandContext {
global_context: crate::GlobalContext,
signer_account_id: near_primitives::types::AccountId,
nft_contract_account_id: near_primitives::types::AccountId,
receiver_account_id: near_primitives::types::AccountId,
token_id: String,
gas: crate::common::NearGas,
deposit: crate::types::near_token::NearToken,
}
impl SendNftCommandContext {
pub fn from_previous_context(
previous_context: super::TokensCommandsContext,
scope: &<SendNftCommand 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,
nft_contract_account_id: scope.nft_contract_account_id.clone().into(),
receiver_account_id: scope.receiver_account_id.clone().into(),
token_id: scope.token_id.clone(),
gas: scope.gas.unwrap_or(near_gas::NearGas::from_tgas(100)),
deposit: scope
.deposit
.unwrap_or(crate::types::near_token::NearToken::from_yoctonear(1)),
})
}
}
impl From<SendNftCommandContext> for crate::commands::ActionContext {
fn from(item: SendNftCommandContext) -> 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();
let nft_contract_account_id = item.nft_contract_account_id.clone();
let receiver_account_id = item.receiver_account_id.clone();
let token_id = item.token_id.clone();
move |_network_config| {
Ok(crate::commands::PrepopulatedTransaction {
signer_id: signer_account_id.clone(),
receiver_id: nft_contract_account_id.clone(),
actions: vec![near_primitives::transaction::Action::FunctionCall(
Box::new(near_primitives::transaction::FunctionCallAction {
method_name: "nft_transfer".to_string(),
args: serde_json::to_vec(&json!({
"receiver_id": receiver_account_id.to_string(),
"token_id": token_id
}))?,
gas: near_primitives::gas::Gas::from_gas(item.gas.as_gas()),
deposit: item.deposit.into(),
}),
)],
})
}
});
let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = std::sync::Arc::new({
let signer_account_id = item.signer_account_id.clone();
let nft_contract_account_id = item.nft_contract_account_id.clone();
let receiver_account_id = item.receiver_account_id.clone();
let token_id = item.token_id.clone();
let verbosity = item.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_account_id}> has successfully transferred NFT token_id=\"{token_id}\" to <{receiver_account_id}> on contract <{nft_contract_account_id}>.",
));
}
}
Ok(())
}
});
Self {
global_context: item.global_context,
interacting_with_account_ids: vec![
item.nft_contract_account_id.clone(),
item.signer_account_id.clone(),
item.receiver_account_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,
}
}
}
impl SendNftCommand {
pub fn input_nft_contract_account_id(
context: &super::TokensCommandsContext,
) -> 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 nft-contract account ID?",
)
}
pub fn input_receiver_account_id(
context: &super::TokensCommandsContext,
) -> 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 receiver 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/tokens/view_near_balance/mod.rs | src/commands/tokens/view_near_balance/mod.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::TokensCommandsContext)]
#[interactive_clap(output_context = ViewNearBalanceContext)]
pub struct ViewNearBalance {
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_view_at_block::NetworkViewAtBlockArgs,
}
#[derive(Clone)]
pub struct ViewNearBalanceContext(crate::network_view_at_block::ArgsForViewContext);
impl ViewNearBalanceContext {
pub fn from_previous_context(
previous_context: super::TokensCommandsContext,
_scope: &<ViewNearBalance 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 owner_account_id = previous_context.owner_account_id.clone();
move |network_config, block_reference| {
let account_transfer_allowance = tokio::runtime::Runtime::new()
.unwrap()
.block_on(crate::common::get_account_transfer_allowance(
network_config,
owner_account_id.clone(),
block_reference.clone(),
))?;
println!("{account_transfer_allowance}");
Ok(())
}
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
config: previous_context.global_context.config,
interacting_with_account_ids: vec![previous_context.owner_account_id],
on_after_getting_block_reference_callback,
}))
}
}
impl From<ViewNearBalanceContext> for crate::network_view_at_block::ArgsForViewContext {
fn from(item: ViewNearBalanceContext) -> 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/tokens/send_ft/mod.rs | src/commands/tokens/send_ft/mod.rs | use color_eyre::eyre::Context;
use serde_json::{json, Value};
use crate::common::CallResultExt;
use crate::common::JsonRpcClientExt;
use super::view_ft_balance::get_ft_balance;
mod amount_ft;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::TokensCommandsContext)]
#[interactive_clap(output_context = SendFtCommandContext)]
pub struct SendFtCommand {
#[interactive_clap(skip_default_input_arg)]
/// What is the ft-contract account ID?
ft_contract_account_id: crate::types::account_id::AccountId,
#[interactive_clap(skip_default_input_arg)]
/// What is the receiver account ID?
receiver_account_id: crate::types::account_id::AccountId,
#[interactive_clap(subargs)]
/// Specify amount FT
amount_ft: self::amount_ft::AmountFt,
}
#[derive(Debug, Clone)]
pub struct SendFtCommandContext {
global_context: crate::GlobalContext,
signer_account_id: near_primitives::types::AccountId,
ft_contract_account_id: near_primitives::types::AccountId,
receiver_account_id: near_primitives::types::AccountId,
}
impl SendFtCommandContext {
pub fn from_previous_context(
previous_context: super::TokensCommandsContext,
scope: &<SendFtCommand 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,
ft_contract_account_id: scope.ft_contract_account_id.clone().into(),
receiver_account_id: scope.receiver_account_id.clone().into(),
})
}
}
impl SendFtCommand {
pub fn input_ft_contract_account_id(
context: &super::TokensCommandsContext,
) -> 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 ft-contract account ID?",
)
}
pub fn input_receiver_account_id(
context: &super::TokensCommandsContext,
) -> 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 receiver account ID?",
)
}
}
#[allow(clippy::too_many_arguments)]
#[tracing::instrument(
name = "Creating a pre-populated transaction for signature ...",
skip_all
)]
pub fn get_prepopulated_transaction(
network_config: &crate::config::NetworkConfig,
ft_contract_account_id: &near_primitives::types::AccountId,
receiver_account_id: &near_primitives::types::AccountId,
signer_id: &near_primitives::types::AccountId,
amount_ft: &crate::types::ft_properties::FungibleToken,
memo: &str,
deposit: crate::types::near_token::NearToken,
gas: crate::common::NearGas,
) -> color_eyre::eyre::Result<crate::commands::PrepopulatedTransaction> {
tracing::info!(target: "near_teach_me", "Creating a pre-populated transaction for signature ...");
let args_ft_transfer = serde_json::to_vec(&crate::types::ft_properties::FtTransfer {
receiver_id: receiver_account_id.clone(),
amount: amount_ft.amount(),
memo: if memo.is_empty() {
None
} else {
Some(memo.to_string())
},
})?;
let action_ft_transfer = near_primitives::transaction::Action::FunctionCall(Box::new(
near_primitives::transaction::FunctionCallAction {
method_name: "ft_transfer".to_string(),
args: args_ft_transfer,
gas: near_primitives::gas::Gas::from_gas(gas.as_gas()),
deposit: deposit.into(),
},
));
let args = serde_json::to_vec(&json!({"account_id": receiver_account_id}))?;
let call_result = network_config
.json_rpc_client()
.blocking_call_view_function(
ft_contract_account_id,
"storage_balance_of",
args.clone(),
near_primitives::types::Finality::Final.into(),
)
.wrap_err_with(||{
format!("Failed to fetch query for view method: 'storage_balance_of' (contract <{}> on network <{}>)",
ft_contract_account_id,
network_config.network_name
)
})?;
if call_result.parse_result_from_json::<Value>()?.is_null() {
let action_storage_deposit = near_primitives::transaction::Action::FunctionCall(Box::new(
near_primitives::transaction::FunctionCallAction {
method_name: "storage_deposit".to_string(),
args,
gas: near_primitives::gas::Gas::from_gas(gas.as_gas()),
deposit: near_token::NearToken::from_millinear(100),
},
));
return Ok(crate::commands::PrepopulatedTransaction {
signer_id: signer_id.clone(),
receiver_id: ft_contract_account_id.clone(),
actions: vec![action_storage_deposit, action_ft_transfer.clone()],
});
}
Ok(crate::commands::PrepopulatedTransaction {
signer_id: signer_id.clone(),
receiver_id: ft_contract_account_id.clone(),
actions: vec![action_ft_transfer.clone()],
})
}
fn get_ft_balance_for_account(
network_config: &crate::config::NetworkConfig,
signer_account_id: &near_primitives::types::AccountId,
ft_contract_account_id: &near_primitives::types::AccountId,
block_reference: near_primitives::types::BlockReference,
) -> color_eyre::eyre::Result<crate::types::ft_properties::FungibleToken> {
let function_args = serde_json::to_vec(&json!({"account_id": signer_account_id}))?;
let amount = get_ft_balance(
network_config,
ft_contract_account_id,
function_args,
block_reference,
)?
.parse_result_from_json::<String>()?;
let crate::types::ft_properties::FtMetadata { decimals, symbol } =
crate::types::ft_properties::params_ft_metadata(
ft_contract_account_id.clone(),
network_config,
near_primitives::types::Finality::Final.into(),
)?;
Ok(crate::types::ft_properties::FungibleToken::from_params_ft(
amount.parse::<u128>()?,
decimals,
symbol,
))
}
| 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/tokens/send_ft/amount_ft.rs | src/commands/tokens/send_ft/amount_ft.rs | use color_eyre::eyre::ContextCompat;
use inquire::CustomType;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::SendFtCommandContext)]
#[interactive_clap(output_context = AmountFtContext)]
pub struct AmountFt {
#[interactive_clap(skip_default_input_arg)]
/// Enter an amount FT to transfer:
ft_transfer_amount: crate::types::ft_properties::FungibleTokenTransferAmount,
#[interactive_clap(named_arg)]
/// Enter a memo for transfer (optional):
memo: FtTransferParams,
}
#[derive(Debug, Clone)]
pub struct AmountFtContext {
global_context: crate::GlobalContext,
signer_account_id: near_primitives::types::AccountId,
ft_contract_account_id: near_primitives::types::AccountId,
receiver_account_id: near_primitives::types::AccountId,
ft_transfer_amount: crate::types::ft_properties::FungibleTokenTransferAmount,
}
impl AmountFtContext {
pub fn from_previous_context(
previous_context: super::SendFtCommandContext,
scope: &<AmountFt as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let ft_transfer_amount =
if let crate::types::ft_properties::FungibleTokenTransferAmount::MaxAmount =
scope.ft_transfer_amount
{
crate::types::ft_properties::FungibleTokenTransferAmount::MaxAmount
} else {
let network_config = crate::common::find_network_where_account_exist(
&previous_context.global_context,
previous_context.ft_contract_account_id.clone(),
)?
.wrap_err_with(|| {
format!(
"Contract <{}> does not exist in networks",
previous_context.ft_contract_account_id
)
})?;
let ft_metadata = crate::types::ft_properties::params_ft_metadata(
previous_context.ft_contract_account_id.clone(),
&network_config,
near_primitives::types::Finality::Final.into(),
)?;
scope.ft_transfer_amount.normalize(&ft_metadata)?
};
Ok(Self {
global_context: previous_context.global_context,
signer_account_id: previous_context.signer_account_id,
ft_contract_account_id: previous_context.ft_contract_account_id,
receiver_account_id: previous_context.receiver_account_id,
ft_transfer_amount,
})
}
}
impl AmountFt {
fn input_ft_transfer_amount(
context: &super::SendFtCommandContext,
) -> color_eyre::eyre::Result<Option<crate::types::ft_properties::FungibleTokenTransferAmount>>
{
let network_config = crate::common::find_network_where_account_exist(
&context.global_context,
context.ft_contract_account_id.clone(),
)?
.wrap_err_with(|| {
format!(
"Contract <{}> does not exist in networks",
context.ft_contract_account_id
)
})?;
let ft_metadata = crate::types::ft_properties::params_ft_metadata(
context.ft_contract_account_id.clone(),
&network_config,
near_primitives::types::Finality::Final.into(),
)?;
Ok(Some(
CustomType::<crate::types::ft_properties::FungibleTokenTransferAmount>::new(&format!(
"Enter an FT amount to transfer (example: 10 {symbol} or 0.5 {symbol} or \"all\" to transfer the entire amount of fungible tokens from your account):",
symbol = ft_metadata.symbol
))
.with_validator(move |ft: &crate::types::ft_properties::FungibleTokenTransferAmount| {
match ft.normalize(&ft_metadata) {
Err(err) => Ok(inquire::validator::Validation::Invalid(
inquire::validator::ErrorMessage::Custom(err.to_string()),
)),
Ok(_) => Ok(inquire::validator::Validation::Valid),
}
})
.with_formatter(&|ft| ft.to_string())
.prompt()?,
))
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = AmountFtContext)]
#[interactive_clap(output_context = FtTransferParamsContext)]
pub struct FtTransferParams {
/// Enter a memo for transfer (optional):
memo: String,
#[interactive_clap(long = "prepaid-gas")]
#[interactive_clap(skip_interactive_input)]
gas: Option<crate::common::NearGas>,
#[interactive_clap(long = "attached-deposit")]
#[interactive_clap(skip_interactive_input)]
deposit: Option<crate::types::near_token::NearToken>,
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_for_transaction::NetworkForTransactionArgs,
}
#[derive(Clone)]
pub struct FtTransferParamsContext(crate::commands::ActionContext);
impl FtTransferParamsContext {
pub fn from_previous_context(
previous_context: AmountFtContext,
scope: &<FtTransferParams 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_account_id = previous_context.signer_account_id.clone();
let ft_contract_account_id = previous_context.ft_contract_account_id.clone();
let receiver_account_id = previous_context.receiver_account_id.clone();
let ft_transfer_amount = previous_context.ft_transfer_amount.clone();
let memo = scope.memo.trim().to_string();
let gas = scope.gas.unwrap_or(near_gas::NearGas::from_tgas(100));
let deposit = scope.deposit.unwrap_or(crate::types::near_token::NearToken::from_yoctonear(1));
move |network_config| {
let amount_ft = if let crate::types::ft_properties::FungibleTokenTransferAmount::ExactAmount(ft) = &ft_transfer_amount {
ft
} else {
&super::get_ft_balance_for_account(
network_config,
&signer_account_id,
&ft_contract_account_id,
near_primitives::types::Finality::Final.into()
)?
};
super::get_prepopulated_transaction(
network_config,
&ft_contract_account_id,
&receiver_account_id,
&signer_account_id,
amount_ft,
&memo,
deposit,
gas
)
}
});
let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = std::sync::Arc::new({
let signer_account_id = previous_context.signer_account_id.clone();
let ft_contract_account_id = previous_context.ft_contract_account_id.clone();
let receiver_account_id = previous_context.receiver_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 {
for action in outcome_view.transaction.actions.clone() {
if let near_primitives::views::ActionView::FunctionCall { method_name: _, args, gas: _, deposit: _ } = action {
if let Ok(ft_transfer) = serde_json::from_slice::<crate::types::ft_properties::FtTransfer>(&args) {
if let Ok(ft_balance) = super::get_ft_balance_for_account(
network_config,
&signer_account_id,
&ft_contract_account_id,
near_primitives::types::BlockId::Hash(outcome_view.receipts_outcome.last().expect("FT transfer should have at least one receipt outcome, but none was received").block_hash).into()
) {
let ft_transfer_amount = crate::types::ft_properties::FungibleToken::from_params_ft(
ft_transfer.amount,
ft_balance.decimals(),
ft_balance.symbol().to_string()
);
if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = verbosity {
tracing_indicatif::suspend_tracing_indicatif(|| eprintln!(
"<{signer_account_id}> has successfully transferred {ft_transfer_amount} (FT-contract: {ft_contract_account_id}) to <{receiver_account_id}>.\nRemaining balance: {ft_balance}",
));
}
return Ok(());
}
}
}
}
if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = verbosity {
tracing_indicatif::suspend_tracing_indicatif(|| eprintln!(
"<{signer_account_id}> has successfully transferred fungible tokens (FT-contract: {ft_contract_account_id}) to <{receiver_account_id}>.",
));
}
}
Ok(())
}
});
Ok(Self(crate::commands::ActionContext {
global_context: previous_context.global_context,
interacting_with_account_ids: vec![
previous_context.ft_contract_account_id,
previous_context.signer_account_id,
previous_context.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,
}))
}
}
impl From<FtTransferParamsContext> for crate::commands::ActionContext {
fn from(item: FtTransferParamsContext) -> 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/message/mod.rs | src/commands/message/mod.rs | use strum::{EnumDiscriminants, EnumIter, EnumMessage};
pub mod sign_nep413;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = crate::GlobalContext)]
pub struct MessageCommand {
#[interactive_clap(subcommand)]
pub message_actions: MessageActions,
}
#[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 message?
pub enum MessageActions {
#[strum_discriminants(strum(
message = "sign-nep413 - Sign a NEP-413 message off-chain"
))]
/// Sign a NEP-413 message off-chain
SignNep413(self::sign_nep413::SignNep413),
}
| 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/message/sign_nep413/mod.rs | src/commands/message/sign_nep413/mod.rs | use near_crypto::{SecretKey, Signature};
use near_primitives::borsh::{self, BorshDeserialize, BorshSerialize};
use near_primitives::hash::hash;
use serde::Serialize;
pub mod message_type;
pub mod nonce;
pub mod recipient;
pub mod signature_options;
pub mod signer;
#[derive(Debug, Clone, BorshDeserialize, BorshSerialize)]
pub struct NEP413Payload {
pub message: String,
pub nonce: [u8; 32],
pub recipient: String,
pub callback_url: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct SignedMessage {
#[serde(rename = "accountId")]
pub account_id: String,
#[serde(rename = "publicKey")]
pub public_key: String,
pub signature: String,
}
pub fn sign_nep413_payload(
payload: &NEP413Payload,
secret_key: &SecretKey,
) -> color_eyre::eyre::Result<Signature> {
const NEP413_SIGN_MESSAGE_PREFIX: u32 = (1u32 << 31u32) + 413u32;
let mut bytes = NEP413_SIGN_MESSAGE_PREFIX.to_le_bytes().to_vec();
borsh::to_writer(&mut bytes, payload)?;
let hash = hash(&bytes);
let signature = secret_key.sign(hash.as_ref());
Ok(signature)
}
#[cfg(feature = "ledger")]
impl From<NEP413Payload> for near_ledger::NEP413Payload {
fn from(payload: NEP413Payload) -> Self {
Self {
message: payload.message,
nonce: payload.nonce,
recipient: payload.recipient,
callback_url: payload.callback_url,
}
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = SignNep413Context)]
pub struct SignNep413 {
#[interactive_clap(subcommand)]
message_type: self::message_type::MessageType,
}
#[derive(Debug, Clone)]
pub struct SignNep413Context {
global_context: crate::GlobalContext,
}
impl SignNep413Context {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
_scope: &<SignNep413 as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context,
})
}
}
#[derive(Debug, Clone)]
pub struct FinalSignNep413Context {
pub global_context: crate::GlobalContext,
pub payload: NEP413Payload,
pub signer_id: near_primitives::types::AccountId,
}
| 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/message/sign_nep413/nonce/mod.rs | src/commands/message/sign_nep413/nonce/mod.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(_context = NonceContext)]
#[interactive_clap(output_context = NonceWrapperContext)]
pub struct Nonce {
/// A 32-byte nonce as a base64-encoded string:
nonce: crate::types::nonce32_bytes::Nonce32,
#[interactive_clap(named_arg)]
recipient: super::recipient::Recipient,
}
#[derive(Debug, Clone)]
pub struct NonceContext {
pub global_context: crate::GlobalContext,
pub message: String,
}
#[derive(Debug, Clone)]
pub struct NonceWrapperContext(super::recipient::RecipientContext);
impl NonceWrapperContext {
pub fn from_previous_context(
previous_context: NonceContext,
scope: &<Nonce as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self(super::recipient::RecipientContext {
global_context: previous_context.global_context,
message: previous_context.message,
nonce: scope.nonce.clone(),
}))
}
}
impl From<NonceWrapperContext> for super::recipient::RecipientContext {
fn from(item: NonceWrapperContext) -> 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/message/sign_nep413/signature_options/sign_with_legacy_keychain.rs | src/commands/message/sign_nep413/signature_options/sign_with_legacy_keychain.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::super::FinalSignNep413Context)]
#[interactive_clap(output_context = SignLegacyKeychainContext)]
pub struct SignLegacyKeychain {
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network::Network,
}
pub struct SignLegacyKeychainContext(crate::network::NetworkContext);
impl SignLegacyKeychainContext {
pub fn from_previous_context(
previous_context: super::super::FinalSignNep413Context,
_scope: &<SignLegacyKeychain as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback =
std::sync::Arc::new({
let signer_id = previous_context.signer_id.clone();
let payload = previous_context.payload.clone();
let credentials_home_dir = previous_context
.global_context
.config
.credentials_home_dir
.clone();
move |network_config| {
let key_pair = crate::commands::account::export_account::get_account_key_pair_from_legacy_keychain(
network_config,
&signer_id,
&credentials_home_dir
)?;
let signature =
super::super::sign_nep413_payload(&payload, &key_pair.private_key)?;
let signed_message = super::super::SignedMessage {
account_id: signer_id.to_string(),
public_key: key_pair.public_key.to_string(),
signature: signature.to_string(),
};
println!("{}", serde_json::to_string_pretty(&signed_message)?);
Ok(())
}
});
Ok(Self(crate::network::NetworkContext {
config: previous_context.global_context.config,
interacting_with_account_ids: vec![previous_context.signer_id],
on_after_getting_network_callback,
}))
}
}
impl From<SignLegacyKeychainContext> for crate::network::NetworkContext {
fn from(item: SignLegacyKeychainContext) -> 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/message/sign_nep413/signature_options/sign_with_keychain.rs | src/commands/message/sign_nep413/signature_options/sign_with_keychain.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::super::FinalSignNep413Context)]
#[interactive_clap(output_context = SignKeychainContext)]
pub struct SignKeychain {
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network::Network,
}
pub struct SignKeychainContext(crate::network::NetworkContext);
impl SignKeychainContext {
pub fn from_previous_context(
previous_context: super::super::FinalSignNep413Context,
_scope: &<SignKeychain as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let on_after_getting_network_callback: crate::network::OnAfterGettingNetworkCallback =
std::sync::Arc::new({
let signer_id = previous_context.signer_id.clone();
let payload = previous_context.payload.clone();
move |network_config| {
let key_pair = crate::commands::account::export_account::get_account_key_pair_from_keychain(network_config, &signer_id)?;
let signature =
super::super::sign_nep413_payload(&payload, &key_pair.private_key)?;
let signed_message = super::super::SignedMessage {
account_id: signer_id.to_string(),
public_key: key_pair.public_key.to_string(),
signature: signature.to_string(),
};
println!("{}", serde_json::to_string_pretty(&signed_message)?);
Ok(())
}
});
Ok(Self(crate::network::NetworkContext {
config: previous_context.global_context.config,
interacting_with_account_ids: vec![previous_context.signer_id],
on_after_getting_network_callback,
}))
}
}
impl From<SignKeychainContext> for crate::network::NetworkContext {
fn from(item: SignKeychainContext) -> 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/message/sign_nep413/signature_options/sign_with_seed_phrase.rs | src/commands/message/sign_nep413/signature_options/sign_with_seed_phrase.rs | use std::str::FromStr;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::super::FinalSignNep413Context)]
#[interactive_clap(output_context = SignSeedPhraseContext)]
pub struct SignSeedPhrase {
/// 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,
}
#[derive(Debug, Clone)]
pub struct SignSeedPhraseContext;
impl SignSeedPhraseContext {
pub fn from_previous_context(
previous_context: super::super::FinalSignNep413Context,
scope: &<SignSeedPhrase 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 secret_key = near_crypto::SecretKey::from_str(&key_pair_properties.secret_keypair_str)?;
let signature = super::super::sign_nep413_payload(&previous_context.payload, &secret_key)?;
let signed_message = super::super::SignedMessage {
account_id: previous_context.signer_id.to_string(),
public_key: key_pair_properties.public_key_str,
signature: signature.to_string(),
};
println!("{}", serde_json::to_string_pretty(&signed_message)?);
Ok(Self)
}
}
impl SignSeedPhrase {
fn input_seed_phrase_hd_path(
_context: &super::super::FinalSignNep413Context,
) -> 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/message/sign_nep413/signature_options/sign_with_access_key_file.rs | src/commands/message/sign_nep413/signature_options/sign_with_access_key_file.rs | use color_eyre::eyre::WrapErr;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::super::FinalSignNep413Context)]
#[interactive_clap(output_context = SignAccessKeyFileContext)]
pub struct SignAccessKeyFile {
/// What is the location of the account access key file?
file_path: crate::types::path_buf::PathBuf,
}
#[derive(Debug, Clone)]
pub struct SignAccessKeyFileContext;
impl SignAccessKeyFileContext {
pub fn from_previous_context(
previous_context: super::super::FinalSignNep413Context,
scope: &<SignAccessKeyFile as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let data =
std::fs::read_to_string(&scope.file_path).wrap_err("Access key file not found!")?;
let account_json: crate::transaction_signature_options::AccountKeyPair =
serde_json::from_str(&data).wrap_err_with(|| {
format!("Error reading data from file: {:?}", &scope.file_path)
})?;
let signature = super::super::sign_nep413_payload(
&previous_context.payload,
&account_json.private_key,
)?;
let signed_message = super::super::SignedMessage {
account_id: previous_context.signer_id.to_string(),
public_key: account_json.public_key.to_string(),
signature: signature.to_string(),
};
println!("{}", serde_json::to_string_pretty(&signed_message)?);
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/message/sign_nep413/signature_options/sign_with_ledger.rs | src/commands/message/sign_nep413/signature_options/sign_with_ledger.rs | use color_eyre::eyre::WrapErr;
use near_crypto::Signature;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::super::FinalSignNep413Context)]
#[interactive_clap(output_context = SignLedgerContext)]
pub struct SignLedger {
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
seed_phrase_hd_path: crate::types::slip10::BIP32Path,
}
#[derive(Debug, Clone)]
pub struct SignLedgerContext;
impl SignLedgerContext {
pub fn from_previous_context(
previous_context: super::super::FinalSignNep413Context,
scope: &<SignLedger 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:?}"
))
})?;
let public_key = near_crypto::PublicKey::ED25519(near_crypto::ED25519PublicKey::from(
near_ledger::get_public_key(scope.seed_phrase_hd_path.clone().into())
.map_err(|err| color_eyre::eyre::eyre!("Ledger get_public_key error: {err:?}"))?
.to_bytes(),
));
std::thread::sleep(std::time::Duration::from_secs(1));
eprintln!("Please approve the message signing on your Ledger device (HD Path: {seed_phrase_hd_path})");
let signature_bytes = near_ledger::sign_message_nep413(
&previous_context.payload.into(),
seed_phrase_hd_path.into(),
)
.map_err(|err| color_eyre::eyre::eyre!("Ledger signing error: {:?}", err))?;
let signature = Signature::from_parts(near_crypto::KeyType::ED25519, &signature_bytes)
.wrap_err("Signature is not expected to fail on deserialization")?;
let signed_message = super::super::SignedMessage {
account_id: previous_context.signer_id.to_string(),
public_key: public_key.to_string(),
signature: signature.to_string(),
};
println!("{}", serde_json::to_string_pretty(&signed_message)?);
Ok(Self)
}
}
impl SignLedger {
pub fn input_seed_phrase_hd_path(
_context: &super::super::FinalSignNep413Context,
) -> 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/message/sign_nep413/signature_options/mod.rs | src/commands/message/sign_nep413/signature_options/mod.rs | use strum::{EnumDiscriminants, EnumIter, EnumMessage};
pub mod sign_with_access_key_file;
pub mod sign_with_keychain;
#[cfg(feature = "ledger")]
pub mod sign_with_ledger;
pub mod sign_with_legacy_keychain;
pub mod sign_with_private_key;
pub mod sign_with_seed_phrase;
#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = super::FinalSignNep413Context)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
/// How do you want to sign the message?
pub enum SignWith {
#[strum_discriminants(strum(
message = "sign-with-keychain - Sign with a key saved in the secure keychain"
))]
SignWithKeychain(self::sign_with_keychain::SignKeychain),
#[strum_discriminants(strum(
message = "sign-with-legacy-keychain - Sign with a key saved in legacy keychain (compatible with the old near CLI)"
))]
SignWithLegacyKeychain(self::sign_with_legacy_keychain::SignLegacyKeychain),
#[cfg(feature = "ledger")]
#[strum_discriminants(strum(
message = "sign-with-ledger - Sign with Ledger Nano device"
))]
SignWithLedger(self::sign_with_ledger::SignLedger),
#[strum_discriminants(strum(
message = "sign-with-plaintext-private-key - Sign with a plaintext private key"
))]
SignWithPlaintextPrivateKey(self::sign_with_private_key::SignPrivateKey),
#[strum_discriminants(strum(
message = "sign-with-access-key-file - Sign using an account access key file"
))]
SignWithAccessKeyFile(self::sign_with_access_key_file::SignAccessKeyFile),
#[strum_discriminants(strum(
message = "sign-with-seed-phrase - Sign using a seed phrase"
))]
SignWithSeedPhrase(self::sign_with_seed_phrase::SignSeedPhrase),
}
| 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/message/sign_nep413/signature_options/sign_with_private_key.rs | src/commands/message/sign_nep413/signature_options/sign_with_private_key.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::super::FinalSignNep413Context)]
#[interactive_clap(output_context = SignPrivateKeyContext)]
pub struct SignPrivateKey {
/// Enter your private (secret) key:
pub private_key: crate::types::secret_key::SecretKey,
}
#[derive(Debug, Clone)]
pub struct SignPrivateKeyContext;
impl SignPrivateKeyContext {
pub fn from_previous_context(
previous_context: super::super::FinalSignNep413Context,
scope: &<SignPrivateKey as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let secret_key: near_crypto::SecretKey = scope.private_key.clone().into();
let public_key = secret_key.public_key();
let signature = super::super::sign_nep413_payload(&previous_context.payload, &secret_key)?;
let signed_message = super::super::SignedMessage {
account_id: previous_context.signer_id.to_string(),
public_key: public_key.to_string(),
signature: signature.to_string(),
};
println!("{}", serde_json::to_string_pretty(&signed_message)?);
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/message/sign_nep413/recipient/mod.rs | src/commands/message/sign_nep413/recipient/mod.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = RecipientContext)]
#[interactive_clap(output_context = RecipientWrapperContext)]
pub struct Recipient {
/// The recipient of the message (e.g. "alice.near" or "myapp.com"):
recipient: String,
#[interactive_clap(named_arg)]
sign_as: super::signer::SignAs,
}
#[derive(Debug, Clone)]
pub struct RecipientContext {
pub global_context: crate::GlobalContext,
pub message: String,
pub nonce: crate::types::nonce32_bytes::Nonce32,
}
#[derive(Debug, Clone)]
pub struct RecipientWrapperContext(super::signer::SignAsContext);
impl RecipientWrapperContext {
pub fn from_previous_context(
previous_context: RecipientContext,
scope: &<Recipient as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self(super::signer::SignAsContext {
global_context: previous_context.global_context,
message: previous_context.message,
nonce: previous_context.nonce,
recipient: scope.recipient.clone(),
}))
}
}
impl From<RecipientWrapperContext> for super::signer::SignAsContext {
fn from(item: RecipientWrapperContext) -> 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/message/sign_nep413/message_type/base64.rs | src/commands/message/sign_nep413/message_type/base64.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::MessageTypeContext)]
#[interactive_clap(output_context = Base64Context)]
pub struct Base64 {
/// The base64-encoded message to sign:
message: crate::types::base64_bytes::Base64Bytes,
#[interactive_clap(named_arg)]
nonce: super::super::nonce::Nonce,
}
#[derive(Debug, Clone)]
pub struct Base64Context(super::super::nonce::NonceContext);
impl Base64Context {
pub fn from_previous_context(
previous_context: super::MessageTypeContext,
scope: &<Base64 as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let message = String::from_utf8(scope.message.as_bytes().to_vec())
.map_err(|e| color_eyre::eyre::eyre!("Message is not valid UTF-8: {}", e))?;
Ok(Self(super::super::nonce::NonceContext {
global_context: previous_context.global_context,
message,
}))
}
}
impl From<Base64Context> for super::super::nonce::NonceContext {
fn from(item: Base64Context) -> 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/message/sign_nep413/message_type/mod.rs | src/commands/message/sign_nep413/message_type/mod.rs | use strum::{EnumDiscriminants, EnumIter, EnumMessage};
mod base64;
mod utf8;
#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = super::SignNep413Context)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
/// Select the message encoding type:
pub enum MessageType {
#[strum_discriminants(strum(message = "utf8 - The message is a plain UTF-8 string"))]
/// The message is a plain UTF-8 string
Utf8(self::utf8::Utf8),
#[strum_discriminants(strum(message = "base64 - The message is a base64-encoded string"))]
/// The message is a base64-encoded string
Base64(self::base64::Base64),
}
#[derive(Debug, Clone)]
pub struct MessageTypeContext {
global_context: crate::GlobalContext,
_message: String,
}
impl MessageTypeContext {
pub fn from_previous_context(
previous_context: super::SignNep413Context,
_scope: &<MessageType as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context.global_context,
_message: String::new(),
})
}
}
impl From<super::SignNep413Context> for MessageTypeContext {
fn from(item: super::SignNep413Context) -> Self {
Self {
global_context: item.global_context,
_message: String::new(),
}
}
}
| 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/message/sign_nep413/message_type/utf8.rs | src/commands/message/sign_nep413/message_type/utf8.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::MessageTypeContext)]
#[interactive_clap(output_context = Utf8Context)]
pub struct Utf8 {
/// The text message (UTF-8 encoded) to sign:
message: String,
#[interactive_clap(named_arg)]
nonce: super::super::nonce::Nonce,
}
#[derive(Debug, Clone)]
pub struct Utf8Context(super::super::nonce::NonceContext);
impl Utf8Context {
pub fn from_previous_context(
previous_context: super::MessageTypeContext,
scope: &<Utf8 as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self(super::super::nonce::NonceContext {
global_context: previous_context.global_context,
message: scope.message.clone(),
}))
}
}
impl From<Utf8Context> for super::super::nonce::NonceContext {
fn from(item: Utf8Context) -> 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/message/sign_nep413/signer/mod.rs | src/commands/message/sign_nep413/signer/mod.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = SignAsContext)]
#[interactive_clap(output_context = SignAsWrapperContext)]
pub struct SignAs {
/// Which account to sign the message with:
signer_account_id: crate::types::account_id::AccountId,
#[interactive_clap(subcommand)]
sign_with: super::signature_options::SignWith,
}
#[derive(Debug, Clone)]
pub struct SignAsContext {
pub global_context: crate::GlobalContext,
pub message: String,
pub nonce: crate::types::nonce32_bytes::Nonce32,
pub recipient: String,
}
#[derive(Debug, Clone)]
pub struct SignAsWrapperContext(super::FinalSignNep413Context);
impl SignAsWrapperContext {
pub fn from_previous_context(
previous_context: SignAsContext,
scope: &<SignAs as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let payload = super::NEP413Payload {
message: previous_context.message,
nonce: previous_context.nonce.as_array(),
recipient: previous_context.recipient,
callback_url: None,
};
Ok(Self(super::FinalSignNep413Context {
global_context: previous_context.global_context,
payload,
signer_id: scope.signer_account_id.clone().into(),
}))
}
}
impl From<SignAsWrapperContext> for super::FinalSignNep413Context {
fn from(item: SignAsWrapperContext) -> 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/config/mod.rs | src/commands/config/mod.rs | use color_eyre::eyre::ContextCompat;
use strum::{EnumDiscriminants, EnumIter, EnumMessage};
mod add_connection;
mod delete_connection;
mod edit_connection;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = crate::GlobalContext)]
pub struct ConfigCommands {
#[interactive_clap(subcommand)]
config_actions: ConfigActions,
}
#[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 config?
pub enum ConfigActions {
#[strum_discriminants(strum(
message = "show-connections - Show a list of network connections"
))]
/// Show a list of network connections
ShowConnections(ShowConnections),
#[strum_discriminants(strum(message = "add-connection - Add a network connection"))]
/// Add a network connection
AddConnection(self::add_connection::AddNetworkConnection),
#[strum_discriminants(strum(message = "edit-connection - Edit a network connection"))]
/// Edit a network connection
EditConnection(self::edit_connection::EditConnection),
#[strum_discriminants(strum(
message = "delete-connection - Delete a network connection"
))]
/// Delete a network connection
DeleteConnection(self::delete_connection::DeleteNetworkConnection),
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = ShowConnectionsContext)]
pub struct ShowConnections;
#[derive(Debug, Clone)]
pub struct ShowConnectionsContext;
impl ShowConnectionsContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
_scope: &<ShowConnections as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let mut path_config_toml =
dirs::config_dir().wrap_err("Impossible to get your config dir!")?;
path_config_toml.push("near-cli/config.toml");
eprintln!(
"\nConfiguration data is stored in a file {:?}",
&path_config_toml
);
let config_toml = toml::to_string(&previous_context.config)?;
eprintln!("{}", &config_toml);
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/config/delete_connection/mod.rs | src/commands/config/delete_connection/mod.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = DeleteNetworkConnectionContext)]
pub struct DeleteNetworkConnection {
/// What is the network connection name?
#[interactive_clap(skip_default_input_arg)]
connection_name: String,
}
#[derive(Debug, Clone)]
pub struct DeleteNetworkConnectionContext;
impl DeleteNetworkConnectionContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<DeleteNetworkConnection as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let mut config = previous_context.config;
config.network_connection.remove(&scope.connection_name);
eprintln!();
config.write_config_toml()?;
eprintln!(
"Network connection \"{}\" was successfully removed from config.toml",
&scope.connection_name
);
Ok(Self)
}
}
impl DeleteNetworkConnection {
fn input_connection_name(
context: &crate::GlobalContext,
) -> color_eyre::eyre::Result<Option<String>> {
crate::common::input_network_name(&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/config/edit_connection/mod.rs | src/commands/config/edit_connection/mod.rs | use inquire::{Select, Text};
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = EditConnectionContext)]
pub struct EditConnection {
#[interactive_clap(skip_default_input_arg)]
/// What is the network connection name?
connection_name: String,
#[interactive_clap(subargs)]
parameter: Parameter,
}
#[derive(Debug, Clone)]
pub struct EditConnectionContext {
global_context: crate::GlobalContext,
connection_name: String,
network_config: crate::config::NetworkConfig,
}
impl EditConnectionContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<EditConnection as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let network_config = previous_context
.config
.network_connection
.get(&scope.connection_name)
.unwrap_or_else(|| {
panic!(
"Network connection \"{}\" not found",
&scope.connection_name
)
})
.clone();
Ok(Self {
global_context: previous_context,
connection_name: scope.connection_name.clone(),
network_config,
})
}
}
impl EditConnection {
fn input_connection_name(
context: &crate::GlobalContext,
) -> color_eyre::eyre::Result<Option<String>> {
crate::common::input_network_name(&context.config, &[])
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = EditConnectionContext)]
#[interactive_clap(output_context = ParameterContext)]
pub struct Parameter {
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
/// Which parameter do you want to update?
key: String,
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
/// Enter a new value for this parameter:
value: String,
}
#[derive(Debug, Clone)]
pub struct ParameterContext;
impl ParameterContext {
pub fn from_previous_context(
previous_context: EditConnectionContext,
scope: &<Parameter as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let mut config = previous_context.global_context.config;
let Some(network_config) = config
.network_connection
.get_mut(&previous_context.connection_name)
else {
return color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!(
"Network connection \"{}\" not found",
&previous_context.connection_name
));
};
match scope.key.as_str() {
"network_name" => network_config.network_name.clone_from(&scope.value),
"rpc_url" => network_config.rpc_url = scope.value.parse()?,
"rpc_api_key" => {
network_config.rpc_api_key = if scope.value == "null" {
None
} else {
Some(scope.value.parse()?)
};
}
"wallet_url" => {
network_config.wallet_url = scope.value.parse()?;
}
"explorer_transaction_url" => {
network_config.explorer_transaction_url = scope.value.parse()?;
}
"linkdrop_account_id" => {
network_config.linkdrop_account_id = if scope.value == "null" {
None
} else {
Some(scope.value.parse()?)
};
}
"near_social_db_contract_account_id" => {
network_config.near_social_db_contract_account_id = if &scope.value == "null" {
None
} else {
Some(scope.value.parse()?)
};
}
"faucet_url" => {
network_config.faucet_url = if scope.value == "null" {
None
} else {
Some(scope.value.parse()?)
};
}
"meta_transaction_relayer_url" => {
network_config.meta_transaction_relayer_url = if &scope.value == "null" {
None
} else {
Some(scope.value.parse()?)
};
}
"fastnear_url" => {
network_config.fastnear_url = if &scope.value == "null" {
None
} else {
Some(scope.value.parse()?)
};
}
"staking_pools_factory_account_id" => {
network_config.staking_pools_factory_account_id = if &scope.value == "null" {
None
} else {
Some(scope.value.parse()?)
};
}
"coingecko_url" => {
network_config.coingecko_url = if &scope.value == "null" {
None
} else {
Some(scope.value.parse()?)
};
}
_ => {
return color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!(
"Configuration key <{}> not found",
&scope.key
));
}
}
eprintln!();
config.write_config_toml()?;
eprintln!(
"Network connection \"{}\" was successfully updated with the new value for <{}>",
&previous_context.connection_name, &scope.key
);
Ok(Self)
}
}
impl Parameter {
fn input_key(context: &EditConnectionContext) -> color_eyre::eyre::Result<Option<String>> {
let variants = context.network_config.get_fields()?;
let select_submit = Select::new("Which setting do you want to change?", variants).prompt();
match select_submit {
Ok(value) => Ok(Some(
value.split_once(':').expect("Internal error").0.to_string(),
)),
Err(
inquire::error::InquireError::OperationCanceled
| inquire::error::InquireError::OperationInterrupted,
) => Ok(None),
Err(err) => Err(err.into()),
}
}
pub fn input_value(
_context: &EditConnectionContext,
) -> color_eyre::eyre::Result<Option<String>> {
let value: String =
Text::new("Enter a new value for this parameter (if you want to remove an optional parameter, use \"null\"):")
.prompt()?;
Ok(Some(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/config/add_connection/mod.rs | src/commands/config/add_connection/mod.rs | use inquire::{CustomType, Select};
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = AddNetworkConnectionContext)]
pub struct AddNetworkConnection {
#[interactive_clap(long)]
/// What is the NEAR network? (e.g. mainnet, testnet, shardnet)
network_name: String,
#[interactive_clap(long)]
/// What is the connection name? (e.g. pagoda-mainnet)
connection_name: String,
#[interactive_clap(long)]
/// What is the RPC endpoint?
rpc_url: crate::types::url::Url,
#[interactive_clap(long)]
/// What is the wallet endpoint?
wallet_url: crate::types::url::Url,
#[interactive_clap(long)]
/// What is the transaction explorer endpoint?
explorer_transaction_url: crate::types::url::Url,
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
rpc_api_key: Option<crate::types::api_key::ApiKey>,
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
linkdrop_account_id: Option<crate::types::account_id::AccountId>,
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
near_social_db_contract_account_id: Option<crate::types::account_id::AccountId>,
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
faucet_url: Option<crate::types::url::Url>,
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
meta_transaction_relayer_url: Option<crate::types::url::Url>,
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
fastnear_url: Option<crate::types::url::Url>,
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
staking_pools_factory_account_id: Option<crate::types::account_id::AccountId>,
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
coingecko_url: Option<crate::types::url::Url>,
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
mpc_contract_account_id: Option<crate::types::account_id::AccountId>,
}
#[derive(Debug, Clone)]
pub struct AddNetworkConnectionContext;
impl AddNetworkConnectionContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<AddNetworkConnection as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let mut config = previous_context.config;
config.network_connection.insert(
scope.connection_name.clone(),
crate::config::NetworkConfig {
network_name: scope.network_name.clone(),
rpc_url: scope.rpc_url.clone().into(),
wallet_url: scope.wallet_url.clone().into(),
explorer_transaction_url: scope.explorer_transaction_url.0.clone(),
rpc_api_key: scope.rpc_api_key.clone(),
linkdrop_account_id: scope
.linkdrop_account_id
.clone()
.map(|linkdrop_account_id| linkdrop_account_id.into()),
near_social_db_contract_account_id: scope
.near_social_db_contract_account_id
.clone()
.map(|near_social_db_contract_account_id| {
near_social_db_contract_account_id.into()
}),
faucet_url: scope.faucet_url.clone().map(|faucet_url| faucet_url.into()),
meta_transaction_relayer_url: scope
.meta_transaction_relayer_url
.clone()
.map(|meta_transaction_relayer_url| meta_transaction_relayer_url.into()),
fastnear_url: scope
.fastnear_url
.clone()
.map(|fastnear_url| fastnear_url.into()),
staking_pools_factory_account_id: scope
.staking_pools_factory_account_id
.clone()
.map(|staking_pools_factory_account_id| {
staking_pools_factory_account_id.into()
}),
coingecko_url: scope
.coingecko_url
.clone()
.map(|coingecko_url| coingecko_url.into()),
mpc_contract_account_id: scope
.mpc_contract_account_id
.clone()
.map(|mpc_contract_account_id| mpc_contract_account_id.into()),
},
);
eprintln!();
config.write_config_toml()?;
eprintln!(
"Network connection \"{}\" was successfully added to config.toml",
&scope.connection_name
);
Ok(Self)
}
}
impl AddNetworkConnection {
fn input_rpc_api_key(
_context: &crate::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::types::api_key::ApiKey>> {
#[derive(strum_macros::Display)]
enum ConfirmOptions {
#[strum(to_string = "Yes, the RPC endpoint requires an API key")]
Yes,
#[strum(to_string = "No, the RPC endpoint does not require an API key")]
No,
}
let select_choose_input = Select::new(
"Do you want to enter an API key?",
vec![ConfirmOptions::Yes, ConfirmOptions::No],
)
.prompt()?;
if let ConfirmOptions::Yes = select_choose_input {
let api_key: crate::types::api_key::ApiKey =
CustomType::new("Enter an API key:").prompt()?;
Ok(Some(api_key))
} else {
Ok(None)
}
}
fn input_linkdrop_account_id(
_context: &crate::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> {
#[derive(strum_macros::Display)]
enum ConfirmOptions {
#[strum(
to_string = "Yes, and I want to enter the name of the account hosting the program \"linkdrop\""
)]
Yes,
#[strum(to_string = "I don't know")]
No,
}
let select_choose_input = Select::new(
"Is there a \"linkdrop\" program on this network?",
vec![ConfirmOptions::Yes, ConfirmOptions::No],
)
.prompt()?;
if let ConfirmOptions::Yes = select_choose_input {
let account_id: crate::types::account_id::AccountId =
CustomType::new("What is the name of the account that hosts the linkdrop program? (e.g. on mainnet it is 'near', on testnet it is 'testnet')").prompt()?;
Ok(Some(account_id))
} else {
Ok(None)
}
}
fn input_near_social_db_contract_account_id(
_context: &crate::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> {
#[derive(strum_macros::Display)]
enum ConfirmOptions {
#[strum(to_string = "Yes, and I want to enter the NEAR Social DB contract account ID")]
Yes,
#[strum(
to_string = "No, I don't want to enter the NEAR Social DB contract account ID"
)]
No,
}
let select_choose_input = Select::new(
"Do you want to enter the NEAR Social DB contract account ID on this network?",
vec![ConfirmOptions::Yes, ConfirmOptions::No],
)
.prompt()?;
if let ConfirmOptions::Yes = select_choose_input {
let account_id: crate::types::account_id::AccountId =
CustomType::new("What is the NEAR Social DB contract account ID? (e.g. on mainnet it is 'social.near')").prompt()?;
Ok(Some(account_id))
} else {
Ok(None)
}
}
fn input_faucet_url(
_context: &crate::GlobalContext,
) -> 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 of the faucet")]
Yes,
#[strum(to_string = "No, I don't want to enter the faucet URL")]
No,
}
let select_choose_input = Select::new(
"Do you want to enter the faucet URL?",
vec![ConfirmOptions::Yes, ConfirmOptions::No],
)
.prompt()?;
if let ConfirmOptions::Yes = select_choose_input {
let faucet_url: crate::types::url::Url =
CustomType::new("What is the faucet URL?").prompt()?;
Ok(Some(faucet_url))
} else {
Ok(None)
}
}
fn input_meta_transaction_relayer_url(
_context: &crate::GlobalContext,
) -> 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 of the relayer")]
Yes,
#[strum(to_string = "No, I don't want to enter the relayer URL")]
No,
}
let select_choose_input = Select::new(
"Do you want to enter the meta transaction relayer URL?",
vec![ConfirmOptions::Yes, ConfirmOptions::No],
)
.prompt()?;
if let ConfirmOptions::Yes = select_choose_input {
let meta_transaction_relayer_url: crate::types::url::Url =
CustomType::new("What is the meta transaction relayer URL?").prompt()?;
Ok(Some(meta_transaction_relayer_url))
} else {
Ok(None)
}
}
fn input_fastnear_url(
_context: &crate::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::types::url::Url>> {
#[derive(strum_macros::Display)]
enum ConfirmOptions {
#[strum(to_string = "Yes, I want to enter the FastNEAR API URL")]
Yes,
#[strum(to_string = "No, I don't want to enter the FastNEAR API URL")]
No,
}
let select_choose_input = Select::new(
"Do you want to enter the FastNEAR API URL?",
vec![ConfirmOptions::Yes, ConfirmOptions::No],
)
.prompt()?;
if let ConfirmOptions::Yes = select_choose_input {
let stake_delegators_api: crate::types::url::Url =
CustomType::new("What is the FastNEAR API URL?").prompt()?;
Ok(Some(stake_delegators_api))
} else {
Ok(None)
}
}
fn input_staking_pools_factory_account_id(
_context: &crate::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> {
#[derive(strum_macros::Display)]
enum ConfirmOptions {
#[strum(to_string = "Yes, I want to enter the staking pools factory account ID")]
Yes,
#[strum(to_string = "No, I don't want to enter the staking pools factory account ID")]
No,
}
let select_choose_input = Select::new(
"Do you want to enter the staking pools factory account ID?",
vec![ConfirmOptions::Yes, ConfirmOptions::No],
)
.prompt()?;
if let ConfirmOptions::Yes = select_choose_input {
let account_id: crate::types::account_id::AccountId =
CustomType::new("What is the staking pools factory account ID?").prompt()?;
Ok(Some(account_id))
} else {
Ok(None)
}
}
fn input_coingecko_url(
_context: &crate::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::types::url::Url>> {
#[derive(strum_macros::Display)]
enum ConfirmOptions {
#[strum(to_string = "Yes, I want to enter the CoinGecko API URL")]
Yes,
#[strum(to_string = "No, I don't want to enter the CoinGecko API URL")]
No,
}
let select_choose_input = Select::new(
"Do you want to enter the CoinGecko API URL?",
vec![ConfirmOptions::Yes, ConfirmOptions::No],
)
.prompt()?;
if let ConfirmOptions::Yes = select_choose_input {
let coingecko_api: crate::types::url::Url =
CustomType::new("What is the CoinGecko API URL?")
.with_starting_input("https://api.coingecko.com/")
.prompt()?;
Ok(Some(coingecko_api))
} else {
Ok(None)
}
}
fn input_mpc_contract_account_id(
_context: &crate::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> {
#[derive(strum_macros::Display)]
enum ConfirmOptions {
#[strum(to_string = "Yes, I want to enter the MPC contract account ID")]
Yes,
#[strum(to_string = "No, I don't want to enter the MPC contract account ID")]
No,
}
let select_choose_input = Select::new(
"Do you want to enter the MPC contract account ID?",
vec![ConfirmOptions::Yes, ConfirmOptions::No],
)
.prompt()?;
if let ConfirmOptions::Yes = select_choose_input {
let mpc_contract_account_id: crate::types::account_id::AccountId =
CustomType::new("What is the MPC (Multi-Party Computation) contract account ID?")
.prompt()?;
Ok(Some(mpc_contract_account_id))
} 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/contract/mod.rs | src/commands/contract/mod.rs | use crate::common::RpcQueryResponseExt;
use color_eyre::eyre::{Context, Report};
use near_primitives::types::BlockReference;
use strum::{EnumDiscriminants, EnumIter, EnumMessage};
use thiserror::Error;
pub mod call_function;
pub mod deploy;
pub mod deploy_global;
mod download_abi;
pub mod download_wasm;
#[cfg(feature = "inspect_contract")]
mod inspect;
#[cfg(feature = "verify_contract")]
mod verify;
mod view_storage;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = crate::GlobalContext)]
pub struct ContractCommands {
#[interactive_clap(subcommand)]
contract_actions: ContractActions,
}
#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = crate::GlobalContext)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
#[non_exhaustive]
/// Choose a contract action:
pub enum ContractActions {
#[strum_discriminants(strum(
message = "call-function - Execute function (contract method)"
))]
/// Execute function (contract method)
CallFunction(self::call_function::CallFunctionCommands),
#[strum_discriminants(strum(
message = "deploy - Deploy own WASM code or re-use an existing global code from the chain"
))]
/// Add a contract code
Deploy(self::deploy::Contract),
#[strum_discriminants(strum(
message = "deploy-as-global - Deploy a WASM contract code to the global contract code on-chain registry"
))]
/// Add a global contract code
DeployAsGlobal(self::deploy_global::Contract),
#[strum_discriminants(strum(
message = "inspect - Get a list of available function names"
))]
/// Get a list of available function names
#[cfg(feature = "inspect_contract")]
Inspect(self::inspect::Contract),
#[strum_discriminants(strum(
message = "verify - Verify the contract for compliance with the program code"
))]
/// Verify the contract for compliance with the program code
#[cfg(feature = "verify_contract")]
Verify(self::verify::Contract),
#[strum_discriminants(strum(message = "download-abi - Download contract ABI"))]
/// Download contract ABI
DownloadAbi(self::download_abi::Contract),
#[strum_discriminants(strum(message = "download-wasm - Download wasm"))]
/// Download wasm
DownloadWasm(self::download_wasm::Contract),
#[strum_discriminants(strum(message = "view-storage - View contract storage state"))]
/// View contract storage state
ViewStorage(self::view_storage::ViewStorage),
}
#[tracing::instrument(name = "Obtaining the ABI for the contract ...", skip_all)]
pub async fn get_contract_abi(
json_rpc_client: &near_jsonrpc_client::JsonRpcClient,
block_reference: &BlockReference,
account_id: &near_primitives::types::AccountId,
) -> Result<near_abi::AbiRoot, FetchAbiError> {
tracing::info!(target: "near_teach_me", "Obtaining the ABI for the contract ...");
let mut retries_left = (0..5).rev();
loop {
let contract_abi_response = json_rpc_client
.call(near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference: block_reference.clone(),
request: near_primitives::views::QueryRequest::CallFunction {
account_id: account_id.clone(),
method_name: "__contract_abi".to_owned(),
args: near_primitives::types::FunctionArgs::from(vec![]),
},
})
.await;
match contract_abi_response {
Err(near_jsonrpc_client::errors::JsonRpcError::TransportError(_))
if retries_left.next().is_some() =>
{
eprintln!("Transport error.\nPlease wait. The next try to send this query is happening right now ...");
}
Err(near_jsonrpc_client::errors::JsonRpcError::ServerError(
near_jsonrpc_client::errors::JsonRpcServerError::HandlerError(
near_jsonrpc_primitives::types::query::RpcQueryError::ContractExecutionError {
vm_error,
..
},
),
)) if vm_error.contains("MethodNotFound") => {
return Err(FetchAbiError::AbiNotSupported);
}
Err(err) => {
return Err(FetchAbiError::RpcError(err));
}
Ok(contract_abi_response) => {
return serde_json::from_slice::<near_abi::AbiRoot>(
&zstd::decode_all(
contract_abi_response
.call_result()
.map_err(FetchAbiError::AbiUnknownFormat)?
.result
.as_slice(),
)
.wrap_err("Failed to 'zstd::decode_all' NEAR ABI")
.map_err(FetchAbiError::AbiUnknownFormat)?,
)
.wrap_err("Failed to parse NEAR ABI schema")
.map_err(FetchAbiError::AbiUnknownFormat);
}
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
#[derive(Error, Debug)]
pub enum FetchAbiError {
#[error("Contract does not support NEAR ABI (https://github.com/near/abi), so there is no way to get details about the function argument and return values.")]
AbiNotSupported,
#[error("The contract has unknown NEAR ABI format (https://github.com/near/abi), so there is no way to get details about the function argument and return values. See more details about the error:\n\n{0}")]
AbiUnknownFormat(Report),
#[error("'__contract_abi' function call failed due to RPC error, so there is no way to get details about the function argument and return values. See more details about the error:\n\n{0}")]
RpcError(
near_jsonrpc_client::errors::JsonRpcError<
near_jsonrpc_primitives::types::query::RpcQueryError,
>,
),
}
| 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/contract/verify/mod.rs | src/commands/contract/verify/mod.rs | use color_eyre::{
eyre::{Context, ContextCompat},
owo_colors::OwoColorize,
};
use strum::{EnumDiscriminants, EnumIter, EnumMessage};
use tracing_indicatif::span_ext::IndicatifSpanExt;
use near_verify_rs::types::{
contract_source_metadata::ContractSourceMetadata,
source_id::{GitReference, SourceId, SourceKind},
whitelist::{Whitelist, WhitelistEntry},
};
use crate::common::JsonRpcClientExt;
use crate::types::contract_properties::ContractProperties;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = ContractContext)]
pub struct Contract {
#[interactive_clap(long)]
#[interactive_clap(skip_interactive_input)]
use_contract_source_code_path: Option<crate::types::path_buf::PathBuf>,
#[interactive_clap(long)]
#[interactive_clap(skip_interactive_input)]
save_contract_source_code_into: Option<crate::types::path_buf::PathBuf>,
#[interactive_clap(long)]
no_image_whitelist: bool,
#[interactive_clap(subcommand)]
source_contract_code: SourceContractCode,
}
#[derive(Debug, Clone)]
pub struct ContractContext {
global_context: crate::GlobalContext,
use_contract_source_code_path: Option<std::path::PathBuf>,
save_contract_source_code_into: Option<std::path::PathBuf>,
no_image_whitelist: bool,
}
impl ContractContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<Contract as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
if scope.use_contract_source_code_path.is_some()
& scope.save_contract_source_code_into.is_some()
{
return color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!(
"You are using the `--use-contract-source-code-path` and `--save-contract-source-code-into` options at the same time. This is not allowed."
));
}
Ok(Self {
global_context: previous_context,
use_contract_source_code_path: scope
.use_contract_source_code_path
.as_ref()
.map(std::path::PathBuf::from),
save_contract_source_code_into: scope
.save_contract_source_code_into
.as_ref()
.map(std::path::PathBuf::from),
no_image_whitelist: scope.no_image_whitelist,
})
}
}
#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = ContractContext)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
/// Choose the code source for the contract:
pub enum SourceContractCode {
#[strum_discriminants(strum(
message = "deployed-at - Verify the contract by contract account ID"
))]
/// Verify the contract by contract account ID
DeployedAt(ContractAccountId),
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = ContractContext)]
#[interactive_clap(output_context = ContractAccountIdContext)]
pub struct ContractAccountId {
#[interactive_clap(skip_default_input_arg)]
/// What is the contract account ID?
contract_account_id: crate::types::account_id::AccountId,
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_view_at_block::NetworkViewAtBlockArgs,
}
impl ContractAccountId {
pub fn input_contract_account_id(
context: &ContractContext,
) -> 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 contract account ID?",
)
}
}
#[derive(Clone)]
pub struct ContractAccountIdContext(crate::network_view_at_block::ArgsForViewContext);
impl ContractAccountIdContext {
pub fn from_previous_context(
previous_context: ContractContext,
scope: &<ContractAccountId 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.contract_account_id.clone().into();
move |network_config, block_reference| {
let contract_code_from_contract_account_id = get_contract_code_from_contract_account_id(&account_id, network_config, block_reference)?;
let contract_properties = get_contract_properties_from_repository(
&account_id,
network_config,
block_reference,
previous_context.use_contract_source_code_path.clone(),
previous_context.save_contract_source_code_into.clone(),
previous_context.no_image_whitelist
)?;
verify_contract(
previous_context.global_context.verbosity,
contract_code_from_contract_account_id,
contract_properties,
);
Ok(())
}
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
config: previous_context.global_context.config,
on_after_getting_block_reference_callback,
interacting_with_account_ids: vec![scope.contract_account_id.clone().into()],
}))
}
}
impl From<ContractAccountIdContext> for crate::network_view_at_block::ArgsForViewContext {
fn from(item: ContractAccountIdContext) -> Self {
item.0
}
}
fn verify_contract(
verbosity: crate::Verbosity,
contract_code: Vec<u8>,
contract_properties: ContractProperties,
) {
if contract_properties.code == contract_code {
if let crate::Verbosity::Quiet = verbosity {
println!(
"The code obtained from the contract account ID and the code calculated from the repository are the same.\n{contract_properties}"
)
} else {
tracing::info!("{}\n{}",
"The code obtained from the contract account ID and the code calculated from the repository are the same.".green(),
crate::common::indent_payload(&contract_properties.to_string())
)
}
} else if let crate::Verbosity::Quiet = verbosity {
println!("The code obtained from the contract account ID and the code calculated from the repository do not match.")
} else {
tracing::info!("{}", "The code obtained from the contract account ID and the code calculated from the repository do not match.".red())
}
}
#[tracing::instrument(
name = "Getting the contract properties from the repository ...",
skip_all
)]
fn get_contract_properties_from_repository(
account_id: &near_primitives::types::AccountId,
network_config: &crate::config::NetworkConfig,
block_reference: &near_primitives::types::BlockReference,
use_contract_source_code_path: Option<std::path::PathBuf>,
save_contract_source_code_into: Option<std::path::PathBuf>,
no_image_whitelist: bool,
) -> color_eyre::eyre::Result<ContractProperties> {
tracing::info!(target: "near_teach_me", "Getting the contract properties from the repository ...");
let contract_source_metadata = tokio::runtime::Runtime::new().unwrap().block_on(
super::inspect::get_contract_source_metadata(
&network_config.json_rpc_client(),
block_reference,
account_id,
),
)?;
get_contract_properties_from_docker_build(
contract_source_metadata,
use_contract_source_code_path,
save_contract_source_code_into,
no_image_whitelist,
)
}
#[tracing::instrument(name = "Getting contract properties from docker build ...", skip_all)]
fn get_contract_properties_from_docker_build(
contract_source_metadata: ContractSourceMetadata,
use_contract_source_code_path: Option<std::path::PathBuf>,
save_contract_source_code_into: Option<std::path::PathBuf>,
no_image_whitelist: bool,
) -> color_eyre::eyre::Result<ContractProperties> {
tracing::info!(target: "near_teach_me", "Getting contract properties from docker build ...");
let whitelist: Option<Whitelist> = if no_image_whitelist {
None
} else {
Some(vec![WhitelistEntry {
expected_docker_image: "sourcescan/cargo-near".to_string(),
}])
};
contract_source_metadata.validate(whitelist)?;
let build_info = contract_source_metadata.build_info.as_ref().wrap_err("`contract_source_metadata` does not have a `build_info` field. This field is an addition to version **1.2.0** of **NEP-330**.")?;
let source_id = SourceId::from_url(&build_info.source_code_snapshot)?;
let tempdir = tempfile::tempdir()?;
let target_dir = if let Some(path_buf) = save_contract_source_code_into {
path_buf
} else if let Some(path_buf) = use_contract_source_code_path.clone() {
path_buf
} else {
tempdir.path().to_path_buf()
};
if use_contract_source_code_path.is_none() {
let SourceKind::Git(GitReference::Rev(rev)) = source_id.kind();
checkout_remote_repo(source_id.url().as_str(), &target_dir, rev)?;
}
let target_dir = camino::Utf8PathBuf::from_path_buf(target_dir)
.map_err(|err| color_eyre::eyre::eyre!("convert path buf {:?}", err))?;
let contract_path_buf = tracing_indicatif::suspend_tracing_indicatif::<
_,
color_eyre::eyre::Result<camino::Utf8PathBuf>,
>(|| {
near_verify_rs::logic::nep330_build::run(
contract_source_metadata.clone(),
target_dir,
vec![],
false,
)
})?;
let contract_code = std::fs::read(&contract_path_buf)
.wrap_err_with(|| format!("Failed to open or read the file: {:?}.", &contract_path_buf,))?;
let contract_code_hash = near_verify_rs::logic::compute_hash(contract_path_buf)?;
let contract_properties = ContractProperties {
code: contract_code,
hash: contract_code_hash,
version: contract_source_metadata.version,
standards: contract_source_metadata.standards,
link: contract_source_metadata.link,
source: build_info.source_code_snapshot.clone(),
build_environment: build_info.build_environment.clone(),
build_command: build_info.build_command.clone(),
};
Ok(contract_properties)
}
fn checkout_remote_repo(
repo_url: &str,
target_path: &std::path::Path,
rev_str: &str,
) -> crate::CliResult {
let repo = git2::Repository::clone_recurse(repo_url, target_path)?;
let oid = git2::Oid::from_str(rev_str)?;
let _commit = repo.find_commit(oid)?;
let object = repo.revparse_single(rev_str)?;
repo.checkout_tree(&object, None)?;
Ok(())
}
#[tracing::instrument(name = "Getting the contract code from", skip_all)]
fn get_contract_code_from_contract_account_id(
account_id: &near_primitives::types::AccountId,
network_config: &crate::config::NetworkConfig,
block_reference: &near_primitives::types::BlockReference,
) -> color_eyre::eyre::Result<Vec<u8>> {
tracing::Span::current().pb_set_message(&format!("{account_id} ..."));
tracing::info!(target: "near_teach_me", "Getting the contract code from {account_id} ...");
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"I am making HTTP call to NEAR JSON RPC to get the contract code (Wasm binary) deployed to `{}` account, learn more https://docs.near.org/api/rpc/contracts#view-contract-code",
account_id
);
let view_code_response = network_config
.json_rpc_client()
.blocking_call(near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference: block_reference.clone(),
request: near_primitives::views::QueryRequest::ViewCode {
account_id: account_id.clone(),
},
})
.wrap_err_with(|| {
format!(
"Failed to fetch query ViewCode for <{}> on network <{}>",
&account_id, network_config.network_name
)
})?;
let contract_code_view =
if let near_jsonrpc_primitives::types::query::QueryResponseKind::ViewCode(result) =
view_code_response.kind
{
result
} else {
return Err(color_eyre::Report::msg("Error call result".to_string()));
};
Ok(contract_code_view.code)
}
| 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/contract/deploy_global/mod.rs | src/commands/contract/deploy_global/mod.rs | use color_eyre::eyre::Context;
use strum::{EnumDiscriminants, EnumIter, EnumMessage};
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = crate::GlobalContext)]
pub struct Contract {
#[interactive_clap(named_arg)]
/// Specify a path to wasm file
use_file: ContractFile,
}
#[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[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)]
mode: DeployGlobalMode,
}
#[derive(Debug, Clone)]
pub struct ContractFileContext {
pub global_context: crate::GlobalContext,
pub code: Vec<u8>,
}
impl ContractFileContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
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,)
})?;
Ok(Self {
global_context: previous_context,
code,
})
}
}
#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = ContractFileContext)]
#[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(DeployGlobalResult),
#[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(DeployGlobalResult),
}
#[derive(Debug, Clone)]
pub struct DeployGlobalModeContext {
pub global_context: crate::GlobalContext,
pub code: Vec<u8>,
pub mode: near_primitives::action::GlobalContractDeployMode,
}
impl DeployGlobalModeContext {
pub fn from_previous_context(
previous_context: ContractFileContext,
scope: &<DeployGlobalMode as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(DeployGlobalModeContext {
global_context: previous_context.global_context,
code: previous_context.code,
mode: match scope {
DeployGlobalModeDiscriminants::AsGlobalHash => {
near_primitives::action::GlobalContractDeployMode::CodeHash
}
DeployGlobalModeDiscriminants::AsGlobalAccountId => {
near_primitives::action::GlobalContractDeployMode::AccountId
}
},
})
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = DeployGlobalModeContext)]
#[interactive_clap(output_context = DeployGlobalResultContext)]
pub struct DeployGlobalResult {
#[interactive_clap(skip_default_input_arg)]
/// What is the signer account ID?
account_id: crate::types::account_id::AccountId,
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_for_transaction::NetworkForTransactionArgs,
}
impl DeployGlobalResult {
pub fn input_account_id(
context: &DeployGlobalModeContext,
) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> {
let question = match context.mode {
near_primitives::action::GlobalContractDeployMode::CodeHash => {
"What is the signer account ID?"
}
near_primitives::action::GlobalContractDeployMode::AccountId => {
"What is the contract account ID?"
}
};
crate::common::input_signer_account_id_from_used_account_list(
&context.global_context.config.credentials_home_dir,
question,
)
}
}
pub struct DeployGlobalResultContext {
pub global_context: crate::GlobalContext,
pub code: Vec<u8>,
pub mode: near_primitives::action::GlobalContractDeployMode,
pub account_id: near_primitives::types::AccountId,
}
impl DeployGlobalResultContext {
pub fn from_previous_context(
previous_context: DeployGlobalModeContext,
scope: &<DeployGlobalResult as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context.global_context,
code: previous_context.code,
mode: previous_context.mode,
account_id: scope.account_id.clone().into(),
})
}
}
impl From<DeployGlobalResultContext> for crate::commands::ActionContext {
fn from(item: DeployGlobalResultContext) -> Self {
let account_id = item.account_id.clone();
let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback =
std::sync::Arc::new({
move |_network_config| {
Ok(crate::commands::PrepopulatedTransaction {
signer_id: item.account_id.clone(),
receiver_id: item.account_id.clone(),
actions: vec![near_primitives::transaction::Action::DeployGlobalContract(
near_primitives::action::DeployGlobalContractAction {
code: item.code.clone().into(),
deploy_mode: item.mode.clone(),
},
)],
})
}
});
Self {
global_context: item.global_context,
interacting_with_account_ids: vec![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/contract/deploy/mod.rs | src/commands/contract/deploy/mod.rs | use color_eyre::eyre::Context;
use strum::{EnumDiscriminants, EnumIter, EnumMessage};
pub mod initialize_mode;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = ContractContext)]
pub struct Contract {
#[interactive_clap(skip_default_input_arg)]
/// What is the contract account ID?
account_id: crate::types::account_id::AccountId,
#[interactive_clap(subcommand)]
/// Specify a deploy mode
deploy_mode: DeployModes,
}
#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = ContractContext)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
#[non_exhaustive]
/// Choose a contract action:
pub enum DeployModes {
#[strum_discriminants(strum(
message = "use-file - Deploy a contract using a wasm file"
))]
/// Deploy a contract using a wasm file
UseFile(ContractFile),
#[strum_discriminants(strum(
message = "use-global-hash - Deploy a contract using a global contract code hash"
))]
/// Deploy a contract using a global contract code hash
UseGlobalHash(ContractHash),
#[strum_discriminants(strum(
message = "use-global-account-id - Deploy a contract using an account ID"
))]
/// Deploy a contract using an global contract account ID
UseGlobalAccountId(ContractAccountId),
}
#[derive(Debug, Clone)]
pub struct ContractContext {
global_context: crate::GlobalContext,
receiver_account_id: near_primitives::types::AccountId,
signer_account_id: near_primitives::types::AccountId,
}
impl ContractContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<Contract as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context,
receiver_account_id: scope.account_id.clone().into(),
signer_account_id: scope.account_id.clone().into(),
})
}
}
impl Contract {
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 is the contract account ID?",
)
}
}
#[derive(Debug, Clone)]
pub struct GenericDeployContext {
pub global_context: crate::GlobalContext,
pub receiver_account_id: near_primitives::types::AccountId,
pub signer_account_id: near_primitives::types::AccountId,
pub deploy_action: near_primitives::transaction::Action,
}
#[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)]
#[interactive_clap(input_context = ContractContext)]
#[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,
}
pub struct ContractFileContext(GenericDeployContext);
impl ContractFileContext {
pub fn from_previous_context(
previous_context: ContractContext,
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,)
})?;
Ok(Self(GenericDeployContext {
global_context: previous_context.global_context,
receiver_account_id: previous_context.receiver_account_id,
signer_account_id: previous_context.signer_account_id,
deploy_action: near_primitives::transaction::Action::DeployContract(
near_primitives::action::DeployContractAction { code },
),
}))
}
}
impl From<ContractFileContext> for GenericDeployContext {
fn from(item: ContractFileContext) -> Self {
item.0
}
}
#[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)]
#[interactive_clap(input_context = ContractContext)]
#[interactive_clap(output_context = ContractHashContext)]
pub struct ContractHash {
/// What is a global contract code hash?
pub hash: crate::types::crypto_hash::CryptoHash,
#[interactive_clap(subcommand)]
initialize: self::initialize_mode::InitializeMode,
}
pub struct ContractHashContext(GenericDeployContext);
impl ContractHashContext {
pub fn from_previous_context(
previous_context: ContractContext,
scope: &<ContractHash as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self(GenericDeployContext {
global_context: previous_context.global_context,
receiver_account_id: previous_context.receiver_account_id,
signer_account_id: previous_context.signer_account_id,
deploy_action: near_primitives::transaction::Action::UseGlobalContract(Box::new(
near_primitives::action::UseGlobalContractAction {
contract_identifier:
near_primitives::action::GlobalContractIdentifier::CodeHash(
scope.hash.into(),
),
},
)),
}))
}
}
impl From<ContractHashContext> for GenericDeployContext {
fn from(item: ContractHashContext) -> Self {
item.0
}
}
#[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)]
#[interactive_clap(input_context = ContractContext)]
#[interactive_clap(output_context = ContractAccountIdContext)]
pub struct ContractAccountId {
#[interactive_clap(skip_default_input_arg)]
/// What is a global contract account ID?
pub global_contract_account_id: crate::types::account_id::AccountId,
#[interactive_clap(subcommand)]
initialize: self::initialize_mode::InitializeMode,
}
impl ContractAccountId {
pub fn input_global_contract_account_id(
context: &ContractContext,
) -> 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 a global contract account ID?",
)
}
}
pub struct ContractAccountIdContext(GenericDeployContext);
impl ContractAccountIdContext {
pub fn from_previous_context(
previous_context: ContractContext,
scope: &<ContractAccountId as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<GenericDeployContext> {
Ok(GenericDeployContext {
global_context: previous_context.global_context,
receiver_account_id: previous_context.receiver_account_id,
signer_account_id: previous_context.signer_account_id,
deploy_action: near_primitives::transaction::Action::UseGlobalContract(Box::new(
near_primitives::action::UseGlobalContractAction {
contract_identifier:
near_primitives::action::GlobalContractIdentifier::AccountId(
scope.global_contract_account_id.clone().into(),
),
},
)),
})
}
}
impl From<ContractAccountIdContext> for GenericDeployContext {
fn from(item: ContractAccountIdContext) -> 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/contract/deploy/initialize_mode/mod.rs | src/commands/contract/deploy/initialize_mode/mod.rs | use strum::{EnumDiscriminants, EnumIter, EnumMessage};
mod call_function_type;
#[derive(Debug, Clone, EnumDiscriminants, interactive_clap_derive::InteractiveClap)]
#[interactive_clap(context = super::GenericDeployContext)]
#[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(self::call_function_type::CallFunctionAction),
/// 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(input_context = super::GenericDeployContext)]
#[interactive_clap(output_context = NoInitializeContext)]
pub struct NoInitialize {
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_for_transaction::NetworkForTransactionArgs,
}
#[derive(Debug, Clone)]
pub struct NoInitializeContext(super::GenericDeployContext);
impl NoInitializeContext {
pub fn from_previous_context(
previous_context: super::GenericDeployContext,
_scope: &<NoInitialize as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self(super::GenericDeployContext {
global_context: previous_context.global_context,
receiver_account_id: previous_context.receiver_account_id,
signer_account_id: previous_context.signer_account_id,
deploy_action: previous_context.deploy_action,
}))
}
}
impl From<NoInitializeContext> for crate::commands::ActionContext {
fn from(item: NoInitializeContext) -> 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: vec![item.0.deploy_action.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/contract/deploy/initialize_mode/call_function_type/mod.rs | src/commands/contract/deploy/initialize_mode/call_function_type/mod.rs | use inquire::CustomType;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::super::GenericDeployContext)]
#[interactive_clap(output_context = CallFunctionActionContext)]
pub struct CallFunctionAction {
/// 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:
super::super::super::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 CallFunctionActionContext {
global_context: crate::GlobalContext,
receiver_account_id: near_primitives::types::AccountId,
signer_account_id: near_primitives::types::AccountId,
deploy_action: near_primitives::transaction::Action,
function_name: String,
function_args: Vec<u8>,
}
impl CallFunctionActionContext {
pub fn from_previous_context(
previous_context: super::super::GenericDeployContext,
scope: &<CallFunctionAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let function_args =
super::super::super::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,
receiver_account_id: previous_context.receiver_account_id,
signer_account_id: previous_context.signer_account_id,
deploy_action: previous_context.deploy_action,
function_name: scope.function_name.clone(),
function_args,
})
}
}
impl CallFunctionAction {
fn input_function_args_type(
_context: &super::super::GenericDeployContext,
) -> color_eyre::eyre::Result<
Option<super::super::super::call_function::call_function_args_type::FunctionArgsType>,
> {
super::super::super::call_function::call_function_args_type::input_function_args_type()
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = CallFunctionActionContext)]
#[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,
receiver_account_id: near_primitives::types::AccountId,
signer_account_id: near_primitives::types::AccountId,
deploy_action: near_primitives::transaction::Action,
function_name: String,
function_args: Vec<u8>,
gas: crate::common::NearGas,
}
impl PrepaidGasContext {
pub fn from_previous_context(
previous_context: CallFunctionActionContext,
scope: &<PrepaidGas as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context.global_context,
receiver_account_id: previous_context.receiver_account_id,
signer_account_id: previous_context.signer_account_id,
deploy_action: previous_context.deploy_action,
function_name: previous_context.function_name,
function_args: previous_context.function_args,
gas: scope.gas,
})
}
}
impl PrepaidGas {
fn input_gas(
_context: &CallFunctionActionContext,
) -> 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(named_arg)]
/// Select network
network_config: crate::network_for_transaction::NetworkForTransactionArgs,
}
#[derive(Clone)]
pub struct DepositContext(crate::commands::ActionContext);
impl DepositContext {
pub fn from_previous_context(
previous_context: PrepaidGasContext,
scope: &<Deposit as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let deposit = scope.deposit;
let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback =
std::sync::Arc::new({
let signer_account_id = previous_context.signer_account_id.clone();
let receiver_account_id = previous_context.receiver_account_id.clone();
move |_network_config| {
Ok(crate::commands::PrepopulatedTransaction {
signer_id: signer_account_id.clone(),
receiver_id: receiver_account_id.clone(),
actions: vec![
previous_context.deploy_action.clone(),
near_primitives::transaction::Action::FunctionCall(Box::new(
near_primitives::transaction::FunctionCallAction {
method_name: previous_context.function_name.clone(),
args: previous_context.function_args.clone(),
gas: near_primitives::gas::Gas::from_gas(previous_context.gas.as_gas()),
deposit: deposit.into(),
},
)),
],
})
}
});
Ok(Self(crate::commands::ActionContext {
global_context: previous_context.global_context,
interacting_with_account_ids: vec![
previous_context.signer_account_id.clone(),
previous_context.receiver_account_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<DepositContext> for crate::commands::ActionContext {
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/contract/download_wasm/mod.rs | src/commands/contract/download_wasm/mod.rs | use std::io::Write;
use color_eyre::eyre::Context;
use inquire::CustomType;
use strum::{EnumDiscriminants, EnumIter, EnumMessage};
use crate::common::JsonRpcClientExt;
#[derive(Debug, Clone)]
pub enum ContractType {
Regular(near_primitives::types::AccountId),
GlobalContractByAccountId {
account_id: near_primitives::types::AccountId,
code_hash: Option<near_primitives::hash::CryptoHash>,
},
GlobalContractByCodeHash(near_primitives::hash::CryptoHash),
}
impl std::fmt::Display for ContractType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ContractType::Regular(account_id) => {
write!(f, "regular:{}", account_id)
}
ContractType::GlobalContractByAccountId { account_id, .. } => {
write!(f, "global-contract-by-account-id:{}", account_id)
}
ContractType::GlobalContractByCodeHash(code_hash) => {
write!(f, "global-contract-by-hash:{}", code_hash)
}
}
}
}
#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = crate::GlobalContext)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
#[non_exhaustive]
/// Which type of contract do you want to pass?
pub enum ContractKind {
#[strum_discriminants(strum(
message = "Regular - Regular contract deployed to an account"
))]
Regular(DownloadRegularContract),
#[strum_discriminants(strum(
message = "Global contract by account id - Global contract identified by account ID"
))]
GlobalContractByAccountId(DownloadGlobalContractByAccountId),
#[strum_discriminants(strum(
message = "Global contract by hash - Global contract identified by code hash"
))]
GlobalContractByCodeHash(DownloadGlobalContractByCodeHash),
}
#[derive(Clone)]
pub struct ArgsForDownloadContract {
pub config: crate::config::Config,
pub contract_type: ContractType,
pub interacting_with_account_ids: Vec<near_primitives::types::AccountId>,
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = ArgsForDownloadContract)]
#[interactive_clap(output_context = DownloadContractContext)]
pub struct DownloadContract {
#[interactive_clap(skip_default_input_arg)]
/// Enter the file path where to save the contract:
file_path: crate::types::path_buf::PathBuf,
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_view_at_block::NetworkViewAtBlockArgs,
}
impl DownloadContract {
fn input_file_path(
_context: &ArgsForDownloadContract,
) -> color_eyre::eyre::Result<Option<crate::types::path_buf::PathBuf>> {
Ok(Some(
CustomType::new("Enter the file path where to save the contract:")
.with_starting_input("contract.wasm")
.prompt()?,
))
}
}
pub struct DownloadContractContext(crate::network_view_at_block::ArgsForViewContext);
impl DownloadContractContext {
pub fn from_previous_context(
previous_context: ArgsForDownloadContract,
scope: &<DownloadContract as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let config = previous_context.config;
let contract_type = previous_context.contract_type.clone();
let interacting_with_account_ids = previous_context.interacting_with_account_ids.clone();
let file_path: std::path::PathBuf = scope.file_path.clone().into();
let on_after_getting_block_reference_callback:
crate::network_view_at_block::OnAfterGettingBlockReferenceCallback =
std::sync::Arc::new(move |network_config, block_reference| {
download_contract_code(
&contract_type,
&file_path,
network_config,
block_reference.clone(),
)
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
config,
on_after_getting_block_reference_callback,
interacting_with_account_ids,
}))
}
}
impl From<DownloadContractContext> for crate::network_view_at_block::ArgsForViewContext {
fn from(item: DownloadContractContext) -> Self {
item.0
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = DownloadRegularContractContext)]
pub struct DownloadRegularContract {
#[interactive_clap(skip_default_input_arg)]
account_id: crate::types::account_id::AccountId,
#[interactive_clap(named_arg)]
save_to_file: DownloadContract,
}
impl DownloadRegularContract {
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 is the contract account ID?",
)
}
}
#[derive(Clone)]
pub struct DownloadRegularContractContext {
global_context: crate::GlobalContext,
account_id: crate::types::account_id::AccountId,
}
impl DownloadRegularContractContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<DownloadRegularContract as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context,
account_id: scope.account_id.clone(),
})
}
}
impl From<DownloadRegularContractContext> for ArgsForDownloadContract {
fn from(context: DownloadRegularContractContext) -> Self {
let account_id: near_primitives::types::AccountId = context.account_id.clone().into();
Self {
config: context.global_context.config,
contract_type: ContractType::Regular(account_id.clone()),
interacting_with_account_ids: vec![account_id],
}
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = DownloadGlobalContractByAccountIdContext)]
pub struct DownloadGlobalContractByAccountId {
#[interactive_clap(skip_default_input_arg)]
account_id: crate::types::account_id::AccountId,
#[interactive_clap(skip_default_input_arg)]
code_hash: Option<crate::types::crypto_hash::CryptoHash>,
#[interactive_clap(named_arg)]
save_to_file: DownloadContract,
}
impl DownloadGlobalContractByAccountId {
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 is the account ID of the global contract?",
)
}
pub fn input_code_hash(
_context: &crate::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::types::crypto_hash::CryptoHash>> {
#[derive(strum_macros::Display)]
enum ConfirmOptions {
#[strum(to_string = "Yes, I want to enter a code hash for the global contract")]
Yes,
#[strum(to_string = "No, I don't want to enter a code hash for the global contract")]
No,
}
let select_choose_input = inquire::Select::new(
"Do you want to enter a code hash for a global contract?",
vec![ConfirmOptions::Yes, ConfirmOptions::No],
)
.prompt()?;
if let ConfirmOptions::Yes = select_choose_input {
Ok(Some(
inquire::Text::new("Enter a code hash for a global contract:")
.prompt()?
.parse()?,
))
} else {
Ok(None)
}
}
}
#[derive(Clone)]
pub struct DownloadGlobalContractByAccountIdContext {
global_context: crate::GlobalContext,
account_id: crate::types::account_id::AccountId,
code_hash: Option<crate::types::crypto_hash::CryptoHash>,
}
impl DownloadGlobalContractByAccountIdContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<DownloadGlobalContractByAccountId as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context,
account_id: scope.account_id.clone(),
code_hash: scope.code_hash,
})
}
}
impl From<DownloadGlobalContractByAccountIdContext> for ArgsForDownloadContract {
fn from(context: DownloadGlobalContractByAccountIdContext) -> Self {
let account_id: near_primitives::types::AccountId = context.account_id.clone().into();
Self {
config: context.global_context.config,
contract_type: ContractType::GlobalContractByAccountId {
account_id: account_id.clone(),
code_hash: context.code_hash.map(|code_hash| code_hash.into()),
},
interacting_with_account_ids: vec![account_id],
}
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = DownloadGlobalContractByCodeHashContext)]
pub struct DownloadGlobalContractByCodeHash {
/// What is the code hash of the global contract?
code_hash: crate::types::crypto_hash::CryptoHash,
#[interactive_clap(named_arg)]
save_to_file: DownloadContract,
}
#[derive(Clone)]
pub struct DownloadGlobalContractByCodeHashContext {
global_context: crate::GlobalContext,
code_hash: crate::types::crypto_hash::CryptoHash,
}
impl DownloadGlobalContractByCodeHashContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<DownloadGlobalContractByCodeHash as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context,
code_hash: scope.code_hash,
})
}
}
impl From<DownloadGlobalContractByCodeHashContext> for ArgsForDownloadContract {
fn from(context: DownloadGlobalContractByCodeHashContext) -> Self {
let code_hash: near_primitives::hash::CryptoHash = context.code_hash.into();
Self {
config: context.global_context.config,
contract_type: ContractType::GlobalContractByCodeHash(code_hash),
interacting_with_account_ids: vec![],
}
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = crate::GlobalContext)]
pub struct Contract {
#[interactive_clap(subcommand)]
/// Which type of contract do you want to download?
contract_kind: ContractKind,
}
fn download_contract_code(
contract_type: &ContractType,
file_path: &std::path::PathBuf,
network_config: &crate::config::NetworkConfig,
block_reference: near_primitives::types::BlockReference,
) -> crate::CliResult {
let code = get_code(contract_type, network_config, block_reference)?;
std::fs::File::create(file_path)
.wrap_err_with(|| format!("Failed to create file: {file_path:?}"))?
.write(&code)
.wrap_err_with(|| format!("Failed to write to file: {file_path:?}"))?;
tracing::info!(
parent: &tracing::Span::none(),
"The file {:?} was downloaded successfully",
file_path
);
Ok(())
}
#[tracing::instrument(name = "Trying to download contract code ...", skip_all)]
pub fn get_code(
contract_type: &ContractType,
network_config: &crate::config::NetworkConfig,
block_reference: near_primitives::types::BlockReference,
) -> color_eyre::eyre::Result<Vec<u8>> {
tracing::info!(target: "near_teach_me", "Trying to download contract code ...");
let (request, hash_to_match) = match contract_type.clone() {
ContractType::Regular(account_id) => (
near_primitives::views::QueryRequest::ViewCode { account_id },
None,
),
ContractType::GlobalContractByAccountId {
account_id,
code_hash,
} => (
near_primitives::views::QueryRequest::ViewGlobalContractCodeByAccountId { account_id },
code_hash,
),
ContractType::GlobalContractByCodeHash(code_hash) => (
near_primitives::views::QueryRequest::ViewGlobalContractCode { code_hash },
Some(code_hash),
),
};
let block_height = network_config
.json_rpc_client()
.blocking_call(near_jsonrpc_client::methods::block::RpcBlockRequest {
block_reference: block_reference.clone(),
})
.wrap_err_with(|| {
format!(
"Failed to fetch block info for block reference {:?} on network <{}>",
block_reference, network_config.network_name
)
})?
.header
.height;
let number_of_shards = network_config
.json_rpc_client()
.blocking_call(
near_jsonrpc_client::methods::EXPERIMENTAL_protocol_config::RpcProtocolConfigRequest {
block_reference: block_reference.clone(),
},
)
.wrap_err_with(|| {
format!(
"Failed to fetch shards info for block height {} on network <{}>",
block_height, network_config.network_name
)
})?
.shard_layout
.num_shards();
for block_height in block_height..=block_height + number_of_shards * 2 {
tracing::info!(
parent: &tracing::Span::none(),
"Trying to fetch contract code for <{}> at block height {} on network <{}>...",
contract_type, block_height, network_config.network_name
);
let Ok(query_view_method_response) = network_config.json_rpc_client().blocking_call(
near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference: near_primitives::types::BlockReference::BlockId(
near_primitives::types::BlockId::Height(block_height),
),
request: request.clone(),
},
) else {
continue;
};
let call_access_view =
if let near_jsonrpc_primitives::types::query::QueryResponseKind::ViewCode(result) =
query_view_method_response.kind
{
result
} else {
return Err(color_eyre::Report::msg("Error call result".to_string()));
};
if let Some(hash_to_match) = hash_to_match {
let code_hash = near_primitives::hash::CryptoHash::hash_bytes(&call_access_view.code);
if code_hash != hash_to_match {
tracing::warn!(
parent: &tracing::Span::none(),
"Fetched code hash {} does not match the expected code hash {}. Trying next block height...",
code_hash,
hash_to_match
);
continue;
}
}
return Ok(call_access_view.code);
}
Err(color_eyre::Report::msg(format!(
"Failed to fetch contract code for <{}> on network <{}> after trying {} block heights.",
contract_type,
network_config.network_name,
block_height + number_of_shards * 2 - block_height + 1
)))
}
| 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/contract/inspect/mod.rs | src/commands/contract/inspect/mod.rs | use std::fmt::Write;
use color_eyre::{
eyre::{Context, Report},
owo_colors::OwoColorize,
};
use thiserror::Error;
use tracing_indicatif::span_ext::IndicatifSpanExt;
use near_primitives::types::BlockReference;
use super::FetchAbiError;
use crate::common::{CallResultExt, RpcQueryResponseExt};
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = ContractContext)]
pub struct Contract {
#[interactive_clap(skip_default_input_arg)]
/// What is the contract account ID?
contract_account_id: crate::types::account_id::AccountId,
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_view_at_block::NetworkViewAtBlockArgs,
}
impl Contract {
pub fn input_contract_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 contract account ID?",
)
}
}
#[derive(Clone)]
pub struct ContractContext(crate::network_view_at_block::ArgsForViewContext);
impl ContractContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<Contract 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.contract_account_id.clone().into();
move |network_config, block_reference| {
tokio::runtime::Runtime::new()
.unwrap()
.block_on(display_inspect_contract(
&account_id,
network_config,
block_reference,
))
}
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
config: previous_context.config,
on_after_getting_block_reference_callback,
interacting_with_account_ids: vec![scope.contract_account_id.clone().into()],
}))
}
}
impl From<ContractContext> for crate::network_view_at_block::ArgsForViewContext {
fn from(item: ContractContext) -> Self {
item.0
}
}
#[tracing::instrument(name = "Obtaining the contract code ...", skip_all)]
async fn get_contract_code(
account_id: &near_primitives::types::AccountId,
network_config: &crate::config::NetworkConfig,
block_reference: &near_primitives::types::BlockReference,
) -> color_eyre::eyre::Result<near_jsonrpc_client::methods::query::RpcQueryResponse> {
tracing::info!(target: "near_teach_me", "Obtaining the contract code ...");
network_config
.json_rpc_client()
.call(near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference: block_reference.clone(),
request: near_primitives::views::QueryRequest::ViewCode {
account_id: account_id.clone(),
},
})
.await
.wrap_err_with(|| {
format!(
"Failed to fetch query ViewCode for <{}> on network <{}>",
&account_id, network_config.network_name
)
})
}
#[tracing::instrument(name = "Contract inspection ...", skip_all)]
async fn display_inspect_contract(
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", "Contract inspection ...");
let json_rpc_client = network_config.json_rpc_client();
let view_code_response = get_contract_code(account_id, network_config, block_reference).await?;
let contract_code_view =
if let near_jsonrpc_primitives::types::query::QueryResponseKind::ViewCode(result) =
view_code_response.kind
{
result
} else {
return Err(color_eyre::Report::msg("Error call result".to_string()));
};
let account_view = get_account_view(
&network_config.network_name,
&json_rpc_client,
block_reference,
account_id,
)
.await?;
let access_keys = get_access_keys(
&network_config.network_name,
&json_rpc_client,
block_reference,
account_id,
)
.await?;
let mut table = prettytable::Table::new();
table.set_format(*prettytable::format::consts::FORMAT_NO_COLSEP);
table.add_row(prettytable::row![
Fg->account_id,
format!("At block #{}\n({})", view_code_response.block_height, view_code_response.block_hash)
]);
let (contract_type, contract_status, checksum_hex, checksum_base58, storage_used) = match (
&account_view.code_hash,
&account_view.global_contract_account_id,
&account_view.global_contract_hash,
) {
(_, Some(global_contract_account_id), None) => (
"Global Contract",
format!("deployed by account ID <{global_contract_account_id}>"),
"no data".to_string(),
"no data".to_string(),
format!("{}", bytesize::ByteSize(account_view.storage_usage)),
),
(_, None, Some(global_contract_hash)) => (
"Global Contract",
"deployed by Hash".to_string(),
hex::encode(global_contract_hash.as_ref()),
bs58::encode(global_contract_hash).into_string(),
format!("{}", bytesize::ByteSize(account_view.storage_usage)),
),
(code_hash, None, None) => (
"Local Contract",
String::new(),
hex::encode(code_hash.as_ref()),
bs58::encode(code_hash).into_string(),
format!(
"{} ({} Wasm + {} data)",
bytesize::ByteSize(account_view.storage_usage),
bytesize::ByteSize(u64::try_from(contract_code_view.code.len())?),
bytesize::ByteSize(
account_view
.storage_usage
.checked_sub(u64::try_from(contract_code_view.code.len())?)
.expect("Unexpected error")
)
),
),
(_code_hash, _global_account_id, _global_hash) => (
"Contract",
"Invalid account contract state. Please contact the developers."
.red()
.to_string(),
String::new(),
String::new(),
format!("{}", bytesize::ByteSize(account_view.storage_usage)),
),
};
table.add_row(prettytable::row![
Fy->contract_type,
contract_status
]);
table.add_row(prettytable::row![
Fy->"SHA-256 checksum [hex]",
checksum_hex
]);
table.add_row(prettytable::row![
Fy->"SHA-256 checksum [base58]",
checksum_base58
]);
table.add_row(prettytable::row![
Fy->"Storage used",
storage_used
]);
let access_keys_summary = if access_keys.is_empty() {
"Contract is locked (no access keys)".to_string()
} else {
let full_access_keys_count = access_keys
.iter()
.filter(|access_key| {
matches!(
access_key.access_key.permission,
near_primitives::views::AccessKeyPermissionView::FullAccess
)
})
.count();
format!(
"{} full access keys and {} function-call-only access keys",
full_access_keys_count,
access_keys.len() - full_access_keys_count
)
};
table.add_row(prettytable::row![
Fy->"Access keys",
access_keys_summary
]);
match get_contract_source_metadata(&json_rpc_client, block_reference, account_id).await {
Ok(contract_source_metadata) => {
table.add_row(prettytable::row![
Fy->"Contract version",
contract_source_metadata.version.unwrap_or_default()
]);
table.add_row(prettytable::row![
Fy->"Contract link",
contract_source_metadata.link.unwrap_or_default()
]);
table.add_row(prettytable::row![
Fy->"Supported standards",
contract_source_metadata.standards
.iter()
.fold(String::new(), |mut output, standard| {
let _ = writeln!(output, "{} ({})", standard.standard, standard.version);
output
})
]);
}
Err(err) => {
table.add_row(prettytable::row![
"",
textwrap::fill(
&format!(
"{}: {}",
match &err {
FetchContractSourceMetadataError::ContractSourceMetadataNotSupported => "Info",
FetchContractSourceMetadataError::ContractSourceMetadataUnknownFormat(_) |
FetchContractSourceMetadataError::RpcError(_) => "Warning",
},
err
),
80
)
]);
table.add_row(prettytable::row![
Fy->"Contract version",
"N/A"
]);
table.add_row(prettytable::row![
Fy->"Contract link",
"N/A"
]);
table.add_row(prettytable::row![
Fy->"Supported standards",
"N/A"
]);
}
}
match super::get_contract_abi(&json_rpc_client, block_reference, account_id).await {
Ok(abi_root) => {
table.add_row(prettytable::row![
Fy->"NEAR ABI version",
abi_root.schema_version
]);
table.printstd();
println!(
"\n {} (hint: you can download full JSON Schema using `download-abi` command)",
"Functions:".yellow()
);
for function in abi_root.body.functions {
let mut table_func = prettytable::Table::new();
table_func.set_format(*prettytable::format::consts::FORMAT_CLEAN);
table_func.add_empty_row();
table_func.add_row(prettytable::row![format!(
"{} ({}) {}\n{}",
format!(
"fn {}({}) -> {}",
function.name.green(),
"...".yellow(),
"...".blue()
),
match function.kind {
near_abi::AbiFunctionKind::Call =>
"read-write function - transcation required",
near_abi::AbiFunctionKind::View => "read-only function",
},
function
.modifiers
.iter()
.fold(String::new(), |mut output, modifier| {
let _ = write!(
output,
"{} ",
match modifier {
near_abi::AbiFunctionModifier::Init => "init".red(),
near_abi::AbiFunctionModifier::Payable => "payable".red(),
near_abi::AbiFunctionModifier::Private => "private".red(),
}
);
output
}),
function.doc.unwrap_or_default()
)]);
table_func.printstd();
let mut table_args = prettytable::Table::new();
table_args.set_format(*prettytable::format::consts::FORMAT_CLEAN);
table_args.get_format().padding(1, 0);
table_args.add_row(prettytable::row![
"...".yellow(),
Fy->"Arguments (JSON Schema):",
]);
table_args.add_row(prettytable::row![
" ",
if function.params.is_empty() {
"No arguments needed".to_string()
} else {
serde_json::to_string_pretty(&function.params).unwrap_or_default()
}
]);
table_args.add_row(prettytable::row![
"...".blue(),
Fb->"Return Value (JSON Schema):",
]);
table_args.add_row(prettytable::row![
" ",
if let Some(result) = function.result {
serde_json::to_string_pretty(&result).unwrap_or_default()
} else {
"No return value".to_string()
}
]);
table_args.printstd();
}
}
Err(err) => {
table.add_row(prettytable::row![
Fy->"NEAR ABI version",
textwrap::fill(
&format!(
"{}: {}",
match &err {
FetchAbiError::AbiNotSupported => "Info",
FetchAbiError::AbiUnknownFormat(_) | FetchAbiError::RpcError(_) => "Warning",
},
err
),
80
)
]);
table.printstd();
println!(
"\n {} (NEAR ABI is not available, so only function names are extracted)\n",
"Functions:".yellow()
);
let parser = wasmparser::Parser::new(0);
for payload in parser.parse_all(&contract_code_view.code) {
if let wasmparser::Payload::ExportSection(export_section) =
payload.wrap_err_with(|| {
format!(
"Could not parse WebAssembly binary of the contract <{account_id}>."
)
})?
{
for export in export_section {
let export = export
.wrap_err_with(|| format!("Could not parse WebAssembly export section of the contract <{account_id}>."))?;
if let wasmparser::ExternalKind::Func = export.kind {
println!(
" fn {}({}) -> {}\n",
export.name.green(),
"...".yellow(),
"...".blue()
);
}
}
}
}
}
}
Ok(())
}
#[tracing::instrument(name = "Getting information about", skip_all)]
async fn get_account_view(
network_name: &str,
json_rpc_client: &near_jsonrpc_client::JsonRpcClient,
block_reference: &BlockReference,
account_id: &near_primitives::types::AccountId,
) -> color_eyre::eyre::Result<near_primitives::views::AccountView> {
tracing::Span::current().pb_set_message(&format!("{account_id} ..."));
tracing::info!(target: "near_teach_me", "Getting information about {account_id} ...");
for _ in 0..5 {
let account_view_response = json_rpc_client
.call(near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference: block_reference.clone(),
request: near_primitives::views::QueryRequest::ViewAccount {
account_id: account_id.clone(),
},
})
.await;
if let Err(near_jsonrpc_client::errors::JsonRpcError::TransportError(_)) =
&account_view_response
{
eprintln!("Transport error.\nPlease wait. The next try to send this query is happening right now ...");
std::thread::sleep(std::time::Duration::from_millis(100))
} else {
return account_view_response
.wrap_err_with(|| {
format!(
"Failed to fetch query ViewAccount for contract <{account_id}> on network <{network_name}>"
)
})?
.account_view();
}
}
color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!(format!(
"Transport error. Failed to fetch query ViewAccount for contract <{account_id}> on network <{network_name}>"
)))
}
#[tracing::instrument(name = "Getting a list of", skip_all)]
async fn get_access_keys(
network_name: &str,
json_rpc_client: &near_jsonrpc_client::JsonRpcClient,
block_reference: &BlockReference,
account_id: &near_primitives::types::AccountId,
) -> color_eyre::eyre::Result<Vec<near_primitives::views::AccessKeyInfoView>> {
tracing::Span::current().pb_set_message(&format!("{account_id} access keys ..."));
tracing::info!(target: "near_teach_me", "Getting a list of {account_id} access keys ...");
for _ in 0..5 {
let access_keys_response = json_rpc_client
.call(near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference: block_reference.clone(),
request: near_primitives::views::QueryRequest::ViewAccessKeyList {
account_id: account_id.clone(),
},
})
.await;
if let Err(near_jsonrpc_client::errors::JsonRpcError::TransportError(_)) =
&access_keys_response
{
eprintln!("Transport error.\nPlease wait. The next try to send this query is happening right now ...");
std::thread::sleep(std::time::Duration::from_millis(100))
} else {
return Ok(access_keys_response
.wrap_err_with(|| {
format!(
"Failed to fetch ViewAccessKeyList for contract <{account_id}> on network <{network_name}>"
)
})?
.access_key_list_view()?
.keys);
}
}
color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!(format!(
"Transport error. Failed to fetch query ViewAccessKeyList for contract <{account_id}> on network <{network_name}>"
)))
}
#[derive(Error, Debug)]
pub enum FetchContractSourceMetadataError {
#[error("Contract Source Metadata (https://nomicon.io/Standards/SourceMetadata) is not supported by the contract, so there is no way to get detailed information.")]
ContractSourceMetadataNotSupported,
#[error("'contract_source_metadata' function call failed due to RPC error, so there is no way to get Contract Source Metadata. See more details about the error:\n\n{0}")]
RpcError(
near_jsonrpc_client::errors::JsonRpcError<
near_jsonrpc_primitives::types::query::RpcQueryError,
>,
),
#[error("The contract source metadata format is unknown (https://nomicon.io/Standards/SourceMetadata), so there is no way to get detailed information. See more details about the error:\n\n{0}")]
ContractSourceMetadataUnknownFormat(Report),
}
#[tracing::instrument(name = "Getting contract source metadata for account", skip_all)]
pub async fn get_contract_source_metadata(
json_rpc_client: &near_jsonrpc_client::JsonRpcClient,
block_reference: &BlockReference,
account_id: &near_primitives::types::AccountId,
) -> Result<
near_verify_rs::types::contract_source_metadata::ContractSourceMetadata,
FetchContractSourceMetadataError,
> {
tracing::Span::current().pb_set_message(&format!("{account_id} ..."));
tracing::info!(target: "near_teach_me", "Getting contract source metadata for account {account_id} ...");
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"I am making HTTP call to NEAR JSON RPC to call a read-only function `contract_source_metadata` on `{}` account, learn more https://docs.near.org/api/rpc/contracts#call-a-contract-function",
account_id
);
let mut retries_left = (0..5).rev();
loop {
let rpc_query_request = near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference: block_reference.clone(),
request: near_primitives::views::QueryRequest::CallFunction {
account_id: account_id.clone(),
method_name: "contract_source_metadata".to_owned(),
args: near_primitives::types::FunctionArgs::from(vec![]),
},
};
crate::common::teach_me_request_payload(json_rpc_client, &rpc_query_request);
let contract_source_metadata_response = json_rpc_client.call(rpc_query_request).await;
match contract_source_metadata_response {
Err(near_jsonrpc_client::errors::JsonRpcError::TransportError(err)) => {
if let Some(retries_left) = retries_left.next() {
sleep_after_error(format!(
"(Previous attempt failed with error: `{}`. Will retry {} more times)",
err.to_string().red(),
retries_left
));
} else {
return Err(FetchContractSourceMetadataError::RpcError(
near_jsonrpc_client::errors::JsonRpcError::TransportError(err),
));
}
}
Err(near_jsonrpc_client::errors::JsonRpcError::ServerError(
near_jsonrpc_client::errors::JsonRpcServerError::HandlerError(
near_jsonrpc_primitives::types::query::RpcQueryError::ContractExecutionError {
vm_error,
..
},
),
)) if vm_error.contains("MethodNotFound") => {
return Err(FetchContractSourceMetadataError::ContractSourceMetadataNotSupported);
}
Err(err) => {
return Err(FetchContractSourceMetadataError::RpcError(err));
}
Ok(contract_source_metadata_response) => {
return contract_source_metadata_response
.call_result()
.inspect(|call_result| {
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"JSON RPC Response:\n{}",
crate::common::indent_payload(&format!(
"{{\n \"block_hash\": {}\n \"block_height\": {}\n \"logs\": {:?}\n \"result\": {:?}\n}}",
contract_source_metadata_response.block_hash,
contract_source_metadata_response.block_height,
call_result.logs,
call_result.result
))
);
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"Decoding the \"result\" array of bytes as UTF-8 string (tip: you can use this Python snippet to do it: `\"\".join([chr(c) for c in result])`):\n{}",
crate::common::indent_payload(&format!("{}\n ",
&String::from_utf8(call_result.result.clone())
.unwrap_or_else(|_| "<decoding failed - the result is not a UTF-8 string>".to_owned())
))
);
})
.inspect_err(|err| {
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"JSON RPC Response:\n{}",
crate::common::indent_payload(&err.to_string())
);
})
.map_err(FetchContractSourceMetadataError::ContractSourceMetadataUnknownFormat)?
.parse_result_from_json::<near_verify_rs::types::contract_source_metadata::ContractSourceMetadata>()
.wrap_err("Failed to parse contract source metadata")
.map_err(
FetchContractSourceMetadataError::ContractSourceMetadataUnknownFormat,
);
}
}
}
}
#[tracing::instrument(name = "Waiting 3 seconds before sending a request via RPC", skip_all)]
fn sleep_after_error(additional_message_for_name: String) {
tracing::Span::current().pb_set_message(&additional_message_for_name);
tracing::info!(target: "near_teach_me", "Waiting 3 seconds before sending a request via RPC {additional_message_for_name}");
std::thread::sleep(std::time::Duration::from_secs(3));
}
| 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/contract/call_function/mod.rs | src/commands/contract/call_function/mod.rs | use inquire::{Select, Text};
use strum::{EnumDiscriminants, EnumIter, EnumMessage};
mod as_read_only;
mod as_transaction;
pub mod call_function_args_type;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = crate::GlobalContext)]
pub struct CallFunctionCommands {
#[interactive_clap(subcommand)]
function_call_actions: CallFunctionActions,
}
#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = crate::GlobalContext)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
/// Сhoose action for account:
pub enum CallFunctionActions {
#[strum_discriminants(strum(message = "as-read-only - Calling a view method"))]
/// Calling a view method
AsReadOnly(self::as_read_only::CallFunctionView),
#[strum_discriminants(strum(message = "as-transaction - Calling a change method"))]
/// Calling a change method
AsTransaction(self::as_transaction::CallFunction),
}
pub fn input_call_function_name(
global_context: &crate::GlobalContext,
contract_account_id: &near_primitives::types::AccountId,
) -> color_eyre::eyre::Result<Option<String>> {
input_function_name(
global_context,
contract_account_id,
near_abi::AbiFunctionKind::Call,
"Select the as-transaction function for your contract:",
)
}
pub fn input_view_function_name(
global_context: &crate::GlobalContext,
contract_account_id: &near_primitives::types::AccountId,
) -> color_eyre::eyre::Result<Option<String>> {
input_function_name(
global_context,
contract_account_id,
near_abi::AbiFunctionKind::View,
"Select the viewing function for your contract:",
)
}
fn input_function_name(
global_context: &crate::GlobalContext,
contract_account_id: &near_primitives::types::AccountId,
function_kind: near_abi::AbiFunctionKind,
message: &str,
) -> color_eyre::eyre::Result<Option<String>> {
let network_config = crate::common::find_network_where_account_exist(
global_context,
contract_account_id.clone(),
)?;
if let Some(network_config) = network_config {
let json_rpc_client = network_config.json_rpc_client();
if let Ok(contract_abi) =
tokio::runtime::Runtime::new()
.unwrap()
.block_on(super::get_contract_abi(
&json_rpc_client,
&near_primitives::types::Finality::Final.into(),
contract_account_id,
))
{
let function_names = contract_abi
.body
.functions
.into_iter()
.filter(|function| function_kind == function.kind)
.map(|function| function.name)
.collect::<Vec<String>>();
if !function_names.is_empty() {
return Ok(Some(
Select::new(message, function_names).prompt()?.to_string(),
));
}
}
}
Ok(Some(
Text::new("What is the name of the function?").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/contract/call_function/as_transaction/mod.rs | src/commands/contract/call_function/as_transaction/mod.rs | use inquire::CustomType;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = CallFunctionContext)]
pub struct CallFunction {
#[interactive_clap(skip_default_input_arg)]
/// What is the contract account ID?
contract_account_id: crate::types::account_id::AccountId,
#[interactive_clap(subargs)]
/// Select function
function: Function,
}
#[derive(Debug, Clone)]
pub struct CallFunctionContext {
global_context: crate::GlobalContext,
contract_account_id: near_primitives::types::AccountId,
}
impl CallFunctionContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<CallFunction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context,
contract_account_id: scope.contract_account_id.clone().into(),
})
}
}
impl CallFunction {
pub fn input_contract_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 contract account ID?",
)
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = CallFunctionContext)]
#[interactive_clap(output_context = FunctionContext)]
pub struct Function {
#[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: super::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(Clone)]
pub struct FunctionContext {
global_context: crate::GlobalContext,
contract_account_id: near_primitives::types::AccountId,
function_name: String,
function_args: Vec<u8>,
}
impl FunctionContext {
pub fn from_previous_context(
previous_context: CallFunctionContext,
scope: &<Function as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let function_args = super::call_function_args_type::function_args(
scope.function_args.clone(),
scope.function_args_type.clone(),
)?;
Ok(Self {
global_context: previous_context.global_context,
contract_account_id: previous_context.contract_account_id,
function_name: scope.function_name.clone(),
function_args,
})
}
}
impl Function {
fn input_function_args_type(
_context: &CallFunctionContext,
) -> color_eyre::eyre::Result<Option<super::call_function_args_type::FunctionArgsType>> {
super::call_function_args_type::input_function_args_type()
}
fn input_function_name(
context: &CallFunctionContext,
) -> color_eyre::eyre::Result<Option<String>> {
super::input_call_function_name(&context.global_context, &context.contract_account_id)
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = FunctionContext)]
#[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,
contract_account_id: near_primitives::types::AccountId,
function_name: String,
function_args: Vec<u8>,
gas: crate::common::NearGas,
}
impl PrepaidGasContext {
pub fn from_previous_context(
previous_context: FunctionContext,
scope: &<PrepaidGas as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context.global_context,
contract_account_id: previous_context.contract_account_id,
function_name: previous_context.function_name,
function_args: previous_context.function_args,
gas: scope.gas,
})
}
}
impl PrepaidGas {
fn input_gas(
_context: &FunctionContext,
) -> 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(named_arg)]
/// What is the signer account ID?
sign_as: SignerAccountId,
}
#[derive(Debug, Clone)]
pub struct DepositContext {
global_context: crate::GlobalContext,
contract_account_id: near_primitives::types::AccountId,
function_name: String,
function_args: Vec<u8>,
gas: crate::common::NearGas,
deposit: crate::types::near_token::NearToken,
}
impl DepositContext {
pub fn from_previous_context(
previous_context: PrepaidGasContext,
scope: &<Deposit as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context.global_context,
contract_account_id: previous_context.contract_account_id,
function_name: previous_context.function_name,
function_args: previous_context.function_args,
gas: previous_context.gas,
deposit: scope.deposit,
})
}
}
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()?
))
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = DepositContext)]
#[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(Debug, Clone)]
pub struct SignerAccountIdContext {
global_context: crate::GlobalContext,
contract_account_id: near_primitives::types::AccountId,
function_name: String,
function_args: Vec<u8>,
gas: crate::common::NearGas,
deposit: crate::types::near_token::NearToken,
signer_account_id: near_primitives::types::AccountId,
}
impl SignerAccountIdContext {
pub fn from_previous_context(
previous_context: DepositContext,
scope: &<SignerAccountId as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context.global_context,
contract_account_id: previous_context.contract_account_id,
function_name: previous_context.function_name,
function_args: previous_context.function_args,
gas: previous_context.gas,
deposit: previous_context.deposit,
signer_account_id: scope.signer_account_id.clone().into(),
})
}
}
impl From<SignerAccountIdContext> for crate::commands::ActionContext {
fn from(item: SignerAccountIdContext) -> 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();
let receiver_account_id = item.contract_account_id.clone();
move |_network_config| {
Ok(crate::commands::PrepopulatedTransaction {
signer_id: signer_account_id.clone(),
receiver_id: receiver_account_id.clone(),
actions: vec![near_primitives::transaction::Action::FunctionCall(
Box::new(near_primitives::transaction::FunctionCallAction {
method_name: item.function_name.clone(),
args: item.function_args.clone(),
gas: near_primitives::gas::Gas::from_gas(item.gas.as_gas()),
deposit: item.deposit.into(),
}),
)],
})
}
});
Self {
global_context: item.global_context,
interacting_with_account_ids: vec![item.signer_account_id, item.contract_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 SignerAccountId {
pub fn input_signer_account_id(
context: &DepositContext,
) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> {
crate::common::input_signer_account_id_from_used_account_list(
&context.global_context.config.credentials_home_dir,
"What is the signer 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/contract/call_function/as_read_only/mod.rs | src/commands/contract/call_function/as_read_only/mod.rs | use color_eyre::eyre::Context;
use std::io::Write;
use crate::common::CallResultExt;
use crate::common::JsonRpcClientExt;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = CallFunctionViewContext)]
pub struct CallFunctionView {
#[interactive_clap(skip_default_input_arg)]
/// What is the contract account ID?
contract_account_id: crate::types::account_id::AccountId,
#[interactive_clap(subargs)]
/// Select function
function: Function,
}
#[derive(Clone)]
pub struct CallFunctionViewContext {
global_context: crate::GlobalContext,
contract_account_id: near_primitives::types::AccountId,
}
impl CallFunctionViewContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<CallFunctionView as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context,
contract_account_id: scope.contract_account_id.clone().into(),
})
}
}
impl CallFunctionView {
pub fn input_contract_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 contract account ID?",
)
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = CallFunctionViewContext)]
#[interactive_clap(output_context = FunctionContext)]
pub struct Function {
#[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: super::call_function_args_type::FunctionArgsType,
/// Enter the arguments to this function:
function_args: String,
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_view_at_block::NetworkViewAtBlockArgs,
}
#[derive(Clone)]
pub struct FunctionContext(crate::network_view_at_block::ArgsForViewContext);
impl FunctionContext {
pub fn from_previous_context(
previous_context: CallFunctionViewContext,
scope: &<Function 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 function_args = scope.function_args.clone();
let function_args_type = scope.function_args_type.clone();
let account_id: near_primitives::types::AccountId = previous_context.contract_account_id.clone();
let function_name = scope.function_name.clone();
move |network_config, block_reference| {
call_view_function(
network_config,
&account_id,
&function_name,
function_args.clone(),
function_args_type.clone(),
block_reference,
previous_context.global_context.verbosity,
)
}
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
config: previous_context.global_context.config,
interacting_with_account_ids: vec![previous_context.contract_account_id],
on_after_getting_block_reference_callback,
}))
}
}
impl From<FunctionContext> for crate::network_view_at_block::ArgsForViewContext {
fn from(item: FunctionContext) -> Self {
item.0
}
}
impl Function {
fn input_function_args_type(
_context: &CallFunctionViewContext,
) -> color_eyre::eyre::Result<Option<super::call_function_args_type::FunctionArgsType>> {
super::call_function_args_type::input_function_args_type()
}
fn input_function_name(
context: &CallFunctionViewContext,
) -> color_eyre::eyre::Result<Option<String>> {
super::input_view_function_name(&context.global_context, &context.contract_account_id)
}
}
#[tracing::instrument(name = "Getting a response to a read-only function call ...", skip_all)]
fn call_view_function(
network_config: &crate::config::NetworkConfig,
account_id: &near_primitives::types::AccountId,
function_name: &str,
function_args: String,
function_args_type: super::call_function_args_type::FunctionArgsType,
block_reference: &near_primitives::types::BlockReference,
verbosity: crate::Verbosity,
) -> crate::CliResult {
tracing::info!(target: "near_teach_me", "Getting a response to a read-only function call ...");
let args = super::call_function_args_type::function_args(function_args, function_args_type)?;
let call_result = network_config
.json_rpc_client()
.blocking_call_view_function(account_id, function_name, args, block_reference.clone())
.wrap_err_with(|| {
format!(
"Failed to fetch query for read-only function call: '{}' (contract <{}> on network <{}>)",
function_name, account_id, network_config.network_name
)
})?;
let info_str = if call_result.result.is_empty() {
"Empty return value".to_string()
} else if let Ok(json_result) = call_result.parse_result_from_json::<serde_json::Value>() {
serde_json::to_string_pretty(&json_result)?
} else if let Ok(string_result) = String::from_utf8(call_result.result.clone()) {
string_result
} else {
"The returned value is not printable (binary data)".to_string()
};
call_result.print_logs();
if let crate::Verbosity::Quiet = verbosity {
std::io::stdout().write_all(&call_result.result)?;
} else {
tracing_indicatif::suspend_tracing_indicatif(|| {
eprintln!("Function execution return value (printed to stdout):")
});
tracing_indicatif::suspend_tracing_indicatif(|| println!("{info_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/contract/call_function/call_function_args_type/mod.rs | src/commands/contract/call_function/call_function_args_type/mod.rs | use std::str::FromStr;
use color_eyre::eyre::Context;
use inquire::Select;
use strum::{EnumDiscriminants, EnumIter, EnumMessage, IntoEnumIterator};
#[derive(Debug, EnumDiscriminants, Clone, clap::ValueEnum)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
/// How do you want to pass the function call arguments?
pub enum FunctionArgsType {
#[strum_discriminants(strum(
message = "json-args - Valid JSON arguments (e.g. {\"token_id\": \"42\"})"
))]
/// Valid JSON arguments (e.g. {"token_id": "42"})
JsonArgs,
#[strum_discriminants(strum(message = "text-args - Arbitrary text arguments"))]
/// Arbitrary text arguments
TextArgs,
#[strum_discriminants(strum(message = "base64-args - Base64-encoded string (e.g. e30=)"))]
/// Base64-encoded string (e.g. e30=)
Base64Args,
#[strum_discriminants(strum(
message = "file-args - Read from file (e.g. reusable JSON or binary data)"
))]
/// Read from file (e.g. reusable JSON or binary data)
FileArgs,
}
impl interactive_clap::ToCli for FunctionArgsType {
type CliVariant = FunctionArgsType;
}
impl std::str::FromStr for FunctionArgsType {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"json-args" => Ok(Self::JsonArgs),
"text-args" => Ok(Self::TextArgs),
"base64-args" => Ok(Self::Base64Args),
"file-args" => Ok(Self::FileArgs),
_ => Err("FunctionArgsType: incorrect value entered".to_string()),
}
}
}
impl std::fmt::Display for FunctionArgsType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Self::JsonArgs => write!(f, "json-args"),
Self::TextArgs => write!(f, "text-args"),
Self::Base64Args => write!(f, "base64-args"),
Self::FileArgs => write!(f, "file-args"),
}
}
}
impl std::fmt::Display for FunctionArgsTypeDiscriminants {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Self::JsonArgs => write!(f, "json-args - Valid JSON arguments (e.g. {{\"token_id\": \"42\"}} or {{}} if no arguments)"),
Self::TextArgs => write!(f, "text-args - Arbitrary text arguments"),
Self::Base64Args => write!(f, "base64-args - Base64-encoded string (e.g. e30=)"),
Self::FileArgs => write!(f, "file-args - Read from file reusable JSON or binary data (e.g. ./args.json)"),
}
}
}
pub fn input_function_args_type() -> color_eyre::eyre::Result<Option<FunctionArgsType>> {
let variants = FunctionArgsTypeDiscriminants::iter().collect::<Vec<_>>();
let selected = Select::new(
"How would you like to pass the function arguments?",
variants,
)
.prompt()?;
match selected {
FunctionArgsTypeDiscriminants::JsonArgs => Ok(Some(FunctionArgsType::JsonArgs)),
FunctionArgsTypeDiscriminants::TextArgs => Ok(Some(FunctionArgsType::TextArgs)),
FunctionArgsTypeDiscriminants::Base64Args => Ok(Some(FunctionArgsType::Base64Args)),
FunctionArgsTypeDiscriminants::FileArgs => Ok(Some(FunctionArgsType::FileArgs)),
}
}
pub fn function_args(
args: String,
function_args_type: FunctionArgsType,
) -> color_eyre::eyre::Result<Vec<u8>> {
match function_args_type {
super::call_function_args_type::FunctionArgsType::JsonArgs => {
let data_json =
serde_json::Value::from_str(&args).wrap_err("Data not in JSON format!")?;
serde_json::to_vec(&data_json).wrap_err("Internal error!")
}
super::call_function_args_type::FunctionArgsType::TextArgs => Ok(args.into_bytes()),
super::call_function_args_type::FunctionArgsType::Base64Args => {
Ok(near_primitives::serialize::from_base64(&args)
.map_err(|_| color_eyre::eyre::eyre!("Data cannot be decoded with base64"))?)
}
super::call_function_args_type::FunctionArgsType::FileArgs => {
let data_path = std::path::PathBuf::from(args);
let data = std::fs::read(&data_path)
.wrap_err_with(|| format!("Access to data file <{:?}> not found!", &data_path))?;
Ok(data)
}
}
}
| 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/contract/download_abi/mod.rs | src/commands/contract/download_abi/mod.rs | use std::io::Write;
use color_eyre::eyre::Context;
use inquire::CustomType;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = ContractContext)]
pub struct Contract {
#[interactive_clap(skip_default_input_arg)]
/// What is the contract account ID?
account_id: crate::types::account_id::AccountId,
#[interactive_clap(named_arg)]
/// Enter the file path where to save the contract ABI:
save_to_file: DownloadContractAbi,
}
#[derive(Debug, Clone)]
pub struct ContractContext {
global_context: crate::GlobalContext,
account_id: near_primitives::types::AccountId,
}
impl ContractContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<Contract as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context,
account_id: scope.account_id.clone().into(),
})
}
}
impl Contract {
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 is the contract account ID?",
)
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = ContractContext)]
#[interactive_clap(output_context = DownloadContractContext)]
pub struct DownloadContractAbi {
#[interactive_clap(skip_default_input_arg)]
/// Enter the file path where to save the contract ABI:
file_path: crate::types::path_buf::PathBuf,
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_view_at_block::NetworkViewAtBlockArgs,
}
#[derive(Clone)]
pub struct DownloadContractContext(crate::network_view_at_block::ArgsForViewContext);
impl DownloadContractContext {
pub fn from_previous_context(
previous_context: ContractContext,
scope: &<DownloadContractAbi 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 = previous_context.account_id.clone();
let file_path: std::path::PathBuf = scope.file_path.clone().into();
move |network_config, block_reference| {
download_contract_abi(&account_id, &file_path, network_config, block_reference, previous_context.global_context.verbosity)
}
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
config: previous_context.global_context.config,
on_after_getting_block_reference_callback,
interacting_with_account_ids: vec![previous_context.account_id],
}))
}
}
impl From<DownloadContractContext> for crate::network_view_at_block::ArgsForViewContext {
fn from(item: DownloadContractContext) -> Self {
item.0
}
}
impl DownloadContractAbi {
fn input_file_path(
context: &ContractContext,
) -> color_eyre::eyre::Result<Option<crate::types::path_buf::PathBuf>> {
Ok(Some(
CustomType::new("Enter the file path where the contract ABI should be saved to:")
.with_starting_input(&format!(
"{}.abi.json",
context.account_id.as_str().replace('.', "_")
))
.prompt()?,
))
}
}
#[tracing::instrument(name = "Download the ABI for the contract ...", skip_all)]
fn download_contract_abi(
account_id: &near_primitives::types::AccountId,
file_path: &std::path::PathBuf,
network_config: &crate::config::NetworkConfig,
block_reference: &near_primitives::types::BlockReference,
verbosity: crate::Verbosity,
) -> crate::CliResult {
tracing::info!(target: "near_teach_me", "Download the ABI for the contract ...");
let abi_root = tokio::runtime::Runtime::new()
.unwrap()
.block_on(super::get_contract_abi(
&network_config.json_rpc_client(),
block_reference,
account_id,
))?;
std::fs::File::create(file_path)
.wrap_err_with(|| format!("Failed to create file: {file_path:?}"))?
.write(&serde_json::to_vec_pretty(&abi_root)?)
.wrap_err_with(|| format!("Failed to write to file: {file_path:?}"))?;
if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = verbosity {
tracing_indicatif::suspend_tracing_indicatif(|| {
eprintln!("The file {file_path:?} was downloaded successfully");
})
}
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/contract/view_storage/mod.rs | src/commands/contract/view_storage/mod.rs | mod keys_to_view;
mod output_format;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = ViewStorageContext)]
pub struct ViewStorage {
#[interactive_clap(skip_default_input_arg)]
/// What is the contract account ID?
contract_account_id: crate::types::account_id::AccountId,
#[interactive_clap(subcommand)]
keys_to_view: self::keys_to_view::KeysToView,
}
#[derive(Debug, Clone)]
pub struct ViewStorageContext {
global_context: crate::GlobalContext,
contract_account_id: near_primitives::types::AccountId,
}
impl ViewStorageContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<ViewStorage as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context,
contract_account_id: scope.contract_account_id.clone().into(),
})
}
}
impl ViewStorage {
pub fn input_contract_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 contract 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/contract/view_storage/output_format/mod.rs | src/commands/contract/view_storage/output_format/mod.rs | use color_eyre::eyre::Context;
use strum::{EnumDiscriminants, EnumIter, EnumMessage};
use crate::common::JsonRpcClientExt;
mod as_json;
mod as_text;
#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = super::keys_to_view::KeysContext)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
/// Choose a format to view contract storage state:
pub enum OutputFormat {
#[strum_discriminants(strum(
message = "as-json - View contract storage state in JSON format"
))]
/// View contract storage state in JSON format
AsJson(self::as_json::AsJson),
#[strum_discriminants(strum(
message = "as-text - View contract storage state in the text"
))]
/// View contract storage state in the text
AsText(self::as_text::AsText),
}
#[tracing::instrument(name = "Obtaining the state of the contract ...", skip_all)]
pub fn get_contract_state(
contract_account_id: &near_primitives::types::AccountId,
prefix: near_primitives::types::StoreKey,
network_config: &crate::config::NetworkConfig,
block_reference: near_primitives::types::BlockReference,
) -> color_eyre::eyre::Result<near_jsonrpc_client::methods::query::RpcQueryResponse> {
tracing::info!(target: "near_teach_me", "Obtaining the state of the contract ...");
network_config
.json_rpc_client()
.blocking_call(near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference,
request: near_primitives::views::QueryRequest::ViewState {
account_id: contract_account_id.clone(),
prefix,
include_proof: false,
},
})
.wrap_err_with(|| {
format!(
"Failed to fetch query ViewState for <{contract_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/contract/view_storage/output_format/as_json.rs | src/commands/contract/view_storage/output_format/as_json.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::super::keys_to_view::KeysContext)]
#[interactive_clap(output_context = AsJsonContext)]
pub struct AsJson {
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_view_at_block::NetworkViewAtBlockArgs,
}
#[derive(Clone)]
pub struct AsJsonContext(crate::network_view_at_block::ArgsForViewContext);
impl AsJsonContext {
pub fn from_previous_context(
previous_context: super::super::keys_to_view::KeysContext,
_scope: &<AsJson 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 contract_account_id = previous_context.contract_account_id.clone();
let prefix = previous_context.prefix;
move |network_config, block_reference| {
let query_view_method_response =
super::get_contract_state(&contract_account_id, prefix.clone(), network_config, block_reference.clone())?;
if let near_jsonrpc_primitives::types::query::QueryResponseKind::ViewState(result) =
query_view_method_response.kind
{
println!("Contract state (values):\n{}\n", serde_json::to_string_pretty(&result.values)?);
println!("Contract state (proof):\n{:#?}\n", result.proof);
} else {
return Err(color_eyre::Report::msg("Error call result".to_string()));
};
Ok(())
}
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
config: previous_context.global_context.config,
interacting_with_account_ids: vec![previous_context.contract_account_id],
on_after_getting_block_reference_callback,
}))
}
}
impl From<AsJsonContext> for crate::network_view_at_block::ArgsForViewContext {
fn from(item: AsJsonContext) -> 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/contract/view_storage/output_format/as_text.rs | src/commands/contract/view_storage/output_format/as_text.rs | use color_eyre::{eyre::Context, owo_colors::OwoColorize};
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::super::keys_to_view::KeysContext)]
#[interactive_clap(output_context = AsTextContext)]
pub struct AsText {
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_view_at_block::NetworkViewAtBlockArgs,
}
#[derive(Clone)]
pub struct AsTextContext(crate::network_view_at_block::ArgsForViewContext);
impl AsTextContext {
pub fn from_previous_context(
previous_context: super::super::keys_to_view::KeysContext,
_scope: &<AsText 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 contract_account_id = previous_context.contract_account_id.clone();
let prefix = previous_context.prefix;
move |network_config, block_reference| {
let query_view_method_response =
super::get_contract_state(&contract_account_id, prefix.clone(), network_config, block_reference.clone())?;
if let near_jsonrpc_primitives::types::query::QueryResponseKind::ViewState(result) =
query_view_method_response.kind
{
let mut info_str = String::new();
for value in &result.values {
info_str.push_str(&format!("\n\tkey: {}", key_value_to_string(&value.key)?.green()));
info_str.push_str(&format!("\n\tvalue: {}", key_value_to_string(&value.value)?.yellow()));
info_str.push_str("\n\t--------------------------------");
}
println!("Contract state (values):{info_str}\n");
println!("Contract state (proof):\n{:#?}\n", result.proof);
} else {
return Err(color_eyre::Report::msg("Error call result".to_string()));
};
Ok(())
}
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
config: previous_context.global_context.config,
interacting_with_account_ids: vec![previous_context.contract_account_id],
on_after_getting_block_reference_callback,
}))
}
}
impl From<AsTextContext> for crate::network_view_at_block::ArgsForViewContext {
fn from(item: AsTextContext) -> Self {
item.0
}
}
fn key_value_to_string(slice: &[u8]) -> color_eyre::eyre::Result<String> {
String::from_utf8(
slice
.iter()
.flat_map(|b| std::ascii::escape_default(*b))
.collect::<Vec<u8>>(),
)
.wrap_err("Wrong format. utf-8 is expected.")
}
| 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/contract/view_storage/keys_to_view/keys_start_with_string.rs | src/commands/contract/view_storage/keys_to_view/keys_start_with_string.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::super::ViewStorageContext)]
#[interactive_clap(output_context = KeysStartWithStringContext)]
pub struct KeysStartWithString {
/// Enter the string that the keys begin with (for example, "S"):
keys_begin_with: String,
#[interactive_clap(subcommand)]
output_format: super::super::output_format::OutputFormat,
}
#[derive(Debug, Clone)]
pub struct KeysStartWithStringContext(super::KeysContext);
impl KeysStartWithStringContext {
pub fn from_previous_context(
previous_context: super::super::ViewStorageContext,
scope: &<KeysStartWithString as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self(super::KeysContext {
global_context: previous_context.global_context,
contract_account_id: previous_context.contract_account_id,
prefix: near_primitives::types::StoreKey::from(
scope.keys_begin_with.clone().into_bytes(),
),
}))
}
}
impl From<KeysStartWithStringContext> for super::KeysContext {
fn from(item: KeysStartWithStringContext) -> 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/contract/view_storage/keys_to_view/keys_start_with_bytes_as_base64.rs | src/commands/contract/view_storage/keys_to_view/keys_start_with_bytes_as_base64.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::super::ViewStorageContext)]
#[interactive_clap(output_context = KeysStartWithBytesAsBase64Context)]
pub struct KeysStartWithBytesAsBase64 {
/// Enter the string that the keys begin with Base64 bytes (for example, "Uw=="):
keys_begin_with: crate::types::base64_bytes::Base64Bytes,
#[interactive_clap(subcommand)]
output_format: super::super::output_format::OutputFormat,
}
#[derive(Debug, Clone)]
pub struct KeysStartWithBytesAsBase64Context(super::KeysContext);
impl KeysStartWithBytesAsBase64Context {
pub fn from_previous_context(
previous_context: super::super::ViewStorageContext,
scope: &<KeysStartWithBytesAsBase64 as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self(super::KeysContext {
global_context: previous_context.global_context,
contract_account_id: previous_context.contract_account_id,
prefix: near_primitives::types::StoreKey::from(
scope.keys_begin_with.clone().into_bytes(),
),
}))
}
}
impl From<KeysStartWithBytesAsBase64Context> for super::KeysContext {
fn from(item: KeysStartWithBytesAsBase64Context) -> 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/contract/view_storage/keys_to_view/mod.rs | src/commands/contract/view_storage/keys_to_view/mod.rs | use strum::{EnumDiscriminants, EnumIter, EnumMessage};
mod all_keys;
mod keys_start_with_bytes_as_base64;
mod keys_start_with_string;
#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = super::ViewStorageContext)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
/// Select keys to view contract storage state:
pub enum KeysToView {
#[strum_discriminants(strum(
message = "all - View contract storage state for all keys"
))]
/// View contract storage state for all keys
All(self::all_keys::AllKeys),
#[strum_discriminants(strum(
message = "keys-start-with-string - View contract storage state for keys that start with a string (for example, \"S\")"
))]
/// View contract storage state for keys that start with a string (for example, "S")
KeysStartWithString(self::keys_start_with_string::KeysStartWithString),
#[strum_discriminants(strum(
message = "keys-start-with-bytes-as-base64 - View contract storage state for keys that start with Base64 bytes (for example, \"Uw==\")"
))]
/// View contract storage state for keys that start with Base64 bytes (for example, "Uw==")
KeysStartWithBytesAsBase64(self::keys_start_with_bytes_as_base64::KeysStartWithBytesAsBase64),
}
#[derive(Debug, Clone)]
pub struct KeysContext {
pub global_context: crate::GlobalContext,
pub contract_account_id: near_primitives::types::AccountId,
pub prefix: near_primitives::types::StoreKey,
}
| 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/contract/view_storage/keys_to_view/all_keys.rs | src/commands/contract/view_storage/keys_to_view/all_keys.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::super::ViewStorageContext)]
#[interactive_clap(output_context = AllKeysContext)]
pub struct AllKeys {
#[interactive_clap(subcommand)]
output_format: super::super::output_format::OutputFormat,
}
#[derive(Debug, Clone)]
pub struct AllKeysContext(super::KeysContext);
impl AllKeysContext {
pub fn from_previous_context(
previous_context: super::super::ViewStorageContext,
_scope: &<AllKeys as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self(super::KeysContext {
global_context: previous_context.global_context,
contract_account_id: previous_context.contract_account_id,
prefix: near_primitives::types::StoreKey::from(Vec::new()),
}))
}
}
impl From<AllKeysContext> for super::KeysContext {
fn from(item: AllKeysContext) -> 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/utils_command/mod.rs | src/utils_command/mod.rs | pub mod generate_keypair_subcommand;
| 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/utils_command/generate_keypair_subcommand/mod.rs | src/utils_command/generate_keypair_subcommand/mod.rs | use std::str::FromStr;
/// Generate a key pair of private and public keys (use it anywhere you need
/// Ed25519 keys)
#[derive(Debug, Clone, clap::Parser)]
pub struct CliGenerateKeypair {
#[clap(long)]
pub master_seed_phrase: Option<String>,
#[clap(long, default_value = "12")]
pub new_master_seed_phrase_words_count: usize,
#[clap(long, default_value = "m/44'/397'/0'")]
pub seed_phrase_hd_path: crate::types::slip10::BIP32Path,
#[clap(long, default_value = "plaintext")]
pub format: crate::common::OutputFormat,
}
impl Default for CliGenerateKeypair {
fn default() -> Self {
Self {
master_seed_phrase: None,
new_master_seed_phrase_words_count: 12,
seed_phrase_hd_path: crate::types::slip10::BIP32Path::from_str("m/44'/397'/0'")
.unwrap(),
format: crate::common::OutputFormat::Json,
}
}
}
| 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/types/public_key.rs | src/types/public_key.rs | #[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Eq)]
pub struct PublicKey(pub near_crypto::PublicKey);
impl std::fmt::Display for PublicKey {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::str::FromStr for PublicKey {
type Err = near_crypto::ParseKeyError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let public_key = near_crypto::PublicKey::from_str(s)?;
Ok(Self(public_key))
}
}
impl From<PublicKey> for near_crypto::PublicKey {
fn from(item: PublicKey) -> Self {
item.0
}
}
impl From<near_crypto::PublicKey> for PublicKey {
fn from(item: near_crypto::PublicKey) -> Self {
Self(item)
}
}
impl interactive_clap::ToCli for PublicKey {
type CliVariant = PublicKey;
}
| 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/types/signed_delegate_action.rs | src/types/signed_delegate_action.rs | use near_primitives::{borsh, borsh::BorshDeserialize};
#[derive(Debug, Clone)]
pub struct SignedDelegateActionAsBase64 {
inner: near_primitives::action::delegate::SignedDelegateAction,
}
impl serde::Serialize for SignedDelegateActionAsBase64 {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let signed_delegate_action_borsh = borsh::to_vec(&self.inner).map_err(|err| {
serde::ser::Error::custom(format!(
"The value could not be borsh encoded due to: {err}"
))
})?;
let signed_delegate_action_as_base64 =
near_primitives::serialize::to_base64(&signed_delegate_action_borsh);
serializer.serialize_str(&signed_delegate_action_as_base64)
}
}
impl<'de> serde::Deserialize<'de> for SignedDelegateActionAsBase64 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let signed_delegate_action_as_base64 =
<String as serde::Deserialize>::deserialize(deserializer)?;
let signed_delegate_action_borsh = near_primitives::serialize::from_base64(
&signed_delegate_action_as_base64,
)
.map_err(|err| {
serde::de::Error::custom(format!(
"The value could not decoded from base64 due to: {err}"
))
})?;
let signed_delegate_action = borsh::from_slice::<
near_primitives::action::delegate::SignedDelegateAction,
>(&signed_delegate_action_borsh)
.map_err(|err| {
serde::de::Error::custom(format!(
"The value could not decoded from borsh due to: {err}"
))
})?;
Ok(Self {
inner: signed_delegate_action,
})
}
}
impl std::str::FromStr for SignedDelegateActionAsBase64 {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self {
inner: near_primitives::action::delegate::SignedDelegateAction::try_from_slice(
&near_primitives::serialize::from_base64(s)
.map_err(|err| format!("parsing of signed delegate action failed due to base64 sequence being invalid: {err}"))?,
)
.map_err(|err| format!("delegate action could not be deserialized from borsh: {err}"))?,
})
}
}
impl std::fmt::Display for SignedDelegateActionAsBase64 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let base64_signed_delegate_action = near_primitives::serialize::to_base64(
&borsh::to_vec(&self.inner)
.expect("Signed Delegate Action serialization to borsh is not expected to fail"),
);
write!(f, "{base64_signed_delegate_action}")
}
}
impl interactive_clap::ToCli for SignedDelegateActionAsBase64 {
type CliVariant = SignedDelegateActionAsBase64;
}
impl From<near_primitives::action::delegate::SignedDelegateAction>
for SignedDelegateActionAsBase64
{
fn from(value: near_primitives::action::delegate::SignedDelegateAction) -> Self {
Self { inner: value }
}
}
impl From<SignedDelegateActionAsBase64>
for near_primitives::action::delegate::SignedDelegateAction
{
fn from(signed_delegate_action: SignedDelegateActionAsBase64) -> Self {
signed_delegate_action.inner
}
}
| 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/types/signature.rs | src/types/signature.rs | #[derive(Debug, Clone)]
pub struct Signature(pub near_crypto::Signature);
impl std::fmt::Display for Signature {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::str::FromStr for Signature {
type Err = near_crypto::ParseSignatureError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let signature = near_crypto::Signature::from_str(s)?;
Ok(Self(signature))
}
}
impl From<Signature> for near_crypto::Signature {
fn from(item: Signature) -> 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/types/near_allowance.rs | src/types/near_allowance.rs | const UNLIMITED: &str = "unlimited";
#[derive(
Debug,
Clone,
Copy,
serde::Serialize,
serde::Deserialize,
derive_more::AsRef,
derive_more::From,
derive_more::Into,
)]
#[as_ref(forward)]
pub struct NearAllowance(Option<crate::types::near_token::NearToken>);
impl std::fmt::Display for NearAllowance {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(amount) = self.0 {
amount.fmt(f)
} else {
write!(f, "{UNLIMITED}")
}
}
}
impl std::str::FromStr for NearAllowance {
type Err = near_token::NearTokenError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s == UNLIMITED {
return Ok(Self(None));
}
Ok(Self(Some(crate::types::near_token::NearToken::from_str(
s,
)?)))
}
}
impl NearAllowance {
pub fn unlimited() -> Self {
Self(None)
}
pub fn from_near(value: crate::types::near_token::NearToken) -> Self {
Self(Some(value))
}
pub fn optional_near_token(&self) -> Option<crate::types::near_token::NearToken> {
self.0
}
}
impl interactive_clap::ToCli for NearAllowance {
type CliVariant = NearAllowance;
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
#[test]
fn near_allowance_to_string_0_near() {
assert_eq!(
NearAllowance(Some(near_token::NearToken::from_near(0).into())).to_string(),
"0 NEAR".to_string()
)
}
#[test]
fn near_allowance_to_string_0_millinear() {
assert_eq!(
NearAllowance(Some(near_token::NearToken::from_millinear(0).into())).to_string(),
"0 NEAR".to_string()
)
}
#[test]
fn near_allowance_to_string_none() {
assert_eq!(NearAllowance(None).to_string(), "unlimited".to_string())
}
#[test]
fn near_allowance_to_string_0dot02_near() {
assert_eq!(
NearAllowance(Some(
near_token::NearToken::from_yoctonear(20_000_000_000_000_000_000_000).into()
))
.to_string(),
"0.02 NEAR".to_string()
)
}
#[test]
fn near_allowance_from_str_unlimited() {
assert_eq!(
NearAllowance::from_str("unlimited")
.unwrap()
.optional_near_token(),
None
);
assert_eq!(NearAllowance::unlimited().optional_near_token(), None);
}
#[test]
fn near_allowance_from_near() {
let amount = crate::types::near_token::NearToken::from_str("0.02 NEAR").unwrap();
assert_eq!(NearAllowance::from_near(amount).0, Some(amount));
}
}
| 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/types/ft_properties.rs | src/types/ft_properties.rs | use color_eyre::eyre::{Context, ContextCompat};
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use crate::common::CallResultExt;
use crate::common::JsonRpcClientExt;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
pub enum FungibleTokenTransferAmount {
/// Transfer of the specified amount of fungible tokens (wNearAmount (10 wNEAR))
ExactAmount(FungibleToken),
/// Transfer the entire amount of fungible tokens from your account ID
MaxAmount,
}
impl interactive_clap::ToCli for FungibleTokenTransferAmount {
type CliVariant = FungibleTokenTransferAmount;
}
impl FungibleTokenTransferAmount {
pub fn normalize(&self, ft_metadata: &FtMetadata) -> color_eyre::eyre::Result<Self> {
if let Self::ExactAmount(ft) = self {
Ok(Self::ExactAmount(ft.normalize(ft_metadata)?))
} else {
Ok(Self::MaxAmount)
}
}
}
impl std::fmt::Display for FungibleTokenTransferAmount {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ExactAmount(ft) => ft.fmt(f),
Self::MaxAmount => write!(f, "all"),
}
}
}
impl std::str::FromStr for FungibleTokenTransferAmount {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.to_lowercase() == "all" {
Ok(Self::MaxAmount)
} else {
Ok(Self::ExactAmount(FungibleToken::from_str(s)?))
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd)]
pub struct FungibleToken {
amount: u128,
decimals: u8,
symbol: String,
}
impl FungibleToken {
pub fn from_params_ft(amount: u128, decimals: u8, symbol: String) -> Self {
Self {
amount,
decimals,
symbol,
}
}
pub fn normalize(&self, ft_metadata: &FtMetadata) -> color_eyre::eyre::Result<Self> {
if ft_metadata.symbol.to_uppercase() != self.symbol.to_uppercase() {
color_eyre::eyre::bail!("Invalid currency symbol")
} else if let Some(decimals_diff) = ft_metadata.decimals.checked_sub(self.decimals) {
let amount = if decimals_diff == 0 {
self.amount
} else {
self.amount
.checked_mul(
10u128
.checked_pow(decimals_diff.into())
.wrap_err("Overflow in decimal normalization")?,
)
.wrap_err("Overflow in decimal normalization")?
};
Ok(Self {
symbol: ft_metadata.symbol.clone(),
decimals: ft_metadata.decimals,
amount,
})
} else {
color_eyre::eyre::bail!(
"Invalid decimal places. Your FT amount exceeds {} decimal places.",
ft_metadata.decimals
)
}
}
pub fn amount(&self) -> u128 {
self.amount
}
pub fn decimals(&self) -> u8 {
self.decimals
}
pub fn symbol(&self) -> &str {
&self.symbol
}
}
impl std::fmt::Display for FungibleToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let one_ft: u128 = 10u128
.checked_pow(self.decimals.into())
.wrap_err("Overflow in FungibleToken normalization")
.unwrap();
if self.amount == 0 {
write!(f, "0 {}", self.symbol)
} else if self.amount.is_multiple_of(one_ft) {
write!(f, "{} {}", self.amount / one_ft, self.symbol)
} else {
write!(
f,
"{}.{} {}",
self.amount / one_ft,
format!(
"{:0>decimals$}",
(self.amount % one_ft),
decimals = self.decimals.into()
)
.trim_end_matches('0'),
self.symbol
)
}
}
}
impl std::str::FromStr for FungibleToken {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let num = s.trim().trim_end_matches(char::is_alphabetic).trim();
let currency = s.trim().trim_start_matches(num).trim().to_string();
let res_split: Vec<&str> = num.split('.').collect();
match res_split.len() {
2 => {
let num_int_part = res_split[0]
.parse::<u128>()
.map_err(|err| format!("FungibleToken: {err}"))?;
let len_fract: u8 = res_split[1]
.trim_end_matches('0')
.len()
.try_into()
.map_err(|_| "Error converting len_fract to u8")?;
let num_fract_part = res_split[1]
.trim_end_matches('0')
.parse::<u128>()
.map_err(|err| format!("FungibleToken: {err}"))?;
let amount = num_int_part
.checked_mul(
10u128
.checked_pow(len_fract.into())
.ok_or("FT Balance: overflow happens")?,
)
.ok_or("FungibleToken: overflow happens")?
.checked_add(num_fract_part)
.ok_or("FungibleToken: overflow happens")?;
Ok(Self {
amount,
decimals: len_fract,
symbol: currency,
})
}
1 => {
if res_split[0].starts_with('0') && res_split[0] != "0" {
return Err("FungibleToken: incorrect number entered".to_string());
};
let amount = res_split[0]
.parse::<u128>()
.map_err(|err| format!("FungibleToken: {err}"))?;
Ok(Self {
amount,
decimals: 0,
symbol: currency,
})
}
_ => Err("FungibleToken: incorrect number entered".to_string()),
}
}
}
impl interactive_clap::ToCli for FungibleToken {
type CliVariant = FungibleToken;
}
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, serde::Deserialize)]
pub struct FtMetadata {
pub symbol: String,
pub decimals: u8,
}
#[tracing::instrument(name = "Getting FT metadata ...", skip_all, parent = None)]
pub fn params_ft_metadata(
ft_contract_account_id: near_primitives::types::AccountId,
network_config: &crate::config::NetworkConfig,
block_reference: near_primitives::types::BlockReference,
) -> color_eyre::eyre::Result<FtMetadata> {
tracing::info!(target: "near_teach_me", "Getting FT metadata ...");
let ft_metadata: FtMetadata = network_config
.json_rpc_client()
.blocking_call_view_function(
&ft_contract_account_id,
"ft_metadata",
vec![],
block_reference,
)
.wrap_err_with(||{
format!("Failed to fetch query for view method: 'ft_metadata' (contract <{}> on network <{}>)",
ft_contract_account_id,
network_config.network_name
)
})?
.parse_result_from_json()?;
Ok(ft_metadata)
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct FtTransfer {
pub receiver_id: near_primitives::types::AccountId,
#[serde(deserialize_with = "parse_u128_string", serialize_with = "to_string")]
pub amount: u128,
#[serde(skip_serializing_if = "Option::is_none")]
pub memo: Option<String>,
}
fn parse_u128_string<'de, D>(deserializer: D) -> color_eyre::eyre::Result<u128, D::Error>
where
D: Deserializer<'de>,
{
String::deserialize(deserializer)?
.parse::<u128>()
.map_err(serde::de::Error::custom)
}
fn to_string<S, T: ToString>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let s = value.to_string();
String::serialize(&s, serializer)
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
#[test]
fn ft_token_to_string_0_wnear() {
let ft_token = FungibleToken::from_str("0 wNEAR").unwrap();
assert_eq!(ft_token.to_string(), "0 wNEAR".to_string());
assert_eq!(ft_token.symbol, "wNEAR".to_string());
assert_eq!(ft_token.decimals, 0)
}
#[test]
fn ft_token_to_string_10_wnear() {
let ft_token = FungibleToken::from_str("10 wNEAR").unwrap();
assert_eq!(ft_token.to_string(), "10 wNEAR".to_string());
assert_eq!(ft_token.symbol, "wNEAR".to_string());
assert_eq!(ft_token.decimals, 0)
}
#[test]
fn ft_token_to_string_0dot0200_wnear() {
let ft_token = FungibleToken::from_str("0.0200 wNEAR").unwrap();
assert_eq!(ft_token.to_string(), "0.02 wNEAR".to_string());
assert_eq!(ft_token.symbol, "wNEAR".to_string());
assert_eq!(ft_token.decimals, 2)
}
#[test]
fn ft_token_to_string_0dot123456_usdc() {
let ft_token = FungibleToken::from_str("0.123456 USDC").unwrap();
assert_eq!(ft_token.to_string(), "0.123456 USDC".to_string());
assert_eq!(ft_token.symbol, "USDC".to_string());
}
#[test]
fn ft_transfer_amount_to_string_0dot123456_usdc() {
let ft_transfer_amount = FungibleTokenTransferAmount::from_str("0.123456 USDC").unwrap();
assert_eq!(ft_transfer_amount.to_string(), "0.123456 USDC".to_string());
assert_eq!(
ft_transfer_amount,
FungibleTokenTransferAmount::ExactAmount(FungibleToken::from_params_ft(
123456,
6,
"USDC".to_string()
))
);
}
#[test]
fn ft_transfer_amount_to_string_all() {
let ft_transfer_amount = FungibleTokenTransferAmount::from_str("all").unwrap();
assert_eq!(ft_transfer_amount.to_string(), "all".to_string());
assert_eq!(ft_transfer_amount, FungibleTokenTransferAmount::MaxAmount);
}
#[test]
fn ft_transfer_with_memo_to_vec_u8() {
let ft_transfer = serde_json::to_vec(&crate::types::ft_properties::FtTransfer {
receiver_id: "fro_volod.testnet".parse().unwrap(),
amount: FungibleToken::from_str("0.123456 USDC").unwrap().amount(),
memo: Some("Memo".to_string()),
})
.unwrap();
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&ft_transfer)
.unwrap()
.to_string(),
"{\"amount\":\"123456\",\"memo\":\"Memo\",\"receiver_id\":\"fro_volod.testnet\"}"
);
}
#[test]
fn ft_transfer_without_memo_to_vec_u8() {
let ft_transfer = serde_json::to_vec(&crate::types::ft_properties::FtTransfer {
receiver_id: "fro_volod.testnet".parse().unwrap(),
amount: FungibleToken::from_str("0.123456 USDC").unwrap().amount(),
memo: None,
})
.unwrap();
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&ft_transfer)
.unwrap()
.to_string(),
"{\"amount\":\"123456\",\"receiver_id\":\"fro_volod.testnet\"}"
);
}
}
| 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/types/json.rs | src/types/json.rs | use color_eyre::eyre::WrapErr;
use serde_json::Value;
#[derive(Debug, Clone, derive_more::FromStr)]
pub struct Json {
inner: Value,
}
impl From<Json> for Value {
fn from(item: Json) -> Self {
item.inner
}
}
impl std::fmt::Display for Json {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.inner.fmt(f)
}
}
impl interactive_clap::ToCli for Json {
type CliVariant = Json;
}
impl Json {
pub fn try_into_bytes(&self) -> color_eyre::Result<Vec<u8>> {
serde_json::to_vec(&self.inner).wrap_err("Data not in JSON format!")
}
}
| 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/types/url.rs | src/types/url.rs | #[derive(Debug, Clone)]
pub struct Url(pub url::Url);
impl From<Url> for url::Url {
fn from(url: Url) -> Self {
url.0
}
}
impl From<url::Url> for Url {
fn from(url: url::Url) -> Self {
Self(url)
}
}
impl std::fmt::Display for Url {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::str::FromStr for Url {
type Err = url::ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let url = url::Url::parse(s)?;
Ok(Self(url))
}
}
impl interactive_clap::ToCli for Url {
type CliVariant = Url;
}
| 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/types/contract_properties.rs | src/types/contract_properties.rs | use near_verify_rs::types::{contract_source_metadata::Standard, sha256_checksum::SHA256Checksum};
pub struct ContractProperties {
pub code: Vec<u8>,
pub hash: SHA256Checksum,
pub version: Option<String>,
pub standards: Vec<Standard>,
pub link: Option<String>,
pub source: String,
pub build_environment: String,
pub build_command: Vec<String>,
}
impl std::fmt::Display for ContractProperties {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Contract code hash: {}\nContract version:\t{}\nStandards used by the contract:\t[{}]\nView the contract's source code on:\t{}\nBuild Environment:\t{}\nBuild Command:\t{}",
self.hash.to_base58_string(),
self.version.clone().unwrap_or("N/A".to_string()),
self.standards.iter().map(|standard| format!("{}:{}", standard.standard, standard.version)).collect::<Vec<String>>().join(", "),
if let Some(link) = &self.link {
link
} else {
&self.source
},
self.build_environment,
shell_words::join(self.build_command.clone()),
)
}
}
| 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/types/signed_transaction.rs | src/types/signed_transaction.rs | use near_primitives::{borsh, borsh::BorshDeserialize};
#[derive(Debug, Clone)]
pub struct SignedTransactionAsBase64 {
pub inner: near_primitives::transaction::SignedTransaction,
}
impl From<SignedTransactionAsBase64> for near_primitives::transaction::SignedTransaction {
fn from(transaction: SignedTransactionAsBase64) -> Self {
transaction.inner
}
}
impl std::str::FromStr for SignedTransactionAsBase64 {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self {
inner: near_primitives::transaction::SignedTransaction::try_from_slice(
&near_primitives::serialize::from_base64(s)
.map_err(|err| format!("base64 transaction sequence is invalid: {err}"))?,
)
.map_err(|err| format!("transaction could not be parsed: {err}"))?,
})
}
}
impl std::fmt::Display for SignedTransactionAsBase64 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let base64_signed_transaction = near_primitives::serialize::to_base64(
&borsh::to_vec(&self.inner)
.expect("Transaction is not expected to fail on serialization"),
);
write!(f, "{base64_signed_transaction}")
}
}
impl interactive_clap::ToCli for SignedTransactionAsBase64 {
type CliVariant = SignedTransactionAsBase64;
}
impl From<near_primitives::transaction::SignedTransaction> for SignedTransactionAsBase64 {
fn from(value: near_primitives::transaction::SignedTransaction) -> Self {
Self { inner: 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/types/api_key.rs | src/types/api_key.rs | #[derive(Eq, Hash, Clone, Debug, PartialEq)]
pub struct ApiKey(pub near_jsonrpc_client::auth::ApiKey);
impl From<ApiKey> for near_jsonrpc_client::auth::ApiKey {
fn from(api_key: ApiKey) -> Self {
api_key.0
}
}
impl std::fmt::Display for ApiKey {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0.to_str().map_err(|_| std::fmt::Error)?)
}
}
impl std::str::FromStr for ApiKey {
type Err = color_eyre::eyre::Report;
fn from_str(api_key: &str) -> Result<Self, Self::Err> {
Ok(Self(near_jsonrpc_client::auth::ApiKey::new(api_key)?))
}
}
impl serde::ser::Serialize for ApiKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
serializer.serialize_str(self.0.to_str().map_err(serde::ser::Error::custom)?)
}
}
impl<'de> serde::de::Deserialize<'de> for ApiKey {
fn deserialize<D>(deserializer: D) -> Result<ApiKey, D::Error>
where
D: serde::de::Deserializer<'de>,
{
String::deserialize(deserializer)?
.parse()
.map_err(|err: color_eyre::eyre::Report| serde::de::Error::custom(err.to_string()))
}
}
impl interactive_clap::ToCli for ApiKey {
type CliVariant = ApiKey;
}
| 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/types/vec_string.rs | src/types/vec_string.rs | #[derive(Debug, Default, Clone)]
pub struct VecString(pub Vec<String>);
impl std::fmt::Display for VecString {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0.join(","))
}
}
impl std::str::FromStr for VecString {
type Err = color_eyre::eyre::ErrReport;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.is_empty() {
return Ok(Self(vec![]));
}
let vec_str: Vec<String> = s.split(',').map(|str| str.trim().to_string()).collect();
Ok(Self(vec_str))
}
}
impl From<VecString> for Vec<String> {
fn from(item: VecString) -> Self {
item.0
}
}
impl From<Vec<String>> for VecString {
fn from(item: Vec<String>) -> Self {
Self(item)
}
}
impl interactive_clap::ToCli for VecString {
type CliVariant = VecString;
}
| 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/types/path_buf.rs | src/types/path_buf.rs | use color_eyre::eyre::Context;
#[derive(
Debug,
Default,
Clone,
derive_more::AsRef,
derive_more::From,
derive_more::Into,
derive_more::FromStr,
)]
#[as_ref(forward)]
pub struct PathBuf(pub std::path::PathBuf);
impl std::fmt::Display for PathBuf {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0.display())
}
}
impl interactive_clap::ToCli for PathBuf {
type CliVariant = PathBuf;
}
impl PathBuf {
pub fn read_bytes(&self) -> color_eyre::Result<Vec<u8>> {
std::fs::read(self.0.clone())
.wrap_err_with(|| format!("Error reading data from file: {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/types/secret_key.rs | src/types/secret_key.rs | #[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecretKey(pub near_crypto::SecretKey);
impl std::fmt::Display for SecretKey {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::str::FromStr for SecretKey {
type Err = near_crypto::ParseKeyError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let private_key = near_crypto::SecretKey::from_str(s)?;
Ok(Self(private_key))
}
}
impl From<SecretKey> for near_crypto::SecretKey {
fn from(item: SecretKey) -> Self {
item.0
}
}
impl interactive_clap::ToCli for SecretKey {
type CliVariant = 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/types/near_token.rs | src/types/near_token.rs | const ONE_NEAR: u128 = 10u128.pow(24);
#[derive(
Debug,
Default,
Clone,
Copy,
Eq,
PartialEq,
Ord,
PartialOrd,
serde::Serialize,
serde::Deserialize,
derive_more::AsRef,
derive_more::From,
derive_more::Into,
derive_more::FromStr,
)]
#[as_ref(forward)]
pub struct NearToken(pub near_token::NearToken);
impl std::fmt::Display for NearToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.as_yoctonear() == 0 {
write!(f, "0 NEAR")
} else if self.as_yoctonear() <= 1_000 {
write!(f, "{} yoctoNEAR", self.as_yoctonear())
} else if self.as_yoctonear().is_multiple_of(ONE_NEAR) {
write!(f, "{} NEAR", self.as_yoctonear() / ONE_NEAR,)
} else {
write!(
f,
"{}.{} NEAR",
self.as_yoctonear() / ONE_NEAR,
format!("{:0>24}", (self.as_yoctonear() % ONE_NEAR)).trim_end_matches('0')
)
}
}
}
impl NearToken {
pub fn as_yoctonear(&self) -> u128 {
self.0.as_yoctonear()
}
pub fn from_yoctonear(inner: u128) -> Self {
Self(near_token::NearToken::from_yoctonear(inner))
}
pub const fn is_zero(&self) -> bool {
self.0.is_zero()
}
}
impl interactive_clap::ToCli for NearToken {
type CliVariant = NearToken;
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
#[test]
fn near_token_to_string_0_near() {
assert_eq!(
NearToken(near_token::NearToken::from_near(0)).to_string(),
"0 NEAR".to_string()
)
}
#[test]
fn near_token_to_string_0_millinear() {
assert_eq!(
NearToken(near_token::NearToken::from_millinear(0)).to_string(),
"0 NEAR".to_string()
)
}
#[test]
fn near_token_to_string_0_yoctonear() {
assert_eq!(
NearToken(near_token::NearToken::from_yoctonear(0)).to_string(),
"0 NEAR".to_string()
)
}
#[test]
fn near_token_to_string_0dot02_near() {
assert_eq!(
NearToken(near_token::NearToken::from_yoctonear(
20_000_000_000_000_000_000_000
))
.to_string(),
"0.02 NEAR".to_string()
)
}
#[test]
fn near_token_to_string_0dot00001230045600789_near() {
assert_eq!(
NearToken(
near_token::NearToken::from_str("0.000012300456007890000000 Near")
.unwrap_or_default()
)
.to_string(),
"0.00001230045600789 NEAR".to_string()
)
}
#[test]
fn near_token_to_string_10_near() {
assert_eq!(
NearToken(near_token::NearToken::from_yoctonear(
10_000_000_000_000_000_000_000_000
))
.to_string(),
"10 NEAR".to_string()
)
}
#[test]
fn near_token_to_string_10dot02_000_01near() {
assert_eq!(
NearToken(near_token::NearToken::from_yoctonear(
10_020_000_000_000_000_000_000_001
))
.to_string(),
"10.020000000000000000000001 NEAR".to_string()
)
}
#[test]
fn near_token_to_string_1_yocto_near() {
assert_eq!(
NearToken(near_token::NearToken::from_yoctonear(1)).to_string(),
"1 yoctoNEAR".to_string()
)
}
#[test]
fn near_token_to_string_100_yocto_near() {
assert_eq!(
NearToken(near_token::NearToken::from_yoctonear(100)).to_string(),
"100 yoctoNEAR".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/types/mod.rs | src/types/mod.rs | pub mod account_id;
pub mod api_key;
pub mod base64_bytes;
#[cfg(feature = "verify_contract")]
pub mod contract_properties;
pub mod crypto_hash;
pub mod file_bytes;
pub mod ft_properties;
pub mod json;
pub mod near_allowance;
pub mod near_token;
pub mod nonce32_bytes;
pub mod partial_protocol_config;
pub mod path_buf;
pub mod public_key;
pub mod public_key_list;
pub mod secret_key;
pub mod signature;
pub mod signed_delegate_action;
pub mod signed_transaction;
pub mod slip10;
pub mod transaction;
pub mod url;
pub mod vec_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/types/base64_bytes.rs | src/types/base64_bytes.rs | #[derive(Debug, Clone)]
pub struct Base64Bytes {
inner: Vec<u8>,
}
impl interactive_clap::ToCli for Base64Bytes {
type CliVariant = Base64Bytes;
}
impl std::str::FromStr for Base64Bytes {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self {
inner: near_primitives::serialize::from_base64(s).map_err(|err| {
format!("parsing action {s} failed due to invalid base64 sequence: {err}")
})?,
})
}
}
impl std::fmt::Display for Base64Bytes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", near_primitives::serialize::to_base64(&self.inner))
}
}
impl Base64Bytes {
pub fn as_bytes(&self) -> &[u8] {
&self.inner
}
pub fn into_bytes(self) -> Vec<u8> {
self.inner
}
}
| 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/types/crypto_hash.rs | src/types/crypto_hash.rs | #[derive(Debug, Copy, Clone)]
pub struct CryptoHash(pub near_primitives::hash::CryptoHash);
impl From<CryptoHash> for near_primitives::hash::CryptoHash {
fn from(item: CryptoHash) -> Self {
item.0
}
}
impl std::fmt::Display for CryptoHash {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::str::FromStr for CryptoHash {
type Err = color_eyre::eyre::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let crypto_hash = near_primitives::hash::CryptoHash::from_str(s)
.map_err(color_eyre::eyre::Report::msg)?;
Ok(Self(crypto_hash))
}
}
impl interactive_clap::ToCli for CryptoHash {
type CliVariant = CryptoHash;
}
| 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/types/partial_protocol_config.rs | src/types/partial_protocol_config.rs | use near_jsonrpc_client::methods::EXPERIMENTAL_protocol_config::RpcProtocolConfigError;
#[derive(Debug, serde::Deserialize)]
pub struct PartialProtocolConfigView {
pub runtime_config: PartialRuntimeConfigView,
}
impl near_jsonrpc_client::methods::RpcHandlerResponse for PartialProtocolConfigView {}
#[derive(Debug, serde::Deserialize)]
pub struct PartialRuntimeConfigView {
/// Amount of yN per byte required to have on the account. See
/// <https://nomicon.io/Economics/Economic#state-stake> for details.
pub storage_amount_per_byte: near_token::NearToken,
}
pub async fn get_partial_protocol_config(
json_rpc_client: &near_jsonrpc_client::JsonRpcClient,
block_reference: &near_primitives::types::BlockReference,
) -> color_eyre::eyre::Result<PartialProtocolConfigView> {
let request = near_jsonrpc_client::methods::any::<
Result<PartialProtocolConfigView, RpcProtocolConfigError>,
>(
"EXPERIMENTAL_protocol_config",
serde_json::to_value(block_reference)?,
);
json_rpc_client
.call(request)
.await
.map_err(|_| color_eyre::eyre::eyre!("Failed to get protocol 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/types/file_bytes.rs | src/types/file_bytes.rs | use color_eyre::eyre::Context;
#[derive(Debug, Clone, derive_more::FromStr)]
pub struct FileBytes {
inner: std::path::PathBuf,
}
impl interactive_clap::ToCli for FileBytes {
type CliVariant = FileBytes;
}
impl std::fmt::Display for FileBytes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.inner.display())
}
}
impl FileBytes {
pub fn read_bytes(&self) -> color_eyre::Result<Vec<u8>> {
std::fs::read(&self.inner)
.wrap_err_with(|| format!("Error reading data from file: {}", self.inner.display()))
}
}
| 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/types/slip10.rs | src/types/slip10.rs | #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct BIP32Path(pub slipped10::BIP32Path);
impl std::fmt::Display for BIP32Path {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::str::FromStr for BIP32Path {
type Err = color_eyre::eyre::Report;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let bip32path = slipped10::BIP32Path::from_str(s).map_err(Self::Err::msg)?;
Ok(Self(bip32path))
}
}
impl From<BIP32Path> for slipped10::BIP32Path {
fn from(item: BIP32Path) -> Self {
item.0
}
}
impl From<slipped10::BIP32Path> for BIP32Path {
fn from(item: slipped10::BIP32Path) -> Self {
Self(item)
}
}
impl serde::ser::Serialize for BIP32Path {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
serializer.serialize_str(&self.0.to_string())
}
}
impl<'de> serde::de::Deserialize<'de> for BIP32Path {
fn deserialize<D>(deserializer: D) -> Result<BIP32Path, D::Error>
where
D: serde::de::Deserializer<'de>,
{
String::deserialize(deserializer)?
.parse()
.map_err(|err: color_eyre::eyre::Report| serde::de::Error::custom(err.to_string()))
}
}
impl interactive_clap::ToCli for crate::types::slip10::BIP32Path {
type CliVariant = crate::types::slip10::BIP32Path;
}
| 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/types/public_key_list.rs | src/types/public_key_list.rs | use interactive_clap::ToCli;
#[derive(Debug, Clone)]
pub struct PublicKeyList(Vec<near_crypto::PublicKey>);
impl std::fmt::Display for PublicKeyList {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let keys: Vec<String> = self.0.iter().map(|key| key.to_string()).collect();
write!(f, "{}", keys.join(","))
}
}
impl std::str::FromStr for PublicKeyList {
type Err = color_eyre::eyre::ErrReport;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let keys: Vec<near_crypto::PublicKey> = s
.split(',')
.map(|str| str.trim().parse())
.collect::<Result<Vec<near_crypto::PublicKey>, _>>()?;
Ok(Self(keys))
}
}
impl From<PublicKeyList> for Vec<near_crypto::PublicKey> {
fn from(item: PublicKeyList) -> Self {
item.0
}
}
impl From<Vec<near_crypto::PublicKey>> for PublicKeyList {
fn from(item: Vec<near_crypto::PublicKey>) -> Self {
Self(item)
}
}
impl ToCli for PublicKeyList {
type CliVariant = PublicKeyList;
}
| 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/types/account_id.rs | src/types/account_id.rs | use std::str::FromStr;
#[derive(Eq, Ord, Hash, Clone, Debug, PartialEq, PartialOrd)]
pub struct AccountId(pub near_primitives::types::AccountId);
impl From<AccountId> for near_primitives::types::AccountId {
fn from(account_id: AccountId) -> Self {
account_id.0
}
}
impl From<near_primitives::types::AccountId> for AccountId {
fn from(account_id: near_primitives::types::AccountId) -> Self {
Self(account_id)
}
}
impl std::fmt::Display for AccountId {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::str::FromStr for AccountId {
type Err = <near_primitives::types::AccountId as std::str::FromStr>::Err;
fn from_str(account_id: &str) -> Result<Self, Self::Err> {
let account_id = near_primitives::types::AccountId::from_str(account_id)?;
Ok(Self(account_id))
}
}
impl AsRef<str> for AccountId {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl AsRef<near_primitives::types::AccountId> for AccountId {
fn as_ref(&self) -> &near_primitives::types::AccountId {
&self.0
}
}
impl interactive_clap::ToCli for AccountId {
type CliVariant = AccountId;
}
impl AccountId {
pub fn get_parent_account_id_from_sub_account(self) -> Self {
let owner_account_id = self.to_string();
let owner_account_id = owner_account_id.split_once('.').map_or("default", |s| s.1);
Self::from_str(owner_account_id).unwrap()
}
}
| 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/types/nonce32_bytes.rs | src/types/nonce32_bytes.rs | #[derive(Debug, Clone, Default)]
pub struct Nonce32 {
inner: [u8; 32],
}
impl std::str::FromStr for Nonce32 {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let bytes = near_primitives::serialize::from_base64(s)
.map_err(|err| format!("Invalid base64: {err}"))?;
if bytes.len() != 32 {
return Err(format!(
"Invalid nonce length: expected 32 bytes, got {}",
bytes.len()
));
}
let mut nonce = [0u8; 32];
nonce.copy_from_slice(&bytes);
Ok(Self { inner: nonce })
}
}
impl std::fmt::Display for Nonce32 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", near_primitives::serialize::to_base64(&self.inner))
}
}
impl Nonce32 {
pub fn as_array(&self) -> [u8; 32] {
self.inner
}
}
impl interactive_clap::ToCli for Nonce32 {
type CliVariant = Nonce32;
}
| 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/types/transaction.rs | src/types/transaction.rs | use near_primitives::{borsh, borsh::BorshDeserialize};
#[derive(Debug, Clone)]
pub struct TransactionAsBase64 {
pub inner: near_primitives::transaction::TransactionV0,
}
impl From<TransactionAsBase64> for near_primitives::transaction::TransactionV0 {
fn from(transaction: TransactionAsBase64) -> Self {
transaction.inner
}
}
impl From<near_primitives::transaction::Transaction> for TransactionAsBase64 {
fn from(value: near_primitives::transaction::Transaction) -> Self {
Self {
inner: near_primitives::transaction::TransactionV0 {
public_key: value.public_key().clone(),
nonce: value.nonce(),
signer_id: value.signer_id().clone(),
receiver_id: value.receiver_id().clone(),
block_hash: *value.block_hash(),
actions: value.take_actions(),
},
}
}
}
impl From<near_primitives::transaction::TransactionV0> for TransactionAsBase64 {
fn from(value: near_primitives::transaction::TransactionV0) -> Self {
Self { inner: value }
}
}
impl From<TransactionAsBase64> for near_primitives::transaction::Transaction {
fn from(transaction: TransactionAsBase64) -> Self {
Self::V0(transaction.inner)
}
}
impl interactive_clap::ToCli for TransactionAsBase64 {
type CliVariant = TransactionAsBase64;
}
impl std::str::FromStr for TransactionAsBase64 {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self {
inner: near_primitives::transaction::TransactionV0::try_from_slice(
&near_primitives::serialize::from_base64(s)
.map_err(|err| format!("base64 transaction sequence is invalid: {err}"))?,
)
.map_err(|err| format!("transaction could not be parsed: {err}"))?,
})
}
}
impl std::fmt::Display for TransactionAsBase64 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let base64_unsigned_transaction = near_primitives::serialize::to_base64(
&borsh::to_vec(&self.inner)
.expect("Transaction is not expected to fail on serialization"),
);
write!(f, "{base64_unsigned_transaction}")
}
}
| 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/network_view_at_block/mod.rs | src/network_view_at_block/mod.rs | use std::str::FromStr;
use color_eyre::eyre::ContextCompat;
use near_primitives::types::{BlockId, BlockReference, Finality};
use strum::{EnumDiscriminants, EnumIter, EnumMessage};
pub type OnAfterGettingBlockReferenceCallback =
std::sync::Arc<dyn Fn(&crate::config::NetworkConfig, &BlockReference) -> crate::CliResult>;
#[derive(Clone)]
pub struct ArgsForViewContext {
pub config: crate::config::Config,
pub interacting_with_account_ids: Vec<near_primitives::types::AccountId>,
pub on_after_getting_block_reference_callback: OnAfterGettingBlockReferenceCallback,
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = ArgsForViewContext)]
#[interactive_clap(output_context = NetworkViewAtBlockArgsContext)]
pub struct NetworkViewAtBlockArgs {
/// What is the name of the network?
#[interactive_clap(skip_default_input_arg)]
network_name: String,
#[interactive_clap(subcommand)]
next: ViewAtBlock,
}
#[derive(Clone)]
pub struct NetworkViewAtBlockArgsContext {
network_config: crate::config::NetworkConfig,
on_after_getting_block_reference_callback: OnAfterGettingBlockReferenceCallback,
}
impl NetworkViewAtBlockArgsContext {
pub fn from_previous_context(
previous_context: ArgsForViewContext,
scope: &<NetworkViewAtBlockArgs as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let network_connection = previous_context.config.network_connection.clone();
let network_config = network_connection
.get(&scope.network_name)
.wrap_err("Failed to get network config!")?
.clone();
Ok(Self {
network_config,
on_after_getting_block_reference_callback: previous_context
.on_after_getting_block_reference_callback,
})
}
}
impl NetworkViewAtBlockArgs {
fn input_network_name(
context: &ArgsForViewContext,
) -> color_eyre::eyre::Result<Option<String>> {
crate::common::input_network_name(&context.config, &context.interacting_with_account_ids)
}
}
#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = NetworkViewAtBlockArgsContext)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
/// Сhoose block for view:
pub enum ViewAtBlock {
#[strum_discriminants(strum(
message = "now - View properties in the final block"
))]
/// View properties in the final block
Now(Now),
#[strum_discriminants(strum(
message = "at-block-height - View properties in a height-selected block"
))]
/// View properties in a height-selected block
AtBlockHeight(AtBlockHeight),
#[strum_discriminants(strum(
message = "at-block-hash - View properties in a hash-selected block"
))]
/// View properties in a hash-selected block
AtBlockHash(BlockIdHash),
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = NetworkViewAtBlockArgsContext)]
#[interactive_clap(output_context = NowContext)]
pub struct Now;
#[derive(Debug, Clone)]
pub struct NowContext;
impl NowContext {
pub fn from_previous_context(
previous_context: NetworkViewAtBlockArgsContext,
_scope: &<Now as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let block_reference = Finality::Final.into();
(previous_context.on_after_getting_block_reference_callback)(
&previous_context.network_config,
&block_reference,
)?;
Ok(Self)
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = NetworkViewAtBlockArgsContext)]
#[interactive_clap(output_context = AtBlockHeightContext)]
pub struct AtBlockHeight {
/// Type the block ID height:
block_id_height: near_primitives::types::BlockHeight,
}
#[derive(Debug, Clone)]
pub struct AtBlockHeightContext;
impl AtBlockHeightContext {
pub fn from_previous_context(
previous_context: NetworkViewAtBlockArgsContext,
scope: &<AtBlockHeight as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let block_reference = BlockReference::BlockId(BlockId::Height(scope.block_id_height));
(previous_context.on_after_getting_block_reference_callback)(
&previous_context.network_config,
&block_reference,
)?;
Ok(Self)
}
}
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = NetworkViewAtBlockArgsContext)]
#[interactive_clap(output_context = BlockIdHashContext)]
pub struct BlockIdHash {
/// Type the block ID hash:
block_id_hash: String,
}
#[derive(Debug, Clone)]
pub struct BlockIdHashContext;
impl BlockIdHashContext {
pub fn from_previous_context(
previous_context: NetworkViewAtBlockArgsContext,
scope: &<BlockIdHash as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let block_reference = BlockReference::BlockId(BlockId::Hash(
near_primitives::hash::CryptoHash::from_str(&scope.block_id_hash).unwrap(),
));
(previous_context.on_after_getting_block_reference_callback)(
&previous_context.network_config,
&block_reference,
)?;
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/network_for_transaction/mod.rs | src/network_for_transaction/mod.rs | use color_eyre::eyre::ContextCompat;
#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::commands::ActionContext)]
#[interactive_clap(output_context = NetworkForTransactionArgsContext)]
#[interactive_clap(skip_default_from_cli)]
pub struct NetworkForTransactionArgs {
/// What is the name of the network?
#[interactive_clap(skip_default_input_arg)]
network_name: String,
#[interactive_clap(subcommand)]
transaction_signature_options: crate::transaction_signature_options::SignWith,
}
#[derive(Clone)]
pub struct NetworkForTransactionArgsContext {
global_context: crate::GlobalContext,
network_config: crate::config::NetworkConfig,
prepopulated_transaction: crate::commands::PrepopulatedTransaction,
on_before_signing_callback: crate::commands::OnBeforeSigningCallback,
on_before_sending_transaction_callback:
crate::transaction_signature_options::OnBeforeSendingTransactionCallback,
on_after_sending_transaction_callback:
crate::transaction_signature_options::OnAfterSendingTransactionCallback,
}
impl NetworkForTransactionArgsContext {
pub fn from_previous_context(
previous_context: crate::commands::ActionContext,
scope: &<NetworkForTransactionArgs as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let network_connection = previous_context
.global_context
.config
.network_connection
.clone();
let network_config = network_connection
.get(&scope.network_name)
.wrap_err("Failed to get network config!")?
.clone();
let prepopulated_transaction = (previous_context
.get_prepopulated_transaction_after_getting_network_callback)(
&network_config
)?;
Ok(Self {
global_context: previous_context.global_context,
network_config,
prepopulated_transaction,
on_before_signing_callback: previous_context.on_before_signing_callback,
on_before_sending_transaction_callback: previous_context
.on_before_sending_transaction_callback,
on_after_sending_transaction_callback: previous_context
.on_after_sending_transaction_callback,
})
}
}
impl From<NetworkForTransactionArgsContext> for crate::commands::TransactionContext {
fn from(item: NetworkForTransactionArgsContext) -> Self {
Self {
global_context: item.global_context,
network_config: item.network_config,
prepopulated_transaction: item.prepopulated_transaction,
on_before_signing_callback: item.on_before_signing_callback,
on_after_signing_callback: std::sync::Arc::new(
|_signed_transaction, _network_config| Ok(()),
),
on_before_sending_transaction_callback: item.on_before_sending_transaction_callback,
on_after_sending_transaction_callback: item.on_after_sending_transaction_callback,
}
}
}
impl interactive_clap::FromCli for NetworkForTransactionArgs {
type FromCliContext = crate::commands::ActionContext;
type FromCliError = color_eyre::eyre::Error;
fn from_cli(
optional_clap_variant: Option<
<NetworkForTransactionArgs as interactive_clap::ToCli>::CliVariant,
>,
context: Self::FromCliContext,
) -> interactive_clap::ResultFromCli<
<Self as interactive_clap::ToCli>::CliVariant,
Self::FromCliError,
>
where
Self: Sized + interactive_clap::ToCli,
{
let mut clap_variant = optional_clap_variant.unwrap_or_default();
if clap_variant.network_name.is_none() {
clap_variant.network_name = match Self::input_network_name(&context) {
Ok(Some(network_name)) => Some(network_name),
Ok(None) => return interactive_clap::ResultFromCli::Cancel(Some(clap_variant)),
Err(err) => return interactive_clap::ResultFromCli::Err(Some(clap_variant), err),
};
}
let network_name = clap_variant.network_name.clone().expect("Unexpected error");
let new_context_scope =
InteractiveClapContextScopeForNetworkForTransactionArgs { network_name };
let new_context = match NetworkForTransactionArgsContext::from_previous_context(
context,
&new_context_scope,
) {
Ok(new_context) => new_context,
Err(err) => return interactive_clap::ResultFromCli::Err(Some(clap_variant), err),
};
if new_context.prepopulated_transaction.actions.is_empty() {
return interactive_clap::ResultFromCli::Cancel(Some(clap_variant));
}
let info_str = if new_context
.network_config
.meta_transaction_relayer_url
.is_some()
{
"Unsigned delegate action:"
} else {
"Unsigned transaction:"
};
tracing::info!(
"{}{}",
info_str,
crate::common::indent_payload(&crate::common::print_unsigned_transaction(
&new_context.prepopulated_transaction,
))
);
match <crate::transaction_signature_options::SignWith as interactive_clap::FromCli>::from_cli(
clap_variant.transaction_signature_options.take(),
new_context.into(),
) {
interactive_clap::ResultFromCli::Ok(cli_sign_with) | interactive_clap::ResultFromCli::Cancel(Some(cli_sign_with)) => {
clap_variant.transaction_signature_options = Some(cli_sign_with);
interactive_clap::ResultFromCli::Ok(clap_variant)
}
interactive_clap::ResultFromCli::Cancel(_) => interactive_clap::ResultFromCli::Cancel(Some(clap_variant)),
interactive_clap::ResultFromCli::Back => interactive_clap::ResultFromCli::Back,
interactive_clap::ResultFromCli::Err(optional_cli_sign_with, err) => {
clap_variant.transaction_signature_options = optional_cli_sign_with;
interactive_clap::ResultFromCli::Err(Some(clap_variant), err)
}
}
}
}
impl NetworkForTransactionArgs {
fn input_network_name(
context: &crate::commands::ActionContext,
) -> color_eyre::eyre::Result<Option<String>> {
crate::common::input_network_name(
&context.global_context.config,
&context.interacting_with_account_ids,
)
}
pub fn get_network_config(
&self,
config: crate::config::Config,
) -> crate::config::NetworkConfig {
config
.network_connection
.get(self.network_name.as_str())
.expect("Impossible to get network name!")
.clone()
}
pub fn get_sign_option(&self) -> crate::transaction_signature_options::SignWith {
self.transaction_signature_options.clone()
}
}
| 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/config/mod.rs | src/config/mod.rs | mod migrations;
pub type CliResult = color_eyre::eyre::Result<()>;
use color_eyre::eyre::{ContextCompat, WrapErr};
use std::{io::Write, str::FromStr};
use tracing_indicatif::span_ext::IndicatifSpanExt;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Config {
pub credentials_home_dir: std::path::PathBuf,
pub network_connection: linked_hash_map::LinkedHashMap<String, NetworkConfig>,
}
impl Default for Config {
fn default() -> Self {
let home_dir = std::env::home_dir().expect("Impossible to get your home dir!");
let mut credentials_home_dir = std::path::PathBuf::from(&home_dir);
credentials_home_dir.push(".near-credentials");
let mut network_connection = linked_hash_map::LinkedHashMap::new();
network_connection.insert(
"mainnet".to_string(),
NetworkConfig {
network_name: "mainnet".to_string(),
rpc_url: "https://archival-rpc.mainnet.fastnear.com/"
.parse()
.unwrap(),
wallet_url: "https://app.mynearwallet.com/".parse().unwrap(),
explorer_transaction_url: "https://explorer.near.org/transactions/"
.parse()
.unwrap(),
rpc_api_key: None,
linkdrop_account_id: Some("near".parse().unwrap()),
near_social_db_contract_account_id: Some("social.near".parse().unwrap()),
faucet_url: None,
meta_transaction_relayer_url: None,
fastnear_url: Some("https://api.fastnear.com/".parse().unwrap()),
staking_pools_factory_account_id: Some("poolv1.near".parse().unwrap()),
coingecko_url: Some("https://api.coingecko.com/".parse().unwrap()),
mpc_contract_account_id: Some("v1.signer".parse().unwrap()),
},
);
network_connection.insert(
"mainnet-fastnear".to_string(),
NetworkConfig {
network_name: "mainnet".to_string(),
rpc_url: "https://rpc.mainnet.fastnear.com/".parse().unwrap(),
rpc_api_key: None,
wallet_url: "https://app.mynearwallet.com/".parse().unwrap(),
explorer_transaction_url: "https://explorer.near.org/transactions/"
.parse()
.unwrap(),
linkdrop_account_id: Some("near".parse().unwrap()),
near_social_db_contract_account_id: Some("social.near".parse().unwrap()),
faucet_url: None,
meta_transaction_relayer_url: None,
fastnear_url: Some("https://api.fastnear.com/".parse().unwrap()),
staking_pools_factory_account_id: Some("poolv1.near".parse().unwrap()),
coingecko_url: Some("https://api.coingecko.com/".parse().unwrap()),
mpc_contract_account_id: Some("v1.signer".parse().unwrap()),
},
);
network_connection.insert(
"mainnet-lava".to_string(),
NetworkConfig {
network_name: "mainnet".to_string(),
rpc_url: "https://near.lava.build/".parse().unwrap(),
rpc_api_key: None,
wallet_url: "https://app.mynearwallet.com/".parse().unwrap(),
explorer_transaction_url: "https://explorer.near.org/transactions/"
.parse()
.unwrap(),
linkdrop_account_id: Some("near".parse().unwrap()),
near_social_db_contract_account_id: Some("social.near".parse().unwrap()),
faucet_url: None,
meta_transaction_relayer_url: None,
fastnear_url: Some("https://api.fastnear.com/".parse().unwrap()),
staking_pools_factory_account_id: Some("poolv1.near".parse().unwrap()),
coingecko_url: Some("https://api.coingecko.com/".parse().unwrap()),
mpc_contract_account_id: Some("v1.signer".parse().unwrap()),
},
);
network_connection.insert(
"testnet".to_string(),
NetworkConfig {
network_name: "testnet".to_string(),
rpc_url: "https://archival-rpc.testnet.fastnear.com/"
.parse()
.unwrap(),
wallet_url: "https://testnet.mynearwallet.com/".parse().unwrap(),
explorer_transaction_url: "https://explorer.testnet.near.org/transactions/"
.parse()
.unwrap(),
rpc_api_key: None,
linkdrop_account_id: Some("testnet".parse().unwrap()),
near_social_db_contract_account_id: Some("v1.social08.testnet".parse().unwrap()),
faucet_url: Some("https://helper.nearprotocol.com/account".parse().unwrap()),
meta_transaction_relayer_url: None,
fastnear_url: Some("https://test.api.fastnear.com/".parse().unwrap()),
staking_pools_factory_account_id: Some("pool.f863973.m0".parse().unwrap()),
coingecko_url: None,
mpc_contract_account_id: Some("v1.signer-prod.testnet".parse().unwrap()),
},
);
network_connection.insert(
"testnet-fastnear".to_string(),
NetworkConfig {
network_name: "testnet".to_string(),
rpc_url: "https://test.rpc.fastnear.com/".parse().unwrap(),
rpc_api_key: None,
wallet_url: "https://testnet.mynearwallet.com/".parse().unwrap(),
explorer_transaction_url: "https://explorer.testnet.near.org/transactions/"
.parse()
.unwrap(),
linkdrop_account_id: Some("testnet".parse().unwrap()),
near_social_db_contract_account_id: Some("v1.social08.testnet".parse().unwrap()),
faucet_url: Some("https://helper.nearprotocol.com/account".parse().unwrap()),
meta_transaction_relayer_url: None,
fastnear_url: Some("https://test.api.fastnear.com/".parse().unwrap()),
staking_pools_factory_account_id: Some("pool.f863973.m0".parse().unwrap()),
coingecko_url: None,
mpc_contract_account_id: Some("v1.signer-prod.testnet".parse().unwrap()),
},
);
network_connection.insert(
"testnet-lava".to_string(),
NetworkConfig {
network_name: "testnet".to_string(),
rpc_url: "https://neart.lava.build/".parse().unwrap(),
rpc_api_key: None,
wallet_url: "https://testnet.mynearwallet.com/".parse().unwrap(),
explorer_transaction_url: "https://explorer.testnet.near.org/transactions/"
.parse()
.unwrap(),
linkdrop_account_id: Some("testnet".parse().unwrap()),
near_social_db_contract_account_id: Some("v1.social08.testnet".parse().unwrap()),
faucet_url: Some("https://helper.nearprotocol.com/account".parse().unwrap()),
meta_transaction_relayer_url: None,
fastnear_url: Some("https://test.api.fastnear.com/".parse().unwrap()),
staking_pools_factory_account_id: Some("pool.f863973.m0".parse().unwrap()),
coingecko_url: None,
mpc_contract_account_id: Some("v1.signer-prod.testnet".parse().unwrap()),
},
);
Self {
credentials_home_dir,
network_connection,
}
}
}
impl Config {
pub fn network_names(&self) -> Vec<String> {
self.network_connection
.iter()
.map(|(_, network_config)| network_config.network_name.clone())
.collect()
}
pub fn into_latest_version(self) -> migrations::ConfigVersion {
migrations::ConfigVersion::V4(self)
}
pub fn get_config_toml() -> color_eyre::eyre::Result<Self> {
if let Some(mut path_config_toml) = dirs::config_dir() {
path_config_toml.extend(&["near-cli", "config.toml"]);
if !path_config_toml.is_file() {
Self::write_config_toml(crate::config::Config::default())?;
};
let config_toml = std::fs::read_to_string(&path_config_toml)?;
let config_version = toml::from_str::<migrations::ConfigVersion>(&config_toml).or_else::<color_eyre::eyre::Report, _>(|err| {
if let Ok(config_v1) = toml::from_str::<migrations::ConfigV1>(&config_toml) {
Ok(migrations::ConfigVersion::V1(config_v1))
} else {
eprintln!("Warning: `near` CLI configuration file stored at {path_config_toml:?} could not be parsed due to: {err}");
eprintln!("Note: The default configuration printed below will be used instead:\n");
let default_config = crate::config::Config::default();
eprintln!("{}", toml::to_string(&default_config)?);
Ok(default_config.into_latest_version())
}
})?;
let is_latest_version = config_version.is_latest_version();
let config: Config = config_version.into();
if !is_latest_version {
Self::write_config_toml(config.clone())?;
}
Ok(config)
} else {
Ok(crate::config::Config::default())
}
}
pub fn write_config_toml(self) -> CliResult {
let config_toml = toml::to_string(&self.into_latest_version())?;
let mut path_config_toml =
dirs::config_dir().wrap_err("Impossible to get your config dir!")?;
path_config_toml.push("near-cli");
std::fs::create_dir_all(&path_config_toml)?;
path_config_toml.push("config.toml");
std::fs::File::create(&path_config_toml)
.wrap_err_with(|| format!("Failed to create file: {path_config_toml:?}"))?
.write(config_toml.as_bytes())
.wrap_err_with(|| format!("Failed to write to file: {path_config_toml:?}"))?;
eprintln!("Note: `near` CLI configuration is stored in {path_config_toml:?}");
Ok(())
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct NetworkConfig {
pub network_name: String,
pub rpc_url: url::Url,
pub rpc_api_key: Option<crate::types::api_key::ApiKey>,
pub wallet_url: url::Url,
pub explorer_transaction_url: url::Url,
// https://github.com/near/near-cli-rs/issues/116
pub linkdrop_account_id: Option<near_primitives::types::AccountId>,
// https://docs.near.org/social/contract
pub near_social_db_contract_account_id: Option<near_primitives::types::AccountId>,
pub faucet_url: Option<url::Url>,
pub meta_transaction_relayer_url: Option<url::Url>,
pub fastnear_url: Option<url::Url>,
pub staking_pools_factory_account_id: Option<near_primitives::types::AccountId>,
pub coingecko_url: Option<url::Url>,
pub mpc_contract_account_id: Option<near_primitives::types::AccountId>,
}
impl NetworkConfig {
pub(crate) fn get_fields(&self) -> color_eyre::eyre::Result<Vec<String>> {
let network_config_value: serde_json::Value =
serde_json::from_str(&serde_json::to_string(self)?)?;
Ok(network_config_value
.as_object()
.wrap_err("Internal error")?
.iter()
.map(|(key, value)| format!("{key}: {value}"))
.collect())
}
#[tracing::instrument(name = "Connecting to RPC", skip_all)]
pub fn json_rpc_client(&self) -> near_jsonrpc_client::JsonRpcClient {
tracing::Span::current().pb_set_message(self.rpc_url.as_str());
tracing::info!(target: "near_teach_me", "Connecting to RPC {}", self.rpc_url.as_str());
let mut json_rpc_client =
near_jsonrpc_client::JsonRpcClient::connect(self.rpc_url.as_ref());
if let Some(rpc_api_key) = &self.rpc_api_key {
json_rpc_client =
json_rpc_client.header(near_jsonrpc_client::auth::ApiKey::from(rpc_api_key.clone()))
};
json_rpc_client
}
pub fn get_near_social_account_id_from_network(
&self,
) -> color_eyre::eyre::Result<near_primitives::types::AccountId> {
if let Some(account_id) = self.near_social_db_contract_account_id.clone() {
return Ok(account_id);
}
match self.network_name.as_str() {
"mainnet" => near_primitives::types::AccountId::from_str("social.near")
.wrap_err("Internal error"),
"testnet" => near_primitives::types::AccountId::from_str("v1.social08.testnet")
.wrap_err("Internal error"),
_ => color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!(
"This network does not provide the \"near-social\" contract"
)),
}
}
pub fn get_mpc_contract_account_id(
&self,
) -> color_eyre::eyre::Result<near_primitives::types::AccountId> {
if let Some(mpc_contract_account_id) = self.mpc_contract_account_id.clone() {
return Ok(mpc_contract_account_id);
}
match self.network_name.as_str() {
"mainnet" => {
near_primitives::types::AccountId::from_str("v1.signer").wrap_err("Internal error")
}
"testnet" => near_primitives::types::AccountId::from_str("v1.signer-prod.testnet")
.wrap_err("Internal error"),
_ => color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!(
"This network does not provide MPC contract account id"
)),
}
}
}
impl From<migrations::ConfigVersion> for Config {
fn from(mut config_version: migrations::ConfigVersion) -> Self {
loop {
config_version = match config_version {
migrations::ConfigVersion::V1(config_v1) => {
eprintln!("Migrating config.toml from V1 to V2...");
migrations::ConfigVersion::V2(config_v1.into())
}
migrations::ConfigVersion::V2(config_v2) => {
eprintln!("Migrating config.toml from V2 to V3...");
migrations::ConfigVersion::V3(config_v2.into())
}
migrations::ConfigVersion::V3(config_v3) => {
eprintln!("Migrating config.toml from V3 to v4...");
migrations::ConfigVersion::V4(config_v3.into())
}
migrations::ConfigVersion::V4(config_v4) => {
break config_v4;
}
};
}
}
}
| 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/config/migrations.rs | src/config/migrations.rs | use crate::config::Config as ConfigV4;
use crate::config::NetworkConfig as NetworkConfigV4;
use NetworkConfigV3 as NetworkConfigV2;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConfigV1 {
pub credentials_home_dir: std::path::PathBuf,
pub network_connection: linked_hash_map::LinkedHashMap<String, NetworkConfigV1>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConfigV2 {
pub credentials_home_dir: std::path::PathBuf,
pub network_connection: linked_hash_map::LinkedHashMap<String, NetworkConfigV2>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConfigV3 {
pub credentials_home_dir: std::path::PathBuf,
pub network_connection: linked_hash_map::LinkedHashMap<String, NetworkConfigV3>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct NetworkConfigV1 {
pub network_name: String,
pub rpc_url: url::Url,
pub rpc_api_key: Option<crate::types::api_key::ApiKey>,
pub wallet_url: url::Url,
pub explorer_transaction_url: url::Url,
// https://github.com/near/near-cli-rs/issues/116
pub linkdrop_account_id: Option<near_primitives::types::AccountId>,
// https://docs.near.org/social/contract
pub near_social_db_contract_account_id: Option<near_primitives::types::AccountId>,
pub faucet_url: Option<url::Url>,
pub meta_transaction_relayer_url: Option<url::Url>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct NetworkConfigV3 {
pub network_name: String,
pub rpc_url: url::Url,
pub rpc_api_key: Option<crate::types::api_key::ApiKey>,
pub wallet_url: url::Url,
pub explorer_transaction_url: url::Url,
pub linkdrop_account_id: Option<near_primitives::types::AccountId>,
pub near_social_db_contract_account_id: Option<near_primitives::types::AccountId>,
pub faucet_url: Option<url::Url>,
pub meta_transaction_relayer_url: Option<url::Url>,
pub fastnear_url: Option<url::Url>,
pub staking_pools_factory_account_id: Option<near_primitives::types::AccountId>,
pub coingecko_url: Option<url::Url>,
}
impl From<ConfigV1> for ConfigV2 {
fn from(config: ConfigV1) -> Self {
ConfigV2 {
credentials_home_dir: config.credentials_home_dir,
network_connection: config
.network_connection
.into_iter()
.map(|(network_name, network_config)| (network_name, network_config.into()))
.collect(),
}
}
}
impl From<ConfigV2> for ConfigV3 {
fn from(config: ConfigV2) -> Self {
ConfigV3 {
credentials_home_dir: config.credentials_home_dir,
network_connection: config
.network_connection
.into_iter()
.map(|(network_name, mut network_config)| {
if network_name == "testnet" && network_config.fastnear_url.is_none() {
network_config.fastnear_url =
Some("https://test.api.fastnear.com/".parse().unwrap());
}
(network_name, network_config)
})
.collect(),
}
}
}
impl From<ConfigV3> for ConfigV4 {
fn from(config: ConfigV3) -> Self {
ConfigV4 {
credentials_home_dir: config.credentials_home_dir,
network_connection: config
.network_connection
.into_iter()
.map(|(network_name, network_config)| (network_name, network_config.into()))
.collect(),
}
}
}
impl From<NetworkConfigV1> for NetworkConfigV2 {
fn from(network_config: NetworkConfigV1) -> Self {
match network_config.network_name.as_str() {
"mainnet" => NetworkConfigV2 {
network_name: network_config.network_name,
rpc_url: network_config.rpc_url,
wallet_url: network_config.wallet_url,
explorer_transaction_url: network_config.explorer_transaction_url,
rpc_api_key: network_config.rpc_api_key,
linkdrop_account_id: network_config.linkdrop_account_id,
near_social_db_contract_account_id: network_config
.near_social_db_contract_account_id,
faucet_url: network_config.faucet_url,
meta_transaction_relayer_url: network_config.meta_transaction_relayer_url,
fastnear_url: Some("https://api.fastnear.com".parse().unwrap()),
staking_pools_factory_account_id: Some("poolv1.near".parse().unwrap()),
coingecko_url: Some("https://api.coingecko.com/".parse().unwrap()),
},
"testnet" => NetworkConfigV2 {
network_name: network_config.network_name,
rpc_url: network_config.rpc_url,
wallet_url: network_config.wallet_url,
explorer_transaction_url: network_config.explorer_transaction_url,
rpc_api_key: network_config.rpc_api_key,
linkdrop_account_id: network_config.linkdrop_account_id,
near_social_db_contract_account_id: network_config
.near_social_db_contract_account_id,
faucet_url: network_config.faucet_url,
meta_transaction_relayer_url: network_config.meta_transaction_relayer_url,
fastnear_url: None,
staking_pools_factory_account_id: Some("pool.f863973.m0".parse().unwrap()),
coingecko_url: None,
},
_ => NetworkConfigV2 {
network_name: network_config.network_name,
rpc_url: network_config.rpc_url,
wallet_url: network_config.wallet_url,
explorer_transaction_url: network_config.explorer_transaction_url,
rpc_api_key: network_config.rpc_api_key,
linkdrop_account_id: network_config.linkdrop_account_id,
near_social_db_contract_account_id: network_config
.near_social_db_contract_account_id,
faucet_url: network_config.faucet_url,
meta_transaction_relayer_url: network_config.meta_transaction_relayer_url,
fastnear_url: None,
staking_pools_factory_account_id: None,
coingecko_url: None,
},
}
}
}
impl From<NetworkConfigV3> for NetworkConfigV4 {
fn from(network_config: NetworkConfigV3) -> Self {
let mpc_contract_account_id: Option<near_primitives::types::AccountId> =
match network_config.network_name.as_str() {
"mainnet" => Some("v1.signer".parse().unwrap()),
"testnet" => Some("v1.signer-prod.testnet".parse().unwrap()),
_ => None,
};
NetworkConfigV4 {
network_name: network_config.network_name,
rpc_url: network_config.rpc_url,
wallet_url: network_config.wallet_url,
explorer_transaction_url: network_config.explorer_transaction_url,
rpc_api_key: network_config.rpc_api_key,
linkdrop_account_id: network_config.linkdrop_account_id,
near_social_db_contract_account_id: network_config.near_social_db_contract_account_id,
faucet_url: network_config.faucet_url,
meta_transaction_relayer_url: network_config.meta_transaction_relayer_url,
fastnear_url: network_config.fastnear_url,
staking_pools_factory_account_id: network_config.staking_pools_factory_account_id,
coingecko_url: network_config.coingecko_url,
mpc_contract_account_id,
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
#[serde(tag = "version")]
pub enum ConfigVersion {
#[serde(rename = "1")]
V1(ConfigV1),
#[serde(rename = "2")]
V2(ConfigV2),
// Adds fastnear_url to the testnet config if it's not present
#[serde(rename = "3")]
V3(ConfigV3),
// Adds mpc_contract_account_id to the mainnet and testnet
#[serde(rename = "4")]
V4(ConfigV4),
}
impl ConfigVersion {
pub fn is_latest_version(&self) -> bool {
// Used match instead of matches! to compile fail if new version is added
match self {
ConfigVersion::V4(_) => true,
ConfigVersion::V3(_) | ConfigVersion::V2(_) | ConfigVersion::V1(_) => false,
}
}
}
| 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/network/mod.rs | src/network/mod.rs | #[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = NetworkContext)]
#[interactive_clap(output_context = NetworkOutputContext)]
pub struct Network {
#[interactive_clap(long)]
#[interactive_clap(skip_interactive_input)]
wallet_url: Option<crate::types::url::Url>,
/// What is the name of the network?
#[interactive_clap(skip_default_input_arg)]
network_name: String,
}
pub type OnAfterGettingNetworkCallback =
std::sync::Arc<dyn Fn(&crate::config::NetworkConfig) -> crate::CliResult>;
#[derive(Clone)]
pub struct NetworkContext {
pub config: crate::config::Config,
pub interacting_with_account_ids: Vec<near_primitives::types::AccountId>,
pub on_after_getting_network_callback: OnAfterGettingNetworkCallback,
}
#[derive(Clone)]
pub struct NetworkOutputContext;
impl NetworkOutputContext {
pub fn from_previous_context(
previous_context: NetworkContext,
scope: &<Network as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let network_connection = previous_context.config.network_connection;
let mut network_config = network_connection
.get(&scope.network_name)
.expect("Failed to get network config!")
.clone();
if let Some(url) = scope.wallet_url.clone() {
network_config.wallet_url = url.into();
}
(previous_context.on_after_getting_network_callback)(&network_config)?;
Ok(Self)
}
}
impl Network {
fn input_network_name(context: &NetworkContext) -> color_eyre::eyre::Result<Option<String>> {
crate::common::input_network_name(&context.config, &context.interacting_with_account_ids)
}
}
| 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/tests/tokens.rs | tests/tokens.rs | mod common;
use common::prepare_tests;
use std::process::Command;
#[tokio::test]
async fn test_view_near_balance() -> Result<(), Box<dyn std::error::Error>> {
let (_sandbox, _temp_dir) = prepare_tests().await?;
let output = Command::new("target/debug/near")
.args(&[
"tokens",
"test.near",
"view-near-balance",
"network-config",
"sandbox",
"now",
])
.output()?;
let stderr = String::from_utf8_lossy(&output.stderr);
let normalize_output = stderr.to_string();
insta::assert_snapshot!("view_near_balance", normalize_output);
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/tests/account.rs | tests/account.rs | mod common;
use std::process::Command;
#[tokio::test]
async fn test_view_account_summary_with_localnet() -> Result<(), Box<dyn std::error::Error>> {
let (_sandbox, _temp_dir) = common::prepare_tests().await?;
let output = Command::new("target/debug/near")
.args(&[
"account",
"view-account-summary",
"test.near",
"network-config",
"sandbox",
"now",
])
.output()?;
let stdout = String::from_utf8_lossy(&output.stdout);
let normalized_stdout = normalize_output(&stdout);
insta::assert_snapshot!("view_account_summary", normalized_stdout);
Ok(())
}
#[tokio::test]
async fn test_view_account_summary_nonexistent() -> Result<(), Box<dyn std::error::Error>> {
let (_sandbox, _temp_dir) = common::prepare_tests().await?;
let output = Command::new("target/debug/near")
.args(&[
"account",
"view-account-summary",
"nonexistent.near",
"network-config",
"sandbox",
"now",
])
.output()?;
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("account nonexistent.near does not exist while viewing"));
Ok(())
}
/// Normalize output by replacing dynamic content with placeholders
fn normalize_output(output: &str) -> String {
use regex::Regex;
let normalized = output;
// Replace block numbers (e.g., "At block #19" -> "At block #[BLOCK_NUM]")
let block_regex = Regex::new(r"At block #\d+").unwrap();
let normalized = block_regex.replace_all(&normalized, "At block #[BLOCK_NUM]");
// Replace block hashes (e.g., "(Gqo3Sym99tdtKm9Ha2aVFUvPPcqNVX8qfQ3dvpUk9B51)" -> "([BLOCK_HASH])")
let hash_regex = Regex::new(r"\([A-Za-z0-9]{43,44}\)").unwrap();
let normalized = hash_regex.replace_all(&normalized, "([BLOCK_HASH])");
normalized.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/tests/common/mod.rs | tests/common/mod.rs | use near_sandbox::{Sandbox, SandboxConfig};
pub async fn prepare_tests() -> Result<(Sandbox, tempfile::TempDir), Box<dyn std::error::Error>> {
// Configure the sandbox with a custom epoch length
let config = SandboxConfig {
additional_genesis: Some(serde_json::json!({
"epoch_length": 43200,
})),
..Default::default()
};
// Start a local sandbox
let sandbox = Sandbox::start_sandbox_with_config(config).await?;
// Create a temporary config directory for this test
let temp_dir = tempfile::tempdir()?;
// Create the config directory structure that near-cli expects:
// $XDG_CONFIG_HOME/near-cli/config.toml
let config_home = temp_dir.path();
std::env::set_var("XDG_CONFIG_HOME", config_home); // Linux
std::env::set_var("HOME", config_home); // macOS
std::env::set_var("APPDATA", config_home); // Windows
let near_cli_config_dir = dirs::config_dir().unwrap().join("near-cli");
std::fs::create_dir_all(&near_cli_config_dir)?;
let config_path = near_cli_config_dir.join("config.toml");
// Write a config file pointing to our sandbox
let credentials_dir = temp_dir.path().join("credentials");
std::fs::create_dir_all(&credentials_dir)?;
// Format the RPC URL properly
let rpc_url = format!("{}/", sandbox.rpc_addr);
// Write a V4 config to avoid migration issues
let config_content = format!(
r#"version = "4"
credentials_home_dir = "{}"
[network_connection.sandbox]
network_name = "sandbox"
rpc_url = "{}"
wallet_url = "{}"
explorer_transaction_url = "{}transactions/"
"#,
credentials_dir.to_string_lossy(),
rpc_url,
rpc_url,
rpc_url
);
std::fs::write(&config_path, config_content)?;
Ok((sandbox, temp_dir))
}
| rust | Apache-2.0 | c9cda7bcb76d513c212e347a76ddacdb941ed755 | 2026-01-04T20:23:22.593044Z | false |
withoutboats/juliex | https://github.com/withoutboats/juliex/blob/cc5144226fcf34d5c3f0c1bdcd349c0c088cd4bb/src/lib.rs | src/lib.rs | //! juliex is a concurrent executor for Rust futures. It is implemented as a
//! threadpool executor using a single, shared queue. Algorithmically, it is very
//! similar to the Threadpool executor provided by the futures crate. The main
//! difference is that juliex uses a crossbeam channel and performs a single
//! allocation per spawned future, whereas the futures Threadpool uses std
//! concurrency primitives and multiple allocations.
//!
//! Similar to [romio][romio] - an IO reactor - juliex currently provides no user
//! configuration. It exposes the most minimal API possible.
//!
//! [romio]: https://github.com/withoutboats/romio
//!
//! ## Example
//! ```rust,no_run
//! use std::io;
//!
//! use futures::StreamExt;
//! use futures::executor;
//! use futures::io::AsyncReadExt;
//!
//! use romio::{TcpListener, TcpStream};
//!
//! fn main() -> io::Result<()> {
//! executor::block_on(async {
//! let mut listener = TcpListener::bind(&"127.0.0.1:7878".parse().unwrap())?;
//! let mut incoming = listener.incoming();
//!
//! println!("Listening on 127.0.0.1:7878");
//!
//! while let Some(stream) = incoming.next().await {
//! let stream = stream?;
//! let addr = stream.peer_addr()?;
//!
//! juliex::spawn(async move {
//! println!("Accepting stream from: {}", addr);
//!
//! echo_on(stream).await.unwrap();
//!
//! println!("Closing stream from: {}", addr);
//! });
//! }
//!
//! Ok(())
//! })
//! }
//!
//! async fn echo_on(stream: TcpStream) -> io::Result<()> {
//! let (mut reader, mut writer) = stream.split();
//! reader.copy_into(&mut writer).await?;
//! Ok(())
//! }
//! ```
use std::cell::{RefCell, UnsafeCell};
use std::fmt;
use std::future::Future;
use std::mem::{forget, ManuallyDrop};
use std::sync::{
atomic::{AtomicUsize, Ordering::SeqCst},
Arc, Weak,
};
use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
use std::thread;
use crossbeam::channel;
use futures::future::BoxFuture;
use futures::prelude::*;
#[cfg(test)]
mod tests;
lazy_static::lazy_static! {
static ref THREAD_POOL: ThreadPool = ThreadPool::new();
}
thread_local! {
static QUEUE: RefCell<Weak<TaskQueue>> = RefCell::new(Weak::new());
}
/// A threadpool that futures can be spawned on.
///
/// This is useful when you want to perform some setup logic around the
/// threadpool. If you don't need to setup extra logic, it's recommended to use
/// `juliex::spawn()` directly.
pub struct ThreadPool {
queue: Arc<TaskQueue>,
}
impl ThreadPool {
/// Create a new threadpool instance.
#[inline]
pub fn new() -> Self {
Self::with_setup(|| ())
}
/// Create a new instance with a method that's called for every thread
/// that's spawned.
#[inline]
pub fn with_setup<F>(f: F) -> Self
where
F: Fn() + Send + Sync + 'static,
{
let f = Arc::new(f);
let (tx, rx) = channel::unbounded();
let queue = Arc::new(TaskQueue { tx, rx });
let max_cpus = num_cpus::get() * 2;
for _ in 0..max_cpus {
let f = f.clone();
let rx = queue.rx.clone();
let queue = Arc::downgrade(&queue);
thread::spawn(move || {
QUEUE.with(|q| *q.borrow_mut() = queue.clone());
f();
for task in rx {
unsafe { task.poll() }
}
});
}
ThreadPool { queue }
}
/// Spawn a new future on the threadpool.
#[inline]
pub fn spawn<F>(&self, future: F)
where
F: Future<Output = ()> + Send + 'static,
{
self.queue
.tx
.send(Task::new(future, self.queue.clone()))
.unwrap();
}
/// Spawn a boxed future on the threadpool.
#[inline]
pub fn spawn_boxed(&self, future: BoxFuture<'static, ()>) {
self.queue
.tx
.send(Task::new_boxed(future, self.queue.clone()))
.unwrap();
}
}
/// Spawn a task on the threadpool.
///
/// ## Example
/// ```rust,ignore
/// use std::thread;
/// use futures::executor;
///
/// fn main() {
/// for _ in 0..10 {
/// juliex::spawn(async move {
/// let id = thread::current().id();
/// println!("Running on thread {:?}", id);
/// })
/// }
/// }
/// ```
#[inline]
pub fn spawn<F>(future: F)
where
F: Future<Output = ()> + Send + 'static,
{
QUEUE.with(|q| {
if let Some(q) = q.borrow().upgrade() {
q.tx.send(Task::new(future, q.clone())).unwrap();
} else {
THREAD_POOL.spawn(future);
}
});
}
struct TaskQueue {
tx: channel::Sender<Task>,
rx: channel::Receiver<Task>,
}
impl Default for TaskQueue {
fn default() -> TaskQueue {
let (tx, rx) = channel::unbounded();
TaskQueue { tx, rx }
}
}
#[derive(Clone, Debug)]
#[repr(transparent)]
struct Task(Arc<AtomicFuture>);
struct AtomicFuture {
queue: Arc<TaskQueue>,
status: AtomicUsize,
future: UnsafeCell<BoxFuture<'static, ()>>,
}
impl fmt::Debug for AtomicFuture {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"AtomicFuture".fmt(f)
}
}
unsafe impl Send for AtomicFuture {}
unsafe impl Sync for AtomicFuture {}
const WAITING: usize = 0; // --> POLLING
const POLLING: usize = 1; // --> WAITING, REPOLL, or COMPLETE
const REPOLL: usize = 2; // --> POLLING
const COMPLETE: usize = 3; // No transitions out
impl Task {
#[inline]
fn new<F: Future<Output = ()> + Send + 'static>(future: F, queue: Arc<TaskQueue>) -> Task {
let future: Arc<AtomicFuture> = Arc::new(AtomicFuture {
queue,
status: AtomicUsize::new(WAITING),
future: UnsafeCell::new(future.boxed()),
});
let future: *const AtomicFuture = Arc::into_raw(future) as *const AtomicFuture;
unsafe { task(future) }
}
#[inline]
fn new_boxed(future: BoxFuture<'static, ()>, queue: Arc<TaskQueue>) -> Task {
let future: Arc<AtomicFuture> = Arc::new(AtomicFuture {
queue,
status: AtomicUsize::new(WAITING),
future: UnsafeCell::new(future),
});
let future: *const AtomicFuture = Arc::into_raw(future) as *const AtomicFuture;
unsafe { task(future) }
}
#[inline]
unsafe fn poll(self) {
self.0.status.store(POLLING, SeqCst);
let waker = ManuallyDrop::new(waker(&*self.0));
let mut cx = Context::from_waker(&waker);
loop {
if let Poll::Ready(_) = (&mut *self.0.future.get()).poll_unpin(&mut cx) {
break self.0.status.store(COMPLETE, SeqCst);
}
match self
.0
.status
.compare_exchange(POLLING, WAITING, SeqCst, SeqCst)
{
Ok(_) => break,
Err(_) => self.0.status.store(POLLING, SeqCst),
}
}
}
}
#[inline]
unsafe fn waker(task: *const AtomicFuture) -> Waker {
Waker::from_raw(RawWaker::new(
task as *const (),
&RawWakerVTable::new(clone_raw, wake_raw, wake_ref_raw, drop_raw),
))
}
#[inline]
unsafe fn clone_raw(this: *const ()) -> RawWaker {
let task = clone_task(this as *const AtomicFuture);
RawWaker::new(
Arc::into_raw(task.0) as *const (),
&RawWakerVTable::new(clone_raw, wake_raw, wake_ref_raw, drop_raw),
)
}
#[inline]
unsafe fn drop_raw(this: *const ()) {
drop(task(this as *const AtomicFuture))
}
#[inline]
unsafe fn wake_raw(this: *const ()) {
let task = task(this as *const AtomicFuture);
let mut status = task.0.status.load(SeqCst);
loop {
match status {
WAITING => {
match task
.0
.status
.compare_exchange(WAITING, POLLING, SeqCst, SeqCst)
{
Ok(_) => {
task.0.queue.tx.send(clone_task(&*task.0)).unwrap();
break;
}
Err(cur) => status = cur,
}
}
POLLING => {
match task
.0
.status
.compare_exchange(POLLING, REPOLL, SeqCst, SeqCst)
{
Ok(_) => break,
Err(cur) => status = cur,
}
}
_ => break,
}
}
}
#[inline]
unsafe fn wake_ref_raw(this: *const ()) {
let task = ManuallyDrop::new(task(this as *const AtomicFuture));
let mut status = task.0.status.load(SeqCst);
loop {
match status {
WAITING => {
match task
.0
.status
.compare_exchange(WAITING, POLLING, SeqCst, SeqCst)
{
Ok(_) => {
task.0.queue.tx.send(clone_task(&*task.0)).unwrap();
break;
}
Err(cur) => status = cur,
}
}
POLLING => {
match task
.0
.status
.compare_exchange(POLLING, REPOLL, SeqCst, SeqCst)
{
Ok(_) => break,
Err(cur) => status = cur,
}
}
_ => break,
}
}
}
#[inline]
unsafe fn task(future: *const AtomicFuture) -> Task {
Task(Arc::from_raw(future))
}
#[inline]
unsafe fn clone_task(future: *const AtomicFuture) -> Task {
let task = task(future);
forget(task.clone());
task
}
| rust | Apache-2.0 | cc5144226fcf34d5c3f0c1bdcd349c0c088cd4bb | 2026-01-04T20:24:37.226415Z | false |
withoutboats/juliex | https://github.com/withoutboats/juliex/blob/cc5144226fcf34d5c3f0c1bdcd349c0c088cd4bb/src/tests.rs | src/tests.rs | use std::cell::Cell;
use std::future::Future;
use std::pin::Pin;
use std::task::Context;
use std::sync::mpsc::*;
use super::*;
struct DropFuture(Sender<()>);
impl Future for DropFuture {
type Output = ();
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
Poll::Ready(())
}
}
impl Drop for DropFuture {
fn drop(&mut self) {
self.0.send(()).unwrap();
}
}
#[test]
fn destructor_runs() {
// Test that the destructor runs
let (tx, rx) = channel();
drop(Task::new(DropFuture(tx), Default::default()));
rx.try_recv().unwrap();
// Test that the destructor doesn't run if we forget the task
let (tx, rx) = channel();
std::mem::forget(Task::new(DropFuture(tx), Default::default()));
assert!(rx.try_recv().is_err());
}
#[test]
fn with_setup() {
thread_local! {
static FLAG: Cell<bool> = Cell::new(false);
}
// Test that the init function gets called.
let pool = ThreadPool::with_setup(|| FLAG.with(|f| f.set(true)));
let (tx, rx) = channel();
pool.spawn(async move {
assert_eq!(FLAG.with(|f| f.get()), true);
tx.send(()).unwrap();
});
rx.recv().unwrap();
}
| rust | Apache-2.0 | cc5144226fcf34d5c3f0c1bdcd349c0c088cd4bb | 2026-01-04T20:24:37.226415Z | false |
withoutboats/juliex | https://github.com/withoutboats/juliex/blob/cc5144226fcf34d5c3f0c1bdcd349c0c088cd4bb/examples/http.rs | examples/http.rs | use std::io;
use futures::StreamExt;
use futures::executor;
use futures::io::AsyncReadExt;
use futures::io::AsyncWriteExt;
use romio::{TcpListener};
fn main() -> io::Result<()> {
executor::block_on(async {
let mut listener = TcpListener::bind(&"127.0.0.1:7878".parse().unwrap())?;
let mut incoming = listener.incoming();
println!("Listening on 127.0.0.1:7878");
while let Some(stream) = incoming.next().await {
let stream = stream?;
juliex::spawn(async move {
let (_, mut writer) = stream.split();
writer.write_all(b"HTTP/1.1 200 OK\r\nContent-Length:0\r\n\r\n").await.unwrap();
});
}
Ok(())
})
}
| rust | Apache-2.0 | cc5144226fcf34d5c3f0c1bdcd349c0c088cd4bb | 2026-01-04T20:24:37.226415Z | false |
withoutboats/juliex | https://github.com/withoutboats/juliex/blob/cc5144226fcf34d5c3f0c1bdcd349c0c088cd4bb/examples/echo.rs | examples/echo.rs | use std::io;
use futures::StreamExt;
use futures::executor;
use futures::io::AsyncReadExt;
use romio::{TcpListener, TcpStream};
fn main() -> io::Result<()> {
executor::block_on(async {
let mut listener = TcpListener::bind(&"127.0.0.1:7878".parse().unwrap())?;
let mut incoming = listener.incoming();
println!("Listening on 127.0.0.1:7878");
while let Some(stream) = incoming.next().await {
let stream = stream?;
let addr = stream.peer_addr()?;
juliex::spawn(async move {
println!("Accepting stream from: {}", addr);
echo_on(stream).await.unwrap();
println!("Closing stream from: {}", addr);
});
}
Ok(())
})
}
async fn echo_on(stream: TcpStream) -> io::Result<()> {
let (reader, mut writer) = stream.split();
reader.copy_into(&mut writer).await?;
Ok(())
}
| rust | Apache-2.0 | cc5144226fcf34d5c3f0c1bdcd349c0c088cd4bb | 2026-01-04T20:24:37.226415Z | false |
reganzm/hug_rust | https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/rust基础/控制和跳转/src/main.rs | rust基础/控制和跳转/src/main.rs | use std::{collections::HashMap, path::PrefixComponent};
fn main() {
// 表达式和语句
// 函数func是语句
fn func() -> i32 {
// 123是表达式,表达式返回
123
}
// 整句是语句,name = "regan".to_string()是表达式
let name = "regan".to_string();
// age=123是表达式
let age = 123;
// 整句是语句,args=[1,2,3]是表达式
let args = [1, 2, 3, 4, 5];
// if else
let num = 50;
if num >= 60 {
println!("num大于等于60");
} else if num <= 30 {
println!("num小于30");
} else {
println!("num大于30且小于60");
}
// let if ; if let ; match
// let if,将满足条件的返回值绑定到result变量
let result = if num >= 50 { true } else { false };
println!("let if:{result}");
// if let模式匹配:pattern = expr
// 匹配到之后将运行{}中的代码,否则运行else中的代码
if let 50 = num {
println!("num==50")
} else {
println!("num!=50");
}
// match模式匹配
match num {
20 => println!("num=20"),
30 => println!("num=30"),
50 => println!("num=50"),
// 使用_表示其它的选项
_ => println!("num not in 20 30 50"),
}
// 单分支多模式匹配
match num {
// pat|pat 单分支多模式匹配
20 | 30 => println!("num=20 or num=30"),
// expr..=expr进行范围匹配
40..=50 => println!("num>=40 and num<=50"),
// 匹配守卫,提供额外的条件
x if x >= 100 => println!("x>=100"),
1 | 2 | 3 | 4 | 500 if num == 500 => print!("num = 500"),
// 使用_表示其它的选项
_ => println!("num not in 20 30 50"),
}
// if let和match结合枚举进行模式匹配
enum Fruit {
Apple,
Orange,
Watermelon,
}
let my_favorite_fruit = Fruit::Watermelon;
// if let结合枚举进行模式匹配
if let Fruit::Watermelon = my_favorite_fruit {
println!("是的,我最喜欢的水果是西瓜");
} else {
println!("猜错了");
}
// match结合枚举进行模式匹配
match my_favorite_fruit {
Fruit::Apple => println!("我讨厌吃苹果"),
Fruit::Orange => println!("橘子一般般"),
Fruit::Watermelon => println!("西瓜,我的最爱"),
}
// 循环
// loop循环体,使用break退出循环
let mut num = 0;
let result = loop {
num += 1;
if num == 10 {
break num * 10; // 结束循环并返回num的值乘以10
}
};
println!("result:{:?}", result);
// for循环
// 遍历切片
for i in 0..=100 {
println!("i:{i}");
}
// 遍历数组
for i in [1, 2, 3] {
println!("i = {i}");
}
// 遍历动态数组
for i in vec![2, 3, 4] {
println!("i=={i}");
}
// 遍历HashMap
let mut map = HashMap::new();
map.insert("regan", 100);
map.insert("pip", 66);
for i in map {
println!("{:?}", i);
}
// 遍历字符串
let s = "加油学习Rust".to_string();
for i in s.chars() {
println!("{:?}", i);
}
// break退出循环 continue结束本次循环
let mut sum = 0;
for i in 1..=100 {
if i == 88 {
// 跳过本次循环
println!("跳过本次循环");
continue;
}
if i == 99 {
// 结束循环
println!("结束循环");
break;
}
sum += i;
}
println!("sum={sum}");
// while循环
let mut i = 0;
while i <= 10 {
println!("i=:{i}");
i += 1;
}
// while let
let mut stack = Vec::new();
stack.push(1);
stack.push(2);
stack.push(3);
while let Some(top_num) = stack.pop() {
println!("top num = {top_num}");
}
}
| rust | Apache-2.0 | 6a2801769c8b062477c2e6273af0218e0e21e75d | 2026-01-04T20:24:35.074754Z | false |
reganzm/hug_rust | https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/rust基础/所有权及引用/src/bin/reference.rs | rust基础/所有权及引用/src/bin/reference.rs | fn main() {
let name = String::from("三角兽");
let nick_name = String::from("兽兽");
println!("name:{name} nick_name:{nick_name}");
// 通过&获取对象的引用
// 不会转移所有权
let ref_name = &name;
let ref_nick_name = &name;
println!("ref_name:{ref_name} ref_nick_name:{ref_nick_name}");
// 打印出引用的地址和值的地址
println!("ref_name_p:{:p} name_p:{:p}", &ref_name, &(*ref_name));
// 传递引用
// 函数传值导致所有权转移
let msg = String::from("2024学好Rust");
do_somthing(&msg);
// 下面使用msg变量能够正常编译了
println!("msg:{msg}");
// 结构体方法中返回引用
let ruster = Ruster {
name: String::from("兽兽"),
};
println!("ruster name:{}", ruster.get_name());
// 可变引用
let mut age = 123;
let age1 = &mut age;
// 使用*解引用,并对其值进行加法操作
*age1 += 10;
println!("age1:{age1}");
}
// 函数接收引用参数引用
fn do_somthing(msg: &String) {
println!("msg:{msg}");
}
struct Ruster {
name: String,
}
impl Ruster {
fn new(name: String) -> Self {
Self { name }
}
// 结构体方法返回引用
fn get_name(&self) -> &String {
&self.name
}
}
| rust | Apache-2.0 | 6a2801769c8b062477c2e6273af0218e0e21e75d | 2026-01-04T20:24:35.074754Z | false |
reganzm/hug_rust | https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/rust基础/所有权及引用/src/bin/owner_and_scope.rs | rust基础/所有权及引用/src/bin/owner_and_scope.rs | #[warn(unused_variables)]
fn main() {
let a: f64 = 3.14;
// 所有权和作用域
owner_and_scope();
} // <-------------------------------main函数作用域中的a离开作用域,自动被回收
// 所有权和作用域
#[warn(unused_variables)]
fn owner_and_scope() {
let a = 1314; // <---------- a出现在owner_and_scope中
{
//------------------------------临时作用域
let a = 3.15; // <-------a出现在临时作用域
println!("a at inner scope:{a}");
let b = 567; // <-------b出现在临时作用域
println!("b at inner scope:{b}");
} // <------------------------------临时作用域中的a和b离开临时作用域,会自动调用drop清理占用的内存
let a = 520; // <-------------a1314被遮盖
println!("a at outer scope:{a}");
} // <-----------------------------------外面的a离开作用域,自动回收
| rust | Apache-2.0 | 6a2801769c8b062477c2e6273af0218e0e21e75d | 2026-01-04T20:24:35.074754Z | false |
reganzm/hug_rust | https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/rust基础/所有权及引用/src/bin/owner_moved.rs | rust基础/所有权及引用/src/bin/owner_moved.rs | fn main() {
// 便量绑定
let str_a = String::from("拿下rust");
// 打印str_a内存地址
println!("str_a memory address :{:p}", &(*str_a));
// move所有权,str_b变量现在拥有值的所有权
// str_a不再拥有值的所有权,不能再访问
let str_b = str_a;
// 打印str_b内存地址
// 可以发现str_b和str_a值对应的内存地址是一样的
// 只是拥有这个值的变量变化了
println!("str_b memory address :{:p}", &(*str_b));
println!("str_b:{str_b}");
// 下面打印编译错误,原因是已不再拥有值的所有权
// println!("str_a:{str_a}");
// 基本类型默认实现了Copy语义,不会发生所有权的移动
let num_a = 520_1314_0_u32;
let num_b = num_a;
println!(
"num_a:{num_a},num_b:{num_b} num_a address:{:p} num_b address:{:p}",
&num_a, &num_b
);
// 函数传值导致所有权转移
let msg = String::from("2024学好Rust");
do_somthing(msg);
// 下面打印报错,因为"2024学好Rust"值的所有权已经被move到函数里面
// 本作用域不能再使用该值
//println!("msg:{msg}");
// 传递基本类型,不会发生所有权转移
let age = 18;
do_somthing2(age);
println!("age:{age}");
} // <------ str_b离开作用域,自动调用drop函数释放"拿下rust"值对应的内存
fn do_somthing(msg: String) {
println!("msg:{msg}");
}
fn do_somthing2(age: u32) {
println!("age:{age}");
}
struct Animal {
name: String,
age: i32,
}
impl Animal {
fn new(name: String, age: i32) -> Self {
Self { name, age }
}
// 下面方法报编译错误,self.name是一个共享引用
// 不能move所有权
//fn get_name(&self)->String{
// self.name
//}
// self.age实现了Copy特征,直接拷贝栈上的值返回
fn get_age(&self) -> i32 {
self.age
}
}
| rust | Apache-2.0 | 6a2801769c8b062477c2e6273af0218e0e21e75d | 2026-01-04T20:24:35.074754Z | false |
reganzm/hug_rust | https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/rust基础/智能指针/src/main.rs | rust基础/智能指针/src/main.rs | use std::{mem::size_of_val, ops::Deref};
fn main() {
let a: &str = "Rust";
// 分别打印出&str的大小、切片变量地址、切片对应值的地址
// 和切片对应值的大小,它和切片中的len属性大小一致
println!(
"size of a:{} , address of a:{:p}, value address of a:{:p} , size of data:{}",
a.len(),
&a,
&(*a),
size_of_val(&(*a))
);
// 指针(引用)
let a: u8 = 8;
let b: &u8 = &a;
let c: *const u32;
let a: i32 = 8;
let b: &i32 = &a;
// 裸指针
let a: i32 = 8;
let b: *const i32 = &a;
unsafe {
println!("a:{a} b:{}", *b);
}
// 指针的指针(引用的引用)
let a = 123_i32;
let b = &a;
let c = &b;
let d = &c;
println!(
"d address:{:p} , c address:{:p} , b address:{:p} , a address:{:p} , a value:{a}",
&d, d, c, b
);
// 为结构体实现Deref和Drop特征
let sandbox = SandBox("Ruster");
// sandbox离开作用域调用drop自动释放内存
println!("sandbox:{:?}", sandbox);
// 使用*解引用运算符获取结构体中的值(如果是指针就是获取指针指向的内存中的值)
// 如果没有实现Deref接口,*sandbox是会报错的
println!("sandbox value:{:?}", *sandbox);
let sandbox_1 = SandBox(33);
println!("sandbox_1:{:?}", sandbox_1);
// 使用解引用运算符*相当于调用了deref方法
println!("sandbox_1 value:{:?} {:?}", *sandbox_1, sandbox_1.deref());
// Box指针,数据存储在对上,调用指针自动解引用
let age_stack = 10;
let age_heap = Box::new(age_stack);
println!(
"age stack:{age_stack}
age_heap:{age_heap}
age_stack_addr:{:p}
age_heap_addr:{:p}",
&age_stack,
&(*age_heap)
);
// 使用*解引用堆上的数据
println!("{} {} ", age_stack == *age_heap, age_heap.deref());
// 使用特征对象存储不同的类型到集合中
get_animals();
// Box::leak,获取全局生效的静态字符串
println!("{}", leak_a_static_str());
}
// 定义元组结构体
#[derive(Debug)]
struct SandBox<T>(T);
impl<T> SandBox<T> {
fn new(x: T) -> Self {
Self(x)
}
}
impl<T> Deref for SandBox<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
println!("解引用...");
&self.0
}
}
impl<T> Drop for SandBox<T> {
fn drop(&mut self) {
println!("沙箱调用drop方法释放内存");
}
}
trait Eat {
fn eat(&self);
}
#[derive(Debug)]
struct Dog {
age: i32,
}
#[derive(Debug)]
struct Pig {
age: i32,
}
impl Eat for Dog {
fn eat(&self) {
println!("我吃肉");
}
}
impl Eat for Pig {
fn eat(&self) {
println!("我吃草");
}
}
fn get_animals() {
// 能成为特征对象,必须保证类型安全:需满足如下条件
// 结构体中不包含泛型
// 所有方法中都不是返回Self
// 方法不是异步的
let animals: Vec<Box<dyn Eat>> = vec![Box::new(Pig { age: 2 }), Box::new(Dog { age: 3 })];
for animal in animals {
animal.eat();
}
}
// Box::leak关联函数
fn leak_a_static_str() -> &'static str {
let s = String::from("拿下Rust,成为一个Ruster");
Box::leak(s.into_boxed_str())
}
// Box所有权转移
fn move_ownership_on_box() {
let pig = Box::new(Pig { age: 10 });
println!("pig:{:?}", pig);
// pig的所有权转移到pig1,pig不能继续访问
let pig1 = pig;
// 下面注释掉的代码会报所有权转移的编译错误
//println!("pig1:{:?} pig:{:?}",pig1,pig);
println!("pig1:{:?} ", pig1);
}
| rust | Apache-2.0 | 6a2801769c8b062477c2e6273af0218e0e21e75d | 2026-01-04T20:24:35.074754Z | false |
reganzm/hug_rust | https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/rust基础/智能指针/src/bin/rc_and_arc.rs | rust基础/智能指针/src/bin/rc_and_arc.rs | use std::{rc::Rc, sync::Arc, thread, time::Duration};
fn main() {
// Rc
let count1: Rc<i32> = Rc::new(10);
// 增加引用计数器
let count2: Rc<i32> = count1.clone();
println!("count1:{count1} count2:{count2}");
println!("reference count:{} ", Rc::strong_count(&count1));
{
let count3 = count2.clone();
println!("reference count:{} ", Rc::strong_count(&count3));
}
println!("reference count:{} ", Rc::strong_count(&count1));
// Arc
let s = Arc::new(10);
let mut handles = Vec::new();
for _i in 0..10 {
// 增加引用计数器
let tmp = Arc::clone(&s);
let handle = thread::spawn(move || {
println!("atomic reference count:{}", Arc::strong_count(&tmp));
thread::sleep(Duration::from_secs(2));
});
handles.push(handle);
}
println!("atomic reference count:{}", Arc::strong_count(&s));
thread::sleep(Duration::from_secs(2));
println!("atomic reference count:{}", Arc::strong_count(&s));
}
| rust | Apache-2.0 | 6a2801769c8b062477c2e6273af0218e0e21e75d | 2026-01-04T20:24:35.074754Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.