Skip to content
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

feat: near-transactions and near-accounts refactor #66

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
46 changes: 33 additions & 13 deletions near-accounts/examples/access_keys.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,34 @@
mod example_config;
use near_accounts::Account;
use near_crypto::InMemorySigner;
use near_crypto::{InMemorySigner, SecretKey};
use near_primitives::types::Balance;
use near_providers::JsonRpcProvider;
use std::sync::Arc;
mod utils;
use near_primitives::types::AccountId;

async fn add_full_access() -> Result<(), Box<dyn std::error::Error>> {
let signer_account_id: AccountId = utils::input("Enter the signer Account ID: ")?.parse()?;
let signer_secret_key = utils::input("Enter the signer's private key: ")?.parse()?;
let signer = InMemorySigner::from_secret_key(signer_account_id.clone(), signer_secret_key);
// Get test account and rpc details.
let config = example_config::get_test_config();

let new_secret_key = near_crypto::SecretKey::from_random(near_crypto::KeyType::ED25519);
//Create a signer
let signer_account_id: AccountId = config.near_account.account_id.parse().unwrap();
let signer_secret_key: SecretKey = config.near_account.secret_key.parse().unwrap();
let signer = Arc::new(InMemorySigner::from_secret_key(
signer_account_id.clone(),
signer_secret_key,
));

let provider = Arc::new(JsonRpcProvider::new("https://rpc.testnet.near.org"));
let signer = Arc::new(signer);
//Creat a Provider
let provider = Arc::new(JsonRpcProvider::new(config.rpc_testnet_endpoint.as_str()));

//Create an Account object
let account = Account::new(signer_account_id, signer, provider);

//Generate a secret Key for new access key
let new_secret_key = near_crypto::SecretKey::from_random(near_crypto::KeyType::ED25519);

//Call add_key function on an Account
let result = account
.add_key(new_secret_key.public_key(), None, None, None)
.await;
Expand All @@ -33,17 +44,26 @@ async fn add_full_access() -> Result<(), Box<dyn std::error::Error>> {
}

async fn add_function_call_key() -> Result<(), Box<dyn std::error::Error>> {
let signer_account_id: AccountId = utils::input("Enter the signer Account ID: ")?.parse()?;
let signer_secret_key = utils::input("Enter the signer's private key: ")?.parse()?;
let signer = InMemorySigner::from_secret_key(signer_account_id.clone(), signer_secret_key);
// Get test account and rpc details.
let config = example_config::get_test_config();

let new_secret_key = near_crypto::SecretKey::from_random(near_crypto::KeyType::ED25519);
//Create a signer
let signer_account_id: AccountId = config.near_account.account_id.parse().unwrap();
let signer_secret_key: SecretKey = config.near_account.secret_key.parse().unwrap();
let signer = Arc::new(InMemorySigner::from_secret_key(
signer_account_id.clone(),
signer_secret_key,
));

let provider = Arc::new(JsonRpcProvider::new("https://rpc.testnet.near.org"));
let signer = Arc::new(signer);
//Creat a Provider
let provider = Arc::new(JsonRpcProvider::new(config.rpc_testnet_endpoint.as_str()));

//Create an Account object
let account = Account::new(signer_account_id, signer, provider);

// Create a secret key for the new function call access key
let new_secret_key = near_crypto::SecretKey::from_random(near_crypto::KeyType::ED25519);

let allowance: Balance = 1_000_000_000_000_000_000_000_000; // Example amount in yoctoNEAR
let contract_id = "contract.near-api-rs.testnet".to_string();
//Create an array of methods
Expand Down
15 changes: 12 additions & 3 deletions near-accounts/examples/account_balance.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod example_config;
use near_accounts::accounts::get_account_balance;
use near_primitives::types::AccountId;
use near_providers::JsonRpcProvider;
Expand All @@ -7,13 +8,21 @@ use std::sync::Arc;
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();

let account_id: AccountId = "contract.near-api-rs.testnet".parse::<AccountId>()?;
let config = example_config::get_test_config();
let account_id: AccountId = config.near_account.account_id.parse().unwrap();

let provider = Arc::new(JsonRpcProvider::new("https://rpc.testnet.near.org"));
let provider = Arc::new(JsonRpcProvider::new(&config.rpc_testnet_endpoint));

let result = get_account_balance(provider, account_id).await;

println!("response: {:#?}", result);
match result {
Ok(res) => {
println!("available balance: {:#?}", res.available);
println!("total balance: {:#?}", res.total);
println!("state staked {:#?}", res.state_staked);
}
Err(err) => println!("Error: {:#?}", err),
}

Ok(())
}
52 changes: 26 additions & 26 deletions near-accounts/examples/async_tx.rs
Original file line number Diff line number Diff line change
@@ -1,57 +1,66 @@
//! This example uses the transact_advance method to send transaction and check its status
use near_accounts::Account;
use near_crypto::{InMemorySigner, SecretKey};
mod example_config;
use near_primitives::views::TxExecutionStatus;
use near_primitives::{types::Gas, views::FinalExecutionOutcomeViewEnum};
use near_providers::jsonrpc_primitives::types::transactions::TransactionInfo;
use near_providers::JsonRpcProvider;
use near_providers::Provider;
use std::sync::Arc;
mod utils;
use near_accounts::Account;
use near_crypto::{InMemorySigner, SecretKey};
use near_primitives::types::AccountId;
use serde_json::json;
use tokio::time;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();
// Get test account and rpc details.
let config = example_config::get_test_config();

let signer_account_id: AccountId = "near-api-rs.testnet".parse::<AccountId>()?;
let signer_secret_key = "ed25519:29nYmQCZMsQeYtztXZzm57ayQt2uBHXdn2SAjK4ccMGSQaNUFNJ7Aoteno81eKTex9cGBbk1FuDuqJRsdzx34xDY".parse::<SecretKey>()?;
let contract_id: AccountId = "contract.near-api-rs.testnet".parse::<AccountId>()?;
let signer = InMemorySigner::from_secret_key(signer_account_id.clone(), signer_secret_key);

let gas: Gas = 100_000_000_000_000; // Example amount in yoctoNEAR
//Create a signer
let signer_account_id: AccountId = config.near_account.account_id.parse().unwrap();
let signer_secret_key: SecretKey = config.near_account.secret_key.parse().unwrap();
let signer = Arc::new(InMemorySigner::from_secret_key(
signer_account_id.clone(),
signer_secret_key,
));

let provider = Arc::new(JsonRpcProvider::new("https://rpc.testnet.near.org"));
let signer = Arc::new(signer);
//Creat a Provider
let provider = Arc::new(JsonRpcProvider::new(config.rpc_testnet_endpoint.as_str()));

//Create an Account object
let account = Account::new(signer_account_id, signer, provider.clone());
let method_name = "set_status".to_string();

//Create argumements for function_call
//Contract id, method_name, method args, gas and deposit.
let contract_id: AccountId = "contract.near-api-rs.testnet".parse::<AccountId>()?;
let method_name = "set_status".to_string();
let args_json = json!({"message": "working1"});
let gas: Gas = 100_000_000_000_000; // Example amount in yoctoNEAR

//Create a Transaction Sender Object;
let transaction_sender = account
.function_call(&contract_id, method_name, args_json, gas, 0)
.await?;

//Get the transaction hash to query the chain later.
let tx_hash = transaction_sender.clone().get_transaction_hash().unwrap();

let t1 = time::Instant::now();
//Send the transaction
//Different Wait_until values: None, Included, ExecutedOptimistic, IncludedFinal, Executed, Final
let result = transaction_sender.transact_advanced("NONE").await;
let t2 = time::Instant::now();
match result {
Ok(res) => match &res.final_execution_outcome {
//Final Execution outcome for finality NONE would always be empty.
Some(FinalExecutionOutcomeViewEnum::FinalExecutionOutcome(outcome)) => {
println!("Final Exuecution outcome: {:?}", outcome);
println!("Final Exuecution outcome: {:?}", outcome.transaction);
println!("Final Execution outcome: {:?}", outcome);
println!("Final Execution outcome: {:?}", outcome.transaction);
}
Some(FinalExecutionOutcomeViewEnum::FinalExecutionOutcomeWithReceipt(
outcome_receipt,
)) => {
println!("Final Exuecution outcome_reciepts: {:?}", outcome_receipt)
println!("Final Execution outcome_receipts: {:?}", outcome_receipt)
}
None => println!("No Final execution outcome."),
},
Expand All @@ -64,22 +73,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
sender_account_id: account.account_id,
};
let wait_until = TxExecutionStatus::ExecutedOptimistic;

time::sleep(time::Duration::from_secs(5)).await;

let t3 = time::Instant::now();
let tx_status = provider.tx_status(transaction_info, wait_until).await;
let t4 = time::Instant::now();

match tx_status {
Ok(response) => {
//println!("response gotten after: {}s", delta);
println!("response: {:#?}", response);
}
Err(err) => println!("Error: {:#?}", err),
}

println!("Time taken for aysnc request: {:?}", t2 - t1);
println!("Time taken for status request: {:?}", t4 - t3);
Ok(())
}
45 changes: 28 additions & 17 deletions near-accounts/examples/create_account.rs
Original file line number Diff line number Diff line change
@@ -1,41 +1,52 @@
mod example_config;
use near_accounts::Account;
use near_crypto::InMemorySigner;
use near_crypto::{InMemorySigner, SecretKey};
use near_primitives::{types::Gas, views::FinalExecutionOutcomeViewEnum};
use near_providers::JsonRpcProvider;
use std::sync::Arc;
mod utils;
use near_primitives::types::{AccountId, Balance};
use near_providers::JsonRpcProvider;
use serde_json::json;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();

