From c558d592f53adbaf23f39cf386169ae7c2473bfa Mon Sep 17 00:00:00 2001 From: Guillermo Alejandro Gallardo Diez Date: Thu, 22 Jan 2026 17:12:12 +0100 Subject: [PATCH 1/5] fix: all naj links --- docs/tools/near-api.md | 1375 ++++++---------------------------------- 1 file changed, 177 insertions(+), 1198 deletions(-) diff --git a/docs/tools/near-api.md b/docs/tools/near-api.md index 5041b4ffe6e..dd56057b17e 100644 --- a/docs/tools/near-api.md +++ b/docs/tools/near-api.md @@ -9,68 +9,35 @@ import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import {Github, Language} from "@site/src/components/UI/Codetabs" -The NEAR API is a collection of language-specific SDKs that allow developers to interact with the NEAR blockchain from both frontend and backend applications. - -These libraries enable you to: - -- Invoke view and call functions on deployed smart contracts -- Query on-chain data such as account state, keys, balance -- Create and manage NEAR accounts -- Transfer tokens, including native NEAR, Fungible Tokens, Non-Fungible Tokens -- Sign transactions/meta-transactions/messages and broadcasting them to the network -- Deploy smart contracts - -Our API is available in multiple languages, including: -- JavaScript/TypeScript: - - [`@near-js/accounts`](https://github.com/near/near-api-js/tree/master/packages/accounts) - A collection of classes, functions, and types for interacting with accounts and contracts. - - [`@near-js/signers`](https://github.com/near/near-api-js/tree/master/packages/signers) - A collection of classes and types to facilitate cryptographic signing. - - [`@near-js/transactions`](https://github.com/near/near-api-js/tree/master/packages/transactions) - A collection of classes, functions, and types for composing, serializing, and signing NEAR transactions. - - [`@near-js/tokens`](https://github.com/near/near-api-js/tree/master/packages/tokens) - A collection of standard tokens. - - [`@near-js/providers`](https://github.com/near/near-api-js/tree/master/packages/providers) - A collection of classes, functions, and types for communicating with the NEAR RPC. - - [`@near-js/utils`](https://github.com/near/near-api-js/tree/master/packages/utils) - A collection of commonly-used functions and constants. - - [`@near-js/crypto`](https://github.com/near/near-api-js/tree/master/packages/crypto) - A collection of classes and types for working with cryptographic key pairs. - - [`@near-js/types`](https://github.com/near/near-api-js/tree/master/packages/types) - A collection of commonly-used classes and types.. - - [`@near-js/keystores`](https://github.com/near/near-api-js/tree/master/packages/keystores), [`@near-js/keystores-node`](https://github.com/near/near-api-js/tree/master/packages/keystores-node) and [`@near-js/keystores-browser`](https://github.com/near/near-api-js/tree/master/packages/keystores-browser) - A collection of classes for storing and managing NEAR-compatible cryptographic keys. - :::info - The legacy [`near-api-js`](https://github.com/near/near-api-js/tree/master/packages/near-api-js) package has been replaced with a set of modular packages under the `@near-js/*` namespace. These new libraries offer improved developer experience, better performance, and more flexibility by allowing you to import only the functionality you need. - ::: -- Rust: [`near-api-rs`](https://github.com/near/near-api-rs) -- Python: [`py-near`](https://github.com/pvolnov/py-near) +We offer a collection of language-specific libraries that allow developers to interact with the NEAR blockchain from both frontend and backend applications. The different APIs allow you to perform a variety of actions on the NEAR blockchain, including but not limited to: -:::tip Wallet Integration -To allow users to login into your web application using a wallet you will need a wallet connector. Read more in our [NEAR Connect](../web3-apps/tutorials/wallet-login) article -::: +1. Create and manage NEAR accounts +2. Call functions on smart contracts +3. Transfer tokens, including native NEAR, Fungible Tokens, Non-Fungible Tokens +4. Sign transactions/meta-transactions/messages and broadcasting them to the network +5. Deploy smart contracts --- -## Install +## Available APIs + +We have APIs available for Javascript, Rust, and Python. Add them to your project using the following commands: - - Include the following core libraries as most applications will need them: + ```bash - npm i @near-js/accounts@2 @near-js/providers@2 @near-js/signers@2 - ``` - - :::tip Static HTML - If you are building a site without using `npm`, you can include libraries directly in your HTML file through a CDN. - - ```html - - - + npm i near-api-js ``` - ::: - + ```bash cargo add near-api ``` - + ```shell pip install py-near @@ -78,424 +45,32 @@ To allow users to login into your web application using a wallet you will need a -
- -### Import {#import} - - - - 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 `near_api` module. - - - - - - - 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 - ``` - -
- -
- -### Connecting to NEAR {#connect} - - - - - 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. - - - - - - -
- -### Key Handlers: Stores & Signers - - - - - In previous versions of the NEAR SDK, signing transactions required setting up a `KeyStore` to manage and retrieve keys. With the new `@near-js/signers` package, this process has been simplified. - - You can now use the `Signer` abstraction, which provides a clean and extensible interface for signing. For most use cases, the `KeyPairSigner` implementation is the simplest option β€” it allows you to sign transactions directly using a single in-memory key pair, without needing a persistent keystore. - - - - - In browser, you typically don’t need to manage private keys manually. Instead, use [NEAR Connect](../web3-apps/tutorials/wallet-login.md) to handle the user authentication and signing process securely - -
- Manually managing keys in the browser (not recommended) - - If your use case requires direct control over keys in the browser (e.g. building a custom signing flow), you can use the `KeyPairSigner` together with in-browser storage. - - ```js - // Creates Signer using private key from local storage - import { KeyPairSigner } from "@near-js/signers"; - import { BrowserLocalStorageKeyStore } from "@near-js/keystores-browser"; - - const keyStore = new BrowserLocalStorageKeyStore(); - const key = await keyStore.getKey('testnet', 'user.testnet'); - const signer = new KeyPairSigner(key); - ``` - -
- -
- - - For Node.js environments (CLI tools, backend services, etc) you can load signing keys from files using the `UnencryptedFileSystemKeyStore` that reads unencrypted `.json` key files stored in a directory on your local machine. - - ```js - import { UnencryptedFileSystemKeyStore } from "@near-js/keystores-node"; - import { homedir } from "os"; - import path from "path"; - - // Create Signer using private key from a folder on the local machine - const credentialsDirectory = ".near-credentials"; - const credentialsPath = path.join(homedir(), credentialsDirectory); - const keyStore = new UnencryptedFileSystemKeyStore(credentialsPath); - const key = await keyStore.getKey('testnet', 'user.testnet'); - const signer = new KeyPairSigner(key); - ``` - - - See full example on GitHub - - - - - - If you have a raw JSON file that includes a NEAR account’s private key β€” it can directly parsed to then construct a KeyPairSigner. - - ```js - import { KeyPairSigner } from "@near-js/signers"; - import fs from "fs"; - - // Create Signer using private key from a JSON file on the local machine - const credentialsPath = "../credentials-file.json"; // Path relative to the working directory - const credentials = JSON.parse(fs.readFileSync(credentialsPath)); - const signer = KeyPairSigner.fromSecretKey(credentials.private_key); - ``` - - - See full example on GitHub - - - - - - It's common to load the NEAR private key from an environment variable or secret manager. With the new version of `KeyPairSigner`, you can create ir directly from a raw private key string. - - The private key must be in the format `"ed25519:xxxxx..."` - - ```js - import { KeyPairSigner } from "@near-js/signers"; - - // Create Signer using private key from a raw private key string - const privateKey = "ed25519:1111222222....."; // put real key here - const signer = KeyPairSigner.fromSecretKey(privateKey); - ``` - - - See full example on GitHub - - - - - - If you're working wallet recovery flows, developer tooling, or onboarding flows where users input their phrasesm you can derive the corresponding secret key and use it for signing. - - To parse and derive a NEAR-compatible key pair from a seed phrase, you’ll need to install the near-seed-phrase package: - ```bash - npm i near-seed-phrase - ``` - - Seed phrases are typically 12 words long, and are in the format "show three gate bird ..." - - ```js - import { KeyPairSigner } from "@near-js/signers"; - import { parseSeedPhrase } from "near-seed-phrase"; - - // Create Signer using seed phrase - const seedPhrase = "show three gate bird ..."; // 12 words long - const { secretKey } = parseSeedPhrase(seedPhrase); - const signer = KeyPairSigner.fromSecretKey(secretKey); - ``` - - - See full example on GitHub - - - -
-
- - - - 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. - - - - - - - Signers can be created using the credentials directory which is the legacy option for saving keys with the NEAR CLI. - - - - - - - Signers can be created by loading a public and private key from a file. - - - - - - - Signers can be created by using a private key string. - - Private keys have the format `ed25519:5Fg2...`. - - - - - - - Signers can be created by using a seed phrase. - - Seed phrases have the format `shoe three gate ...` and are usually 12 words long. - - - - - - - - - TODO: not exactly the same in Python, it's more and account + RPC URL, or a JSON RPC provider - -
- - -
- - ### RPC Failover - - RPC endpoints can occasionally become unreliable due to network issues, server downtime, or rate limiting - leading to failed requests or dropped transactions. To make your application more resilient, you can define multiple RPC endpoints and automatically fall back to the next available one when an issue occurs. - - - - - You can pass multiple individual `Provider` instances into the `FailoverRpcProvider` to improve the reliability of your application's connection. - - It’s also important to note that each `Provider` can internally use different transport protocols (such as HTTPS or WebSocket), making the failover strategy flexible across various infrastructure setups. - - ```js - import { JsonRpcProvider, FailoverRpcProvider } from "@near-js/providers"; - - const jsonProviders = [ - new JsonRpcProvider({ url: "https://incorrect-rpc-url.com" }), // Incorrect RPC URL - new JsonRpcProvider( - { url: "https://test.rpc.fastnear.com" }, // Valid RPC URL - { - retries: 3, // Number of retries before giving up on a request - backoff: 2, // Backoff factor for the retry delay - wait: 500, // Wait time between retries in milliseconds - } // Retry options - ), - ]; - - const provider = new FailoverRpcProvider(jsonProviders); - ``` - - - See full example on GitHub - - - - - You can pass multiple RPC providers to `JsonRpcProvider` +:::tip Wallet Integration - ```python - from py_near.providers import JsonProvider +If you are building a web app and need to add Wallet Login on it you will instead need a [`Wallet Connector`](../web3-apps/tutorials/wallet-login) - provider = JsonProvider(["https://test.rpc.fastnear.com", "https://rpc.testnet.pagoda.co"]) - ``` - - +::: --- ## Account -### Instantiate Account {#instantiate-account} - -This will return an Account object for you to interact with. - - - - - You can create an `Account` instance using the code below. At a minimum, it requires a `Provider` to fetch data from the blockchain. If you also want to perform actions on behalf of the account (such as sending tokens, signing transactions, or managing keys) - you’ll need to pass a `Signer` as well. See the [section above](#key-handlers-stores--signers) on how to create one using a private key, seed phrase, or JSON file. - - - - - - - - - - - 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") - ``` - - - -
- ### Get Balance {#get-balance} Gets the available and staked balance of an account in yoctoNEAR. - - - Once you've [created an `Account` instance](#instantiate-account), you can use it to query the balance of a token in its smallest unit β€” whether it's the native NEAR token or any other fungible token (FT). Let's start by checking the balance of NEAR. - - :::info Pro Tip - If you need to display the balance in a human-readable format, each `Token` instance provides a `toDecimal` method that you can use to convert raw values to their standard decimal representation. - ::: - - ```js - import { NEAR } from "@near-js/tokens"; - - const account = new Account("user.testnet", provider); - - // returns yoctoNear amount as bigint - const amount = await account.getBalance(NEAR); - // converts to human-readable string like "1.234" - NEAR.toDecimal(amount); - ``` - - For commonly used tokens like USDT or USDC, you can access pre-configured token definitions from the either `@near-js/tokens/testnet`, or `@near-js/tokens/mainnet` package, depending on the network. These built-in tokens make it easy to fetch balances without additional setup. - - ```js - import { USDT } from "@near-js/tokens/testnet"; - // import { USDT } from "@near-js/tokens/mainnet"; - - const account = new Account("user.testnet", provider); - - // returns units as bigint - const amount = await account.getBalance(USDT); - // converts to human-readable string like "1.234" - USDT.toDecimal(amount); - ``` - - If your token isn’t included in the provided collections, no problemβ€”you can manually create a `Token` instance for any fungible token contract by following the example below. - - ```js - import { FungibleToken } from "@near-js/tokens"; - - const account = new Account("user.testnet", provider); - - const REF = new FungibleToken("ref.fakes.testnet", { - decimals: 18, - symbol: "REF", - }); - - // returns units as bigint - const amount = await account.getBalance(REF); - // converts to human-readable string like "1.234" - REF.toDecimal(amount); - ``` - - - See full example on GitHub - - + + - + + url="https://github.com/near-examples/near-api-examples/tree/main/rust/examples/account_details.rs" /> - + ```python from py_near.account import Account @@ -515,35 +90,20 @@ Gets the available and staked balance of an account in yoctoNEAR. Get basic account information, such as its code hash and storage usage. - - - Once you've [created an `Account` instance](#instantiate-account), you can use it to query basic on-chain information about the account, such as its code hash and current storage usage. - - ```js - const account = new Account("user.testnet", provider); - - await account.getState(); - ``` + - While the `Account` class represents a wallet on-chain, some use cases, like simply reading account state or contract data β€” do not require full account access. In those cases, you can skip creating an `Account` and use the `Provider` directly, as shown below. - - ```js - await provider.viewAccount("user.testnet"); - ``` - - - See full example on GitHub - + - + - + ```python from py_near.account import Account @@ -560,62 +120,14 @@ Get basic account information, such as its code hash and storage usage. ### Create Named Account {#create-named-account} -To create a named account like `user.testnet`, you need to call the `create_account` function on a [top-level account’s contract](https://github.com/near/near-linkdrop) β€” that’s `testnet` on testnet or `near` on mainnet. Yes, on NEAR, every account can have a contract deployed to it, even top-level ones. - -Keep in mind that creating a named account requires a small amount of NEAR to cover Gas fees. - -When creating a new account, you’ll need to provide: -- A public key, which will be added to the account as [FullAccess key](/protocol/access-keys#full-access-keys) -- An optional initial balance in NEAR (this can be zero if you don’t want to fund it right away) +To create a named account like `user.testnet`, you need to call the `create_account` function on `near` (or `testnet`), passing as parameters the new account ID, and a public key to add as [FullAccess key](/protocol/access-keys#full-access-keys) - - - Once you've [created an `Account` instance](#instantiate-account), you can create any available named account (as long as it's not already taken). To do this, the creator account must include a `Signer`, since signing a transaction is required. If you're not sure how to set that up, check [the section above](#key-handlers-stores--signers) on how to connect a signer. - - ```js - const account = new Account("user.testnet", provider, signer); - - // generate a keypair randomly - const keyPair = KeyPair.fromRandom("ed25519"); - await account.createAccount( - "another_user.testnet", - keyPair.getPublicKey(), - // attaches 1.234 NEAR tokens that will become - // an initial balance of "another_user.testnet" - NEAR.toUnits("1.234") - ); - ``` - - - See full example on GitHub - - - In some cases, you might need to create an account using a seed phrase. Here’s how you can do that: - - ```js - import { generateSeedPhrase } from "near-seed-phrase"; - - const account = new Account("user.testnet", provider, signer); - - // get public key from a randomly generated seed phrase - const { seedPhrase, publicKey, secretKey } = generateSeedPhrase(); - - await account.createAccount( - "another_user.testnet", - publicKey, - // attaches 1.234 NEAR tokens that will become - // an initial balance of "another_user.testnet" - NEAR.toUnits("1.234") - ); - ``` - - - See full example on GitHub - + + - + - + ```python await account.function_call("testnet", "create_account", {"new_account_id": "example-account.testnet", "new_public_key": "ed25519:..."}, "30000000000000", 1 * NEAR) @@ -649,46 +161,22 @@ When creating a new account, you’ll need to provide: Accounts on NEAR can create sub-accounts under their own namespace, which is useful for organizing accounts by purpose β€” for example, `project.user.testnet`. -:::warning -The parent account **DOES NOT** have any control over its sub-accounts once they are created. -::: - -Keep in mind that creating a sub-account requires a small amount of NEAR to cover Gas fees. - -To create a sub-account, the parent must send a transaction to itself with the [`CreateAccount` action](/protocol/transaction-anatomy#actions). Just like when creating named accounts, you'll need to provide a public key that will be assigned to the new sub-account, along with an optional initial deposit to fund it (can be zero). - - - - Once you've [created an `Account` instance](#instantiate-account), you can create any sub-account (as long as it hasn't been created previously). To do this, the creator account must include a `Signer`, since signing a transaction is required. If you're not sure how to set that up, check [the section above](#key-handlers-stores--signers) on how to connect a signer. - - ```js - const account = new Account("user.testnet", provider, signer); - - // generate a keypair randomly - const keyPair = KeyPair.fromRandom("ed25519"); - await account.createAccount( - "project.user.testnet", - keyPair.getPublicKey(), - // attaches 1.234 NEAR tokens that will become - // an initial balance of "project.user.testnet" - NEAR.toUnits("1.234") - ); - ``` + + + - - See full example on GitHub - - + - + Create a sub-account and fund it with your main account: @@ -704,148 +192,66 @@ To create a sub-account, the parent must send a transaction to itself with the [ -
- -### Delete Account {#delete-account} - -An account on NEAR can only delete itself β€” it **CANNOT** delete other accounts or its sub-accounts. - -To delete an account, it must send a transaction to itself with the [`DeleteAccount` action](/protocol/transaction-anatomy#actions), including a required parameter called `beneficiary_id`. This is the account that will receive any remaining NEAR tokens. - :::info -Deleting an account **DOES NOT** affect its sub-accounts - they will remain active. -::: - - - - - ```js - const account = new Account("user.testnet", provider, signer); - - // account "user.testnet" gets deleted - // and remaining funds will go to account "beneficiary.testnet" (if it exists) - await account.deleteAccount("beneficiary.testnet"); - ``` - - - See full example on GitHub - - - - - - - - +Parent accounts have **no control** over their sub-accounts, they are completely independent. -:::danger Keep in mind -- Only NEAR tokens are transferred to the beneficiary. -- Fungible (FTs) or Non-Fungible tokens (NFTs) held by the account **ARE NOT** automatically transferred. These tokens are still associated with the account, even after the account is deleted. Make sure to transfer those assets manually before deletion, or you're risking losing them permanently! Once the account is gone, those assets are effectively stuck unless the same account is recreated by anyone (not necessarily you). -- If the beneficiary account doesn't exist, all NEAR tokens sent to it will be burned. Double-check the account ID before proceeding. ::: ---- - -## Transactions +
-### Send Tokens {#send-tokens} +### Delete Account {#delete-account} -Accounts can transfer different types of tokens to other accounts, including the native NEAR token and [NEP-141](https://github.com/near/NEPs/tree/master/neps/nep-0141.md) fungible tokens. +Accounts on NEAR can delete themselves, transferring any remaining balance to a specified beneficiary account. - - - To begin with, you’ll need the `@near-js/tokens` package, which provides the necessary utilities. - - Once you've [created an `Account` instance](#instantiate-account), you can transfer tokens to others. Let’s start by looking at how to transfer native `NEAR` tokens. - - ```js - import { NEAR } from "@near-js/tokens"; - - const account = new Account("user.testnet", provider, signer); - - // transfer 0.1 NEAR tokens to receiver.testnet - await account.transfer({ - token: NEAR, - amount: NEAR.toUnits("0.1"), - receiverId: "receiver.testnet" - }); - ``` - - You can also use the same package to send fungible tokens (NEP-141) like USDT β€” many of the most common tokens are included out of the box and can be imported from `@near-js/tokens/testnet` or `@near-js/tokens/mainnet`, depending on the network you're using. - - :::warning - Before receiving fungible tokens (NEP-141), the recipient must be registered on the token’s contract. If they aren’t, the transfer will fail. - - If your use case involves sending tokens to users, you have two options: - - - Cover the storage cost and register them yourself - - Ask the user to register in advance - - Good news - *if the account is already registered, any repeated registration attempt will automatically refund the storage deposit β€” so you’ll never pay it twice*. - ::: - - ```js - import { USDT } from "@near-js/tokens/testnet"; - - const account = new Account("user.testnet", provider, signer); + - // double-check that a recipient is registered - await USDT.registerAccount({ - accountIdToRegister: "receiver.testnet", - fundingAccount: account, - }) + + + - // transfer 1.23 USDT to receiver.testnet - await account.transfer({ - token: USDT, - amount: USDT.toUnits("1.23"), - receiverId: "receiver.testnet" - }); - ``` + - For more advanced use cases, such as working with custom or less common tokens, you can create your own instance of the `FungibleToken` class by passing the appropriate parameters. The example below demonstrates this using the `REF` token. + + - ```js - import { FungibleToken } from "@near-js/tokens/testnet"; +:::info +Deleting an account **DOES NOT** affect its sub-accounts - they will remain active. +::: - const account = new Account("user.testnet", provider, signer); +:::danger Keep in mind +- Only NEAR tokens are transferred to the beneficiary. +- Fungible (FTs) or Non-Fungible tokens (NFTs) held by the account **ARE NOT** automatically transferred. These tokens are still associated with the account, even after the account is deleted. Make sure to transfer those assets manually before deletion, or you're risking losing them permanently! Once the account is gone, those assets are effectively stuck unless the same account is recreated by anyone (not necessarily you). +- If the beneficiary account doesn't exist, all NEAR tokens sent to it will be burned. Double-check the account ID before proceeding. +::: - const REF = new FungibleToken("ref.fakes.testnet", { - decimals: 18, - symbol: "REF", - }); +--- - // double-check that a recipient is registered - await REF.registerAccount({ - accountIdToRegister: "receiver.testnet", - fundingAccount: account, - }) +## Transactions - // transfer 2.34 REF to receiver.testnet - await account.transfer({ - token: REF, - amount: REF.toUnits("2.34"), - receiverId: "receiver.testnet" - }); - ``` +### Send Tokens {#send-tokens} - - See full example on GitHub - +Accounts can transfer different types of tokens to other accounts, including the native NEAR token and [NEP-141](https://github.com/near/NEPs/tree/master/neps/nep-0141.md) fungible tokens. + + + - + - + ```python from py_near.account import Account @@ -866,83 +272,20 @@ Accounts can transfer different types of tokens to other accounts, including the A smart contract exposes its methods, and making a function call that modifies state requires a `Signer`/`KeyPair`. You can optionally attach a `NEAR` deposit to the call. - - - Once you've [created an `Account` instance](#instantiate-account), you can start interacting with smart contracts. - - The most convenient way to interact with contracts is the `TypedContract` class. It provides full type safety for method names, arguments, and return values, especially when used together with an ABI. - - For example, lets say there is a [Guestbook](https://github.com/near-examples/guest-book-examples) contract deployed at `guestbook.near-examples.testnet`, and you want to add a message to it. To do that, you’d call its `add_message` method. - - ```js - import { NEAR } from "@near-js/tokens"; - import { TypedContract, AbiRoot } from "@near-js/accounts"; - - // "as const satisfies AbiRoot" is necessary for TypeScript to infer ABI types - const guestbookAbi = {...} as const satisfies AbiRoot; - - const account = new Account("user.testnet", provider, signer); - const contract = new TypedContract({ - contractId: "guestbook.near-examples.testnet", - provider, - abi: guestbookAbi, - }); - - await contract.call.add_message({ - account: account, // Account must have Signer to sign tx - args: { - text: "Hello, world!" - }, - deposit: NEAR.toUnits("0.0001"), // optional - gas: BigInt("30000000000000") // 30 TGas, optional - }); - ``` - - - See full example on GitHub - - - In this function call, we’ve attached a small deposit of 0.001 NEAR to [cover the storage cost](/protocol/storage/storage-staking) of adding the message. - - We’ve also [attached 30 TGas](/protocol/gas) to limit the amount of computational resources the method can consume. - -
- What if I don't have ABI? - - If no ABI was provided, `TypedContract` would still work, though return types by default would be `unknown`, which you could override with generics as in the example below: - - ```js - type Message = { sender: string; text: string; premium: boolean }; - const messages = await contract.view.get_messages(); - // ^? { sender: string; text: string; premium: boolean }[] - ``` - -
- - ---------------------- - - You can also call contract methods directly using the `Account` class. This approach is supported, but not recommended anymore, because it doesn’t provide compile-time safety for method names or arguments. The main benefit of this style is that it is quick to set up. - - ```js - import { NEAR } from "@near-js/tokens"; - - const account = new Account("user.testnet", provider, signer); - - await account.callFunction({ - contractId: "guestbook.near-examples.testnet", - methodName: "add_message", - args: { text: "Hello, world!" }, - deposit: NEAR.toUnits('0.001'), // 0.001 NEAR - gas: "30000000000000" // 30 TGas - }); - ``` - - - See full example on GitHub - + + + + + + + + + - + - + ```python await account.function_call("usn.near", "ft_transfer", {"receiver_id": "bob.near", "amount": "1000000000000000000000000"}) @@ -968,46 +311,11 @@ A smart contract exposes its methods, and making a function call that modifies s You can send multiple [actions](../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. - - - Once you've [created an `Account` instance](#instantiate-account), you can start sending transactions. - - Let’s take a look at an example of a batched transaction that performs multiple actions in a single call - it increments a counter on a smart contract `counter.near-examples.testnet` twice, then transfers 0.1 NEAR tokens to this address. - - Each function call to increment the counter has [10 TGas attached](/protocol/gas), which is enough for a lightweight state update. - No deposit is included with these calls, since they don’t store new data β€” just update existing values. - - ```js - import { NEAR } from "@near-js/tokens"; - - const account = new Account("user.testnet", provider, signer); - - await account.signAndSendTransaction({ - receiverId: "counter.near-examples.testnet", - actions: [ - actionCreators.functionCall( - "increment", - {}, - "10000000000000", // 10 TGas - 0 // 0 NEAR - ), - actionCreators.functionCall( - "increment", - {}, - "10000000000000", // 10 TGas - 0 // 0 NEAR - ), - actionCreators.transfer(NEAR.toUnits("0.1")) - ], - }); - ``` - - - See full example on GitHub - - + + - + - - - Once you've [created an `Account` instance](#instantiate-account), you can start by generating [two new key pairs](/protocol/access-keys) and adding them to the account. In our example, we’re using Full Access keys, but that’s not a requirement β€” Function Call access keys can work just as well, depending on your use case. - - If you already have the keys prepared, feel free to skip this step. We're including it here to show the full setup for learning purposes. - - :::note - Notice that we’re adding both keys in a batched transaction. Learn more about it [here](#batch-actions). - ::: - - ```js - const account = new Account("user.testnet", provider, signer); - - const keyPairOne = KeyPair.fromRandom("ed25519"); - const keyPairTwo = KeyPair.fromRandom("ed25519"); - - // add two keys in a single transaction - await account.signAndSendTransaction({ - receiverId: account.accountId, - actions: [ - actionCreators.addKey( - keyPairOne.getPublicKey(), - actionCreators.fullAccessKey() - ), - actionCreators.addKey( - keyPairTwo.getPublicKey(), - actionCreators.fullAccessKey() - ), - ], - waitUntil: "FINAL", - }); - ``` - - Now that we’ve created two separate keys, we need to create corresponding `Account` instances for each one. These will be used to build and send different transactions independently. - - One of the transactions adds a message to the [Guestbook](https://github.com/near-examples/guest-book-examples) contract, while the other increments a counter on a different contract. - - ```js - const accountOne = new Account( - accountId, - provider, - new KeyPairSigner(keyPairOne) - ); - const accountTwo = new Account( - accountId, - provider, - new KeyPairSigner(keyPairTwo) - ); - - const signedTxOne = await accountOne.createSignedTransaction( - "guestbook.near-examples.testnet", - [ - actionCreators.functionCall( - "add_message", - { text: "Hello, world!" }, - "30000000000000", // 30 TGas - NEAR.toUnits("0.001") // 0.001 NEAR - ), - ] - ); - const signedTxTwo = await accountTwo.createSignedTransaction( - "counter.near-examples.testnet", - [ - actionCreators.functionCall( - "increment", - {}, - "10000000000000", // 10 TGas - 0 // 0 NEAR - ), - ] - ); - ``` - - The last step is to broadcast both transactions concurrently to the network using the `Provider`. - - ```js - const sendTxOne = provider.sendTransaction(signedTxOne); - const sendTxTwo = provider.sendTransaction(signedTxTwo); - - const transactionsResults = await Promise.all([sendTxOne, sendTxTwo]); - ``` - - - See full example on GitHub - - + + - + - + ```python import asyncio @@ -1145,38 +362,22 @@ If your use case requires strict ordering or depends on all actions succeeding t +:::warning Keep in mind +Simultaneous execution means there’s no guarantee of order or success. Any transaction may fail independently. If your use case requires strict ordering, then you should stick to sending transactions sequentially from a single key. +::: +
### Deploy a Contract {#deploy-a-contract} On NEAR, a smart contract is deployed as a WASM file. Every account has the potential to become a contract β€” you simply need to deploy code to it. -:::note -Unlike many other blockchains, contracts on NEAR are mutable, meaning you have the ability to redeploy updated versions to the same account. However, if you remove all access keys from the account, it becomes impossible to sign new deploy transactions, effectively locking the contract code permanently. -::: - - - - Once you've [created an `Account` instance](#instantiate-account), you can deploy a smart contract to it. - - Let's read a `.wasm` file from your local machine and deploy its content directly to the account. - - ```js - import { readFileSync } from "fs"; - - const account = new Account("user.testnet", provider, signer); - - const wasm = readFileSync("../contracts/contract.wasm"); - await account.deployContract(wasm); - ``` - - - See full example on GitHub - - + + - + Note that the `signer` here needs to be a signer for the same `account_id` as the one used to construct the `Contract` object. @@ -1185,7 +386,7 @@ Unlike many other blockchains, contracts on NEAR are mutable, meaning you have t start="54" end="61" /> - + ```python import asyncio @@ -1212,55 +413,24 @@ There are two ways to reference a global contract: - **[By hash](../smart-contracts/global-contracts.md#reference-by-hash):** You reference the contract by its immutable code hash. - - - Once you've created an Account instance, you can deploy your regular contract as a global contract. + - - - - Let’s look at an example of deploying a global contract by account. - - To do this, use the `deployGlobalContract` function and set the mode to `accountId`, along with the contract’s code bytes. - - ```js - import { readFileSync } from "fs"; - - const account = new Account("user.testnet", provider, signer); - - const wasm = readFileSync("../contracts/contract.wasm"); - await account.deployGlobalContract(wasm, "accountId"); - ``` - - - See full example on GitHub - + + + - - - - Let’s look at an example of deploying a global contract by hash. - - To do this, use the `deployGlobalContract` function and set the mode to `codeHash`, along with the contract’s code bytes. - - ```js - import { readFileSync } from "fs"; - - const account = new Account("user.testnet", provider, signer); - - const wasm = readFileSync("../contracts/contract.wasm"); - await account.deployGlobalContract(wasm, "codeHash"); - ``` - - - See full example on GitHub - + + - + Once you've created an Account instance, you can deploy your regular contract as a global contract. @@ -1321,45 +491,22 @@ There are two ways to reference a global contract: Once a [global contract](../smart-contracts/global-contracts.md) has been [deployed](#deploy-a-global-contract), let’s see how you can reference and use it from another account. - - - - - - To reference a global contract by account, you need to call the `useGlobalContract` function and pass the source `accountId` where the contract was originally deployed. - - ```js - const account = new Account("another_user.testnet", provider, signer); - - await account.useGlobalContract({ accountId: "user.testnet" }); - ``` - - - See full example on GitHub - - - - - - To reference a global contract by hash, you need to call the `useGlobalContract` function and pass the source `codeHash` of the original contract. - - ```js - const account = new Account("another_user.testnet", provider, signer); - - await account.useGlobalContract({ - codeHash: "36b15ea09f737220583f63ad120d91b7e233d2039bebea43be527f8fd85450c9", - }); - ``` - - - See full example on GitHub - - - - + + + + + + + + + - + @@ -1415,38 +562,22 @@ Once a [global contract](../smart-contracts/global-contracts.md) has been [deplo ## View Function -View functions are read-only methods on a smart contract that do not modify state. You can call them without needing a `Signer` or `KeyPair`, and there’s no need to attach gas or a deposit. +View functions are read-only methods on a smart contract that do not modify state. You can call them without using an account or signing a transaction. - - - Let’s look at an example using the [Guestbook](https://github.com/near-examples/guest-book-examples) contract to read how many messages are currently stored. - - ```js - import { JsonRpcProvider } from "@near-js/providers"; - - const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com" }); - - await provider.callFunction( - "guestbook.near-examples.testnet", - "total_messages", - {} - ); - ``` - - - See full example on GitHub - - + + - + - + ```python view_call_result = await account.view_function("guestbook.near-examples.testnet", "total_messages", {}) @@ -1466,34 +597,20 @@ View functions are read-only methods on a smart contract that do not modify stat ### Get All Access Keys {#get-all-access-keys} -List all the access keys for an account. - - - - Let’s walk through an example of how to query the list of access keys associated with an account. - - ```js - import { JsonRpcProvider } from "@near-js/providers"; - - const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com" }); - - await provider.viewAccessKeyList("user.testnet"); - ``` - - - See full example on GitHub - - + + - + - + ```python keys = await account.get_access_key_list() @@ -1505,42 +622,24 @@ List all the access keys for an account. ### Add Full Access Key {#add-full-access-key} -Each account on NEAR can have multiple access keys, each with different permissions. +A [Full Access key](/protocol/access-keys.md#full-access-keys) grants complete control over the account. -A [Full Access key](/protocol/access-keys.md#full-access-keys), as the name suggests, grants complete control over the account. Anyone with this key can transfer funds, sign transactions, interact with contracts, or even delete the account entirely. +Anyone with this key can transfer funds, sign transactions, interact with contracts, or even delete the account entirely. - - - Once you've [created an `Account` instance](#instantiate-account), you can add another Full Access key to it. - - Simply generate a new key pair, then use the method below to add it to the account. - - ```js - import { KeyPair } from "@near-js/crypto"; - - const account = new Account("user.testnet", provider, signer); - - const keyPair = KeyPair.fromRandom("ed25519"); - - await account.addFullAccessKey( - keyPair.getPublicKey() - ); - ``` - - - See full example on GitHub - - + + - + - + ```python keys = await account.add_full_access_public_key("5X9WvUbRV3aSd9Py1LK7HAndqoktZtcgYdRjMt86SxMj") @@ -1552,59 +651,26 @@ A [Full Access key](/protocol/access-keys.md#full-access-keys), as the name sugg ### Add Function Call Key {#add-function-call-key} -Each account on NEAR can have multiple access keys, each with different permissions. - A [Function Call access key](/protocol/access-keys.md#function-call-keys) is designed specifically to sign transactions that include only [`functionCall` actions](/protocol/transaction-anatomy#actions) to a specific contract. You can further restrict this key by: - Limiting which method names can be called - Capping the amount of `NEAR` the key can spend on transaction fees -:::warning -For security reasons, Function Call access keys **can only be used with function calls that attach zero `NEAR` tokens. Any attempt to include a deposit will result in a failed transaction. -::: - -:::tip -One of the most powerful use cases for this type of key is enabling seamless user experiences β€” such as allowing a user to sign actions in a browser game without being redirected to a wallet for every interaction. -::: - - - - Once you've [created an `Account` instance](#instantiate-account), you can add a Functional Access key to it. - - Simply generate a new key pair, then use the method below to add it to the account. - - ```js - import { KeyPair } from "@near-js/crypto"; - import { NEAR } from "@near-js/tokens"; - - const account = new Account("user.testnet", provider, signer); - - const keyPair = KeyPair.fromRandom("ed25519"); - - await account.addFunctionCallAccessKey({ - publicKey: keyPair.getPublicKey(), - contractId: "example-contract.testnet", // Contract this key is allowed to call - methodNames: ["example_method"], // Methods this key is allowed to call (optional) - allowance: NEAR.toUnits("0.25") // Gas allowance key can use to call methods (optional) - } - ); - ``` - - - See full example on GitHub - - + + - + - + ```python await account.add_public_key( @@ -1618,41 +684,30 @@ One of the most powerful use cases for this type of key is enabling seamless use +:::tip +For security reasons, Function Call access keys **can only be used with function calls that attach zero `NEAR` tokens. Any attempt to include a deposit will result in a failed transaction. +::: +
### Delete Access Key {#delete-access-key} -Each account on Near can have multiple access keys, or even none at all. An account has the ability to remove its own keys, but not the keys of any other account, including its sub-accounts. - -:::danger -Be very careful when deleting keys. If you remove the same key used to sign the deletion, and it’s your only key, you will lose access to the account permanently. There’s no recovery unless another key was previously added. Always double-check before removing your access key. -::: +Accounts on NEAR can delete their own keys. - - - Once you've [created an `Account` instance](#instantiate-account), you can delete a key from it by simply providing the public key of the key pair you want to remove. - - ```js - const account = new Account("user.testnet", provider, signer); - - const publicKey = "ed25519:xxxxxxxx"; - await account.deleteKey(publicKey); - ``` - - - See full example on GitHub - - + + - + - + ```python await account.delete_public_key("5X9WvUbRV3aSd9Py1LK7HAndqoktZtcgYdRjMt86SxMj") @@ -1660,6 +715,10 @@ Be very careful when deleting keys. If you remove the same key used to sign the +:::danger +Be very careful when deleting keys, remove all keys from an account and you will lose access to the account permanently +::: + --- ## Validate Message Signatures @@ -1667,90 +726,10 @@ Be very careful when deleting keys. If you remove the same key used to sign the Users can sign messages using the `wallet-selector` `signMessage` method, which returns a signature. This signature can be verified using the following code: - - - - - - - ---- - - -## Utilities - -### NEAR to yoctoNEAR {#near-to-yoctonear} - -Convert an amount in NEAR to an amount in yoctoNEAR. - - - - - The `@near-js/tokens` package provides ready-to-use instances of common tokens, making it easy to format and convert token amounts. - - Let’s import the `NEAR` token and see how effortlessly you can convert a human-readable amount into `yoctoNEAR` units. - - ```js - import { NEAR } from "@near-js/tokens"; - - // outputs as BigInt(100000000000000000000000) - NEAR.toUnits("0.1"); - ``` - - - See full example on GitHub - - - - - - - - - - - ```python - from py_near.dapps.core import NEAR - - amount_in_yocto = 1 * NEAR - ``` - - - - -
- -### Format Amount {#format-amount} - - - - - The `@near-js/tokens` package provides ready-to-use instances of common tokens, making it easy to format and convert token amounts. - - Let’s import the `NEAR` token and see how easily you can convert values from `yoctoNEAR` back to a human-readable decimal amount. - - ```js - import { NEAR } from "@near-js/tokens"; - - // outputs as "1.23" - NEAR.toDecimal("1230000000000000000000000"); - ``` - - - See full example on GitHub - - - - - - Format an amount of NEAR into a string of NEAR or yoctoNEAR depending on the amount. + - + @@ -1760,7 +739,7 @@ Convert an amount in NEAR to an amount in yoctoNEAR. ## Additional resources - + - [Documentation](https://near.github.io/near-api-js) - [Github](https://github.com/near/near-api-js) @@ -1768,14 +747,14 @@ Convert an amount in NEAR to an amount in yoctoNEAR. - [Cookbook](https://github.com/near/near-api-js/tree/master/packages/cookbook) which contains examples using the near-js/client package, a wrapper tree shakable package for near-api-js. - + - [Documentation](https://docs.rs/near-api/latest/near_api/) - [Github](https://github.com/near/near-api-rs) - [Full Examples](https://github.com/near-examples/near-api-examples/tree/main/rust) - + - [Phone number transfer](https://py-near.readthedocs.io/en/latest/clients/phone.html) From 6fe09d1d9f126853baf84e3f8b2fb4b5e82bb5ac Mon Sep 17 00:00:00 2001 From: Guillermo Alejandro Gallardo Diez Date: Thu, 22 Jan 2026 17:34:43 +0100 Subject: [PATCH 2/5] feat: added near-kit --- docs/tools/near-api.md | 123 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 121 insertions(+), 2 deletions(-) diff --git a/docs/tools/near-api.md b/docs/tools/near-api.md index dd56057b17e..332a1be7769 100644 --- a/docs/tools/near-api.md +++ b/docs/tools/near-api.md @@ -30,6 +30,13 @@ We have APIs available for Javascript, Rust, and Python. Add them to your projec npm i near-api-js ``` + + + + ```bash + npm i near-kit + ``` + @@ -64,6 +71,10 @@ Gets the available and staked balance of an account in yoctoNEAR. + + + + + + + + @@ -127,6 +144,10 @@ To create a named account like `user.testnet`, you need to call the `create_acco + + + + + + + + + + @@ -211,6 +239,12 @@ Accounts on NEAR can delete themselves, transferring any remaining balance to a url="https://github.com/near-examples/near-api-examples/blob/main/near-api-js/examples/delete-account.ts" /> + + + + + + +
+ + + + + + + + + + + + + + + + + + + + Note that the `signer` here needs to be a signer for the same `account_id` as the one used to construct the `Contract` object. @@ -430,6 +494,21 @@ There are two ways to reference a global contract: + + + + + + + + + + + + + Once you've created an Account instance, you can deploy your regular contract as a global contract. @@ -506,6 +585,19 @@ Once a [global contract](../smart-contracts/global-contracts.md) has been [deplo
+ + + + + + + + + + + @@ -570,6 +662,10 @@ View functions are read-only methods on a smart contract that do not modify stat url="https://github.com/near-examples/near-api-examples/blob/main/near-api-js/examples/contract-interaction.ts" start="9" end="21" /> + + + + + + + + + + + + + + + + +
--- @@ -744,7 +858,12 @@ Users can sign messages using the `wallet-selector` `signMessage` method, which - [Documentation](https://near.github.io/near-api-js) - [Github](https://github.com/near/near-api-js) - [Full Examples](https://github.com/near-examples/near-api-examples/tree/main) - - [Cookbook](https://github.com/near/near-api-js/tree/master/packages/cookbook) which contains examples using the near-js/client package, a wrapper tree shakable package for near-api-js. + +
+ + + - [Github](https://github.com/r-near/near-kit/tree/main) + - [Full Examples](https://github.com/near-examples/near-api-examples/tree/main/near-kit) @@ -756,7 +875,7 @@ Users can sign messages using the `wallet-selector` `signMessage` method, which - - [Phone number transfer](https://py-near.readthedocs.io/en/latest/clients/phone.html) + - [Github](github.com/pvolnov/py-near)
From d4590bac70c6bc1cc22a00268deb537e95766058 Mon Sep 17 00:00:00 2001 From: Guillermo Alejandro Gallardo Diez Date: Thu, 22 Jan 2026 17:40:02 +0100 Subject: [PATCH 3/5] fix: broken link --- docs/tools/near-api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tools/near-api.md b/docs/tools/near-api.md index 332a1be7769..8eef284a0f3 100644 --- a/docs/tools/near-api.md +++ b/docs/tools/near-api.md @@ -875,7 +875,7 @@ Users can sign messages using the `wallet-selector` `signMessage` method, which
- - [Github](github.com/pvolnov/py-near) + - [Github](https://github.com/pvolnov/py-near)
From 73f593c3eb156d3fd0d1b4172e0c785686f2a767 Mon Sep 17 00:00:00 2001 From: Guillermo Alejandro Gallardo Diez Date: Thu, 22 Jan 2026 18:14:38 +0100 Subject: [PATCH 4/5] chore: last minor edits --- docs/tools/near-api.md | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/docs/tools/near-api.md b/docs/tools/near-api.md index 8eef284a0f3..335e1a33804 100644 --- a/docs/tools/near-api.md +++ b/docs/tools/near-api.md @@ -258,10 +258,12 @@ Accounts on NEAR can delete themselves, transferring any remaining balance to a Deleting an account **DOES NOT** affect its sub-accounts - they will remain active. ::: -:::danger Keep in mind -- Only NEAR tokens are transferred to the beneficiary. -- Fungible (FTs) or Non-Fungible tokens (NFTs) held by the account **ARE NOT** automatically transferred. These tokens are still associated with the account, even after the account is deleted. Make sure to transfer those assets manually before deletion, or you're risking losing them permanently! Once the account is gone, those assets are effectively stuck unless the same account is recreated by anyone (not necessarily you). -- If the beneficiary account doesn't exist, all NEAR tokens sent to it will be burned. Double-check the account ID before proceeding. +:::danger The Beneficiary Only Receives NEAR Tokens +Fungible (FTs) or Non-Fungible tokens (NFTs) held by the account **ARE NOT** automatically transferred. These tokens are still associated with the account, even after the account is deleted. Make sure to transfer those assets manually before deletion, or you're risking losing them permanently! Once the account is gone, those assets are effectively stuck unless the same account is recreated by anyone (not necessarily you). +::: + +:::danger Make Sure the Beneficiary Account Exists +If the beneficiary account doesn't exist, all NEAR tokens sent to it will be burned. Double-check the account ID before proceeding. ::: --- @@ -317,6 +319,9 @@ A smart contract exposes its methods, and making a function call that modifies s + :::tip Typed Result + When using Typescript, you can type the return of `callFunction` + ::: + :::tip Typed Result + When using Typescript, you can type the return of `Near.view` and `Near.call` + ::: + :::tip Typed Result + When using Typescript, you can type the return of `callFunction` + ::: + :::tip Typed Result + When using Typescript, you can type the return of `Near.view` + ::: From fca67e53ce8539396d39846582c77077b9af679e Mon Sep 17 00:00:00 2001 From: Guillermo Alejandro Gallardo Diez Date: Thu, 22 Jan 2026 18:25:25 +0100 Subject: [PATCH 5/5] fix: naj examples on rpc api section --- docs/api/rpc/access-keys.md | 42 ++++++++++++++++++----- docs/api/rpc/block-chunk.md | 64 +++++++++++++++++++++++++++++++----- docs/api/rpc/contracts.md | 64 +++++++++++++++++++++++++++++++----- docs/api/rpc/gas.md | 24 ++++++++++++-- docs/api/rpc/network.md | 8 ++++- docs/api/rpc/protocol.md | 18 ++++++++-- docs/api/rpc/providers.md | 2 +- docs/api/rpc/setup.md | 3 +- docs/api/rpc/transactions.md | 32 ++++++++++++------ 9 files changed, 214 insertions(+), 43 deletions(-) diff --git a/docs/api/rpc/access-keys.md b/docs/api/rpc/access-keys.md index d9f9b735086..ffb34a413dd 100644 --- a/docs/api/rpc/access-keys.md +++ b/docs/api/rpc/access-keys.md @@ -65,12 +65,20 @@ The RPC API enables you to retrieve information about an account's access keys. ```js - const response = await near.connection.provider.query({ - request_type: 'view_access_key', - finality: 'final', - account_id: 'account.rpc-examples.testnet', - public_key: 'ed25519:EddTahJwZpJjYPPmat7DBm1m2vdrFBzVv7e3T4hzkENd', + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", + }); + + const response = await provider.query({ + request_type: 'view_access_key', + finality: 'final', + account_id: 'account.rpc-examples.testnet', + public_key: 'ed25519:EddTahJwZpJjYPPmat7DBm1m2vdrFBzVv7e3T4hzkENd', }); + + console.log(response); ``` @@ -163,7 +171,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.query({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", + }); + + const response = await provider.query({ request_type: 'view_access_key_list', finality: 'final', account_id: 'account.rpc-examples.testnet', @@ -277,7 +291,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.singleAccessKeyChanges( + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.singleAccessKeyChanges( [ { account_id: 'account.rpc-examples.testnet', @@ -395,7 +415,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.accessKeyChanges(['account.rpc-examples.testnet'], { + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.accessKeyChanges(['account.rpc-examples.testnet'], { blockId: 187309655, }); ``` diff --git a/docs/api/rpc/block-chunk.md b/docs/api/rpc/block-chunk.md index 07157cc3521..e400e591da6 100644 --- a/docs/api/rpc/block-chunk.md +++ b/docs/api/rpc/block-chunk.md @@ -56,7 +56,13 @@ Here's a quick reference table for all the methods in this section: ```js - const response = await near.connection.provider.block({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", + }); + + const response = await provider.block({ finality: 'final', }); ``` @@ -94,7 +100,13 @@ Here's a quick reference table for all the methods in this section: ```js - const response = await near.connection.provider.block({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.block({ blockId: 187310138, }); ``` @@ -132,7 +144,13 @@ Here's a quick reference table for all the methods in this section: ```js - const response = await near.connection.provider.block({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.block({ blockId: '6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w', }); ``` @@ -436,7 +454,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.blockChanges({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", + }); + + const response = await provider.blockChanges({ finality: 'final', }); ``` @@ -474,7 +498,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.blockChanges({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.blockChanges({ blockId: 187310138, }); ``` @@ -512,7 +542,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.blockChanges({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.blockChanges({ blockId: '6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w', }); ``` @@ -624,7 +660,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.chunk( + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.chunk( 'CzPafxtJmM1FnRoasKWAVhceJzZzkz9RKUBQQ4kY9V1v', ); ``` @@ -663,7 +705,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.chunk([187310138, 0]); + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.chunk([187310138, 0]); ``` diff --git a/docs/api/rpc/contracts.md b/docs/api/rpc/contracts.md index 22e8fcb7f90..5384e039b52 100644 --- a/docs/api/rpc/contracts.md +++ b/docs/api/rpc/contracts.md @@ -56,7 +56,13 @@ The RPC API enables you to view details about accounts and contracts as well as ```js - const response = await near.connection.provider.query({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", + }); + + const response = await provider.query({ request_type: 'view_account', finality: 'final', account_id: 'account.rpc-examples.testnet', @@ -139,7 +145,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.accountChanges(['contract.rpc-examples.testnet'], { + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.accountChanges(['contract.rpc-examples.testnet'], { blockId: 187310139, }); ``` @@ -246,7 +258,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.query({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", + }); + + const response = await provider.query({ request_type: 'view_code', finality: 'final', account_id: 'contract.rpc-examples.testnet', @@ -330,7 +348,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.query({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", + }); + + const response = await provider.query({ request_type: 'view_state', finality: 'final', account_id: 'contract.rpc-examples.testnet', @@ -431,7 +455,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.contractStateChanges( + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.contractStateChanges( ['contract.rpc-examples.testnet'], { blockId: 187310139 }, '' @@ -536,7 +566,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.contractCodeChanges( + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.contractCodeChanges( ['contract.rpc-examples.testnet'], { blockId: 187309439 } ); @@ -629,7 +665,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.query({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", + }); + + const response = await provider.query({ request_type: 'call_function', finality: 'final', account_id: 'contract.rpc-examples.testnet', @@ -723,7 +765,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.query({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", + }); + + const response = await provider.query({ request_type: 'call_function', finality: 'final', account_id: 'contract.rpc-examples.testnet', diff --git a/docs/api/rpc/gas.md b/docs/api/rpc/gas.md index bc2fa6662a1..8eabd30a29a 100644 --- a/docs/api/rpc/gas.md +++ b/docs/api/rpc/gas.md @@ -50,7 +50,13 @@ The RPC API enables you to query the gas price for a specific block or hash. ```js - const response = await near.connection.provider.gasPrice(null); + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", + }); + + const response = await provider.gasPrice(null); ``` @@ -82,7 +88,13 @@ The RPC API enables you to query the gas price for a specific block or hash. ```js - const response = await near.connection.provider.gasPrice(187310138); + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.gasPrice(187310138); ``` @@ -114,7 +126,13 @@ The RPC API enables you to query the gas price for a specific block or hash. ```js - const response = await near.connection.provider.gasPrice( + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.gasPrice( '6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w', ); ``` diff --git a/docs/api/rpc/network.md b/docs/api/rpc/network.md index 9f2ab03b6ee..dc38a4bf4de 100644 --- a/docs/api/rpc/network.md +++ b/docs/api/rpc/network.md @@ -49,7 +49,13 @@ The RPC API enables you to query status information for nodes and validators. ```js - const response = await near.connection.provider.status(); + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", + }); + + const response = await provider.status(); ``` diff --git a/docs/api/rpc/protocol.md b/docs/api/rpc/protocol.md index fe2b2dc5a84..687a4261ee9 100644 --- a/docs/api/rpc/protocol.md +++ b/docs/api/rpc/protocol.md @@ -46,9 +46,15 @@ The RPC API enables you to retrieve the current genesis and protocol configurati ```js - const response = await near.connection.provider.experimental_protocolConfig({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", + }); + + const response = await provider.experimental_protocolConfig({ sync_checkpoint: 'genesis', -}); + }); ``` @@ -263,7 +269,13 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.experimental_protocolConfig({ + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://test.rpc.fastnear.com", + }); + + const response = await provider.experimental_protocolConfig({ finality: "final" }); ``` diff --git a/docs/api/rpc/providers.md b/docs/api/rpc/providers.md index dc992a0528e..e4229f244cd 100644 --- a/docs/api/rpc/providers.md +++ b/docs/api/rpc/providers.md @@ -61,7 +61,7 @@ FastNear maintains [a comprehensive Grafana dashboard](https://grafana.fastnear. ## RPC Failover -In `near-api-js` you can use [`FailoverRpcProvider`](../../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. +In `near-api-js` you can use [`FailoverRpcProvider`](https://github.com/near-examples/near-api-examples/blob/main/near-api-js/examples/rpc-failover.ts) 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. diff --git a/docs/api/rpc/setup.md b/docs/api/rpc/setup.md index dd332339efb..ea36afd22f1 100644 --- a/docs/api/rpc/setup.md +++ b/docs/api/rpc/setup.md @@ -58,14 +58,15 @@ You only need to configure two things: After that is set up, just copy/paste the `JSON object` example snippets below into the `body` of your request, on Postman, and click `send`. --- + ## JavaScript Setup {#javascript-setup} All of the queries listed in this documentation page can be called using [`near-api-js`](https://github.com/near/near-api-js). - For `near-api-js` installation and setup please refer to `near-api-js` [quick reference documentation](../../tools/near-api.md). -- All JavaScript code snippets require a `near` object. For examples of how to instantiate, [**click here**](../../tools/near-api.md#connect). --- + ## HTTPie Setup {#httpie-setup} If you prefer to use a command line interface, we have provided RPC examples you can use with [HTTPie](https://httpie.org/). Please note that params take diff --git a/docs/api/rpc/transactions.md b/docs/api/rpc/transactions.md index f647e6e2aed..e6b6a5ddd51 100644 --- a/docs/api/rpc/transactions.md +++ b/docs/api/rpc/transactions.md @@ -184,11 +184,17 @@ When making RPC API requests, you may encounter various errors related to networ ```js - const response = await near.connection.provider.txStatus( - '7AfonAhbK4ZbdBU9VPcQdrTZVZBXE25HmZAMEABs9To1', - 'rpc-examples.testnet', - 'FINAL', - ); + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.txStatus( + '7AfonAhbK4ZbdBU9VPcQdrTZVZBXE25HmZAMEABs9To1', + 'rpc-examples.testnet', + 'FINAL', + ); ``` @@ -349,11 +355,17 @@ When making RPC API requests, you may encounter various errors related to networ ```js -const response = await near.connection.provider.txStatusReceipts( - '7AfonAhbK4ZbdBU9VPcQdrTZVZBXE25HmZAMEABs9To1', - 'rpc-examples.testnet', - 'FINAL', -); + import { JsonRpcProvider } from "near-api-js"; + + const provider = new JsonRpcProvider({ + url: "https://archival-rpc.testnet.near.org", + }); + + const response = await provider.txStatusReceipts( + '7AfonAhbK4ZbdBU9VPcQdrTZVZBXE25HmZAMEABs9To1', + 'rpc-examples.testnet', + 'FINAL', + ); ```