Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/commands/contract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ mod download_abi;
pub mod download_wasm;
#[cfg(feature = "inspect_contract")]
mod inspect;
pub mod state_init;

#[cfg(feature = "verify_contract")]
mod verify;
Expand Down Expand Up @@ -44,6 +45,11 @@ pub enum ContractActions {
))]
/// Add a global contract code
DeployAsGlobal(self::deploy_global::Contract),
#[strum_discriminants(strum(
message = "state-init - Initialize a deterministic account with a global contract and state data"
))]
/// Initialize a deterministic account with a global contract and state data
StateInit(self::state_init::StateInit),
#[strum_discriminants(strum(
message = "inspect - Get a list of available function names"
))]
Expand Down
332 changes: 332 additions & 0 deletions src/commands/contract/state_init/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,332 @@
use color_eyre::eyre::Context;
use strum::{EnumDiscriminants, EnumIter, EnumMessage};

#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = crate::GlobalContext)]
pub struct StateInit {
#[interactive_clap(subcommand)]
state_init: StateInitModeCommand,
}

#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = crate::GlobalContext)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
#[non_exhaustive]
/// How do you want to identify the global contract code?
pub enum StateInitModeCommand {
#[strum_discriminants(strum(
message = "use-global-hash - Use a global contract code hash (immutable)"
))]
/// Use a global contract code hash (immutable)
UseGlobalHash(StateInitWithContractHashRef),
#[strum_discriminants(strum(
message = "use-global-account-id - Use a global contract account ID (mutable)"
))]
/// Use a global contract account ID (mutable)
UseGlobalAccountId(StateInitWithContractRefByAccount),
}

#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = StateInitWithContractHashRefContext)]
pub struct StateInitWithContractHashRef {
/// What is the hash of the global contract?
pub hash: crate::types::crypto_hash::CryptoHash,
#[interactive_clap(subcommand)]
data: Data,
}

#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = StateInitWithContractRefByAccountContext)]
pub struct StateInitWithContractRefByAccount {
/// What is the account ID of the global contract?
pub account_id: crate::types::account_id::AccountId,
#[interactive_clap(subcommand)]
data: Data,
}

#[derive(Debug, Clone)]
pub struct StateInitModeContext {
pub global_context: crate::GlobalContext,
pub code: near_primitives::action::GlobalContractIdentifier,
}

#[derive(Debug, Clone)]
pub struct StateInitWithContractHashRefContext(StateInitModeContext);

impl StateInitWithContractHashRefContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<StateInitWithContractHashRef as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self(StateInitModeContext {
global_context: previous_context,
code: near_primitives::action::GlobalContractIdentifier::CodeHash(scope.hash.into()),
}))
}
}

impl From<StateInitWithContractHashRefContext> for StateInitModeContext {
fn from(item: StateInitWithContractHashRefContext) -> Self {
item.0
}
}

impl From<StateInitWithContractRefByAccountContext> for StateInitModeContext {
fn from(item: StateInitWithContractRefByAccountContext) -> Self {
item.0
}
}

#[derive(Debug, Clone)]
pub struct StateInitWithContractRefByAccountContext(StateInitModeContext);

impl StateInitWithContractRefByAccountContext {
pub fn from_previous_context(
previous_context: crate::GlobalContext,
scope: &<StateInitWithContractRefByAccount as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self(StateInitModeContext {
global_context: previous_context,
code: near_primitives::action::GlobalContractIdentifier::AccountId(
scope.account_id.clone().into(),
),
}))
}
}

#[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = StateInitModeContext)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
#[non_exhaustive]
/// How do you want to provide the initial state data?
pub enum Data {
#[strum_discriminants(strum(
message = "data-from-file - Read hex-encoded key-value JSON data from a file"
))]
/// Read hex-encoded key-value JSON data from a file
DataFromFile(DataFromFile),
#[strum_discriminants(strum(
message = "data-from-json - Provide hex-encoded key-value JSON data inline"
))]
/// Provide hex-encoded key-value JSON data inline
DataFromJson(DataFromJson),
}
Comment on lines +104 to +115

Choose a reason for hiding this comment

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

Maybe add an option to provide the whole StateInit serialized as borsh and encoded as base64 as well?


#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = StateInitModeContext)]
#[interactive_clap(output_context = DataFromFileContext)]
pub struct DataFromFile {
/// What is the file path of the JSON state data?
pub file_path: crate::types::path_buf::PathBuf,
#[interactive_clap(named_arg)]
/// Specify deposit
deposit: Deposit,
}

#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = StateInitModeContext)]
#[interactive_clap(output_context = DataFromJsonContext)]
pub struct DataFromJson {
/// Enter hex-encoded key-value JSON data (e.g. '{"deadbeef": "cafebabe"}' or '{}' for empty state):
pub data: String,
#[interactive_clap(named_arg)]
/// Specify deposit
deposit: Deposit,
}

#[derive(Debug, Clone)]
pub struct StateInitDataContext {
pub global_context: crate::GlobalContext,
pub state_init: near_primitives::deterministic_account_id::DeterministicAccountStateInit,
pub receiver_account_id: near_primitives::types::AccountId,
}

