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

enhancements: added more docs #36

Merged
merged 2 commits into from
Mar 20, 2024
Merged
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
7 changes: 3 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
[workspace]

resolver = "2"
members = [
"near-providers",
"near-transactions",
"near-api",
"near-api-lib",
"near-accounts"
]

exclude = ["examples/"]

[workspace.package]
version = "0.0.1"
version = "0.1.0-alpha"
97 changes: 94 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,35 +1,126 @@
# NEAR Rust API

Rust library to interact with NEAR Protocol via RPC API. Inspired by [NEAR API JS](https://github.com/near/near-api-js)
# near-api-lib


The NEAR API library is a comprehensive Rust library designed to simplify the development of applications on the NEAR blockchain. It provides developers with essential tools and abstractions for account management, transaction building and signing, querying the blockchain state, and performing cryptographic operations, all from the comfort of Rust.


## Features

- Account Management: Easily manage NEAR accounts, allowing for the creation of new accounts, key management, and account deletion.

- Transaction Building and Signing: Utilize a builder pattern for constructing and signing transactions with support for various actions.

- Blockchain Interaction: Communicate with the NEAR blockchain using the provided JSON RPC provider to query data or send transactions.

- Cryptographic Utilities: Access cryptographic functions for key generation, signing, and verification. (Rexport for easy access to existing `near-crypto` crate.)

- NEAR Blockchain Primitives: Work directly with NEAR blockchain primitives for low-level operations. (Rexport for easy access to existing `near-primitives` crate.)




## Getting Started

Add the following to your Cargo.toml file:

```toml
[dependencies]
near-api-lib = "0.1.0-alpha"
```

### Usage

```rust
use near_api_lib::primitives::types::{AccountId, Balance, Gas};
use near_api_lib::Account;
use near_api_lib::InMemorySigner;
use near_api_lib::JsonRpcProvider;

use serde_json::json;
use std::sync::Arc;

mod utils;

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


let gas: Gas = 100_000_000_000_000; // Example amount in yoctoNEAR
// Amount to transfer to the new account
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 args_json = json!({
"new_account_id": new_account_id,
"new_public_key": new_secret_key.public_key()
});

let result = account
.function_call(contract_id, method_name, args_json, gas, amount)
.await;


println!("Response: {:#?}", result);
println!("New Account ID: {}", new_account_id);
println!("Secret Key: {}", new_secret_key);

Ok(())
}
```

### Examples

The crate includes examples that demonstrate how to use various features. To run an example, use the following command:
`cargo run --example <example_name>`

For instance, to test the `create_account` function:
`cargo run --example create_account`



## Contributing

We welcome contributions to the `near-api-lib` crate! Please feel free to submit pull requests or open issues to suggest improvements or add new features.


## Disclaimer

### General Use
The near-api-rs is provided "as is" and "as available," without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and noninfringement. In no event shall the authors, contributors, or copyright holders be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the software or the use or other dealings in the software.

### Liability
The creators of near-api-rs shall not be held liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including but not limited to procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.

### No Warranty
By using near-api-rs, you acknowledge and agree that the use of the software is entirely at your own risk. The software is provided "as is" and without warranty of any kind, either express or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose.

### Accuracy and Reliability
The authors and contributors to near-api-rs make no warranty that:
1. The software will meet your requirements or expectations.
2. The software will be uninterrupted, timely, secure, or error-free.
3. The results obtained from the use of the software will be accurate or reliable.
4. Any errors in the software will be corrected.

### Responsibility
It is your responsibility to ensure that your use of near-api-rs complies with all applicable laws and regulations, and to decide whether the software is suitable for your intended use. The authors and contributors assume no responsibility for your use of the software.

### Modifications
The authors and contributors reserve the right to modify this disclaimer at any time, and such modifications shall be effective immediately upon posting of the modified disclaimer. Your continued use of near-api-rs shall be deemed your conclusive acceptance of the modified disclaimer.
The authors and contributors reserve the right to modify this disclaimer at any time, and such modifications shall be effective immediately upon posting of the modified disclaimer. Your continued use of near-api-rs shall be deemed your conclusive acceptance of the modified disclaimer.
4 changes: 3 additions & 1 deletion near-accounts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
name = "near-accounts"
version = "0.1.0-alpha"
edition = "2021"
description = "Simplify interaction with NEAR Protocol accounts. High-level abstractions for managing accounts, deploying contracts, and executing transactions on the NEAR blockchain."
license = "MIT OR Apache-2.0"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
near-crypto = "0.20.0"
near-crypto = "0.20.1"
near-primitives = "0.20.1"
near-providers = {path ="../near-providers"}
near-transactions = {path ="../near-transactions"}
Expand Down
5 changes: 1 addition & 4 deletions near-accounts/examples/create_account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
"new_account_id": new_account_id,
"new_public_key": new_secret_key.public_key()
});
// Serialize the JSON to a Vec<u8>
// .into will convert it into Value type.
let args = serde_json::to_vec(&args_json)?.into();

let result = account
.function_call(contract_id, method_name, args, gas, amount)
.function_call(contract_id, method_name, args_json, gas, amount)
.await;

println!("response: {:#?}", result);
Expand Down
2 changes: 0 additions & 2 deletions near-accounts/examples/function_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let method_name = "set_status".to_string();

let args_json = json!({"message": "working1"});
// Serialize the JSON to a Vec<u8>
//let args = serde_json::to_vec(&args_json)?;