let signer_account_id: AccountId = utils::input("Enter the signer Account ID: ")?.parse()?;
let signer_secret_key = utils::input("Enter the signer's private key: ")?.parse()?;
//To-do, implement account exist check.
let new_account_id: AccountId = utils::input("Enter new account name: ")?.parse()?;
// Get test account and rpc details.
let config = example_config::get_test_config();

//Create a signer
let signer_account_id: AccountId = config.near_account.account_id.parse().unwrap();
let signer_secret_key: SecretKey = config.near_account.secret_key.parse().unwrap();
let signer = Arc::new(InMemorySigner::from_secret_key(
signer_account_id.clone(),
signer_secret_key,
));

//Creat a Provider
let provider = Arc::new(JsonRpcProvider::new(config.rpc_testnet_endpoint.as_str()));

let signer = InMemorySigner::from_secret_key(signer_account_id.clone(), signer_secret_key);
//Create an Account object
let account = Account::new(signer_account_id, signer, provider.clone());

//Ask the user for the new Account id.
let new_account_id: AccountId = utils::input("Enter new account name: ")?.parse()?;
// Amount to transfer to the new account
let gas: Gas = 100_000_000_000_000; // Example amount in yoctoNEAR
let amount: Balance = 10_000_000_000_000_000_000_000; // Example amount in yoctoNEAR

