near-api-lib 0.1.0-alpha

A Rust library for seamless NEAR blockchain development, offering tools for account management, transaction operations, and blockchain queries.
Documentation
use near_api_lib::primitives::transaction::{Action, FunctionCallAction, Transaction};
use near_api_lib::primitives::types::BlockReference;
use near_api_lib::providers::jsonrpc_client::{methods, JsonRpcClient};
use near_api_lib::providers::types::query::QueryResponseKind;

use near_api_lib::JsonRpcProvider;

// items from traits can only be used if the trait is in scope
// can we change it somehow with better crate design?
use near_api_lib::providers::Provider;

use serde_json::json;

mod utils;

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

    let client = JsonRpcClient::connect("https://rpc.testnet.near.org");

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

    let signer_account_id = utils::input("Enter the signer Account ID: ")?.parse()?;
    let signer_secret_key = utils::input("Enter the signer's private key: ")?.parse()?;

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

    let access_key_query_response = client
        .call(methods::query::RpcQueryRequest {
            block_reference: BlockReference::latest(),
            request: near_primitives::views::QueryRequest::ViewAccessKey {
                account_id: signer.account_id.clone(),
                public_key: signer.public_key.clone(),
            },
        })
        .await?;

    let current_nonce = match access_key_query_response.kind {
        QueryResponseKind::AccessKey(access_key) => access_key.nonce,
        _ => Err("failed to extract current nonce")?,
    };

    let other_account = utils::input("Enter the account to be rated: ")?;
    let rating = utils::input("Enter a rating: ")?.parse::<f32>()?;

    let transaction = Transaction {
        signer_id: signer.account_id.clone(),
        public_key: signer.public_key.clone(),
        nonce: current_nonce + 1,
        receiver_id: "nosedive.testnet".parse()?,
        block_hash: access_key_query_response.block_hash,
        actions: vec![Action::FunctionCall(Box::new(FunctionCallAction {
            method_name: "rate".to_string(),
            args: json!({
                "account_id": other_account,
                "rating": rating,
            })
            .to_string()
            .into_bytes(),
            gas: 100_000_000_000_000, // 100 TeraGas
            deposit: 0,
        }))],
    };

    let response = provider.send_transaction(transaction.sign(&signer)).await?;

    println!("response: {:#?}", response);

    Ok(())
}