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

Introduce Action builder, Transaction Wrapper and add test config reader for running examples #63

Closed
Closed
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
10 changes: 2 additions & 8 deletions near-accounts/examples/access_keys.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod example_config;
use near_accounts::Account;
use near_crypto::InMemorySigner;
use near_primitives::types::Balance;
Expand All @@ -7,16 +8,9 @@ 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);

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 account = example_config::create_account();

let result = account
.add_key(new_secret_key.public_key(), None, None, None)
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(())
}
18 changes: 6 additions & 12 deletions near-accounts/examples/async_tx.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
//! 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;
Expand All @@ -15,18 +14,13 @@ use tokio::time;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();

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

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.clone());
let account = example_config::create_account();
let method_name = "set_status".to_string();

let args_json = json!({"message": "working1"});
Expand All @@ -45,13 +39,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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 Down Expand Up @@ -79,7 +73,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Err(err) => println!("Error: {:#?}", err),
}

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

#[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()?;

let signer = InMemorySigner::from_secret_key(signer_account_id.clone(), signer_secret_key);

// 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 account = example_config::create_account();

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 +35,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
13 changes: 2 additions & 11 deletions near-accounts/examples/create_subaccount.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,21 @@
//use near_providers::Provider;
use near_accounts::Account;
use near_crypto::InMemorySigner;
mod example_config;
use near_primitives::types::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()?;
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);
let account = example_config::create_account();
// Call create_account
let result = account
.create_account(&new_account_id, new_key_pair.public_key(), amount)
Expand Down
21 changes: 5 additions & 16 deletions near-accounts/examples/delete_account.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,15 @@
use near_accounts::Account;
use near_crypto::InMemorySigner;
use near_providers::JsonRpcProvider;
use std::sync::Arc;
mod example_config;
mod utils;
use near_primitives::types::AccountId;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();
let beneficiary_account_id: AccountId =
utils::input("Enter the account name where you want to transfer current account balance before deleting it")?.parse()?;
let account = example_config::create_account();

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);

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 response = account.delete_account(user_account_id.clone()).await;
let response = account.delete_account(beneficiary_account_id.clone()).await;

match response {
Ok(res) => {
Expand Down
17 changes: 3 additions & 14 deletions near-accounts/examples/delete_key.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,11 @@
use near_accounts::Account;
use near_crypto::{InMemorySigner, PublicKey};
use near_providers::JsonRpcProvider;
use std::sync::Arc;
mod example_config;
use near_crypto::PublicKey;
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()?;
let signer = 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);

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

let public_key: PublicKey =
"ed25519:EohEtHT8Dt8jURC3DcJ661hWCx6ExPRtDV82FpT4jfNB".parse::<PublicKey>()?;
Expand Down
32 changes: 3 additions & 29 deletions near-accounts/examples/deploy_contract.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,14 @@
use near_accounts::Account;
use near_crypto::InMemorySigner;
use near_providers::JsonRpcProvider;
use std::sync::Arc;
mod example_config;
mod utils;
use near_primitives::types::AccountId;
use std::fs::File;
use std::io;
use std::io::Read;

fn read_wasm_file() -> io::Result<Vec<u8>> {
let file_path = "examples/contract-wasm/status_message.wasm";
let mut file = File::open(file_path)?;
let mut contents = Vec::new();
file.read_to_end(&mut contents)?;
Ok(contents)
}

#[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()?;
let signer = 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);
let account: Account = example_config::create_account();

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

let wasm_code = read_wasm_file()?;
let wasm_code = example_config::read_wasm_file()?;

let response = account.deploy_contract(&wasm_code).await;

Expand All @@ -43,8 +22,3 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
Ok(())
}

// New Account ID: contract.near-api-rs.testnet
// Secret Key: ed25519:2ytXTGiGkMfpdW1JujZNebTCKRFQAFqq89fbkq9akBXy8kqqfhTqUCzmDexeNrCD1sjijMATdPWKzyCj9XnteFgN
// Public Key: ed25519:4mKgZ8e9PgSJvrVtJ4omkgmPR7ssgpCPGc2N5AGWkhfQ
// Deposit: 10000000000000000000000
62 changes: 62 additions & 0 deletions near-accounts/examples/example_config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
use near_accounts::Account;
use near_crypto::{InMemorySigner, SecretKey};
use near_primitives::types::AccountId;
use near_providers::JsonRpcProvider;
use serde::Deserialize;
use std::fs;
use std::fs::File;
use std::io;
use std::io::Read;
use std::sync::Arc;

#[derive(Debug, Deserialize)]
#[serde()]
pub struct TestConfig {
pub near_account: AccountConfig,
pub rpc_testnet_endpoint: String,
pub contract_account: AccountConfig,
}

#[derive(Debug, Deserialize)]
#[serde()]
pub struct AccountConfig {
pub account_id: String,
pub secret_key: String,
pub public_key: String,
}

pub fn get_test_config() -> TestConfig {
let the_file = "examples/resources/config/test_config.json";

let data = fs::read_to_string(the_file).expect("Unable to read file");
let test_config: TestConfig =
serde_json::from_str(data.as_str()).expect("JSON was not well-formatted");
return test_config;
}

#[allow(dead_code)]
pub fn create_account() -> Account {
let config = get_test_config();
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 = InMemorySigner::from_secret_key(signer_account_id.clone(), signer_secret_key);

let provider = Arc::new(JsonRpcProvider::new(config.rpc_testnet_endpoint.as_str()));
let signer = Arc::new(signer);

return Account::new(signer_account_id, signer, provider);
}

#[allow(dead_code)]
pub fn read_wasm_file() -> io::Result<Vec<u8>> {
let file_path = "examples/resources/contract-wasm/status_message.wasm";
let mut file = File::open(file_path)?;
let mut contents = Vec::new();
file.read_to_end(&mut contents)?;
Ok(contents)
}

#[allow(dead_code)]
fn main() {
panic!("not a binary")
}
11 changes: 7 additions & 4 deletions near-accounts/examples/function_call.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod example_config;
use near_accounts::Account;
use near_crypto::InMemorySigner;
use near_crypto::SecretKey;
Expand All @@ -12,14 +13,16 @@ use serde_json::json;
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();

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 config = example_config::get_test_config();
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 contract_id: AccountId = config.contract_account.account_id.parse().unwrap();
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

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

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