From a06e73c767b6052ba30a060ccbe1162d46411a76 Mon Sep 17 00:00:00 2001
From: garikbesson
Date: Wed, 9 Oct 2024 13:08:25 +0200
Subject: [PATCH 01/13] js + rust overview
---
docs/4.tools/near-api.md | 1045 ++++++++++++++++++++++++++++++++++++++
website/sidebars.js | 1 +
2 files changed, 1046 insertions(+)
create mode 100644 docs/4.tools/near-api.md
diff --git a/docs/4.tools/near-api.md b/docs/4.tools/near-api.md
new file mode 100644
index 00000000000..df15d344b03
--- /dev/null
+++ b/docs/4.tools/near-api.md
@@ -0,0 +1,1045 @@
+---
+id: near-api
+title: NEAR API
+sidebar_label: NEAR API
+---
+
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+## What is NEAR API
+
+There are differents libraries to interact with the NEAR blockchain. You can use it in the browser ([`near-api-js`](https://github.com/near/near-api-js)), or in server runtime ([`near-api-js`](https://github.com/near/near-api-js) for Node.js, [`near-jsonrpc-client`](https://github.com/near/near-jsonrpc-client-rs) for Rust and [`py-near`](https://github.com/pvolnov/py-near) for Python).
+
+:::tip
+To quickly get started with integrating NEAR in a web browser, read our [Web Frontend integration](/build/web3-apps/integrate-contracts) article.
+:::
+
+---
+
+## Basics
+
+### Install {#install}
+
+
+
+ Include `near-api-js` as a dependency in your package.
+
+ ```bash
+ npm i --save near-api-js
+ ```
+
+
+
+ ```bash
+ cargo add near-jsonrpc-client
+ ```
+
+
+
+
+
+### Import {#import}
+
+
+
+ You can use the API library in the browser, or in Node.js runtime. Some features are available only in one of the environments. For example, the `WalletConnection` is only for the browser, and there are different `KeyStore` providers for each environment.
+
+ ```js
+ import * as nearAPI from "near-api-js";
+ ```
+
+
+
+ Each one of the valid JSON RPC methods are defined in the methods module.
+ ```rust
+ use near_jsonrpc_client::methods;
+ ```
+
+
+
+
+
+### Connecting to NEAR {#connect}
+
+
+
+
+ The object returned from `connect` is your entry-point for all commands in the API.
+ To sign a transaction you'll need a [`KeyStore`](#key-store) to create a connection.
+
+ ```js
+ const { connect } = nearAPI;
+
+ const connectionConfig = {
+ networkId: "testnet",
+ keyStore: myKeyStore, // first create a key store
+ nodeUrl: "https://rpc.testnet.near.org",
+ walletUrl: "https://testnet.mynearwallet.com/",
+ helperUrl: "https://helper.testnet.near.org",
+ explorerUrl: "https://testnet.nearblocks.io",
+ };
+ const nearConnection = await connect(connectionConfig);
+ ```
+
+
+ Mainnet/Localnet connection
+
+ ```js
+ // Mainnet config example
+ const connectionConfig = {
+ networkId: "mainnet",
+ keyStore: myKeyStore, // first create a key store
+ nodeUrl: "https://rpc.mainnet.near.org",
+ walletUrl: "https://wallet.mainnet.near.org",
+ helperUrl: "https://helper.mainnet.near.org",
+ explorerUrl: "https://nearblocks.io",
+ };
+
+ // Localnet config example
+ const connectionConfig = {
+ networkId: "local",
+ nodeUrl: "http://localhost:3030",
+ walletUrl: "http://localhost:4000/wallet",
+ };
+ ```
+
+
+
+
+ #### Key Store
+
+ If you sign transactions, you need to create a _Key Store_. In the browser, the LocalStorage KeyStore will be used once you ask your user to Sign In with the Wallet.
+
+ ```js
+ /* Browser
+ Creates keyStore using private key in local storage
+ */
+ const { keyStores } = nearAPI;
+ const myKeyStore = new keyStores.BrowserLocalStorageKeyStore();
+
+ /* Credentials Directory
+ Creates a keyStore that searches for keys in .near-credentials
+ Requires credentials stored locally by using a NEAR-CLI command: `near login`
+ https://docs.near.org/tools/cli#near-login
+ */
+ const { keyStores } = nearAPI;
+ const homedir = require("os").homedir();
+ const CREDENTIALS_DIR = ".near-credentials";
+ const credentialsPath = require("path").join(homedir, CREDENTIALS_DIR);
+ const myKeyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath);
+
+ /* File
+ Creates keyStore from a provided file
+ You will need to pass the location of the .json key pair
+ */
+ const { KeyPair, keyStores } = require("near-api-js");
+ const fs = require("fs");
+ const homedir = require("os").homedir();
+
+ const ACCOUNT_ID = "near-example.testnet"; // NEAR account tied to the keyPair
+ const NETWORK_ID = "testnet";
+ // path to your custom keyPair location (ex. function access key for example account)
+ const KEY_PATH = "/.near-credentials/near-example-testnet/get_token_price.json";
+
+ const credentials = JSON.parse(fs.readFileSync(homedir + KEY_PATH));
+ const myKeyStore = new keyStores.InMemoryKeyStore();
+ myKeyStore.setKey(
+ NETWORK_ID,
+ ACCOUNT_ID,
+ KeyPair.fromString(credentials.private_key)
+ );
+
+ /* Private key string
+ Creates keyStore from a private key string
+ You can define your key here or use an environment variable
+ */
+ const { keyStores, KeyPair } = nearAPI;
+ const myKeyStore = new keyStores.InMemoryKeyStore();
+ const PRIVATE_KEY =
+ "by8kdJoJHu7uUkKfoaLd2J2Dp1q1TigeWMG123pHdu9UREqPcshCM223kWadm";
+ // creates a public / private key pair using the provided private key
+ const keyPair = KeyPair.fromString(PRIVATE_KEY);
+ // adds the keyPair you created to keyStore
+ await myKeyStore.setKey("testnet", "example-account.testnet", keyPair);
+ ```
+
+
+
+ ```rust
+ use near_jsonrpc_client::JsonRpcClient;
+
+ let testnet_client = JsonRpcClient::connect("https://rpc.testnet.near.org");
+ ```
+
+
+
+
+
+### RPC Failover
+
+RPC providers can experience intermittent downtime, connectivity issues, or rate limits that cause client transactions to fail. This can be prevented by using the `FailoverRpcProvider` that supports multiple RPC providers.
+
+
+
+
+ ```js
+ const jsonProviders = [
+ new JsonRpcProvider({
+ url: 'https://rpc.mainnet.near.org',
+ }),
+ new JsonRpcProvider(
+ {
+ url: 'https://another-rpc.cloud.com',
+ headers: { 'X-Api-Key': 'some string' },
+ },
+ { retries: 3, backoff: 2, wait: 500 }
+ ),
+ ];
+ const provider = new FailoverRpcProvider(jsonProviders);
+
+ await connect({
+ networkId: 'mainnet',
+ provider: provider,
+ // this isn't used if `provider` is specified, but is still required for backward compatibility
+ nodeUrl: 'https://rpc.mainnet.near.org',
+ });
+ ```
+
+
+
+
+---
+
+## Account
+
+### Get Account {#get-account}
+
+This will return an Account object for you to interact with.
+
+
+
+
+ ```js
+ const account = await nearConnection.account("example-account.testnet");
+ ```
+
+
+
+
+
+
+### Get Account Balance {#get-account-balance}
+
+
+
+
+ ```js
+ // gets account balance
+ const account = await nearConnection.account("example-account.testnet");
+ const accountBalance = await account.getAccountBalance();
+ ```
+
+
+
+
+
+
+### Get Account Details {#get-account-details}
+
+Returns information about an account, such as authorized apps.
+
+
+
+
+
+ ```js
+ // gets account details in terms of authorized apps and transactions
+ const account = await nearConnection.account("example-account.testnet");
+ const accountDetails = await account.getAccountDetails();
+ ```
+
+
+
+
+
+
+### Get Account State {#get-account-state}
+
+Get basic account information, such as amount of tokens the account has or the amount of storage it uses.
+
+
+
+
+ ```js
+ const account = await nearConnection.account("example-account.testnet");
+ const accountState = await account.state();
+ ```
+
+
+
+ ```rust
+ use near_jsonrpc_client::methods;
+ use near_jsonrpc_primitives::types::query::QueryResponseKind;
+ use near_primitives::types::{AccountId, BlockReference, Finality};
+ use near_primitives::views::QueryRequest;
+
+ mod utils;
+
+ #[tokio::main]
+ async fn main() -> Result<(), Box> {
+ env_logger::init();
+
+ let client = utils::select_network()?;
+
+ let account_id: AccountId = utils::input("Enter an Account ID to lookup: ")?.parse()?;
+
+ let request = methods::query::RpcQueryRequest {
+ block_reference: BlockReference::Finality(Finality::Final),
+ request: QueryRequest::ViewAccount { account_id },
+ };
+
+ let response = client.call(request).await?;
+
+ if let QueryResponseKind::ViewAccount(result) = response.kind {
+ println!("{:#?}", result);
+ }
+
+ Ok(())
+ }
+ ```
+
+
+
+
+
+### Create Account {#create-account}
+
+Create a sub-account.
+
+
+
+
+ ```js
+ // creates a sub-account using funds from the account used to create it.
+ const account = await nearConnection.account("example-account.testnet");
+ await account.createAccount(
+ "sub.example-account.testnet", // sub-account name
+ "8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc", // public key for sub account
+ "10000000000000000000" // initial balance for new account in yoctoNEAR
+ );
+ ```
+
+ For creating .near or .testnet accounts please refer to the [cookbook](https://github.com/near/near-api-js/tree/master/packages/cookbook/accounts).
+
+
+
+
+ ```rust
+ //! Creates an account on the network.
+ //!
+ //! Creates either;
+ //! - a top-level mainnet / testnet account
+ //! - or a sub-account for any account on the network.
+ //!
+ //! top-level account example: `miraclx.near` creates `foobar.near`
+ //! sub-account example: `miraclx.near` creates `test.miraclx.near`
+ //!
+ //! This script is interactive.
+
+ use near_crypto::Signer;
+ use near_jsonrpc_client::methods::broadcast_tx_commit::RpcTransactionError;
+ use near_jsonrpc_client::{methods, JsonRpcClient};
+ use near_jsonrpc_primitives::types::query::QueryResponseKind;
+ use near_jsonrpc_primitives::types::transactions::TransactionInfo;
+ use near_primitives::hash::CryptoHash;
+ use near_primitives::transaction::{
+ Action, AddKeyAction, CreateAccountAction, FunctionCallAction, Transaction, TransactionV0,
+ TransferAction,
+ };
+ use near_primitives::types::{AccountId, BlockReference};
+ use near_primitives::views::{FinalExecutionStatus, TxExecutionStatus};
+
+ use serde_json::json;
+ use tokio::time;
+
+ mod utils;
+
+ async fn account_exists(
+ client: &JsonRpcClient,
+ account_id: &AccountId,
+ ) -> Result> {
+ let access_key_query_response = client
+ .call(methods::query::RpcQueryRequest {
+ block_reference: BlockReference::latest(),
+ request: near_primitives::views::QueryRequest::ViewAccount {
+ account_id: account_id.clone(),
+ },
+ })
+ .await;
+
+ match access_key_query_response {
+ Ok(_) => Ok(true),
+ Err(near_jsonrpc_client::errors::JsonRpcError::ServerError(
+ near_jsonrpc_client::errors::JsonRpcServerError::HandlerError(
+ near_jsonrpc_primitives::types::query::RpcQueryError::UnknownAccount { .. },
+ ),
+ )) => Ok(false),
+ Err(res) => Err(res)?,
+ }
+ }
+
+ async fn get_current_nonce(
+ client: &JsonRpcClient,
+ account_id: &AccountId,
+ public_key: &near_crypto::PublicKey,
+ ) -> Result
+
+
+
+
+### Delete Account {#delete-account}
+
+
+
+
+ ```js
+ // deletes account found in the `account` object
+ // transfers remaining account balance to the accountId passed as an argument
+ const account = await nearConnection.account("example-account.testnet");
+ await account.deleteAccount("beneficiary-account.testnet");
+ ```
+
+
+
+
+---
+
+## Transactions
+
+### Send Tokens {#send-tokens}
+
+Transfer NEAR tokens between accounts. This returns an object with transaction and receipts outcomes and status.
+
+
+
+
+ ```js
+ const account = await nearConnection.account("sender-account.testnet");
+ await account.sendMoney(
+ "receiver-account.testnet", // receiver account
+ "1000000000000000000000000" // amount in yoctoNEAR
+ );
+ ```
+
+
+
+
+
+### View
+
+
+
+
+ ```js
+ import { providers } from 'near-api-js';
+
+ const url = `https://rpc.${this.networkId}.near.org`;
+ const provider = new providers.JsonRpcProvider({ url });
+
+ const response = await provider.query({
+ request_type: 'call_function',
+ account_id: contractId,
+ method_name: method,
+ args_base64: Buffer.from(JSON.stringify(args)).toString('base64'),
+ finality: 'optimistic',
+ });
+
+ const result = JSON.parse(Buffer.from(res.result).toString());
+ ```
+
+
+
+ ```rust
+ use near_jsonrpc_client::{methods, JsonRpcClient};
+ use near_jsonrpc_primitives::types::query::QueryResponseKind;
+ use near_primitives::types::{BlockReference, Finality, FunctionArgs};
+ use near_primitives::views::QueryRequest;
+
+ use serde::Deserialize;
+ use serde_json::{from_slice, json};
+
+ mod utils;
+
+ #[derive(Debug, Deserialize)]
+ pub struct AccountStatus {
+ pub rating: f32,
+ pub given: u64,
+ pub received: u64,
+ }
+
+ #[tokio::main]
+ async fn main() -> Result<(), Box> {
+ env_logger::init();
+
+ let client = JsonRpcClient::connect("https://rpc.testnet.near.org");
+
+ let account_id = utils::input("Enter the account to view: ")?;
+
+ let request = methods::query::RpcQueryRequest {
+ block_reference: BlockReference::Finality(Finality::Final),
+ request: QueryRequest::CallFunction {
+ account_id: "nosedive.testnet".parse()?,
+ method_name: "status".to_string(),
+ args: FunctionArgs::from(
+ json!({
+ "account_id": account_id,
+ })
+ .to_string()
+ .into_bytes(),
+ ),
+ },
+ };
+
+ let response = client.call(request).await?;
+
+ if let QueryResponseKind::CallResult(result) = response.kind {
+ println!("{:#?}", from_slice::(&result.result)?);
+ }
+
+ Ok(())
+ }
+ ```
+
+
+
+
+
+### Call
+
+
+
+
+ ```js
+ import { connect, transactions, keyStores } from "near-api-js";
+
+ const account = await nearConnection.account("example-account.testnet");
+ const result = await account.signAndSendTransaction({
+ receiverId: "example-contract.testnet",
+ actions: [
+ transactions.functionCall(
+ "new",
+ Buffer.from(JSON.stringify(newArgs)),
+ 10000000000000,
+ "0"
+ ),
+ ],
+ });
+ ```
+
+
+
+ ```rust
+ use near_crypto::Signer;
+ use near_jsonrpc_client::{methods, JsonRpcClient};
+ use near_jsonrpc_primitives::types::query::QueryResponseKind;
+ use near_jsonrpc_primitives::types::transactions::{RpcTransactionError, TransactionInfo};
+ use near_primitives::transaction::{Action, FunctionCallAction, Transaction, TransactionV0};
+ use near_primitives::types::BlockReference;
+ use near_primitives::views::TxExecutionStatus;
+
+ use serde_json::json;
+ use tokio::time;
+
+ mod utils;
+
+ #[tokio::main]
+ async fn main() -> Result<(), Box> {
+ env_logger::init();
+
+ let client = JsonRpcClient::connect("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::()?;
+
+ let transaction = TransactionV0 {
+ 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 request = methods::broadcast_tx_async::RpcBroadcastTxAsyncRequest {
+ signed_transaction: Transaction::V0(transaction).sign(&Signer::InMemory(signer.clone())),
+ };
+
+ let sent_at = time::Instant::now();
+ let tx_hash = client.call(request).await?;
+
+ loop {
+ let response = client
+ .call(methods::tx::RpcTransactionStatusRequest {
+ transaction_info: TransactionInfo::TransactionId {
+ tx_hash,
+ sender_account_id: signer.account_id.clone(),
+ },
+ wait_until: TxExecutionStatus::Executed,
+ })
+ .await;
+ let received_at = time::Instant::now();
+ let delta = (received_at - sent_at).as_secs();
+
+ if delta > 60 {
+ Err("time limit exceeded for the transaction to be recognized")?;
+ }
+
+ match response {
+ Err(err) => match err.handler_error() {
+ Some(
+ RpcTransactionError::TimeoutError
+ | RpcTransactionError::UnknownTransaction { .. },
+ ) => {
+ time::sleep(time::Duration::from_secs(2)).await;
+ continue;
+ }
+ _ => Err(err)?,
+ },
+ Ok(response) => {
+ println!("response gotten after: {}s", delta);
+ println!("response: {:#?}", response);
+ break;
+ }
+ }
+ }
+
+ Ok(())
+ }
+ ```
+
+
+
+
+
+### Deploy a Contract {#deploy-a-contract}
+
+You can deploy a contract from a compiled WASM file. This returns an object with transaction and receipts outcomes and status.
+
+
+
+
+ ```js
+ const account = await nearConnection.account("example-account.testnet");
+ const transactionOutcome = await account.deployContract(
+ fs.readFileSync("example-file.wasm")
+ );
+ ```
+
+
+
+---
+
+## Keys
+
+You can get and manage keys for an account.
+
+### Add Function Access Key {#add-function-access-key}
+
+
+
+
+ ```js
+ const account = await nearConnection.account("example-account.testnet");
+ await account.addKey(
+ "8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc", // public key for new account
+ "example-account.testnet", // contract this key is allowed to call (optional)
+ "example_method", // methods this key is allowed to call (optional)
+ "2500000000000" // allowance key can use to call methods (optional)
+ );
+ ```
+
+
+
+
+
+
+### Add Full Access Key {#add-full-access-key}
+
+
+
+
+ ```js
+ // takes public key as string for argument
+ const account = await nearConnection.account("example-account.testnet");
+ await account.addKey("8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc");
+ ```
+
+
+
+
+
+
+### Get All Access Keys {#get-all-access-keys}
+
+
+
+
+ ```js
+ const account = await nearConnection.account("example-account.testnet");
+ await account.getAccessKeys();
+ ```
+
+
+
+
+ ```rust
+ use near_jsonrpc_client::methods;
+ use near_jsonrpc_primitives::types::query::QueryResponseKind;
+ use near_primitives::types::BlockReference;
+
+ mod utils;
+
+ fn indent(indentation: usize, s: String) -> String {
+ let mut lines = s.split_inclusive("\n");
+ let mut r = lines.next().unwrap().to_string();
+ for l in lines {
+ r.push_str(&" ".repeat(indentation - 3));
+ r.push_str("\x1b[38;5;244m>\x1b[0m ");
+ r.push_str(l);
+ }
+ r
+ }
+
+ #[tokio::main]
+ async fn main() -> Result<(), Box> {
+ env_logger::init();
+
+ let client = utils::select_network()?;
+
+ let account_id = utils::input("Enter the Account ID whose keys we're listing: ")?.parse()?;
+
+ let access_key_query_response = client
+ .call(methods::query::RpcQueryRequest {
+ block_reference: BlockReference::latest(),
+ request: near_primitives::views::QueryRequest::ViewAccessKeyList { account_id },
+ })
+ .await?;
+
+ if let QueryResponseKind::AccessKeyList(response) = access_key_query_response.kind {
+ for access_key in response.keys {
+ println!("π [{}]", access_key.public_key);
+ println!(" \u{21b3} nonce: {}", access_key.access_key.nonce);
+ println!(
+ " \u{21b3} permission: {}",
+ indent(20, format!("{:#?}", access_key.access_key.permission))
+ );
+ }
+ }
+
+ Ok(())
+ }
+ ```
+
+
+
+
+
+### Delete Access Key {#delete-access-key}
+
+
+
+
+ ```js
+ const account = await nearConnection.account("example-account.testnet");
+ await account.deleteKey("8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc");
+ ```
+
+
+
+
+---
+
+## Utilities
+
+### NEAR => yoctoNEAR {#near--yoctonear}
+
+
+
+
+ ```js
+ // converts NEAR amount into yoctoNEAR (10^-24)
+
+ const { utils } = nearAPI;
+ const amountInYocto = utils.format.parseNearAmount("1");
+ ```
+
+
+
+
+
+
+### YoctoNEAR => NEAR {#yoctonear--near}
+
+
+
+
+ ```js
+ // converts yoctoNEAR (10^-24) amount into NEAR
+
+ const { utils } = nearAPI;
+ const amountInNEAR = utils.format.formatNearAmount("1000000000000000000000000");
+ ```
+
+
+
+
+---
+
+## Additional resources
+
+
+
+
+ - [Handling Passphrases](https://github.com/near/near-seed-phrase)
+ - [Type Docs](https://near.github.io/near-api-js)
+
+
+
\ No newline at end of file
diff --git a/website/sidebars.js b/website/sidebars.js
index 54c61defd8b..54d82eac36b 100644
--- a/website/sidebars.js
+++ b/website/sidebars.js
@@ -529,6 +529,7 @@ const sidebar = {
"type": "html",
"value": " Developer Tools "
},
+ "tools/near-api",
{
"type": "category",
"label": "JavaScript API",
From 8d0ffcb9f1a38c95d68d6ae211a7d9d4e61f3bca Mon Sep 17 00:00:00 2001
From: gagdiez
Date: Wed, 9 Oct 2024 15:00:26 +0200
Subject: [PATCH 02/13] minor improvements
---
docs/4.tools/near-api.md | 87 ++++++++++++++++++++++++++++--------
website/docusaurus.config.js | 2 +-
2 files changed, 70 insertions(+), 19 deletions(-)
diff --git a/docs/4.tools/near-api.md b/docs/4.tools/near-api.md
index df15d344b03..9056f58379c 100644
--- a/docs/4.tools/near-api.md
+++ b/docs/4.tools/near-api.md
@@ -7,19 +7,22 @@ sidebar_label: NEAR API
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
-## What is NEAR API
+The NEAR API is a set of libraries that allow you to interact with the NEAR blockchain. You can use it to create accounts, send tokens, deploy contracts, and more.
-There are differents libraries to interact with the NEAR blockchain. You can use it in the browser ([`near-api-js`](https://github.com/near/near-api-js)), or in server runtime ([`near-api-js`](https://github.com/near/near-api-js) for Node.js, [`near-jsonrpc-client`](https://github.com/near/near-jsonrpc-client-rs) for Rust and [`py-near`](https://github.com/pvolnov/py-near) for Python).
+The API is available in multiple languages, including:
+- JavaScript: [`near-api-js`](https://github.com/near/near-api-js)
+- Rust: [`near-jsonrpc-client`](https://github.com/near/near-jsonrpc-client-rs)
+- Python: [`py-near`](https://github.com/pvolnov/py-near)
-:::tip
-To quickly get started with integrating NEAR in a web browser, read our [Web Frontend integration](/build/web3-apps/integrate-contracts) article.
+For example, you could use [`near-api-js`](https://github.com/near/near-api-js) to create web applications or backend services written in node.js servers.
+
+:::tip Wallet Integration
+To allow users to login into your web application using a wallet you will need the `wallet-selector`. Read more in our [Web Frontend integration](/build/web3-apps/integrate-contracts) article
:::
---
-## Basics
-
-### Install {#install}
+## Install {#install}
@@ -28,6 +31,15 @@ To quickly get started with integrating NEAR in a web browser, read our [Web Fro
```bash
npm i --save near-api-js
```
+
+ :::tip Static HTML
+ If you are building a site without using `npm`, you can include the library directly in your HTML file through a CDN.
+
+ ```html
+
+ ```
+ :::
+
@@ -111,6 +123,21 @@ To quickly get started with integrating NEAR in a web browser, read our [Web Fro
If you sign transactions, you need to create a _Key Store_. In the browser, the LocalStorage KeyStore will be used once you ask your user to Sign In with the Wallet.
+
+
+
+ ```js
+ Hello
+ ```
+
+
+
+ ```js
+ World
+ ```
+
+
+
```js
/* Browser
Creates keyStore using private key in local storage
@@ -213,7 +240,7 @@ RPC providers can experience intermittent downtime, connectivity issues, or rate
## Account
-### Get Account {#get-account}
+### Instantiate Account {#load-account}
This will return an Account object for you to interact with.
@@ -227,9 +254,13 @@ This will return an Account object for you to interact with.
+:::warning
+In order to be able to use the account, its credentials must be stored in the [key store](#key-store)
+:::
+
-### Get Account Balance {#get-account-balance}
+### Get Balance {#get-account-balance}
@@ -245,11 +276,10 @@ This will return an Account object for you to interact with.
-### Get Account Details {#get-account-details}
+### Get Details {#get-account-details}
Returns information about an account, such as authorized apps.
-
@@ -264,7 +294,7 @@ Returns information about an account, such as authorized apps.
-### Get Account State {#get-account-state}
+### Get State {#get-account-state}
Get basic account information, such as amount of tokens the account has or the amount of storage it uses.
@@ -313,7 +343,7 @@ Get basic account information, such as amount of tokens the account has or the a
-### Create Account {#create-account}
+### Create Sub-Account {#create-account}
Create a sub-account.
@@ -330,7 +360,25 @@ Create a sub-account.
);
```
- For creating .near or .testnet accounts please refer to the [cookbook](https://github.com/near/near-api-js/tree/master/packages/cookbook/accounts).
+
+ Creating .near or .testnet accounts
+
+ In order to create .near or .testnet accounts, you need to make a function call to the top-level-domain (i.e. `near` or `testnet`), calling `create_account`:
+
+ ```js
+ return await creatorAccount.functionCall({
+ contractId: "testnet",
+ methodName: "create_account",
+ args: {
+ new_account_id: "new-account.testnet",
+ new_public_key: "ed25519:2ASWccunZMBSygADWG2pXuHM6jWdnzLzWFU6r7wtaHYt",
+ },
+ gas: "300000000000000",
+ attachedDeposit: utils.format.parseNearAmount(amount),
+ });
+ ```
+
+
@@ -643,7 +691,9 @@ Transfer NEAR tokens between accounts. This returns an object with transaction a
-### View
+### View Function
+
+View functions are read-only functions that don't change the state of the contract. We can call these functions without instantiating an account or a key store.
@@ -653,11 +703,12 @@ Transfer NEAR tokens between accounts. This returns an object with transaction a
const url = `https://rpc.${this.networkId}.near.org`;
const provider = new providers.JsonRpcProvider({ url });
+ const args = { greeting: 'hello' };
const response = await provider.query({
request_type: 'call_function',
- account_id: contractId,
- method_name: method,
+ account_id: 'hello.near-examples.testnet',
+ method_name: 'get_greeting',
args_base64: Buffer.from(JSON.stringify(args)).toString('base64'),
finality: 'optimistic',
});
@@ -722,7 +773,7 @@ Transfer NEAR tokens between accounts. This returns an object with transaction a
-### Call
+### Call Function
diff --git a/website/docusaurus.config.js b/website/docusaurus.config.js
index 62a8bb7bbfc..1385eac31ae 100644
--- a/website/docusaurus.config.js
+++ b/website/docusaurus.config.js
@@ -148,7 +148,7 @@ const config = {
type: 'html',
value: ' Essentials ',
},
- { label: 'NEAR API', to: '/tools/near-api-js/quick-reference' },
+ { label: 'NEAR API', to: '/tools/near-api' },
{ label: 'NEAR SDK', to: '/tools/sdk' },
{ label: 'NEAR CLI', to: '/tools/near-cli' },
{
From b75bfddc85bee4cd40f8958e382543c10bf85d8a Mon Sep 17 00:00:00 2001
From: garikbesson
Date: Wed, 9 Oct 2024 16:56:41 +0200
Subject: [PATCH 03/13] style fixes
---
docs/4.tools/near-api.md | 260 +++++++++++++++++++++++++++++----------
1 file changed, 196 insertions(+), 64 deletions(-)
diff --git a/docs/4.tools/near-api.md b/docs/4.tools/near-api.md
index 9056f58379c..4862b8f7cfe 100644
--- a/docs/4.tools/near-api.md
+++ b/docs/4.tools/near-api.md
@@ -22,10 +22,10 @@ To allow users to login into your web application using a wallet you will need t
---
-## Install {#install}
+## Install
-
+
Include `near-api-js` as a dependency in your package.
```bash
@@ -41,7 +41,7 @@ To allow users to login into your web application using a wallet you will need t
:::
-
+
```bash
cargo add near-jsonrpc-client
@@ -54,14 +54,14 @@ To allow users to login into your web application using a wallet you will need t
### Import {#import}
-
+
You can use the API library in the browser, or in Node.js runtime. Some features are available only in one of the environments. For example, the `WalletConnection` is only for the browser, and there are different `KeyStore` providers for each environment.
```js
import * as nearAPI from "near-api-js";
```
-
+
Each one of the valid JSON RPC methods are defined in the methods module.
```rust
@@ -75,7 +75,7 @@ To allow users to login into your web application using a wallet you will need t
### Connecting to NEAR {#connect}
-
+
The object returned from `connect` is your entry-point for all commands in the API.
To sign a transaction you'll need a [`KeyStore`](#key-store) to create a connection.
@@ -123,43 +123,38 @@ To allow users to login into your web application using a wallet you will need t
If you sign transactions, you need to create a _Key Store_. In the browser, the LocalStorage KeyStore will be used once you ask your user to Sign In with the Wallet.
-
-
-
- ```js
- Hello
- ```
-
-
-
- ```js
- World
- ```
-
-
+
+
```js
- /* Browser
- Creates keyStore using private key in local storage
- */
+ // creates keyStore using private key in local storage
+
const { keyStores } = nearAPI;
const myKeyStore = new keyStores.BrowserLocalStorageKeyStore();
+ ```
+
+
+
+
+ ```js
+ // creates a keyStore that searches for keys in .near-credentials
+ // requires credentials stored locally by using a NEAR-CLI command: `near login`
+ // https://docs.near.org/tools/cli#near-login
- /* Credentials Directory
- Creates a keyStore that searches for keys in .near-credentials
- Requires credentials stored locally by using a NEAR-CLI command: `near login`
- https://docs.near.org/tools/cli#near-login
- */
const { keyStores } = nearAPI;
const homedir = require("os").homedir();
const CREDENTIALS_DIR = ".near-credentials";
const credentialsPath = require("path").join(homedir, CREDENTIALS_DIR);
const myKeyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath);
+ ```
+
+
+
+
+ ```js
+ // creates keyStore from a provided file
+ // you will need to pass the location of the .json key pair
- /* File
- Creates keyStore from a provided file
- You will need to pass the location of the .json key pair
- */
const { KeyPair, keyStores } = require("near-api-js");
const fs = require("fs");
const homedir = require("os").homedir();
@@ -176,11 +171,15 @@ To allow users to login into your web application using a wallet you will need t
ACCOUNT_ID,
KeyPair.fromString(credentials.private_key)
);
+ ```
+
+
+
+
+ ```js
+ // creates keyStore from a private key string
+ // you can define your key here or use an environment variable
- /* Private key string
- Creates keyStore from a private key string
- You can define your key here or use an environment variable
- */
const { keyStores, KeyPair } = nearAPI;
const myKeyStore = new keyStores.InMemoryKeyStore();
const PRIVATE_KEY =
@@ -190,8 +189,33 @@ To allow users to login into your web application using a wallet you will need t
// adds the keyPair you created to keyStore
await myKeyStore.setKey("testnet", "example-account.testnet", keyPair);
```
+
+
+
+
+
+ Window error using `Node.js`
+
+ You're maybe using a KeyStore that's for the browser. Instead, use a [filesystem key](/tools/near-api-js/quick-reference#key-store) or private key string.
+
+ **Browser KeyStore:**
+
+ ```js
+ const { keyStores } = require("near-api-js");
+ const keyStore = new keyStores.BrowserLocalStorageKeyStore();
+ ```
+
+ **FileSystem KeyStore:**
+
+ ```js
+ const { keyStores } = require("near-api-js");
+ const KEY_PATH = "~./near-credentials/testnet/example-account.json";
+ const keyStore = new keyStores.UnencryptedFileSystemKeyStore(KEY_PATH);
+ ```
+
+
-
+
```rust
use near_jsonrpc_client::JsonRpcClient;
@@ -208,7 +232,7 @@ To allow users to login into your web application using a wallet you will need t
RPC providers can experience intermittent downtime, connectivity issues, or rate limits that cause client transactions to fail. This can be prevented by using the `FailoverRpcProvider` that supports multiple RPC providers.
-
+
```js
const jsonProviders = [
@@ -240,12 +264,12 @@ RPC providers can experience intermittent downtime, connectivity issues, or rate
## Account
-### Instantiate Account {#load-account}
+### Instantiate Account {#instantiate-account}
This will return an Account object for you to interact with.
-
+
```js
const account = await nearConnection.account("example-account.testnet");
@@ -260,10 +284,10 @@ In order to be able to use the account, its credentials must be stored in the [k
-### Get Balance {#get-account-balance}
+### Get Balance {#get-balance}
-
+
```js
// gets account balance
@@ -276,12 +300,12 @@ In order to be able to use the account, its credentials must be stored in the [k
-### Get Details {#get-account-details}
+### Get Details {#get-details}
Returns information about an account, such as authorized apps.
-
+
```js
// gets account details in terms of authorized apps and transactions
@@ -294,19 +318,19 @@ Returns information about an account, such as authorized apps.
-### Get State {#get-account-state}
+### Get State {#get-state}
Get basic account information, such as amount of tokens the account has or the amount of storage it uses.
-
+
```js
const account = await nearConnection.account("example-account.testnet");
const accountState = await account.state();
```
-
+
```rust
use near_jsonrpc_client::methods;
@@ -348,7 +372,7 @@ Get basic account information, such as amount of tokens the account has or the a
Create a sub-account.
-
+
```js
// creates a sub-account using funds from the account used to create it.
@@ -381,7 +405,7 @@ Create a sub-account.
-
+
```rust
//! Creates an account on the network.
@@ -656,7 +680,7 @@ Create a sub-account.
### Delete Account {#delete-account}
-
+
```js
// deletes account found in the `account` object
@@ -677,7 +701,7 @@ Create a sub-account.
Transfer NEAR tokens between accounts. This returns an object with transaction and receipts outcomes and status.
-
+
```js
const account = await nearConnection.account("sender-account.testnet");
@@ -696,7 +720,7 @@ Transfer NEAR tokens between accounts. This returns an object with transaction a
View functions are read-only functions that don't change the state of the contract. We can call these functions without instantiating an account or a key store.
-
+
```js
import { providers } from 'near-api-js';
@@ -716,7 +740,7 @@ View functions are read-only functions that don't change the state of the contra
const result = JSON.parse(Buffer.from(res.result).toString());
```
-
+
```rust
use near_jsonrpc_client::{methods, JsonRpcClient};
@@ -776,7 +800,7 @@ View functions are read-only functions that don't change the state of the contra
### Call Function
-
+
```js
import { connect, transactions, keyStores } from "near-api-js";
@@ -795,7 +819,7 @@ View functions are read-only functions that don't change the state of the contra
});
```
-
+
```rust
use near_crypto::Signer;
@@ -910,12 +934,120 @@ View functions are read-only functions that don't change the state of the contra
+### Batch Transactions
+
+
+
+
+ You may batch send transactions by using the `signAndSendTransaction({})` method from `account`. This method takes an array of transaction actions, and if one fails, the entire operation will fail. Here's a simple example:
+
+ ```js
+ const { connect, transactions, keyStores } = require("near-api-js");
+ const fs = require("fs");
+ const path = require("path");
+ const homedir = require("os").homedir();
+
+ const CREDENTIALS_DIR = ".near-credentials";
+ const CONTRACT_NAME = "spf.idea404.testnet";
+ const WASM_PATH = path.join(__dirname, "../build/uninitialized_nft.wasm");
+
+ const credentialsPath = path.join(homedir, CREDENTIALS_DIR);
+ const keyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath);
+
+ const config = {
+ keyStore,
+ networkId: "testnet",
+ nodeUrl: "https://rpc.testnet.near.org",
+ };
+
+ sendTransactions();
+
+ async function sendTransactions() {
+ const near = await connect({ ...config, keyStore });
+ const account = await near.account(CONTRACT_NAME);
+ const args = { some_field: 1, another_field: "hello" };
+
+ const balanceBefore = await account.getAccountBalance();
+ console.log("Balance before:", balanceBefore);
+
+ try {
+ const result = await account.signAndSendTransaction({
+ receiverId: CONTRACT_NAME,
+ actions: [
+ transactions.deployContract(fs.readFileSync(WASM_PATH)), // Contract does not get deployed
+ transactions.functionCall("new", Buffer.from(JSON.stringify(args)), 10000000000000, "0"), // this call fails
+ transactions.transfer("1" + "0".repeat(24)), // 1 NEAR is not transferred either
+ ],
+ });
+ console.log(result);
+ } catch (e) {
+ console.log("Error:", e);
+ }
+
+ const balanceAfter = await account.getAccountBalance();
+ console.log("Balance after:", balanceAfter);
+ }
+ ```
+
+
+ Response Example
+ ```bash
+ Balance before: {
+ total: '49987878054959838200000000',
+ stateStaked: '4555390000000000000000000',
+ staked: '0',
+ available: '45432488054959838200000000'
+ }
+ Receipts: 2PPueY6gnA4YmmQUzc8DytNBp4PUpgTDhmEjRSHHVHBd, 3isLCW9SBH1MrPjeEPAmG9saHLj9Z2g7HxzfBdHmaSaG
+ Failure [spf.idea404.testnet]: Error: {"index":1,"kind":{"ExecutionError":"Smart contract panicked: panicked at 'Failed to deserialize input from JSON.: Error(\"missing field `owner_id`\", line: 1, column: 40)', nft/src/lib.rs:47:1"}}
+ Error: ServerTransactionError: {"index":1,"kind":{"ExecutionError":"Smart contract panicked: panicked at 'Failed to deserialize input from JSON.: Error(\"missing field `owner_id`\", line: 1, column: 40)', nft/src/lib.rs:47:1"}}
+ at parseResultError (/Users/dennis/Code/naj-test/node_modules/near-api-js/lib/utils/rpc_errors.js:31:29)
+ at Account. (/Users/dennis/Code/naj-test/node_modules/near-api-js/lib/account.js:156:61)
+ at Generator.next ()
+ at fulfilled (/Users/dennis/Code/naj-test/node_modules/near-api-js/lib/account.js:5:58)
+ at processTicksAndRejections (node:internal/process/task_queues:96:5) {
+ type: 'FunctionCallError',
+ context: undefined,
+ index: 1,
+ kind: {
+ ExecutionError: "Smart contract panicked: panicked at \'Failed to deserialize input from JSON.: Error("missing field `owner_id`", line: 1, column: 40)\', nft/src/lib.rs:47:1"
+ },
+ transaction_outcome: {
+ block_hash: '5SUhYcXjXR1svCxL5BhCuw88XNdEjKXqWgA9X4XZW1dW',
+ id: 'SKQqAgnSN27fyHpncaX3fCUxWknBrMtxxytWLRDQfT3',
+ outcome: {
+ executor_id: 'spf.idea404.testnet',
+ gas_burnt: 4839199843770,
+ logs: [],
+ metadata: [Object],
+ receipt_ids: [Array],
+ status: [Object],
+ tokens_burnt: '483919984377000000000'
+ },
+ proof: [ [Object], [Object], [Object], [Object], [Object] ]
+ }
+ }
+ Balance after: {
+ total: '49985119959346682700000000',
+ stateStaked: '4555390000000000000000000',
+ staked: '0',
+ available: '45429729959346682700000000'
+ }
+ ```
+
+
+ You may also find an example of batch transactions in the [Cookbook](/tools/near-api-js/cookbook).
+
+
+
+
+
### Deploy a Contract {#deploy-a-contract}
You can deploy a contract from a compiled WASM file. This returns an object with transaction and receipts outcomes and status.
-
+
```js
const account = await nearConnection.account("example-account.testnet");
@@ -935,7 +1067,7 @@ You can get and manage keys for an account.
### Add Function Access Key {#add-function-access-key}
-
+
```js
const account = await nearConnection.account("example-account.testnet");
@@ -955,7 +1087,7 @@ You can get and manage keys for an account.
### Add Full Access Key {#add-full-access-key}
-
+
```js
// takes public key as string for argument
@@ -971,7 +1103,7 @@ You can get and manage keys for an account.
### Get All Access Keys {#get-all-access-keys}
-
+
```js
const account = await nearConnection.account("example-account.testnet");
@@ -979,7 +1111,7 @@ You can get and manage keys for an account.
```
-
+
```rust
use near_jsonrpc_client::methods;
@@ -1036,7 +1168,7 @@ You can get and manage keys for an account.
### Delete Access Key {#delete-access-key}
-
+
```js
const account = await nearConnection.account("example-account.testnet");
@@ -1053,7 +1185,7 @@ You can get and manage keys for an account.
### NEAR => yoctoNEAR {#near--yoctonear}
-
+
```js
// converts NEAR amount into yoctoNEAR (10^-24)
@@ -1070,7 +1202,7 @@ You can get and manage keys for an account.
### YoctoNEAR => NEAR {#yoctonear--near}
-
+
```js
// converts yoctoNEAR (10^-24) amount into NEAR
@@ -1087,7 +1219,7 @@ You can get and manage keys for an account.
## Additional resources
-
+
- [Handling Passphrases](https://github.com/near/near-seed-phrase)
- [Type Docs](https://near.github.io/near-api-js)
From 83cacb3203b42f9fd69fe076d63be25d4ac90421 Mon Sep 17 00:00:00 2001
From: PiVortex
Date: Thu, 28 Nov 2024 14:52:24 +0000
Subject: [PATCH 04/13] add most of rust
---
docs/4.tools/near-api.md | 773 ++++++++++++++-------------------------
1 file changed, 272 insertions(+), 501 deletions(-)
diff --git a/docs/4.tools/near-api.md b/docs/4.tools/near-api.md
index 4862b8f7cfe..00750785909 100644
--- a/docs/4.tools/near-api.md
+++ b/docs/4.tools/near-api.md
@@ -11,7 +11,7 @@ The NEAR API is a set of libraries that allow you to interact with the NEAR bloc
The API is available in multiple languages, including:
- JavaScript: [`near-api-js`](https://github.com/near/near-api-js)
-- Rust: [`near-jsonrpc-client`](https://github.com/near/near-jsonrpc-client-rs)
+- Rust: [`near-api-rs`](https://github.com/near/near-api-rs)
- Python: [`py-near`](https://github.com/pvolnov/py-near)
For example, you could use [`near-api-js`](https://github.com/near/near-api-js) to create web applications or backend services written in node.js servers.
@@ -44,7 +44,7 @@ To allow users to login into your web application using a wallet you will need t
```bash
- cargo add near-jsonrpc-client
+ cargo add near-api
```
@@ -63,9 +63,9 @@ To allow users to login into your web application using a wallet you will need t
- Each one of the valid JSON RPC methods are defined in the methods module.
+ The methods to interact with the NEAR API are available through the `prelude` module.
```rust
- use near_jsonrpc_client::methods;
+ use near_api::prelude::*;
```
@@ -217,11 +217,96 @@ To allow users to login into your web application using a wallet you will need t
+ Standard connections `mainnet` and `testnet` are available that come with standard configurations for each network.
+
+ ```rust
+ let network = NetworkConfig::testnet();
+ ```
+
+ You can make the connection mutable to change some details of the connection.
+
```rust
- use near_jsonrpc_client::JsonRpcClient;
+ let mut network = NetworkConfig::testnet();
+ network.rpc_url = "https://rpc.testnet.near.org".parse().unwrap();
+ ```
+
+ You can also create your own custom connection.
- let testnet_client = JsonRpcClient::connect("https://rpc.testnet.near.org");
+ ```rust
+ let network = NetworkConfig {
+ network_name: "testnet".to_string(),
+ rpc_url: "https://rpc.testnet.near.org".parse().unwrap(),
+ rpc_api_key: None,
+ linkdrop_account_id: Some("testnet".parse().unwrap()),
+ near_social_db_contract_account_id: Some("v1.social08.testnet".parse().unwrap()),
+ faucet_url: Some("https://helper.nearprotocol.com/account".parse().unwrap()),
+ meta_transaction_relayer_url: Some("http://localhost:3030/relay".parse().unwrap()),
+ fastnear_url: None,
+ staking_pools_factory_account_id: Some("pool.f863973.m0".parse().unwrap()),
+ };
```
+
+
+
+ #### Signer
+
+ If you're going to sign transactions, you need to create a `signer` object.
+
+
+
+
+ This example uses the Keystore that is also used as the standard for saving keys with the NEAR CLI.
+
+ ```rust
+ use near_api::signer::keystore::KeystoreSigner;
+
+ let search_keystore_signer = KeystoreSigner::search_for_keys(my_account_id.clone(), &network)
+ .await
+ .unwrap();
+ let keystore_signer_search = Signer::new(search_keystore_signer).unwrap();
+ ```
+
+
+
+
+ Keys can be loaded from a file that contains a public and private key. This is an example of loading a key from a file that was saved using the legacy option using the NEAR CLI.
+
+ ```rust
+ use std::env;
+ use std::path::Path;
+
+ let my_account_id = "example-account.testnet";
+ let home_dir = env::var("HOME").unwrap();
+ let credentials_dir = Path::new(&home_dir).join(".near-credentials");
+ let file_path = credentials_dir.join(format!("testnet/{}.json", my_account_id));
+
+ let file_signer = Signer::new(Signer::access_keyfile(file_path).unwrap()).unwrap();
+ ```
+
+
+
+
+ ```rust
+ let seed_phrase =
+ "shoe three gate jelly whole tissue parrot robust census lens staff ship".to_string();
+ let seed_phrase_signer = Signer::new(Signer::seed_phrase(seed_phrase, None).unwrap()).unwrap();
+ ```
+
+
+
+
+
+ ```rust
+ use near_crypto::SecretKey;
+ use std::str::FromStr;
+
+ let private_key = SecretKey::from_str("ed25519:3bUTUXCPHPbAD5JDukzsWT6AaJ9iZA3FF9wLgYgRvzC7CDYMgmEExtxyGjnGATvmM3oggqUErvRkN9sjzNTD8yd7").unwrap();
+ let priv_key_signer = Signer::new(Signer::secret_key(private_key)).unwrap();
+ ```
+
+
+
+
@@ -275,13 +360,21 @@ This will return an Account object for you to interact with.
const account = await nearConnection.account("example-account.testnet");
```
+ :::warning
+ In order to be able to use the account, its credentials must be stored in the [key store](#key-store)
+ :::
+
+
+
+
+ ```rust
+ let account_id: AccountId = "example-account.testnet".parse().unwrap();
+ let account = Account::new(account_id.clone(), network);
+ ```
+
-:::warning
-In order to be able to use the account, its credentials must be stored in the [key store](#key-store)
-:::
-
### Get Balance {#get-balance}
@@ -295,6 +388,18 @@ In order to be able to use the account, its credentials must be stored in the [k
const accountBalance = await account.getAccountBalance();
```
+
+
+
+ ```rust
+ let account_id: AccountId = "example-account.testnet".parse().unwrap();
+ let account_balance = Tokens::of(account_id.clone())
+ .near_balance()
+ .fetch_from(&network)
+ .await
+ .unwrap();
+ ```
+
@@ -333,34 +438,10 @@ Get basic account information, such as amount of tokens the account has or the a
```rust
- use near_jsonrpc_client::methods;
- use near_jsonrpc_primitives::types::query::QueryResponseKind;
- use near_primitives::types::{AccountId, BlockReference, Finality};
- use near_primitives::views::QueryRequest;
-
- mod utils;
-
- #[tokio::main]
- async fn main() -> Result<(), Box> {
- env_logger::init();
-
- let client = utils::select_network()?;
+ let account_id: AccountId = "example-account.testnet".parse().unwrap();
+ let account = Account::new(my_account_id.clone(), network);
- let account_id: AccountId = utils::input("Enter an Account ID to lookup: ")?.parse()?;
-
- let request = methods::query::RpcQueryRequest {
- block_reference: BlockReference::Finality(Finality::Final),
- request: QueryRequest::ViewAccount { account_id },
- };
-
- let response = client.call(request).await?;
-
- if let QueryResponseKind::ViewAccount(result) = response.kind {
- println!("{:#?}", result);
- }
-
- Ok(())
- }
+ let account_state = account.view().fetch_from(&network).await.unwrap();
```
@@ -394,284 +475,60 @@ Create a sub-account.
contractId: "testnet",
methodName: "create_account",
args: {
- new_account_id: "new-account.testnet",
- new_public_key: "ed25519:2ASWccunZMBSygADWG2pXuHM6jWdnzLzWFU6r7wtaHYt",
+ new_account_id: "new-account.testnet",
+ new_public_key: "ed25519:2ASWccunZMBSygADWG2pXuHM6jWdnzLzWFU6r7wtaHYt",
},
gas: "300000000000000",
attachedDeposit: utils.format.parseNearAmount(amount),
- });
+ });
```
+ You will need to create a signer object first.
- ```rust
- //! Creates an account on the network.
- //!
- //! Creates either;
- //! - a top-level mainnet / testnet account
- //! - or a sub-account for any account on the network.
- //!
- //! top-level account example: `miraclx.near` creates `foobar.near`
- //! sub-account example: `miraclx.near` creates `test.miraclx.near`
- //!
- //! This script is interactive.
-
- use near_crypto::Signer;
- use near_jsonrpc_client::methods::broadcast_tx_commit::RpcTransactionError;
- use near_jsonrpc_client::{methods, JsonRpcClient};
- use near_jsonrpc_primitives::types::query::QueryResponseKind;
- use near_jsonrpc_primitives::types::transactions::TransactionInfo;
- use near_primitives::hash::CryptoHash;
- use near_primitives::transaction::{
- Action, AddKeyAction, CreateAccountAction, FunctionCallAction, Transaction, TransactionV0,
- TransferAction,
- };
- use near_primitives::types::{AccountId, BlockReference};
- use near_primitives::views::{FinalExecutionStatus, TxExecutionStatus};
-
- use serde_json::json;
- use tokio::time;
-
- mod utils;
-
- async fn account_exists(
- client: &JsonRpcClient,
- account_id: &AccountId,
- ) -> Result> {
- let access_key_query_response = client
- .call(methods::query::RpcQueryRequest {
- block_reference: BlockReference::latest(),
- request: near_primitives::views::QueryRequest::ViewAccount {
- account_id: account_id.clone(),
- },
- })
- .await;
-
- match access_key_query_response {
- Ok(_) => Ok(true),
- Err(near_jsonrpc_client::errors::JsonRpcError::ServerError(
- near_jsonrpc_client::errors::JsonRpcServerError::HandlerError(
- near_jsonrpc_primitives::types::query::RpcQueryError::UnknownAccount { .. },
- ),
- )) => Ok(false),
- Err(res) => Err(res)?,
- }
- }
+ This example creates the sub-account and saves the seed phrase of a generated key pair to a file.
- async fn get_current_nonce(
- client: &JsonRpcClient,
- account_id: &AccountId,
- public_key: &near_crypto::PublicKey,
- ) -> Result
@@ -689,6 +546,18 @@ Create a sub-account.
await account.deleteAccount("beneficiary-account.testnet");
```
+
+
+
+ ```rust
+ account
+ .delete_account_with_beneficiary(beneficiary_account_id.clone())
+ .with_signer(signer.clone())
+ .send_to(&network)
+ .await
+ .unwrap();
+ ```
+
@@ -711,16 +580,30 @@ Transfer NEAR tokens between accounts. This returns an object with transaction a
);
```
+
+
+ ```rust
+ Tokens::of(sender_account_id.clone())
+ .send_to(receiver_account_id.clone())
+ .near(NearToken::from_near(1))
+ .with_signer(signer.clone())
+ .send_to(&network)
+ .await
+ .unwrap()
+ .assert_success();
+ ```
+
+
### View Function
-View functions are read-only functions that don't change the state of the contract. We can call these functions without instantiating an account or a key store.
-
+
+ View functions are read-only functions that don't change the state of the contract. We can call these functions without instantiating an account or a key store.
```js
import { providers } from 'near-api-js';
@@ -741,56 +624,20 @@ View functions are read-only functions that don't change the state of the contra
```
+ View functions are read-only functions that don't change the state of the contract. We can call these functions without a signer.
- ```rust
- use near_jsonrpc_client::{methods, JsonRpcClient};
- use near_jsonrpc_primitives::types::query::QueryResponseKind;
- use near_primitives::types::{BlockReference, Finality, FunctionArgs};
- use near_primitives::views::QueryRequest;
-
- use serde::Deserialize;
- use serde_json::{from_slice, json};
-
- mod utils;
-
- #[derive(Debug, Deserialize)]
- pub struct AccountStatus {
- pub rating: f32,
- pub given: u64,
- pub received: u64,
- }
+ You need to specify what type the view function returns.
- #[tokio::main]
- async fn main() -> Result<(), Box> {
- env_logger::init();
-
- let client = JsonRpcClient::connect("https://rpc.testnet.near.org");
-
- let account_id = utils::input("Enter the account to view: ")?;
-
- let request = methods::query::RpcQueryRequest {
- block_reference: BlockReference::Finality(Finality::Final),
- request: QueryRequest::CallFunction {
- account_id: "nosedive.testnet".parse()?,
- method_name: "status".to_string(),
- args: FunctionArgs::from(
- json!({
- "account_id": account_id,
- })
- .to_string()
- .into_bytes(),
- ),
- },
- };
-
- let response = client.call(request).await?;
-
- if let QueryResponseKind::CallResult(result) = response.kind {
- println!("{:#?}", from_slice::(&result.result)?);
- }
+ ```rust
+ let res: Data = contract
+ .call_function("total_messages", ())
+ .unwrap()
+ .read_only()
+ .fetch_from(&network)
+ .await
+ .unwrap();
- Ok(())
- }
+ println!("{:?}", res.data);
```
@@ -802,6 +649,8 @@ View functions are read-only functions that don't change the state of the contra
+ A call function changes the contract's state and does require an account.
+
```js
import { connect, transactions, keyStores } from "near-api-js";
@@ -821,113 +670,22 @@ View functions are read-only functions that don't change the state of the contra
+ A call function changes the contract's state and does require a signer.
```rust
- use near_crypto::Signer;
- use near_jsonrpc_client::{methods, JsonRpcClient};
- use near_jsonrpc_primitives::types::query::QueryResponseKind;
- use near_jsonrpc_primitives::types::transactions::{RpcTransactionError, TransactionInfo};
- use near_primitives::transaction::{Action, FunctionCallAction, Transaction, TransactionV0};
- use near_primitives::types::BlockReference;
- use near_primitives::views::TxExecutionStatus;
-
- use serde_json::json;
- use tokio::time;
-
- mod utils;
-
- #[tokio::main]
- async fn main() -> Result<(), Box> {
- env_logger::init();
-
- let client = JsonRpcClient::connect("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::()?;
-
- let transaction = TransactionV0 {
- 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 request = methods::broadcast_tx_async::RpcBroadcastTxAsyncRequest {
- signed_transaction: Transaction::V0(transaction).sign(&Signer::InMemory(signer.clone())),
- };
-
- let sent_at = time::Instant::now();
- let tx_hash = client.call(request).await?;
-
- loop {
- let response = client
- .call(methods::tx::RpcTransactionStatusRequest {
- transaction_info: TransactionInfo::TransactionId {
- tx_hash,
- sender_account_id: signer.account_id.clone(),
- },
- wait_until: TxExecutionStatus::Executed,
- })
- .await;
- let received_at = time::Instant::now();
- let delta = (received_at - sent_at).as_secs();
-
- if delta > 60 {
- Err("time limit exceeded for the transaction to be recognized")?;
- }
-
- match response {
- Err(err) => match err.handler_error() {
- Some(
- RpcTransactionError::TimeoutError
- | RpcTransactionError::UnknownTransaction { .. },
- ) => {
- time::sleep(time::Duration::from_secs(2)).await;
- continue;
- }
- _ => Err(err)?,
- },
- Ok(response) => {
- println!("response gotten after: {}s", delta);
- println!("response: {:#?}", response);
- break;
- }
- }
- }
+ let args = json!({
+ "text": "Hello, world!"
+ });
- Ok(())
- }
+ contract
+ .call_function("add_message", args)
+ .unwrap()
+ .transaction()
+ .deposit(NearToken::from_near(1))
+ .with_signer(my_account_id.clone(), signer.clone())
+ .send_to(&network)
+ .await
+ .unwrap()
+ .assert_success();
```
@@ -1058,6 +816,12 @@ You can deploy a contract from a compiled WASM file. This returns an object with
+
+
+### Signing Messages
+
+
+
---
## Keys
@@ -1079,6 +843,30 @@ You can get and manage keys for an account.
);
```
+
+
+
+ ```rust
+ use near_primitives::account::FunctionCallPermission;
+
+ let new_function_call_key = AccessKeyPermission::FunctionCall(FunctionCallPermission {
+ allowance: Some(250_000_000_000_000_000_000_000), // Allowance this key is allowed to call (optional)
+ receiver_id: "example-account.testnet".to_string(), // Contract this key is allowed to call
+ method_names: vec!["example_method".to_string()], // Methods this key is allowed to call
+ });
+
+ let (new_private_key, txn) = Account(account_id.clone())
+ .add_key(new_function_call_key)
+ .new_keypair()
+ .generate_secret_key() // Generates a new keypair via private key
+ .unwrap();
+
+ println!("New private key: {:?}", new_private_key.to_string());
+ println!("New public key: {:?}", new_private_key.public_key().to_string());
+
+ txn.with_signer(signer.clone()).send_to(&network).await.unwrap(); // Sends the transaction to the network
+ ```
+
@@ -1095,6 +883,24 @@ You can get and manage keys for an account.
await account.addKey("8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc");
```
+
+
+
+ ```rust
+ use near_primitives::account::AccessKeyPermission;
+
+ let (new_private_key, txn) = Account(account_id.clone())
+ .add_key(AccessKeyPermission::FullAccess)
+ .new_keypair()
+ .generate_secret_key() // Generates a new keypair via private key
+ .unwrap();
+
+ println!("New private key: {:?}", new_private_key.to_string());
+ println!("New public key: {:?}", new_private_key.public_key().to_string());
+
+ txn.with_signer(signer.clone()).send_to(&network).await.unwrap();
+ ```
+
@@ -1114,51 +920,8 @@ You can get and manage keys for an account.
```rust
- use near_jsonrpc_client::methods;
- use near_jsonrpc_primitives::types::query::QueryResponseKind;
- use near_primitives::types::BlockReference;
-
- mod utils;
-
- fn indent(indentation: usize, s: String) -> String {
- let mut lines = s.split_inclusive("\n");
- let mut r = lines.next().unwrap().to_string();
- for l in lines {
- r.push_str(&" ".repeat(indentation - 3));
- r.push_str("\x1b[38;5;244m>\x1b[0m ");
- r.push_str(l);
- }
- r
- }
-
- #[tokio::main]
- async fn main() -> Result<(), Box> {
- env_logger::init();
-
- let client = utils::select_network()?;
-
- let account_id = utils::input("Enter the Account ID whose keys we're listing: ")?.parse()?;
-
- let access_key_query_response = client
- .call(methods::query::RpcQueryRequest {
- block_reference: BlockReference::latest(),
- request: near_primitives::views::QueryRequest::ViewAccessKeyList { account_id },
- })
- .await?;
-
- if let QueryResponseKind::AccessKeyList(response) = access_key_query_response.kind {
- for access_key in response.keys {
- println!("π [{}]", access_key.public_key);
- println!(" \u{21b3} nonce: {}", access_key.access_key.nonce);
- println!(
- " \u{21b3} permission: {}",
- indent(20, format!("{:#?}", access_key.access_key.permission))
- );
- }
- }
-
- Ok(())
- }
+ let account = Account(account_id.clone());
+ let keys = account.list_keys().fetch_from(&network).await.unwrap();
```
@@ -1175,6 +938,14 @@ You can get and manage keys for an account.
await account.deleteKey("8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc");
```
+
+
+
+ ```rust
+ let my_account = Account(account_id.clone());
+ my_account.delete_key(new_private_key.public_key()).with_signer(signer.clone()).send_to(&network).await.unwrap();
+ ```
+
From ca654528e77b842baea840953d0757a2601d0487 Mon Sep 17 00:00:00 2001
From: PiVortex
Date: Fri, 29 Nov 2024 13:42:36 +0000
Subject: [PATCH 05/13] api additions
---
docs/4.tools/near-api.md | 196 ++++++++++++++++++++++++---------------
1 file changed, 122 insertions(+), 74 deletions(-)
diff --git a/docs/4.tools/near-api.md b/docs/4.tools/near-api.md
index 00750785909..ec5d801e535 100644
--- a/docs/4.tools/near-api.md
+++ b/docs/4.tools/near-api.md
@@ -263,7 +263,7 @@ To allow users to login into your web application using a wallet you will need t
let search_keystore_signer = KeystoreSigner::search_for_keys(my_account_id.clone(), &network)
.await
.unwrap();
- let keystore_signer_search = Signer::new(search_keystore_signer).unwrap();
+ let signer = Signer::new(search_keystore_signer).unwrap();
```
@@ -275,12 +275,12 @@ To allow users to login into your web application using a wallet you will need t
use std::env;
use std::path::Path;
- let my_account_id = "example-account.testnet";
+ let account_id = "example-account.testnet";
let home_dir = env::var("HOME").unwrap();
let credentials_dir = Path::new(&home_dir).join(".near-credentials");
- let file_path = credentials_dir.join(format!("testnet/{}.json", my_account_id));
+ let file_path = credentials_dir.join(format!("testnet/{}.json", account_id));
- let file_signer = Signer::new(Signer::access_keyfile(file_path).unwrap()).unwrap();
+ let signer = Signer::new(Signer::access_keyfile(file_path).unwrap()).unwrap();
```
@@ -289,7 +289,7 @@ To allow users to login into your web application using a wallet you will need t
```rust
let seed_phrase =
"shoe three gate jelly whole tissue parrot robust census lens staff ship".to_string();
- let seed_phrase_signer = Signer::new(Signer::seed_phrase(seed_phrase, None).unwrap()).unwrap();
+ let signer = Signer::new(Signer::seed_phrase(seed_phrase, None).unwrap()).unwrap();
```
@@ -301,7 +301,7 @@ To allow users to login into your web application using a wallet you will need t
use std::str::FromStr;
let private_key = SecretKey::from_str("ed25519:3bUTUXCPHPbAD5JDukzsWT6AaJ9iZA3FF9wLgYgRvzC7CDYMgmEExtxyGjnGATvmM3oggqUErvRkN9sjzNTD8yd7").unwrap();
- let priv_key_signer = Signer::new(Signer::secret_key(private_key)).unwrap();
+ let signer = Signer::new(Signer::secret_key(private_key)).unwrap();
```
@@ -369,7 +369,7 @@ This will return an Account object for you to interact with.
```rust
let account_id: AccountId = "example-account.testnet".parse().unwrap();
- let account = Account::new(account_id.clone(), network);
+ let account = Account(account_id.clone());
```
@@ -439,7 +439,7 @@ Get basic account information, such as amount of tokens the account has or the a
```rust
let account_id: AccountId = "example-account.testnet".parse().unwrap();
- let account = Account::new(my_account_id.clone(), network);
+ let account = Account(my_account_id.clone());
let account_state = account.view().fetch_from(&network).await.unwrap();
```
@@ -448,13 +448,61 @@ Get basic account information, such as amount of tokens the account has or the a
-### Create Sub-Account {#create-account}
+### Create an Account {#create-account}
+
+
+
+
+ In order to create .near or .testnet accounts, you need to make a function call to the top-level-domain (i.e. `near` or `testnet`), calling `create_account`:
+
+ ```js
+ return await creatorAccount.functionCall({
+ contractId: "testnet",
+ methodName: "create_account",
+ args: {
+ new_account_id: "new-account.testnet",
+ new_public_key: "ed25519:2ASWccunZMBSygADWG2pXuHM6jWdnzLzWFU6r7wtaHYt",
+ },
+ gas: "300000000000000",
+ attachedDeposit: utils.format.parseNearAmount(amount),
+ });
+ ```
+
+
+
+
+ In this example when we create the account we generate a seed phrase for the new account and save it to a file.
+
+ ```rust
+ let account_id: AccountId = "example-account.testnet".parse().unwrap();
+ let new_account_id: AccountId = "new_example-account.testnet".parse().unwrap();
+ let res = Account::create_account()
+ .fund_myself(
+ new_account_id.clone(), // new account id
+ account_id.clone(), // account id funding the new account
+ NearToken::from_near(1), // Initial balance for the new account
+ )
+ .new_keypair() // Generates a new random key pair
+ .save_generated_seed_to_file("./new_account_seed".into())
+ .unwrap()
+ .with_signer(signer.clone())
+ .send_to(&network)
+ .await
+ .unwrap();
+ ```
+
+
+
+
+
-Create a sub-account.
+### Create a Sub-Account {#create-sub-account}
+ For creating a sub-account there is a specific method that is used.
+
```js
// creates a sub-account using funds from the account used to create it.
const account = await nearConnection.account("example-account.testnet");
@@ -465,68 +513,27 @@ Create a sub-account.
);
```
-
- Creating .near or .testnet accounts
-
- In order to create .near or .testnet accounts, you need to make a function call to the top-level-domain (i.e. `near` or `testnet`), calling `create_account`:
-
- ```js
- return await creatorAccount.functionCall({
- contractId: "testnet",
- methodName: "create_account",
- args: {
- new_account_id: "new-account.testnet",
- new_public_key: "ed25519:2ASWccunZMBSygADWG2pXuHM6jWdnzLzWFU6r7wtaHYt",
- },
- gas: "300000000000000",
- attachedDeposit: utils.format.parseNearAmount(amount),
- });
- ```
-
-
-
- You will need to create a signer object first.
- This example creates the sub-account and saves the seed phrase of a generated key pair to a file.
+ The process for creating a sub-account is the same as creating a new account, but with an account id that is a sub-account of the parent account.
```rust
let account_id: AccountId = "example-account.testnet".parse().unwrap();
let new_account_id: AccountId = "sub.example-account.testnet".parse().unwrap();
let res = Account::create_account()
- .fund_myself(
- new_account_id.clone(), // new account id
- account_id.clone(), // account id funding the new account
- NearToken::from_near(1), // Initial balance for the new account
- )
- .new_keypair() // Generates a new random key pair
- .save_generated_seed_to_file("./new_account_seed".into())
- .unwrap()
- .with_signer(signer.clone())
- .send_to(&network)
- .await
- .unwrap();
- ```
-
- Creating a `.near` or `.testnet` account is the exact same process as creating a sub-account.
-
- ```rust
- let account_id: AccountId = "example-account.testnet".parse().unwrap();
- let new_account_id: AccountId = "new_example-account.testnet".parse().unwrap();
- let res = Account::create_account()
- .fund_myself(
- new_account_id.clone(), // new account id
- account_id.clone(), // account id funding the new account
- NearToken::from_near(1), // Initial balance for the new account
- )
- .new_keypair() // Generates a new random key pair
- .save_generated_seed_to_file("./new_account_seed".into())
- .unwrap()
- .with_signer(signer.clone())
- .send_to(&network)
- .await
- .unwrap();
+ .fund_myself(
+ new_account_id.clone(), // new account id
+ account_id.clone(), // account id funding the new account
+ NearToken::from_near(1), // Initial balance for the new account
+ )
+ .new_keypair() // Generates a new random key pair
+ .save_generated_seed_to_file("./new_account_seed".into())
+ .unwrap()
+ .with_signer(signer.clone())
+ .send_to(&network)
+ .await
+ .unwrap();
```
@@ -629,6 +636,9 @@ Transfer NEAR tokens between accounts. This returns an object with transaction a
You need to specify what type the view function returns.
```rust
+ let contract_id: AccountId = "example-contract.testnet".parse().unwrap();
+ let contract = Contract(contract_id.clone());
+
let res: Data = contract
.call_function("total_messages", ())
.unwrap()
@@ -672,6 +682,9 @@ Transfer NEAR tokens between accounts. This returns an object with transaction a
A call function changes the contract's state and does require a signer.
```rust
+ let contract_id: AccountId = "example-contract.testnet".parse().unwrap();
+ let contract = Contract(contract_id.clone());
+
let args = json!({
"text": "Hello, world!"
});
@@ -692,12 +705,12 @@ Transfer NEAR tokens between accounts. This returns an object with transaction a
-### Batch Transactions
+### Batch Actions
- You may batch send transactions by using the `signAndSendTransaction({})` method from `account`. This method takes an array of transaction actions, and if one fails, the entire operation will fail. Here's a simple example:
+ You may batch send actions by using the `signAndSendTransaction({})` method from `account`. This method takes an array of transaction actions, and if one fails, the entire operation will fail. Here's a simple example:
```js
const { connect, transactions, keyStores } = require("near-api-js");
@@ -718,9 +731,9 @@ Transfer NEAR tokens between accounts. This returns an object with transaction a
nodeUrl: "https://rpc.testnet.near.org",
};
- sendTransactions();
+ sendBatchActions();
- async function sendTransactions() {
+ async function sendBatchActions() {
const near = await connect({ ...config, keyStore });
const account = await near.account(CONTRACT_NAME);
const args = { some_field: 1, another_field: "hello" };
@@ -796,6 +809,29 @@ Transfer NEAR tokens between accounts. This returns an object with transaction a
You may also find an example of batch transactions in the [Cookbook](/tools/near-api-js/cookbook).
+
+
+ ```rust
+ let function_call_action = Action::FunctionCall(Box::new(FunctionCallAction {
+ method_name: "increment".to_string(),
+ args: vec![],
+ gas: 30_000_000_000_000,
+ deposit: 0,
+ })); // Create a function call action
+ let transfer_action = Action::Transfer(TransferAction {
+ deposit: 1_000_000_000_000_000_000_000_000,
+ }); // Create a transfer action
+ let actions = vec![function_call_action, transfer_action];
+
+ Transaction::construct(account_id.clone(), receiver_id.clone())
+ .add_actions(actions)
+ .with_signer(signer)
+ .send_to(&network)
+ .await
+ .unwrap()
+ .assert_success();
+ ```
+
@@ -814,13 +850,25 @@ You can deploy a contract from a compiled WASM file. This returns an object with
);
```
-
-
-
+
-### Signing Messages
+ Note that the `signer` here needs to be a signer for the same `account_id` as the one used to construct the `Contract` object.
+ ```rust
+ let new_contract_id: AccountId = "new-contract.testnet".parse().unwrap();
+ let contract = Contract(new_contract_id.clone());
+ new_contract
+ .deploy(include_bytes!("../contracts/contract.wasm").to_vec())
+ .without_init_call() // Can also be .with_init_call()
+ .with_signer(signer)
+ .send_to(&network)
+ .await
+ .unwrap()
+ .assert_success();
+ ```
+
+
---
@@ -942,8 +990,8 @@ You can get and manage keys for an account.
```rust
- let my_account = Account(account_id.clone());
- my_account.delete_key(new_private_key.public_key()).with_signer(signer.clone()).send_to(&network).await.unwrap();
+ let account = Account(account_id.clone());
+ account.delete_key(new_private_key.public_key()).with_signer(signer.clone()).send_to(&network).await.unwrap();
```
From 32c51ef1ec12e679debff72003a3d3b30744465e Mon Sep 17 00:00:00 2001
From: PiVortex
Date: Fri, 29 Nov 2024 13:46:54 +0000
Subject: [PATCH 06/13] quick fix
---
docs/4.tools/near-api.md | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/docs/4.tools/near-api.md b/docs/4.tools/near-api.md
index ec5d801e535..4d3c0205878 100644
--- a/docs/4.tools/near-api.md
+++ b/docs/4.tools/near-api.md
@@ -811,7 +811,12 @@ Transfer NEAR tokens between accounts. This returns an object with transaction a
+ You can send actions in a batch to a single receiver. If one action fails then the entire batch of actions will be reverted.
+
```rust
+ use near_primitives::transaction::Action;
+ use near_primitives::action::{FunctionCallAction, TransferAction};
+
let function_call_action = Action::FunctionCall(Box::new(FunctionCallAction {
method_name: "increment".to_string(),
args: vec![],
From 1bd33bec6fab3ff4f5f0092cef59492a6ec9ea07 Mon Sep 17 00:00:00 2001
From: PiVortex
Date: Thu, 5 Dec 2024 12:23:28 +0000
Subject: [PATCH 07/13] swapping to code snippets
---
docs/4.tools/near-api.md | 193 +++++++++++----------------------------
1 file changed, 54 insertions(+), 139 deletions(-)
diff --git a/docs/4.tools/near-api.md b/docs/4.tools/near-api.md
index 4d3c0205878..ddaefc186d6 100644
--- a/docs/4.tools/near-api.md
+++ b/docs/4.tools/near-api.md
@@ -6,6 +6,7 @@ sidebar_label: NEAR API
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
+import {Github, Language} from "@site/src/components/codetabs"
The NEAR API is a set of libraries that allow you to interact with the NEAR blockchain. You can use it to create accounts, send tokens, deploy contracts, and more.
@@ -57,9 +58,10 @@ To allow users to login into your web application using a wallet you will need t
You can use the API library in the browser, or in Node.js runtime. Some features are available only in one of the environments. For example, the `WalletConnection` is only for the browser, and there are different `KeyStore` providers for each environment.
- ```js
- import * as nearAPI from "near-api-js";
- ```
+
+
@@ -80,19 +82,9 @@ To allow users to login into your web application using a wallet you will need t
The object returned from `connect` is your entry-point for all commands in the API.
To sign a transaction you'll need a [`KeyStore`](#key-store) to create a connection.
- ```js
- const { connect } = nearAPI;
-
- const connectionConfig = {
- networkId: "testnet",
- keyStore: myKeyStore, // first create a key store
- nodeUrl: "https://rpc.testnet.near.org",
- walletUrl: "https://testnet.mynearwallet.com/",
- helperUrl: "https://helper.testnet.near.org",
- explorerUrl: "https://testnet.nearblocks.io",
- };
- const nearConnection = await connect(connectionConfig);
- ```
+ Mainnet/Localnet connection
@@ -136,59 +128,23 @@ To allow users to login into your web application using a wallet you will need t
- ```js
- // creates a keyStore that searches for keys in .near-credentials
- // requires credentials stored locally by using a NEAR-CLI command: `near login`
- // https://docs.near.org/tools/cli#near-login
-
- const { keyStores } = nearAPI;
- const homedir = require("os").homedir();
- const CREDENTIALS_DIR = ".near-credentials";
- const credentialsPath = require("path").join(homedir, CREDENTIALS_DIR);
- const myKeyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath);
- ```
+
- ```js
- // creates keyStore from a provided file
- // you will need to pass the location of the .json key pair
-
- const { KeyPair, keyStores } = require("near-api-js");
- const fs = require("fs");
- const homedir = require("os").homedir();
-
- const ACCOUNT_ID = "near-example.testnet"; // NEAR account tied to the keyPair
- const NETWORK_ID = "testnet";
- // path to your custom keyPair location (ex. function access key for example account)
- const KEY_PATH = "/.near-credentials/near-example-testnet/get_token_price.json";
-
- const credentials = JSON.parse(fs.readFileSync(homedir + KEY_PATH));
- const myKeyStore = new keyStores.InMemoryKeyStore();
- myKeyStore.setKey(
- NETWORK_ID,
- ACCOUNT_ID,
- KeyPair.fromString(credentials.private_key)
- );
- ```
+
- ```js
- // creates keyStore from a private key string
- // you can define your key here or use an environment variable
-
- const { keyStores, KeyPair } = nearAPI;
- const myKeyStore = new keyStores.InMemoryKeyStore();
- const PRIVATE_KEY =
- "by8kdJoJHu7uUkKfoaLd2J2Dp1q1TigeWMG123pHdu9UREqPcshCM223kWadm";
- // creates a public / private key pair using the provided private key
- const keyPair = KeyPair.fromString(PRIVATE_KEY);
- // adds the keyPair you created to keyStore
- await myKeyStore.setKey("testnet", "example-account.testnet", keyPair);
- ```
+
@@ -319,28 +275,9 @@ RPC providers can experience intermittent downtime, connectivity issues, or rate
- ```js
- const jsonProviders = [
- new JsonRpcProvider({
- url: 'https://rpc.mainnet.near.org',
- }),
- new JsonRpcProvider(
- {
- url: 'https://another-rpc.cloud.com',
- headers: { 'X-Api-Key': 'some string' },
- },
- { retries: 3, backoff: 2, wait: 500 }
- ),
- ];
- const provider = new FailoverRpcProvider(jsonProviders);
-
- await connect({
- networkId: 'mainnet',
- provider: provider,
- // this isn't used if `provider` is specified, but is still required for backward compatibility
- nodeUrl: 'https://rpc.mainnet.near.org',
- });
- ```
+
@@ -356,9 +293,9 @@ This will return an Account object for you to interact with.
- ```js
- const account = await nearConnection.account("example-account.testnet");
- ```
+
:::warning
In order to be able to use the account, its credentials must be stored in the [key store](#key-store)
@@ -382,11 +319,9 @@ This will return an Account object for you to interact with.
- ```js
- // gets account balance
- const account = await nearConnection.account("example-account.testnet");
- const accountBalance = await account.getAccountBalance();
- ```
+
@@ -405,44 +340,42 @@ This will return an Account object for you to interact with.
-### Get Details {#get-details}
+### Get State {#get-state}
-Returns information about an account, such as authorized apps.
+Get basic account information, such as amount of tokens the account has or the amount of storage it uses.
- ```js
- // gets account details in terms of authorized apps and transactions
- const account = await nearConnection.account("example-account.testnet");
- const accountDetails = await account.getAccountDetails();
- ```
+
+
+
+ ```rust
+ let account_id: AccountId = "example-account.testnet".parse().unwrap();
+ let account = Account(my_account_id.clone());
+
+ let account_state = account.view().fetch_from(&network).await.unwrap();
+ ```
+
-### Get State {#get-state}
+### Get Details {#get-details}
-Get basic account information, such as amount of tokens the account has or the amount of storage it uses.
+Returns information about an account, such as authorized apps.
- ```js
- const account = await nearConnection.account("example-account.testnet");
- const accountState = await account.state();
- ```
-
-
-
- ```rust
- let account_id: AccountId = "example-account.testnet".parse().unwrap();
- let account = Account(my_account_id.clone());
+
- let account_state = account.view().fetch_from(&network).await.unwrap();
- ```
@@ -455,18 +388,9 @@ Get basic account information, such as amount of tokens the account has or the a
In order to create .near or .testnet accounts, you need to make a function call to the top-level-domain (i.e. `near` or `testnet`), calling `create_account`:
- ```js
- return await creatorAccount.functionCall({
- contractId: "testnet",
- methodName: "create_account",
- args: {
- new_account_id: "new-account.testnet",
- new_public_key: "ed25519:2ASWccunZMBSygADWG2pXuHM6jWdnzLzWFU6r7wtaHYt",
- },
- gas: "300000000000000",
- attachedDeposit: utils.format.parseNearAmount(amount),
- });
- ```
+
@@ -503,15 +427,9 @@ Get basic account information, such as amount of tokens the account has or the a
For creating a sub-account there is a specific method that is used.
- ```js
- // creates a sub-account using funds from the account used to create it.
- const account = await nearConnection.account("example-account.testnet");
- await account.createAccount(
- "sub.example-account.testnet", // sub-account name
- "8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc", // public key for sub account
- "10000000000000000000" // initial balance for new account in yoctoNEAR
- );
- ```
+
@@ -546,12 +464,9 @@ Get basic account information, such as amount of tokens the account has or the a
- ```js
- // deletes account found in the `account` object
- // transfers remaining account balance to the accountId passed as an argument
- const account = await nearConnection.account("example-account.testnet");
- await account.deleteAccount("beneficiary-account.testnet");
- ```
+
From 2f07816b853dea8f2de89c4c878636cdfdb91e9a Mon Sep 17 00:00:00 2001
From: PiVortex
Date: Tue, 17 Dec 2024 12:53:01 +0000
Subject: [PATCH 08/13] complete rust + javascript api docs
---
docs/4.tools/near-api.md | 857 ++++++++++++++++-----------------------
1 file changed, 342 insertions(+), 515 deletions(-)
diff --git a/docs/4.tools/near-api.md b/docs/4.tools/near-api.md
index ddaefc186d6..f92fc004b1a 100644
--- a/docs/4.tools/near-api.md
+++ b/docs/4.tools/near-api.md
@@ -21,6 +21,8 @@ For example, you could use [`near-api-js`](https://github.com/near/near-api-js)
To allow users to login into your web application using a wallet you will need the `wallet-selector`. Read more in our [Web Frontend integration](/build/web3-apps/integrate-contracts) article
:::
+These examples are references to code snippets, feel free to explore the full code examples in context by clicking `See full example on GitHub` below each example.
+
---
## Install
@@ -30,7 +32,7 @@ To allow users to login into your web application using a wallet you will need t
Include `near-api-js` as a dependency in your package.
```bash
- npm i --save near-api-js
+ npm i near-api-js
```
:::tip Static HTML
@@ -56,19 +58,32 @@ To allow users to login into your web application using a wallet you will need t
- You can use the API library in the browser, or in Node.js runtime. Some features are available only in one of the environments. For example, the `WalletConnection` is only for the browser, and there are different `KeyStore` providers for each environment.
+ You can use the API library in the browser, or in Node.js runtime.
+
+ Using the API in Node.js
+
+ All these examples are written for the browser, to use these examples in Node.js you should convert the project to an ES module. To do this, add the following to your `package.json`:
+
+
+
+
+
The methods to interact with the NEAR API are available through the `prelude` module.
- ```rust
- use near_api::prelude::*;
- ```
+
+
+
@@ -80,11 +95,11 @@ To allow users to login into your web application using a wallet you will need t
The object returned from `connect` is your entry-point for all commands in the API.
- To sign a transaction you'll need a [`KeyStore`](#key-store) to create a connection.
+ To transactions you'll need a [`KeyStore`](#signers).
+ url="https://github.com/PiVortex/near-api-examples/tree/main/javascript/examples/send-tokens.js#L17-L22"
+ start="17" end="22" />
Mainnet/Localnet connection
@@ -93,191 +108,177 @@ To allow users to login into your web application using a wallet you will need t
// Mainnet config example
const connectionConfig = {
networkId: "mainnet",
- keyStore: myKeyStore, // first create a key store
+ keyStore: myKeyStore,
nodeUrl: "https://rpc.mainnet.near.org",
- walletUrl: "https://wallet.mainnet.near.org",
- helperUrl: "https://helper.mainnet.near.org",
- explorerUrl: "https://nearblocks.io",
};
// Localnet config example
const connectionConfig = {
networkId: "local",
nodeUrl: "http://localhost:3030",
- walletUrl: "http://localhost:4000/wallet",
};
```
-
+
+
- #### Key Store
+ To interact with the blockchain you'll need to create a `NetworkConfig` object.
+
+ Preset connections `mainnet` and `testnet` are available that come with standard configurations for each network.
+
+
+
+ You can also create your own custom connection.
+
+
+
+
+
+
+### Signers
+
+
+
- If you sign transactions, you need to create a _Key Store_. In the browser, the LocalStorage KeyStore will be used once you ask your user to Sign In with the Wallet.
+ To sign transactions you'll need to a `KeyStore` with valid keypairs.
+ `BrowserLocalStorageKeyStore` can only be used in the browser, it uses the browser's local storage to store the keys.
+
```js
- // creates keyStore using private key in local storage
+ // Creates keyStore using private key in local storage
const { keyStores } = nearAPI;
const myKeyStore = new keyStores.BrowserLocalStorageKeyStore();
```
-
+
+
+ `UnencryptedFileSystemKeyStore` can be used is used to load keys from the legacy credentials directory used by the NEAR CLI.
+ url="https://github.com/PiVortex/near-api-examples/tree/main/javascript/examples/keystore-options/credentials-directory.js#L11-L13"
+ start="11" end="13" />
-
+ Keystores can be created by loading a private key from a json file.
-
-
-
-
+
-
-
-
- Window error using `Node.js`
-
- You're maybe using a KeyStore that's for the browser. Instead, use a [filesystem key](/tools/near-api-js/quick-reference#key-store) or private key string.
+
- **Browser KeyStore:**
+ Keystores can be created by using a private key string.
- ```js
- const { keyStores } = require("near-api-js");
- const keyStore = new keyStores.BrowserLocalStorageKeyStore();
- ```
+ Private keys have the format "ed25519::5Fg2...".
- **FileSystem KeyStore:**
-
- ```js
- const { keyStores } = require("near-api-js");
- const KEY_PATH = "~./near-credentials/testnet/example-account.json";
- const keyStore = new keyStores.UnencryptedFileSystemKeyStore(KEY_PATH);
- ```
-
+
-
+
- Standard connections `mainnet` and `testnet` are available that come with standard configurations for each network.
+ Keystores can be created by using a seed phrase. To parse the seed phrase into a private key, the `near-seed-phrase` library is needed.
- ```rust
- let network = NetworkConfig::testnet();
- ```
-
- You can make the connection mutable to change some details of the connection.
-
- ```rust
- let mut network = NetworkConfig::testnet();
- network.rpc_url = "https://rpc.testnet.near.org".parse().unwrap();
+ ```bash
+ npm i near-seed-phrase
```
- You can also create your own custom connection.
+ Seed phrases have the format "shoe three gate ..." and are usually 12 words long.
- ```rust
- let network = NetworkConfig {
- network_name: "testnet".to_string(),
- rpc_url: "https://rpc.testnet.near.org".parse().unwrap(),
- rpc_api_key: None,
- linkdrop_account_id: Some("testnet".parse().unwrap()),
- near_social_db_contract_account_id: Some("v1.social08.testnet".parse().unwrap()),
- faucet_url: Some("https://helper.nearprotocol.com/account".parse().unwrap()),
- meta_transaction_relayer_url: Some("http://localhost:3030/relay".parse().unwrap()),
- fastnear_url: None,
- staking_pools_factory_account_id: Some("pool.f863973.m0".parse().unwrap()),
- };
- ```
+
-
+
+
+
- #### Signer
+
- If you're going to sign transactions, you need to create a `signer` object.
+ To sign transactions you'll need to create a `Signer` that holds a valid keypair.
-
+
- This example uses the Keystore that is also used as the standard for saving keys with the NEAR CLI.
+ Signers can be created using the Keystore that is also used as the standard for saving keys with the NEAR CLI.
- ```rust
- use near_api::signer::keystore::KeystoreSigner;
+
- let search_keystore_signer = KeystoreSigner::search_for_keys(my_account_id.clone(), &network)
- .await
- .unwrap();
- let signer = Signer::new(search_keystore_signer).unwrap();
- ```
+
+
+
+ Signers can be created using the credentials directory which is the legacy option for saving keys with the NEAR CLI.
+
+
- Keys can be loaded from a file that contains a public and private key. This is an example of loading a key from a file that was saved using the legacy option using the NEAR CLI.
+ Signers can be created by loading a public and private key from a file.
- ```rust
- use std::env;
- use std::path::Path;
+
- let account_id = "example-account.testnet";
- let home_dir = env::var("HOME").unwrap();
- let credentials_dir = Path::new(&home_dir).join(".near-credentials");
- let file_path = credentials_dir.join(format!("testnet/{}.json", account_id));
+
+
- let signer = Signer::new(Signer::access_keyfile(file_path).unwrap()).unwrap();
- ```
+ Signers can be created by using a private key string.
-
-
+ Private keys have the format "ed25519::5Fg2...".
- ```rust
- let seed_phrase =
- "shoe three gate jelly whole tissue parrot robust census lens staff ship".to_string();
- let signer = Signer::new(Signer::seed_phrase(seed_phrase, None).unwrap()).unwrap();
- ```
+
+
-
+ Signers can be created by using a seed phrase.
- ```rust
- use near_crypto::SecretKey;
- use std::str::FromStr;
+ Seed phrases have the format "shoe three gate ..." and are usually 12 words long.
- let private_key = SecretKey::from_str("ed25519:3bUTUXCPHPbAD5JDukzsWT6AaJ9iZA3FF9wLgYgRvzC7CDYMgmEExtxyGjnGATvmM3oggqUErvRkN9sjzNTD8yd7").unwrap();
- let signer = Signer::new(Signer::secret_key(private_key)).unwrap();
- ```
+
-
+
-
-### RPC Failover
+
+
+ ### RPC Failover
-RPC providers can experience intermittent downtime, connectivity issues, or rate limits that cause client transactions to fail. This can be prevented by using the `FailoverRpcProvider` that supports multiple RPC providers.
+ RPC providers can experience intermittent downtime, connectivity issues, or rate limits that cause client transactions to fail. This can be prevented by using the `FailoverRpcProvider` that supports multiple RPC providers.
-
+
+ url="https://github.com/PiVortex/near-api-examples/tree/main/javascript/examples/rpc-failover.js#L12-L34"
+ start="12" end="34" />
@@ -294,20 +295,15 @@ This will return an Account object for you to interact with.
-
- :::warning
- In order to be able to use the account, its credentials must be stored in the [key store](#key-store)
- :::
+ url="https://github.com/PiVortex/near-api-examples/tree/main/javascript/examples/account-details.js#L9"
+ start="9" end="9" />
- ```rust
- let account_id: AccountId = "example-account.testnet".parse().unwrap();
- let account = Account(account_id.clone());
- ```
+
@@ -316,24 +312,21 @@ This will return an Account object for you to interact with.
### Get Balance {#get-balance}
+Gets the available and staked balance of an account in yoctoNEAR.
+
+ url="https://github.com/PiVortex/near-api-examples/tree/main/javascript/examples/account-details.js#L12"
+ start="12" end="12" />
- ```rust
- let account_id: AccountId = "example-account.testnet".parse().unwrap();
- let account_balance = Tokens::of(account_id.clone())
- .near_balance()
- .fetch_from(&network)
- .await
- .unwrap();
- ```
+
@@ -342,24 +335,22 @@ This will return an Account object for you to interact with.
### Get State {#get-state}
-Get basic account information, such as amount of tokens the account has or the amount of storage it uses.
+Get basic account information, such as its code hash and storage usage.
+ url="https://github.com/PiVortex/near-api-examples/tree/main/javascript/examples/account-details.js#L16"
+ start="16" end="16" />
- ```rust
- let account_id: AccountId = "example-account.testnet".parse().unwrap();
- let account = Account(my_account_id.clone());
+
- let account_state = account.view().fetch_from(&network).await.unwrap();
- ```
@@ -367,14 +358,14 @@ Get basic account information, such as amount of tokens the account has or the a
### Get Details {#get-details}
-Returns information about an account, such as authorized apps.
+Returns the authorized apps of an account. This is a list of contracts that the account has function call access keys for.
+ url="https://github.com/PiVortex/near-api-examples/tree/main/javascript/examples/account-details.js#L20"
+ start="20" end="20" />
@@ -386,34 +377,46 @@ Returns information about an account, such as authorized apps.
- In order to create .near or .testnet accounts, you need to make a function call to the top-level-domain (i.e. `near` or `testnet`), calling `create_account`:
+ In order to create .near or .testnet accounts, you need to make a function call to the top-level-domain account (i.e. `near` or `testnet`), calling `create_account`. In this example we generate a new public key for the account by generating a random private key.
+
+ The deposit determines the initial balance of the account.
+ url="https://github.com/PiVortex/near-api-examples/tree/main/javascript/examples/create-account.js#L24-L39"
+ start="24" end="39" />
+
+
+ Creating an account from a seed phrase
+
+ You can also create an account with a public key that is derived from a randomly generated seed phrase.
+
+
+
+
- In this example when we create the account we generate a seed phrase for the new account and save it to a file.
-
- ```rust
- let account_id: AccountId = "example-account.testnet".parse().unwrap();
- let new_account_id: AccountId = "new_example-account.testnet".parse().unwrap();
- let res = Account::create_account()
- .fund_myself(
- new_account_id.clone(), // new account id
- account_id.clone(), // account id funding the new account
- NearToken::from_near(1), // Initial balance for the new account
- )
- .new_keypair() // Generates a new random key pair
- .save_generated_seed_to_file("./new_account_seed".into())
- .unwrap()
- .with_signer(signer.clone())
- .send_to(&network)
- .await
- .unwrap();
- ```
+ In this example we create a .testnet account with a random keypair.
+
+ The deposit determines the initial balance of the account.
+
+
+
+
+ Creating an account from a seed phrase
+
+ You can also create an account via a randomly generated seed phrase.
+
+
+
+
@@ -425,34 +428,24 @@ Returns information about an account, such as authorized apps.
- For creating a sub-account there is a specific method that is used.
+ For creating a sub-account (sub.example-account.testnet) the API provides specific method.
+
+ The deposit determines the initial balance of the account.
+ url="https://github.com/PiVortex/near-api-examples/tree/main/javascript/examples/create-account.js#L45-L56"
+ start="45" end="56" />
- The process for creating a sub-account is the same as creating a new account, but with an account id that is a sub-account of the parent account.
-
- ```rust
- let account_id: AccountId = "example-account.testnet".parse().unwrap();
- let new_account_id: AccountId = "sub.example-account.testnet".parse().unwrap();
- let res = Account::create_account()
- .fund_myself(
- new_account_id.clone(), // new account id
- account_id.clone(), // account id funding the new account
- NearToken::from_near(1), // Initial balance for the new account
- )
- .new_keypair() // Generates a new random key pair
- .save_generated_seed_to_file("./new_account_seed".into())
- .unwrap()
- .with_signer(signer.clone())
- .send_to(&network)
- .await
- .unwrap();
- ```
+ The process for creating a sub-account (sub.example-account.testnet) is the same as creating a .testnet account, but with an account id that is a sub-account of the parent account.
+
+ The deposit determines the initial balance of the account.
+
+
@@ -461,24 +454,21 @@ Returns information about an account, such as authorized apps.
### Delete Account {#delete-account}
+When deleting an account, you need to specify a beneficiary account id. This is the account that will receive the remaining NEAR balance of the account being deleted. Remember that no other assets will to transferred to the beneficiary, so you should transfer all your FTs, NFTs, etc. to another account before deleting.
+
+ url="https://github.com/PiVortex/near-api-examples/tree/main/javascript/examples/delete-account.js#L45-L46"
+ start="45" end="46" />
- ```rust
- account
- .delete_account_with_beneficiary(beneficiary_account_id.clone())
- .with_signer(signer.clone())
- .send_to(&network)
- .await
- .unwrap();
- ```
+
@@ -489,268 +479,102 @@ Returns information about an account, such as authorized apps.
### Send Tokens {#send-tokens}
-Transfer NEAR tokens between accounts. This returns an object with transaction and receipts outcomes and status.
+Transfer NEAR tokens between accounts.
- ```js
- const account = await nearConnection.account("sender-account.testnet");
- await account.sendMoney(
- "receiver-account.testnet", // receiver account
- "1000000000000000000000000" // amount in yoctoNEAR
- );
- ```
+
+
- ```rust
- Tokens::of(sender_account_id.clone())
- .send_to(receiver_account_id.clone())
- .near(NearToken::from_near(1))
- .with_signer(signer.clone())
- .send_to(&network)
- .await
- .unwrap()
- .assert_success();
- ```
+
-### View Function
+### Call Function
-
+A call function changes the contract's state and requires a signer/keypair.
-
- View functions are read-only functions that don't change the state of the contract. We can call these functions without instantiating an account or a key store.
- ```js
- import { providers } from 'near-api-js';
+
+
- const url = `https://rpc.${this.networkId}.near.org`;
- const provider = new providers.JsonRpcProvider({ url });
- const args = { greeting: 'hello' };
+ You need to specify the account id of the contract you want to call, the method you want to call, and optionally the arguments for the method, the amount of gas you want to allocate for the call, and the deposit you want to send with the call.
- const response = await provider.query({
- request_type: 'call_function',
- account_id: 'hello.near-examples.testnet',
- method_name: 'get_greeting',
- args_base64: Buffer.from(JSON.stringify(args)).toString('base64'),
- finality: 'optimistic',
- });
+
- const result = JSON.parse(Buffer.from(res.result).toString());
- ```
- View functions are read-only functions that don't change the state of the contract. We can call these functions without a signer.
- You need to specify what type the view function returns.
+ To call a function on a contract, you need to create a `Contract` object.
- ```rust
- let contract_id: AccountId = "example-contract.testnet".parse().unwrap();
- let contract = Contract(contract_id.clone());
+
- let res: Data = contract
- .call_function("total_messages", ())
- .unwrap()
- .read_only()
- .fetch_from(&network)
- .await
- .unwrap();
+ You need to specify the account id of the contract you want to call, the method you want to call, the deposit you want to send with the call, and optionally the arguments for the method, the amount of gas you want to allocate for the call.
+
+
- println!("{:?}", res.data);
- ```
-### Call Function
+### Batch Actions
+
+You can send multiple [actions](../1.concepts/protocol/transaction-anatomy.md#actions) in a batch to a single receiver. If one action fails then the entire batch of actions will be reverted.
+
+
- A call function changes the contract's state and does require an account.
-
- ```js
- import { connect, transactions, keyStores } from "near-api-js";
-
- const account = await nearConnection.account("example-account.testnet");
- const result = await account.signAndSendTransaction({
- receiverId: "example-contract.testnet",
- actions: [
- transactions.functionCall(
- "new",
- Buffer.from(JSON.stringify(newArgs)),
- 10000000000000,
- "0"
- ),
- ],
- });
- ```
- A call function changes the contract's state and does require a signer.
- ```rust
- let contract_id: AccountId = "example-contract.testnet".parse().unwrap();
- let contract = Contract(contract_id.clone());
-
- let args = json!({
- "text": "Hello, world!"
- });
-
- contract
- .call_function("add_message", args)
- .unwrap()
- .transaction()
- .deposit(NearToken::from_near(1))
- .with_signer(my_account_id.clone(), signer.clone())
- .send_to(&network)
- .await
- .unwrap()
- .assert_success();
- ```
+
+
-### Batch Actions
+### Simultaneous Transactions
+
+Transactions can be sent in parallel to the network, so you don't have to wait for one transaction to complete before sending the next one. Note that these one transaction could be successful and the other one could fail.
-
- You may batch send actions by using the `signAndSendTransaction({})` method from `account`. This method takes an array of transaction actions, and if one fails, the entire operation will fail. Here's a simple example:
- ```js
- const { connect, transactions, keyStores } = require("near-api-js");
- const fs = require("fs");
- const path = require("path");
- const homedir = require("os").homedir();
-
- const CREDENTIALS_DIR = ".near-credentials";
- const CONTRACT_NAME = "spf.idea404.testnet";
- const WASM_PATH = path.join(__dirname, "../build/uninitialized_nft.wasm");
-
- const credentialsPath = path.join(homedir, CREDENTIALS_DIR);
- const keyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath);
-
- const config = {
- keyStore,
- networkId: "testnet",
- nodeUrl: "https://rpc.testnet.near.org",
- };
-
- sendBatchActions();
-
- async function sendBatchActions() {
- const near = await connect({ ...config, keyStore });
- const account = await near.account(CONTRACT_NAME);
- const args = { some_field: 1, another_field: "hello" };
-
- const balanceBefore = await account.getAccountBalance();
- console.log("Balance before:", balanceBefore);
-
- try {
- const result = await account.signAndSendTransaction({
- receiverId: CONTRACT_NAME,
- actions: [
- transactions.deployContract(fs.readFileSync(WASM_PATH)), // Contract does not get deployed
- transactions.functionCall("new", Buffer.from(JSON.stringify(args)), 10000000000000, "0"), // this call fails
- transactions.transfer("1" + "0".repeat(24)), // 1 NEAR is not transferred either
- ],
- });
- console.log(result);
- } catch (e) {
- console.log("Error:", e);
- }
-
- const balanceAfter = await account.getAccountBalance();
- console.log("Balance after:", balanceAfter);
- }
- ```
+
-
- Response Example
- ```bash
- Balance before: {
- total: '49987878054959838200000000',
- stateStaked: '4555390000000000000000000',
- staked: '0',
- available: '45432488054959838200000000'
- }
- Receipts: 2PPueY6gnA4YmmQUzc8DytNBp4PUpgTDhmEjRSHHVHBd, 3isLCW9SBH1MrPjeEPAmG9saHLj9Z2g7HxzfBdHmaSaG
- Failure [spf.idea404.testnet]: Error: {"index":1,"kind":{"ExecutionError":"Smart contract panicked: panicked at 'Failed to deserialize input from JSON.: Error(\"missing field `owner_id`\", line: 1, column: 40)', nft/src/lib.rs:47:1"}}
- Error: ServerTransactionError: {"index":1,"kind":{"ExecutionError":"Smart contract panicked: panicked at 'Failed to deserialize input from JSON.: Error(\"missing field `owner_id`\", line: 1, column: 40)', nft/src/lib.rs:47:1"}}
- at parseResultError (/Users/dennis/Code/naj-test/node_modules/near-api-js/lib/utils/rpc_errors.js:31:29)
- at Account. (/Users/dennis/Code/naj-test/node_modules/near-api-js/lib/account.js:156:61)
- at Generator.next ()
- at fulfilled (/Users/dennis/Code/naj-test/node_modules/near-api-js/lib/account.js:5:58)
- at processTicksAndRejections (node:internal/process/task_queues:96:5) {
- type: 'FunctionCallError',
- context: undefined,
- index: 1,
- kind: {
- ExecutionError: "Smart contract panicked: panicked at \'Failed to deserialize input from JSON.: Error("missing field `owner_id`", line: 1, column: 40)\', nft/src/lib.rs:47:1"
- },
- transaction_outcome: {
- block_hash: '5SUhYcXjXR1svCxL5BhCuw88XNdEjKXqWgA9X4XZW1dW',
- id: 'SKQqAgnSN27fyHpncaX3fCUxWknBrMtxxytWLRDQfT3',
- outcome: {
- executor_id: 'spf.idea404.testnet',
- gas_burnt: 4839199843770,
- logs: [],
- metadata: [Object],
- receipt_ids: [Array],
- status: [Object],
- tokens_burnt: '483919984377000000000'
- },
- proof: [ [Object], [Object], [Object], [Object], [Object] ]
- }
- }
- Balance after: {
- total: '49985119959346682700000000',
- stateStaked: '4555390000000000000000000',
- staked: '0',
- available: '45429729959346682700000000'
- }
- ```
-
-
- You may also find an example of batch transactions in the [Cookbook](/tools/near-api-js/cookbook).
- You can send actions in a batch to a single receiver. If one action fails then the entire batch of actions will be reverted.
-
- ```rust
- use near_primitives::transaction::Action;
- use near_primitives::action::{FunctionCallAction, TransferAction};
-
- let function_call_action = Action::FunctionCall(Box::new(FunctionCallAction {
- method_name: "increment".to_string(),
- args: vec![],
- gas: 30_000_000_000_000,
- deposit: 0,
- })); // Create a function call action
- let transfer_action = Action::Transfer(TransferAction {
- deposit: 1_000_000_000_000_000_000_000_000,
- }); // Create a transfer action
- let actions = vec![function_call_action, transfer_action];
-
- Transaction::construct(account_id.clone(), receiver_id.clone())
- .add_actions(actions)
- .with_signer(signer)
- .send_to(&network)
- .await
- .unwrap()
- .assert_success();
- ```
+
+
@@ -758,82 +582,73 @@ Transfer NEAR tokens between accounts. This returns an object with transaction a
### Deploy a Contract {#deploy-a-contract}
-You can deploy a contract from a compiled WASM file. This returns an object with transaction and receipts outcomes and status.
+You can deploy a contract from a compiled WASM file.
- ```js
- const account = await nearConnection.account("example-account.testnet");
- const transactionOutcome = await account.deployContract(
- fs.readFileSync("example-file.wasm")
- );
- ```
+
+
Note that the `signer` here needs to be a signer for the same `account_id` as the one used to construct the `Contract` object.
- ```rust
- let new_contract_id: AccountId = "new-contract.testnet".parse().unwrap();
- let contract = Contract(new_contract_id.clone());
-
- new_contract
- .deploy(include_bytes!("../contracts/contract.wasm").to_vec())
- .without_init_call() // Can also be .with_init_call()
- .with_signer(signer)
- .send_to(&network)
- .await
- .unwrap()
- .assert_success();
- ```
+
+
---
-## Keys
-
-You can get and manage keys for an account.
+## View Functions
-### Add Function Access Key {#add-function-access-key}
+View functions are read-only functions that don't change the state of the contract. We can call these functions without a signer / keypair or any gas.
- ```js
- const account = await nearConnection.account("example-account.testnet");
- await account.addKey(
- "8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc", // public key for new account
- "example-account.testnet", // contract this key is allowed to call (optional)
- "example_method", // methods this key is allowed to call (optional)
- "2500000000000" // allowance key can use to call methods (optional)
- );
- ```
+ To call a view function a json provider is used instead of the connection object. You can copy the `viewContract` function into your own code.
+
+
- ```rust
- use near_primitives::account::FunctionCallPermission;
+
- let new_function_call_key = AccessKeyPermission::FunctionCall(FunctionCallPermission {
- allowance: Some(250_000_000_000_000_000_000_000), // Allowance this key is allowed to call (optional)
- receiver_id: "example-account.testnet".to_string(), // Contract this key is allowed to call
- method_names: vec!["example_method".to_string()], // Methods this key is allowed to call
- });
+
+
- let (new_private_key, txn) = Account(account_id.clone())
- .add_key(new_function_call_key)
- .new_keypair()
- .generate_secret_key() // Generates a new keypair via private key
- .unwrap();
+---
- println!("New private key: {:?}", new_private_key.to_string());
- println!("New public key: {:?}", new_private_key.public_key().to_string());
+## Keys
- txn.with_signer(signer.clone()).send_to(&network).await.unwrap(); // Sends the transaction to the network
- ```
+### Get All Access Keys {#get-all-access-keys}
+
+List all the access keys for an account.
+
+
+
+
+
+
+
+
+
+
@@ -842,55 +657,45 @@ You can get and manage keys for an account.
### Add Full Access Key {#add-full-access-key}
+Add a new [full access key](../1.concepts/protocol/access-keys.md#full-access-keys) to an account. Here we generate a random keypair, alternatively you can use a keypair from a seed phrase.
+
- ```js
- // takes public key as string for argument
- const account = await nearConnection.account("example-account.testnet");
- await account.addKey("8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc");
- ```
+
- ```rust
- use near_primitives::account::AccessKeyPermission;
-
- let (new_private_key, txn) = Account(account_id.clone())
- .add_key(AccessKeyPermission::FullAccess)
- .new_keypair()
- .generate_secret_key() // Generates a new keypair via private key
- .unwrap();
-
- println!("New private key: {:?}", new_private_key.to_string());
- println!("New public key: {:?}", new_private_key.public_key().to_string());
-
- txn.with_signer(signer.clone()).send_to(&network).await.unwrap();
- ```
+
-### Get All Access Keys {#get-all-access-keys}
+### Add Function Call Key {#add-function-call-key}
+
+Add a new [function call key](../1.concepts/protocol/access-keys.md#function-call-keys) to an account. When adding the key you should specify the contract id the key can call, an array of methods the key is allowed to call, and the allowance in gas for the key.
- ```js
- const account = await nearConnection.account("example-account.testnet");
- await account.getAccessKeys();
- ```
+
-
- ```rust
- let account = Account(account_id.clone());
- let keys = account.list_keys().fetch_from(&network).await.unwrap();
- ```
+
+
+
@@ -898,21 +703,21 @@ You can get and manage keys for an account.
### Delete Access Key {#delete-access-key}
+When deleting an access key, you need to specify the public key of the key you want to delete.
+
- ```js
- const account = await nearConnection.account("example-account.testnet");
- await account.deleteKey("8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc");
- ```
+
- ```rust
- let account = Account(account_id.clone());
- account.delete_key(new_private_key.public_key()).with_signer(signer.clone()).send_to(&network).await.unwrap();
- ```
+
@@ -921,34 +726,48 @@ You can get and manage keys for an account.
## Utilities
-### NEAR => yoctoNEAR {#near--yoctonear}
+### NEAR to yoctoNEAR {#near-to-yoctonear}
+
+Convert an amount in NEAR to an amount in yoctoNEAR.
- ```js
- // converts NEAR amount into yoctoNEAR (10^-24)
+
- const { utils } = nearAPI;
- const amountInYocto = utils.format.parseNearAmount("1");
- ```
+
+
+
+
-### YoctoNEAR => NEAR {#yoctonear--near}
+### Format Amount {#format-amount}
- ```js
- // converts yoctoNEAR (10^-24) amount into NEAR
+ Format an amount in yoctoNEAR to an amount in NEAR.
- const { utils } = nearAPI;
- const amountInNEAR = utils.format.formatNearAmount("1000000000000000000000000");
- ```
+
+
+
+
+
+ Format an amount of NEAR into a string of NEAR or yoctoNEAR depending on the amount.
+
+
@@ -960,8 +779,16 @@ You can get and manage keys for an account.
- - [Handling Passphrases](https://github.com/near/near-seed-phrase)
- - [Type Docs](https://near.github.io/near-api-js)
+ - [Documentation](https://near.github.io/near-api-js)
+ - [Github](https://github.com/near/near-api-js)
+ - [Full Examples](https://github.com/PiVortex/near-api-examples/tree/main/javascript)
+
+
+
+
+ - [Documentation](https://docs.rs/near-api/latest/near_api/)
+ - [Github](https://github.com/near/near-api-rs)
+ - [Full Examples](https://github.com/PiVortex/near-api-examples/tree/main/rust)
-
\ No newline at end of file
+
From ea053dfd7370fe5917c5b84261a3098b0367bcd6 Mon Sep 17 00:00:00 2001
From: PiVortex
Date: Wed, 18 Dec 2024 10:39:31 +0000
Subject: [PATCH 09/13] change sidebars
---
docs/4.tools/near-api-js/cookbook.md | 26 --
docs/4.tools/near-api-js/faq.md | 434 --------------------
docs/4.tools/near-api-js/naj-account.md | 160 --------
docs/4.tools/near-api-js/naj-contract.md | 128 ------
docs/4.tools/near-api-js/naj-utils.md | 27 --
docs/4.tools/near-api-js/naj-wallet.md | 140 -------
docs/4.tools/near-api-js/quick-reference.md | 258 ------------
docs/4.tools/near-api.md | 7 +-
website/sidebars.js | 22 -
9 files changed, 4 insertions(+), 1198 deletions(-)
delete mode 100644 docs/4.tools/near-api-js/cookbook.md
delete mode 100644 docs/4.tools/near-api-js/faq.md
delete mode 100644 docs/4.tools/near-api-js/naj-account.md
delete mode 100644 docs/4.tools/near-api-js/naj-contract.md
delete mode 100644 docs/4.tools/near-api-js/naj-utils.md
delete mode 100644 docs/4.tools/near-api-js/naj-wallet.md
delete mode 100644 docs/4.tools/near-api-js/quick-reference.md
diff --git a/docs/4.tools/near-api-js/cookbook.md b/docs/4.tools/near-api-js/cookbook.md
deleted file mode 100644
index b13a4c7e1c7..00000000000
--- a/docs/4.tools/near-api-js/cookbook.md
+++ /dev/null
@@ -1,26 +0,0 @@
----
-id: cookbook
-title: Common Use Cases
-sidebar_label: Cookbook
----
-
-import Tabs from '@theme/Tabs';
-import TabItem from '@theme/TabItem';
-
-The repository contains [many recipes](https://github.com/near/near-api-js/blob/master/packages/cookbook) that you can readily use to solve common case scenarios.
-
-| Name | Description |
-|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| ----------------------------------------------------------------------------------------------------------- |
-| **ACCOUNTS** | |
-| [Create Account](https://github.com/near/near-api-js/blob/master/packages/cookbook/accounts/create-testnet-account.js) | Create [NEAR accounts](/concepts/protocol/account-model) without using NEAR Wallet. |
-| [Access Key Rotation](https://github.com/near/near-api-js/tree/master/packages/cookbook/accounts/access-keys) | Create and delete [access keys](/concepts/protocol/access-keys) for added security. |
-| **TRANSACTIONS** | |
-| [Get Transaction Status](https://github.com/near/near-api-js/blob/master/packages/cookbook/transactions/get-tx-status.ts) | Gets transaction status using a tx hash and associated account/contract ID. |
-| [Recent Transaction Details](https://github.com/near/near-api-js/blob/master/packages/cookbook/transactions/get-tx-detail.js) | Get recent transaction details without using an [indexing](/concepts/advanced/near-indexer-framework) service. |
-| [Batch Transactions](https://github.com/near/near-api-js/blob/master/packages/cookbook/transactions/batch-transactions.js) | Sign and send multiple [transactions](/concepts/protocol/transactions). |
-| **UTILS** | |
-| [Deploy Contract](https://github.com/near/near-api-js/blob/master/packages/cookbook/utils/deploy-contract.js) | Deploys a smart contract using a pre-compiled WASM file. |
-| [Calculate Gas](https://github.com/near/near-api-js/blob/master/packages/cookbook/utils/calculate-gas.js) | Calculate [gas burnt](/concepts/protocol/gas) from any contract call. |
-| [Read State w/o Account](https://github.com/near/near-api-js/blob/master/packages/cookbook/utils/get-state.js) | Read state of a contract without instantiating an account. |
-| [Wrap](https://github.com/near/near-api-js/blob/master/packages/cookbook/utils/wrap-near.js) & [Unwrap](https://github.com/near/near-api-js/blob/master/packages/cookbook/utils/unwrap-near.js) NEAR | Wrap and unwrap NEAR using the `wrap.near` smart contract. |
-| [Verify Signature](https://github.com/near/near-api-js/blob/master/packages/cookbook/utils/verify-signature.js) | Verify a key pair signature. |
diff --git a/docs/4.tools/near-api-js/faq.md b/docs/4.tools/near-api-js/faq.md
deleted file mode 100644
index 55647966db9..00000000000
--- a/docs/4.tools/near-api-js/faq.md
+++ /dev/null
@@ -1,434 +0,0 @@
----
-id: faq
-title: FAQ for NEAR JavaScript API
-sidebar_label: FAQ
----
-
-A collection of Frequently Asked Questions by the community.
-
-
-## General {#general}
-
-### Can I use `near-api-js` on a static html page? {#can-i-use-near-api-js-on-a-static-html-page}
-
-You can load the script from a CDN.
-
-```html
-
-```
-
-:::note
-Make sure you load the latest version.
-
-Versions list is on [npmjs.com](https://www.npmjs.com/package/near-api-js)
-:::
-
-
-Example Implementation
-
-
-```html
-
-
-
-
-
-
-
- Document
-
-
-
-
-
-
-
-
-
-
-
-```
-
-
-
-
----
-
-### What front-end frameworks can I use the JavaScript API with?
-
-The JavaScript API is framework-agnostic. You can include it in any front-end framework, such as React, Vue, Angular, and others.
-
-You can use [`create-near-app`](https://github.com/near/create-near-app) to quickly bootstrap projects with different templates:
-
- npx create-near-app
-
-### Can I use the JavaScript API with mobile JavaScript frameworks such as React Native?
-
-The JavaScript API can be used in most JavaScript runtimes, and under the hood, itβs an abstraction over NEARβs [RPC API](/api/rpc/introduction). However, notice that the Wallet canβt be used everywhere. For example, in React Native apps youβll be able to use the Wallet in web versions of the apps, but it wonβt work in the native app deployments.
-
-You can use the Wallet in `WebView` components in iOS or Android, however be aware that it uses `LocalStorage` for `KeyStore`, and itβs your responsibility to persist the storage when you manage loading of `WebView` components.
-
----
-
-## Transactions {#transactions}
-
-### How to check the status of transaction
-
-Please refer to examples about transactions in the [Cookbook](/tools/near-api-js/cookbook).
-
-### How transactions are signed and sent by near-api-js
-
-There are a few steps involved before transaction data is communicated to the network and eventually included in a block. The following steps are taken when creating, signing and ultimately a transaction from a user's account:
-
-1. The user creates a transaction object using the [`account.signAndSendTransaction` method](https://github.com/near/near-api-js/blob/f78616480ba84c73f681211fe6266bd2ed2b9da1/packages/near-api-js/src/account.ts#L200). This method accepts an array of actions and returns an object for the outcome of the transaction.
-2. The transaction is signed using the [`account.signTransaction` method](https://github.com/near/near-api-js/blob/f78616480ba84c73f681211fe6266bd2ed2b9da1/packages/near-api-js/src/account.ts#L204). This method accepts an array of actions and returns a signed transaction object.
-3. The signed transaction object is sent to the network using the [`account.connection.provider.sendTransaction` method](https://github.com/near/near-api-js/blob/f78616480ba84c73f681211fe6266bd2ed2b9da1/packages/near-api-js/src/account.ts#L208). This method accepts a signed transaction object and returns a transaction hash. This step [performs the borsh serialization of the transaction object](https://github.com/near/near-api-js/blob/f78616480ba84c73f681211fe6266bd2ed2b9da1/packages/near-api-js/src/providers/json-rpc-provider.ts#L80) and calls the [`broadcast_tx_commit` JSON RPC method with the serialized transaction object encoded in base64](https://github.com/near/near-api-js/blob/f78616480ba84c73f681211fe6266bd2ed2b9da1/packages/near-api-js/src/providers/json-rpc-provider.ts#L81).
-
-### How to send batch transactions
-
-You may batch send transactions by using the `signAndSendTransaction({})` method from `account`. This method takes an array of transaction actions, and if one fails, the entire operation will fail. Here's a simple example:
-
-```js
-const { connect, transactions, keyStores } = require("near-api-js");
-const fs = require("fs");
-const path = require("path");
-const homedir = require("os").homedir();
-
-const CREDENTIALS_DIR = ".near-credentials";
-const CONTRACT_NAME = "spf.idea404.testnet";
-const WASM_PATH = path.join(__dirname, "../build/uninitialized_nft.wasm");
-
-const credentialsPath = path.join(homedir, CREDENTIALS_DIR);
-const keyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath);
-
-const config = {
- keyStore,
- networkId: "testnet",
- nodeUrl: "https://rpc.testnet.near.org",
-};
-
-sendTransactions();
-
-async function sendTransactions() {
- const near = await connect({ ...config, keyStore });
- const account = await near.account(CONTRACT_NAME);
- const args = { some_field: 1, another_field: "hello" };
-
- const balanceBefore = await account.getAccountBalance();
- console.log("Balance before:", balanceBefore);
-
- try {
- const result = await account.signAndSendTransaction({
- receiverId: CONTRACT_NAME,
- actions: [
- transactions.deployContract(fs.readFileSync(WASM_PATH)), // Contract does not get deployed
- transactions.functionCall("new", Buffer.from(JSON.stringify(args)), 10000000000000, "0"), // this call fails
- transactions.transfer("1" + "0".repeat(24)), // 1 NEAR is not transferred either
- ],
- });
- console.log(result);
- } catch (e) {
- console.log("Error:", e);
- }
-
- const balanceAfter = await account.getAccountBalance();
- console.log("Balance after:", balanceAfter);
-}
-```
-
-```
-Balance before: {
- total: '49987878054959838200000000',
- stateStaked: '4555390000000000000000000',
- staked: '0',
- available: '45432488054959838200000000'
-}
-Receipts: 2PPueY6gnA4YmmQUzc8DytNBp4PUpgTDhmEjRSHHVHBd, 3isLCW9SBH1MrPjeEPAmG9saHLj9Z2g7HxzfBdHmaSaG
- Failure [spf.idea404.testnet]: Error: {"index":1,"kind":{"ExecutionError":"Smart contract panicked: panicked at 'Failed to deserialize input from JSON.: Error(\"missing field `owner_id`\", line: 1, column: 40)', nft/src/lib.rs:47:1"}}
-Error: ServerTransactionError: {"index":1,"kind":{"ExecutionError":"Smart contract panicked: panicked at 'Failed to deserialize input from JSON.: Error(\"missing field `owner_id`\", line: 1, column: 40)', nft/src/lib.rs:47:1"}}
- at parseResultError (/Users/dennis/Code/naj-test/node_modules/near-api-js/lib/utils/rpc_errors.js:31:29)
- at Account. (/Users/dennis/Code/naj-test/node_modules/near-api-js/lib/account.js:156:61)
- at Generator.next ()
- at fulfilled (/Users/dennis/Code/naj-test/node_modules/near-api-js/lib/account.js:5:58)
- at processTicksAndRejections (node:internal/process/task_queues:96:5) {
- type: 'FunctionCallError',
- context: undefined,
- index: 1,
- kind: {
- ExecutionError: 'Smart contract panicked: panicked at \'Failed to deserialize input from JSON.: Error("missing field `owner_id`", line: 1, column: 40)\', nft/src/lib.rs:47:1'
- },
- transaction_outcome: {
- block_hash: '5SUhYcXjXR1svCxL5BhCuw88XNdEjKXqWgA9X4XZW1dW',
- id: 'SKQqAgnSN27fyHpncaX3fCUxWknBrMtxxytWLRDQfT3',
- outcome: {
- executor_id: 'spf.idea404.testnet',
- gas_burnt: 4839199843770,
- logs: [],
- metadata: [Object],
- receipt_ids: [Array],
- status: [Object],
- tokens_burnt: '483919984377000000000'
- },
- proof: [ [Object], [Object], [Object], [Object], [Object] ]
- }
-}
-Balance after: {
- total: '49985119959346682700000000',
- stateStaked: '4555390000000000000000000',
- staked: '0',
- available: '45429729959346682700000000'
-}
-
-```
-
-You may also find an example of batch transactions in the [Cookbook](/tools/near-api-js/cookbook).
-
----
-
-## Accounts {#accounts}
-
-### Whatβs the difference between `Account` and `ConnectedWalletAccount`?
-
-Interaction with the wallet is only possible in a web-browser environment because NEARβs Wallet is web-based.
-The difference between `Account` and `ConnectedWalletAccount` is mostly about the way it signs transactions. The `ConnectedWalletAccount` uses the wallet to approve transactions.
-Under the hood the `ConnectedWalletAccount` inherits and overrides some methods of `Account`.
-
-### How to create implicit accounts?
-
-You can read about it in the article about [Implicit Accounts](https://docs.near.org/integrations/implicit-accounts).
-
----
-
-## Contracts {#contracts}
-
-### How do I attach gas / a deposit? {#how-do-i-attach-gas--a-deposit}
-
-After [contract is instantiated](/tools/near-api-js/contract#load-contract) you can then call the contract and specify the amount of attached gas.
-
-```js
-await contract.method_name(
- {
- arg_name: "value", // argument name and value - pass empty object if no args required
- },
- "300000000000000", // attached GAS (optional)
- "1000000000000000000000000" // attached deposit in yoctoNEAR (optional)
-);
-```
-
----
-
-## Common Errors {#common-errors}
-
-### RPC Errors
-
-Refer to the exhaustive [list of error messages](https://github.com/near/near-api-js/blob/16ba17251ff7d9c8454261001cd6b87e9a994789/packages/near-api-js/src/res/error_messages.json)
-that RPC endpoints throws and JavaScript API propagates.
-
-### Missing contract methods {#missing-contract-method}
-
-When constructing a `Contract` instance on the client-side, you need to specify
-the contract's methods. If you misspell, mismatch, or miss method names - you'll
-receive errors about missing methods.
-
-There are a few cases of missing or wrong methods:
-- When you call a method you didn't specify in the constructor.
-- When you call a method that doesn't exist on the blockchain's contract (but you did specify it in the client-side constructor).
-- When you mismatch between `viewMethods` and `changeMethods`.
-
-For example, let's look at the following contract code.
-It contains one `view` and one `call` method:
-
-```js
-@NearBindgen
-class MyContract extends NearContract {
- constructor() { super(); }
-
- @view
- method_A_view(): string {
- return 'Hi';
- }
-
- @call
- method_B_call(): void {}
-}
-```
-
-#### Client-side errors for missing methods
-
-##### `TypeError: contract.METHOD_NAME is not a function`
-
-The following contract constructor declares only `method_A_view`, it doesn't declare `method_B_call`
-```js
-const contract = await new nearAPI.Contract(
- walletConnection.account(), 'guest-book.testnet',
- {
- viewMethods: ['method_A_view'], // <=== Notice this
- changeMethods: [], // <=== Notice this
- sender: walletConnection.getAccountId(),
- }
-);
-
-// This will work because we declared `method_A_view` in constructor
-await contract.method_A_view();
-
-// This will throw `TypeError: contract.method_B_call is not a function`
-// because we didn't declare `method_B_call` in constructor,
-// even if it exists in the real contract.
-await contract.method_B_call();
-
-// This will also throw `TypeError: contract.method_C is not a function`,
-// not because `method_C` doesn't exist on the contract, but because we didn't declare it
-// in the client-side constructor.
-await contract.method_C();
-```
-
-#### RPC errors for missing methods
-
-##### `wasm execution failed with error: FunctionCallError(MethodResolveError(MethodNotFound))`
-
-In this example we specify and call a method, but this method doesn't exist on the blockchain:
-```js
-const contract = await new nearAPI.Contract(
- // ...
- {
- viewMethods: ["method_C"], // <=== method_C doesn't exist on the contract above
- changeMethods: [],
- // ...
- }
-);
-// We did specify `method_C` name in constructor, so this function exists on client-side `contract` instance,
-// but a method with this name does not exist on the actual contract on the blockchain.
-// This will return an error from RPC call `FunctionCallError(MethodResolveError(MethodNotFound))`
-// and will throw it on the client-side
-await contract.method_C();
-
-// Notice: if we call `method_A_view` we get `TypeError: contract.method_A_view is not a function`.
-// Even though the method exists on the actual blockchain contract,
-// we didn't specify `method_A_view` in the contract's client-side constructor.
-await contract.method_A_view();
-```
-
-##### `wasm execution failed with error: FunctionCallError(HostError(ProhibitedInView { method_name: "storage_write" }))`
-
-Last case is when you mismatch `viewMethods` and `changeMethods`.
-
-In the contract above we declared:
-- A `@view` method named `method_A_view`
-- A `@call` method named `method_B_call`
-
-In a client-side constructor, the contract's `@view` method names must be specified under `viewMethods`,
-and the contract's `@call` method names must be specified under `changeMethods`.
-If we mismatch between the types we will receive errors.
-
-For example:
-```js
-const contract = await new nearAPI.Contract(
- // ...
- {
- viewMethods: ['method_B_call'], // <=== here should be `method_A_view`
- changeMethods: ['method_A_view'], // <=== and here should be `method_B_call`
- // ...
- }
-);
-
-// This will return an error from RPC call and throw:
-// `wasm execution failed with error: FunctionCallError(HostError(ProhibitedInView { method_name: "storage_write" }))`
-// This error indicates that we are trying to call a state-changing method but declare it as a read-only method in client-side.
-await contract.method_B_call();
-
-// The following behavior is undefined and might not work as expected.
-// `method_A_veiw` should be declared under `viewMethods` and in our example here we declare it under `changeMethods`.
-await contract.method_A_view();
-```
-
-### Class `{X}` is missing in schema: publicKey
-
-There is currently a known issue with the JavaScript API library, when you `import` it more than once
-it might cause a namespace collision.
-
-A temporary workaround: make sure you don't re-import it, for example when running tests.
-
----
-
-### `regeneratorRuntime` is not defined {#regeneratorruntime-is-not-defined}
-
-You are probably using [Parcel](https://parceljs.org/) like we do in [other examples](https://github.com/near-examples). Please make sure you have this line at the top of your main JS file. (Most likely `index.js`):
-
-```js
-import "regenerator-runtime/runtime";
-```
-
-- Also, ensure the dependencies for this are added to the project by checking the dev dependencies in your `package.json`. If not found you can install this by running the following in your terminal:
-
-```bash
-npm install regenerator-runtime --save-dev
-```
-
----
-
-### Window error using `Node.js` {#window-error-using-nodejs}
-
-You're maybe using a KeyStore that's for the browser. Instead, use a [filesystem key](/tools/near-api-js/quick-reference#key-store) or private key string.
-
-**Browser KeyStore:**
-
-```js
-const { keyStores } = require("near-api-js");
-const keyStore = new keyStores.BrowserLocalStorageKeyStore();
-```
-
-**FileSystem KeyStore:**
-
-```js
-const { keyStores } = require("near-api-js");
-const KEY_PATH = "~./near-credentials/testnet/example-account.json";
-const keyStore = new keyStores.UnencryptedFileSystemKeyStore(KEY_PATH);
-```
diff --git a/docs/4.tools/near-api-js/naj-account.md b/docs/4.tools/near-api-js/naj-account.md
deleted file mode 100644
index 8c762fcb23b..00000000000
--- a/docs/4.tools/near-api-js/naj-account.md
+++ /dev/null
@@ -1,160 +0,0 @@
----
-id: account
-title: Account
-sidebar_label: Account
----
-
-You can interact with, create or delete NEAR accounts.
-
-### Load Account {#load-account}
-
-This will return an Account object for you to interact with.
-
-```js
-const account = await nearConnection.account("example-account.testnet");
-```
-
-[ Class `Account`](https://near.github.io/near-api-js/classes/near_api_js.account.Account.html)
-
-### Create Account {#create-account}
-
-Create a sub-account.
-
-```js
-// creates a sub-account using funds from the account used to create it.
-const account = await nearConnection.account("example-account.testnet");
-await account.createAccount(
- "sub.example-account.testnet", // sub-account name
- "8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc", // public key for sub account
- "10000000000000000000" // initial balance for new account in yoctoNEAR
-);
-```
-
-[ Method `Account.createAccount`](https://near.github.io/near-api-js/classes/near_api_js.account.Account.html#createAccount)
-
-For creating .near or .testnet accounts please refer to the [cookbook](https://github.com/near/near-api-js/tree/master/packages/cookbook/accounts).
-
-### Delete Account {#delete-account}
-
-```js
-// deletes account found in the `account` object
-// transfers remaining account balance to the accountId passed as an argument
-const account = await nearConnection.account("example-account.testnet");
-await account.deleteAccount("beneficiary-account.testnet");
-```
-
-[ Method `Account.deleteAccount`](https://near.github.io/near-api-js/classes/near_api_js.account.Account.html#deleteAccount)
-
-### Get Account Balance {#get-account-balance}
-
-```js
-// gets account balance
-const account = await nearConnection.account("example-account.testnet");
-await account.getAccountBalance();
-```
-
-[ Method `Account.getAccountBalance`](https://near.github.io/near-api-js/classes/near_api_js.account.Account.html#getAccountBalance)
-
-### Get Account details {#get-account-details}
-
-Returns information about an account, such as authorized apps.
-
-```js
-// gets account details in terms of authorized apps and transactions
-const account = await nearConnection.account("example-account.testnet");
-await account.getAccountDetails();
-```
-
-[ Method `Account.getAccountDetails`](https://near.github.io/near-api-js/classes/near_api_js.account.Account.html#getAccountDetails)
-
-### Deploy a Contract {#deploy-a-contract}
-
-You can deploy a contract from a compiled WASM file. This returns an object with transaction and receipts outcomes and status.
-
-```js
-const account = await nearConnection.account("example-account.testnet");
-const transactionOutcome = await account.deployContract(
- fs.readFileSync("example-file.wasm")
-);
-```
-
-[ Method `Account.deployContract`](https://near.github.io/near-api-js/classes/near_api_js.account.Account.html#deployContract)
-
-[ Interface `FinalExecutionOutcome`](https://near.github.io/near-api-js/interfaces/_near_js_types.provider_response.FinalExecutionOutcome.html)
-
-### Send Tokens {#send-tokens}
-
-Transfer NEAR tokens between accounts. This returns an object with transaction and receipts outcomes and status.
-
-```js
-const account = await nearConnection.account("sender-account.testnet");
-await account.sendMoney(
- "receiver-account.testnet", // receiver account
- "1000000000000000000000000" // amount in yoctoNEAR
-);
-```
-
-[ Method `Account.sendMoney`](https://near.github.io/near-api-js/classes/near_api_js.account.Account.html#sendMoney)
-
-[ Interface `FinalExecutionOutcome`](https://near.github.io/near-api-js/interfaces/_near_js_types.provider_response.FinalExecutionOutcome.html)
-
-### State {#state}
-
-Get basic account information, such as amount of tokens the account has or the amount of storage it uses.
-
-```js
-const account = await nearConnection.account("example-account.testnet");
-const accountState = await account.state();
-```
-
-[ Method `Account.state`](https://near.github.io/near-api-js/classes/near_api_js.account.Account.html#state)
-
-[ Interface `AccountView`](https://near.github.io/near-api-js/interfaces/near_api_js.providers_provider.AccountView.html)
-
-### Access Keys {#access-keys}
-
-You can get and manage keys for an account.
-
-#### Add Full Access Key {#add-full-access-key}
-
-```js
-// takes public key as string for argument
-const account = await nearConnection.account("example-account.testnet");
-await account.addKey("8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc");
-```
-
-[ Method `Account.addKey`](https://near.github.io/near-api-js/classes/near_api_js.account.Account.html#addKey)
-
-#### Add Function Access Key {#add-function-access-key}
-
-```js
-const account = await nearConnection.account("example-account.testnet");
-await account.addKey(
- "8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc", // public key for new account
- "example-account.testnet", // contract this key is allowed to call (optional)
- "example_method", // methods this key is allowed to call (optional)
- "2500000000000" // allowance key can use to call methods (optional)
-);
-```
-
-[ Method `Account.addKey`](https://near.github.io/near-api-js/classes/near_api_js.account.Account.html#addKey)
-
-#### Get All Access Keys {#get-all-access-keys}
-
-```js
-const account = await nearConnection.account("example-account.testnet");
-await account.getAccessKeys();
-```
-
-[ Method `Account.getAccessKeys`](https://near.github.io/near-api-js/classes/near_api_js.account.Account.html#getAccessKeys)
-
-[ Interface `AccessKeyInfoView`](https://near.github.io/near-api-js/interfaces/near_api_js.providers_provider.AccessKeyInfoView.html)
-
-#### Delete Access Key {#delete-access-key}
-
-```js
-const account = await nearConnection.account("example-account.testnet");
-await account.deleteKey("8hSHprDq2StXwMtNd43wDTXQYsjXcD4MJTXQYsjXcc");
-```
-
-[ Method `Account.deleteKey`](https://near.github.io/near-api-js/classes/near_api_js.account.Account.html#deleteKey)
diff --git a/docs/4.tools/near-api-js/naj-contract.md b/docs/4.tools/near-api-js/naj-contract.md
deleted file mode 100644
index 60b2af055dc..00000000000
--- a/docs/4.tools/near-api-js/naj-contract.md
+++ /dev/null
@@ -1,128 +0,0 @@
----
-id: contract
-title: Contract
-sidebar_label: Contract
----
-
-import Tabs from '@theme/Tabs';
-import TabItem from '@theme/TabItem';
-
-When you instantiate an instance of `Contract` you need to specify the names of the functions you have on your smart contract.
-Then the new instance of `Contract` will have methods with the same names as your smart contract functions.
-For example if you deployed a contract with `my_smart_contract_function` function on it, then this will work:
-
-```js
-const contract = new Contract(account, "example-contract.testnet", {
- changeMethods: ["my_smart_contract_function"], // your smart-contract has a function `my_smart_contract_function`
-});
-// `contract` object has `my_smart_contract_function` function on it:
-contract.my_smart_contract_function();
-```
-
-### Load Contract {#load-contract}
-
-
-
-
-```js
-const { Contract } = nearAPI;
-
-const contract = new Contract(
- account, // the account object that is connecting
- "example-contract.testnet",
- {
- // name of contract you're connecting to
- viewMethods: ["getMessages"], // view methods do not change state but usually return a value
- changeMethods: ["addMessage"], // change methods modify state
- }
-);
-```
-
-[ Class `Contract`](https://near.github.io/near-api-js/classes/_near_js_accounts.contract.Contract.html)
-
-
-
-
-```js
-const { Contract } = nearAPI;
-
-const contract = new Contract(
- wallet.account(), // the account object that is connecting
- "example-contract.testnet",
- {
- // name of contract you're connecting to
- viewMethods: ["getMessages"], // view methods do not change state but usually return a value
- changeMethods: ["addMessage"], // change methods modify state
- }
-);
-```
-
-[ Class `Contract`](https://near.github.io/near-api-js/classes/_near_js_accounts.contract.Contract.html)
-
-
-
-
-### Call Contract {#call-contract}
-
-
-
-
-```js
-const contract = new Contract(account, "example-contract.testnet", {
- changeMethods: ["method_name"],
-});
-await contract.method_name(
- {
- arg_name: "value", // argument name and value - pass empty object if no args required
- },
- "300000000000000", // attached GAS (optional)
- "1000000000000000000000000" // attached deposit in yoctoNEAR (optional)
-);
-```
-
-
-
-
-```js
-const contract = new Contract(account, "example-contract.testnet", {
- changeMethods: ["method_name"],
-});
-await contract.method_name({
- callbackUrl: "https://example.com/callback", // callbackUrl after the transaction approved (optional)
- meta: "some info", // meta information NEAR Wallet will send back to the application. `meta` will be attached to the `callbackUrl` as a url param
- args: {
- arg_name: "value", // argument name and value - pass empty object if no args required
- },
- gas: 300000000000000, // attached GAS (optional)
- amount: 1000000000000000000000000, // attached deposit in yoctoNEAR (optional)
-});
-```
-
-
-
-
-```js
-const contract = new Contract(account, "example-contract.testnet", {
- viewMethods: ["view_method_name"],
-});
-const response = await contract.view_method_name();
-```
-
-
-
-
-```js
-const contract = new Contract(account, "example-contract.testnet", {
- viewMethods: ["view_method_name"],
-});
-const response = await contract.view_method_name({ arg_name: "arg_value" });
-```
-
-
-
-
-[ Class `Contract`](https://near.github.io/near-api-js/classes/_near_js_accounts.contract.Contract.html)
-
-[//]: # "## Transactions {#transactions}"
-[//]: # "A [Transaction](/concepts/protocol/transactions) is a collection of Actions, and there are few types of Actions."
-[//]: # "For every type of Action there is a function on Account that you can use to invoke the Action, but Account also exposes `signAndSendTransaction` function which you can use to build and invoke a batch transaction."
diff --git a/docs/4.tools/near-api-js/naj-utils.md b/docs/4.tools/near-api-js/naj-utils.md
deleted file mode 100644
index e20f3a95177..00000000000
--- a/docs/4.tools/near-api-js/naj-utils.md
+++ /dev/null
@@ -1,27 +0,0 @@
----
-id: utils
-title: Utilities
-sidebar_label: Utilities
----
-
-### NEAR => yoctoNEAR {#near--yoctonear}
-
-```js
-// converts NEAR amount into yoctoNEAR (10^-24)
-
-const { utils } = nearAPI;
-const amountInYocto = utils.format.parseNearAmount("1");
-```
-
-[ Function `parseNearAmount`](https://near.github.io/near-api-js/functions/_near_js_utils.format.parseNearAmount.html)
-
-### YoctoNEAR => NEAR {#yoctonear--near}
-
-```js
-// converts yoctoNEAR (10^-24) amount into NEAR
-
-const { utils } = nearAPI;
-const amountInNEAR = utils.format.formatNearAmount("1000000000000000000000000");
-```
-
-[ Function `formatNearAmount`](https://near.github.io/near-api-js/functions/_near_js_utils.format.formatNearAmount.html)
diff --git a/docs/4.tools/near-api-js/naj-wallet.md b/docs/4.tools/near-api-js/naj-wallet.md
deleted file mode 100644
index 47355d83e88..00000000000
--- a/docs/4.tools/near-api-js/naj-wallet.md
+++ /dev/null
@@ -1,140 +0,0 @@
----
-id: wallet
-title: Interacting with the Wallet
-sidebar_label: Wallet
----
-
-import Tabs from '@theme/Tabs';
-import TabItem from '@theme/TabItem';
-
-Wallet interaction is possible only in the browser, because NEAR's Wallet is web-based.
-
-Most frequent action is Sign In. Your user is redirected to the Wallet page to authorize your application.
-Once the user has Signed In, an access key is saved in browser's LocalStorage.
-All following actions that require the access key will be allowed.
-In case a user needs to authorize a transaction that has a deposit attached, your user will be automatically redirected to the Wallet again.
-
-### Creating Wallet Connection {#wallet-connection}
-
-In Wallet connection you use a LocalStorage [`KeyStore`](/tools/near-api-js/quick-reference#key-store).
-
-
-
-
-```js
-const { connect, keyStores, WalletConnection } = nearAPI;
-
-const connectionConfig = {
- networkId: "testnet",
- keyStore: new keyStores.BrowserLocalStorageKeyStore(),
- nodeUrl: "https://rpc.testnet.near.org",
- walletUrl: "https://testnet.mynearwallet.com/",
- helperUrl: "https://helper.testnet.near.org",
- explorerUrl: "https://testnet.nearblocks.io",
-};
-
-// connect to NEAR
-const nearConnection = await connect(connectionConfig);
-
-// create wallet connection
-// provide a prefix for the key
-const walletConnection = new WalletConnection(nearConnection, "example-prefix");
-```
-
-
-
-
-```js
-const { connect, keyStores, WalletConnection } = nearAPI;
-
-const connectionConfig = {
- networkId: "mainnet",
- keyStore: new keyStores.BrowserLocalStorageKeyStore(),
- nodeUrl: "https://rpc.mainnet.near.org",
- walletUrl: "https://wallet.mainnet.near.org",
- helperUrl: "https://helper.mainnet.near.org",
- explorerUrl: "https://nearblocks.io",
-};
-
-// connect to NEAR
-const nearConnection = await connect(connectionConfig);
-
-// create wallet connection
-const walletConnection = new WalletConnection(nearConnection);
-```
-
-
-
-
-
-[ Module `browserConnect`](https://near.github.io/near-api-js/modules/near_api_js.browserConnect.html)
-
-[ Class `WalletConnection`](https://near.github.io/near-api-js/classes/_near_js_wallet_account.walletAccount.WalletConnection.html)
-
-### Ask your user to Sign In {#sign-in}
-
-You first create a [WalletConnection](#wallet-connection), and then call `requestSignIn`.
-This will redirect the current page to the Wallet authentication page. You can optionally configure success and failure redirect URLs.
-
-When you create a wallet connection you have the option to create a [function call access key](/concepts/protocol/access-keys#function-call-keys) for a specific contract to be used by your application. This allows the app to automatically sign `non-payable methods` for the user without having to sign each transaction manually in the wallet. You can also decide to specify a list of `methodNames` that will restrict the key to sign only certain methods on the specified contract. Passing an empty array will allow all methods to be signed.
-
-```js
-// const walletConnection = new WalletConnection(nearConnection);
-// all parameters are optional
-walletConnection.requestSignIn({
- contractId: "example-contract.testnet.REPLACE_ME", // optional
- methodNames: [], // optional
- successUrl: "REPLACE_ME://.com/success", // optional redirect URL on success
- failureUrl: "REPLACE_ME://.com/failure", // optional redirect URL on failure
-});
-```
-
-[ Method `WalletConnection.requestSignIn`](https://near.github.io/near-api-js/classes/_near_js_wallet_account.walletAccount.WalletConnection.html#requestSignIn)
-
-:::tip
-Sign In is **_not required_** if you are using an alternative key store to local storage, or you are not signing transactions (meaning - you are only calling read-only _view_ methods on a contract)
-:::
-
-### Sign Out your user {#sign-out}
-
-```js
-// const walletConnection = new WalletConnection(nearConnection);
-walletConnection.signOut();
-```
-
-[ Method `WalletConnection.signOut`](https://near.github.io/near-api-js/classes/_near_js_wallet_account.walletAccount.WalletConnection.html#signOut)
-
-### Check if Signed In {#check-if-signed-in}
-
-```js
-// const walletConnection = new WalletConnection(nearConnection);
-if (walletConnection.isSignedIn()) {
- // user is signed in
-}
-```
-
-[ Method `WalletConnection.isSignedId`](https://near.github.io/near-api-js/classes/_near_js_wallet_account.walletAccount.WalletConnection.html#isSignedIn)
-
-### Get Wallet Account {#get-authorized-account}
-
-Get the [Account](naj-account.md) your user has signed in with in the Wallet.
-
-#### Get Account ID (as string) {#get-authorized-account-id}
-
-```js
-// const walletConnection = new WalletConnection(nearConnection);
-const walletAccountId = walletConnection.getAccountId();
-```
-
-[ Method `WalletConnection.getAccountId`](https://near.github.io/near-api-js/classes/_near_js_wallet_account.walletAccount.WalletConnection.html#getAccountId)
-
-#### Get Account Object {#get-authorized-account-object}
-
-```js
-// const walletConnection = new WalletConnection(nearConnection);
-const walletAccountObj = walletConnection.account();
-```
-
-[ Method `WalletConnection.account`](https://near.github.io/near-api-js/classes/_near_js_wallet_account.walletAccount.WalletConnection.html#account)
-
-[ Class `ConnectedWalletAccount`](https://near.github.io/near-api-js/classes/_near_js_wallet_account.walletAccount.ConnectedWalletAccount.html)
diff --git a/docs/4.tools/near-api-js/quick-reference.md b/docs/4.tools/near-api-js/quick-reference.md
deleted file mode 100644
index d8de49d4789..00000000000
--- a/docs/4.tools/near-api-js/quick-reference.md
+++ /dev/null
@@ -1,258 +0,0 @@
----
-id: quick-reference
-title: Using JavaScript API to interact with NEAR
-sidebar_label: Using JavaScript API
----
-
-import Tabs from '@theme/Tabs';
-import TabItem from '@theme/TabItem';
-
-## Quick Reference
-
-- [Installation](#install)
-- [Interacting with the Wallet](naj-wallet.md)
-- [Accounts](naj-account.md)
-- [Contracts](naj-contract.md)
-- [Utilities](naj-utils.md)
-
-## What is `near-api-js`
-
-`near-api-js` is a complete library to interact with the NEAR blockchain. You can use it in the browser, or in Node.js runtime.
-
-You'll typically first create a connection to NEAR with [`connect`](#connect) using a [`KeyStore`](#key-store).
-With the connection object you now can:
-
-- Interact with the [Wallet](naj-wallet.md) in a browser.
-- Instantiate an [Account](naj-account.md) object to:
- - Send tokens
- - Deploy contracts
- - Inspect, create or delete accounts
- - Manage keys for accounts.
-- Instantiate a [Contract](naj-contract.md) object to call smart contract methods.
-
-The library also contains some [utility functions](naj-utils.md).
-
-:::tip
-To quickly get started with integrating NEAR in a web browser, read our [Web Frontend integration](/build/web3-apps/integrate-contracts) article.
-:::
-
-:::info
-Note the difference between `near-api-js` and `near-sdk-js`:
-
-The JavaScript _SDK_ is a library for developing smart contracts. It contains classes and functions you use to write your smart contract code.
-
-The JavaScript _API_ is a complete library for all possible commands to interact with NEAR. Itβs a wrapper for the RPC endpoints, a library to interact with NEAR Wallet in the browser, and a tool for keys management.
-:::
-
----
-
-## Install {#install}
-
-Include `near-api-js` as a dependency in your package.
-
-```bash
-npm i --save near-api-js
-```
-
-## Import {#import}
-
-You can use the API library in the browser, or in Node.js runtime. Some features are available only in one of the environments.
-For example, the `WalletConnection` is only for the browser, and there are different `KeyStore` providers for each environment.
-
-
-
-
-```js
-import * as nearAPI from "near-api-js";
-```
-
-
-
-
-```js
-const nearAPI = require("near-api-js");
-```
-
-
-
-
-## Key Store {#key-store}
-
-If you sign transactions, you need to create a _Key Store_. In the browser, the LocalStorage KeyStore will be used once you ask your user to Sign In with the Wallet.
-
-
-
-
-```js
-// creates keyStore using private key in local storage
-
-const { keyStores } = nearAPI;
-const myKeyStore = new keyStores.BrowserLocalStorageKeyStore();
-```
-
-[ Class `BrowserLocalStorageKeyStore`](https://near.github.io/near-api-js/classes/_near_js_keystores_browser.browser_local_storage_key_store.BrowserLocalStorageKeyStore.html)
-
-
-
-
-```js
-// creates a keyStore that searches for keys in .near-credentials
-// requires credentials stored locally by using a NEAR-CLI command: `near login`
-// https://docs.near.org/tools/cli#near-login
-
-const { keyStores } = nearAPI;
-const homedir = require("os").homedir();
-const CREDENTIALS_DIR = ".near-credentials";
-const credentialsPath = require("path").join(homedir, CREDENTIALS_DIR);
-const myKeyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath);
-```
-
-[ Class `UnencryptedFileSystemKeyStore`](https://near.github.io/near-api-js/classes/_near_js_keystores_node.unencrypted_file_system_keystore.UnencryptedFileSystemKeyStore.html)
-
-
-
-
-```js
-// creates keyStore from a provided file
-// you will need to pass the location of the .json key pair
-
-const { KeyPair, keyStores } = require("near-api-js");
-const fs = require("fs");
-const homedir = require("os").homedir();
-
-const ACCOUNT_ID = "near-example.testnet"; // NEAR account tied to the keyPair
-const NETWORK_ID = "testnet";
-// path to your custom keyPair location (ex. function access key for example account)
-const KEY_PATH = "/.near-credentials/near-example-testnet/get_token_price.json";
-
-const credentials = JSON.parse(fs.readFileSync(homedir + KEY_PATH));
-const myKeyStore = new keyStores.InMemoryKeyStore();
-myKeyStore.setKey(
- NETWORK_ID,
- ACCOUNT_ID,
- KeyPair.fromString(credentials.private_key)
-);
-```
-
-[ Class `InMemoryKeyStore`](https://near.github.io/near-api-js/classes/_near_js_keystores.in_memory_key_store.InMemoryKeyStore.html)
-
-[ Class `KeyPair`](https://near.github.io/near-api-js/classes/_near_js_crypto.key_pair.KeyPair.html)
-
-
-
-
-```js
-// creates keyStore from a private key string
-// you can define your key here or use an environment variable
-
-const { keyStores, KeyPair } = nearAPI;
-const myKeyStore = new keyStores.InMemoryKeyStore();
-const PRIVATE_KEY =
- "by8kdJoJHu7uUkKfoaLd2J2Dp1q1TigeWMG123pHdu9UREqPcshCM223kWadm";
-// creates a public / private key pair using the provided private key
-const keyPair = KeyPair.fromString(PRIVATE_KEY);
-// adds the keyPair you created to keyStore
-await myKeyStore.setKey("testnet", "example-account.testnet", keyPair);
-```
-
-[ Class `InMemoryKeyStore`](https://near.github.io/near-api-js/classes/_near_js_keystores.in_memory_key_store.InMemoryKeyStore.html)
-
-[ Class `KeyPair`](https://near.github.io/near-api-js/classes/_near_js_crypto.key_pair.KeyPair.html)
-
-
-
-
-## Connecting to NEAR {#connect}
-
-The object returned from `connect` is your entry-point for all commands in the API.
-To sign a transaction you'll need a [`KeyStore`](#key-store) to create a connection.
-
-
-
-
-```js
-const { connect } = nearAPI;
-
-const connectionConfig = {
- networkId: "testnet",
- keyStore: myKeyStore, // first create a key store
- nodeUrl: "https://rpc.testnet.near.org",
- walletUrl: "https://testnet.mynearwallet.com/",
- helperUrl: "https://helper.testnet.near.org",
- explorerUrl: "https://testnet.nearblocks.io",
-};
-const nearConnection = await connect(connectionConfig);
-```
-
-
-
-
-```js
-const { connect } = nearAPI;
-
-const connectionConfig = {
- networkId: "mainnet",
- keyStore: myKeyStore, // first create a key store
- nodeUrl: "https://rpc.mainnet.near.org",
- walletUrl: "https://wallet.mainnet.near.org",
- helperUrl: "https://helper.mainnet.near.org",
- explorerUrl: "https://nearblocks.io",
-};
-const nearConnection = await connect(connectionConfig);
-```
-
-
-
-
-
-```js
-const { connect } = nearAPI;
-const connectionConfig = {
- networkId: "local",
- nodeUrl: "http://localhost:3030",
- walletUrl: "http://localhost:4000/wallet",
-};
-const nearConnection = await connect(connectionConfig);
-```
-
-
-
-
-[ Module `connect`](https://near.github.io/near-api-js/modules/near_api_js.connect.html)
-
-## RPC Failover
-
-RPC providers can experience intermittent downtime, connectivity issues, or rate limits that cause client transactions to fail. This can be prevented by using the `FailoverRpcProvider` that supports multiple RPC providers.
-
-
-
-
-```js
-const jsonProviders = [
- new JsonRpcProvider({
- url: 'https://rpc.mainnet.near.org',
- }),
- new JsonRpcProvider(
- {
- url: 'https://another-rpc.cloud.com',
- headers: { 'X-Api-Key': 'some string' },
- },
- { retries: 3, backoff: 2, wait: 500 }
- ),
-];
-const provider = new FailoverRpcProvider(jsonProviders);
-
-await connect({
- networkId: 'mainnet',
- provider: provider,
- // this isn't used if `provider` is specified, but is still required for backward compatibility
- nodeUrl: 'https://rpc.mainnet.near.org',
-});
-```
-
-
-
-
-
-
-[ Class `FailoverRpcProvider `](https://near.github.io/near-api-js/classes/near_api_js.providers_failover_rpc_provider.FailoverRpcProvider.html)
diff --git a/docs/4.tools/near-api.md b/docs/4.tools/near-api.md
index f92fc004b1a..7509a0e029e 100644
--- a/docs/4.tools/near-api.md
+++ b/docs/4.tools/near-api.md
@@ -182,7 +182,7 @@ These examples are references to code snippets, feel free to explore the full co
Keystores can be created by using a private key string.
- Private keys have the format "ed25519::5Fg2...".
+ Private keys have the format "ed25519:5Fg2...".
diff --git a/website/sidebars.js b/website/sidebars.js
index 33a129869a8..251021a7e08 100644
--- a/website/sidebars.js
+++ b/website/sidebars.js
@@ -517,28 +517,6 @@ const sidebar = {
"value": " Developer Tools "
},
"tools/near-api",
- {
- "type": "category",
- "label": "JavaScript API",
- "items": [
- "tools/near-api-js/quick-reference",
- "tools/near-api-js/wallet",
- "tools/near-api-js/account",
- "tools/near-api-js/contract",
- "tools/near-api-js/utils",
- "tools/near-api-js/faq",
- {
- "type": "link",
- "label": "Handling Passphrases",
- "href": "https://github.com/near/near-seed-phrase"
- },
- {
- "type": "link",
- "label": "Type Docs",
- "href": "https://near.github.io/near-api-js"
- }
- ]
- },
"tools/sdk",
"tools/near-cli",
{
From cad680faa76cd50a22675d4eeb509ec1759a110f Mon Sep 17 00:00:00 2001
From: PiVortex
Date: Wed, 18 Dec 2024 11:01:10 +0000
Subject: [PATCH 10/13] fix links
---
docs/2.build/2.smart-contracts/release/upgrade.md | 4 ++--
docs/2.build/4.web3-apps/frontend.md | 4 ++--
docs/5.api/rpc/providers.md | 2 +-
3 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/docs/2.build/2.smart-contracts/release/upgrade.md b/docs/2.build/2.smart-contracts/release/upgrade.md
index 28b3db0c8b2..ece58a4914a 100644
--- a/docs/2.build/2.smart-contracts/release/upgrade.md
+++ b/docs/2.build/2.smart-contracts/release/upgrade.md
@@ -11,8 +11,8 @@ allowing the code to be changed.
Contract's can be updated in two ways:
-1. **Through tools** such as [NEAR CLI](../../../4.tools/cli.md) or
- [near-api-js](../../../4.tools/near-api-js/quick-reference.md) (if you hold
+1. **Through tools** such as [NEAR CLI](../../../4.tools/cli.md) or the
+ [NEAR API](../../../4.tools/near-api.md) (if you hold
the account's
[full access key](../../../1.concepts/protocol/access-keys.md)).
2. **Programmatically**, by implementing a method that
diff --git a/docs/2.build/4.web3-apps/frontend.md b/docs/2.build/4.web3-apps/frontend.md
index b4e27a0ea33..2fae10c11cc 100644
--- a/docs/2.build/4.web3-apps/frontend.md
+++ b/docs/2.build/4.web3-apps/frontend.md
@@ -29,12 +29,12 @@ While your user interface layer will remain centralized, the backend layerβinc
When building a frontend that can connect with the NEAR blockchain using standard web2 tooling will require you to import two dependencies:
-- [NEAR API JS](../../4.tools/near-api-js/quick-reference.md) - A JavaScript API tool that allows frontend clients the ability to view and retrieve data directly from the blockchain.
+- [NEAR API JS](../../4.tools/near-api.md) - A JavaScript API tool that allows frontend clients the ability to view and retrieve data directly from the blockchain.
- [Wallet Selector](../../4.tools/wallet-selector.md) - Wallet integration tool allowing developers to choose which wallets are supported and allows users to choose which wallet they would like to connect with.
:::tip
-[Checkout this article](integrate-contracts.md) to learn how to integrate smart contracts to your frontend, using [Wallet Selector](../../4.tools/wallet-selector.md) and [NEAR API JS](../../4.tools/near-api-js/quick-reference.md).
+[Checkout this article](integrate-contracts.md) to learn how to integrate smart contracts to your frontend, using [Wallet Selector](../../4.tools/wallet-selector.md) and [NEAR API JS](../../4.tools/near-api.md).
:::
diff --git a/docs/5.api/rpc/providers.md b/docs/5.api/rpc/providers.md
index 59f8b6e6ca2..4b00449033e 100644
--- a/docs/5.api/rpc/providers.md
+++ b/docs/5.api/rpc/providers.md
@@ -45,7 +45,7 @@ If you want to use a custom RPC provider with NEAR Wallet Selector, [check this
## RPC Failover
-In `near-api-js` you can use [`FailoverRpcProvider`](../../4.tools/near-api-js/quick-reference.md#rpc-failover) to automatically switch RPC providers when one provider is experiencing downtime, or implement an RPC selection widget that allows users to add their own RPC provider.
+In `near-api-js` you can use [`FailoverRpcProvider`](../../4.tools/near-api.md#rpc-failover) to automatically switch RPC providers when one provider is experiencing downtime, or implement an RPC selection widget that allows users to add their own RPC provider.
As a user, if a dApp or wallet doesn't support RPC failover and the primary provider is down, you can use an RPC Selector browser extension to redirect all requests to an RPC provider of your choice.
From d250042faec096d749156eee795287127da299b6 Mon Sep 17 00:00:00 2001
From: Guillermo Alejandro Gallardo Diez
Date: Thu, 2 Jan 2025 15:53:36 +0100
Subject: [PATCH 11/13] fix: minor fixes
---
docs/4.tools/near-api.md | 70 +++++++++++++++++++---------------------
1 file changed, 34 insertions(+), 36 deletions(-)
diff --git a/docs/4.tools/near-api.md b/docs/4.tools/near-api.md
index 7509a0e029e..0b05a2e6fa3 100644
--- a/docs/4.tools/near-api.md
+++ b/docs/4.tools/near-api.md
@@ -140,7 +140,9 @@ These examples are references to code snippets, feel free to explore the full co
-### Signers
+
+
+### Key Handlers: Stores & Signers
@@ -148,7 +150,7 @@ These examples are references to code snippets, feel free to explore the full co
To sign transactions you'll need to a `KeyStore` with valid keypairs.
-
+
`BrowserLocalStorageKeyStore` can only be used in the browser, it uses the browser's local storage to store the keys.
@@ -160,7 +162,7 @@ These examples are references to code snippets, feel free to explore the full co
```
-
+
`UnencryptedFileSystemKeyStore` can be used is used to load keys from the legacy credentials directory used by the NEAR CLI.
@@ -169,7 +171,7 @@ These examples are references to code snippets, feel free to explore the full co
start="11" end="13" />
-
+
Keystores can be created by loading a private key from a json file.
@@ -178,7 +180,7 @@ These examples are references to code snippets, feel free to explore the full co
start="10" end="16" />
-
+
Keystores can be created by using a private key string.
@@ -189,7 +191,7 @@ These examples are references to code snippets, feel free to explore the full co
start="10" end="12" />
-
+
Keystores can be created by using a seed phrase. To parse the seed phrase into a private key, the `near-seed-phrase` library is needed.
@@ -212,7 +214,7 @@ These examples are references to code snippets, feel free to explore the full co
To sign transactions you'll need to create a `Signer` that holds a valid keypair.
-
+
Signers can be created using the Keystore that is also used as the standard for saving keys with the NEAR CLI.
@@ -221,7 +223,7 @@ These examples are references to code snippets, feel free to explore the full co
start="12" end="18" />
-
+
Signers can be created using the credentials directory which is the legacy option for saving keys with the NEAR CLI.
@@ -230,7 +232,7 @@ These examples are references to code snippets, feel free to explore the full co
start="10" end="13" />
-
+
Signers can be created by loading a public and private key from a file.
@@ -239,7 +241,7 @@ These examples are references to code snippets, feel free to explore the full co
start="12" end="13" />
-
+
Signers can be created by using a private key string.
@@ -250,7 +252,7 @@ These examples are references to code snippets, feel free to explore the full co
start="13" end="14" />
-
+
Signers can be created by using a seed phrase.
@@ -374,12 +376,12 @@ Returns the authorized apps of an account. This is a list of contracts that the
### Create an Account {#create-account}
-
-
+In order to create .near or .testnet accounts, you need to make a function call to the top-level-domain account (i.e. `near` or `testnet`), calling `create_account`. In this example we generate a new public key for the account by generating a random private key.
- In order to create .near or .testnet accounts, you need to make a function call to the top-level-domain account (i.e. `near` or `testnet`), calling `create_account`. In this example we generate a new public key for the account by generating a random private key.
+The deposit determines the initial balance of the account.
- The deposit determines the initial balance of the account.
+
+
- In this example we create a .testnet account with a random keypair.
-
- The deposit determines the initial balance of the account.
-
@@ -425,12 +423,12 @@ Returns the authorized apps of an account. This is a list of contracts that the
### Create a Sub-Account {#create-sub-account}
-
-
+Accounts can create sub-accounts of themselves, which are useful for creating separate accounts for different purposes. It is important to remark that the parent account has no control over any of its sub-accounts.
- For creating a sub-account (sub.example-account.testnet) the API provides specific method.
+The deposit determines the initial balance of the account.
- The deposit determines the initial balance of the account.
+
+
- The process for creating a sub-account (sub.example-account.testnet) is the same as creating a .testnet account, but with an account id that is a sub-account of the parent account.
-
- The deposit determines the initial balance of the account.
-
@@ -454,7 +448,7 @@ Returns the authorized apps of an account. This is a list of contracts that the
### Delete Account {#delete-account}
-When deleting an account, you need to specify a beneficiary account id. This is the account that will receive the remaining NEAR balance of the account being deleted. Remember that no other assets will to transferred to the beneficiary, so you should transfer all your FTs, NFTs, etc. to another account before deleting.
+When deleting an account, you need to specify a beneficiary account id. This is the account that will receive the remaining NEAR balance of the account being deleted.
@@ -473,6 +467,18 @@ When deleting an account, you need to specify a beneficiary account id. This is
+:::warning
+
+Only NEAR tokens will be transferred to the beneficiary, so you should transfer all your FTs, NFTs, etc. to another account before deleting.
+
+:::
+
+:::danger
+
+If the beneficiary account does not exist, the NEAR tokens will be burned
+
+:::
+
---
## Transactions
@@ -508,8 +514,6 @@ A call function changes the contract's state and requires a signer/keypair.
- You need to specify the account id of the contract you want to call, the method you want to call, and optionally the arguments for the method, the amount of gas you want to allocate for the call, and the deposit you want to send with the call.
-
@@ -517,14 +521,10 @@ A call function changes the contract's state and requires a signer/keypair.
- To call a function on a contract, you need to create a `Contract` object.
-
- You need to specify the account id of the contract you want to call, the method you want to call, the deposit you want to send with the call, and optionally the arguments for the method, the amount of gas you want to allocate for the call.
-
@@ -612,8 +612,6 @@ View functions are read-only functions that don't change the state of the contra
- To call a view function a json provider is used instead of the connection object. You can copy the `viewContract` function into your own code.
-
From bc2e8fcb5421ab888a657ba5ecac9e847f00946e Mon Sep 17 00:00:00 2001
From: Reza Rahemtola <49811529+RezaRahemtola@users.noreply.github.com>
Date: Thu, 2 Jan 2025 15:54:42 +0100
Subject: [PATCH 12/13] New NEAR API section - Python examples (#2358)
* feat(near-api/python): Install, account and utilities examples
* feat(near-api/python): Missing examples added
---
docs/4.tools/near-api.md | 189 +++++++++++++++++++++++++++++++++++++++
1 file changed, 189 insertions(+)
diff --git a/docs/4.tools/near-api.md b/docs/4.tools/near-api.md
index 0b05a2e6fa3..823d60d4e44 100644
--- a/docs/4.tools/near-api.md
+++ b/docs/4.tools/near-api.md
@@ -50,6 +50,12 @@ These examples are references to code snippets, feel free to explore the full co
cargo add near-api
```
+
+
+ ```shell
+ pip install py-near
+ ```
+
@@ -85,6 +91,19 @@ These examples are references to code snippets, feel free to explore the full co
start="2" end="2" />
+
+
+ You can use the NEAR API by importing the `py_near` package, either entirely
+ ```python
+ import py_near
+ ```
+
+ or only the parts you need, for example:
+ ```python
+ from py_near.account import Account
+ from py_near.providers import JsonProvider
+ ```
+
@@ -266,6 +285,9 @@ These examples are references to code snippets, feel free to explore the full co
+
+ TODO: not exactly the same in Python, it's more and account + RPC URL, or a JSON RPC provider
+
@@ -283,6 +305,15 @@ These examples are references to code snippets, feel free to explore the full co
start="12" end="34" />
+
+ You can pass multiple RPC providers to `JsonRpcProvider`
+
+ ```python
+ from py_near.providers import JsonProvider
+
+ provider = JsonProvider(["https://test.rpc.fastnear.com", "https://rpc.testnet.pagoda.co"])
+ ```
+
---
@@ -308,6 +339,22 @@ This will return an Account object for you to interact with.
start="5" end="7" />
+
+ You can instantiate any account with the following code:
+
+ ```python
+ from py_near.account import Account
+
+ account = Account(account_id="example-account.testnet", rpc_addr="https://rpc.testnet.pagoda.co")
+ await account.startup()
+ ```
+
+ If you want to use it to submit transactions later, you need to also pass the `private_key` param:
+
+ ```python
+ account = Account(account_id="example-account.testnet", private_key="ed25519:...", rpc_addr="https://rpc.testnet.pagoda.co")
+ ```
+
@@ -331,6 +378,17 @@ Gets the available and staked balance of an account in yoctoNEAR.
start="13" end="18" />
+
+
+ ```python
+ from py_near.account import Account
+
+ account = Account(account_id="example-account.testnet", rpc_addr="https://rpc.testnet.pagoda.co")
+ await account.startup()
+
+ account_balance = account.get_balance()
+ ```
+
@@ -354,6 +412,17 @@ Get basic account information, such as its code hash and storage usage.
start="21" end="21" />
+
+
+ ```python
+ from py_near.account import Account
+
+ account = Account(account_id="example-account.testnet", rpc_addr="https://rpc.testnet.pagoda.co")
+ await account.startup()
+
+ account_state = account.fetch_state()
+ ```
+
@@ -442,6 +511,20 @@ The deposit determines the initial balance of the account.
start="65" end="82" />
+
+
+ Create a sub-account and fund it with your main account:
+
+ ```python
+ from py_near.account import Account
+ from py_near.dapps.core import NEAR
+
+ account = Account(account_id="example-account.testnet", private_key="ed25519:...", rpc_addr="https://rpc.testnet.pagoda.co")
+ await account.startup()
+
+ res = account.create_account(account_id="sub.example-account.testnet", public_key="...", initial_balance=1 * NEAR))
+ ```
+
@@ -502,6 +585,18 @@ Transfer NEAR tokens between accounts.
start="22" end="28" />
+
+
+ ```python
+ from py_near.account import Account
+ from py_near.dapps.core import NEAR
+
+ account = Account(account_id="example-account.testnet", private_key="ed25519:...", rpc_addr="https://rpc.testnet.pagoda.co")
+ await account.startup()
+
+ await account.send_money("receiver-account.testnet", 1 * NEAR))
+ ```
+
@@ -530,6 +625,12 @@ A call function changes the contract's state and requires a signer/keypair.
start="37" end="49" />
+
+
+ ```python
+ await account.function_call("usn.near", "ft_transfer", {"receiver_id": "bob.near", "amount": "1000000000000000000000000"})
+ ```
+
@@ -575,6 +676,24 @@ Transactions can be sent in parallel to the network, so you don't have to wait f
url="https://github.com/PiVortex/near-api-examples/tree/main/rust/examples/simultaneous_transactions.rs#L23-L55"
start="23" end="55" />
+
+
+
+ ```python
+ import asyncio
+ from py_near.account import Account
+
+ account = Account(account_id="example-account.testnet", private_key="ed25519:...", rpc_addr="https://rpc.testnet.pagoda.co")
+ await account.startup()
+
+ # Prepare the transactions
+ tx1 = account.function_call("guestbook.near-examples.testnet", "add_message", { "text": "Hello, world!" })
+ tx2 = account.function_call("counter.near-examples.testnet", "increment", {})
+
+ # Send the transactions simultaneously
+ const transactionsResults = await asyncio.gather(tx1, tx2)
+ ```
+
@@ -601,6 +720,20 @@ You can deploy a contract from a compiled WASM file.
start="54" end="61" />
+
+
+ ```python
+ import asyncio
+ from py_near.account import Account
+
+ account = Account(account_id="example-account.testnet", private_key="ed25519:...", rpc_addr="https://rpc.testnet.pagoda.co")
+ await account.startup()
+
+ with open("contract.wasm", "rb") as f:
+ contract_code = f.read()
+ await account.deploy_contract(contract_code)
+ ```
+
---
@@ -624,6 +757,18 @@ View functions are read-only functions that don't change the state of the contra
start="22" end="33" />
+
+
+ ```python
+ view_call_result = await account.view_function("guestbook.near-examples.testnet", "total_messages", {})
+ # If args are required, they can be passed in like this in the 3rd argument:
+ # {
+ # "from_index": "0",
+ # "limit": "10"
+ # }
+ print(view_call_result)
+ ```
+
---
@@ -649,6 +794,12 @@ List all the access keys for an account.
start="22" end="22" />
+
+
+ ```python
+ keys = await account.get_access_key_list()
+ ```
+
@@ -672,6 +823,12 @@ Add a new [full access key](../1.concepts/protocol/access-keys.md#full-access-ke
start="22" end="39" />
+
+
+ ```python
+ keys = await account.add_full_access_public_key("5X9WvUbRV3aSd9Py1LK7HAndqoktZtcgYdRjMt86SxMj")
+ ```
+
@@ -695,6 +852,18 @@ Add a new [function call key](../1.concepts/protocol/access-keys.md#function-cal
start="43" end="62" />
+
+
+ ```python
+ await account.add_public_key(
+ "5X9WvUbRV3aSd9Py1LK7HAndqoktZtcgYdRjMt86SxMj",
+ "example-contract.testnet", # Contract this key is allowed to call
+ ["example_method"], # Methods this key is allowed to call (optional)
+ 0.25 * NEAR # Gas allowance key can use to call methods (optional)
+ )
+ ```
+
+
@@ -718,6 +887,12 @@ When deleting an access key, you need to specify the public key of the key you w
start="67" end="72" />
+
+
+ ```python
+ await account.delete_public_key("5X9WvUbRV3aSd9Py1LK7HAndqoktZtcgYdRjMt86SxMj")
+ ```
+
---
@@ -743,6 +918,15 @@ Convert an amount in NEAR to an amount in yoctoNEAR.
start="7" end="7" />
+
+
+ ```python
+ from py_near.dapps.core import NEAR
+
+ amount_in_yocto = 1 * NEAR
+ ```
+
+
@@ -789,5 +973,10 @@ Convert an amount in NEAR to an amount in yoctoNEAR.
- [Github](https://github.com/near/near-api-rs)
- [Full Examples](https://github.com/PiVortex/near-api-examples/tree/main/rust)
+
+
+
+ - [Phone number transfer](https://py-near.readthedocs.io/en/latest/clients/phone.html)
+
From 4b72a5ea4f89bc0f76033871b52de09491210d58 Mon Sep 17 00:00:00 2001
From: Guillermo Alejandro Gallardo Diez
Date: Thu, 2 Jan 2025 16:01:29 +0100
Subject: [PATCH 13/13] fix: added snippet for python
---
docs/4.tools/near-api.md | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/docs/4.tools/near-api.md b/docs/4.tools/near-api.md
index 823d60d4e44..ecac66fd6fc 100644
--- a/docs/4.tools/near-api.md
+++ b/docs/4.tools/near-api.md
@@ -486,6 +486,14 @@ The deposit determines the initial balance of the account.
+
+
+ ```python
+ await account.function_call("testnet", "create_account", {"new_account_id": "example-account.testnet", "new_public_key": "ed25519:..."}, "30000000000000", 1 * NEAR)
+ ```
+
+
+