let result = account
.function_call(contract_id, method_name, args_json, gas, 0)
Expand Down
4 changes: 1 addition & 3 deletions near-accounts/examples/view_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args_json = json!({"account_id": "contract.near-api-rs.testnet"});
let method_name = "get_status".to_string();

let args_vec = serde_json::to_vec(&args_json)?.into();

let result = account
.view_function(contract_id, method_name, args_vec)
.view_function(contract_id, method_name, args_json)
.await;

println!("response: {:#?}", result);
Expand Down
8 changes: 5 additions & 3 deletions near-accounts/src/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use crate::access_keys::{full_access_key, function_call_access_key};
use near_crypto::{PublicKey, Signer};
use near_primitives::account::AccessKey;
use near_primitives::types::{AccountId, Balance, BlockReference, Finality, FunctionArgs, Gas};
use near_primitives::types::{AccountId, Balance, BlockReference, Finality, Gas};
use near_primitives::views::{FinalExecutionOutcomeView, QueryRequest};
use near_providers::types::query::{QueryResponseKind, RpcQueryResponse};
use near_providers::Provider;
Expand Down Expand Up @@ -351,12 +351,14 @@ impl Account {
&self,
contract_id: AccountId,
method_name: String,
args: FunctionArgs,
args: Value,
) -> Result<near_primitives::views::CallResult, Box<dyn std::error::Error>> {
let args_vec = serde_json::to_vec(&args)?.into();

let query_request = QueryRequest::CallFunction {
account_id: contract_id.clone(),
method_name: method_name.clone(),
args: args.clone(),
args: args_vec,
};

// Send the query to the NEAR blockchain
Expand Down
3 changes: 0 additions & 3 deletions near-accounts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,6 @@
//! let method_name = "set_status".to_string();

//! let args_json = json!({"message": "working1"});
//! // Serialize the JSON to a Vec<u8>
//! //let args = serde_json::to_vec(&args_json)?;

//! let result = account
//! .function_call(contract_id, method_name, args_json, gas, 0)
//! .await;
Expand Down
6 changes: 4 additions & 2 deletions near-api/Cargo.toml → near-api-lib/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
[package]
name = "near-api"
name = "near-api-lib"
version = "0.1.0-alpha"
edition = "2021"
description = "A Rust library for seamless NEAR blockchain development, offering tools for account management, transaction operations, and blockchain queries."
license = "MIT OR Apache-2.0"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
near-accounts = {path ="../near-accounts"}
near-providers = {path ="../near-providers"}
near-crypto = "0.20.0"
near-crypto = "0.20.1"
near-primitives = "0.20.1"
tokio = { version = "1", features = ["full"] }
serde_json = "1.0.85"
Expand Down
108 changes: 108 additions & 0 deletions near-api-lib/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@

# near-api-lib

The NEAR API library is a comprehensive Rust library designed to simplify the development of applications on the NEAR blockchain. It provides developers with essential tools and abstractions for account management, transaction building and signing, querying the blockchain state, and performing cryptographic operations, all from the comfort of Rust.


## Features

- Account Management: Easily manage NEAR accounts, allowing for the creation of new accounts, key management, and account deletion.

- Transaction Building and Signing: Utilize a builder pattern for constructing and signing transactions with support for various actions.

- Blockchain Interaction: Communicate with the NEAR blockchain using the provided JSON RPC provider to query data or send transactions.

- Cryptographic Utilities: Access cryptographic functions for key generation, signing, and verification. (Rexport for easy access to existing `near-crypto` crate.)

- NEAR Blockchain Primitives: Work directly with NEAR blockchain primitives for low-level operations. (Rexport for easy access to existing `near-primitives` crate.)




## Getting Started



Add the following to your Cargo.toml file:



```toml
[dependencies]
near-api-lib = "0.1.0-alpha"
```



### Usage



```rust
use near_api_lib::primitives::types::{AccountId, Balance, Gas};
use near_api_lib::Account;
use near_api_lib::InMemorySigner;
use near_api_lib::JsonRpcProvider;

use serde_json::json;
use std::sync::Arc;

mod utils;

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


let gas: Gas = 100_000_000_000_000; // Example amount in yoctoNEAR
// Amount to transfer to the new account
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 args_json = json!({
"new_account_id": new_account_id,
"new_public_key": new_secret_key.public_key()
});

let result = account
.function_call(contract_id, method_name, args_json, gas, amount)
.await;


println!("Response: {:#?}", result);
println!("New Account ID: {}", new_account_id);
println!("Secret Key: {}", new_secret_key);

Ok(())
}
```

### Examples

The crate includes examples that demonstrate how to use various features. To run an example, use the following command:
`cargo run --example <example_name>`

For instance, to test the `create_account` function:
`cargo run --example create_account`



## Contributing

We welcome contributions to the `near-api-lib` crate! Please feel free to submit pull requests or open issues to suggest improvements or add new features.
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use near_api::primitives::transaction::{Action, FunctionCallAction, Transaction};
use near_api::primitives::types::BlockReference;
use near_api::providers::jsonrpc_client::{methods, JsonRpcClient};
use near_api::providers::types::query::QueryResponseKind;
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::JsonRpcProvider;
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::providers::Provider;
use near_api_lib::providers::Provider;

use serde_json::json;

Expand Down
Loading
Loading