impl StateInitDataContext {
fn build(
code: near_primitives::action::GlobalContractIdentifier,
global_context: crate::GlobalContext,
data: std::collections::BTreeMap<Vec<u8>, Vec<u8>>,
) -> color_eyre::eyre::Result<Self> {
let state_init =
near_primitives::deterministic_account_id::DeterministicAccountStateInit::V1(
near_primitives::deterministic_account_id::DeterministicAccountStateInitV1 {
code,
data,
},
);
let receiver_account_id =
near_primitives::utils::derive_near_deterministic_account_id(&state_init);
Ok(Self {
global_context,
state_init,
receiver_account_id,
})
}
}

impl From<DataFromFileContext> for StateInitDataContext {
fn from(item: DataFromFileContext) -> Self {
item.0
}
}

#[derive(Debug, Clone)]
pub struct DataFromFileContext(StateInitDataContext);

impl DataFromFileContext {
pub fn from_previous_context(
previous_context: StateInitModeContext,
scope: &<DataFromFile as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let json_str = std::fs::read_to_string(&scope.file_path).wrap_err_with(|| {
format!(
"Failed to open or read the file: {}",
scope.file_path.0.display()
)
})?;
let data = crate::common::parse_hex_kv_map(&json_str)?;
Ok(Self(StateInitDataContext::build(
previous_context.code,
previous_context.global_context,
data,
)?))
}
}

impl From<DataFromJsonContext> for StateInitDataContext {
fn from(item: DataFromJsonContext) -> Self {
item.0
}
}

#[derive(Debug, Clone)]
pub struct DataFromJsonContext(StateInitDataContext);

impl DataFromJsonContext {
pub fn from_previous_context(
previous_context: StateInitModeContext,
scope: &<DataFromJson as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
let data = crate::common::parse_hex_kv_map(&scope.data)?;
Ok(Self(StateInitDataContext::build(
previous_context.code,
previous_context.global_context,
data,
)?))
}
}

#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = StateInitDataContext)]
#[interactive_clap(output_context = DepositContext)]
pub struct Deposit {
/// How much do you want to deposit with the state init (e.g. '1 NEAR' or '0 NEAR')?
pub deposit: crate::types::near_token::NearToken,
#[interactive_clap(skip_default_input_arg)]
/// What is the signer account ID?
pub signer_account_id: crate::types::account_id::AccountId,
#[interactive_clap(named_arg)]
/// Select network
network_config: crate::network_for_transaction::NetworkForTransactionArgs,
}

impl Deposit {
pub fn input_signer_account_id(
context: &StateInitDataContext,
) -> 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?",
)
}
}

#[derive(Debug, Clone)]
pub struct DepositContext {
pub global_context: crate::GlobalContext,
pub state_init: near_primitives::deterministic_account_id::DeterministicAccountStateInit,
pub receiver_account_id: near_primitives::types::AccountId,
pub deposit: near_token::NearToken,
pub signer_account_id: near_primitives::types::AccountId,
}

impl DepositContext {
pub fn from_previous_context(
previous_context: StateInitDataContext,
scope: &<Deposit as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
) -> color_eyre::eyre::Result<Self> {
Ok(Self {
global_context: previous_context.global_context,
state_init: previous_context.state_init,
receiver_account_id: previous_context.receiver_account_id,
deposit: scope.deposit.into(),
signer_account_id: scope.signer_account_id.clone().into(),
})
}
}

impl From<DepositContext> for crate::commands::ActionContext {
fn from(item: DepositContext) -> Self {
let signer_id = item.signer_account_id.clone();
let receiver_id = item.receiver_account_id.clone();

let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback =
std::sync::Arc::new({
move |network_config| {
use crate::common::JsonRpcClientExt as _;
let receiver_id = &item.receiver_account_id;
let result = network_config
.json_rpc_client()
.blocking_call_view_account(
receiver_id,
near_primitives::types::Finality::Final.into(),
);
// Best-effort check — only cancel if we positively confirm account exists.
// All errors (UnknownAccount, network timeout, connection refused, etc.)
// are treated as "proceed" to support the sign-later offline signing flow,
// where the network may be unreachable at transaction construction time.
if result.is_ok() {
eprintln!(
"\nDeterministic account <{}> already exists on <{}> network. No transaction needed.",
receiver_id,
network_config.network_name,
);
return Ok(crate::commands::PrepopulatedTransaction {
signer_id: item.signer_account_id.clone(),
receiver_id: item.receiver_account_id.clone(),
actions: vec![],
});
}
Ok(crate::commands::PrepopulatedTransaction {
signer_id: item.signer_account_id.clone(),
receiver_id: item.receiver_account_id.clone(),
actions: vec![
near_primitives::transaction::Action::DeterministicStateInit(Box::new(
near_primitives::action::DeterministicStateInitAction {
state_init: item.state_init.clone(),
deposit: item.deposit,
},
)),
],
})
}
});

Self {
global_context: item.global_context,
interacting_with_account_ids: vec![signer_id, receiver_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(()),
),
}
}
}
Loading
Loading