let new_secret_key = near_crypto::SecretKey::from_random(near_crypto::KeyType::ED25519);
let provider = Arc::new(JsonRpcProvider::new("https://rpc.testnet.near.org"));
let signer = Arc::new(signer);

let account = Account::new(signer_account_id, signer, provider);

let contract_id: AccountId = "testnet".parse::<AccountId>()?;
let method_name = "create_account".to_string();

let new_secret_key = near_crypto::SecretKey::from_random(near_crypto::KeyType::ED25519);
let args_json = json!({
"new_account_id": new_account_id,
"new_public_key": new_secret_key.public_key()
});

println!("New Secret key : {}", new_secret_key);
println!("New Public key: {}", new_secret_key.public_key());

let result = account
.function_call(&contract_id, method_name, args_json, gas, amount)
.await?
Expand All @@ -45,13 +56,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
match result {
Ok(res) => match &res.final_execution_outcome {
Some(FinalExecutionOutcomeViewEnum::FinalExecutionOutcome(outcome)) => {
println!("Final Exuecution outcome: {:?}", outcome);
println!("Final Exuecution outcome: {:?}", outcome.transaction);
println!("Final Execution outcome Status: {:?}", outcome.status);
println!("Final Execution Transaction: {:?}", outcome.transaction);
}
Some(FinalExecutionOutcomeViewEnum::FinalExecutionOutcomeWithReceipt(
outcome_receipt,
)) => {
println!("Final Exuecution outcome: {:?}", outcome_receipt)
println!("Final Execution outcome receipt: {:?}", outcome_receipt)
}
None => println!("No Final execution outcome."),
},
Expand Down
34 changes: 23 additions & 11 deletions near-accounts/examples/create_subaccount.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,42 @@
//use near_providers::Provider;
mod example_config;
use near_accounts::Account;
use near_crypto::InMemorySigner;
use near_primitives::types::Balance;
use near_crypto::{InMemorySigner, SecretKey};
mod utils;
use near_primitives::types::{AccountId, Balance};
use near_providers::JsonRpcProvider;
use std::sync::Arc;
mod utils;
use near_primitives::types::AccountId;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();

let signer_account_id: AccountId = utils::input("Enter the signer Account ID: ")?.parse()?;
let signer_secret_key = utils::input("Enter the signer's private key: ")?.parse()?;
// Get test account and rpc details.
let config = example_config::get_test_config();

//Create a signer
let signer_account_id: AccountId = config.near_account.account_id.parse().unwrap();
let signer_secret_key: SecretKey = config.near_account.secret_key.parse().unwrap();
let signer = Arc::new(InMemorySigner::from_secret_key(
signer_account_id.clone(),
signer_secret_key,
));

//Creat a Provider
let provider = Arc::new(JsonRpcProvider::new(config.rpc_testnet_endpoint.as_str()));

//Create an Account object
let account = Account::new(signer_account_id, signer, provider.clone());

//Ask user for the new account id, it should be of the form something.near-api-rs.testnet
//or whatever signer account you are using.
let new_account_id: AccountId =
utils::input("Enter the account name of new account ")?.parse()?;
let signer = InMemorySigner::from_secret_key(signer_account_id.clone(), signer_secret_key);

// Amount to transfer to the new account
let amount: Balance = 10_000_000_000_000_000_000_000; // Example amount in yoctoNEAR

let new_key_pair = near_crypto::SecretKey::from_random(near_crypto::KeyType::ED25519);
let provider = Arc::new(JsonRpcProvider::new("https://rpc.testnet.near.org"));
let signer = Arc::new(signer);

let account = Account::new(signer_account_id, signer, provider);
// Call create_account
let result = account
.create_account(&new_account_id, new_key_pair.public_key(), amount)
Expand Down
30 changes: 20 additions & 10 deletions near-accounts/examples/delete_account.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod example_config;
use near_accounts::Account;
use near_crypto::InMemorySigner;
use near_crypto::{InMemorySigner, SecretKey};
use near_providers::JsonRpcProvider;
use std::sync::Arc;
mod utils;
Expand All @@ -9,18 +10,27 @@ use near_primitives::types::AccountId;
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();

let signer_account_id: AccountId = utils::input("Enter the signer Account ID: ")?.parse()?;
let signer_secret_key = utils::input("Enter the signer's private key: ")?.parse()?;
let user_account_id: AccountId =
utils::input("Enter the account name which need to be deleted ")?.parse()?;
let signer = InMemorySigner::from_secret_key(signer_account_id.clone(), signer_secret_key);
// Get test account and rpc details.
let config = example_config::get_test_config();

let provider = Arc::new(JsonRpcProvider::new("https://rpc.testnet.near.org"));
let signer = Arc::new(signer);
//Create a signer
let signer_account_id: AccountId = config.near_account.account_id.parse().unwrap();
let signer_secret_key: SecretKey = config.near_account.secret_key.parse().unwrap();
let signer = Arc::new(InMemorySigner::from_secret_key(
signer_account_id.clone(),
signer_secret_key,
));

let account = Account::new(signer_account_id, signer, provider);
//Creat a Provider
let provider = Arc::new(JsonRpcProvider::new(config.rpc_testnet_endpoint.as_str()));

let response = account.delete_account(user_account_id.clone()).await;
//Create an Account object
let account = Account::new(signer_account_id, signer, provider.clone());

let beneficiary_account_id: AccountId =
utils::input("Enter the account name where you want to transfer current account balance before deleting it")?.parse()?;

let response = account.delete_account(beneficiary_account_id.clone()).await;

match response {
Ok(res) => {
Expand Down
Loading
Loading