-
Notifications
You must be signed in to change notification settings - Fork 78
feat: state-init command #560
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pityjllk
wants to merge
1
commit into
near:main
Choose a base branch
from
pityjllk:feat/state-init
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+380
−4
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,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), | ||
| } | ||
|
|
||
| #[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(()), | ||
| ), | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe add an option to provide the whole
StateInitserialized as borsh and encoded as base64 as well?