# Post block
Source: https://docs.near.org/api-reference/post-block
/openapi.json post /block
Returns block details for given height or hash
# Post block effects
Source: https://docs.near.org/api-reference/post-block_effects
/openapi.json post /block_effects
Returns changes in block for given block height or hash over all transactions for all the types. Includes changes like account_touched, access_key_touched, data_touched, contract_code_touched.
# Post broadcast tx async
Source: https://docs.near.org/api-reference/post-broadcast_tx_async
/openapi.json post /broadcast_tx_async
[Deprecated] Sends a transaction and immediately returns transaction hash. Consider using send_tx instead.
# Post broadcast tx commit
Source: https://docs.near.org/api-reference/post-broadcast_tx_commit
/openapi.json post /broadcast_tx_commit
[Deprecated] Sends a transaction and waits until transaction is fully complete. (Has a 10 second timeout). Consider using send_tx instead.
# Post changes
Source: https://docs.near.org/api-reference/post-changes
/openapi.json post /changes
Returns changes for a given account, contract or contract code for given block height or hash.
# Post chunk
Source: https://docs.near.org/api-reference/post-chunk
/openapi.json post /chunk
Returns details of a specific chunk. You can run a block details query to get a valid chunk hash.
# Post client config
Source: https://docs.near.org/api-reference/post-client_config
/openapi.json post /client_config
Queries client node configuration
# Post experimental call function
Source: https://docs.near.org/api-reference/post-experimental_call_function
/openapi.json post /EXPERIMENTAL_call_function
Calls a view function on a contract and returns the result.
# Post experimental changes
Source: https://docs.near.org/api-reference/post-experimental_changes
/openapi.json post /EXPERIMENTAL_changes
[Deprecated] Returns changes for a given account, contract or contract code for given block height or hash. Consider using changes instead.
# Post experimental changes in block
Source: https://docs.near.org/api-reference/post-experimental_changes_in_block
/openapi.json post /EXPERIMENTAL_changes_in_block
[Deprecated] Returns changes in block for given block height or hash over all transactions for all the types. Includes changes like account_touched, access_key_touched, data_touched, contract_code_touched. Consider using block_effects instead
# Post experimental congestion level
Source: https://docs.near.org/api-reference/post-experimental_congestion_level
/openapi.json post /EXPERIMENTAL_congestion_level
Queries the congestion level of a shard. More info about congestion [here](https://near.github.io/nearcore/architecture/how/receipt-congestion.html?highlight=congestion#receipt-congestion)
# Post experimental genesis config
Source: https://docs.near.org/api-reference/post-experimental_genesis_config
/openapi.json post /EXPERIMENTAL_genesis_config
[Deprecated] Get initial state and parameters for the genesis block. Consider genesis_config instead.
# Post experimental light client block proof
Source: https://docs.near.org/api-reference/post-experimental_light_client_block_proof
/openapi.json post /EXPERIMENTAL_light_client_block_proof
Returns the proofs for a transaction execution.
# Post experimental light client proof
Source: https://docs.near.org/api-reference/post-experimental_light_client_proof
/openapi.json post /EXPERIMENTAL_light_client_proof
Returns the proofs for a transaction execution.
# Post experimental maintenance windows
Source: https://docs.near.org/api-reference/post-experimental_maintenance_windows
/openapi.json post /EXPERIMENTAL_maintenance_windows
[Deprecated] Returns the future windows for maintenance in current epoch for the specified account. In the maintenance windows, the node will not be block producer or chunk producer. Consider using maintenance_windows instead.
# Post experimental protocol config
Source: https://docs.near.org/api-reference/post-experimental_protocol_config
/openapi.json post /EXPERIMENTAL_protocol_config
A configuration that defines the protocol-level parameters such as gas/storage costs, limits, feature flags, other settings
# Post experimental receipt
Source: https://docs.near.org/api-reference/post-experimental_receipt
/openapi.json post /EXPERIMENTAL_receipt
Fetches a receipt by its ID (as is, without a status or execution outcome)
# Post experimental receipt to tx
Source: https://docs.near.org/api-reference/post-experimental_receipt_to_tx
/openapi.json post /EXPERIMENTAL_receipt_to_tx
Resolves a receipt ID back to the originating transaction hash and sender account
# Post experimental split storage info
Source: https://docs.near.org/api-reference/post-experimental_split_storage_info
/openapi.json post /EXPERIMENTAL_split_storage_info
Contains the split storage information. More info on split storage [here](https://near-nodes.io/archival/split-storage-archival)
# Post experimental tx status
Source: https://docs.near.org/api-reference/post-experimental_tx_status
/openapi.json post /EXPERIMENTAL_tx_status
[Deprecated] Queries status of a transaction by hash, returning the final transaction result and details of all receipts. Consider using `tx_status` instead.
# Post experimental validators ordered
Source: https://docs.near.org/api-reference/post-experimental_validators_ordered
/openapi.json post /EXPERIMENTAL_validators_ordered
Returns the current epoch validators ordered in the block producer order with repetition. This endpoint is solely used for bridge currently and is not intended for other external use cases.
# Post experimental view access key
Source: https://docs.near.org/api-reference/post-experimental_view_access_key
/openapi.json post /EXPERIMENTAL_view_access_key
Returns information about a single access key for given account.
# Post experimental view access key list
Source: https://docs.near.org/api-reference/post-experimental_view_access_key_list
/openapi.json post /EXPERIMENTAL_view_access_key_list
Returns all access keys for a given account.
# Post experimental view account
Source: https://docs.near.org/api-reference/post-experimental_view_account
/openapi.json post /EXPERIMENTAL_view_account
Returns information about an account for given account_id.
# Post experimental view code
Source: https://docs.near.org/api-reference/post-experimental_view_code
/openapi.json post /EXPERIMENTAL_view_code
Returns the contract code (Wasm binary) deployed to the account.
# Post experimental view state
Source: https://docs.near.org/api-reference/post-experimental_view_state
/openapi.json post /EXPERIMENTAL_view_state
Returns the state (key-value pairs) of a contract based on the key prefix.
# Post gas price
Source: https://docs.near.org/api-reference/post-gas_price
/openapi.json post /gas_price
Returns gas price for a specific block_height or block_hash. Using [null] will return the most recent block's gas price.
# Post genesis config
Source: https://docs.near.org/api-reference/post-genesis_config
/openapi.json post /genesis_config
Get initial state and parameters for the genesis block
# Post health
Source: https://docs.near.org/api-reference/post-health
/openapi.json post /health
Returns the current health status of the RPC node the client connects to.
# Post light client proof
Source: https://docs.near.org/api-reference/post-light_client_proof
/openapi.json post /light_client_proof
Returns the proofs for a transaction execution.
# Post maintenance windows
Source: https://docs.near.org/api-reference/post-maintenance_windows
/openapi.json post /maintenance_windows
Returns the future windows for maintenance in current epoch for the specified account. In the maintenance windows, the node will not be block producer or chunk producer.
# Post network info
Source: https://docs.near.org/api-reference/post-network_info
/openapi.json post /network_info
Queries the current state of node network connections. This includes information about active peers, transmitted data, known producers, etc.
# Post next light client block
Source: https://docs.near.org/api-reference/post-next_light_client_block
/openapi.json post /next_light_client_block
Returns the next light client block.
# Post query
Source: https://docs.near.org/api-reference/post-query
/openapi.json post /query
This module allows you to make generic requests to the network.
The `RpcQueryRequest` struct takes in a [`BlockReference`](https://docs.rs/near-primitives/0.12.0/near_primitives/types/enum.BlockReference.html) and a [`QueryRequest`](https://docs.rs/near-primitives/0.12.0/near_primitives/views/enum.QueryRequest.html).
The `BlockReference` enum allows you to specify a block by `Finality`, `BlockId` or `SyncCheckpoint`.
The `QueryRequest` enum provides multiple variants for performing the following actions:
- View an account's details
- View a contract's code
- View the state of an account
- View the `AccessKey` of an account
- View the `AccessKeyList` of an account
- Call a function in a contract deployed on the network.
# Post send tx
Source: https://docs.near.org/api-reference/post-send_tx
/openapi.json post /send_tx
Sends transaction. Returns the guaranteed execution status and the results the blockchain can provide at the moment.
# Post status
Source: https://docs.near.org/api-reference/post-status
/openapi.json post /status
Requests the status of the connected RPC node. This includes information about sync status, nearcore node version, protocol version, the current set of validators, etc.
# Post tx
Source: https://docs.near.org/api-reference/post-tx
/openapi.json post /tx
Queries status of a transaction by hash and returns the final transaction result.
# Post tx status
Source: https://docs.near.org/api-reference/post-tx_status
/openapi.json post /tx_status
Queries status of a transaction by hash, returning the final transaction result and details of all receipts.
# Post validators
Source: https://docs.near.org/api-reference/post-validators
/openapi.json post /validators
Queries active validators on the network. Returns details and the state of validation on the blockchain.
# Block / Chunk
Source: https://docs.near.org/api/rpc/block-chunk
Learn how to retrieve details about blocks and chunks from the NEAR RPC API.
The RPC API enables you to query the network and get details about specific blocks or chunks.
## Quick Reference
| Method | Description | Parameters |
| - | - | - |
| [`block`](#block-details) | Get block details by height, hash, or finality | `finality` OR `block_id` |
| [`block_effects`](#block-effects) | Get changes in a specific block | `finality` OR `block_id` |
| [`chunk`](#chunk-details) | Get chunk details by chunk\_id or block\_id + shard\_id | `chunk_id` OR `block_id` + `shard_id` |
***
## Block Details
Queries network and returns block for given height or hash. You can also use `finality` param to return latest block details.
**Note**: You may choose to search by a specific block *or* finality, you cannot choose both.
* **method**: `block`
* **params**: `finality` OR `block_id`
> [tab] by finality
>
> > [tab] JSON
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "jsonrpc": "2.0",
> > "id": "dontcare",
> > "method": "block",
> > "params": {
> > "finality": "final"
> > }
> > }
> > ```
>
> > [tab] JavaScript
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > import { JsonRpcProvider } from "near-api-js";
> >
> > const provider = new JsonRpcProvider({
> > url: "https://test.rpc.fastnear.com",
> > });
> >
> > const response = await provider.block({
> > finality: 'final',
> > });
> > ```
>
> > [tab] HTTPie
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > http POST https://rpc.testnet.near.org \
> > jsonrpc=2.0 \
> > id=dontcare \
> > method=block \
> > params:='{"finality": "final"}'
> > ```
> [tab] by block height
>
> > [tab] JSON
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "jsonrpc": "2.0",
> > "id": "dontcare",
> > "method": "block",
> > "params": {
> > "block_id": 187310138
> > }
> > }
> > ```
>
> > [tab] JavaScript
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > import { JsonRpcProvider } from "near-api-js";
> >
> > const provider = new JsonRpcProvider({
> > url: "https://archival-rpc.testnet.near.org",
> > });
> >
> > const response = await provider.block({
> > blockId: 187310138,
> > });
> > ```
>
> > [tab] HTTPie
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > http POST https://archival-rpc.testnet.near.org \
> > jsonrpc=2.0 \
> > id=dontcare \
> > method=block \
> > params:='{"block_id": 187310138}'
> > ```
> [tab] by block hash
>
> > [tab] JSON
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "jsonrpc": "2.0",
> > "id": "dontcare",
> > "method": "block",
> > "params": {
> > "block_id": "6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w"
> > }
> > }
> > ```
>
> > [tab] JavaScript
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > import { JsonRpcProvider } from "near-api-js";
> >
> > const provider = new JsonRpcProvider({
> > url: "https://archival-rpc.testnet.near.org",
> > });
> >
> > const response = await provider.block({
> > blockId: '6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w',
> > });
> > ```
>
> > [tab] HTTPie
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > http POST https://archival-rpc.testnet.near.org \
> > jsonrpc=2.0 \
> > id=dontcare \
> > method=block \
> > params:='{"block_id": "6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w"}'
> > ```
> [accordion] Example response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "author": "node2",
> "chunks": [
> {
> "chunk_hash": "CzPafxtJmM1FnRoasKWAVhceJzZzkz9RKUBQQ4kY9V1v",
> "shard_id": 0,
> "gas_limit": 1000000000000000,
> "gas_used": 0,
> "height_created": 187310138,
> "height_included": 187310138
> }
> ],
> "header": {
> "hash": "6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w",
> "height": 187310138,
> "timestamp": 1739254177539033760,
> "gas_price": "100000000",
> "latest_protocol_version": 73
> }
> },
> "id": "dontcare"
> }
> ```
***
## Block Effects
Returns changes in a block for given block height or hash. Includes changes like `account_touched`, `access_key_touched`, `data_touched`, `contract_code_touched`.
* **method**: `block_effects`
* **params**: `finality` OR `block_id`
> [tab] by finality
>
> > [tab] JSON
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "jsonrpc": "2.0",
> > "id": "dontcare",
> > "method": "block_effects",
> > "params": {
> > "finality": "final"
> > }
> > }
> > ```
>
> > [tab] JavaScript
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > import { JsonRpcProvider } from "near-api-js";
> >
> > const provider = new JsonRpcProvider({
> > url: "https://test.rpc.fastnear.com",
> > });
> >
> > const response = await provider.blockChanges({
> > finality: 'final',
> > });
> > ```
>
> > [tab] HTTPie
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > http POST https://rpc.testnet.near.org \
> > jsonrpc=2.0 \
> > id=dontcare \
> > method=block_effects \
> > params:='{"finality": "final"}'
> > ```
> [tab] by block height
>
> > [tab] JSON
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "jsonrpc": "2.0",
> > "id": "dontcare",
> > "method": "block_effects",
> > "params": {
> > "block_id": 187310138
> > }
> > }
> > ```
>
> > [tab] JavaScript
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > import { JsonRpcProvider } from "near-api-js";
> >
> > const provider = new JsonRpcProvider({
> > url: "https://archival-rpc.testnet.near.org",
> > });
> >
> > const response = await provider.blockChanges({
> > blockId: 187310138,
> > });
> > ```
>
> > [tab] HTTPie
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > http POST https://archival-rpc.testnet.near.org \
> > jsonrpc=2.0 \
> > id=dontcare \
> > method=block_effects \
> > params:='{"block_id": 187310138}'
> > ```
> [tab] by block hash
>
> > [tab] JSON
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "jsonrpc": "2.0",
> > "id": "dontcare",
> > "method": "block_effects",
> > "params": {
> > "block_id": "6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w"
> > }
> > }
> > ```
>
> > [tab] JavaScript
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > import { JsonRpcProvider } from "near-api-js";
> >
> > const provider = new JsonRpcProvider({
> > url: "https://archival-rpc.testnet.near.org",
> > });
> >
> > const response = await provider.blockChanges({
> > blockId: '6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w',
> > });
> > ```
>
> > [tab] HTTPie
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > http POST https://archival-rpc.testnet.near.org \
> > jsonrpc=2.0 \
> > id=dontcare \
> > method=block_effects \
> > params:='{"block_id": "6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w"}'
> > ```
> [accordion] Example response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "block_hash": "6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w",
> "changes": [
> { "account_id": "account.rpc-examples.testnet", "type": "account_touched" },
> { "account_id": "ping-account.testnet", "type": "account_touched" },
> { "account_id": "account.rpc-examples.testnet", "type": "access_key_touched" },
> { "account_id": "dev2-nsp.testnet", "type": "data_touched" }
> ]
> },
> "id": "dontcare"
> }
> ```
***
## Chunk Details
Returns details of a specific chunk. You can run a [block details](#block-details) query to get a valid chunk hash.
* **method**: `chunk`
* **params**: `chunk_id` OR `block_id` + `shard_id`
> [tab] by chunk\_id
>
> > [tab] JSON
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "jsonrpc": "2.0",
> > "id": "dontcare",
> > "method": "chunk",
> > "params": {
> > "chunk_id": "CzPafxtJmM1FnRoasKWAVhceJzZzkz9RKUBQQ4kY9V1v"
> > }
> > }
> > ```
>
> > [tab] JavaScript
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > import { JsonRpcProvider } from "near-api-js";
> >
> > const provider = new JsonRpcProvider({
> > url: "https://archival-rpc.testnet.near.org",
> > });
> >
> > const response = await provider.chunk(
> > 'CzPafxtJmM1FnRoasKWAVhceJzZzkz9RKUBQQ4kY9V1v',
> > );
> > ```
>
> > [tab] HTTPie
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > http POST https://archival-rpc.testnet.near.org \
> > jsonrpc=2.0 \
> > id=dontcare \
> > method=chunk \
> > params:='{"chunk_id": "CzPafxtJmM1FnRoasKWAVhceJzZzkz9RKUBQQ4kY9V1v"}'
> > ```
> [tab] by block\_id + shard\_id
>
> > [tab] JSON
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "jsonrpc": "2.0",
> > "id": "dontcare",
> > "method": "chunk",
> > "params": {
> > "block_id": 187310138,
> > "shard_id": 0
> > }
> > }
> > ```
>
> > [tab] JavaScript
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > import { JsonRpcProvider } from "near-api-js";
> >
> > const provider = new JsonRpcProvider({
> > url: "https://archival-rpc.testnet.near.org",
> > });
> >
> > const response = await provider.chunk([187310138, 0]);
> > ```
>
> > [tab] HTTPie
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > http POST https://archival-rpc.testnet.near.org \
> > jsonrpc=2.0 \
> > id=dontcare \
> > method=chunk \
> > params:='{"block_id": 187310138, "shard_id": 0}'
> > ```
> [accordion] Example response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "author": "kiln.pool.f863973.m0",
> "header": {
> "chunk_hash": "CzPafxtJmM1FnRoasKWAVhceJzZzkz9RKUBQQ4kY9V1v",
> "shard_id": 0,
> "gas_limit": 1000000000000000,
> "gas_used": 0,
> "height_created": 187310138,
> "height_included": 187310138
> },
> "receipts": [],
> "transactions": [
> {
> "hash": "J3KbUXF9YPu2eGnbDCACxGvmMDZMdP7acGYhVLHGu9y2",
> "signer_id": "account.rpc-examples.testnet",
> "receiver_id": "contract.rpc-examples.testnet"
> }
> ]
> },
> "id": "dontcare"
> }
> ```
***
## Error Handling
| Error Code | Description | Solution |
| - | - | - |
| `UNKNOWN_BLOCK` | Block not found or garbage-collected | Check block validity; use archival node for old blocks |
| `UNKNOWN_CHUNK` | Chunk not found in database | Verify chunk ID; use archival node for old chunks |
| `INVALID_SHARD_ID` | Shard ID does not exist | Provide valid shard ID for existing shard |
| `NOT_SYNCED_YET` | Node still syncing | Wait for sync completion or use different node |
| `PARSE_ERROR` | Invalid request parameters | Check parameter format and completeness |
| `INTERNAL_ERROR` | Server-side issue | Retry request or try different RPC endpoint |
# Accounts / Contracts
Source: https://docs.near.org/api/rpc/contracts
Learn to query information from accounts and contracts using the NEAR RPC API.
The RPC API enables you to view details about accounts and contracts as well as perform contract calls.
## Quick Reference
| Method | Purpose |
| - | - |
| [`view_account`](#view-account) | Get basic account information |
| [`view_account_changes`](#view-account-changes) | Monitor account state changes |
| [`view_access_key`](#view-access-key) | Get the nonce and permissions of a single access key |
| [`view_access_key_list`](#view-access-key-list) | List all access keys on an account |
| [`view_gas_key_nonces`](#view-gas-key-nonces) | List the parallel nonces of a gas key |
| [`view_code`](#view-contract-code) | Get deployed contract WASM code |
| [`view_global_contract_code`](#view-global-contract-code-by-hash) | Get global contract WASM code by its code hash |
| [`view_global_contract_code_by_account_id`](#view-global-contract-code-by-account) | Get global contract WASM code by its owner account |
| [`view_state`](#view-contract-state) | Get contract storage data |
| [`data_changes`](#view-contract-state-changes) | Monitor contract state changes |
| [`contract_code_changes`](#view-contract-code-changes) | Monitor contract deployments |
| [`call_function`](#call-a-contract-function) | Execute read-only contract methods |
***
## View Account
Returns basic account information.
* **method**: `query`
* **params**: `request_type: view_account`, `finality` OR `block_id`, `account_id`
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "view_account",
> "finality": "final",
> "account_id": "account.rpc-examples.testnet"
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> 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',
> });
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=query \
> params:='{"request_type":"view_account","finality":"final","account_id":"account.rpc-examples.testnet"}'
> ```
> [accordion] Example response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "amount": "999788200694421800000000",
> "block_hash": "56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW",
> "block_height": 187440904,
> "code_hash": "11111111111111111111111111111111",
> "locked": "0",
> "storage_usage": 410
> },
> "id": "dontcare"
> }
> ```
> [!TIP]
>
> **Extra fields on an uninitialized [universal account](/protocol/accounts-contracts/account-id#universal-address)**
>
> A `0u` account that's been funded but [not initialized](/protocol/tutorials/creating-universal-accounts#the-uninitialized-account) returns `state: "uninitialized"` and a `bootstrap_nonce`.
>
> Both fields are omitted once the account initializes — see [Creating Universal Accounts](/protocol/tutorials/creating-universal-accounts#the-uninitialized-account) for a full example response.
***
## View Account Changes
Returns account changes from transactions in a given account.
* **method**: `changes`
* **params**: `changes_type: account_changes`, `account_ids`, `finality` OR `block_id`
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "changes",
> "params": {
> "changes_type": "account_changes",
> "account_ids": ["contract.rpc-examples.testnet"],
> "block_id": 187310139
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> 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 }
> );
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://archival-rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=changes \
> params:='{"changes_type":"account_changes","account_ids":["contract.rpc-examples.testnet"],"block_id":187310139}'
> ```
***
## View Access Key
Returns the nonce and permissions of a single [access key](/protocol/accounts-contracts/access-keys), given the account and the key's public key.
* **method**: `query`
* **params**: `request_type: view_access_key`, `finality` OR `block_id`, `account_id`, `public_key`
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "view_access_key",
> "finality": "final",
> "account_id": "account.rpc-examples.testnet",
> "public_key": "ed25519:DCkbTMS8s4kqV4nGvz5kRBdNbY9YwjjvNGNXKpAg2eFa"
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> 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:DCkbTMS8s4kqV4nGvz5kRBdNbY9YwjjvNGNXKpAg2eFa',
> });
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=query \
> params:='{"request_type":"view_access_key","finality":"final","account_id":"account.rpc-examples.testnet","public_key":"ed25519:DCkbTMS8s4kqV4nGvz5kRBdNbY9YwjjvNGNXKpAg2eFa"}'
> ```
> [accordion] Example response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "nonce": 187310139000001,
> "permission": "FullAccess",
> "block_hash": "56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW",
> "block_height": 187440904
> },
> "id": "dontcare"
> }
> ```
>
> For a function-call key, `permission` is an object instead of the `"FullAccess"` string:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> "permission": {
> "FunctionCall": {
> "allowance": "250000000000000000000000",
> "receiver_id": "contract.rpc-examples.testnet",
> "method_names": ["get_greeting"]
> }
> }
> ```
>
> For a [gas key](/protocol/accounts-contracts/gas-keys), `permission` also carries the key's prepaid `balance` and number of nonce lanes (`num_nonces`). A full-access gas key uses `GasKeyFullAccess`:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> "permission": {
> "GasKeyFullAccess": {
> "balance": "5000000000000000000000000",
> "num_nonces": 8
> }
> }
> ```
>
> A function-call gas key uses `GasKeyFunctionCall`, which is a flat object carrying the same function-call restrictions (`allowance`, `receiver_id`, `method_names`) as `FunctionCall`, alongside the gas-key `balance` and `num_nonces`:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> "permission": {
> "GasKeyFunctionCall": {
> "balance": "5000000000000000000000000",
> "num_nonces": 8,
> "allowance": "250000000000000000000000",
> "receiver_id": "contract.rpc-examples.testnet",
> "method_names": ["get_greeting"]
> }
> }
> ```
>
> The nonces of the individual lanes are not included — query them with [`view_gas_key_nonces`](#view-gas-key-nonces).
> [!NOTE]
>
> For a post-quantum [`ml-dsa-65`](/protocol/accounts-contracts/access-keys#signature-schemes) key, pass the **full** `ml-dsa-65:` public key in `public_key`. The network hashes it to locate the on-chain entry, so you query it exactly like an `ed25519` or `secp256k1` key.
***
## View Access Key List
Returns the [access keys](/protocol/accounts-contracts/access-keys) of an account, each with its nonce and permissions.
* **method**: `query`
* **params**: `request_type: view_access_key_list`, `finality` OR `block_id`, `account_id`, optional `limit`, optional `after_key`
> [!NOTE]
>
> From nearcore 2.14.0, a request without `limit` or `after_key` fails with `TOO_MANY_ACCESS_KEYS` if the account has more than 100 keys (the default limit). Use pagination for such accounts. See [Paginate the key list](#paginate-the-key-list).
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "view_access_key_list",
> "finality": "final",
> "account_id": "account.rpc-examples.testnet"
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> 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',
> });
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=query \
> params:='{"request_type":"view_access_key_list","finality":"final","account_id":"account.rpc-examples.testnet"}'
> ```
> [accordion] Example response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "keys": [
> {
> "public_key": "ed25519:DCkbTMS8s4kqV4nGvz5kRBdNbY9YwjjvNGNXKpAg2eFa",
> "access_key": {
> "nonce": 187310139000001,
> "permission": "FullAccess"
> }
> },
> {
> "public_key": "ml-dsa-65-hash:7Xx2X4vHb9dG8pJ5tZqD3mN6kRfWcA1sLuYoP2eB4hT",
> "access_key": {
> "nonce": 187420021000003,
> "permission": "FullAccess"
> }
> }
> ],
> "block_hash": "56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW",
> "block_height": 187440904
> },
> "id": "dontcare"
> }
> ```
> [!NOTE]
>
> Post-quantum [`ml-dsa-65`](/protocol/accounts-contracts/access-keys#signature-schemes) keys are stored on-chain by hash, so they appear here with an `ml-dsa-65-hash:` prefix (a base58-encoded 32-byte SHA3-256 digest) rather than the full `ml-dsa-65:` key. To match an entry to one of your own keys, derive its handle — the SHA3-256 of the domain-separation tag `near:ml-dsa-65-pubkey-hash:v1` followed by the raw public key — and compare it against the returned value (hashing the key without that prefix will not match).
### Paginate the key list
> [accordion] Pagination example
>
> Request the first page with `limit`:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "view_access_key_list",
> "finality": "final",
> "account_id": "account.rpc-examples.testnet",
> "limit": 1
> }
> }
> ```
>
> The response has `last_key` when more keys remain:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "keys": [
> {
> "public_key": "ed25519:DCkbTMS8s4kqV4nGvz5kRBdNbY9YwjjvNGNXKpAg2eFa",
> "access_key": {
> "nonce": 187310139000001,
> "permission": "FullAccess"
> }
> }
> ],
> "last_key": "ed25519:DCkbTMS8s4kqV4nGvz5kRBdNbY9YwjjvNGNXKpAg2eFa",
> "block_hash": "56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW",
> "block_height": 187440904
> },
> "id": "dontcare"
> }
> ```
>
> Request the next page with `after_key` set to that `last_key`. To read every page from the same state, also replace `finality` with `block_id` set to the `block_hash` of the first response:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "view_access_key_list",
> "block_id": "56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW",
> "account_id": "account.rpc-examples.testnet",
> "after_key": "ed25519:DCkbTMS8s4kqV4nGvz5kRBdNbY9YwjjvNGNXKpAg2eFa",
> "limit": 1
> }
> }
> ```
>
> A response without `last_key` is the last page.
| Rule | Details |
| - | - |
| Keys per response | At most `view_access_keys_limit`, which is 100 by default. Node operators can change it. A larger `limit` is lowered to this value. |
| Request without `limit` or `after_key` | Fails with `TOO_MANY_ACCESS_KEYS` if the account has more keys than `view_access_keys_limit`. |
| Version | From nearcore 2.14.0. Nodes on nearcore 2.13 return all keys in one response and ignore `limit` and `after_key`. |
***
## View Gas Key Nonces
Returns the current nonce of every parallel nonce lane of a [gas key](/protocol/accounts-contracts/gas-keys), given the account and the key's public key. The array is indexed by `nonce_index`: the first element is lane `0`, the second is lane `1`, and so on. Use [`view_access_key`](#view-access-key) to see the gas key's balance and permission.
* **method**: `query`
* **params**: `request_type: view_gas_key_nonces`, `finality` OR `block_id`, `account_id`, `public_key`
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "view_gas_key_nonces",
> "finality": "final",
> "account_id": "account.rpc-examples.testnet",
> "public_key": "ed25519:DCkbTMS8s4kqV4nGvz5kRBdNbY9YwjjvNGNXKpAg2eFa"
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { JsonRpcProvider } from "near-api-js";
>
> const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com" });
>
> const response = await provider.query({
> request_type: 'view_gas_key_nonces',
> finality: 'final',
> account_id: 'account.rpc-examples.testnet',
> public_key: 'ed25519:DCkbTMS8s4kqV4nGvz5kRBdNbY9YwjjvNGNXKpAg2eFa',
> });
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=query \
> params:='{"request_type":"view_gas_key_nonces","finality":"final","account_id":"account.rpc-examples.testnet","public_key":"ed25519:DCkbTMS8s4kqV4nGvz5kRBdNbY9YwjjvNGNXKpAg2eFa"}'
> ```
> [accordion] Example response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "nonces": [
> 187438921000012,
> 187438921000003,
> 187438921000000,
> 187438921000000
> ],
> "block_hash": "56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW",
> "block_height": 187440904
> },
> "id": "dontcare"
> }
> ```
>
> Each lane starts at `block_height * 10^6` from when the key was added and advances independently as transactions use it.
> [!NOTE]
>
> Querying a key that exists but is not a gas key (or does not exist at all) returns an `UnknownGasKey` error.
***
## View Contract Code
Returns the contract code (Wasm binary) deployed to the account. The returned code is encoded in base64.
* **method**: `query`
* **params**: `request_type: view_code`, `finality` OR `block_id`, `account_id`
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "view_code",
> "finality": "final",
> "account_id": "contract.rpc-examples.testnet"
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> 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',
> });
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=query \
> params:='{"request_type":"view_code","finality":"final","account_id":"contract.rpc-examples.testnet"}'
> ```
***
## View Global Contract Code by Hash
Returns the global contract's Wasm binary for an immutable global contract identified by its code hash. The returned code is base64-encoded.
* **method**: `query`
* **params**: `request_type: view_global_contract_code`, `finality` OR `block_id`, `code_hash`
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "view_global_contract_code",
> "finality": "final",
> "code_hash": "DxfRbrjT3QPmoANMDYTR6iXPGJr7xRUyDnQhcAWjcoFF"
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { JsonRpcProvider } from "near-api-js";
>
> const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com" });
>
> const response = await provider.query({
> request_type: 'view_global_contract_code',
> finality: 'final',
> code_hash: 'DxfRbrjT3QPmoANMDYTR6iXPGJr7xRUyDnQhcAWjcoFF',
> });
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=query \
> params:='{"request_type":"view_global_contract_code","finality":"final","code_hash":"DxfRbrjT3QPmoANMDYTR6iXPGJr7xRUyDnQhcAWjcoFF"}'
> ```
***
## View Global Contract Code by Account
Returns the global contract's Wasm binary for the global contract published under an account ID. The returned code is base64-encoded.
* **method**: `query`
* **params**: `request_type: view_global_contract_code_by_account_id`, `finality` OR `block_id`, `account_id`
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "view_global_contract_code_by_account_id",
> "finality": "final",
> "account_id": "nft-contract.testnet"
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { JsonRpcProvider } from "near-api-js";
>
> const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com" });
>
> const response = await provider.query({
> request_type: 'view_global_contract_code_by_account_id',
> finality: 'final',
> account_id: 'nft-contract.testnet',
> });
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=query \
> params:='{"request_type":"view_global_contract_code_by_account_id","finality":"final","account_id":"nft-contract.testnet"}'
> ```
***
## View Contract State
Returns the state (key-value pairs) of a contract based on a key prefix (base64 encoded). Pass an empty string for `prefix_base64` to return the entire state.
* **method**: `query`
* **params**: `request_type: view_state`, `finality` OR `block_id`, `account_id`, `prefix_base64`, optional `limit`, optional `after_key_base64`, optional `include_proof`
> [!WARNING]
>
> By default, a node rejects a `view_state` request with `TOO_LARGE_CONTRACT_STATE` if the account's state is above 50,000 bytes. A narrower `prefix_base64` does not avoid the error. To read a large state, use pagination. See [Paginate the state](#paginate-the-state).
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "view_state",
> "finality": "final",
> "account_id": "contract.rpc-examples.testnet",
> "prefix_base64": ""
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> 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',
> prefix_base64: '',
> });
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=query \
> params:='{"request_type":"view_state","finality":"final","account_id":"contract.rpc-examples.testnet","prefix_base64":""}'
> ```
### Paginate the state
> [accordion] Pagination example
>
> Request the first page with `limit`:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "view_state",
> "finality": "final",
> "account_id": "contract.rpc-examples.testnet",
> "prefix_base64": "",
> "limit": 2
> }
> }
> ```
>
> The response has `last_key` when more entries remain. Keys and values are base64:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "values": [
> { "key": "YQ==", "value": "MQ==" },
> { "key": "Yg==", "value": "Mg==" }
> ],
> "last_key": "Yg==",
> "block_hash": "56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW",
> "block_height": 187440904
> },
> "id": "dontcare"
> }
> ```
>
> Request the next page with `after_key_base64` set to that `last_key`. To read every page from the same state, also replace `finality` with `block_id` set to the `block_hash` of the first response:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "view_state",
> "block_id": "56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW",
> "account_id": "contract.rpc-examples.testnet",
> "prefix_base64": "",
> "after_key_base64": "Yg==",
> "limit": 2
> }
> }
> ```
>
> A response without `last_key` is the last page.
A request without `limit` or `after_key_base64` is checked against the size of the whole account. This size is the account's storage usage without the contract code, so a narrower `prefix_base64` does not avoid the error. Paginated requests skip this check.
| Rule | Details |
| - | - |
| Request without `limit` or `after_key_base64` | Fails with `TOO_LARGE_CONTRACT_STATE` if the account's state is above `trie_viewer_state_size_limit`. The default is 50,000 bytes, and the node operator can change it. |
| Items per page | At most 10,000. A larger `limit` is lowered to 10,000. |
| Bytes per page | The node stops adding items once the keys and values of the page reach 50,000 bytes. The last item can make a page larger than that. |
| `after_key_base64` | After decoding, the key must start with the decoded `prefix_base64`. The base64 strings themselves do not have to match. Otherwise the node returns `INTERNAL_ERROR`. |
| `include_proof` | Cannot be combined with `limit` or `after_key_base64`. If it is, the node returns `INTERNAL_ERROR`. |
| Version | `limit` and `after_key_base64` are available from nearcore 2.13.0. |
***
## View Contract State Changes
Returns state change details of a contract based on a key prefix (base64 encoded).
* **method**: `changes`
* **params**: `changes_type: data_changes`, `account_ids`, `key_prefix_base64`, `finality` OR `block_id`
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "changes",
> "params": {
> "changes_type": "data_changes",
> "account_ids": ["contract.rpc-examples.testnet"],
> "key_prefix_base64": "",
> "block_id": 187310139
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> 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 },
> ''
> );
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://archival-rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=changes \
> params:='{"changes_type":"data_changes","account_ids":["contract.rpc-examples.testnet"],"key_prefix_base64":"","block_id":187310139}'
> ```
***
## View Contract Code Changes
Returns code changes made when deploying a contract. Change is returned as a base64 encoded WASM file.
* **method**: `changes`
* **params**: `changes_type: contract_code_changes`, `account_ids`, `finality` OR `block_id`
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "changes",
> "params": {
> "changes_type": "contract_code_changes",
> "account_ids": ["contract.rpc-examples.testnet"],
> "block_id": 187309439
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> 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 }
> );
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://archival-rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=changes \
> params:='{"changes_type":"contract_code_changes","account_ids":["contract.rpc-examples.testnet"],"block_id":187309439}'
> ```
***
## Call a Contract Function
Allows you to call a contract method as a view function (read-only).
* **method**: `query`
* **params**: `request_type: call_function`, `finality` OR `block_id`, `account_id`, `method_name`, `args_base64`
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "call_function",
> "finality": "final",
> "account_id": "contract.rpc-examples.testnet",
> "method_name": "get_greeting",
> "args_base64": ""
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> 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',
> method_name: 'get_greeting',
> args_base64: '',
> });
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=query \
> params:='{"request_type":"call_function","finality":"final","account_id":"contract.rpc-examples.testnet","method_name":"get_greeting","args_base64":""}'
> ```
### Decode the result
A `call_function` query returns the contract's serialized return value as an array of bytes. Decode those bytes as UTF-8 and parse as JSON.
For example, `[34, 104, 101, 108, 108, 111, 34]` decodes to the JSON string `"hello"`.
```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Decoding a call_function result
JSON.parse(Buffer.from(response.result.result).toString("utf8"));
```
#### Transaction return values
Transaction and receipt outcomes encode successful return values in the base64 string `status.SuccessValue`. Decode that string, then parse it if the method returns JSON. An empty `SuccessValue` indicates no return value. Inspect `Failure` as an execution error.
With a full transaction RPC response saved as `response.json`:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
node -e '
const response = JSON.parse(require("node:fs").readFileSync("response.json", "utf8"));
const status = response.result.status;
if ("SuccessValue" in status) {
console.log(status.SuccessValue === "" ? undefined :
JSON.parse(Buffer.from(status.SuccessValue, "base64").toString("utf8")));
} else {
console.log(status);
}
'
```
***
## Error Handling
Query errors come back in four ways. Check for an `error` object first, and then for `result.error`.
### Request errors
If the node cannot parse the request parameters, it returns an error with `error.name` set to `REQUEST_VALIDATION_ERROR` and `error.cause.name` set to `PARSE_ERROR`. This happens, for example, when `args_base64` is not valid base64.
### Internal errors
If the node fails internally, it returns an error with `error.name` set to `INTERNAL_ERROR`. The message is in `error.cause.info.error_message`. `view_state` also answers this way when `include_proof` is combined with pagination, or when `after_key_base64` is outside the prefix.
### Handler errors
For the errors below, the response has `error.name` set to `HANDLER_ERROR` and `error.cause.name` set to the listed value. For example:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"jsonrpc": "2.0",
"error": {
"name": "HANDLER_ERROR",
"cause": {
"name": "TOO_LARGE_CONTRACT_STATE",
"info": {
"contract_account_id": "contract.rpc-examples.testnet",
"block_height": 187440904,
"block_hash": "56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW"
}
},
"code": -32000,
"message": "Server error",
"data": "State of contract contract.rpc-examples.testnet is too large to be viewed"
},
"id": "dontcare"
}
```
| `error.cause.name` | Description | Solution |
| - | - | - |
| `UNKNOWN_ACCOUNT` | Account does not exist | Check account ID spelling |
| `INVALID_ACCOUNT` | Invalid account format | Use valid account ID (e.g., `account.near`) |
| `UNKNOWN_BLOCK` | Block not found | Use a valid block hash or height |
| `UNKNOWN_GAS_KEY` | Key is not a gas key or does not exist | Check the public key and that it was added as a gas key |
| `GARBAGE_COLLECTED_BLOCK` | Block too old | Use archival node or more recent block |
| `NO_CONTRACT_CODE` | No contract deployed (returned by `view_code`) | Verify the account has a deployed contract |
| `NO_GLOBAL_CONTRACT_CODE` | No global contract for this code hash or account | Check the code hash or the publishing account ID |
| `TOO_LARGE_CONTRACT_STATE` | Account state is above the node's `view_state` limit | Paginate with `limit` and `after_key_base64` |
| `TOO_MANY_ACCESS_KEYS` | Account has more keys than one response can hold | Paginate with `limit` and `after_key` |
### Errors in the result
A view function call that fails while the contract runs does not return an `error` object. The node answers with HTTP status 200, and `result.error` holds a text message:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"jsonrpc": "2.0",
"result": {
"block_hash": "56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW",
"block_height": 187440904,
"error": "wasm execution failed with error: MethodResolveError(MethodNotFound)",
"logs": []
},
"id": "dontcare"
}
```
Check `result.error` before you decode `result.result`. `view_access_key` for a key that does not exist answers the same way.
Common messages:
* The method does not exist: `wasm execution failed with error: MethodResolveError(MethodNotFound)`.
* The account has no contract: the message starts with `wasm execution failed with error: CompilationError(CodeDoesNotExist`.
# Gas
Source: https://docs.near.org/api/rpc/gas
Query gas prices for specific blocks or hashes using the NEAR RPC API.
The RPC API enables you to query the gas price for a specific block or hash.
## Quick Reference
| Parameter | Type | Description |
| - | - | - |
| `block_height` | `number` | Specific block height to query gas price for |
| `block_hash` | `string` | Specific block hash to query gas price for |
| `null` | `null` | Returns gas price for the latest block |
***
## Gas Price
Returns gas price for a specific `block_height` or `block_hash`. Using `[null]` will return the most recent block's gas price.
* **method**: `gas_price`
* **params**: `[block_height]`, `["block_hash"]`, or `[null]`
> [tab] null (latest)
>
> > [tab] JSON
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "jsonrpc": "2.0",
> > "id": "dontcare",
> > "method": "gas_price",
> > "params": [null]
> > }
> > ```
>
> > [tab] JavaScript
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > import { JsonRpcProvider } from "near-api-js";
> >
> > const provider = new JsonRpcProvider({
> > url: "https://test.rpc.fastnear.com",
> > });
> >
> > const response = await provider.gasPrice(null);
> > ```
>
> > [tab] HTTPie
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > http POST https://rpc.testnet.near.org \
> > jsonrpc=2.0 \
> > id=dontcare \
> > method=gas_price \
> > params:='[null]'
> > ```
> [tab] by block height
>
> > [tab] JSON
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "jsonrpc": "2.0",
> > "id": "dontcare",
> > "method": "gas_price",
> > "params": [187310138]
> > }
> > ```
>
> > [tab] JavaScript
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > import { JsonRpcProvider } from "near-api-js";
> >
> > const provider = new JsonRpcProvider({
> > url: "https://archival-rpc.testnet.near.org",
> > });
> >
> > const response = await provider.gasPrice(187310138);
> > ```
>
> > [tab] HTTPie
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > http POST https://archival-rpc.testnet.near.org \
> > jsonrpc=2.0 \
> > id=dontcare \
> > method=gas_price \
> > params:='[187310138]'
> > ```
> [tab] by block hash
>
> > [tab] JSON
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "jsonrpc": "2.0",
> > "id": "dontcare",
> > "method": "gas_price",
> > "params": ["6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w"]
> > }
> > ```
>
> > [tab] JavaScript
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > import { JsonRpcProvider } from "near-api-js";
> >
> > const provider = new JsonRpcProvider({
> > url: "https://archival-rpc.testnet.near.org",
> > });
> >
> > const response = await provider.gasPrice(
> > '6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w',
> > );
> > ```
>
> > [tab] HTTPie
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > http POST https://archival-rpc.testnet.near.org \
> > jsonrpc=2.0 \
> > id=dontcare \
> > method=gas_price \
> > params:='["6RWmTYhXCzjMjoY3Mz1rfFcnBm8E6XeDDbFEPUA4sv1w"]'
> > ```
> [accordion] Example response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "result": {
> "gas_price": "100000000"
> }
> }
> ```
# Protocol Call Reference
Source: https://docs.near.org/api/rpc/introduction
Overview of tools and methods for interacting with the NEAR Protocol.
NEAR Protocol provides multiple ways to interact with the network — from low-level JSON-RPC calls to visual explorers and wallets.
## Tools
> [card] [NEAR Explorer](https://nearblocks.io)
>
> Browse transactions, accounts, blocks, and contracts on mainnet and testnet.
> [card] [NEAR Wallet](https://wallet.near.org)
>
> Create and manage NEAR accounts, send tokens, and interact with dApps.
## RPC API
NEAR exposes a JSON-RPC 2.0 API for programmatic access to the network. Send requests with `POST` to the root of a provider endpoint and put the method name in the JSON request body.
> [!NOTE]
>
> The endpoint reference in the RPC sidebar is generated from `openapi.json` and is the source of truth for request and response schemas. The hand-written RPC pages provide guidance, context, and worked examples.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://rpc.mainnet.near.org/ \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":"status","method":"status","params":[]}'
```
See [RPC Providers](/api/rpc/providers) for the full list of public endpoints. Send one JSON-RPC request object per HTTP request. nearcore does not support JSON-RPC batch requests.
## Available Methods
| Category | Methods |
| - | - |
| [**Transactions**](/api/rpc/transactions) | `send_tx`, `tx`, `tx_status` (or `EXPERIMENTAL_tx_status` before nearcore 2.14.0), `EXPERIMENTAL_receipt`, `EXPERIMENTAL_receipt_to_tx`, `broadcast_tx_async`, `broadcast_tx_commit` |
| [**Query**](/api/rpc/contracts) | `query` — see [Accounts / Contracts](/api/rpc/contracts) for every supported `request_type` |
| **Accounts & access keys** | `EXPERIMENTAL_view_account`, `changes`, `EXPERIMENTAL_changes`, `EXPERIMENTAL_view_access_key`, `EXPERIMENTAL_view_access_key_list` |
| **Smart contracts** | `EXPERIMENTAL_view_code`, `EXPERIMENTAL_view_state`, `EXPERIMENTAL_call_function` |
| [**Blocks & chunks**](/api/rpc/block-chunk) | `block`, `chunk`, `block_effects`, `EXPERIMENTAL_changes_in_block` |
| **Network** | `status`, `health`, `network_info`, `validators`, `client_config`, `EXPERIMENTAL_validators_ordered` |
| [**Gas & configuration**](/api/rpc/gas) | `gas_price`, `genesis_config`, `EXPERIMENTAL_genesis_config`, `EXPERIMENTAL_protocol_config`, `EXPERIMENTAL_congestion_level` |
| **Light client** | `light_client_proof`, `next_light_client_block`, `EXPERIMENTAL_light_client_proof`, `EXPERIMENTAL_light_client_block_proof` |
| **Maintenance & storage** | `maintenance_windows`, `EXPERIMENTAL_maintenance_windows`, `EXPERIMENTAL_split_storage_info` |
Explore the full interactive reference in the sidebar, or start with [RPC Providers](/api/rpc/providers) to configure your endpoint.
# Protocol
Source: https://docs.near.org/api/rpc/protocol
Learn how to retrieve the genesis and current protocol configurations using the NEAR RPC API.
The RPC API enables you to retrieve the current genesis and protocol configuration.
## Quick Reference
| Method | Parameters | Description |
| - | - | - |
| [`genesis_config`](#genesis-config) | *none* | Returns current genesis configuration |
| [`EXPERIMENTAL_protocol_config`](#protocol-config) | `finality` OR `block_id` | Returns protocol configuration for latest or specific block |
***
## Genesis Config
Returns current genesis configuration.
* **method**: `genesis_config`
* **params**: *none*
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "genesis_config"
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> 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',
> });
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://rpc.testnet.near.org \
> jsonrpc=2.0 \
> id=dontcare \
> method=genesis_config
> ```
> [accordion] Example response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "chain_id": "testnet",
> "epoch_length": 43200,
> "gas_limit": 1000000000000000,
> "genesis_height": 42376888,
> "genesis_time": "2020-07-31T03:39:42.911378Z",
> "min_gas_price": "5000",
> "num_block_producer_seats": 200,
> "protocol_version": 29,
> "total_supply": "2089646653180081825096998107194444"
> },
> "id": "dontcare"
> }
> ```
***
## Protocol Config
Returns most recent protocol configuration or a specific queried block. Useful for finding current storage and transaction costs.
* **method**: `EXPERIMENTAL_protocol_config`
* **params**: `finality` OR `block_id`
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "EXPERIMENTAL_protocol_config",
> "params": {
> "finality": "final"
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { JsonRpcProvider } from "near-api-js";
>
> const provider = new JsonRpcProvider({
> url: "https://test.rpc.fastnear.com",
> });
>
> const response = await provider.experimental_protocolConfig({
> finality: "final"
> });
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://rpc.testnet.near.org \
> jsonrpc=2.0 \
> id=dontcare \
> method=EXPERIMENTAL_protocol_config \
> params:='{"finality": "final"}'
> ```
> [accordion] Example response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "chain_id": "testnet",
> "epoch_length": 43200,
> "gas_limit": 1000000000000000,
> "protocol_version": 73,
> "runtime_config": {
> "storage_amount_per_byte": "10000000000000000000",
> "transaction_costs": {
> "action_receipt_creation_config": {
> "execution": 108059500000,
> "send_not_sir": 108059500000,
> "send_sir": 108059500000
> }
> }
> }
> },
> "id": "dontcare"
> }
> ```
***
## Best Practices
* Use `finality: "final"` for most recent confirmed protocol configuration
* Use specific `block_id` when you need protocol config for a particular block
* Cache protocol configuration results as they change infrequently
* Use the protocol config to calculate current storage and transaction costs
# RPC Providers
Source: https://docs.near.org/api/rpc/providers
List of public RPC endpoints for the NEAR Protocol.
NEAR Protocol exposes a JSON-RPC API for interacting with the network. You can use any of the providers below or run your own node.
## RPC Providers
FastNear maintains a [comprehensive dashboard](https://grafana.fastnear.com/public-dashboards/577b37c6cfe84b2bae23af471d27cade) with response times for most of the available endpoints.
### Mainnet
| Provider | Endpoint | Public Endpoint | Archival Node | Free Tier | Free Tier Limit | Paid Plan |
| - | - | :-: | :-: | :-: | :-: | :-: |
| [FASTNEAR](https://fastnear.com) | `https://free.rpc.fastnear.com` | ✅ | Paid Only | ✅ | Not published | ✅ |
| [NEAR](https://near.org) | `https://archival-rpc.mainnet.near.org` | ✅ | ✅ | Severely rate limited | Not published | ❌ |
| [All That Node](https://www.allthatnode.com/protocol/near.dsrv) | N/A | ❌ | ✅ | ✅ | [500K CU/day](https://www.allthatnode.com/pricing.dsrv) | ✅ |
| [Ankr](https://www.ankr.com/rpc/near/) | `https://rpc.ankr.com/near` | ❌ | ❌ | ✅ | [\~30 req/s](https://www.ankr.com/docs/rpc-service/service-plans/) | ✅ |
| [BlockPI Network](https://blockpi.io/chain/near) | `https://near.blockpi.network/v1/rpc/{api-key}` | ❌ | ❌ | ✅ | [20 req/s](https://docs.blockpi.io/pricing/pricing-and-rate-limit) | ✅ |
| [dRPC](https://drpc.org/chainlist/near-mainnet-rpc) | `https://near.drpc.org` | ✅ | ❌ | ✅ | [\~2,100 CU/s](https://drpc.org/docs/howitworks/ratelimiting) | ✅ |
| [GetBlock](https://getblock.io/nodes/near/) | `https://go.getblock.io/{api-key}` | ❌ | ❌ | ✅ | [50K CU/day](https://docs.getblock.io/getting-started/plans-and-limits/choosing-your-plan) | ✅ |
| [Intear RPC](https://intea.rs/) | `https://rpc.intea.rs` | ✅ | ❌ | ✅ | Not published | ❌ |
| [Lavender.Five Nodes](https://www.lavenderfive.com/tools/near/overview) | N/A | ❌ | ❌ | ✅ | Not published | ✅ |
| [node101](https://node101.io/en/rpc/near) | N/A | ❌ | Paid Only | ❌ | — | ✅ |
| [NodeReal](https://nodereal.io/api-marketplace/near-rpc) | `https://near-mainnet.nodereal.io/v1/{api-key}` | ❌ | ❌ | ✅ | [100M CU/month](https://nodereal.io/api-marketplace/near-rpc) | ✅ |
| [NOWNodes](https://nownodes.io/near) | `https://near.nownodes.io/{api-key}` | ❌ | ❌ | ✅ | [100K req/month](https://nownodes.io/near) | ✅ |
| [QuickNode](https://www.quicknode.com/chains/near) | N/A | ❌ | ✅ | ✅ | [15 req/s](https://www.quicknode.com/pricing) | ✅ |
| [Shitzu](https://shitzuapes.xyz/) | `https://rpc.shitzuapes.xyz` | ✅ | ❌ | ✅ | Not published | ❌ |
| [Tatum](https://tatum.io/chain/near/) | N/A | ❌ | ❌ | ✅ | [3 req/s](https://docs.tatum.io/docs/plans-limits) | ✅ |
| [ZAN](https://zan.top/service/apikeys) | `https://api.zan.top/near-mainnet` | ✅ | ❌ | ✅ | [\~20 req/s](https://docs.zan.top/docs/resource-pricing) | ✅ |
| [Zeeve](https://www.zeeve.io/blockchain-protocols/deploy-near-node/) | N/A | ❌ | ✅ | ❌ | — | ✅ |
### Testnet
| Provider | Endpoint | Public Endpoint | Archival Node | Free Tier | Free Tier Limit | Paid Plan |
| - | - | :-: | :-: | :-: | :-: | :-: |
| [FASTNEAR](https://fastnear.com) | `https://test.rpc.fastnear.com` | ✅ | Paid Only | ✅ | Not published | ✅ |
| [NEAR](https://near.org) | `https://archival-rpc.testnet.near.org` | ✅ | ✅ | Severely rate limited | Not published | ❌ |
| [All That Node](https://www.allthatnode.com/protocol/near.dsrv) | N/A | ❌ | ✅ | ✅ | [500K CU/day](https://www.allthatnode.com/pricing.dsrv) | ✅ |
| [dRPC](https://drpc.org/chainlist/near-testnet-rpc) | `https://near-testnet.drpc.org` | ✅ | ❌ | ✅ | [\~2,100 CU/s](https://drpc.org/docs/howitworks/ratelimiting) | ✅ |
| [Intear RPC](https://intea.rs/) | `https://testnet-rpc.intea.rs` | ✅ | ❌ | ✅ | Not published | ❌ |
| [node101](https://node101.io/en/rpc/near) | N/A | ❌ | Paid Only | ❌ | — | ✅ |
| [QuickNode](https://www.quicknode.com/chains/near) | N/A | ❌ | ✅ | ✅ | [15 req/s](https://www.quicknode.com/pricing) | ✅ |
| [Tatum](https://tatum.io/chain/near/) | N/A | ❌ | ❌ | ✅ | [3 req/s](https://docs.tatum.io/docs/plans-limits) | ✅ |
| [ZAN](https://zan.top/service/apikeys) | `https://api.zan.top/near-testnet` | ✅ | ❌ | ✅ | [\~20 req/s](https://docs.zan.top/docs/resource-pricing) | ✅ |
| [Zeeve](https://www.zeeve.io/blockchain-protocols/deploy-near-node/) | N/A | ❌ | ❌ | ❌ | — | ✅ |
> [!NOTE]
>
> **Free Tier Limit** values link to each provider's own pricing/docs page as the source. Limits are reported in the units each provider publishes (`req` = requests, `CU` = compute units), so they are not directly comparable across providers and may change at any time — always confirm on the linked page. "Not published" means the endpoint is free but has no documented numeric limit.
For live latency benchmarks across these providers, see [OpenChainBench](https://openchainbench.com/benchmarks/near-rpc) — p50/p90/p99 measured every 60 seconds from US-East, EU-West and Singapore.
## Making requests
Send JSON-RPC 2.0 requests with `POST` to the root of the provider endpoint. Put the method and parameters in the JSON request body.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://rpc.mainnet.near.org/ \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":"status","method":"status","params":[]}'
```
Send one request object per HTTP request. nearcore does not support JSON-RPC batch requests. If the body is a JSON array, a nearcore node rejects the whole request with HTTP `400` and error code `-32700` (`Parse error`), and none of the requests in the array run.
> [!WARNING]
>
> Never load test a shared public endpoint. Run performance tests only against a node you operate or an endpoint whose operator has explicitly authorized the test.
## Run your own node
To run a local RPC node, follow the [NEAR node documentation](https://near-nodes.io/rpc/hardware-rpc).
> [!NOTE]
>
> Testnet tokens have no real value and can be obtained from the [NEAR Faucet](/getting-started/faucet).
# Transactions
Source: https://docs.near.org/api/rpc/transactions
Send transactions and query their status using the NEAR RPC API.
The RPC API exposes several methods for broadcasting signed transactions and tracking their execution. All transaction methods accept a base64-encoded `signed_tx_base64` payload. Status methods accept either the same payload or a `tx_hash` + `sender_account_id` pair.
## Quick Reference
| Method | Purpose |
| - | - |
| [`send_tx`](#send-transaction) | Broadcast a signed transaction and wait for the result |
| [`tx`](#transaction-status) | Get the status of a previously broadcast transaction |
| [`tx_status`](#transaction-status-with-receipts) | Like `tx`, but also returns receipt details (nearcore 2.14.0 or later) |
| [`EXPERIMENTAL_receipt`](#receipt-by-id) | Fetch a single receipt by id |
| [`broadcast_tx_async`](#broadcast-async) | Broadcast and return immediately with the transaction hash |
| [`broadcast_tx_commit`](#broadcast-commit) | Broadcast and wait until the transaction is included in a block |
> [!NOTE]
>
> Prefer `send_tx` and `tx` for new integrations, and `tx_status` on nodes that run nearcore 2.14.0 or later. On older nodes, use `EXPERIMENTAL_tx_status`, which also works on 2.14.0 and later. The `broadcast_tx_async` and `broadcast_tx_commit` methods are kept for backward compatibility but offer less control over when the call returns.
***
## The `wait_until` Field
`send_tx`, `tx`, and `tx_status` accept an optional `wait_until` field that controls **how long the RPC waits before returning a response**. Each value waits for a stricter execution milestone than the previous one — pick the lowest level that satisfies your use case so you don't pay extra latency.
| Value | Returns when… | Typical use |
| - | - | - |
| `NONE` | Right away. `send_tx` returns before the node validates or includes the transaction, and its response is `{"final_execution_status": "NONE"}` with no transaction hash. `tx` and `tx_status` return the current status without waiting. | Fire-and-forget broadcasts. Compute the transaction hash on the client, or use `broadcast_tx_async` if you need the RPC to return it. |
| `INCLUDED` | The transaction is included in a block (the block may not be finalized). | UI optimism: you want to confirm the tx hit the chain. |
| `EXECUTED_OPTIMISTIC` *(default)* | Included + all non-refund receipts have executed (blocks may still not be finalized). | Default for most apps — you can read the result. |
| `INCLUDED_FINAL` | Included in a *finalized* block. | You need finality but don't care about receipts. |
| `EXECUTED` | Finalized + all non-refund receipts executed. | Strong correctness without waiting for refund receipts. |
| `FINAL` | Finalized + all receipts (including refunds) finalized. | Accounting and cross-chain settlement, where refund-tracking matters. |
If the field is omitted, the RPC behaves as if `EXECUTED_OPTIMISTIC` was passed.
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"jsonrpc": "2.0",
"id": "dontcare",
"method": "send_tx",
"params": {
"signed_tx_base64": "DwAAAHNlbmRlci50ZXN0bmV0...",
"wait_until": "FINAL"
}
}
```
> [!WARNING]
>
> Higher `wait_until` levels can take several seconds. If your client has a short timeout, prefer `INCLUDED` or `EXECUTED_OPTIMISTIC` and poll `tx` for the stricter level.
***
## Send Transaction
Broadcasts a signed transaction and waits for the requested execution milestone before returning.
* **method**: `send_tx`
* **params**: `signed_tx_base64`, optional `wait_until`
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "send_tx",
> "params": {
> "signed_tx_base64": "DwAAAHNlbmRlci50ZXN0bmV0...",
> "wait_until": "EXECUTED_OPTIMISTIC"
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { JsonRpcProvider } from "near-api-js";
>
> const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com" });
>
> const response = await provider.sendTransactionUntil(
> signedTransaction,
> 'EXECUTED_OPTIMISTIC',
> );
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=send_tx \
> params:='{"signed_tx_base64":"DwAAAHNlbmRlci50ZXN0bmV0...","wait_until":"EXECUTED_OPTIMISTIC"}'
> ```
Successful contract return values appear as base64-encoded `status.SuccessValue`. See the [decoded result](/api/rpc/contracts#transaction-return-values) reference to read them.
***
## Transaction Status
Returns the status of a previously submitted transaction.
* **method**: `tx`
* **params**: either `signed_tx_base64`, or `tx_hash` + `sender_account_id`. Optional `wait_until`.
> [tab] JSON (by hash)
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "tx",
> "params": {
> "tx_hash": "6zgh2u9DqHHiXzdy9ouTP7oGky2T4nugbhqsK7wQHnZS",
> "sender_account_id": "sender.testnet",
> "wait_until": "FINAL"
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { JsonRpcProvider } from "near-api-js";
>
> const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com" });
>
> const response = await provider.txStatus(
> '6zgh2u9DqHHiXzdy9ouTP7oGky2T4nugbhqsK7wQHnZS',
> 'sender.testnet',
> 'FINAL',
> );
> ```
***
## Transaction Status with Receipts
`tx_status` returns the same payload as `tx`, plus a `receipts` list with the receipts that the transaction produced. It is useful when debugging cross-contract calls.
* **method**: `tx_status`
* **params**: same as `tx`
The `receipts` list can be incomplete:
* Receipts that have not run yet when the node answers are not in the list. With the default `wait_until` (`EXECUTED_OPTIMISTIC`), refund receipts are often still missing. `wait_until: "FINAL"` waits until all receipts, including refunds, have run.
* When the signer and the receiver are the same account, the list leaves out the first receipt. This is the receipt converted from the transaction.
* A node that does not track the signer's shard can return the result without the `receipts` list.
> [!NOTE]
>
> `tx_status` is available from nearcore 2.14.0. The 2.14.0 release candidates (versions that start with `2.14.0-rc`) also have it. Earlier versions call this method `EXPERIMENTAL_tx_status`. Nodes that run them return a "Method not found" error for `tx_status`. `EXPERIMENTAL_tx_status` still works in 2.14.0, as a deprecated alias with identical request and response types. Use `EXPERIMENTAL_tx_status` until every node you call runs one of these versions or later. To see which version a node runs, call the `status` method and read `version.version`.
***
## Receipt by Id
Fetches a single receipt by its id.
* **method**: `EXPERIMENTAL_receipt`
* **params**: `receipt_id`
***
## Broadcast Async
Broadcasts a signed transaction and returns immediately with the transaction hash. It submits the transaction the same way as `send_tx` with `wait_until: "NONE"`. The difference is the response: `broadcast_tx_async` returns the transaction hash as a string, while `send_tx` returns only `{"final_execution_status": "NONE"}`.
* **method**: `broadcast_tx_async`
* **params**: a single positional string — the base64-encoded signed transaction.
***
## Broadcast Commit
Broadcasts a signed transaction and waits for it to be included in a block. Equivalent to `send_tx` with `wait_until: "EXECUTED_OPTIMISTIC"`.
* **method**: `broadcast_tx_commit`
* **params**: a single positional string — the base64-encoded signed transaction.
***
## Error Handling
`INTERNAL_ERROR` is returned as the error `name`. The other errors are returned with `name` set to `HANDLER_ERROR` and the error code below in `cause.name`.
| Error Code | Description | Solution |
| - | - | - |
| `INVALID_TRANSACTION` | The signed transaction failed validation. | See [Invalid transactions](#invalid-transactions). |
| `TIMEOUT_ERROR` | The chosen `wait_until` level was not reached before the RPC's deadline. | See [Timeouts](#timeouts). |
| `UNKNOWN_TRANSACTION` | No record of the requested transaction hash. `tx` and `tx_status` return this only when `wait_until` is `NONE`. With other values, they wait until the deadline and return `TIMEOUT_ERROR`. | Verify the hash and `sender_account_id`. |
| `DOES_NOT_TRACK_SHARD` | The node does not track the shard needed to answer the request. | Send the request to a node that tracks that shard, such as an RPC node that tracks all shards. |
| `INTERNAL_ERROR` | The node reached its limits or failed internally. | Try again later. |
### Invalid transactions
The reason for an `INVALID_TRANSACTION` error is in `data.TxExecutionError.InvalidTxError`. For example, this is the error for a transaction whose reference block hash is too old:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"jsonrpc": "2.0",
"error": {
"name": "HANDLER_ERROR",
"cause": {
"name": "INVALID_TRANSACTION",
"info": {}
},
"code": -32000,
"message": "Server error",
"data": {
"TxExecutionError": {
"InvalidTxError": "Expired"
}
}
},
"id": "dontcare"
}
```
The reason is a string, such as `"Expired"`, or an object, such as `{"InvalidNonce": {"tx_nonce": 5, "ak_nonce": 7}}`. What to do depends on the reason:
* `Expired`: the reference block hash is too old. Refresh `block_hash` and sign again.
* `InvalidSignature`: the signature does not match the signer's key. Sign again with the matching access key.
* `ShardCongested` or `ShardStuck`: the receiver's shard is congested. The node checks congestion before the signature, key, nonce and balance, so the transaction may still be valid. Wait, and then send the same signed transaction again while its block hash is still valid.
* Any other reason: fix the reported nonce, key or balance, and sign again.
### Timeouts
A `TIMEOUT_ERROR` means that the transaction did not reach the chosen `wait_until` level before the RPC's deadline. The nearcore default deadline is 10 seconds. Node operators can change it, so some providers wait longer.
From nearcore 2.14.0, `cause.info.cause` says how far the transaction got. Older nodes send no `cause.info`.
* `NOT_OBSERVED`: the node has not seen the transaction in a block. After `send_tx`, poll `tx` with the transaction hash, and send the same signed transaction again if it does not appear. After `tx`, check the hash and `sender_account_id`.
* `PENDING`: the node has seen the transaction, but it has not reached the chosen level yet. The last known status is in `cause.info.status`. Poll `tx` again.
* `DOES_NOT_TRACK_SHARD`: the node does not track the shard of the transaction, and it got no answer from a node that does. Send the request to a node that tracks that shard.
* `ERROR`: the node could not get a usable status before the deadline. Try again later.
You can also lower `wait_until` and poll `tx`, or use an archival or dedicated provider.
# What are Chain Signatures?
Source: https://docs.near.org/chain-abstraction/chain-signatures
Learn how Chain Signatures enable NEAR accounts to sign and execute transactions across multiple blockchains using Multi-Party Computation for secure cross-chain operations.
Chain signatures enable NEAR accounts, including smart contracts, to sign and execute transactions across many blockchain protocols.
This unlocks the next level of blockchain interoperability by giving ownership of diverse assets, cross-chain accounts, and data to every single NEAR account.

*Diagram of a chain signature in NEAR*
> [accordion] Supported Networks
>
> While you can sign transactions for any network using Eddsa or Ecdsa keys, each chain signs transactions differently.
>
> Our example [implementation](./chain-signatures/implementation) shows you how to sign transactions for: Bitcoin, Solana, Cosmos, XRP, Aptos, Sui and EVM networks (Ethereum, Base, BNB Chain, Avalanche, Polygon, Arbitrum, and more).
## Benefits
Integration with Chain Signatures brings many benefits to Web3 developers:
* Single Account, Multi-Chain Operations: Developers can manage interactions with external blockchains from one NEAR account, without needing multiple wallets or addresses.
* Reduced Overhead in Cross-Chain Development: Developers can write smart contracts on NEAR that directly sign for cross-chain transactions.
* Secure Transaction Signing: Using [Multi-Party Computation (MPC)](#multi-party-computation-service), no single entity controls the signing key.
> [!TIP]
>
> Keep in mind that Chain Signatures is a “one way” solution to sign and execute outbound transactions happening on other blockchains.
> If you're looking to access states on external blockchains, you should check out Omnibridge.
***
## How It Works
Controlling accounts and their assets on other blockchain platforms is made possible thanks to the interaction between three elements:
1. [**Derivation Paths**](#derivation-paths-one-account-multiple-chains) - A deterministic way to derive foreign addresses from one NEAR account
2. [**Multichain Smart Contract**](#multichain-smart-contract) - Receives requests to sign a transaction for other blockchains
3. [**Multiparty Computation Service**](#multi-party-computation-service) - Third-party service providing signatures to the contract

*Chain signatures flow*
### Derivation Paths: One Account, Multiple Chains
Chain Signatures link NEAR accounts to addresses in other blockchain using [Additive Key Derivation](https://eprint.iacr.org/2021/1330) (a simple mechanism for deriving many subkeys from a single master key). These keys are generated using `derivation paths` (or `paths` for short).
A `derivation path` is simply a string (e.g. `ethereum-1`, `ethereum-2`, etc) that in conjunction with the NEAR account derives a unique address on the target blockchain.
For example, we can derive multiple Ethereum addresses from `example.near` by using different paths:
1. `example.near` + `ethereum-1` = `0x1b48b83a308ea4beb845db088180dc3389f8aa3b`
2. `example.near` + `ethereum-2` = `0x99c5d3025dc736541f2d97c3ef3c90de4d221315`
3. `example.near` + `...` = `0x...`
It is important to note that this allows us to discover the **public address** of the foreign account that we can control. To actually control the foreign account, we need to request signatures from the MPC service.
> [!TIP]
>
> In practice, the external address is deterministically derived using the NEAR address (`example.near`), the path (`ethereum-1`) and the MPC service's public key
> [!WARNING]
>
> **Avoid ambiguous signatures across chains**
>
> A signature is only bound to a specific network if the signed payload itself encodes that network. When it doesn't, the same signed transaction can be valid on more than one chain, allowing it to be **replayed** on a chain you did not intend to interact with. Two common cases:
>
> * **EVM networks:** transactions that follow [EIP-155](https://eips.ethereum.org/EIPS/eip-155) include the `chainId` in the signed data and are safe. Legacy (pre-EIP-155) transactions omit it and can be replayed across *any* EVM chain (Ethereum, Polygon, BNB Chain, Arbitrum, …).
> * **Bitcoin-like networks:** chains that share Bitcoin's transaction format (Litecoin, Dogecoin, Bitcoin Cash, …) may accept the same signed payload unless the chain adds replay protection (e.g. Bitcoin Cash's `SIGHASH_FORKID`).
>
> Rather than tracking which chains are affected, the robust rule is to **use a distinct derivation path per chain** (for example `ethereum-1` and `polygon-1` instead of reusing one path). Different paths derive different keys, so a signature for one chain cannot authorize a transaction on another.
### Multichain Smart Contract
A deployed smart contract ([v1.signer](https://nearblocks.io/address/v1.signer)) is used to request signatures for transactions on other blockchains.
This contract has [a `sign` method](https://github.com/near/mpc/blob/d0fc87b19e2643299e7becdd7d9611afcd5d5a78/crates/contract/src/api/sign.rs#L29) that takes these three parameters:
1. The `payload` (transaction or transaction hash) to be signed for the target blockchain.
2. The `path` that identifies the account to be used to sign the transaction.
3. The `domain_id`: an integer that picks the key and signature scheme, only the two signing domains are currently supported: `0` for `Secp256k1` or `1` for `Ed25519`.
For example, a user could request a signature to `send 0.1 ETH to 0x060f1...` **(transaction)** using the `ethereum-1` account **(path)** with `0` (Secp256k1) as **domain ID**.
After a request is made, the `sign` method will yield execution waiting while the [MPC signing service](#multi-party-computation-service) signs the transaction.
Once the signature is ready, the contract resumes computation and returns it to the user. This signature is a valid signed transaction that can be readily sent to the target blockchain to be executed.
For the user, the process is made completely **on chain**, since they only need to make a call to a smart contract and wait for the response.
> [!TIP]
>
> The `sign` method currently supports both Secp256k1 and Ed25519 signature schemes which enables signing transactions for the vast majority of the well-known blockchains including Bitcoin, Ethereum, Solana, BNB chain, Ton, or Stellar.
### Multi-Party Computation Service
The essence of Multi-Party Computation (MPC) is to enable independent parties to perform shared computations on private information without revealing secrets to each other. In practice, this system can be used with blockchain platforms to safely sign a transaction on behalf of a user without ever having to expose a private key.
NEAR's MPC service is comprised of several independent nodes, **none of which can sign by itself**, but instead create **signature-shares** that are **aggregated through multiple rounds** to **jointly** sign a transaction. The participant set and the signing threshold are public in the `v1.signer` contract, and they change only through its `vote_new_parameters` method, when enough current participants vote for it (see [The MPC network today](#the-mpc-network-today)).
This service continuously listens for signature requests (i.e. users calling the `sign` method on the `v1.signer` smart contract) and when a call is detected the MPC service:
1. Asks its nodes to jointly derive a signature for the `payload` using the account identified by the `path`
2. Once complete, call the `v1.signer` contract to store the resulting `Signature`
> [!NOTE]
>
> **A Custom MPC Service**
> Generally, MPC signing services work by sharing a master key, which needs to be re-created each time a node joins or leaves.
>
> NEAR's MPC service allows for nodes to safely join and leave, without needing to re-derive a master key.
> [!TIP]
>
> Want to learn more about the mathematics that enable MPC? [**Check this awesome article**](https://www.zellic.io/blog/mpc-from-scratch/).
#### The MPC network today
Read the live mainnet participant set and threshold from the contract:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-read-only v1.signer state json-args {} network-config mainnet now
```
[mpc.nearone.org](https://mpc.nearone.org) shows the live operators and a security overview. The audit reports are in [near/mpc/audits](https://github.com/near/mpc/tree/main/audits), and the [operator guide](https://github.com/near/mpc/blob/main/docs/guide/operating-an-mpc-node.md) covers running a node.
# Signing Transactions
Source: https://docs.near.org/chain-abstraction/chain-signatures/implementation
Learn how to sign transactions across multiple blockchains.
Chain signatures enable NEAR accounts, including smart contracts, to sign and execute transactions across many blockchain protocols.
This unlocks the next level of blockchain interoperability by giving ownership of diverse assets, cross-chain accounts, and data to a single NEAR account.
> [accordion] Supported Networks
>
> While you can sign transactions for any network using Eddsa or Ecdsa keys, each chain signs transactions differently.
>
> Our example implementation shows you how to sign transactions for: Bitcoin, Solana, Cosmos, XRP, Aptos, Sui and EVM networks (Ethereum, Base, BNB Chain, Avalanche, Polygon, Arbitrum, and more).
***
## Create a Chain Signature
There are five steps to create a Chain Signature:
1. [Deriving the Foreign Address](#1-deriving-the-foreign-address) - Derive the address that will be controlled on the target blockchain.
2. [Creating a Transaction](#2-creating-the-transaction) - Create the transaction or message to be signed.
3. [Requesting a Signature](#3-requesting-the-signature) - Call the NEAR MPC contract requesting it to sign the transaction.
4. [Formatting the Signature](#4-formatting-the-signature) - Format the signature from the MPC contract and add it to the transaction.
5. [Relaying the Signed Transaction](#5-relaying-the-signed-transaction) - Send the signed transaction to the destination chain for execution.

*Diagram of a chain signature in NEAR*
The [chainsig.js](https://github.com/NearDeFi/chainsig.js) library provides a convenient interface for completing each of these steps. The frontend uses `@hot-labs/near-connect` for wallet connections and transaction signing, and `near-api-js` for NEAR queries. Its `NearProvider` exposes the connected account and `signAndSendTransactions` through the local `useNearWallet` hook.
> [!TIP]
>
> For building transactions inside of NEAR smart contracts written in Rust, you can use the [Omni Transaction](https://github.com/near/omni-transaction-rs) library to easily build transactions for different blockchains (like Bitcoin and Ethereum).
> [!NOTE]
>
> **MPC Contracts**
>
> There is an [MPC contract](https://github.com/near/mpc/tree/main/crates/contract) available on both `mainnet` and `testnet`:
>
> * Mainnet: `v1.signer`
> * Testnet: `v1.signer-prod.testnet`
>
> The live participant set and threshold are in `v1.signer`: see [The MPC network today](/chain-abstraction/chain-signatures#the-mpc-network-today).
***
## Chain Signatures Contract
To interact with the chain signatures library you first need to instantiate a `ChainSignaturesContract`.
```js title="config.js" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
export const SIGNET_CONTRACT = new contracts.ChainSignatureContract({
networkId: NetworkId,
contractId: MPC_CONTRACT,
});
```
[See code on GitHub](https://github.com/near-examples/near-multichain/blob/7e1c9f1a8f8cf641685076810a155f5fdfe05d92/src/config.js#L53-L56)
The `networkId` and `contractId` are set to the values specified in the previous section depending which network you are on.
***
## Chain Adapters
To interact with a specific chain, you need to instantiate the relevant `chainAdapter`.
> [tab] Ξ EVM
>
> ```js title="EVM.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const publicClient = useMemo(() => createPublicClient({
> transport: http(rpcUrl),
> }), [rpcUrl]);
>
> const Evm = useMemo(() => new chainAdapters.evm.EVM({
> publicClient,
> contract: SIGNET_CONTRACT,
> }), [publicClient]);
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/EVM/EVM.jsx#L40-L47)
>
> The EVM chain adapter takes the `ChainSignaturesContract` as an argument as well as `publicClient` which is constructed from an EVM RPC URL.
>
> > [!TIP]
> >
> > To use different EVM networks, simply specify the RPC URL for your desired network.
> > The example demonstrates compatibility with multiple EVM-compatible networks including Ethereum, Base, BNB Chain, Avalanche, Polygon, Arbitrum, zkSync, and many others.
> > You can find RPC URLs for various networks at [ChainList](https://chainlist.org/?testnets=true).
> [tab] ₿ Bitcoin
>
> ```js title="Bitcoin.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const btcRpcAdapter = new chainAdapters.btc.BTCRpcAdapters.Mempool(
> "https://mempool.space/testnet4/api",
> );
>
> const Bitcoin = new chainAdapters.btc.Bitcoin({
> network: NetworkId,
> btcRpcAdapter,
> contract: SIGNET_CONTRACT,
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Bitcoin.jsx#L10-L18)
>
> The Bitcoin chain adapter takes the `ChainSignaturesContract` as an argument as well as the `network` ("mainnet", "testnet" or "regtest") and a `btcRpcAdapter` which handles communication with the Bitcoin network.
> [tab] ◎ Solana
>
> ```js title="Solana.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const connection = new SolanaConnection("https://api.devnet.solana.com");
>
> const Solana = new chainAdapters.solana.Solana({
> solanaConnection: connection,
> contract: SIGNET_CONTRACT,
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Solana.jsx#L12-L17)
>
> The Solana chain adapter takes the `ChainSignaturesContract` as an argument as well as a `connection` which is constructed from a Solana RPC URL. If you want to use Mainnet, then you need to choose a Mainnet RPC.
> [tab] ◉ XRP
>
> ```js title="XRP.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const Xrp = new chainAdapters.xrp.XRP({
> rpcUrl: "wss://s.altnet.rippletest.net:51233/",
> contract: SIGNET_CONTRACT,
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/XRP.jsx#L11-L14)
>
> The XRP chain adapter takes the `ChainSignaturesContract` as an argument as well as an `rpcUrl` for the XRP Ledger and the `rpcURl` specification. For testnet, use `https://s.altnet.rippletest.net:51234`.
> [tab] ◈ SUI
>
> ```js title="Sui.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const rpcUrl = getFullnodeUrl("testnet");
> const suiClient = new SuiClient({ url: rpcUrl });
>
> const Sui = new chainAdapters.sui.SUI({
> client: suiClient,
> contract: SIGNET_CONTRACT,
> rpcUrl: rpcUrl,
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Sui.jsx#L13-L20)
>
> The SUI chain adapter takes the `ChainSignaturesContract` as an argument as well as a `connection` which is a SuiClient constructed from a SUI RPC URL.
> [tab] ⬟ Aptos
>
> ```js title="Aptos.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const aptosClient = new AptosClient(
> new AptosConfig({
> network: Network.TESTNET,
> }),
> );
>
> const Aptos = new chainAdapters.aptos.Aptos({
> client: aptosClient,
> contract: SIGNET_CONTRACT,
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Aptos.jsx#L12-L21)
>
> The Aptos chain adapter takes the `ChainSignaturesContract` as `contract` and an `AptosClient` as `client`. Configure the client with the Aptos network and node URL you want to use.
***
## 1. Deriving the Foreign Address
Chain Signatures use [`derivation paths`](../chain-signatures#derivation-paths-one-account-multiple-chains) to represent accounts on the target blockchain. The foreign address to be controlled can be deterministically derived from:
* The NEAR account calling the MPC contract (e.g., `example.near`, `example.testnet`, etc.)
* A derivation path (a string such as `ethereum-1`, `ethereum-2`, etc.)
* The MPC service's master public key (we don't need to worry about this as it is defined in the library we're using).
To derive the address call the `deriveAddressAndPublicKey` method passing the near account Id from which the address is being derived and the derivation path.
> [tab] Ξ EVM
>
> ```js title="EVM.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const { address } = await Evm.deriveAddressAndPublicKey(signedAccountId, debouncedDerivationPath);
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/EVM/EVM.jsx#L92-L92)
> [tab] ₿ Bitcoin
>
> ```js title="Bitcoin.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const { address, publicKey } = await Bitcoin.deriveAddressAndPublicKey(
> signedAccountId,
> debouncedDerivationPath,
> );
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Bitcoin.jsx#L49-L52)
> [tab] ◎ Solana
>
> ```js title="Solana.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const { publicKey } = await Solana.deriveAddressAndPublicKey(
> signedAccountId,
> debouncedDerivationPath,
> );
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Solana.jsx#L47-L50)
>
> On Solana, your address is the same as your public key.
> [tab] ◉ XRP
>
> ```js title="XRP.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const { address, publicKey } = await Xrp.deriveAddressAndPublicKey(
> signedAccountId,
> debouncedDerivationPath,
> );
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/XRP.jsx#L45-L48)
> [tab] ◈ SUI
>
> ```js title="Sui.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const { address, publicKey } = await Sui.deriveAddressAndPublicKey(
> signedAccountId,
> debouncedDerivationPath,
> );
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Sui.jsx#L51-L54)
> [tab] ⬟ Aptos
>
> ```js title="Aptos.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const { address, publicKey } = await Aptos.deriveAddressAndPublicKey(
> signedAccountId,
> debouncedDerivationPath,
> );
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Aptos.jsx#L52-L55)
> [!NOTE]
>
> The same NEAR account and path will always produce the same address on the target blockchain.
>
> * `example.near` + `ethereum-1` = `0x1b48b83a308ea4beb845db088180dc3389f8aa3b`
> * `example.near` + `ethereum-2` = `0x99c5d3025dc736541f2d97c3ef3c90de4d221315`
***
## 2. Creating the Transaction
To construct the transaction to be signed use the method `prepareTransactionForSigning`.
> [tab] Ξ EVM
>
> Constructing a transaction to transfer ETH is very simple. The `value` is the amount of ETH in Wei as type BigInt (1 ETH = 1018 Wei).
>
> ```js title="Transfer.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> return await Evm.prepareTransactionForSigning({
> from: senderAddress,
> to: receiverAddress,
> value: BigInt(Web3.utils.toWei(transferAmount, "ether")),
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/7e1c9f1a8f8cf641685076810a155f5fdfe05d92/src/components/EVM/Transfer.jsx#L17-L21)
>
> This method returns the `unsigned transaction` and the transaction `hash(es)` (also known as the `payload`).
> [tab] ₿ Bitcoin
>
> Constructing a transaction to transfer BTC is very simple. The `value` is the amount of BTC in satoshis as a string (1 BTC = 100,000,000 sats).
>
> ```js title="Bitcoin.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const { transaction, hashesToSign } =
> await Bitcoin.prepareTransactionForSigning({
> publicKey: senderPublicKey,
> from: senderAddress,
> to: receiverAddress,
> value: transferAmount.toString(),
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Bitcoin.jsx#L71-L77)
>
> This method returns the `unsigned transaction` and the transaction `hash(es)` (also known as the `payload`).
> [tab] ◎ Solana
>
> Constructing a transaction to transfer SOL is very simple. The `value` is the amount of SOL in lamports as type BigInt (1 SOL = 1,000,000,000 lamports).
>
> ```js title="Solana.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const {
> transaction: { transaction },
> hashesToSign,
> } = await Solana.prepareTransactionForSigning({
> from: senderAddress,
> to: receiverAddress,
> amount: decimalToBigInt(transferAmount, 9),
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Solana.jsx#L65-L72)
>
> This method returns the `unsigned transaction` and `hashesToSign`, the message bytes to pass to the signing contract.
> [tab] ◉ XRP
>
> Constructing a transaction to transfer XRP is straightforward. The `value` is the amount of XRP in drops as a string (1 XRP = 1,000,000 drops).
>
> ```js title="XRP.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const { transaction, hashesToSign } =
> await Xrp.prepareTransactionForSigning({
> from: senderAddress,
> to: receiverAddress,
> amount: decimalToBigInt(transferAmount, 6).toString(),
> publicKey: senderPublicKey,
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/XRP.jsx#L63-L69)
>
> This method returns the `unsigned transaction` and the transaction `hash` (also known as the `payload`).
> [tab] ◈ SUI
>
> Constructing a transaction to transfer SUI is simple. The `value` is the amount of SUI in MIST as type BigInt (1 SUI = 1,000,000,000 MIST).
>
> ```js title="Sui.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const transactionSui = new Transaction();
>
> const [coin] = transactionSui.splitCoins(transactionSui.gas, [
> decimalToBigInt(transferAmount, 9),
> ]);
>
> transactionSui.transferObjects([coin], receiverAddress);
> transactionSui.setSender(senderAddress);
>
> const { hashesToSign, transaction } =
> await Sui.prepareTransactionForSigning(transactionSui);
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Sui.jsx#L70-L80)
>
> This method returns the `unsigned transaction` and the transaction `hash` (also known as the `payload`).
> [tab] ⬟ Aptos
>
> Constructing a transaction to transfer APT is straightforward. The `value` is the amount of APT in octas as type BigInt (1 APT = 100,000,000 octas).
>
> ```js title="Aptos.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const transactionPayload = {
> function: "0x1::aptos_account::transfer",
> functionArguments: [receiverAddress, decimalToBigInt(transferAmount, 8)],
> };
>
> const transaction = await aptosClient.transaction.build.simple({
> sender: senderAddress,
> data: transactionPayload,
> });
>
> const { hashesToSign } =
> await Aptos.prepareTransactionForSigning(transaction);
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Aptos.jsx#L71-L82)
>
> This method returns the `unsigned transaction` and the transaction `hash` (also known as the `payload`).
> [accordion] EVM Function Calls
>
> To call a function on a smart contract we need the ABI of the contract, in our repo this is defined in the [config.js](https://github.com/near-examples/near-multichain/blob/main/src/config.js#L23-L63) file (this can be gathered from Remix or using Etherscan).
>
> Then define a `Contract` object using the `ethers` library
>
> ```js title="FunctionCall.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const contract = useMemo(() => new Contract(contractAddress, ABI, new JsonRpcProvider(rpcUrl)), [contractAddress, rpcUrl]);
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/EVM/FunctionCall.jsx#L17-L17)
>
> Then to construct the transaction
>
> ```js title="FunctionCall.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const data = contract.interface.encodeFunctionData("set", [number]);
>
> return await Evm.prepareTransactionForSigning({
> from: senderAddress,
> to: contractAddress,
> data,
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/EVM/FunctionCall.jsx#L30-L36)
>
> This approach allows you to call smart contract functions by encoding the function data and including it in the transaction.
***
## 3. Requesting the Signature
Once the transaction is created and ready to be signed, a signature request is made by calling `sign` on the MPC smart contract.
The method requires four parameters:
1. The `payloads` (or hashes) to be signed for the target blockchain
2. The derivation `path` for the account we want to use to sign the transaction
3. The `keyType`, `Ecdsa` for `Secp256k1` signatures and `Eddsa` for `Ed25519` signatures.
4. The `signerAccount` which contains the `accountId` that is signing and the `signAndSendTransactions` function from [Near Connect](../../web3-apps/tutorials/wallet-login).
> [tab] Ξ EVM
>
> ```js title="EVM.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const rsvSignatures = await SIGNET_CONTRACT.sign({
> payloads: hashesToSign,
> path: debouncedDerivationPath,
> keyType: "Ecdsa",
> signerAccount: {
> accountId: signedAccountId,
> signAndSendTransactions,
> },
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/EVM/EVM.jsx#L115-L123)
> [tab] ₿ Bitcoin
>
> ```js title="Bitcoin.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const rsvSignatures = await SIGNET_CONTRACT.sign({
> payloads: hashesToSign,
> path: debouncedDerivationPath,
> keyType: "Ecdsa",
> signerAccount: {
> accountId: signedAccountId,
> signAndSendTransactions,
> },
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Bitcoin.jsx#L83-L91)
>
> For Bitcoin, it is common to have multiple UTXOs to sign when sending a single transaction. We create a NEAR transaction (to call `sign` on the MPC contract) for each UTXO and send them to be signed by the MPC individually. Each signature is then parsed from each transaction outcome to produce an array of signatures.
> [tab] ◎ Solana
>
> Pass the `hashesToSign` returned by `Solana.prepareTransactionForSigning` directly to `SIGNET_CONTRACT.sign`. For Solana, the adapter supplies the serialized transaction message as a byte array for Ed25519 signing.
>
> ```js title="Solana.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const rsvSignatures = await SIGNET_CONTRACT.sign({
> payloads: hashesToSign,
> path: debouncedDerivationPath,
> keyType: "Eddsa",
> signerAccount: {
> accountId: signedAccountId,
> signAndSendTransactions,
> },
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Solana.jsx#L79-L87)
> [tab] ◉ XRP
>
> ```js title="XRP.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const rsvSignatures = await SIGNET_CONTRACT.sign({
> payloads: hashesToSign,
> path: debouncedDerivationPath,
> keyType: "Ecdsa",
> signerAccount: {
> accountId: signedAccountId,
> signAndSendTransactions,
> },
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/XRP.jsx#L76-L84)
> [tab] ◈ SUI
>
> ```js title="Sui.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const rsvSignatures = await SIGNET_CONTRACT.sign({
> payloads: hashesToSign,
> path: debouncedDerivationPath,
> keyType: "Eddsa",
> signerAccount: {
> accountId: signedAccountId,
> signAndSendTransactions,
> },
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Sui.jsx#L87-L95)
> [tab] ⬟ Aptos
>
> ```js title="Aptos.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const rsvSignatures = await SIGNET_CONTRACT.sign({
> payloads: hashesToSign,
> path: debouncedDerivationPath,
> keyType: "Eddsa",
> signerAccount: {
> accountId: signedAccountId,
> signAndSendTransactions,
> },
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Aptos.jsx#L88-L96)
***
## 4. Formatting the Signature
Once the signature is returned from the MPC it needs to be formatted and added to the transaction to produce a signed transaction.
> [tab] Ξ EVM
>
> ```js title="EVM.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const finalizedTransaction = Evm.finalizeTransactionSigning({
> transaction,
> rsvSignatures,
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/EVM/EVM.jsx#L125-L128)
> [tab] ₿ Bitcoin
>
> ```js title="Bitcoin.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const finalizedTransaction = Bitcoin.finalizeTransactionSigning({
> transaction,
> rsvSignatures,
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Bitcoin.jsx#L97-L100)
>
> For Bitcoin, the array of signatures is added to the transaction to produce a complete signed transaction.
> [tab] ◎ Solana
>
> ```js title="Solana.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const finalizedTransaction = Solana.finalizeTransactionSigning({
> transaction,
> rsvSignatures: rsvSignatures[0],
> senderAddress,
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Solana.jsx#L93-L97)
> [tab] ◉ XRP
>
> ```js title="XRP.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const finalizedTransaction = Xrp.finalizeTransactionSigning({
> transaction,
> rsvSignatures,
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/XRP.jsx#L90-L93)
> [tab] ◈ SUI
>
> ```js title="Sui.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const finalizedTransaction = Sui.finalizeTransactionSigning({
> transaction,
> rsvSignatures: rsvSignatures[0],
> publicKey: senderPublicKey,
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Sui.jsx#L101-L105)
> [tab] ⬟ Aptos
>
> ```js title="Aptos.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const finalizedTransaction = Aptos.finalizeTransactionSigning({
> transaction,
> rsvSignatures: rsvSignatures[0],
> publicKey: senderPublicKey,
> });
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Aptos.jsx#L102-L106)
***
## 5. Relaying the Signed Transaction
Now that we have a signed transaction, we can relay it to the target network using `broadcastTx`.
> [tab] Ξ EVM
>
> ```js title="EVM.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const transactionHash = await Evm.broadcastTx(signedTransaction);
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/EVM/EVM.jsx#L150-L150)
> [tab] ₿ Bitcoin
>
> ```js title="Bitcoin.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const transactionHash = await Bitcoin.broadcastTx(signedTransaction);
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Bitcoin.jsx#L119-L119)
> [tab] ◎ Solana
>
> ```js title="Solana.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const transactionHash = await Solana.broadcastTx(signedTransaction);
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Solana.jsx#L116-L116)
> [tab] ◉ XRP
>
> ```js title="XRP.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const transactionHash = await Xrp.broadcastTx(signedTransaction);
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/XRP.jsx#L114-L114)
> [tab] ◈ SUI
>
> ```js title="Sui.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const transactionHash = await Sui.broadcastTx(signedTransaction);
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Sui.jsx#L124-L124)
> [tab] ⬟ Aptos
>
> ```js title="Aptos.jsx" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const transactionHash = await Aptos.broadcastTx(signedTransaction);
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-multichain/blob/58a54ebb22847a719b554454a4ee1a575cfde9c8/src/components/Aptos.jsx#L123-L123)
The method returns a transaction hash which can be used to locate the transaction on an explorer.
> [!NOTE]
>
> ⭐️ For a deep dive into the concepts of Chain Signatures, see [What are Chain Signatures?](../chain-signatures)
>
> ⭐️ For a complete example of a NEAR account using chain signatures in a frontend, see our [web app example](https://github.com/near-examples/near-multichain).
# Controlling a NEAR account
Source: https://docs.near.org/chain-abstraction/chain-signatures/tutorials/controlling-near-accounts/0-introduction
Learn to control a NEAR account securely using Multi-Party Computation.
Imagine acting on behalf of another Near account - without ever holding its private key. Sounds futuristic? It’s possible today, thanks to [Chain Abstraction and Multi-Party Computation (MPC)](/chain-abstraction/what-is), and this tutorial will walk you step-by-step through the entire process of transferring 0.1 NEAR on behalf of another Near account.
## How It Works
Behind the scenes, a smart contract constructs a valid transaction on behalf of a user and forwards it to an MPC contract for signing.
The key advantage of this approach is that no single entity possesses the private key — ensuring enhanced security and decentralization.
> [!NOTE]
>
> The complete source code for the smart contract used in this tutorial, along with scripts for playground simulation, is available in the [GitHub repository](https://github.com/nearuaguild/control-near-account-with-mpc-example).
>
> The contract is rolled out on testnet at `broken-rock.testnet`, feel free to use it for your own purposes if you don't want to dig deeper into deploying it on your own.
## What You Will Learn
In this tutorial, you will learn how to:
* [Prepare Near account](/chain-abstraction/chain-signatures/tutorials/controlling-near-accounts/1-setup) to be fully controlled via MPC
* [Build a transfer transaction and get it signed](/chain-abstraction/chain-signatures/tutorials/controlling-near-accounts/2-transfer) in a smart contract
* [Broadcast a signed transaction](/chain-abstraction/chain-signatures/tutorials/controlling-near-accounts/2-transfer) into the network over RPC.
# Setting up a Near account to be controlled by MPC
Source: https://docs.near.org/chain-abstraction/chain-signatures/tutorials/controlling-near-accounts/1-setup
Set up a NEAR account to be securely controlled via MPC by deriving a public key and adding it as an access key.
One of the powerful features of the NEAR Protocol is its flexible [access keys architecture](/protocol/accounts-contracts/access-keys). An account can hold multiple access keys, each with different levels of permission. This enables us to grant transaction-signing capabilities to an external key without compromising security.
To achieve secure external control via MPC, we must derive a valid `secp256k1` public key from the MPC smart contract. This key belongs to a key pair that will be used later in the tutorial for signing transactions securely.
Before we proceed, let's create an account on whose behalf we will be acting.
## Creating an account
If you already have a NEAR account that you want to control via MPC, feel free to skip this step.
Otherwise, use the following command:
```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
near account create-account fund-myself
```
## Deriving a Public Key from MPC
As you already know from the [Chain Signatures documentation](/chain-abstraction/chain-signatures#how-it-works), `derivation_path` is the key component that allows generating multiple distinct key pairs. When combined with `predecessor_id`, it forms a unique and secure pair.
In our example, the smart contract acts as a proxy between a user and the MPC, `User Account <-> Contract Proxy <-> Contract Requesting a Signature`, which means the contract itself becomes the `predecessor` in the derivation process: `predecessor: contract_proxy_address`.
If the Contract Proxy were deployed directly onto the User Account, `User Account <-> Contract Requesting a Signature`, the User Account would become the `predecessor` in the derivation process: `predecessor: user_account_address`.
To understand how `derivation_path` is built, let's examine the [smart contract implementation](https://github.com/nearuaguild/control-near-account-with-mpc-example/blob/97883851483c05d4c9206afb6efeac02ec9c2541/contract/src/lib.rs#L64-L68):
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
let derivation_path = format!(
"{}-{}",
env::predecessor_account_id().to_string(),
args.signer_id.to_string()
);
```
* `args.signer_id` is the account on whose behalf we're acting
* `env::predecessor_account_id().to_string()` refers to the account that is calling the contract, please do not confuse it with previously mentioned `predecessor_id` as it refers to the smart contract address
Now that we understand how each input is calculated, let's put them together and actually derive a public key.
> [tab] TypeScript
>
> ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const contractId = "broken-rock.testnet"; // smart contract address
> const adminAccountId = "admin.testnet"; // signs transactions to act on behalf of `controllableAccountId`
> const controllableAccountId = "controllable.testnet"; // on whose behalf we'll be acting
>
> // admin.testnet-controllable.testnet
> const derivationPath = `${adminAccountId}-${controllableAccountId}`;
>
> // secp256k1:m2CUiQw9f5nN8sAszkHrbok6apRz7j6LkpFZ6vT6zzxLHh2C54udU9Ue7eRy7FRK42pD796nNSwEdsqXzLb96PR
> const derivedPublicKey = await deriveKey(contractId, derivationPath);
> ```
## Adding key to the account
Once we have the public key, the final step is to add it to the NEAR account.
> [tab] Near CLI
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near account add-key controllable.testnet grant-full-access use-manually-provided-public-key secp256k1:m2CUiQw9f5nN8sAszkHrbok6apRz7j6LkpFZ6vT6zzxLHh2C54udU9Ue7eRy7FRK42pD796nNSwEdsqXzLb96PR network-config testnet sign-with-legacy-keychain send
> ```
> [tab] TypeScript
>
> ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const path = require("node:path");
> const { homedir } = require("node:os");
> const { keyStores, connect } = require("near-api-js");
>
> const CREDENTIALS_DIR = ".near-credentials";
> const credentialsPath = path.join(homedir(), CREDENTIALS_DIR);
> const keyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath);
>
> const config = {
> keyStore,
> networkId: "testnet",
> nodeUrl: "https://rpc.testnet.near.org",
> };
>
> const near = await connect(config);
>
> const account = await near.account("controllable.testnet");
>
> // uses derivedPublicKey from previous step
> await account.addKey(derivedPublicKey);
> ```
In our example, we’ve added this public key as a [**FullAccess key**](/protocol/accounts-contracts/access-keys#full-access-keys), meaning it has full control over the account, this allows us to execute all transactions without limitations. However, it is also possible to add the key as a **FunctionCall access key** with limited permissions.
The next step is to create, sign and eventually send a transfer transaction on behalf of `controllable.testnet`. Continue to [the next chapter](/chain-abstraction/chain-signatures/tutorials/controlling-near-accounts/2-transfer) to learn how.
# Transfer Near tokens on behalf of a controlled account
Source: https://docs.near.org/chain-abstraction/chain-signatures/tutorials/controlling-near-accounts/2-transfer
Build transaction arguments, request MPC signatures, and broadcast signed NEAR token transfers securely.
In this part of the tutorial, we'll dig into how transaction arguments are built, how to request a signature according to the arguments from the smart contract, and how to broadcast the signed transaction into the network.
## Building transaction arguments
Now that we've set up the account and derived the public key, it's time to build the transaction arguments.
For a transaction to be valid, we must attach both a `nonce` and a `recent_block_hash` - these values ensure that the transaction is unique and prevent replay attacks.
Let's fetch `nonce` first:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
const accessKey = await near.connection.provider.query({
request_type: "view_access_key",
account_id: controllableAccountId, // "controllable.testnet"
public_key: derivedPublicKey, // derived in the previous chapter
finality: "optimistic",
});
const nonce = accessKey.nonce;
```
And `recent_block_hash`, now it's your turn:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
const block = await near.connection.provider.block({
finality: "final",
});
const blockHash = block.header.hash;
```
Now that we have everything needed, let's build transaction arguments:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
const transactionArgs = {
signer_id: controllableAccountId, // "controllable.testnet"
signer_pk: derivedPublicKey, // derived in the previous chapter
nonce: (nonce + 1).toString(),
block_hash: blockHash,
};
```
## Requesting signature from Smart Contract
After building transaction arguments, the next step is to request a signature from the smart contract.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
const adminAccount = await near.account("admin.testnet");
const outcome = await adminAccount.functionCall({
contractId: contractId, // "broken-rock.testnet"
methodName: "transfer_on_behalf_of",
args: {
args: transactionArgs,
},
gas: "300000000000000",
attachedDeposit: "100000000000000000000000", // 0.1 NEAR is enough in most cases to pay MPC fee
});
```
## Broadcasting the transaction
With the signature in hand, we are now ready to send it to the network!
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Get the signed transaction from the outcome
result = providers.getTransactionLastResult(outcome);
const signedTx = new Uint8Array(result);
// Send the signed transaction
const transferOutcome = await near.connection.provider.sendJsonRpc(
"broadcast_tx_commit",
[Buffer.from(signedTx).toString("base64")]
);
console.log(
`https://nearblocks.io/txns/${transferOutcome.transaction_outcome.id}`
);
```
## Final Thoughts
With that, we've successfully completed the full journey of acting on behalf of another Near account securely and transferred to yourself 0.1 NEAR from a controllable account. By following this process, you now have a solid understanding of how to manage external accounts on Near using Multi-Party Computation (MPC).
# Near Multi-Chain DAO Governance
Source: https://docs.near.org/chain-abstraction/chain-signatures/tutorials/multichain-dao/0-intro
Learn how Abstract DAO enables a single vote on NEAR to execute actions across multiple EVM chains.
Many multi-chain organizations deploy copies of the same smart contract across multiple EVM chains, which need to be kept in sync.
Generally, this is tackled by handling multiple DAOs - one per chain - where the same action is voted simultaneously, a process that is not only time-consuming, but also very expensive and error-prone.

To solve this, we have built the [Abstract DAO](https://github.com/nearuaguild/abstract-dao), which enables organizations to **vote once** in NEAR, and then **execute the same action** across **multiple chains**.

> [!WARNING]
>
> Abstract DAO is an example, and as such it has not been audited, use it at your own risk.
> [accordion] Common use cases
>
> * **Run one DAO vote that executes on several EVM chains:** vote once on NEAR and execute the same action on every chain.
> * **Keep contracts on multiple EVM chains in sync:** update copies of the same contract across chains with a single governance decision.
***
### How It Works?
The [Abstract DAO](https://github.com/nearuaguild/abstract-dao) acts as an intermediary between NEAR DAOs and the EVM chains.
The process of voting and executing an action looks like this:
1. **Craft an EIP-1559 Payload**: You create the transaction that will execute across all chain, specifying the recipient address, nonce, value, and transaction data. Only the gas parameters are not set, as they will vary across chains.
2. **Choose a Single Allowed Account**: As part of the voting process, your organization chooses an "allowed account," which is the member who will be responsible to setup gas parameters, and generate signatures for all the chains.
3. **Vote on the Request**: Your decentralized organization votes once on NEAR to approve this request. Each member can review the transaction, then cast their vote to confirm or reject it.
4. **Generate Signatures**: Once the request has enough confirmations, the transaction is approved. The "allowed account" can now interact with the [Abstract DAO](https://github.com/nearuaguild/abstract-dao) to generate signatures for as many EVM-compatible chains as needed.
The result is a drastically simplified governance process (one vote, one confirmation) and the ability to sign and execute transactions across multiple chains in a coordinated manner.
> [!TIP]
>
> **Handling Gas**
> Since Gas prices can vary widely across chains, the transaction's gas price is not set until the signatures are generated.
>
> This means that the "allowed account" will be in charge of setting the gas price for each transaction being signed.
***
## Prerequisites
To complete this tutorial successfully, you will need [Near CLI](/tools/cli#installation) to be installed, and have a general understanding of how [Chain Signatures](/chain-abstraction/chain-signatures) work.
***
## Next steps
Ready to start? Let's jump to the first step, in which we will understand how the Abstract DAO contract works.
***
> [!NOTE]
>
> **Versioning for this article**
>
> * near-cli: `0.12.0`
> * rustc: `1.78.0`
> * cargo: `1.80.1`
> * cargo-near: `0.6.2`
> * rustc: `1.78.0`
> * node: `21.6.1`
# Abstract DAO: Requests
Source: https://docs.near.org/chain-abstraction/chain-signatures/tutorials/multichain-dao/1-request
Learn how to create a signature request in Abstract DAO to execute actions on foreign EVM chains.
The Abstract DAO contract works as an intermediary between decentralized organizations in NEAR and EVM networks. To better understand how it works it is better to start by using it by itself, without using a DAO yet.
Join us as we explore how to create a request in the Abstract DAO contract, that will be later used to derive signatures for foreign EVM chains.
> [!TIP]
>
> We have deployed the Abstract DAO in two environments:
>
> 1. Testnet: `abstract-dao.testnet`
> 2. Dev (unstable): `dev.abstract-dao.testnet`
***
## Ethereum Function Call
Imagine that our organization agreed on changing a value in a simple [counter we deployed on Sepolia Ethereum](https://sepolia.etherscan.io/address/0xe2a01146FFfC8432497ae49A7a6cBa5B9Abd71A3), and now want to leave this intent in the Abstract DAO.
For this, we will call the **`register_signature_request`** function on Abstract Dao saying:
*We allow **executor.testnet** to request signatures for one of our Ethereum accounts, making it set a counter to `1000`*.
Here are the parameters, take a quick glance for now, since we will go over each one of them:
```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"request": {
"derivation_seed_number": 0,
"allowed_account_id": "executor.testnet",
"transaction_payload": {
"to": "0xe2a01146FFfC8432497ae49A7a6cBa5B9Abd71A3",
"nonce": "0",
"function_data": {
"function_abi": {
"inputs": [
{
"internalType": "uint256",
"name": "_num",
"type": "uint256"
}
],
"name": "set",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
"arguments": [
{
"Uint": "A97"
}
]
}
},
}
}
```
There are 3 arguments in the call above: `derivation_seed_number`, `transaction_payload`, and `allowed_account_id` lets see them in depth.
### Derivation Path
The parameter `derivation seed number` will be used to derive which external address we will be requesting signatures from, the address will be derived as:
`DAO Address` + `Derivation Path` + `Contract Address` = `EVM Address`
For example, if we register a request from the address `...` using the derivation path `0` we will obtain control the `0x...` account.
> [!TIP]
>
> Learn more about derivation paths [here](/chain-abstraction/chain-signatures)
### Transaction Payload
The `transaction_payload` contains all the information on the transaction that we want to perform, particularly:
* `to`: The recipient address of the transaction
* `nonce`: The transaction nonce, used to ensure uniqueness
* `function_data`: (optional) Defines the function that will be called on the recipient's contract, including:
* `function_abi`: The ABI of the function being called
* `arguments`: The input arguments for the function, all ABI encoded (e.g. integers are `base64`)
There are a couple important points to notice about this `transaction_payload`:
* **Readable Payload:** The parameters make it easy for anyone to quickly understand what transaction will be executed externally. The Abstract DAO is designed to be transparent and easy to audit, abstracting away the complexity of creating the transaction.
* **We Are Setting a Nonce:** By setting the nonce, we make sure that the transaction will only be valid once, as future transactions will need higher `nonces`
* **We Are Not Setting the GAS:** Gas prices are expected to vary wildly across EVMs, for which it makes no sense to setup a fixed gas amount and gas price for all the networks, for this is that we use the last parameter `allowed_account`
### Allowed Account
In this case, the `allowed_account` will be the one in charge of generating the signatures. At the time of generating the signature, the account will also set the `gas_price` for the transaction on a per-chain basis.
# Abstract Dao: Signatures
Source: https://docs.near.org/chain-abstraction/chain-signatures/tutorials/multichain-dao/2-signing
Learn how to sign Abstract DAO requests for different chains and relay them to target EVM networks.
In the previous section, we saw how to register a signature request on the Abstract DAO contract. Now, it is time to sign the transaction for different chains and relay it to the target EVM network.
***
## Signing the Transaction
To sign a transaction for a specific chain, the allowed account needs to call the `get_signature` function, passing the `request_id` (generated on the previous section) and all the necessary info to finish creating the transaction before signing it.
For example, to sign the transaction for the Sepolia Testnet, the following command can be used:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction abstract-dao.testnet get_signature json-args '{
"request_id": 1,
"other_payload": {
"chain_id": 11155111,
"max_fee_per_gas": "1000000000",
"max_priority_fee_per_gas": "100000000"
}
}' prepaid-gas '300.0 Tgas' attached-deposit '0.05 NEAR' sign-as executor.testnet network-config testnet
```
Note that all we are specifying now is the `chain_id` (to identify the destination chain), the `max_fee_per_gas`, and the `max_priority_fee_per_gas` (to set the transaction fee).
The account authorized to call `get_signature` - in this case `executor.testnet` cannot change any parameter of the transaction being signed besides setting a gas fee per chain.
***
## Signature Response
The signature response is going to look like this:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"big_r": {
"signature": {
"affine_point": "02D532992B0ECBF67800DB14E04530D9BA55609AD31213CC7ABDB554E8FDA986D3"
},
"recovery_id": 1,
"s": {
"scalar": "40E81711B8174712B9F34B2540EE0F642802387D15543CBFC84211BB04B83AC3"
}
},
"tx": "0x02f85083aa36a702850485034c878517a4eb0789829dd094e2a01146fffc8432497ae49a7a6cba5b9abd71a380a460fe47b1000000000000000000000000000000000000000000000000000000000000a84bc0"
}
```
As we can see, it is not the signed transaction itself, but instead the data we need to reconstruct it. We have created an [script](https://github.com/nearuaguild/multichain-dao-scripts) to automate this process, as well as the relaying to the target EVM network.
# MultiSig Voting
Source: https://docs.near.org/chain-abstraction/chain-signatures/tutorials/multichain-dao/3-voting
Learn how to deploy a MultiSig contract and vote on multi-chain proposals using the Abstract DAO.
Now that we understand how the Abstract DAO works, it is time to use it in within an organization. Lets see how to deploy a MultiSig contract, where users will vote on a multi-chain proposal.
***
## Creating a MultiSig Contract
As a first step we need to create an account and deploy a MultiSig contract on it, so users can start creating proposals and voting on them.
> [!NOTE]
>
> **Deploy Multisig**
> You can download the [compiled multisig](https://github.com/near/core-contracts/raw/refs/heads/master/multisig2/res/multisig2.wasm) from the near repository
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near create-account --useFaucet
near deploy multisig2.wasm
```
> [!TIP]
>
> See the github repository for instructions on how to [initialize the multisig contract](https://github.com/near/core-contracts/tree/master/multisig2)
***
## Creating a Request on the Multisig Contract
To call `register_signature_request` on the Multi-Chain DAO Governance Contract, you need to submit a request through your Multisig contract. This ensures that the decision to generate a signature is confirmed by the necessary members.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction multisignature.testnet add_request json-args '{
"request": {
"receiver_id": "abstract-dao.testnet",
"actions": [
{
"type": "FunctionCall",
"method_name": "register_signature_request",
"args": {
"request": {
"allowed_account_id": "executor.testnet",
"derivation_seed_number": 0,
"transaction_payload": {
"to": "0xe2a01146FFfC8432497ae49A7a6cBa5B9Abd71A3",
"nonce": "0",
"function_data": {
"function_abi": {
"inputs": [
{
"internalType": "uint256",
"name": "_num",
"type": "uint256"
}
],
"name": "set",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
"arguments": [
{
"Uint": "A97"
}
]
}
}
}
},
"gas": "100000000000000",
"deposit": "0.1"
}
]
}
}' prepaid-gas '100.0 Tgas' attached-deposit '1 yoctoNEAR' sign-as executor.testnet network-config testnet
```
***
## Voting on the Request
Once the request is submitted, members of the multisig contract have a set amount of time to vote to either Confirm or Reject the request. Each member needs to cast their vote using the following command:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction multisignature.testnet confirm json-args '{"request_id": 1}' prepaid-gas '100.0 Tgas' attached-deposit '1 yoctoNEAR' sign-as account.testnet network-config testnet
```
> [!NOTE]
>
> Replace provided `request_id` with value retrieved from the response when creating the request
Once the request has received enough confirmations, it will be automatically executed. At this point, the signature request is successfully registered on the Multi-Chain DAO Governance Contract.
Now, the allowed account (specified in the request) can generate signatures for the transaction just as we saw in the [previous section](./2-signing).
# NEAR Intents
Source: https://docs.near.org/chain-abstraction/intents/overview
Learn how the intents protocol works
NEAR Intents is a multichain transaction protocol where users specify what they want and let third parties compete to provide the best solution. This works for everything from token swaps to pizza delivery, creating a universal marketplace across crypto and traditional services.
> [accordion] Common use cases
>
> * **One API for cross-chain swaps:** swap tokens across chains through a single integration with the [1Click API](https://docs.near-intents.org).
> * **Move stablecoins between chains programmatically:** send USDC from one chain and receive it on another without building bridge integrations.
> * **Charge for APIs with x402 and get paid on any chain:** the [x402 1Click gateway](https://github.com/IkerAlus/x402_1CS_gateway) accepts x402 payments in USDC on an EVM chain and settles them to a merchant on any chain NEAR Intents supports. It is a pilot that has not been battle-tested.

> [card] [Read Intents Docs](https://docs.near-intents.org)
>
> Read the official documentation to learn more about NEAR Intents and how to use it
***
## How It Works
**1. Intent Creation**
A user or AI agent expresses a desired outcome *(ex: Swap Token A for Token B)* and broadcasts the intent to network of Market Makers (also called Solvers).
**2. Market Maker Competition**
An off-chain decentralized network of Market Makers (aka solvers) compete to fulfill the request in the most optimal way. When the network finds the best solution, it presents it as a quote to the originating user/agent for approval.
**3. Intent Execution**
If the quote from the Market Maker is accepted, the intent is executed by calling a "Verifier" smart contract on NEAR Protocol. This contract securely verifies and settles the final transaction.
***
## Resources
> [card] [Official NEAR Intents Documentation](https://docs.near-intents.org)
>
> Read the official documentation to learn more about NEAR Intents.
> [card] [Dev Support Channel](https://t.me/near_intents)
>
> Join the Telegram developer support channel.
> [card] [Integration Example](https://github.com/near-examples/near-intents-examples)
>
> Explore an easy integration example that uses the 1Click API.
> [card] [near-intents.org (Live Site)](https://near-intents.org)
>
> Try the live demo application showcasing token swaps.
> [card] [Independent Fee Benchmark](https://openchainbench.com/benchmarks/bridge-fee)
>
> Compare NEAR Intents against other bridges on effective USDC transfer costs, measured independently across Solana, Base, and Arbitrum corridors.
# How Omni Bridge Works
Source: https://docs.near.org/chain-abstraction/omnibridge/how-it-works
Learn how Omni Bridge uses Chain Signatures to enable cross-chain transfers.
The journey toward truly trustless cross-chain communication took a significant leap forward when the NEAR team [created the first trustless bridge with Ethereum](https://near.org/blog/the-rainbow-bridge-is-live) (Rainbow Bridge). This pioneering achievement demonstrated that completely trustless cross-chain communication was possible, marking a crucial step toward the vision of chain abstraction. However, this approach relied on implementing a NEAR light client directly on Ethereum - essentially requiring Ethereum to understand and verify NEAR's complex blockchain rules.
Omni Bridge introduces a more elegant solution using Chain Signatures. Instead of running light clients on each destination chain, it leverages Chain Signature's MPC Service to enable secure cross-chain message verification without the overhead of light client verification. This new approach reduces verification times from hours to minutes while significantly reducing gas costs across all supported chains.
### Issues with Light Clients
A light client is a smart contract that lets one blockchain verify events happening on another blockchain. In Rainbow Bridge's case, the Ethereum light client needs to track NEAR's blocks, verify its validators' signatures, and confirm transactions. This comes with major technical challenges: it requires storing two weeks of Ethereum block data, maintaining an updated list of NEAR validators and their stakes, and most crucially, verifying NEAR's ED25519 signatures - a process Ethereum wasn't built for. This verification is computationally expensive, making the whole process slow, costly, and ultimately a major bottleneck.
For example, with Rainbow Bridge, transactions from NEAR to Ethereum take between 4 and 8 hours due to the 4-hour challenge period and block submission intervals driven by Ethereum's high gas costs. More importantly, this approach becomes increasingly impractical when connecting to multiple chains, as each chain would require its own light client implementation. Some chains, such as Bitcoin, don't even support smart contracts, making it technically impossible to implement a NEAR light client.
While we still need to support light clients of different networks on NEAR (which is significantly easier to implement), a different approach is needed for verifying NEAR state on foreign chains.
### Token Standards and Cross-Chain Communication
Before exploring how Chain Signatures solves these issues, it's important to understand how tokens work on NEAR. [NEP-141](https://github.com/near/NEPs/tree/master/neps/nep-0141.md), NEAR's fungible token standard, has a key feature that sets it apart from Ethereum's ERC-20: built-in composability through transfer-and-call functionality.
When a token transfer happens on NEAR using `ft_transfer_call`, the token contract first transfers the tokens and then automatically calls the specified `ft_on_transfer` method on the receiver contract. While these operations happen in sequence within the same transaction, the receiver contract has the ability to reject the transfer, causing the tokens to be refunded. This atomic behavior ensures the integrity and safety of bridge operations by preventing partial execution states.
For more information see [Fungible Tokens](../../primitives/ft/ft).
## Enter Chain Signatures
Instead of maintaining complex light clients on destination chains, Chain Signatures introduces a fundamentally different approach based on three core components:
1. **Deterministic Address Derivation** - Every NEAR account can mathematically derive addresses on other chains through derivation paths. This isn't just a mapping - it's a cryptographic derivation that ensures the same NEAR account always controls the same set of addresses across all supported chains.
2. **Bridge Smart Contract** - A central contract on NEAR coordinates with the MPC network to generate secure signatures for cross-chain transactions. This contract handles the token locking and requesting of signatures for outbound transfers
3. **MPC Service** - A decentralized network of nodes that jointly sign transactions without ever reconstructing a full private key. The security comes from threshold cryptography - no single node or small group of nodes can create valid signatures alone.
## Putting It All Together
As we've learned, Chain Signatures fundamentally changes the verification mechanism for cross-chain messages. Here's what this means in practice:
The light client approach requires destination chains to verify ED25519 signatures from NEAR validators. Chain Signatures replaces this with a single MPC signature verification. Destination chains only need to verify one signature using their native signature verification schemes - typically ECDSA for EVM chains.
NEP-141's transaction guarantees handle the security of token locking. A transfer out of NEAR takes two steps:
1. The user's transfer to the bridge locks or burns the tokens and records the transfer state
2. A relayer calls `sign_transfer`, which requests the MPC signature for the destination chain
The Locker contract requests signatures from the MPC network, which then generates signatures for valid transfer requests. This replaces the need for challenge periods - the security derives from the MPC threshold guarantees rather than optimistic assumptions.
Adding new chains becomes a matter of implementing three standard components:
1. Chain-specific address derivation
2. MPC signature verification (or transaction signing for chains like Bitcoin)
3. Bridge contract deployment
4. Communication path for transfers back to NEAR (currently using Wormhole for newer chains)
While we still need light clients on NEAR for receiving transfers from other chains, this approach makes it feasible to support a wider range of chains without implementing complex verification logic on each destination chain.
```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
sequenceDiagram
title: High-Level Overview of NEAR to External Chain Transfer
participant User as User Account
participant Bridge as Omni Bridge
Locker Contract
participant MPC as MPC Service
(off-chain)
participant Relayer as Relayer
(off-chain)
participant Other as Destination Chain
note over User, Bridge: NEAR Blockchain
User->>Bridge:1. Submits transfer
token request
Bridge->>Bridge: 2. Locks or burns tokens
Relayer->>Bridge: 3. Calls sign_transfer
Bridge->>MPC: 4. Requests signature
MPC->>MPC: 5. Signs message
MPC-->>Bridge: 6. Returns signed msg
Relayer->>Other: 7. Submits signed msg to destination chain
Other->>Other: 8. Mints or releases tokens
```
To get started building with Omni Bridge, see:
* [Bridge SDK JS](https://github.com/near-one/bridge-sdk-js) Omni Bridge implementation in JavaScript
* [Bridge SDK Rust](https://github.com/near-one/bridge-sdk-rs) Omni Bridge implementation in Rust
# Implementation Details
Source: https://docs.near.org/chain-abstraction/omnibridge/implementation
Explore Omni Bridge's technical architecture
The Omni Bridge is a sophisticated cross-chain bridge infrastructure that enables secure and efficient token transfers between NEAR Protocol and various other blockchain networks. This document provides a detailed technical overview of the bridge's architecture, covering its core components, security model, and operational mechanisms. By leveraging a combination of Multi-Party Computation (MPC), chain-specific light clients, and a relayer network, the bridge achieves a robust balance of security, decentralization, and user experience.
For reference code implementations, see:
* [Bridge SDK JS](https://github.com/near-one/bridge-sdk-js) Omni Bridge implementation in JavaScript
* [Bridge SDK Rust](https://github.com/near-one/bridge-sdk-rs) Omni Bridge implementation in Rust
***
## The Bridge Token Factory Pattern
At the core of Omni Bridge is the Bridge Token Factory contract on NEAR that serves as both a token factory and custodian. This unified contract handles both native tokens from the source chain and bridged tokens created by the factory itself. This design simplifies maintenance and reduces complexity compared to having separate contracts.
The contract has several key responsibilities:
### For bridged tokens (tokens originally from other chains):
* Deploys new token contracts when bridging tokens for the first time
* Mints tokens when receiving valid transfer messages
* Burns tokens when initiating transfers back to the origin chain
### For native NEAR tokens:
* Acts as a custodian by locking tokens during transfers
* Releases tokens when receiving valid transfer messages
* Manages token operations through the NEP-141 standard
### Transfer Lifecycle
A transfer's lifecycle includes several states, shown below for a NEAR to Ethereum transfer of native NEAR tokens:
```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
stateDiagram-v2
[*] --> Initiated: User calls transfer
Initiated --> Locked: Tokens locked in bridge
Locked --> Signed: MPC signature generated
Signed --> Completed: Tokens released on Ethereum
Completed --> [*]
```
***
## Message Signing and Verification
For most chains, the bridge uses a payload-based message signing system (with Bitcoin being a notable exception requiring full transaction signing).
### Message Types
The bridge supports several types of signed messages:
* **Transfer Messages**
* Initiation messages
* Finalization messages
* **Token Messages**
* Deployment messages
* Metadata update messages
### Payload Structure
Messages are encoded using Borsh serialization and contain:
| Component | Description |
| - | - |
| Message Type | Identifier for the message category |
| Chain Info | Chain IDs and relevant addresses |
| Operation Data | Amounts, recipients, fees, etc. |
### Signature Process
1. The bridge contract on NEAR records the transfer when the tokens arrive
2. A relayer calls `sign_transfer`, and the bridge asks the MPC contract (`v1.signer`) to sign the payload
3. The MPC network signs it, and the bridge logs the signature in a `SignTransferEvent`
4. Signature is verified on destination chains
> [!TIP]
>
> **Key Benefits**
>
> * Clearer message intent through structured payloads
> * More efficient signature verification on destination chains
> * Standardized message format across chains
## Transaction Flow: NEAR to Other Chains
Here's an overview of how transfers are processed from NEAR to different destination chains:
```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
flowchart TD
Start[User Initiates Transfer] --> TokenCheck{Token Type?}
TokenCheck -->|NEAR Native| Lock[Lock in Bridge Contract]
TokenCheck -->|Bridged Token| Burn[Burn Token]
Lock --> MPCSign[Request MPC Signature]
Burn --> MPCSign
MPCSign --> Chain{Destination Chain}
Chain -->|Bitcoin| BTCBridge[Bitcoin Script]
Chain -->|Other| OtherBridge[Verify MPC Signature]
BTCBridge --> Mint[Mint/Release Tokens]
OtherBridge --> Mint
Mint --> End[Transfer Complete]
```
### Transfer Process
Let's follow what happens when a user wants to transfer tokens from NEAR to another chain:
#### 1. Initiation
The user starts by calling the token contract with:
* Amount to transfer
* Destination chain and address
* Fee preferences (whether to pay fees in the token being transferred or in NEAR)
* Fees are minted on NEAR side for relayers
#### 2. Token Lock
The token contract transfers tokens to the locker contract, which:
* Validates the transfer message
* Assigns a unique nonce
* Records the pending transfer
* Emits a transfer event
#### 3. MPC Signing
The bridge contract:
* Requests signature generation
* MPC nodes jointly generate and aggregate signature
* Maintains threshold security throughout process
#### 4. Destination Chain
The Bridge Token Factory on the destination chain:
* Verifies the MPC signature
* Mints equivalent tokens
***
## Transaction Flow: Other Chains to NEAR
The reverse flow varies based on the source chain:
### 1. Ethereum
Uses NEAR light client for maximum security:
* Burning tokens on source chain
* Submitting proof to NEAR
* Verifying proof through light client
* Releasing tokens to recipient
### 2. Wormhole Chains (Solana, Fogo, Base, Arbitrum, BNB Chain, Polygon, HyperEVM)
Utilize established message passing protocols (such as Wormhole) for:
* Message passing between chains
* Transaction verification
* Integration with NEAR token factory system
### 3. MPC-Verified Chains (Abstract, Starknet, Aptos)
The bridge's MPC prover asks the MPC network to check the source-chain transaction (`verify_foreign_transaction` on `v1.signer`) and accepts the transfer once the signed result verifies.
***
## Transaction Flow: Chain to Chain (via NEAR)
For transfers between two non-NEAR chains (e.g., Ethereum to Solana), the bridge combines both flows using NEAR as an intermediary routing layer. Rather than minting or unlocking tokens on NEAR, the bridge creates a forwarding message that directs tokens to be minted or unlocked on the final destination chain.
From the user's perspective, this appears as a single operation - they initiate the transfer on the source chain, and the off-chain relayer infrastructure handles the intermediate NEAR routing automatically.
***
## Security Model
### Trust Assumptions
Omni Bridge requires different trust assumptions depending on the chain connection:
#### For Chain Signatures:
* NEAR Protocol security (2/3+ honest validators)
* MPC network security (2/3+ honest nodes)
* No single entity controls enough MPC nodes to forge signatures
* Correct implementation of the signing protocol
#### For Ethereum/Bitcoin connections:
* Light client security
* Finality assumptions (e.g., sufficient block confirmations)
* Chain-specific consensus assumptions
#### For Message Passing connections:
* Security of the underlying message passing protocol (e.g., Wormhole Guardian network)
* Verified by NEAR network participants (e.g., validators and full nodes)
***
## Relayer Network
Relayers are infrastructure operators who monitor for bridge events and execute cross-chain transactions. On NEAR, the relayer steps of `omni.bridge.near` (`sign_transfer`, `fin_transfer`, `claim_fee` and fast transfers) are open only to **trusted relayers**: accounts with the bridge's `DAO` or `UnrestrictedRelayer` role, or accounts that staked the required NEAR with `apply_for_trusted_relayer` and waited out the activation period. `get_relayer_config` returns the stake and the waiting period, and `get_active_relayers` lists the staked relayers. On EVM destination chains, anyone can submit an already-signed transfer to `finTransfer`.
Unlike many bridge designs, our relayers cannot:
* Forge transfers
* Steal funds
* Front-run transactions for profit
* Do not create additional security assumptions
> [!NOTE]
>
> The relayer's role is purely operational - executing valid transfers and collecting predetermined fees. Multiple relayers can operate simultaneously, creating competition for faster execution and lower fees. Relayers are paid from the fee set when a transfer starts, so a transfer with a zero fee may never be signed or finalized.
***
## Fast Transfers
Standard cross-chain transfers can take time due to finality and verification requirements. **Fast Transfers** allow relayers to expedite this process by fronting liquidity.
### How it Works
1. **User Initiation:** A user sends a `FastFinTransferMsg` specifying the destination and fee.
2. **Relayer Execution:** A trusted relayer detects the request and instantly transfers the equivalent amount (minus fees) to the user on the destination chain from their own funds.
3. **Settlement:** The bridge later reimburses the relayer once the original transfer is fully verified and finalized.
> [!TIP]
>
> Fast transfers are ideal for users who prioritize speed over cost, as relayers may charge a premium for the liquidity and convenience.
***
## Multi-Token Support (ERC1155)
Omni Bridge supports the **ERC1155** standard, enabling the transfer of multiple token types within a single contract.
### Address Derivation
To maintain consistency across chains, bridged ERC1155 tokens use a deterministic address derivation scheme:
* **Deterministic Address:** `keccak256(tokenAddress + tokenId)`
* This ensures that each `tokenId` within an ERC1155 contract maps to a unique, consistent address on the destination chain.
### Key Functions
* **`initTransfer1155`**: Initiates a transfer for a specific ERC1155 token ID.
* **`logMetadata1155`**: Registers metadata for a specific token ID, ensuring it is recognized by indexers and wallets.
***
## Fee Structure
Bridge fees are unified and processed on NEAR, with components including:
### Execution Fees
* Destination chain gas costs
* Source chain storage costs
* Relayer operational costs
* MPC signing costs
### Fee Payment Options
* Native tokens of source chain
* The token being transferred
> [!NOTE]
>
> Fees dynamically adjust based on gas prices across different chains to ensure reliable execution.
### Design Goals
The fee structure is designed to:
* Ensure relayer economic viability
* Prevent economic attacks
* Allow fee market competition
* Cover worst-case execution costs
> [!TIP]
>
> On EVM destination chains, users can submit an already-signed transfer themselves, paying only that chain's gas. The steps on NEAR (signing an outbound transfer, finalizing an inbound one) need a trusted relayer.
# Omni Bridge Overview
Source: https://docs.near.org/chain-abstraction/omnibridge/overview
Learn about Omni Bridge, a multi-chain asset bridge that enables secure and efficient transfers between blockchain networks using Chain Signatures and MPC technology.
The [Omni Bridge](https://github.com/Near-One/omni-bridge) is a multi-chain asset bridge that facilitates secure and efficient asset transfers between different blockchain networks. It solves key challenges in cross-chain communication by leveraging [Chain Signatures](/chain-abstraction/chain-signatures) and its decentralized [Multi-Party Computation (MPC) service](/chain-abstraction/chain-signatures#multi-party-computation-service) to enable trustless cross-chain asset transfers.
> [!TIP]
>
> To learn more see [How Omni Bridge Works](./how-it-works).
## Supported Chains
Omni Bridge launches with a hybrid architecture, utilizing different verification methods based on chain-specific requirements and technical constraints. This approach allows us to support multiple chains from day one while progressively transitioning to full Chain Signatures integration.
Currently the supported chains are:
* **Ethereum** - *(Light client + Chain Signatures)*
* **Bitcoin** - *(Light client + Chain Signatures)*
* **Zcash** - *(Light client + Chain Signatures)*
* **Solana** - *(Wormhole + Chain Signatures)*
* **Base** - *(Wormhole + Chain Signatures)*
* **BNB** - *(Wormhole + Chain Signatures)*
* **Arbitrum** - *(Wormhole + Chain Signatures)*
* **Polygon** - *(Wormhole + Chain Signatures)*
* **HyperEVM** - *(Wormhole + Chain Signatures)*
* **Fogo** - *(Wormhole + Chain Signatures)*
* **Abstract** - *(MPC verification + Chain Signatures)*
* **Starknet** - *(MPC verification + Chain Signatures)*
* **Aptos** - *(MPC verification + Chain Signatures)*
The bridge contract lists how each chain's inbound transfers are verified. Read it with:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-read-only omni.bridge.near get_provers json-args {} network-config mainnet now
```
Bitcoin and Zcash are listed by `get_utxo_chain_connectors` instead.
> [!NOTE]
>
> See [Omni Bridge Roadmap](./roadmap) for more details.
## Resources
* [Near-One/omni-bridge](https://github.com/Near-One/omni-bridge) - Omni Bridge repository
* [Near-One/bridge-sdk-js](https://github.com/Near-One/bridge-sdk-js) - JavaScript SDK
* [Near-One/bridge-sdk-rs](https://github.com/Near-One/bridge-sdk-rs) - Rust SDK
# Omni Bridge Roadmap
Source: https://docs.near.org/chain-abstraction/omnibridge/roadmap
Explore the Omni Bridge roadmap, including hybrid architecture launch, Chain Signatures migration path, and future development plans for cross-chain infrastructure.
Omni Bridge launches with a hybrid architecture, utilizing different verification methods based on chain-specific requirements and technical constraints. This approach allows us to support multiple chains from day one while progressively transitioning to full Chain Signatures integration.
## Supported Chains
The bridge currently supports the following networks:
* **EVM Chains:**
* Ethereum
* Base
* Arbitrum
* BNB Chain
* Polygon (PoS)
* Abstract
* HyperEVM
* **Non-EVM Chains:**
* Bitcoin
* Solana
* Zcash
* Starknet
* Aptos
* Fogo
## Architecture Overview
Omni Bridge utilizes **Chain Signatures** as its primary verification mechanism for outbound transfers from NEAR. Incoming transfers rely on chain-specific verification methods, including light clients for maximum security where available.
### Verification Methods
* **Ethereum, Bitcoin & Zcash:** Light Client verification for inbound transfers.
* **Abstract, Starknet & Aptos:** the MPC network checks the source-chain transaction (`verify_foreign_transaction` on `v1.signer`).
* **Other Chains:** Message passing protocols (Wormhole) verified by the NEAR network.
* **Outbound (All Chains):** Chain Signatures (MPC) for secure transaction signing.
## Future Development
1. **Protocol Improvements**
* Enhanced fee mechanisms
* Cross-chain contract calls
* New token standards support
Beyond basic asset transfers, we're expanding the bridge's capabilities. Enhanced fee mechanisms will better handle gas price volatility, while cross-chain contract calls will enable more complex interactions.
2. **Infrastructure**
* Expanded relayer network
* Improved monitoring tools
* Enhanced developer tooling
Infrastructure development focuses on reliability and usability. An expanded relayer network improves transfer speeds and reliability, while better monitoring and developer tools make integration and maintenance easier.
## Get Involved
### Areas for Contribution
* Chain integrations
* Performance optimization
* Security analysis
* Developer tools
* [Near-One/omni-bridge](https://github.com/Near-One/omni-bridge) - Omni Bridge repository
* [Near-One/bridge-sdk-js](https://github.com/Near-One/bridge-sdk-js) - JavaScript SDK
* [Near-One/bridge-sdk-rs](https://github.com/Near-One/bridge-sdk-rs) - Rust SDK and Bridge CLI
The code is open source and we welcome contributions from the community. Whether you're interested in adding support for new chains, optimizing performance, or building developer tools, there's room for meaningful contribution.
Bridge infrastructure is a fundamental component of a multi-chain future. Through Chain Signatures, we're creating a more efficient, secure, and scalable approach to cross-chain communication. Join us in building it.
# What is Chain Abstraction?
Source: https://docs.near.org/chain-abstraction/what-is
Learn how NEAR allows you to seamlessly work across all chains
Through a combination of innovative technologies, NEAR enables developers to build applications that work seamlessly across multiple blockchains while abstracting away the underlying complexity for both developers and end users.
> [card] [Multi-Chain Accounts](./chain-signatures)
>
> Chain Signatures allow NEAR accounts **and smart contracts** to sign transactions for all other chains (including Bitcoin, Ethereum and Solana)
> [card] [Swaps via Intents](./intents/overview)
>
> A decentralized system where users simply **express desired outcomes** (like "swap BTC for ETH at the best price"), and a network of solvers competes to fulfill these intents optimally
> [card] [OmniBridge](./omnibridge/overview)
>
> A multi-chain bridge that enables secure and efficient cross-chain transfers. The bridge serves as both a token factory and custodian, managing native and bridged tokens through a unified interface
***
## Why Chain Abstraction Matters
By building on NEAR, developers do not need to worry about the complexities of integrating with multiple blockchains. Instead, they can focus on building great applications that work seamlessly across all chains.
Meanwhile, users can enjoy a smooth experience, using unified accounts and assets without needing to even understand on which blockchain they are operating.
> [card] Benefits for Developers
>
> * Integrate with multiple blockchains through a single NEAR API
> * Focus on application logic instead of blockchain complexity
> * Reach users regardless of their preferred blockchain network
> [card] Benefits for Users
>
> * Operate across all chains using a single NEAR account
> * Access assets and services from multiple blockchains seamlessly
> * Enjoy a unified and intuitive user experience
> [accordion] Example: Cross-Chain NFT Marketplace
>
> Imagine building a digital art marketplace where users can purchase NFTs from different blockchains (Ethereum, Solana, etc.). Without chain abstraction, you'd need to:
>
> * Implement multiple blockchain connections
> * Handle different wallet types
> * Manage cross-chain transfers
> * Build complex UIs to explain blockchain concepts
>
> With chain abstraction, both you and your users just focus on the core experience: browsing and trading art. All blockchain complexity is handled automatically behind the scenes.
# Communities
Source: https://docs.near.org/communities
Connect with the NEAR community through various channels and join specialized communities.
NEAR is a global community of Web3 enthusiasts and innovators. Connect with developers, builders, and founders across our social channels.
> [card] [Telegram](https://t.me/neardev)
> [card] [Discord](https://discord.gg/RhZGHPXPf2)
> [card] [GitHub](https://github.com/near)
> [card] [X](https://twitter.com/nearprotocol)
***
## Frequently Asked Questions
> [accordion] What is the expectation for a support resolution?
>
> Upon submitting a support ticket, you can expect to receive an initial response from our team within 72 hours during our business hours. Our business hours are on weekdays in the PST timezone, excluding US holidays.
> [accordion] Where can I find help to troubleshoot a development issue?
>
> Social channels such as [Telegram](https://t.me/neardev) and [Discord](https://discord.gg/RhZGHPXPf2) are a great resource to tap into for community support on development issues.
> [accordion] Where can I find funding for my project?
>
> You can find information on grants and funding opportunities on the [main NEAR portal](https://www.near.org/funding).
> [accordion] How can I find out about the latest product developments?
>
> Follow [NEAR on X](https://twitter.com/nearprotocol) for our latest product announcements.
> [accordion] I found a bug — where can I flag this?
>
> For any issues or concerns you've encountered, please feel free to provide us with detailed information through our [Bug Bounty Program](https://hackenproof.com/near). Your cooperation and additional details will assist us in addressing and resolving any potential vulnerabilities effectively. We appreciate your proactive approach in helping us maintain the security and integrity of the NEAR ecosystem.
> [accordion] What happened to Near Wallet?
>
> wallet.near.org is now a wallet hub: a curated list of the wallets available in our ecosystem. Your funds are safe! Accounts exist on the blockchain, not in a wallet. Wallets are just an interface into using the blockchain with your account, so you can import your account into any of the [available wallets](https://wallet.near.org/)
> [accordion] Question about Transfer Exchange?
>
> For issues relating to a third-party exchange, such as Binance or Coinbase, we're unable to investigate issues on external platforms. To address your concern effectively, we recommend contacting the customer support team of the specific exchange where you're experiencing issues. They are most equipped to assist you in resolving the matter.
# BigQuery Public Dataset
Source: https://docs.near.org/data-infrastructure/big-query
Learn how to use NEAR Protocol's BigQuery public dataset for blockchain data analysis, including querying on-chain data, understanding costs, and accessing historical transaction data.
This document provides an overview of the BigQuery public dataset that allows users to query historical on-chain data from the NEAR Protocol. It includes setup instructions, example queries, and information about the available data structures.
> [accordion] Common use cases
>
> * **Query NEAR on-chain data with SQL:** analyze transactions, accounts and events without running your own indexer.
> * **Analyze historical activity at scale:** track token transfers, contract usage or user activity across the whole chain history.
# NEAR Public Lakehouse
Blockchain data indexing in NEAR Public Lakehouse is for anyone wanting to understand blockchain data. This includes:
* **Users**: create queries to track NEAR assets, monitor transactions, or analyze on-chain events at a massive scale.
* **Researchers**: use indexed data for data science tasks, including on-chain activities, identifying trends, or feeding AI/ML pipelines for predictive analysis.
* **Startups**: can use NEAR's indexed data for deep insights on user engagement, smart contract utilization, or insights across tokens and NFT adoption.
Benefits:
* **NEAR instant insights**: Historical on-chain data queried at scale.
* **Cost-effective**: eliminate the need to store and process bulk NEAR protocol data; query as little or as much data as preferred.
* **Easy to use**: no prior experience with blockchain technology is required; bring a general knowledge of SQL to unlock insights.
## Getting started
1. Login into your [Google Cloud Account](https://console.cloud.google.com/).
2. Open the [NEAR Protocol BigQuery Public Dataset](https://console.cloud.google.com/bigquery?p=bigquery-public-data\&d=crypto_near_mainnet_us\&page=dataset).
3. Click in the VIEW DATASET button.
4. Click in the + to create a new tab and write your query, click in the RUN button, and check the `Query results` below the query.
5. Done :)
> [!NOTE]
>
> The [NEAR Public Lakehouse repository](https://github.com/near/near-public-lakehouse) contains the source code for ingesting NEAR Protocol data stored as JSON files in AWS S3 by [NEAR Lake Indexer](https://github.com/near/near-lake-indexer).
> [!WARNING]
>
> **NEAR Lake (the AWS S3 source) was deprecated on March 24, 2026** and no longer indexes new blocks. The NEAR Public Lakehouse / BigQuery dataset itself remains available; check the [NEAR Public Lakehouse repository](https://github.com/near/near-public-lakehouse) for the latest ingestion source.
### Example Queries
* *How many unique signers and accounts have interacted with my smart contract per day?*
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
SELECT
ra.block_date collected_for_day,
COUNT(DISTINCT t.signer_account_id) as total_signers,
COUNT(DISTINCT ra.receipt_predecessor_account_id) as total_accounts
FROM `bigquery-public-data.crypto_near_mainnet_us.receipt_actions` ra
JOIN `bigquery-public-data.crypto_near_mainnet_us.receipt_origin_transaction` ro ON ro.receipt_id = ra.receipt_id
JOIN `bigquery-public-data.crypto_near_mainnet_us.transactions` t ON ro.originated_from_transaction_hash = t.transaction_hash
WHERE ra.action_kind = 'FUNCTION_CALL'
AND ra.receipt_receiver_account_id = 'social.near' -- change to your contract
GROUP BY 1
ORDER BY 1 DESC;
```
## How much it costs?
* NEAR pays for the storage and doesn't charge you to use the public dataset.
> To learn more about BigQuery public datasets [check this page](https://cloud.google.com/bigquery/public-data).
* Google GCP charges for the queries that you perform on the data. For example, in today's price "Sep 1st, 2023" the On-demand (per TB) query pricing is \$6.25 per TB where the first 1 TB per month is free.
> Check [Google's pricing page](https://cloud.google.com/bigquery/pricing#analysis_pricing_models) for detailed pricing info, options, and best practices.
> [!TIP]
>
> You can check how much data it will query before running it in the BigQuery console UI. Again, since BigQuery uses a columnar data structure and partitions, it's recommended to select only the columns and partitions (`block_date`) needed to avoid unnecessary query costs.

## Architecture
The data is loaded in a streaming fashion using [Databricks Autoloader](https://docs.gcp.databricks.com/ingestion/auto-loader/index.html) into raw/bronze tables, and transformed with [Databricks Delta Live Tables](https://www.databricks.com/product/delta-live-tables) streaming jobs into cleaned/enriched/silver tables.
The silver tables are also copied into the [GCP BigQuery Public Dataset](https://cloud.google.com/bigquery/public-data).

> [!NOTE]
>
> [Databricks Medallion Architecture](https://www.databricks.com/glossary/medallion-architecture).
## Available Data
The current data that NEAR is providing was inspired by [NEAR Indexer for Explorer](https://github.com/near/near-indexer-for-explorer/).
> [!NOTE]
>
> NEAR plans to improve the data available in the NEAR Public Lakehouse making it easier to consume by denormalizing some tables.
The tables available in the NEAR Public Lakehouse are:
* **blocks**: A structure that represents an entire block in the NEAR blockchain. `Block` is the main entity in NEAR Protocol blockchain. Blocks are produced in NEAR Protocol every second.
* **chunks**: A structure that represents a chunk in the NEAR blockchain. `Chunk` of a `Block` is a part of a `Block` from a `Shard`. The collection of `Chunks` of the `Block` forms the NEAR Protocol Block. `Chunk` contains all the structures that make the `Block`: `Transactions`, [`Receipts`](https://nomicon.io/RuntimeSpec/Receipts), and `Chunk Header`.
* **transactions**: `Transaction` is the main way of interaction between a user and a blockchain. Transaction contains: Signer account ID, Receiver account ID, and Actions.
* **execution\_outcomes**: Execution outcome is the result of execution of `Transaction` or `Receipt`. In the result of the Transaction execution will always be a Receipt.
* **receipt\_details**: All cross-contract (we assume that each account lives in its own shard) communication in Near happens through Receipts. Receipts are stateful in a sense that they serve not only as messages between accounts but also can be stored in the account storage to await `DataReceipts`. Each receipt has a `predecessor_id` (who sent it) and `receiver_id` the current account.
* **receipt\_origin**: Tracks the transaction that originated the receipt.
* **receipt\_actions**: Action Receipt represents a request to apply actions on the `receiver_id` side. It could be derived as a result of a `Transaction` execution or another `ACTION` Receipt processing. Action kind can be: `ADD_KEY`, `CREATE_ACCOUNT`, `DELEGATE_ACTION`, `DELETE_ACCOUNT`, `DELETE_KEY`, `DEPLOY_CONTRACT`, `FUNCTION_CALL`, `STAKE`, `TRANSFER`.
* **receipts (view)**: It's recommended to select only the columns and partitions (`block_date`) needed to avoid unnecessary query costs. This view join the receipt details, the transaction that originated the receipt and the receipt execution outcome.
* **account\_changes**: Each account has an associated state where it stores its metadata and all the contract-related data (contract's code + storage).
> [!NOTE]
>
> **Additional information about the data**
>
> * Skipped Blocks: NEAR Blockchain can contain skipped blocks, e.g. block `57730443`. For these cases we can find the block for the chunk data using the `prev_block_hash` column, e.g. `SELECT * FROM chunks c JOIN blocks b ON c.chunk.header.prev_block_hash = b.header.prev_hash`.
> [!NOTE]
>
> **References**
>
> * [Protocol documentation](/getting-started/what-is-near)
> * [Near Data flow](/protocol/data-flow/near-data-flow)
> * [Protocol specification](https://nomicon.io/)
# Data APIs
Source: https://docs.near.org/data-infrastructure/data-api
Explore community-built APIs for accessing on-chain data
If you are building a decentralized applications, chances are that you will need to query on-chain data. Since building a full indexer is not always feasible, the community has created a set of APIs that you can use to query data from the NEAR blockchain.
These APIs provide a simple way to access on-chain data without having to run your own indexer or node. They are designed to be easy to use and provide a wide range of functionality, from querying account balances to exploring transactions and blocks.
***
## FastNEAR API
The [FastNEAR API](https://github.com/fastnear/fastnear-api-server-rs?tab=readme-ov-file#api-v1) allows to easily query the NEAR blockchain to get an account's assets, map keys into account IDs, explore a block's transactions, etc.
Possible use cases include:
* Querying all assets of an account (including fungible and non-fungible tokens)
* Querying the last block produced
* Mapping Public Key to Account ID
* Mapping Full Access Public Key to Account ID
* Knowing a user's staking pools (validators)
* Querying the top holders of a token
#### Examples
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Query user's FTs
curl https://api.fastnear.com/v1/account/root.near/ft
# Query user's NFTs
curl https://api.fastnear.com/v1/account/root.near/nft
# Query all user's assets
curl https://api.fastnear.com/v1/account/root.near/full
```
***
## NearBlocks API
[NearBlocks API](https://api.nearblocks.io/api-docs/) provides an endpoint to query actions that happened on a NEAR account, possible use cases include:
* Query an account balance
* Query all function calls to specific contract
* Get total NEAR supply and circulating supply
* Query the number of total transactions on NEAR
#### Examples
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# All the transactions where somebody called `create_drop` on Keypom
curl -X GET "https://api.nearblocks.io/v1/account/v2.keypom.near/txns?method=create_drop"
# All the times that `gagdiez.near` called `create_drop` on Keypom
curl -X GET "https://api.nearblocks.io/v1/account/v2.keypom.near/txns?method=create_drop&from=gagdiez.near"
```
***
## Pikespeak API
The [Pikespeak API](https://doc.pikespeak.ai/) allows you to fetch blockchain events and aggregated analytics on wallets, validators, delegators, money transfers, dApps activity, and more.
Use case includes:
* Querying account balances
* Querying the most active wallets
* Querying historic account events
*To access the Pikespeak API you'll need to [register and create an account](https://pikespeak.ai/plans). Once you're registered, under the [`My Account`](https://pikespeak.ai/myaccount) page you can get your API key*
#### Examples
```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Check the account balance for `root.near`:
curl -X GET https://api.pikespeak.ai/account/balance/root.near -H "accept: application/json" -H "x-api-key: YOUR-PIKESPEAK-API-KEY"
# Most active wallets NEAR senders
curl -X GET https://api.pikespeak.ai/hot-wallets/near -H "accept: application/json" -H "x-api-key: YOUR-PIKESPEAK-API-KEY"
# Get historic account events for `keypom.near`
curl -X GET https://api.pikespeak.ai/event-historic/keypom.near -H "accept: application/json" -H "x-api-key: YOUR-PIKESPEAK-API-KEY"
```
***
## The Graph
[The Graph](https://thegraph.com/docs/en/cookbook/near/) gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts.
***
## SubQuery
[SubQuery](https://academy.subquery.network/quickstart/quickstart_chains/near.html): A fast, flexible, and reliable open-source data indexer that provides you with custom APIs for your web3 project across NEAR and many other chains
# Data Services
Source: https://docs.near.org/data-infrastructure/data-services
Indexers are constantly listening for transactions and storing them so they can be easily queried.
Data Services are constantly listening to the blockchain, processing the transactions and storing them in a database that can be easily queried. You can use them to access blockchain data efficiently:
* [Neardata](https://docs.fastnear.com/neardata): block data delivered over HTTP for your custom indexer.
* [BigQuery](./big-query): Blockchain data indexing in NEAR Public Lakehouse is for anyone wanting to understand blockchain data.
* [Indexer.xyz Multichain Indexer](https://indexer.xyz/): Indexer.xyz is an application layer that you can build your NFT or DeFi applications entirely on top of. In addition to raw transaction indexing, Indexer.xyz provides you with a standardized GraphQL API layer to easily tap into transactions across contracts and chains.
* [The Graph](https://thegraph.com/docs/en/cookbook/near/): development tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is able to process NEAR events, which means that NEAR developers can build subgraphs to index their smart contracts.
* [GetBlock](https://getblock.io/explorers/near/blocks/): developer tools offering a simple and reliable API access for historical data streams and other services for NEAR.
* [Community APIs](./data-api): build precise & reliable dApps with our community's APIs.
* [Covalent](https://goldrush.dev/docs/networks/): for [Aurora EVM](https://aurora.dev/) indexing, Covalent provides a unified API bringing visibility to billions of Web3 data points.
* [NEAR Indexer Framework](https://github.com/near/nearcore/tree/master/chain/indexer): a micro-framework providing you with a "live" stream of blocks. Useful to handle on-chain real-time `events`.
* [SubQuery](https://academy.subquery.network/quickstart/quickstart_chains/near.html): is an end to end multi-blockchain indexing solution that provides NEAR developers with fast, flexible, universal, open source and decentralized APIs for web3 projects. The [NEAR starter project](https://github.com/subquery/near-subql-starter/tree/main/Near/near-starter) provides a template for developers to get up and running within minutes.
* [GoldSky](https://docs.goldsky.com/chains/near): a hosted data platform that supports NEAR mainnet via **Mirror** (real-time data replication into your own infrastructure) and **Turbo** (high-performance streaming pipelines with sub-second latency). No infrastructure to manage — connect your data destination and start streaming on-chain data immediately.
# Introduction to Indexers
Source: https://docs.near.org/data-infrastructure/indexers
Learn about blockchain indexers, how they work with NEAR Protocol, the difference between pull and push models, and when to use indexers for data querying.
Here you will find everything you need to know in order to familiarize yourself with the concept of indexers.
> [!NOTE]
>
> We recommend checking the [NEAR Data Flow](../protocol/data-flow/near-data-flow) to familiarize yourself with how data flows within the NEAR ecosystem
***
## Blockchains and their nature
Blockchain data is optimized for serialized **writes**, one block at a time, as the chain is being created. Querying the blockchain for data about a specific block or account is fairly straightforward, as only the data for a specific block needs to be retrieved.
However, querying data across many blocks (e.g. `all transfers between date X and Y`) can be cumbersome because we have to aggregate results from multiple single-block queries.
Given the fact that a blockchain itself is a distributed database, and a smart contract (decentralized application, dApp) is an application that runs on a virtual machine inside a blockchain, we need to understand that smart contracts should *not* be considered as a "backend". While some applications might consist only of smart contracts, building a dApp with only smart contracts, in most cases, is not possible.
Smart contracts are limited in terms of interactions. By "interactions" we mean things that are very common in the real world, like user notifications, integration with third-party applications, etc.
However, the nature of a blockchain is that it *must* be deterministic. A critical feature of a blockchain is that it knows the state at a given time, and for blockchains that time unit is a block. Think of them as being snapshots. A blockchain does snapshots of its state on every block. We as users can call smart contracts for a specific block, and the blockchain provides guarantees that execution will always produce the same result for the same block any time we call it.
The deterministic nature of a blockchain closes it from external (off-chain) variables. It is totally impossible to perform a call to an API from within a smart contract. A blockchain and a smart contract are closed off from the external (off-chain) world.

Blockchains are great at providing a way to apply the requested changes to the state in a decentralized manner. However, in order to observe the changes, you need to actively pull the information from the network.
Instead of abstract explanations let's look at an example.
> [!NOTE]
>
> **Example dApp**
>
> Say, we have a smart contract that sells e-books. Once a user buys a book we want to send them a copy via email.
The dApp has a helper deployed somewhere off-chain, and this helper has code that can send an email with a copy of an e-book. But how would we trigger the helper?
***
## Getting the data from a blockchain from the external world
NEAR blockchain implements a [JSON-RPC endpoint](/api/rpc/introduction) for everyone to interact with the blockchain. Through the JSON-RPC API users can call smart contracts triggering them to be executed with given parameters. Also, users can view the data from the blockchain.
So, continuing with our example we can make our helper pull a [Block](/api/rpc/block-chunk#block-details) every second, then pull all the [Chunks](/api/rpc/block-chunk#chunk-details) and analyze the Transactions included in the Block to check if there is a transaction to our smart contract with "buy an e-book" function call. If we observe such a Transaction, we need to ensure it is successful, so we don't send the e-book to a user whose "buy e-book" Transaction failed.
After the process is complete we can trigger the helper's code to send the user an email with the e-book they bought.
This approach is so-called *pull model* of getting the data. There is nothing wrong with this approach, but sometimes you might find it is not the most comfortable or reliable approach.
Also, not all the data is available through the JSON-RPC. *Local Receipts* for example are not available through the JSON-RPC, because they are not stored in NEAR node's internal database.
***
## Indexer
A blockchain indexer is an implementation of the *push model* of getting the data. Instead of actively pulling the data from the source, your helper waits for the data to be sent to it. The data is complete and so the helper can start analyzing it immediately; ideally the data is complete enough to avoid additional pulls to get more details.
Getting back to our example, the helper becomes **an indexer** that receives every *Block*, along with **Chunks**, **Transactions** with its statuses, etc. In the same way the helper analyzes the data and triggers the code to send the user an email with the e-book they bought.

> [!NOTE]
>
> **An indexer concept**
>
> An indexer listens to the *stream of data as it's being written on chain* and can then be immediately filtered and processed to detect interesting events or patterns.
***
## Indexers and "wide" queries
The term *"wide" queries* was mentioned in the beginning of this document. Here's a recap:
> [!NOTE]
>
> **"Wide" queries definition**
>
> To query data across many blocks requires the aggregation of results from multiple single-block queries. We can consider these aggregates as coming from *"wide" queries*.
Because indexers listen to the *stream of data* from the blockchain and the data can be immediately filtered and processed according to defined requirements, they can be used to simplify the "wide" queries execution. For example, a stream of data can be written to a permanent database for later data analysis using a convenient query language like SQL.
Another example that highlights the need for a "wide query" is when you use a seed phrase to recover one or more accounts. Since a seed phrase essentially represents a signing key pair, the recovery is for all accounts that share the associated public key. Therefore, when a seed phrase is used to recover an account via [NEAR Wallet](https://wallet.near.org), the query requires that all accounts with a matching public key are found and recovered. An indexer can store account and access-key changes in a permanent database, allowing a wallet to perform such "wide queries". This is impossible to achieve using JSON-RPC only.
***
## Indexers in the NEAR ecosystem
For a custom indexer that consumes hosted block data, use [Neardata](https://docs.fastnear.com/neardata). Your application fetches blocks over HTTP and processes the data it needs.
If speed is critical for your indexing needs, consider using [Near Indexer](./near-indexer). However, please note that maintaining it can be more complex and costly, as it essentially operates as an independent node in the network.
If you prefer not to host your own solution, you can utilize [third-party services](./data-services).
***
## Summary
We hope this article gives you an understanding of the Indexer concept. Also, we hope now you can easily decide whether you need an indexer for your application.
***
## What's next?
See [Neardata](https://docs.fastnear.com/neardata) for hosted block data, or follow the [nearcore indexer tutorial](/data-infrastructure/tutorials/near-indexer) to process blocks from your own node.
Alternatively, there are a few other third-party indexers that are tightly integrated with the NEAR ecosystem. You can review all of your data sourcing options (including The Graph, Pikespeak, SubQuery, and GoldSky) under [indexing tools](./data-services).
# What is NEAR Indexer?
Source: https://docs.near.org/data-infrastructure/near-indexer
A framework to handle real-time events on the blockchain
As scaling dApps enter NEAR’s mainnet, an issue may arise: how do they quickly and efficiently access state from our deployed smart contracts, and cut out the cruft? Contracts may grow to have complex data structures and querying the network RPC may not be the optimal way to access state data.
The [NEAR Indexer](https://github.com/near/nearcore/tree/master/chain/indexer) is a micro-framework specifically designed to handle real-time events on the blockchain, allowing to capture and index streams of blocks in a customized manner.
With the NEAR Indexer, developers can perform both high-level data aggregation and low-level introspection of blockchain events.
> [!TIP]
>
> To ingest blocks without operating a NEAR node, use [Neardata](https://docs.fastnear.com/neardata) as the data source for your indexer.
***
## How It Works
The NEAR Indexer works by **running a node** and processing blocks as they are added to the blockchain. The framework provides a stream of blocks, allowing developers to subscribe and process these blocks in real-time.
> [!TIP]
>
> Learn how to run it following the [tutorial](./tutorials/near-indexer).
# Tutorial: Creating an Indexer
Source: https://docs.near.org/data-infrastructure/tutorials/near-indexer
This tutorial will guide you through building an indexer using the NEAR Indexer Framework. The indexer will listen for FunctionCalls on a specific contract and log the details of each call.
In this tutorial, we will build an indexer using the NEAR Indexer Framework. The indexer will listen realtime blocks data from NEAR blockchain.
To get our indexer up and running we will need two steps:
1. To [initialize](#initialization) the indexer
2. To [start it](#starting-the-indexer)
The full source code for the indexer example is available in the [GitHub repository](https://github.com/near/nearcore/tree/master/tools/indexer/example).
> [!NOTE]
>
> Source code link is for `nearcore` repository, as the Indexer Framework is part of the `nearcore` codebase. We provide the link to `master` branch. If you want to use **the latest stable release version** you should check the [releases page](https://github.com/near/nearcore/releases) and checkout the corresponding tag.
> [!CAUTION]
>
> NEAR Indexer Framework only works on **`Linux x86`**, it does **not** support Windows or MacOS
***
## Prerequisites
### Install Rust
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```
### Install developer tools
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
apt update
apt install -y git binutils-dev libcurl4-openssl-dev zlib1g-dev libdw-dev libiberty-dev cmake gcc g++ python docker.io protobuf-compiler libssl-dev pkg-config clang llvm cargo awscli
```
> [!CAUTION]
>
> NEAR Indexer Framework only works on **`Linux x86`**, it does **not** support Windows or MacOS
### Clone nearcore repository
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
git clone git@github.com:near/nearcore.git
```
***
## Initialization
In order for our indexer to process blocks it needs to join the NEAR network as a node. To do that, we need first to initialize it, which will download the blockchain `genesis` config, and create a `key` for our node to communicate with other nodes.
Go to the `nearcore/tools/indexer/example` folder and build the indexer:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cd nearcore/tools/indexer/example && cargo build --release
```
Then, run the following command to initialize the network configuration:
> [tab] Localnet
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> cargo run --release -- --home-dir ~/.near/localnet init
> ```
> [tab] Testnet
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> cargo run --release -- --home-dir ~/.near/testnet init --chain-id testnet --download-config rpc --download-genesis
> ```
> [tab] Mainnet
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> cargo run --release -- --home-dir ~/.near/mainnet init --chain-id mainnet --download-config rpc --download-genesis
> ```
Depending on the network we want to connect, the keys will be created in different folders (`~/.near/`).
#### Config File
A configuration file (`~/.near//config.json`) is created automatically, whoever, it is recommended to replace with one of the following ones, intended for RPC nodes:
* [testnet config.json](https://s3-us-west-1.amazonaws.com/build.nearprotocol.com/nearcore-deploy/testnet/rpc/config.json)
* [mainnet config.json](https://s3-us-west-1.amazonaws.com/build.nearprotocol.com/nearcore-deploy/mainnet/rpc/config.json)
> [!NOTE]
>
> **Configuration Options**
>
> See the [Custom Configuration](#custom-configuration) section below to learn more about further configuration options.
***
## Starting the Indexer
After we finish initializing the indexer, and configuring it, we can start it by running the following command:
> [tab] Localnet
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> cargo run --release -- --home-dir ~/.near/localnet run
> ```
> [tab] Testnet
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> cargo run --release -- --home-dir ~/.near/testnet run
> ```
> [tab] Mainnet
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> cargo run --release -- --home-dir ~/.near/mainnet run
> ```
> [accordion] How it works
>
> * The command initializes the indexer's configuration: home directory, sync mode, streaming mode, finality, etc.
> * Creates a Tokio runtime on a dedicated thread.
> * Creates an instance of the Indexer using the provided configuration, starts it, and streams blocks to our handler. Within the handler (`listen_blocks` method), there is an infinite loop that parses block data for each new block received.
>
> ```rust title="main.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> let indexer_config = near_indexer::IndexerConfig {
> home_dir,
> sync_mode: near_indexer::SyncModeEnum::FromInterruption,
> await_for_node_synced: near_indexer::AwaitForNodeSyncedEnum::WaitForFullSync,
> finality: near_primitives::types::Finality::Final,
> validate_genesis: true,
> skip_broken_blocks: false,
> };
> let tokio_runtime = tokio::runtime::Builder::new_current_thread()
> .enable_all()
> .build()
> .expect("Failed to create Tokio runtime");
> tokio_runtime.block_on(async move {
> let indexer =
> near_indexer::Indexer::new(indexer_config).await.expect("Indexer::new()");
> let stream = indexer.streamer();
> listen_blocks(stream).await;
> });
> }
> ```
>
> [See code on GitHub](https://github.com/near/nearcore/blob/6ac40f1a7806598f26e8e8593b51b3214b9e3f5f/tools/indexer/example/src/main.rs#L271-L289)
#### Run into an Error?
* If your indexer cannot find `boot nodes`, check the [boot nodes](#boot-nodes) section
***
## Parsing the Block Data
Within the `listen_blocks` method, we can parse the block data as it flows from the stream. From the block data, we can access the transactions, their receipts, and actions. See the code below for an example of how to parse the block data:
```rust title="main.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
while let Some(streamer_message) = stream.recv().await {
// TODO: handle data as you need
// Example of `StreamerMessage` with all the data (the data is synthetic)
//
// Note that `outcomes` for a given transaction won't be included into the same block.
// Execution outcomes are included into the blocks after the transaction or receipt
// are recorded on a chain; in most cases, it is the next block after the one that has
// the transaction or receipt.
//
// StreamerMessage {
// block: BlockView {
// author: "test.near",
// header: BlockHeaderView {
// height: 63596,
// epoch_id: `Bk7pvZWUTfHRRZtfgTDjnQ6y5cV8yG2h3orCqJvUbiym`,
// next_epoch_id: `3JuBZ4Gz5Eauf7PzQegfqSEDyvws3eKJYPbfGHAYmeR5`,
// hash: `5X37niQWWcihDGQjsvDMHYKLCurNJyQLxCeLgneDb8mk`,
// prev_hash: `2vJNJca72pBiq2eETq2xvuoc6caKDaUkdRgtdefyutbA`,
// prev_state_root: `GkdxSBf4Kfq8V16N4Kqn3YdcThG1f5KG1KLBmXpMzP1k`,
// chunk_receipts_root: `9ETNjrt6MkwTgSVMMbpukfxRshSD1avBUUa4R4NuqwHv`,
// chunk_headers_root: `C7dVr9KdXYKt31yF2BkeAu115fpo79zYTqeU3FzqbFak`,
// chunk_tx_root: `7tkzFg8RHBmMw1ncRJZCCZAizgq4rwCftTKYLce8RU8t`,
// outcome_root: `7tkzFg8RHBmMw1ncRJZCCZAizgq4rwCftTKYLce8RU8t`,
// chunks_included: 1,
// challenges_root: `11111111111111111111111111111111`,
// timestamp: 1618558205803345000,
// timestamp_nanosec: 1618558205803345000,
// random_value: `3cAa93XmoLaKAJQgWz3K7SiKwnA3uaxi8MGgLM78HTNS`,
// validator_proposals: [],
// chunk_mask: [
// true,
// ],
// gas_price: 1000000000,
// rent_paid: 0,
// validator_reward: 0,
// total_supply: 2050206401403887985811862247311434,
// challenges_result: [],
// last_final_block: `DCkMmXYHqibzcMjgFjRXJP7eckAMLrA4ijggSApMNwKu`,
// last_ds_final_block: `2vJNJca72pBiq2eETq2xvuoc6caKDaUkdRgtdefyutbA`,
// next_bp_hash: `4DJWnxRbUhRrsXK6EBkx4nFeXHKgJWqteDnJ7Hv4MZ6M`,
// block_merkle_root: `Bvn5K89fJ3uPNsj3324Ls9TXAGUVteHPpfKwKqL1La6W`,
// approvals: [
// Some(
// ed25519:F816hgJod7nPfD2qQz5yhaKDMn1JXmvzj2iXegsJpsmPNnYYZpKYJXgyuVTVJ4TKQbcJ2Q3USCGZF6fX2TcwBBv,
// ),
// ],
// signature: ed25519:239NbE4BuJaxneQA3AEsPrsGY7v3wBgaezbgg56HER69zPrBoc3a4fbyVWPXeoKE3LvgGma1g6pSHk9QHkmETCZY,
// latest_protocol_version: 43,
// },
// chunks: [
// ChunkHeaderView {
// chunk_hash: `2M2oeNFBbUUnHfkU1UuBr8EKBCLMH9xr2vfsGRpyiBmA`,
// prev_block_hash: `2vJNJca72pBiq2eETq2xvuoc6caKDaUkdRgtdefyutbA`,
// outcome_root: `11111111111111111111111111111111`,
// prev_state_root: `3gZPPijaumgMRCvMuuZZM1Ab2LoHTSfYigMKwLqZ67m6`,
// encoded_merkle_root: `79Bt7ivt9Qhp3c6dJYnueaTyPVweYxZRpQHASRRAiyuy`,
// encoded_length: 8,
// height_created: 63596,
// height_included: 63596,
// shard_id: 0,
// gas_used: 0,
// gas_limit: 1000000000000000,
// rent_paid: 0,
// validator_reward: 0,
// balance_burnt: 0,
// outgoing_receipts_root: `H4Rd6SGeEBTbxkitsCdzfu9xL9HtZ2eHoPCQXUeZ6bW4`,
// tx_root: `11111111111111111111111111111111`,
// validator_proposals: [],
// signature: ed25519:2vWNayBzEoW5DRc7gTdhxdLbkKuK6ACQ78p3JGpKSAZZCarnLroeoALPAFwpr9ZNPxBqdVYh9QLBe7WHZebsS17Z,
// },
// ],
// },
// shards: [
// IndexerShard {
// shard_id: 0,
// chunk: Some(
// IndexerChunkView {
// author: "test.near",
// header: ChunkHeaderView {
// chunk_hash: `2M2oeNFBbUUnHfkU1UuBr8EKBCLMH9xr2vfsGRpyiBmA`,
// prev_block_hash: `2vJNJca72pBiq2eETq2xvuoc6caKDaUkdRgtdefyutbA`,
// outcome_root: `11111111111111111111111111111111`,
// prev_state_root: `3gZPPijaumgMRCvMuuZZM1Ab2LoHTSfYigMKwLqZ67m6`,
// encoded_merkle_root: `79Bt7ivt9Qhp3c6dJYnueaTyPVweYxZRpQHASRRAiyuy`,
// encoded_length: 8,
// height_created: 63596,
// height_included: 0,
// shard_id: 0,
// gas_used: 0,
// gas_limit: 1000000000000000,
// rent_paid: 0,
// validator_reward: 0,
// balance_burnt: 0,
// outgoing_receipts_root: `H4Rd6SGeEBTbxkitsCdzfu9xL9HtZ2eHoPCQXUeZ6bW4`,
// tx_root: `11111111111111111111111111111111`,
// validator_proposals: [],
// signature: ed25519:2vWNayBzEoW5DRc7gTdhxdLbkKuK6ACQ78p3JGpKSAZZCarnLroeoALPAFwpr9ZNPxBqdVYh9QLBe7WHZebsS17Z,
// },
// transactions: [
// IndexerTransactionWithOutcome {
// transaction: SignedTransactionView {
// signer_id: "test.near",
// public_key: ed25519:8NA7mh6TAWzy2qz68bHp62QHTEQ6nJLfiYeKDRwEbU3X,
// nonce: 1,
// receiver_id: "some.test.near",
// actions: [
// CreateAccount,
// Transfer {
// deposit: 40000000000000000000000000,
// },
// AddKey {
// public_key: ed25519:2syGhqwJ8ba2nUGmP9tkZn9m1DYZPYYobpufiERVnug8,
// access_key: AccessKeyView {
// nonce: 0,
// permission: FullAccess,
// },
// },
// ],
// signature: ed25519:Qniuu7exnr6xbe6gKafV5vDhuwM1jt9Bn7sCTF6cHfPpYWVJ4Q6kq8RAxKSeLoxbCreVp1XzMMJmXt8YcUqmMYw,
// hash: `8dNv9S8rAFwso9fLwfDQXmw5yv5zscDjQpta96pMF6Bi`,
// },
// outcome: IndexerExecutionOutcomeWithReceipt {
// execution_outcome: ExecutionOutcomeWithIdView {
// proof: [],
// block_hash: `G9v6Fsv94xaa7BRY2N5PFF5PJwT7ec6DPzQK73Yf3CZ6`,
// id: `8dNv9S8rAFwso9fLwfDQXmw5yv5zscDjQpta96pMF6Bi`,
// outcome: ExecutionOutcomeView {
// logs: [],
// receipt_ids: [
// `CbWu7WYYbYbn3kThs5gcxANrxy7AKLcMcBLxLw8Zq1Fz`,
// ],
// gas_burnt: 424555062500,
// tokens_burnt: 424555062500000000000,
// executor_id: "test.near",
// status: SuccessReceiptId(CbWu7WYYbYbn3kThs5gcxANrxy7AKLcMcBLxLw8Zq1Fz),
// },
// },
// receipt: None,
// },
// },
// ],
// receipts: [
// ReceiptView {
// predecessor_id: "test.near",
// receiver_id: "some.test.near",
// receipt_id: `CbWu7WYYbYbn3kThs5gcxANrxy7AKLcMcBLxLw8Zq1Fz`,
// receipt: Action {
// signer_id: "test.near",
// signer_public_key: ed25519:8NA7mh6TAWzy2qz68bHp62QHTEQ6nJLfiYeKDRwEbU3X,
// gas_price: 1030000000,
// output_data_receivers: [],
// input_data_ids: [],
// actions: [
// CreateAccount,
// Transfer {
// deposit: 40000000000000000000000000,
// },
// AddKey {
// public_key: ed25519:2syGhqwJ8ba2nUGmP9tkZn9m1DYZPYYobpufiERVnug8,
// access_key: AccessKeyView {
// nonce: 0,
// permission: FullAccess,
// },
// },
// ],
// },
// },
// ],
// },
// ),
// receipt_execution_outcomes: [
// IndexerExecutionOutcomeWithReceipt {
// execution_outcome: ExecutionOutcomeWithIdView {
// proof: [],
// block_hash: `BXPB6DQGmBrjARvcgYwS8qKLkyto6dk9NfawGSmfjE9Q`,
// id: `CbWu7WYYbYbn3kThs5gcxANrxy7AKLcMcBLxLw8Zq1Fz`,
// outcome: ExecutionOutcomeView {
// logs: [],
// receipt_ids: [
// `8vJ1QWM4pffRDnW3c5CxFFV5cMx8wiqxsAqmZTitHvfh`,
// ],
// gas_burnt: 424555062500,
// tokens_burnt: 424555062500000000000,
// executor_id: "some.test.near",
// status: SuccessValue(``),
// },
// },
// receipt: ReceiptView {
// predecessor_id: "test.near",
// receiver_id: "some.test.near",
// receipt_id: `CbWu7WYYbYbn3kThs5gcxANrxy7AKLcMcBLxLw8Zq1Fz`,
// receipt: Action {
// signer_id: "test.near",
// signer_public_key: ed25519:8NA7mh6TAWzy2qz68bHp62QHTEQ6nJLfiYeKDRwEbU3X,
// gas_price: 1030000000,
// output_data_receivers: [],
// input_data_ids: [],
// actions: [
// CreateAccount,
// Transfer {
// deposit: 40000000000000000000000000,
// },
// AddKey {
// public_key: ed25519:2syGhqwJ8ba2nUGmP9tkZn9m1DYZPYYobpufiERVnug8,
// access_key: AccessKeyView {
// nonce: 0,
// permission: FullAccess,
// },
// },
// ],
// },
// },
// },
// ],
// },
// ],
// state_changes: [
// StateChangeWithCauseView {
// cause: ValidatorAccountsUpdate,
// value: AccountUpdate {
// account_id: "test.near",
// account: AccountView {
// amount: 1000000000000000000000000000000000,
// locked: 50000000000000000000000000000000,
// code_hash: `11111111111111111111111111111111`,
// storage_usage: 182,
// storage_paid_at: 0,
// },
// },
// },
// ],
// }
tracing::info!(
target: "indexer_example",
height = %streamer_message.block.header.height,
hash = ?streamer_message.block.header.hash,
num_shards = %streamer_message.shards.len(),
num_transactions = %streamer_message.shards.iter().map(|shard| if let Some(chunk) = &shard.chunk { chunk.transactions.len() } else { 0usize }).sum::(),
num_receipts = %streamer_message.shards.iter().map(|shard| if let Some(chunk) = &shard.chunk { chunk.receipts.len() } else { 0usize }).sum::(),
num_execution_outcomes = %streamer_message.shards.iter().map(|shard| shard.receipt_execution_outcomes.len()).sum::(),
"block processed"
);
}
}
```
[See code on GitHub](https://github.com/near/nearcore/blob/6ac40f1a7806598f26e8e8593b51b3214b9e3f5f/tools/indexer/example/src/main.rs#L10-L254)
***
## Custom Configuration
By default, nearcore is configured to do as little work as possible while still operating on an up-to-date state. Indexers may have different requirements, so you might need to tweak the configuration based on yours.
### Shards/Accounts to Track
We need to ensure that NEAR Indexer follows all the necessary shards, so by default the `"tracked_shards_config"` is set to `"AllShards"`. If you only need the data of specific accounts, list those accounts in the `"tracked_shards_config"` section (`~/.near//config.json` file). The node then tracks the shards that hold these accounts:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
...
"tracked_shards_config": {
"Accounts": [
"account_a",
"account_b"
]
},
...
```
The indexer supports only these two settings: `"AllShards"`, or `"Accounts"` with at least one account. With any other value, including a `"Shards"` list of shard UIDs, the indexer stops at startup.
### Sync Mode
You can choose the starting point for syncing by setting the Indexer Framework sync mode:
* LatestSynced - Real-time syncing, always taking the latest finalized block to stream
* FromInterruption - Starts syncing from the block NEAR Indexer was interrupted last time
* BlockHeight(u64) - Specific block height to start syncing from.
```rust title="main.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
sync_mode: near_indexer::SyncModeEnum::FromInterruption,
```
[See code on GitHub](https://github.com/near/nearcore/blob/6ac40f1a7806598f26e8e8593b51b3214b9e3f5f/tools/indexer/example/src/main.rs#L273-L273)
### Streaming Mode
You can choose Indexer Framework streaming mode by setting what to stream:
* StreamWhileSyncing - Stream while node is syncing
* WaitForFullSync - Don't stream until the node is fully synced
```rust title="main.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
await_for_node_synced: near_indexer::AwaitForNodeSyncedEnum::WaitForFullSync,
```
[See code on GitHub](https://github.com/near/nearcore/blob/6ac40f1a7806598f26e8e8593b51b3214b9e3f5f/tools/indexer/example/src/main.rs#L274-L274)
### Finality
You can choose finality level at which blocks are streamed:
* None - `optimistic`, a block that (though unlikely) might be skipped
* DoomSlug - `near-final`, a block that is irreversible, unless at least one block producer signs two conflicting blocks or approvals
* Final - `final`, the block is final and irreversible.
```rust title="main.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
finality: near_primitives::types::Finality::Final,
```
[See code on GitHub](https://github.com/near/nearcore/blob/6ac40f1a7806598f26e8e8593b51b3214b9e3f5f/tools/indexer/example/src/main.rs#L275-L275)
### Boot Nodes
If your node can't find any peers to connect to, you can manually specify some boot nodes in the `config.json` file. You can get a list of active peers for your network by running the following command:
> [tab] Testnet
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> curl -X POST https://rpc.testnet.near.org \
> -H "Content-Type: application/json" \
> -d '{
> "jsonrpc": "2.0",
> "method": "network_info",
> "params": [],
> "id": "dontcare"
> }' | \
> jq '.result.active_peers as $list1 | .result.known_producers as $list2 |
> $list1[] as $active_peer | $list2[] |
> select(.peer_id == $active_peer.id) |
> "\(.peer_id)@\($active_peer.addr)"' |\
> awk 'NR>2 {print ","} length($0) {print p} {p=$0}' ORS="" | sed 's/"//g'
> ```
> [tab] Mainnet
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> curl -X POST https://rpc.mainnet.near.org \
> -H "Content-Type: application/json" \
> -d '{
> "jsonrpc": "2.0",
> "method": "network_info",
> "params": [],
> "id": "dontcare"
> }' | \
> jq '.result.active_peers as $list1 | .result.known_producers as $list2 |
> $list1[] as $active_peer | $list2[] |
> select(.peer_id == $active_peer.id) |
> "\(.peer_id)@\($active_peer.addr)"' |\
> awk 'NR>2 {print ","} length($0) {print p} {p=$0}' ORS="" | sed 's/"//g'
> ```
And then add the output to the `boot_nodes` section of your `config.json` file as a string:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
...
"network": {
"addr": "0.0.0.0:24567",
"boot_nodes": "ed25519:8oVENgBp6zJfnwXFe...",
...
},
...
```
### Historical Data
Indexer Framework also exposes access to the internal APIs (see Indexer::client\_actors method), so you can fetch data about any block, transaction, etc, yet by default, nearcore is configured to remove old data (garbage collection), so querying the data that was observed a few epochs before may return an error saying that the data is not found. If you only need blocks streaming, you don't need this tweak, but if you need access to the historical data right from your Indexer, consider updating "archive" setting in config.json to true:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
...
"archive": true,
...
```
***
## Using NEAR Indexer in your Project
You can also use NEAR Indexer Framework as a dependency in your own Rust project. To do that, add the following to your `Cargo.toml` file (replace `2.8.0` with the latest stable release version):
```toml theme={"theme":{"light":"github-light","dark":"github-dark"}}
[dependencies]
near-indexer = { git = "https://github.com/near/nearcore", tag = "2.9.1" }
near-indexer-primitives = { git = "https://github.com/near/nearcore", tag = "2.9.1" }
near-config-utils = { git = "https://github.com/near/nearcore", tag = "2.9.1" }
near-o11y = { git = "https://github.com/near/nearcore", tag = "2.9.1" }
near-primitives = { git = "https://github.com/near/nearcore", tag = "2.9.1" }
```
# What is Data Infrastructure?
Source: https://docs.near.org/data-infrastructure/what-is
Explore NEAR's data infrastructure for accessing on-chain data
NEAR offers ready-to-use solutions to access and monitor on-chain data easily. This is very useful to automate actions based on specific **events**, cache data to **reduce latency**, gather **usage data** of the blockchain, and even **study user preferences**.

In NEAR you will find three main solutions to access and monitor on-chain data: [**Data APIs**](#data-apis), [**BigQuery Public Dataset**](#bigquery-public-dataset) and [**Block Streams and Indexers**](#block-streams-and-indexers). Each of these solutions is designed to fit different needs and use cases, and can be used in combination to create a complete data infrastructure for your application.
***
## [Data APIs](./data-api)
Members of the NEAR community have built a set of APIs to access and monitor on-chain data. These APIs are designed to be easy to use and can be accessed from any application through a simple API call.
* User assets: Easily track all the assets that a user or a contract holds
* Monitor transactions: Get all the transactions of a user, a contract or a specific token
* Track on-chain events: Get all the events emitted by a contract, or a specific event type
***
## [BigQuery: Public Dataset](./big-query)
A large dataset with on-chain data publicly available on Google Cloud Platform. Obtain near real-time blockchain data using simple SQL queries. **All the data, zero setup**.
* Instant insights: Historic on-chain data queried at scale. No need to run your own infrastructure.
* Cost-effective: Eliminate the need to store and process bulk NEAR Protocol data. Query as little or as much data as you like.
* As easy as SQL: No prior experience with blockchain technology is required. Just bring a general knowledge of SQL to unlock insights.
***
## Block Streams and Indexers
Use [Neardata](https://docs.fastnear.com/neardata) to ingest block data into your application or custom indexer. To process blocks directly from a node you operate, use the [nearcore indexer](/data-infrastructure/near-indexer).
NEAR Lake has been retired. See the [retirement notice](/data-infrastructure/lake-framework/near-lake) for migration guidance.
***
## Conclusion
Data infrastructure is a key component of any blockchain application. It allows developers to access and monitor on-chain data easily, which is essential for building applications that interact with the blockchain.
NEAR offers a range of solutions to help developers build robust data infrastructure for their applications, including Data APIs, BigQuery Public Dataset, and block streams. By using these solutions in combination, developers can create a complete data infrastructure that meets their specific needs and use cases.
# Create an Account
Source: https://docs.near.org/getting-started/create-account
Understand how to create a NEAR account using a wallet and the NEAR CLI
A NEAR `testnet` account allows you to deploy contracts and log in to Web3 apps without spending any real money. You can create a `testnet` NEAR account through one of the following methods:
> [card] [Using one of the wallets listed in wallet.near.org](#using-a-wallet)
> [card] [Using the command line interface (CLI)](#through-the-cli)
> [!TIP]
>
> You do not need an account to start building: test smart contracts locally using [NEAR Sandbox](/smart-contracts/testing/integration-test) and the frontend through [a local network](/web3-apps/tutorials/localnet/run).
> [!NOTE]
>
> If you already have a NEAR account, you can import it into another wallet or the CLI. See [Importing Existing Accounts](#importing-existing-accounts) below.
***
## Using a Wallet
Go to [wallet.near.org](https://wallet.near.org/) and choose one of the wallets listed there. Do not worry, the list has been curated, so you can be sure that all wallets listed there are safe to use.
In general, all wallets will offer similar functionality, so in theory you can choose any of them. However, know that some wallets will readily allow you to create [named accounts](/protocol/accounts-contracts/account-id#named-address) (e.g. `alice.testnet`), which are easier to remember.
Remember to write down the seed phrase, as it is the only way to access your account!
> [!WARNING]
>
> **Testnet**
> Make sure to create a `testnet` account (ending with `.testnet`, e.g. `alice.testnet`), and not a `mainnet` account (ending with `.near`).
>
> NEAR `testnet` is a separate network that allows you to test your applications without spending real money.
> [!TIP]
>
> **Funding the Wallet**
>
> Need `testnet` funds? try using one of our [faucets](/getting-started/faucet)
***
## Through the CLI
When developing smart contracts you will expend lots of time interacting with the NEAR blockchain through the command line interface (CLI).
First, you will need to install the [NEAR CLI](/tools/cli#installation):
> [tab] npm
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> npm install -g near-cli-rs@latest
> ```
> [tab] Homebrew
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> brew install near
> ```
> [tab] Cargo
>
> ```
> $ cargo install near-cli-rs
> ```
> [tab] Mac and Linux (binaries)
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/near-cli-rs/releases/latest/download/near-cli-rs-installer.sh | sh
> ```
> [tab] Windows (binaries)
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> irm https://github.com/near/near-cli-rs/releases/latest/download/near-cli-rs-installer.ps1 | iex
> ```
Once you have the CLI installed, you can create a new account using the following command:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near create-account --useFaucet
```
This command will create a new account with the name `` and fund it using the `testnet` faucet. Make sure to replace `` with your desired account name.
***
## Importing Existing Accounts
If you want to use an existing NEAR account in another wallet or in the CLI, you can import it using your seed phrase or private key.
> [accordion] 1. Export your seed phrase or private key
>
> From your current wallet, use its account backup/export flow.
>
> If the account was created with the CLI, run:
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near account export-account
> ```
> [accordion] 2. Import into a wallet
>
> In your destination wallet, choose the account import/restore option and provide your seed phrase.
> [accordion] 3. Import into the CLI
>
> Run:
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near account import-account
> ```
>
> Then follow the prompts to enter your seed phrase or private key.
> [!WARNING]
>
> Keep your seed phrase and private key secure. Anyone with access to them can control your account.
***
## Next Steps
Now that you have created a NEAR account, you can start developing applications on the NEAR Protocol.
Here are some resources to help you get started:
* Fund the wallet through one of our [faucets](/getting-started/faucet)
* Create your [first smart contract](/smart-contracts/quickstart)
* Build a [Web3 Application](/web3-apps/quickstart)
* Learn how to build an [Auction App from end-to-end](/web3-apps/tutorials/mastering-near/0-intro)
* Not sure where to begin? Check [Start Building](/getting-started/start-building)
# Token Faucet
Source: https://docs.near.org/getting-started/faucet
Learn how to get free testnet tokens for development and testing on the NEAR blockchain
A **faucet** provides free `testnet` tokens for testing and development purposes.
There are two testnet faucets: the built‑in faucet on this page - which provides native `testnet` NEAR only - and the [Testnet Faucet](#external-faucet), which supports many fungible tokens (NEAR, USDT, and more).
> [!NOTE]
>
> If any of the faucets is not working, please report it on our [NEAR Telegram Channel](https://t.me/neardev)
***
## Faucet
Simply introduce the account you want to receive the tokens in, and click on the "Request" button. The faucet will send a small amount of `testnet` NEAR tokens to that account.
NEAR Testnet Faucet
Get free NEAR tokens for testing
***
## External Faucet
Navigate to the [Testnet Faucet](https://near-faucet.io/) page, input your address and select which type of token you need! The faucet supports a wide range of fungible tokens, including NEAR, Tether USD, Ether, and many others.

> [!NOTE]
>
> Please know that the faucet might be out of tokens at times, keep reading below for alternative ways to get other fungible tokens
***
## Getting Fungible Tokens
If you need `testnet` USDC, use the [Circle Faucet](https://faucet.circle.com/), which provides 20 USDC on NEAR `testnet` every 2 hours.
Another way to get fungible tokens on `testnet` is through the [`testnet` version of ref finance](https://testnet.ref.finance/#near|ref.fakes.testnet)
There, you can swap `testnet` NEAR for other fungible tokens, such as `testnet USDC`, `testnet USDT`, `testnet DAI`, and others
> [!NOTE]
>
> Please notice that tokens on `testnet` might not hold the same rate as on `mainnet` (e.g. `1 USDC` might not exchange to the same amount of `NEAR` as on `mainnet`), furthermore, liquidity on `testnet` might be very low
# Start Building
Source: https://docs.near.org/getting-started/start-building
Choose what to build on NEAR, and find the guides and tools you need for it
NEAR lets you write smart contracts in Rust, build Web3 apps where users log in with their wallets, control accounts on other chains, and give AI agents access to the blockchain.
Pick what you want to build, and follow its guide.
> [card] [Smart Contracts](#smart-contracts)
>
> Write programs in Rust that store data, hold tokens, and run on-chain.
> [card] [Web3 Apps](#web3-apps)
>
> Build frontends where users log in with their NEAR wallets.
> [card] [Multichain Apps](#multichain-apps)
>
> Sign transactions for Bitcoin, Ethereum, Solana, and more.
> [card] [AI Agents](#ai-agents)
>
> Help your coding agent build on NEAR, or let agents use the blockchain.
> [card] [On-Chain Data](#on-chain-data)
>
> Query the history of accounts, transactions, and events.
> [card] [Build a Complete App](#go-further)
>
> Combine a contract, tests, a frontend, and an indexer in one app.
> [card] [Need Help?](/communities)
>
> Ask questions in the NEAR developer channels, and find answers to common questions.
***
## Smart Contracts
Smart contracts are programs that live on the blockchain: they store data, hold tokens, and execute code when users call their functions. In NEAR, contracts are written in Rust.
> [card] [Smart Contract Quickstart](/smart-contracts/quickstart)
>
> Create, test and deploy an auction contract.
#### Tools you will use
> [card] [near-sdk-rs](/tools/sdk)
>
> The official SDK to write contracts in Rust.
> [card] [NEAR Sandbox](/smart-contracts/testing/integration-test)
>
> Tests your contract locally, no account needed.
> [card] [NEAR CLI](/tools/cli)
>
> Creates accounts, deploys contracts, and calls their functions from the terminal.
> [card] [cargo-near](https://github.com/near/cargo-near)
>
> Creates, builds and deploys contracts.
***
## Web3 Apps
Web3 apps are frontends where users log in with their NEAR wallets and interact with smart contracts.
> [card] [Web3 App Quickstart](/web3-apps/quickstart)
>
> Create a React app where users log in and call a contract already deployed on `testnet`.
> [card] [Add Wallet Login](/web3-apps/tutorials/wallet-login)
>
> Already have an app? Add NEAR wallet login to it.
#### Tools you will use
> [card] [NEAR Connect](/tools/near-connect)
>
> Lets users log in with any NEAR wallet.
> [card] [NEAR API JS](/tools/near-api#🌐-near-api-js)
>
> Reads data from the blockchain and sends transactions.
> [card] [near-kit](/tools/near-api#🌐-near-kit)
>
> Modern TypeScript client with a fetch-like API.
> [card] [near-kit-py](/tools/near-api#🐍-near-kit-py)
>
> Reads data from the blockchain and sends transactions from Python.
> [card] [create-near-app](https://github.com/near/create-near-app)
>
> Creates a frontend template ready to talk with NEAR.
> [card] [near-sign-verify](https://github.com/elliotBraem/near-sign-verify)
>
> Creates and validates NEP-413 signed messages.
> [card] [better-near-auth](https://github.com/elliotBraem/better-near-auth)
>
> Sign in with NEAR plugin for Better Auth.
***
## Multichain Apps
NEAR accounts and contracts can sign transactions for other chains, such as Bitcoin, Ethereum and Solana, and users can swap assets across chains by simply expressing the outcome they want.
> [card] [Chain Signatures](/chain-abstraction/chain-signatures/implementation)
>
> Sign transactions for other chains from a NEAR account or contract.
> [card] [NEAR Intents](/chain-abstraction/intents/overview)
>
> Let users swap assets across chains, with solvers competing to fill their request.
#### Tools you will use
> [card] [chainsig.js](/chain-abstraction/chain-signatures/implementation)
>
> Builds and signs transactions for other chains from TypeScript.
> [card] [omni-transaction-rs](https://github.com/near/omni-transaction-rs)
>
> Builds transactions for other chains from Rust, including from within a contract.
> [card] 1Click SDKs
>
> Request cross-chain swaps through NEAR Intents, from [TypeScript](https://github.com/defuse-protocol/one-click-sdk-typescript), [Rust](https://github.com/defuse-protocol/one-click-sdk-rs) or [Go](https://github.com/defuse-protocol/one-click-sdk-go).
> [card] [intents-sdk](https://github.com/defuse-protocol/sdk-monorepo/tree/main/packages/intents-sdk)
>
> SDK to build intents-based applications.
> [card] [NEAR Intents Docs](https://docs.near-intents.org/near-intents)
>
> The complete documentation of NEAR Intents.
> [card] [NEAR Intents Explorer](https://explorer.near-intents.org/)
>
> Explore the transactions made through NEAR Intents.
***
## AI Agents
Coding agents can help you build on NEAR, and agents can use NEAR to hold assets and send transactions.
> [card] [Tools for AI Agents](/getting-started/tools-for-ai)
>
> Give your agent access to these docs, to task-specific skills, and to the blockchain.
#### Tools you will use
> [card] [Agent Skills](/getting-started/tools-for-ai#near-agent-skills)
>
> Task-specific guidance for coding agents building on NEAR.
> [card] [NEAR AI Cloud](https://docs.near.ai/)
>
> Private, verifiable AI inference.
> [card] [near-ai-chat](https://github.com/jlwaugh/near-ai-chat)
>
> AI chat agent starter template for NEAR AI Cloud.
> [!TIP]
>
> **Need NEAR AI credits?** You can [request NEAR AI Cloud credits](https://www.notion.so/Requesting-NEAR-AI-Cloud-Credits-2deda22d7b6481aea8e1e30282efcb5e) for your project.
***
## On-Chain Data
If your app needs historical data, such as all the transactions of a user or the events of a contract, you will need more than the RPC: data APIs, public datasets, and indexers.
> [card] [What is Data Infrastructure?](/data-infrastructure/what-is)
>
> Learn about the options to access on-chain data, and when to use each.
#### Tools you will use
> [card] [Data APIs](/data-infrastructure/data-api)
>
> Track the assets, transactions and events of any account through simple API calls.
> [card] [BigQuery](/data-infrastructure/big-query)
>
> Query historical on-chain data using SQL.
> [card] [Neardata](https://docs.fastnear.com/neardata)
>
> Stream blocks into your own indexer.
> [card] [Stream NEAR](https://stream.near.tools)
>
> Server-Sent Events stream for real-time block data.
***
## Go Further
> [card] [Mastering NEAR](/web3-apps/tutorials/mastering-near/0-intro)
>
> Once you have gone through a quickstart, build a complete app: an auction contract with tests, a frontend, an indexer, NFT and FT support, and a factory to deploy new auctions.
# Tools for AI Agents
Source: https://docs.near.org/getting-started/tools-for-ai
Guide your agent on building NEAR applications
NEAR offers multiple tools and resources to help your AI agents build and use NEAR applications. This page provides an overview of the key tools available and how to use them effectively.
For coding agents with terminal access, start with NEAR CLI for blockchain operations and Agent Skills for task-specific guidance. Use the [testnet faucet](/getting-started/faucet) to fund development accounts. NEAR MCP is an optional integration for clients that need blockchain operations exposed as structured tools.
> [card] [NEAR CLI](#near-cli)
>
> When your agent has terminal access and needs to query accounts, send tokens, or interact with contracts.
> [card] [llms.txt](#llms-txt)
>
> When you need to provide your agent with a quick reference to all NEAR docs.
> [card] [Docs MCP](#docs-mcp-endpoint)
>
> When you want agents to search docs in real-time for up-to-date details.
> [card] [Agent Skills](#near-agent-skills)
>
> When you need your agent to become an expert in a specific task (e.g. using our API).
> [card] [NEAR MCP (Optional)](#near-mcp-server-optional)
>
> When your client needs blockchain operations exposed through MCP.
> [card] [Testnet Faucet](#testnet-faucet)
>
> When you need testnet NEAR for development accounts.
***
## NEAR CLI
[NEAR CLI](https://github.com/near/near-cli-rs) lets agents query accounts, transfer tokens, deploy contracts, and call contract methods from the terminal.
Install the CLI and check that the `near` command is available:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npm install -g near-cli-rs@latest
near --version
```
Supply complete commands, including the network and final action, so the CLI does not need to prompt for missing arguments. For example, check an account's testnet balance:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near tokens your-account.testnet view-near-balance network-config testnet now
```
Replace `your-account.testnet` with your account ID. Read-only queries do not require a signing key. To read contract data, specify the contract, method, and JSON arguments:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-read-only wrap.testnet ft_metadata json-args '{}' network-config testnet now
```
For transactions, configure a signer available to the agent's runtime and provide the signing option in the command. See the [CLI reference](/tools/cli) for account management, transfers, deployment, and signing options. The [`near-cli-rs` skill](#near-agent-skills) provides command syntax and workflows for agents.
***
## llms.txt
**What it is:** Curated NEAR docs context for coding assistants.
**Use it when:** You need to provide your agent with a quick reference to all NEAR docs.
**Link:** [https://docs.near.org/llms.txt](https://docs.near.org/llms.txt)
> [accordion] VS Code Setup
>
> Use `#fetch` in your prompt:
>
> ```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
> How can I upgrade a contract state?
> #fetch https://docs.near.org/llms.txt
> ```
> [accordion] Cursor Setup
>
> Add docs source once in Cursor Chat:
>
> 1. `@` → `Docs` → `+ Add new doc`
> 2. Add: `https://docs.near.org/llms.txt`
> 3. Select the source while prompting
***
## Docs MCP endpoint
**What it is:** An endpoint to search NEAR documentation via MCP.
**Use it when:** You want agents to search docs in real-time for up-to-date details and narrower API lookups.
**Link:** [https://docs.near.org/mcp](https://docs.near.org/mcp)
Use two complementary layers:
1. **Static context (`llms.txt`)** for fast, high-signal docs grounding.
2. **Retrieval (Docs MCP)** when the agent needs live lookup across docs.
***
## NEAR Agent Skills
NEAR Agent Skills are reusable capabilities that package repeatable workflows.
**Use it when:** You need your agent to become an expert in specific tasks (for example, using NEAR APIs).
**Link:** [https://github.com/near/agent-skills](https://github.com/near/agent-skills)
Install the skills using:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npx skills add near/agent-skills
```
To install a specific skill, pass its name. For example, install the CLI skill with:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npx skills add near/agent-skills --skill near-cli-rs
```
| Skill | Focus |
| - | - |
| [near-ai-cloud](https://github.com/near/agent-skills/tree/main/skills/near-ai-cloud) | Verifiable private AI inference and attestation |
| [near-api-js](https://github.com/near/agent-skills/tree/main/skills/near-api-js) | JS/TS blockchain interaction, transactions, tokens, and wallet integration |
| [near-cli-rs](https://github.com/near/agent-skills/tree/main/skills/near-cli-rs) | CLI commands for accounts, tokens, contracts, signing, and network configuration |
| [near-contract-audit](https://github.com/near/agent-skills/tree/main/skills/near-contract-audit) | Security review of Rust contracts, vulnerability analysis, and findings with remediation |
| [near-dapp](https://github.com/near/agent-skills/tree/main/skills/near-dapp) | dApp project setup, wallet integration, React/Next.js patterns |
| [near-intents](https://github.com/near/agent-skills/tree/main/skills/near-intents) | Cross-chain swaps via the 1Click API |
| [near-kit](https://github.com/near/agent-skills/tree/main/skills/near-kit) | TypeScript client for contract calls, transactions, and Sandbox tests |
| [near-smart-contracts](https://github.com/near/agent-skills/tree/main/skills/near-smart-contracts) | Rust smart contract development, security, and state management |
***
## NEAR MCP Server (Optional)
The [NEAR MCP Server](https://github.com/nearai/near-mcp) exposes blockchain operations as structured tools through the Model Context Protocol.
> [accordion] Common use cases
>
> * **Give Claude, Cursor or another MCP client on-chain actions:** let your assistant check balances, manage accounts and keys, and call smart contracts on NEAR.
> * **Run agents without terminal access:** expose NEAR operations as tools to clients that cannot run [NEAR CLI](#near-cli).
**Use it when:** Your client supports MCP and needs blockchain tools through that interface, for example when it does not have terminal access. Coding agents with terminal access can use [NEAR CLI](#near-cli) directly.
**Repo**: [https://github.com/nearai/near-mcp](https://github.com/nearai/near-mcp)
**Remote deployment guide**: [https://github.com/nearai/near-mcp/blob/main/tee.md](https://github.com/nearai/near-mcp/blob/main/tee.md)
> [!WARNING]
>
> The NEAR MCP is designed to run **locally** or on your **trusted infrastructure** because it handles private keys. There is no hosted public version.
***
## Testnet Faucet
Use the [testnet faucet](/getting-started/faucet) to send **5 testnet NEAR** to your agent's account. Enter the recipient's account ID and click **Request Tokens**. Only the account ID is required; keep its private key in your agent's local signer.
The faucet requires a browser. If your agent does not have browser access, fund its account through the faucet before continuing with CLI or SDK operations.
***
## Shade Agent Framework (Deprecated)
> [!WARNING]
>
> **Do not use the Shade Agent Framework.** It has not been maintained since April 19, 2026. Do not use it for new projects, and do not recommend it to builders.
The framework remains open source, and its documentation now lives in the [Shade Agent Framework repository](https://github.com/NearDeFi/shade-agent-framework/tree/main/docs). Teams that still run it are responsible for its maintenance, updates and fixes.
# What is NEAR?
Source: https://docs.near.org/getting-started/what-is-near
An introduction to NEAR, a scalable and secure blockchain built with usability in mind
NEAR is a **user-friendly** blockchain, built to be fast, secure, and infinitely scalable. It offers a simple user experience with named accounts, low fees, and a robust developer ecosystem.

In technical terms, NEAR is a [layer one](https://coinmarketcap.com/academy/glossary/layer-1-blockchain), [sharded](https://near.org/blog/near-launches-nightshade-sharding-paving-the-way-for-mass-adoption), [proof-of-stake](https://en.wikipedia.org/wiki/Proof_of_stake) blockchain built with usability in mind.
In simpler terms, NEAR is the **blockchain for everyone**.
> [accordion] What do these Technical Terms mean?
>
> [Layer-1](https://coinmarketcap.com/academy/glossary/layer-1-blockchain) means NEAR is the foundation that supports everything else built on it. It keeps all the transaction records safe and unchangeable which keeps the network secure and trustworthy.
>
> [Sharded](https://near.org/blog/near-launches-nightshade-sharding-paving-the-way-for-mass-adoption) means the network is broken into pieces that work in parallel. This helps NEAR process transactions quickly and efficiently.
>
> [Proof-of-stake](https://en.wikipedia.org/wiki/Proof_of_stake) uses less electricity compared with other blockchains which use proof-of-work. Users show they own NEAR tokens to help run the network. This makes it cheaper and lets more people use it.
***
## Why Choose NEAR?
NEAR offers built-in features such as named accounts and account abstraction. For developers, NEAR offers everything needed for their applications, from smart contracts to indexers. All while being interoperable with other chains.
### Simple to Use
1. Use [**named accounts**](/protocol/accounts-contracts/account-model) like `alice.near`
2. Simple sign-up: create an [account for free](/getting-started/create-account), login with socials (through [NEAR Auth](/web3-apps/tutorials/near-auth) or [Privy](/web3-apps/tutorials/privy)) or [telegram](https://web.telegram.org/k/#@herewalletbot)
3. Transactions are **fast** *(\~1.2s finality, with blocks every 600ms)* and **cheap** *(\< 1¢ in fees)*
4. Users don't need to buy crypto: apps can pay their gas fees through [**meta transactions**](/web3-apps/tutorials/meta-transactions)
5. [Access Keys](/protocol/accounts-contracts/access-keys) make it safe and easy to use
6. Control accounts on **other chains** thanks to [chain signatures](../chain-abstraction/chain-signatures)
### Battle-Tested
1. **100% uptime** since its 2020 launch and [**over 5.4 Billion** transactions](https://chainspect.app/chain/near) processed
2. NEAR has sustained peaks of [>13M transactions](https://pikespeak.ai/near-world/overview) in a single day
3. NEAR is home to decentralized apps with [millions of users](https://dappradar.com/rankings/protocol/near?sort=uawCount\&order=desc\&range=30d):
* [NEAR Intents](https://docs.near-intents.org/near-intents)
* [Sweat](https://swe.at/)
* [Hot Wallet](https://t.me/herewalletbot/)
### Great Developer Experience
1. Build smart contracts in **Rust** with the [official NEAR SDK](/tools/sdk)
2. **Simple onboarding**, thanks to its complete documentation and examples
3. Earn from your contract's gas fees
4. **EVM compatible** with [Project Aurora](http://www.aurora.dev) *(Deploy your Solidity contracts with ease)*
### Environmentally Friendly
1. In 2021, NEAR was **[certified carbon-neutral](https://near.org/blog/the-near-blockchain-is-climate-neutral/)**
2. NEAR **consumes in a year** the same energy [**bitcoin consumes in a few minutes**](https://medium.com/nearprotocol/how-near-went-carbon-neutral-e656db96da47#:~:text=The%20firm%20found%20that%20NEAR,PoS%20technology%20instead%20of%20PoW)
***
## Start Building
Ready to build on NEAR? Check [Start Building](/getting-started/start-building) to choose what you want to build, and find the guides and tools you need for it.
#
Source: https://docs.near.org/index
[MCP Ready](https://docs.near.org/mcp)
[LLMs.txt Ready](https://docs.near.org/llms.txt)
# NEAR Developer Docs
Build contracts in Rust, create Web3 apps, and sign transactions on any chain from a single NEAR account.
### Deploy your First Contract
Create, test and deploy contracts with simple commands.
[What is a Contract? →](/smart-contracts/what-is)
[Quickstart →](/smart-contracts/quickstart)
```bash bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cargo near new hello-world
# ✅ Success! Created 'hello-near', a smart contract in Rust
# Build, test, and deploy your contract with Cargo
cargo near build
cargo test
cargo near deploy
```
```bash create-near-app theme={"theme":{"light":"github-light","dark":"github-dark"}}
npx create-near-app@latest
# ✅ What do you want to build? › "A Web App"
# ✅ Select a framework for your frontend › "Vite (React)"
# ✅ Name your project: "hello-near"
#Start using your new NEAR app:
cd hello-near
npm run dev
```
### Build Web3 Applications
Easily authenticate users and call smart contracts from any frontend framework.
[What are Web3 Apps? →](/web3-apps/what-is)
[Create your first app →](/web3-apps/quickstart)
***
## Why NEAR?
> [card] Sub-second block finality
>
> Transactions reach deterministic finality in 1.2s, no reorgs, no waiting.
> [card] Near-zero fees
>
> Average transaction fees are \$0.002. Storage costs are fully refundable upon deletion.
> [card] Sharded & scalable
>
> The network automatically scales as demand grows, with no downtime or hard forks.
> [card] WASM contracts in Rust
>
> Write smart contracts in Rust with NEAR's official SDK.
> [card] Chain Signatures
>
> Control accounts on Bitcoin, Ethereum, Solana, and more.
> [card] TEE-backed agents
>
> Run AI inference inside Trusted Execution Environments for verifiable, tamper-proof outputs.
***
## Browse the docs
> [card] [Protocol](/protocol/network/architecture)
>
> Accounts, access keys, gas, transactions, consensus, and more.
> [card] [Smart contract reference](/smart-contracts/anatomy/anatomy)
>
> State, functions, collections, callbacks, cross-contract calls, and security.
> [card] [Web application guides](/web3-apps/quickstart)
>
> Wallet authentication, JavaScript APIs, data types, and contract calls.
> [card] [Tokens and primitives](/primitives/what-is)
>
> FTs, NFTs, DAOs, linkdrops, staking, oracles, and off-chain compute.
> [card] [Data infrastructure](/data-infrastructure/what-is)
>
> Index and query on-chain data with Data APIs, BigQuery, and block streams.
> [card] [AI agent tooling](/getting-started/tools-for-ai)
>
> Use llms.txt, Docs MCP, agent skills, and on-chain MCP tools.
## More NEAR docs
> [card] [NEAR Intents](https://docs.near-intents.org/near-intents)
>
> Let users express the outcome they want, such as swapping assets across chains, while solvers compete to fulfill it.
> [card] [NEAR AI](https://docs.near.ai/)
>
> Private, verifiable AI inference running inside Trusted Execution Environments.
# Accounts
Source: https://docs.near.org/integrations/accounts
Implicit-account derivation, on-chain creation, transfers, key management, and account costs for exchanges.
NEAR supports implicit accounts with 64-character hexadecimal IDs derived locally from an ED25519 public key. An account can be created with no initial deposit; the creator pays a **0.007 NEAR** creation charge through gas fees, plus the other transaction fees.
> [!TIP]
>
> See the [NEAR account model](/protocol/accounts-contracts/account-model) for account types, access keys, and permissions.
***
## Implicit Accounts
An ED25519 implicit account ID is the 64-character lowercase hexadecimal encoding of its 32-byte public key. Exchanges can derive deposit addresses locally before creating the accounts on-chain. The corresponding private key signs transactions after account creation.
> [!NOTE]
>
> [NEAR implicit accounts](/protocol/accounts-contracts/account-id#implicit-address).
### Generate a key pair and account ID
These examples generate an ED25519 key pair and derive the account ID locally; they do not create the account on-chain.
> [tab] NEAR CLI
>
> The CLI saves the credentials to `~/.near-credentials/implicit`.
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> # Test environment should use the testnet, for production use mainnet
> export NEAR_ENV=testnet
>
> near account create-account fund-later use-auto-generation save-to-folder ~/.near-credentials/implicit
>
> # Example output:
> # The file "~/.near-credentials/implicit/8bca86065be487de45e795b2c3154fe834d53ffa07e0a44f29e76a2a5f075df8.json" was saved successfully
> #
> # Here is your console command if you need to script it or re-run:
> # near account create-account fund-later use-auto-generation save-to-folder ~/.near-credentials/implicit
> ```
> [tab] near-api-js
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { KeyPairEd25519, baseDecode } from "near-api-js";
>
> const keyPair = KeyPairEd25519.fromRandom();
> const publicKey = keyPair.getPublicKey().toString();
> const accountId = Buffer.from(baseDecode(publicKey.split(":")[1])).toString("hex");
> const privateKey = keyPair.toString(); // Store securely for signing transactions.
>
> console.log({ accountId, publicKey });
> ```
> [accordion] How are Account IDs derived
>
> This Python example derives the account ID from a public key:
>
> ```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import base58
>
> public_key = 'ed25519:DGiK1ZZ4K5D89dz8YLKjhFz3xvJioSedgJbxtKna4DL6'
> pk58 = public_key.removeprefix('ed25519:')
> account_id = base58.b58decode(pk58).hex()
> print(account_id)
>
> # Output:
> # b652aa4a5697a1dd3151edf8edad3454fd3bf6b7f2c49787fccbea5c57635bab
> ```
### Create the account on-chain
Deriving an address locally does not create the account on-chain. Before the account can send transactions, including [meta-transactions](/web3-apps/tutorials/meta-transactions), it must be created on-chain and its creation charge paid.
The **first transfer to the address creates the account**, including a transfer of **0 NEAR**. The sender pays the **0.007 NEAR** creation charge through gas fees, plus other transaction fees. See [account creation costs](#account-creation-cost).
For example, [this transaction](https://testnet.nearblocks.io/txns/5bkXWTL159ZLMZurFHQGPefYYXmgTH3dZz6J8ihbQoWq) created the implicit account `f44f3...` by sending a zero-deposit transfer using the command:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near tokens influencer.testnet send-near f44f34572d483c73600d0b117b68901cab911e9363968d78c5d57501b7331bfd '0 NEAR' network-config testnet sign-with-keychain send
```
> [!TIP]
>
> Once created on-chain, an implicit account can send transactions using its access key. See [Sending Withdrawals](/integrations/create-transactions#send-a-transfer) for CLI and SDK examples.
***
## Key management and recovery
Backup keys can provide signing authority if another key is lost or deleted. Recovery depends on the access keys and contract permissions that remain available.
### Loss of [`FullAccess` key](/protocol/accounts-contracts/access-keys#full-access-keys)
Loss of the only `FullAccess` private key removes the ability to sign transactions with that key.
Only if the account had a smart contract with a recovery method implemented - which is not the default - can the account potentially be recovered after losing the `FullAccess` key.
### Loss of [`FunctionCall` access key](/protocol/accounts-contracts/access-keys#function-call-keys)
Function call keys do not have the authority to perform native transfers or replace other keys on the account.
Deleting a `FunctionCall` access key revokes its on-chain permissions to call methods on a specific smart contract. Be careful when removing these keys, specially if they are the only remaining access keys for the account.
***
## Frequently Asked Questions
> [accordion] What is a valid account ID?
>
> See [Account IDs](/protocol/accounts-contracts/account-id) for address formats and derivation.
> [accordion] What is the account model?
>
> User can have one or multiple NEAR Accounts. Each account lives on a single shard, can hold a smart contract, and store multiple keys for signing transactions.
>
> *You can read [more about NEAR accounts here](/protocol/accounts-contracts/account-model)*
> [accordion] How much does account creation cost?
>
> Account creation has a **0.007 NEAR** creation charge, collected through **gas fees**.
>
> NEAR supports **zero-balance accounts**: an account can be created with an [initial deposit of 0 NEAR](https://testnet.nearblocks.io/txns/5bkXWTL159ZLMZurFHQGPefYYXmgTH3dZz6J8ihbQoWq/execution), while the creator still pays the creation charge and transaction fees.
> [accordion] Is there a minimum account balance?
>
> Accounts pay for their own stored data. For accounts using **770 bytes or less**, the creation charge covers this storage, so no additional storage balance is required.
>
> Accounts using **more than 770 bytes** must reserve a balance to cover **all** their stored data, including the first 770 bytes, at **10^19 yoctoNEAR (0.00001 NEAR) per byte**. Query the current price using [`protocol_config`](/api/rpc/protocol#protocol-config); see [storage staking](/protocol/storage/storage-staking).
>
> Deleting stored data reduces the storage requirement, making any balance no longer needed for storage available.
>
> Creation charges and transaction gas are separate from the balance retained for storage; see [account creation costs](#account-creation-cost).
>
> An account can remain active with a zero balance if it meets the storage requirements above. Explicit deletion removes its native account state. Recreating the account starts with fresh state.
> [accordion] How many keys can an account have?
>
> An account can have arbitrarily many keys, as long as it has enough tokens for their storage.
> [accordion] How are cryptographic functions used?
>
> Account keys support `ed25519`, `secp256k1`, and `ML-DSA-65`, with different encodings and signing rules. The [transaction examples](/integrations/create-transactions) use ED25519. Consult the [cryptographic definitions for your node version](https://github.com/near/nearcore/tree/2.13.4/core/crypto/src) when implementing other key types.
> [accordion] Do you have a cold wallet implementation (ie. Ledger)?
>
> Yes, NEAR accounts can be managed with a Ledger hardware wallet using the [NEAR Ledger app](https://github.com/LedgerHQ/app-near).
# Balances & Reconciliation
Source: https://docs.near.org/integrations/balance-changes
Learn how to query and track account balances in NEAR protocol, including native NEAR tokens, fungible tokens, and balance management for integrations.
Balance changes on accounts can be tracked by using our [changes RPC endpoint](/api/rpc/contracts#view-account-changes). You can test this out by sending tokens to an account using [NEAR-CLI](/tools/cli#send-near) and then viewing the changes made.
> [!TIP]
>
> For continuous monitoring, use an [indexer](/data-infrastructure/indexers) to process finalized receipts and outcomes across shards and store the movements affecting your accounts.
***
## View Balance Changes
For an incoming deposit, identify the successful finalized receiving receipt and use its outcome’s `block_hash`; the transaction-inclusion block may be different. Query changes for the exchange **receiver**, not the original signer.
For general reconciliation, select one finalized block hash and query all relevant accounts and token contracts at that checkpoint. Inspect change causes; fees, outgoing transfers, and refunds also change balances.
The example below queries the receiving receipt of [this finalized testnet transaction](https://testnet.nearblocks.io/txns/GgjJMwGhJF8ybgMCCc6v9HxE7DPm8UJyRT6yxdJV3stj) from `influencer.testnet`. It transfers **2 NEAR** to `linkdrop.primitives.testnet`. The returned `amount` is the receiver’s total balance after the transfer, in yoctoNEAR. The `receipt_hash` identifies the receipt that caused the update.
**Example Query using HTTPie:**
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
http post https://archival-rpc.testnet.near.org jsonrpc=2.0 id=dontcare \
method=changes \
'params:={
"block_id": "C8hyrSb5LJjHS5fJXGroWA56hDenCL5YR5bVbuuguDCj",
"changes_type": "account_changes",
"account_ids": ["linkdrop.primitives.testnet"]
}'
```
**Example Response:**
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"jsonrpc": "2.0",
"result": {
"block_hash": "C8hyrSb5LJjHS5fJXGroWA56hDenCL5YR5bVbuuguDCj",
"changes": [
{
"cause": {
"receipt_hash": "Eide5UwGWRDUk3ZFJVKFu9rdL7hJiUiEZ7wqeyvwTuP4",
"type": "receipt_processing"
},
"change": {
"account_id": "linkdrop.primitives.testnet",
"amount": "2998044874632158900000000",
"code_hash": "11111111111111111111111111111111",
"locked": "0",
"storage_paid_at": 0,
"storage_usage": 182
},
"type": "account_update"
}
]
},
"id": "dontcare"
}
```
***
## Balance Snapshot
Alternatively, [query `view_account`](/api/rpc/contracts#view-account) for a balance snapshot. Use the same finalized block hash for reconciliation.
> [!TIP]
>
> Balances like this do not include Fungible Tokens; FT balances require `ft_balance_of` on the token contract
**Example HTTPie Request:**
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
http post https://archival-rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=query \
params:='{
"request_type": "view_account",
"block_id": "C8hyrSb5LJjHS5fJXGroWA56hDenCL5YR5bVbuuguDCj",
"account_id": "linkdrop.primitives.testnet"
}'
```
**Example Response:**
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"jsonrpc": "2.0",
"result": {
"amount": "2998044874632158900000000",
"block_hash": "C8hyrSb5LJjHS5fJXGroWA56hDenCL5YR5bVbuuguDCj",
"block_height": 271205691,
"code_hash": "11111111111111111111111111111111",
"locked": "0",
"storage_paid_at": 0,
"storage_usage": 182
},
"id": "dontcare"
}
```
***
## Frequently Asked Questions
> [accordion] Which balance look-ups exist? What is required?
>
> We have an [RPC method for viewing account](/api/rpc/contracts#view-account).
>
> The [JS implementation is here](https://github.com/near/near-api-js/blob/d7f0cb87ec320b723734045a4ee9d17d94574a19/src/providers/json-rpc-provider.ts#L73). Note that in this RPC interface you can specify the finality requirement (whether to query the latest state or finalized state).
>
> For custody purposes, query finalized state.
# Blocks and Finality
Source: https://docs.near.org/integrations/blocks-and-finality
Finalized block queries, skipped heights, chunk processing, and transaction execution milestones for exchanges.
NEAR blocks contain chunks from individual shards. Transactions can produce receipt chains that execute across multiple blocks; exchanges confirm asset movements using successful, finalized receipt outcomes.
***
## Block processing
Typical block time is around **600ms**, with finality around **1.2s**. Confirm deposits using finalized execution outcomes. Query the latest finalized block with `{"finality": "final"}`:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
http post https://rpc.mainnet.near.org method=block params:='{"finality":"final"}' id=123 jsonrpc=2.0
```
### Skipped block heights
Block heights can be skipped when a block producer misses its slot. If height 101 is skipped, block 102 references block 100 as its previous block. Follow `header.prev_hash` across gaps when scanning the chain.
### New chunks
A block's `chunks` array can include chunks from earlier blocks when a shard produces no new chunk. Process a chunk as new only when its `height_included` equals the containing block's `header.height`.
***
## Transaction execution milestones
When sending or querying a transaction, you can control which execution milestone the RPC waits for before returning a response by setting the [`wait_until` field](/api/rpc/transactions#the-wait_until-field) in `send_tx`, `tx`, or `EXPERIMENTAL_tx_status`:
| Value | Milestone |
| - | - |
| `NONE` | Submission returns without waiting for inclusion. |
| `INCLUDED` | Transaction included in a block. |
| `EXECUTED_OPTIMISTIC` (default) | All non-refund receipts executed; blocks may still be unfinalized. |
| `INCLUDED_FINAL` | Transaction included in a finalized block. |
| `EXECUTED` | Transaction block finalized and all non-refund receipts executed. |
| `FINAL` | Transaction and all receipt outcomes finalized, including refunds. |
For exchange settlement, request `wait_until: "FINAL"`, verify `final_execution_status === "FINAL"`, and inspect receipt outcomes for success or failure. Finality alone does not indicate successful execution.
Query an existing transaction using its hash and original signer:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
http post https://rpc.mainnet.near.org jsonrpc=2.0 id=txstatus method=tx \
params:='{"tx_hash":"","sender_account_id":"","wait_until":"FINAL"}'
```
For full receipt bodies, use [`EXPERIMENTAL_tx_status`](/api/rpc/transactions#transaction-status-with-receipts). If the RPC times out, poll the saved transaction hash; see [submission recovery](/integrations/create-transactions#submission-errors-and-retries).
***
## Frequently Asked Questions
> [accordion] Which consensus algorithm does NEAR use?
>
> NEAR is a sharded **proof-of-stake** blockchain using Doomslug consensus. [Nightshade](/papers/Nightshade.pdf) describes its sharding architecture.
> [accordion] How does on-chain transaction finality work?
>
> Query a block with `finality: "final"` to obtain finalized block context. For a transaction, request `wait_until: "FINAL"` and verify `final_execution_status === "FINAL"` before crediting its successful asset movements. The transaction’s inclusion block can finalize before downstream receipts finish.
>
> Typical finality is approximately 1.2 seconds. Confirm deposits using finalized execution outcomes. See [transaction status](/api/rpc/transactions) and [native deposit checks](/integrations/deposits#transfer-from-function-call).
# Sending Withdrawals
Source: https://docs.near.org/integrations/create-transactions
Learn how to create, sign, and send transactions on NEAR protocol, including transaction structure, actions, and best practices for integration.
You can send a transfer on NEAR using [NEAR CLI](/tools/cli) or an API library such as [near-api-js](https://github.com/near/near-api-js), [near-kit](https://github.com/r-near/near-kit), or [near-api-rs](https://github.com/near/near-api-rs).
***
## Send a Transfer
> [tab] High-level JS
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { Account, JsonRpcProvider, KeyPairSigner, actions, nearToYocto } from "near-api-js";
>
> const sender = "sender.testnet";
> const privateKey = process.env.SENDER_PRIVATE_KEY;
> const signer = KeyPairSigner.fromSecretKey(privateKey);
>
> const receiver = "receiver.testnet";
>
> const provider = new JsonRpcProvider({ url: `https://rpc.testnet.near.org` });
> const senderAccount = new Account(sender, provider, signer);
>
> const result = await senderAccount.signAndSendTransaction({
> receiverId: receiver,
> actions: [actions.transfer(nearToYocto("1.5"))],
> waitUntil: "FINAL",
> });
> console.log(result);
> ```
> [tab] Low-level JS
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { Account, JsonRpcProvider, KeyPairSigner, actions, nearToYocto } from "near-api-js";
>
> const sender = "sender.testnet";
> const privateKey = process.env.SENDER_PRIVATE_KEY;
> const signer = KeyPairSigner.fromSecretKey(privateKey);
>
> const receiver = "receiver.testnet";
>
> const provider = new JsonRpcProvider({ url: `https://rpc.testnet.near.org` });
> const senderAccount = new Account(sender, provider, signer);
>
> const transaction = await senderAccount.createTransaction({
> receiverId: receiver,
> actions: [actions.transfer(nearToYocto("1.5"))],
> publicKey: await signer.getPublicKey(),
> });
> const { signedTransaction } = await signer.signTransaction(transaction);
>
> const result = await provider.sendTransactionUntil(signedTransaction, "FINAL");
> console.log(result);
> ```
> [tab] NEAR CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near tokens send-near '1.5 NEAR' network-config testnet sign-with-keychain send
> ```
>
> > [!TIP]
> >
> > The `near-cli` allows you to use keys from multiple sources, including the keychain, local files, ledger, or a private key directly.
> [!TIP]
>
> A plain transfer to a **non-created implicit** account [creates it](/integrations/accounts#transferring-to-the-implicit-account); the sender pays the account-creation charge.
> [!NOTE]
>
> A plain transfer to a non-existing **named account** fails and refunds the transferred amount, while consumed gas remains charged.
> [!WARNING]
>
> Never use `DeleteAccount` to withdraw or sweep an account's balance. If the beneficiary does not exist, the remaining balance is burned. Transfer first, wait for finalized success and outstanding refunds, then delete the account if needed. See [safe account deletion](/protocol/network/token-loss#deleting-account-with-non-existent-beneficiary).
### Transaction results
Inspect `result.status` for success or failure and require `final_execution_status === "FINAL"` before treating the transfer as complete. The example below shows a finalized FT transfer-and-call submitted by `influencer.testnet` on testnet.
> [accordion] Example FT transfer-and-call response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "final_execution_status": "FINAL",
> "receipts_outcome": [
> {
> "block_hash": "F2EuP23LqgsiQhYkjp3P3wP7RqpTU9rJQPzHAtJaAYed",
> "id": "C1vLKuWqXokpEHyVMkvH9erBSySgBEcny2xPrrAPKNAh",
> "outcome": {
> "executor_id": "bg10003.tkn.primitives.testnet",
> "gas_burnt": 2567973604837,
> "logs": [
> "EVENT_JSON:{\"standard\":\"nep141\",\"version\":\"1.0.0\",\"event\":\"ft_transfer\",\"data\":[{\"old_owner_id\":\"influencer.testnet\",\"new_owner_id\":\"linkdrop.primitives.testnet\",\"amount\":\"5000\"}]}"
> ],
> "metadata": {
> "contracts": [
> {
> "local": "GYERWoeEc8vr5J8B15ixRHegkDrcNYZS1MSKJ7PNyEzA"
> }
> ],
> "gas_profile": [
> {
> "cost": "FUNCTION_CALL_BASE",
> "cost_category": "ACTION_COST",
> "gas_used": "400000000000"
> },
> {
> "cost": "FUNCTION_CALL_BYTE",
> "cost_category": "ACTION_COST",
> "gas_used": "3781255452"
> },
> {
> "cost": "NEW_ACTION_RECEIPT",
> "cost_category": "ACTION_COST",
> "gas_used": "289092464624"
> },
> {
> "cost": "BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "8737347663"
> },
> {
> "cost": "CONTRACT_LOADING_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "35445963"
> },
> {
> "cost": "CONTRACT_LOADING_BYTES",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "245748219885"
> },
> {
> "cost": "LOG_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "3543313050"
> },
> {
> "cost": "LOG_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "2375782380"
> },
> {
> "cost": "PROMISE_RETURN",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "560152386"
> },
> {
> "cost": "READ_CACHED_TRIE_NODE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "68400000000"
> },
> {
> "cost": "READ_MEMORY_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "49587400800"
> },
> {
> "cost": "READ_MEMORY_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "2455661118"
> },
> {
> "cost": "READ_REGISTER_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "20137321488"
> },
> {
> "cost": "READ_REGISTER_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "21387954"
> },
> {
> "cost": "STORAGE_READ_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "169070537247"
> },
> {
> "cost": "STORAGE_READ_KEY_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "1857151980"
> },
> {
> "cost": "STORAGE_READ_VALUE_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "370326264"
> },
> {
> "cost": "STORAGE_WRITE_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "192590208000"
> },
> {
> "cost": "STORAGE_WRITE_EVICTED_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "2119742262"
> },
> {
> "cost": "STORAGE_WRITE_KEY_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "4228972020"
> },
> {
> "cost": "STORAGE_WRITE_VALUE_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "2047223574"
> },
> {
> "cost": "TOUCHING_TRIE_NODE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "41040000000"
> },
> {
> "cost": "UTF8_DECODING_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "9335337183"
> },
> {
> "cost": "UTF8_DECODING_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "69104573523"
> },
> {
> "cost": "WASM_INSTRUCTION",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "41136977244"
> },
> {
> "cost": "WRITE_MEMORY_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "25234153749"
> },
> {
> "cost": "WRITE_MEMORY_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "634638876"
> },
> {
> "cost": "WRITE_REGISTER_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "25789702374"
> },
> {
> "cost": "WRITE_REGISTER_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "684281520"
> }
> ],
> "version": 4
> },
> "receipt_ids": [
> "CSCdHkuqoS4pUbWdewtmVT5fBd6qF1YwubYWwULNA1LC",
> "6J3B1L9mEQTiZDGAVwBm68z9mSin1M2DG81BkPtoiy7",
> "6JXrv4TmrJNzGQjXkAdo6A2AMEhrNW5jCSSsK4ofXzs6"
> ],
> "status": {
> "SuccessReceiptId": "6J3B1L9mEQTiZDGAVwBm68z9mSin1M2DG81BkPtoiy7"
> },
> "tokens_burnt": "256797360483700000000"
> },
> "proof": []
> },
> {
> "block_hash": "77Wb4yo8QgMbmzohczcFwSRbYWqPJRJmKjHLefRPMGuV",
> "id": "CSCdHkuqoS4pUbWdewtmVT5fBd6qF1YwubYWwULNA1LC",
> "outcome": {
> "executor_id": "linkdrop.primitives.testnet",
> "gas_burnt": 1618792626321,
> "logs": [],
> "metadata": {
> "contracts": [
> {
> "local": "6yMWYyHYAk2BHwAM85PPYHRyzKBxP6qRXVvw1nrdUqxK"
> }
> ],
> "gas_profile": [
> {
> "cost": "NEW_DATA_RECEIPT_BYTE",
> "cost_category": "ACTION_COST",
> "gas_used": "194687178"
> },
> {
> "cost": "BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "4236289776"
> },
> {
> "cost": "CONTRACT_LOADING_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "35445963"
> },
> {
> "cost": "CONTRACT_LOADING_BYTES",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "278766929925"
> },
> {
> "cost": "READ_CACHED_TRIE_NODE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "57000000000"
> },
> {
> "cost": "READ_MEMORY_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "18269042400"
> },
> {
> "cost": "READ_MEMORY_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "456159960"
> },
> {
> "cost": "READ_REGISTER_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "10068660744"
> },
> {
> "cost": "READ_REGISTER_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "18431094"
> },
> {
> "cost": "STORAGE_READ_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "112713691498"
> },
> {
> "cost": "STORAGE_READ_KEY_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "309525330"
> },
> {
> "cost": "STORAGE_READ_VALUE_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "544267388"
> },
> {
> "cost": "STORAGE_WRITE_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "128393472000"
> },
> {
> "cost": "STORAGE_WRITE_EVICTED_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "3115378779"
> },
> {
> "cost": "STORAGE_WRITE_KEY_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "704828670"
> },
> {
> "cost": "STORAGE_WRITE_VALUE_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "3008798283"
> },
> {
> "cost": "TOUCHING_TRIE_NODE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "59280000000"
> },
> {
> "cost": "WASM_INSTRUCTION",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "20835472944"
> },
> {
> "cost": "WRITE_MEMORY_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "14018974305"
> },
> {
> "cost": "WRITE_MEMORY_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "552925716"
> },
> {
> "cost": "WRITE_REGISTER_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "17193134916"
> },
> {
> "cost": "WRITE_REGISTER_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "851550336"
> }
> ],
> "version": 4
> },
> "receipt_ids": [
> "3JuqUSzjFxjEE5oHyBvwf5d1Wu1ZXZ3yPXoWVzW2iTH6"
> ],
> "status": {
> "SuccessValue": "IjAi"
> },
> "tokens_burnt": "161879262632100000000"
> },
> "proof": [
> {
> "direction": "Right",
> "hash": "HZCuDdmCYaWqxUzHp9A9VVJmYgzqdwNcLVe8EWsyhYqN"
> },
> {
> "direction": "Right",
> "hash": "AoqrPtKyGcVQXbEv719BgeXbq9yZEJoJZC1d2c99U9Bc"
> }
> ]
> },
> {
> "block_hash": "CQoryo6QvNPkBjXBfL7ckUz3rWw8wTnxWDjVMpsDWZHn",
> "id": "3JuqUSzjFxjEE5oHyBvwf5d1Wu1ZXZ3yPXoWVzW2iTH6",
> "outcome": {
> "executor_id": "influencer.testnet",
> "gas_burnt": 223182562500,
> "logs": [],
> "metadata": {
> "contracts": [
> {
> "local": "8rcuPGUwWycBSwoHAN7UjAQonPkgu7KJYP6RSfiwcQgP"
> }
> ],
> "gas_profile": [],
> "version": 4
> },
> "receipt_ids": [],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "0"
> },
> "proof": []
> },
> {
> "block_hash": "CQoryo6QvNPkBjXBfL7ckUz3rWw8wTnxWDjVMpsDWZHn",
> "id": "6J3B1L9mEQTiZDGAVwBm68z9mSin1M2DG81BkPtoiy7",
> "outcome": {
> "executor_id": "bg10003.tkn.primitives.testnet",
> "gas_burnt": 1370288853457,
> "logs": [],
> "metadata": {
> "contracts": [
> {
> "local": "GYERWoeEc8vr5J8B15ixRHegkDrcNYZS1MSKJ7PNyEzA"
> }
> ],
> "gas_profile": [
> {
> "cost": "BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "4765825998"
> },
> {
> "cost": "CONTRACT_LOADING_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "35445963"
> },
> {
> "cost": "CONTRACT_LOADING_BYTES",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "245748219885"
> },
> {
> "cost": "READ_CACHED_TRIE_NODE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "2280000000"
> },
> {
> "cost": "READ_MEMORY_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "10439452800"
> },
> {
> "cost": "READ_MEMORY_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "190066650"
> },
> {
> "cost": "READ_REGISTER_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "12585825930"
> },
> {
> "cost": "READ_REGISTER_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "18825342"
> },
> {
> "cost": "STORAGE_READ_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "56356845749"
> },
> {
> "cost": "STORAGE_READ_KEY_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "154762665"
> },
> {
> "cost": "STORAGE_READ_VALUE_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "190774136"
> },
> {
> "cost": "STORAGE_WRITE_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "64196736000"
> },
> {
> "cost": "STORAGE_WRITE_EVICTED_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "1091988438"
> },
> {
> "cost": "STORAGE_WRITE_KEY_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "352414335"
> },
> {
> "cost": "STORAGE_WRITE_VALUE_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "1054630326"
> },
> {
> "cost": "TOUCHING_TRIE_NODE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "29640000000"
> },
> {
> "cost": "WASM_INSTRUCTION",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "17808553620"
> },
> {
> "cost": "WRITE_MEMORY_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "16822769166"
> },
> {
> "cost": "WRITE_MEMORY_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "563820804"
> },
> {
> "cost": "WRITE_REGISTER_BASE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "17193134916"
> },
> {
> "cost": "WRITE_REGISTER_BYTE",
> "cost_category": "WASM_HOST_COST",
> "gas_used": "486600192"
> }
> ],
> "version": 4
> },
> "receipt_ids": [
> "8dZqVCdRhy2gvBUiFNAKhFJxx5kqR85387uZzipxWtyi"
> ],
> "status": {
> "SuccessValue": "IjUwMDAi"
> },
> "tokens_burnt": "137028885345700000000"
> },
> "proof": []
> },
> {
> "block_hash": "5wRsvygLPZywStcHNVcq6gzwoWDyzwtpNTFtDihLjnL",
> "id": "8dZqVCdRhy2gvBUiFNAKhFJxx5kqR85387uZzipxWtyi",
> "outcome": {
> "executor_id": "influencer.testnet",
> "gas_burnt": 223182562500,
> "logs": [],
> "metadata": {
> "contracts": [
> {
> "local": "8rcuPGUwWycBSwoHAN7UjAQonPkgu7KJYP6RSfiwcQgP"
> }
> ],
> "gas_profile": [],
> "version": 4
> },
> "receipt_ids": [],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "0"
> },
> "proof": []
> },
> {
> "block_hash": "77Wb4yo8QgMbmzohczcFwSRbYWqPJRJmKjHLefRPMGuV",
> "id": "6JXrv4TmrJNzGQjXkAdo6A2AMEhrNW5jCSSsK4ofXzs6",
> "outcome": {
> "executor_id": "influencer.testnet",
> "gas_burnt": 223182562500,
> "logs": [],
> "metadata": {
> "contracts": [
> {
> "local": "8rcuPGUwWycBSwoHAN7UjAQonPkgu7KJYP6RSfiwcQgP"
> }
> ],
> "gas_profile": [],
> "version": 4
> },
> "receipt_ids": [],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "0"
> },
> "proof": []
> }
> ],
> "status": {
> "SuccessValue": "IjUwMDAi"
> },
> "transaction": {
> "actions": [
> {
> "FunctionCall": {
> "args": "eyJyZWNlaXZlcl9pZCI6Imxpbmtkcm9wLnByaW1pdGl2ZXMudGVzdG5ldCIsImFtb3VudCI6IjUwMDAiLCJtc2ciOiI4In0=",
> "deposit": "1",
> "gas": 300000000000000,
> "method_name": "ft_transfer_call"
> }
> }
> ],
> "hash": "42Ac8N8XpAJAxcmM61mnGRvznYjDVtbrkdbtHy9RbsAP",
> "nonce": 156033053000611,
> "priority_fee": 0,
> "public_key": "ed25519:GnsdHdSrhe8v3MMAQi2bnXR59xMDwdkSRAFZ961ydxWZ",
> "receiver_id": "bg10003.tkn.primitives.testnet",
> "signature": "ed25519:3DQL5dUQhLBrJEvB1KNcxMaoGwKotV6FtNkgkYEWY2jgaGLYgncy2bSjkjRg45bCDjFqr8AgJnEEqf4sPAXNAWnB",
> "signer_id": "influencer.testnet"
> },
> "transaction_outcome": {
> "block_hash": "CV64wnbwjjwCY7xnH5AG4hqrKnsMRZGGbWY13qQAWWiL",
> "id": "42Ac8N8XpAJAxcmM61mnGRvznYjDVtbrkdbtHy9RbsAP",
> "outcome": {
> "executor_id": "influencer.testnet",
> "gas_burnt": 312207983205,
> "logs": [],
> "metadata": {
> "gas_profile": null,
> "version": 1
> },
> "receipt_ids": [
> "C1vLKuWqXokpEHyVMkvH9erBSySgBEcny2xPrrAPKNAh"
> ],
> "status": {
> "SuccessReceiptId": "C1vLKuWqXokpEHyVMkvH9erBSySgBEcny2xPrrAPKNAh"
> },
> "tokens_burnt": "31220798320500000000"
> },
> "proof": []
> }
> }
> ```
For detailed information, see [transaction receipts](/protocol/transactions/transaction-execution). To view the transaction in [NearBlocks Explorer](https://testnet.nearblocks.io/), use `result.transaction.hash`.
***
## Concurrent Transactions
If you start sending multiple transactions from a same account - e.g. when creating a relayer - you need to manage nonces carefully to avoid conflicts.
In NEAR, accounts can have multiple keys, each with its own nonce sequence. So the simplest way to avoid `nonce` collisions is to use multiple access keys for concurrent transactions.
In `near-api-js` the [`MultiKeySigner`](https://near.github.io/near-api-js/classes/signers_multikey_signer.MultiKeySigner.html) rotates through a set of keys when creating transactions:
```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { MultiKeySigner } from "near-api-js";
const secretKeys = [
process.env.SENDER_PRIVATE_KEY,
process.env.SENDER_PRIVATE_KEY_2,
];
const multiKeySigner = MultiKeySigner.fromSecretKeys(secretKeys);
const concurrentAccount = new Account(sender, provider, multiKeySigner);
const receivers = [
"receiver.testnet",
"receiver-2.testnet",
"receiver-3.testnet",
"receiver-4.testnet",
"receiver-5.testnet",
];
const transfers = [];
for (const receiverId of receivers) {
transfers.push(concurrentAccount.signAndSendTransaction({
receiverId,
actions: [actions.transfer(nearToYocto("1.5"))],
waitUntil: "FINAL",
retries: 0,
}));
}
const results = await Promise.allSettled(transfers);
console.log(results);
```
***
## Submission errors and retries
With `near-api-js` 7.3.1, error handling depends on the method used:
| Method | Error behavior |
| - | - |
| `Account.signAndSendTransaction()` | Throws RPC errors and, by default (`throwOnFailure: true`), execution failures. Set `throwOnFailure: false` to inspect execution failures in the returned `result.status`; RPC errors still throw. |
| `provider.sendTransactionUntil()` or `provider.sendJsonRpc("send_tx", …)` | Throws RPC errors, but returns execution failures in `result.status.Failure`. Check both `final_execution_status` and `status` before settling the withdrawal. |
| `Promise.allSettled()` in the concurrent example | Preserves each call's fulfilled result or rejected error in input order. Inspect every entry independently. |
Typed errors are exported from `near-api-js/rpc-errors`. When the high-level method throws a transaction or contract execution error derived from a submitted transaction, its `transactionResult` contains the RPC response, including receipt outcomes. Use that response to inspect `status.Failure` and the failed receipt; read-only call errors do not include transaction outcomes.
`Account.signAndSendTransaction()` defaults to up to 10 retries after `InvalidNonceError`, constructing and signing a new transaction on each retry. These examples set `retries: 0` so withdrawal recovery controls replacement transactions. This setting does not disable the provider's HTTP retries.
Before broadcasting a withdrawal, persist its business intent, network, signer, reserved nonce, signed bytes, and transaction hash. Keep one recovery process in control of that intent until its outcome is resolved.
| Result | Handling |
| - | - |
| Receiver shard congested (`ShardCongestedError` or `ShardStuckError` in `near-api-js`, or `ShardCongested` or `ShardStuck` in the raw `INVALID_TRANSACTION` error) | The shard of the receiver account is too busy or is not producing chunks, so the node did not accept the transaction. The node checks congestion before the key, nonce, and balance, so this error does not mean the rest of the transaction is valid. Do not sign a replacement. Wait and resend the same signed bytes while their reference block hash is still valid. If the resend fails with a different validation error, handle it as an explicit validation rejection. |
| Explicit validation rejection | For any other validation error, correct the reported key, permissions, balance, nonce, or block hash. If this intent was submitted previously, resolve that earlier hash before creating a replacement. |
| Timeout, connection loss, server error, or unknown transaction | Submission is uncertain. Query the saved hash and signer on the same network, using another provider or an archival node when needed. Do not assume the withdrawal failed. |
| Included or still executing | Poll [`tx` or `EXPERIMENTAL_tx_status`](/api/rpc/transactions#transaction-status-with-receipts) with `wait_until: "FINAL"`; require `final_execution_status === "FINAL"` before settlement. |
| Finalized execution failure | Inspect the failed receipt and its `ActionError.index`, where present. Account for fees and refunds, and reconcile any earlier successful receipts before retrying the business operation. |
If rebroadcasting is necessary, resend **the same signed bytes** while their reference block remains valid. A newly signed transaction has a different hash and can execute a second payment. An expired block hash or consumed nonce on a later attempt does not prove that the original transaction never executed. Resolve the original outcome and reconcile balances before issuing a replacement under the same intent lock.
Actions within one receipt are atomic; separate receipts are not rolled back together. A contract call can fail after an earlier receipt has transferred funds. Keep transport errors, validation rejections, and execution failures distinct in your withdrawal records.
***
## Frequently Asked Questions
> [accordion] What is the fee structure for on-chain transactions?
>
> NEAR uses a gas-based model where prices are generally deterministically adjusted based on congestion of the network.
>
> We avoid making changes that are too large through re-sharding by changing number of available shards (and thus throughput).
>
> Accounts don’t have associated resources. Gas amount is predetermined for all transactions except function calls. For function call transactions the user (or more likely the developer) attaches the required amount of gas. Unused prepaid gas is refunded according to current runtime rules, including any configured unused-gas refund penalty. Query the runtime configuration and budget gas for the contract being called.
> [accordion] How do we know how much gas to add to a transaction?
>
> * See [Gas fees](/protocol/transactions/gas).
> * See API documentation for [discovering gas price via RPC here](/api/rpc/gas#gas-price).
>
> The issuer of a transaction should attach some amount of gas by taking a guess at budget which will get the transaction processed. The contract knows how much to fund different cross contract calls. Gas price is calculated and fixed per block, but may change from block to block depending on how full / busy the block is. If blocks become more than half full then gas price increases.
>
> See [gas purchase, burn, and refund accounting](/protocol/transactions/gas) for the current fee model.
> [accordion] How do we follow Tx status?
>
> See related [RPC interface for fetching transaction status here](/api/rpc/transactions#transaction-status).
# Receiving Deposits
Source: https://docs.near.org/integrations/deposits
Track finalized native NEAR deposits through blocks, chunks, and receipt outcomes.
Native NEAR deposits can arrive as direct transfers or as transfers generated by contract calls. Both are detected through successful, finalized receipt outcomes. For fungible-token deposits, see [Fungible Tokens](/integrations/fungible-tokens).
***
## Detecting Deposits
### Find Incoming Receipts
Exchange can [query finalized blocks](/api/rpc/block-chunk#block-details) and their new chunks, or consume a receipt stream from an indexer. Track incoming receipts across all shards: scanning only original transaction receivers misses deposits generated by contracts in later blocks. Inspect chunk receipts as well as transactions, and resolve receipt outcomes even when their original transactions were included earlier.
For indexers and hosted data APIs, see [Accessing On-chain Data](/integrations/on-chain-data).
### Verify Finalized Execution
For a known transaction, [query status with receipts](/api/rpc/transactions#transaction-status-with-receipts) using named parameters `tx_hash`, `sender_account_id`, and `wait_until: "FINAL"`. Require `final_execution_status === "FINAL"`. An indexer must independently establish finality of each receipt’s outcome block.
For each receipt addressed to an exchange-controlled account, match `receipt_id` to `receipts_outcome[].id` and verify that `outcome.executor_id` matches the receiver. A successful receipt has `SuccessValue` or `SuccessReceiptId`, not `Failure` or `Unknown`.
### Identify Deposit Amounts
Inspect **every** `Transfer` action, including those in mixed-action receipts. Record the deposit amount and action index; review key changes, contract deployment, or deletion in the same receipt before accepting it under your custody policy.
Receipts with `predecessor_id: "system"` are [refunds or system payouts](/protocol/transactions/transaction-execution#refund-receipts); reconcile them separately rather than crediting a new customer deposit. NEAR attached to a `FunctionCall` needs an approved exchange-contract interface that authenticates the customer and accounts for accepted funds, forwarding, and refunds. Do not infer a deposit solely from the attached amount.
***
## Direct Transfer Example
[This testnet transaction](https://testnet.nearblocks.io/txns/GgjJMwGhJF8ybgMCCc6v9HxE7DPm8UJyRT6yxdJV3stj) transfers **2 NEAR** from `influencer.testnet` to `linkdrop.primitives.testnet`. Query its finalized receipt details:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
http post https://archival-rpc.testnet.near.org jsonrpc=2.0 id=deposit method=EXPERIMENTAL_tx_status \
params:='{"tx_hash":"GgjJMwGhJF8ybgMCCc6v9HxE7DPm8UJyRT6yxdJV3stj","sender_account_id":"influencer.testnet","wait_until":"FINAL"}'
```
Selected fields from the response:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"final_execution_status": "FINAL",
"receipts": [
{
"receipt_id": "Eide5UwGWRDUk3ZFJVKFu9rdL7hJiUiEZ7wqeyvwTuP4",
"predecessor_id": "influencer.testnet",
"receiver_id": "linkdrop.primitives.testnet",
"receipt": {
"Action": {
"actions": [{ "Transfer": { "deposit": "2000000000000000000000000" } }]
}
}
}
],
"receipts_outcome": [
{
"id": "Eide5UwGWRDUk3ZFJVKFu9rdL7hJiUiEZ7wqeyvwTuP4",
"block_hash": "C8hyrSb5LJjHS5fJXGroWA56hDenCL5YR5bVbuuguDCj",
"outcome": {
"executor_id": "linkdrop.primitives.testnet",
"status": { "SuccessValue": "" }
}
}
]
}
```
The receipt ID matches the outcome ID, the executor matches the receiver, and execution succeeded and finalized. The `Transfer.deposit` is `2000000000000000000000000` yoctoNEAR (**2 NEAR**). If the receiver is a customer-assigned account you control, record that movement once using its receipt ID and action index (`0` here). The receiver's balance after this transfer is shown in [Balances & Reconciliation](/integrations/balance-changes).
***
## Transfer from Function Call
NEAR allows transfers to happen within a function call. More importantly, when an account is deployed with some contract, it is possible that the only way to transfer tokens from that account is through a function call. Therefore, **exchanges need to support transfers through function calls** as well.
The lockup and multisig examples below show how contract calls generate transfer receipts and how to inspect their execution outcomes.
### Example of transfer from a lockup contract
A contract `evgeny.lockup.near` is deployed and we can check its owner by
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-read-only evgeny.lockup.near get_owner_account_id json-args '{}' network-config testnet now
# View call: evgeny.lockup.near.get_owner_account_id()
# 'evgeny.near'
```
Now we want to transfer some unlocked tokens (1 NEAR) with the following call
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction evgeny.lockup.near transfer json-args '{"amount":"1000000000000000000000000", "receiver_id": "evgeny.near"}' prepaid-gas '100.0 Tgas' attached-deposit '0 NEAR' sign-as evgeny.near network-config testnet sign-with-keychain send
```
**Note**: the response below can be obtained by hitting the RPC with the transaction hash and NEAR account like this:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
http post https://rpc.testnet.near.org jsonrpc=2.0 id=txstatus method=EXPERIMENTAL_tx_status \
params:='{"tx_hash":"GXP8YaSonoN2eBY6dB3FbMN2NyYD2JeJJvKdvbL4Jmb2","sender_account_id":"evgeny.near","wait_until":"FINAL"}'
```
> [accordion] Example RPC response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "id": "123",
> "jsonrpc": "2.0",
> "result": {
> "receipts": [
> {
> "predecessor_id": "evgeny.near",
> "receipt": {
> "Action": {
> "actions": [
> {
> "FunctionCall": {
> "args": "eyJhbW91bnQiOiIxMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwIiwicmVjZWl2ZXJfaWQiOiJldmdlbnkubmVhciJ9",
> "deposit": "0",
> "gas": 100000000000000,
> "method_name": "transfer"
> }
> }
> ],
> "gas_price": "186029458",
> "input_data_ids": [],
> "output_data_receivers": [],
> "signer_id": "evgeny.near",
> "signer_public_key": "ed25519:BVRTxEEMx3gFceSgJtnvPFbSnPDwwUzHe6KGduRh5Byq"
> }
> },
> "receipt_id": "CyJL22SYqt26qgh2XVnk9MGfvzgyiiq5Lny7DdbTdTWU",
> "receiver_id": "evgeny.lockup.near"
> },
> {
> "predecessor_id": "evgeny.lockup.near",
> "receipt": {
> "Action": {
> "actions": [
> {
> "Transfer": {
> "deposit": "1000000000000000000000000"
> }
> }
> ],
> "gas_price": "186029458",
> "input_data_ids": [],
> "output_data_receivers": [],
> "signer_id": "evgeny.near",
> "signer_public_key": "ed25519:BVRTxEEMx3gFceSgJtnvPFbSnPDwwUzHe6KGduRh5Byq"
> }
> },
> "receipt_id": "EvHfj4fUyVuLBRKNdCZmFGr4WfqwYf7YCbzFsRGFTFJC",
> "receiver_id": "evgeny.near"
> },
> {
> "predecessor_id": "system",
> "receipt": {
> "Action": {
> "actions": [
> {
> "Transfer": {
> "deposit": "19200274886926125000"
> }
> }
> ],
> "gas_price": "0",
> "input_data_ids": [],
> "output_data_receivers": [],
> "signer_id": "evgeny.near",
> "signer_public_key": "ed25519:BVRTxEEMx3gFceSgJtnvPFbSnPDwwUzHe6KGduRh5Byq"
> }
> },
> "receipt_id": "J1bBKH43nXHYg4NuS97R1PFzdZchrJboVAdRsK5NRrAv",
> "receiver_id": "evgeny.near"
> },
> {
> "predecessor_id": "system",
> "receipt": {
> "Action": {
> "actions": [
> {
> "Transfer": {
> "deposit": "18655658845681462514128"
> }
> }
> ],
> "gas_price": "0",
> "input_data_ids": [],
> "output_data_receivers": [],
> "signer_id": "evgeny.near",
> "signer_public_key": "ed25519:BVRTxEEMx3gFceSgJtnvPFbSnPDwwUzHe6KGduRh5Byq"
> }
> },
> "receipt_id": "6PFaxnNvK5r6qxBq5WfV9uGjoNM6qjhHwLehLP1qak9d",
> "receiver_id": "evgeny.near"
> }
> ],
> "receipts_outcome": [
> {
> "block_hash": "9boEKq9G1UFsEuzmuQrxh5dkRc8xsv8PSPGEkYiTyRLj",
> "id": "CyJL22SYqt26qgh2XVnk9MGfvzgyiiq5Lny7DdbTdTWU",
> "outcome": {
> "executor_id": "evgeny.lockup.near",
> "gas_burnt": 3574640311481,
> "logs": [
> "Transferring 1000000000000000000000000 to account @evgeny.near"
> ],
> "receipt_ids": [
> "EvHfj4fUyVuLBRKNdCZmFGr4WfqwYf7YCbzFsRGFTFJC",
> "6PFaxnNvK5r6qxBq5WfV9uGjoNM6qjhHwLehLP1qak9d"
> ],
> "status": {
> "SuccessReceiptId": "EvHfj4fUyVuLBRKNdCZmFGr4WfqwYf7YCbzFsRGFTFJC"
> },
> "tokens_burnt": "357464031148100000000"
> },
> "proof": []
> },
> {
> "block_hash": "7qn4BjmMD4QbyVvMa8QEzm7h5YuhoGTFTgLeNMUp85UQ",
> "id": "EvHfj4fUyVuLBRKNdCZmFGr4WfqwYf7YCbzFsRGFTFJC",
> "outcome": {
> "executor_id": "evgeny.near",
> "gas_burnt": 223182562500,
> "logs": [],
> "receipt_ids": ["J1bBKH43nXHYg4NuS97R1PFzdZchrJboVAdRsK5NRrAv"],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "22318256250000000000"
> },
> "proof": [
> {
> "direction": "Right",
> "hash": "AwHdk5dushTSXHFBt3R5MiexjiXybwdnEaB7L9iJ5F6t"
> }
> ]
> },
> {
> "block_hash": "46788Ay85YGnQaH5tfbboQNWJs3gyXsPbcWzRyxqw56K",
> "id": "J1bBKH43nXHYg4NuS97R1PFzdZchrJboVAdRsK5NRrAv",
> "outcome": {
> "executor_id": "evgeny.near",
> "gas_burnt": 0,
> "logs": [],
> "receipt_ids": [],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "0"
> },
> "proof": []
> },
> {
> "block_hash": "7qn4BjmMD4QbyVvMa8QEzm7h5YuhoGTFTgLeNMUp85UQ",
> "id": "6PFaxnNvK5r6qxBq5WfV9uGjoNM6qjhHwLehLP1qak9d",
> "outcome": {
> "executor_id": "evgeny.near",
> "gas_burnt": 0,
> "logs": [],
> "receipt_ids": [],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "0"
> },
> "proof": [
> {
> "direction": "Left",
> "hash": "9RRJpH5VdDxsHpp323EshcAauV5wUNDyW9FpEJBRXXq8"
> }
> ]
> }
> ],
> "status": {
> "SuccessValue": ""
> },
> "transaction": {
> "actions": [
> {
> "FunctionCall": {
> "args": "eyJhbW91bnQiOiIxMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwIiwicmVjZWl2ZXJfaWQiOiJldmdlbnkubmVhciJ9",
> "deposit": "0",
> "gas": 100000000000000,
> "method_name": "transfer"
> }
> }
> ],
> "hash": "GXP8YaSonoN2eBY6dB3FbMN2NyYD2JeJJvKdvbL4Jmb2",
> "nonce": 6,
> "public_key": "ed25519:BVRTxEEMx3gFceSgJtnvPFbSnPDwwUzHe6KGduRh5Byq",
> "receiver_id": "evgeny.lockup.near",
> "signature": "ed25519:4nfzTMpQJKCY3KaqUTFig4Xy9uxwbMeQpMJjtNKsXmwiVqgcVSWRguZEgZM8L2x1jvdpZHsYjLCxc9cSBamXuXPH",
> "signer_id": "evgeny.near"
> },
> "transaction_outcome": {
> "block_hash": "4u7maz2U43W4DPxqQE8KoRNi5dTRHrAsKsFk2qDQsQEw",
> "id": "GXP8YaSonoN2eBY6dB3FbMN2NyYD2JeJJvKdvbL4Jmb2",
> "outcome": {
> "executor_id": "evgeny.near",
> "gas_burnt": 2428086459116,
> "logs": [],
> "receipt_ids": ["CyJL22SYqt26qgh2XVnk9MGfvzgyiiq5Lny7DdbTdTWU"],
> "status": {
> "SuccessReceiptId": "CyJL22SYqt26qgh2XVnk9MGfvzgyiiq5Lny7DdbTdTWU"
> },
> "tokens_burnt": "242808645911600000000"
> },
> "proof": []
> }
> }
> }
> ```
As we can see, there are four receipts generated in this function call. If we apply the criteria mentioned above, we can
find in `receipts` field this object
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"predecessor_id": "evgeny.lockup.near",
"receipt": {
"Action": {
"actions": [
{
"Transfer": {
"deposit": "1000000000000000000000000"
}
}
],
"gas_price": "186029458",
"input_data_ids": [],
"output_data_receivers": [],
"signer_id": "evgeny.near",
"signer_public_key": "ed25519:BVRTxEEMx3gFceSgJtnvPFbSnPDwwUzHe6KGduRh5Byq"
}
},
"receipt_id": "EvHfj4fUyVuLBRKNdCZmFGr4WfqwYf7YCbzFsRGFTFJC",
"receiver_id": "evgeny.near"
}
```
which contains only `Transfer` action and whose `predecessor_id` is not `system`. Now we can check the status of the
execution by looking for the same receipt id `EvHfj4fUyVuLBRKNdCZmFGr4WfqwYf7YCbzFsRGFTFJC` in `receipts_outcome` field
of the rpc return result, this leads us to this execution outcome
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"block_hash": "7qn4BjmMD4QbyVvMa8QEzm7h5YuhoGTFTgLeNMUp85UQ",
"id": "EvHfj4fUyVuLBRKNdCZmFGr4WfqwYf7YCbzFsRGFTFJC",
"outcome": {
"executor_id": "evgeny.near",
"gas_burnt": 223182562500,
"logs": [],
"receipt_ids": ["J1bBKH43nXHYg4NuS97R1PFzdZchrJboVAdRsK5NRrAv"],
"status": {
"SuccessValue": ""
},
"tokens_burnt": "22318256250000000000"
},
"proof": [
{
"direction": "Right",
"hash": "AwHdk5dushTSXHFBt3R5MiexjiXybwdnEaB7L9iJ5F6t"
}
]
}
```
and its status contains `SuccessValue`, which indicates that the receipt has succeeded. Therefore we know that
`1000000000000000000000000` yoctoNEAR, or 1 NEAR has been successfully transferred.
### Example of transfer from a multisig contract
Multisig contract, as the name suggests, uses multiple signatures to confirm a transaction and therefore, actions performed
by the multisig contract involve multiple transactions. In the following example, we will show how a transfer is done from
a multisig contract that requires two confirmations.
* First step: `add_request_and_confirm`. This initiates the action that the multisig contract wants to perform with one
confirmation. The multisig contract `multisigtest.testnet` wants to transfer 1 NEAR to `bowen` and it first
sends a transaction that calls `add_request_and_confirm` with a request
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"request": {
"receiver_id": "bowen",
"actions": [
{
"type": "Transfer",
"amount": "1000000000000000000000000"
}
]
}
}
```
that indicates it wants to transfer 1 NEAR to `bowen`. Notice that this transaction only records the action
but does not perform the actual transfer. The transaction result is as follows:
> [accordion] Example RPC response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "id": "123",
> "jsonrpc": "2.0",
> "result": {
> "receipts": [
> {
> "predecessor_id": "system",
> "receipt": {
> "Action": {
> "actions": [
> {
> "Transfer": {
> "deposit": "3069687780141648922140"
> }
> }
> ],
> "gas_price": "0",
> "input_data_ids": [],
> "output_data_receivers": [],
> "signer_id": "multisigtest.testnet",
> "signer_public_key": "ed25519:JDewsbE7nz6orFD4zJ3mVzqhfcaoSD6Hmi5as3AHHiTt"
> }
> },
> "receipt_id": "4qgDptd7Wm6vswAhWMCsVpTjBEkmLJEUxSNVQS1wu3rD",
> "receiver_id": "multisigtest.testnet"
> }
> ],
> "receipts_outcome": [
> {
> "block_hash": "6uJWHTvUrtFQAurUyfuAfy9EdoR9FhLodGh44aHJta6m",
> "id": "94LiYwKJEDherHMNg9fqLy9ShFTDiQiUN3nDaGmLZwth",
> "outcome": {
> "executor_id": "multisigtest.testnet",
> "gas_burnt": 8024094920263,
> "logs": [],
> "receipt_ids": ["4qgDptd7Wm6vswAhWMCsVpTjBEkmLJEUxSNVQS1wu3rD"],
> "status": {
> "SuccessValue": "OA=="
> },
> "tokens_burnt": "802409492026300000000"
> },
> "proof": [
> {
> "direction": "Left",
> "hash": "GedzmwRkxA5VkT8GLBCnrPUmnEhWPXadPmiq4Ho1s9pH"
> },
> {
> "direction": "Right",
> "hash": "GirkzdS9YpsAz5fXuL5T3rXd93aRcnXNAdXYi241qpWK"
> }
> ]
> },
> {
> "block_hash": "4JyQ6guJKeWZxxXrKndLDuSa5URuirmBi6RzsbKYFsBE",
> "id": "4qgDptd7Wm6vswAhWMCsVpTjBEkmLJEUxSNVQS1wu3rD",
> "outcome": {
> "executor_id": "multisigtest.testnet",
> "gas_burnt": 0,
> "logs": [],
> "receipt_ids": [],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "0"
> },
> "proof": []
> }
> ],
> "status": {
> "SuccessValue": "OA=="
> },
> "transaction": {
> "actions": [
> {
> "FunctionCall": {
> "args": "eyJyZXF1ZXN0Ijp7InJlY2VpdmVyX2lkIjoiYm93ZW4iLCJhY3Rpb25zIjpbeyJ0eXBlIjoiVHJhbnNmZXIiLCJhbW91bnQiOiIxMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwIn1dfX0=",
> "deposit": "0",
> "gas": 30000000000000,
> "method_name": "add_request_and_confirm"
> }
> }
> ],
> "hash": "FGREJkC1e8y95Rc35iD1LVRiDy1WcAZhAxxkSinfb2mL",
> "nonce": 10,
> "public_key": "ed25519:JDewsbE7nz6orFD4zJ3mVzqhfcaoSD6Hmi5as3AHHiTt",
> "receiver_id": "multisigtest.testnet",
> "signature": "ed25519:3NUKXd4uj2eEBqGQtRAxkTFW7UfG44tjvQNNHBDvN9ZswTTMRsDrMJSd1U3GqWF7QToqWQR9J8atNEVTemSWYw41",
> "signer_id": "multisigtest.testnet"
> },
> "transaction_outcome": {
> "block_hash": "6uJWHTvUrtFQAurUyfuAfy9EdoR9FhLodGh44aHJta6m",
> "id": "FGREJkC1e8y95Rc35iD1LVRiDy1WcAZhAxxkSinfb2mL",
> "outcome": {
> "executor_id": "multisigtest.testnet",
> "gas_burnt": 2428204963618,
> "logs": [],
> "receipt_ids": ["94LiYwKJEDherHMNg9fqLy9ShFTDiQiUN3nDaGmLZwth"],
> "status": {
> "SuccessReceiptId": "94LiYwKJEDherHMNg9fqLy9ShFTDiQiUN3nDaGmLZwth"
> },
> "tokens_burnt": "242820496361800000000"
> },
> "proof": [
> {
> "direction": "Right",
> "hash": "AsNAQabPFkmaugRGhCbzcEcR8Gnd22WXxPM2fb2cwHiv"
> },
> {
> "direction": "Right",
> "hash": "GirkzdS9YpsAz5fXuL5T3rXd93aRcnXNAdXYi241qpWK"
> }
> ]
> }
> }
> }
> ```
* Second step: `confirm`. A second transaction is sent to confirm the transfer. This transaction takes the request id
returned by the first transaction and does the actual transfer. The transaction result is as follows
> [accordion] Example RPC response
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "id": "123",
> "jsonrpc": "2.0",
> "result": {
> "receipts": [
> {
> "predecessor_id": "multisigtest.testnet",
> "receipt": {
> "Action": {
> "actions": [
> {
> "Transfer": {
> "deposit": "1000000000000000000000000"
> }
> }
> ],
> "gas_price": "451542320",
> "input_data_ids": [],
> "output_data_receivers": [],
> "signer_id": "multisigtest.testnet",
> "signer_public_key": "ed25519:BmVX32jhvEd8d8outiQdjf66GGYV3pb7kaxrKTdNisCz"
> }
> },
> "receipt_id": "DZbHTEf3i3XznK4oJHQfcrteoiCL6WykRiA8vsn4LmAy",
> "receiver_id": "bowen"
> },
> {
> "predecessor_id": "system",
> "receipt": {
> "Action": {
> "actions": [
> {
> "Transfer": {
> "deposit": "78458115804795000000"
> }
> }
> ],
> "gas_price": "0",
> "input_data_ids": [],
> "output_data_receivers": [],
> "signer_id": "multisigtest.testnet",
> "signer_public_key": "ed25519:BmVX32jhvEd8d8outiQdjf66GGYV3pb7kaxrKTdNisCz"
> }
> },
> "receipt_id": "6SxC9GfYdjqm7Ao5EAw51XUAjgoN8Lj2X9xJfxjDQYXd",
> "receiver_id": "multisigtest.testnet"
> },
> {
> "predecessor_id": "system",
> "receipt": {
> "Action": {
> "actions": [
> {
> "Transfer": {
> "deposit": "112870156274913516718240"
> }
> }
> ],
> "gas_price": "0",
> "input_data_ids": [],
> "output_data_receivers": [],
> "signer_id": "multisigtest.testnet",
> "signer_public_key": "ed25519:BmVX32jhvEd8d8outiQdjf66GGYV3pb7kaxrKTdNisCz"
> }
> },
> "receipt_id": "CHfzz6NLcQMyiLHBQoczhgm5BFjLVfv9B7eCyXKLhhcT",
> "receiver_id": "multisigtest.testnet"
> }
> ],
> "receipts_outcome": [
> {
> "block_hash": "9JEiMrZ1SpAUEbQswde3Diptzwy35Vrvd41VZWG9hYVE",
> "id": "FfuhYhsgFL7sLC8pk1tuRnMHJdqycE6gEcfgZLW9fmFB",
> "outcome": {
> "executor_id": "multisigtest.testnet",
> "gas_burnt": 10109796553814,
> "logs": [],
> "receipt_ids": [
> "DZbHTEf3i3XznK4oJHQfcrteoiCL6WykRiA8vsn4LmAy",
> "CHfzz6NLcQMyiLHBQoczhgm5BFjLVfv9B7eCyXKLhhcT"
> ],
> "status": {
> "SuccessReceiptId": "DZbHTEf3i3XznK4oJHQfcrteoiCL6WykRiA8vsn4LmAy"
> },
> "tokens_burnt": "1010979655381400000000"
> },
> "proof": [
> {
> "direction": "Left",
> "hash": "9e2UcG6qBRahBh3V2Z8bGJLh5c4jXfZdP3WBJkCpJCfj"
> }
> ]
> },
> {
> "block_hash": "4LkVfqyhhrxDdVFmow6NxLf1jTaj6XVr7CVcUxxySd1R",
> "id": "DZbHTEf3i3XznK4oJHQfcrteoiCL6WykRiA8vsn4LmAy",
> "outcome": {
> "executor_id": "bowen",
> "gas_burnt": 223182562500,
> "logs": [],
> "receipt_ids": ["6SxC9GfYdjqm7Ao5EAw51XUAjgoN8Lj2X9xJfxjDQYXd"],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "22318256250000000000"
> },
> "proof": [
> {
> "direction": "Right",
> "hash": "FFWaWUFt6sNx5XNHzGYsYBSYFWtGPoww5XQz1QmLVc8i"
> }
> ]
> },
> {
> "block_hash": "G6LDdnAa2b38TB4KZ89HAyVgfgyiRPDDgSxoZypbUYpx",
> "id": "6SxC9GfYdjqm7Ao5EAw51XUAjgoN8Lj2X9xJfxjDQYXd",
> "outcome": {
> "executor_id": "multisigtest.testnet",
> "gas_burnt": 0,
> "logs": [],
> "receipt_ids": [],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "0"
> },
> "proof": []
> },
> {
> "block_hash": "4LkVfqyhhrxDdVFmow6NxLf1jTaj6XVr7CVcUxxySd1R",
> "id": "CHfzz6NLcQMyiLHBQoczhgm5BFjLVfv9B7eCyXKLhhcT",
> "outcome": {
> "executor_id": "multisigtest.testnet",
> "gas_burnt": 0,
> "logs": [],
> "receipt_ids": [],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "0"
> },
> "proof": [
> {
> "direction": "Left",
> "hash": "DpDYAEKZTtSomgyeNcJ2i4qjvfqnCtf1CXa83Cz5wvEy"
> }
> ]
> }
> ],
> "status": {
> "SuccessValue": ""
> },
> "transaction": {
> "actions": [
> {
> "FunctionCall": {
> "args": "eyJyZXF1ZXN0X2lkIjo4fQ==",
> "deposit": "0",
> "gas": 250000000000000,
> "method_name": "confirm"
> }
> }
> ],
> "hash": "Fu39vwxC4mu9ks1DZA5Cib63RnBMHpFonk2DcbpioEYc",
> "nonce": 9,
> "public_key": "ed25519:BmVX32jhvEd8d8outiQdjf66GGYV3pb7kaxrKTdNisCz",
> "receiver_id": "multisigtest.testnet",
> "signature": "ed25519:2raQq7t3cmzSL2krE2xaNqXhAw7cKMoXrBjT2ZhAGfCVtGwzbbQ8zkB17vrCSFZDbFmPWSJpoqsw8qPZZiorwSzS",
> "signer_id": "multisigtest.testnet"
> },
> "transaction_outcome": {
> "block_hash": "9JEiMrZ1SpAUEbQswde3Diptzwy35Vrvd41VZWG9hYVE",
> "id": "Fu39vwxC4mu9ks1DZA5Cib63RnBMHpFonk2DcbpioEYc",
> "outcome": {
> "executor_id": "multisigtest.testnet",
> "gas_burnt": 2427972426482,
> "logs": [],
> "receipt_ids": ["FfuhYhsgFL7sLC8pk1tuRnMHJdqycE6gEcfgZLW9fmFB"],
> "status": {
> "SuccessReceiptId": "FfuhYhsgFL7sLC8pk1tuRnMHJdqycE6gEcfgZLW9fmFB"
> },
> "tokens_burnt": "242797242648200000000"
> },
> "proof": [
> {
> "direction": "Right",
> "hash": "B6hN48qeVP8J3hP8XGcANShM264QkNjgJAfMtsuknqex"
> }
> ]
> }
> }
> }
> ```
Notice that similar to the transfer from lockup contract, there is also one receipt in the `receipts` field that meet
our requirements:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"predecessor_id": "multisigtest.testnet",
"receipt": {
"Action": {
"actions": [
{
"Transfer": {
"deposit": "1000000000000000000000000"
}
}
],
"gas_price": "451542320",
"input_data_ids": [],
"output_data_receivers": [],
"signer_id": "multisigtest.testnet",
"signer_public_key": "ed25519:BmVX32jhvEd8d8outiQdjf66GGYV3pb7kaxrKTdNisCz"
}
},
"receipt_id": "DZbHTEf3i3XznK4oJHQfcrteoiCL6WykRiA8vsn4LmAy",
"receiver_id": "bowen"
}
```
and we can find its outcome in `receipts_outcome`:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"block_hash": "4LkVfqyhhrxDdVFmow6NxLf1jTaj6XVr7CVcUxxySd1R",
"id": "DZbHTEf3i3XznK4oJHQfcrteoiCL6WykRiA8vsn4LmAy",
"outcome": {
"executor_id": "bowen",
"gas_burnt": 223182562500,
"logs": [],
"receipt_ids": ["6SxC9GfYdjqm7Ao5EAw51XUAjgoN8Lj2X9xJfxjDQYXd"],
"status": {
"SuccessValue": ""
},
"tokens_burnt": "22318256250000000000"
},
"proof": [
{
"direction": "Right",
"hash": "FFWaWUFt6sNx5XNHzGYsYBSYFWtGPoww5XQz1QmLVc8i"
}
]
}
```
which indicates that the transaction is successful.
For fungible-token deposits, see [Fungible Tokens](/integrations/fungible-tokens).
# Error Handling
Source: https://docs.near.org/integrations/errors/introduction
Learn about common error patterns in NEAR protocol integrations and how to handle and troubleshoot issues in your applications.
Transaction submission can fail before execution, and accepted transactions can fail while their receipts execute. A timeout leaves the transaction's outcome unknown; recover using its original hash before submitting a replacement.
***
## Handling Transaction Errors
For SDK error handling, nonce errors, and timeout recovery, see [submission errors and retries](/integrations/create-transactions#submission-errors-and-retries). The [transaction RPC reference](/api/rpc/transactions) documents submission and status responses.
Actions within one receipt are atomic; separate receipts are not rolled back together. Inspect finalized receipt outcomes and account for successful movements, fees, and refunds before retrying an operation.
***
## Avoiding Token Loss
This document provides an overview of potential scenarios that can lead to token loss on the NEAR Protocol and how to mitigate these risks. It covers improper key management, refunding deleted accounts, failed asynchronous function calls, and deleting gas keys or accounts that hold gas key balances.
Token loss is possible under multiple scenarios. These scenarios can be grouped into a few related classes:
1. [Improper key management](/integrations/accounts#improper-key-management)
2. Refunding deleted accounts
3. Failed asynchronous function calls
4. Deleting gas keys, or accounts that hold gas key balances
> [!WARNING]
>
> Careful! Losing tokens means losing money!
***
## Refunding deleted accounts
See [refunding deleted accounts](/protocol/network/token-loss#refunding-deleted-accounts) for payout failures and outstanding refunds that can cause token loss.
### Deleting account with non-existent beneficiary
> [!WARNING]
>
> Never use `DeleteAccount` as a replacement for `Transfer`. Follow the [safe account deletion procedure](/protocol/network/token-loss#deleting-account-with-non-existent-beneficiary): transfer, wait for finalized success and outstanding refunds, then delete if needed.
### Account deleted before it receives a refund
See [account deletion with outstanding refunds](/protocol/network/token-loss#account-deleted-before-it-receives-a-refund).
***
## Failed asynchronous function calls
> [!WARNING]
>
> When designing a smart contract, you should always consider the asynchronous nature of NEAR Protocol.
If a contract function `f1` calls two (or more) other functions `f2` and `f3`, and at least one of these functions, `f2` and `f3` fails, then tokens will be refunded from the function that failed, but tokens will be appropriately credited to the function(s) which succeed.
These are separate receipts, not an atomic batch of actions in one receipt. A failed downstream call does not undo a previously successful transfer. Track each movement and refund before deciding whether recovery is needed.
***
## Deleting gas keys, or accounts that hold gas key balances
Only the account balance goes to the beneficiary. NEAR held in a [gas key](/protocol/accounts-contracts/gas-keys) is burned when you delete that gas key or the account.
* A `DeleteKey` action fails with `GasKeyBalanceTooHigh` if the gas key it deletes holds more than 1 NEAR.
* A `DeleteAccount` action fails with `GasKeyBalanceTooHigh` if all gas keys on the account hold more than 1 NEAR in total, even when each key holds less than 1 NEAR.
Balances at or below these limits are burned, not paid out. Withdraw every gas key balance with `WithdrawFromGasKey` before you delete a gas key or the account.
# Exchange Integration
Source: https://docs.near.org/integrations/exchange-integration
Learn how to integrate NEAR Protocol.
NEAR is an open-source, sharded proof-of-stake blockchain with support for smart contracts.
| Property | Value / behavior | Reference |
| - | - | - |
| Native token precision | 24 decimals; `1 NEAR = 10²⁴ yoctoNEAR`. RPC balances and transfer amounts use integer strings in yoctoNEAR. | [Balances](/integrations/balance-changes) |
| Account addresses | Implicit IDs: 64 lowercase hexadecimal characters; named IDs such as `alice.near`; Ethereum-like IDs starting with `0x`; deterministic IDs starting with `0s`; from protocol version 88 (nearcore 2.14.0), universal IDs starting with `0u` (54 characters). See the note below the table. | [Account IDs](/protocol/accounts-contracts/account-id) |
| Block time | Produced in \~600 ms, final in \~1.2 s. | [Blocks & Finality](/integrations/blocks-and-finality) [Execution milestones](/api/rpc/transactions#the-wait_until-field) |
| Transaction validity | `transaction_validity_period` is measured in blocks; `86400` blocks is \~14.4 hours at a 600 ms cadence. | [Transaction Lifecycle](/integrations/transaction-lifecycle#how-old-can-the-referenced-block-hash-be-before-its-invalid%3F) |
| Transaction fees | The gas price has a floor of **0.0001 NEAR/Tgas** and rises with network load. Gas for execution is bought up front at no less than 0.001 NEAR/Tgas. Unused gas and the price difference are refunded. See [Fees and required balances](#fees-and-required-balances). | [Gas fees](/protocol/transactions/gas) |
> [!NOTE]
>
> A transfer to a `0u` ID that does not exist yet creates an uninitialized account that holds the deposit. Before protocol version 88, a transfer to a `0u` ID fails.
## Fees and required balances
Gas usage is determined by the actions and their parameters. For function calls, it also depends on contract execution. A transaction pays for gas in three steps:
| Step | Gas | Price |
| - | - | - |
| Send the transaction | Fees for sending the transaction | The current gas price |
| Buy gas for executing it | Fees for executing the transaction, plus any gas attached to function calls | The current gas price or 0.001 NEAR/Tgas, whichever is higher |
| Execute it | The gas that is burned | The current gas price, but never above the price at which the gas was bought |
The first two steps are paid up front. With a regular access key, the account balance must cover this up-front cost plus any deposit. With a [gas key](/protocol/accounts-contracts/gas-keys), the gas key balance covers the gas and the account balance covers the deposit.
Unused gas and the price difference are refunded. When a transaction creates an account, part of that refund is kept so that the account creation charge comes to about 0.007 NEAR.
***
## Integration Reference
* [Nodes & RPC](/integrations/nodes)
* [Accessing On-chain Data](/integrations/on-chain-data)
* [Accounts](/integrations/accounts)
* [Blocks and Finality](/integrations/blocks-and-finality)
* [Transaction Lifecycle](/integrations/transaction-lifecycle)
* [Testing](/integrations/testing)
* [Receiving Deposits](/integrations/deposits)
* [Sending Withdrawals](/integrations/create-transactions)
* [Fungible Tokens](/integrations/fungible-tokens)
* [Balances & Reconciliation](/integrations/balance-changes)
* [Staking & Delegation](/integrations/staking)
* [Error Handling](/integrations/errors/introduction)
### Transaction Reference Links
* [Basics](/protocol/transactions)
* [Transaction Structure](/protocol/transactions/transaction-anatomy)
* [Constructing Transactions](/integrations/create-transactions)
***
## Additional Resources
* [The Beginner's Guide to the NEAR Blockchain](https://near.org/blog/the-beginners-guide-to-the-near-blockchain)
* [NEAR Whitepaper](https://www.near.org/papers)
* [NEAR GitHub](https://www.github.com/near)
***
## Frequently Asked Questions
These guides provide answers to frequently asked questions about integrating with the NEAR Protocol. It covers topics such as account management, validator operations, transaction processing, and more.
> [accordion] What is a good project summary for NEAR?
>
> NEAR is a sharded, public, proof-of-stake blockchain and supports smart contracts written in Rust and compiled to WebAssembly (WASM).
> [accordion] What's special about NEAR?
>
> NEAR is the blockchain for builders.
>
> If you understand the basics of web development, you can write, test and deploy scalable decentralized applications in minutes on the most developer-friendly blockchain without having to learn new tools or languages.
> [accordion] Is NEAR open source?
>
> Yes. Have a look at our [GitHub organization](https://github.com/near).
> [accordion] Do you have any on-chain governance mechanisms?
>
> NEAR has [House of Stake governance](https://gov.houseofstake.org/blog/introducing-near-house-of-stake). Governance proposals and consensus protocol activation are separate processes; follow the implementation and activation requirements for each change.
> [accordion] Do you have a bug-bounty program?
>
> Follow the current [nearcore security policy](https://github.com/near/nearcore/security/policy) for disclosure instructions and links to any applicable program.
> [accordion] What contracts should we be aware of right now?
>
> The [core-contracts repository](https://github.com/near/core-contracts) contains reference implementations. Review the deployed version and authority of each contract you integrate with:
>
> * **Staking Pool / Delegation contract**
> * **Lockup / Vesting contract**
> * Whitelist Contract
> * Staking Pool Factory
> * Multisig contract
# Fungible tokens
Source: https://docs.near.org/integrations/fungible-tokens
Integrate NEP-141 fungible tokens, including balance queries, storage registration, transfers, and metadata.
Fungible tokens on NEAR follow the [NEP-141 standard](https://github.com/near/NEPs/blob/master/neps/nep-0141.md). Each token is implemented as a smart contract that tracks account balances and exposes methods to query balances (`ft_balance_of`), transfer tokens (`ft_transfer`), and transfer tokens to another contract while calling its `ft_on_transfer` method (`ft_transfer_call`).
> [!NOTE]
>
> Please see the [spec for the fungible token standard](https://github.com/near/NEPs/tree/master/neps/nep-0141.md) and an [example implementation](https://github.com/near-examples/FT) for reference details.
***
## Token metadata
The [`ft_metadata` method](https://github.com/near/NEPs/blob/master/neps/nep-0148.md) returns the token's name, symbol, decimals, and optional display information such as its icon.
> [tab] NEAR CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract call-function as-read-only meta-pool.near ft_metadata json-args '{}' network-config mainnet now
>
> # Selected result fields:
> # {
> # "spec": "ft-1.0.0",
> # "name": "Staked NEAR",
> # "symbol": "STNEAR",
> # "decimals": 24
> # }
> ```
> [tab] RPC
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http post https://rpc.mainnet.near.org jsonrpc=2.0 id=ftmetadata method=query \
> params:='{"request_type":"call_function","finality":"final","account_id":"meta-pool.near","method_name":"ft_metadata","args_base64":"e30="}'
> ```
>
> > [accordion] Metadata RPC response
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "jsonrpc": "2.0",
> > "result": {
> > "block_hash": "8cwU7ukBxmzFqejV9U75MiRmw4RENnweqT8egx2Tz2s3",
> > "block_height": 219151015,
> > "logs": [],
> > "result": [123, 34, 115, 112, 101, 99, 34, 58, 34, 102, 116, 45, 49, 46, 48, 46, 48, 34, 44, 34, 110, 97, 109, 101, 34, 58, 34, 83, 116, 97, 107, 101, 100, 32, 78, 69, 65, 82, 34, 44, 34, 115, 121, 109, 98, 111, 108, 34, 58, 34, 83, 84, 78, 69, 65, 82, 34, 44, 34, 105, 99, 111, 110, 34, 58, 34, 100, 97, 116, 97, 58, 105, 109, 97, 103, 101, 47, 115, 118, 103, 43, 120, 109, 108, 44, 37, 51, 99, 115, 118, 103, 32, 119, 105, 100, 116, 104, 61, 39, 57, 54, 39, 32, 104, 101, 105, 103, 104, 116, 61, 39, 57, 54, 39, 32, 118, 105, 101, 119, 66, 111, 120, 61, 39, 48, 32, 48, 32, 57, 54, 32, 57, 54, 39, 32, 102, 105, 108, 108, 61, 39, 110, 111, 110, 101, 39, 32, 120, 109, 108, 110, 115, 61, 39, 104, 116, 116, 112, 58, 47, 47, 119, 119, 119, 46, 119, 51, 46, 111, 114, 103, 47, 50, 48, 48, 48, 47, 115, 118, 103, 39, 37, 51, 101, 37, 51, 99, 114, 101, 99, 116, 32, 119, 105, 100, 116, 104, 61, 39, 57, 54, 39, 32, 104, 101, 105, 103, 104, 116, 61, 39, 57, 54, 39, 32, 114, 120, 61, 39, 52, 56, 39, 32, 102, 105, 108, 108, 61, 39, 119, 104, 105, 116, 101, 39, 47, 37, 51, 101, 37, 51, 99, 112, 97, 116, 104, 32, 102, 105, 108, 108, 45, 114, 117, 108, 101, 61, 39, 101, 118, 101, 110, 111, 100, 100, 39, 32, 99, 108, 105, 112, 45, 114, 117, 108, 101, 61, 39, 101, 118, 101, 110, 111, 100, 100, 39, 32, 100, 61, 39, 77, 52, 56, 46, 48, 48, 48, 54, 32, 50, 48, 76, 52, 49, 46, 50, 53, 55, 53, 32, 50, 54, 46, 55, 52, 51, 49, 76, 52, 56, 46, 48, 48, 48, 54, 32, 51, 51, 46, 52, 56, 54, 50, 76, 53, 52, 46, 55, 52, 51, 55, 32, 50, 54, 46, 55, 52, 51, 49, 76, 52, 56, 46, 48, 48, 48, 54, 32, 50, 48, 90, 77, 51, 55, 46, 50, 56, 49, 32, 51, 48, 46, 55, 49, 56, 56, 76, 51, 48, 46, 55, 49, 52, 52, 32, 51, 55, 46, 50, 56, 53, 51, 76, 52, 55, 46, 57, 57, 57, 56, 32, 53, 52, 46, 53, 55, 48, 55, 76, 54, 53, 46, 50, 56, 53, 49, 32, 51, 55, 46, 50, 56, 53, 51, 76, 53, 56, 46, 55, 49, 56, 54, 32, 51, 48, 46, 55, 49, 56, 56, 76, 52, 55, 46, 57, 57, 57, 56, 32, 52, 49, 46, 52, 51, 55, 54, 76, 51, 55, 46, 50, 56, 49, 32, 51, 48, 46, 55, 49, 56, 56, 90, 77, 50, 54, 46, 55, 51, 56, 52, 32, 52, 49, 46, 50, 54, 49, 76, 49, 57, 46, 57, 57, 53, 51, 32, 52, 56, 46, 48, 48, 52, 49, 76, 52, 55, 46, 57, 57, 57, 53, 32, 55, 54, 46, 48, 48, 56, 51, 76, 55, 54, 46, 48, 48, 51, 55, 32, 52, 56, 46, 48, 48, 52, 49, 76, 54, 57, 46, 50, 54, 48, 54, 32, 52, 49, 46, 50, 54, 49, 49, 76, 52, 55, 46, 57, 57, 57, 53, 32, 54, 50, 46, 53, 50, 50, 49, 76, 50, 54, 46, 55, 51, 56, 52, 32, 52, 49, 46, 50, 54, 49, 90, 39, 32, 102, 105, 108, 108, 61, 39, 37, 50, 51, 50, 51, 49, 66, 53, 49, 39, 47, 37, 51, 101, 37, 51, 99, 47, 115, 118, 103, 37, 51, 101, 34, 44, 34, 114, 101, 102, 101, 114, 101, 110, 99, 101, 34, 58, 34, 104, 116, 116, 112, 115, 58, 47, 47, 109, 101, 116, 97, 112, 111, 111, 108, 46, 97, 112, 112, 34, 44, 34, 114, 101, 102, 101, 114, 101, 110, 99, 101, 95, 104, 97, 115, 104, 34, 58, 110, 117, 108, 108, 44, 34, 100, 101, 99, 105, 109, 97, 108, 115, 34, 58, 50, 52, 125]
> > },
> > "id": "ftmetadata"
> > }
> > ```
>
> [Decoded result](/api/rpc/contracts#decode-the-result) (selected fields):
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "spec": "ft-1.0.0",
> "name": "Staked NEAR",
> "symbol": "STNEAR",
> "decimals": 24
> }
> ```
### Decimals
`decimals` determines how to display the integer amounts in which the token is denominated.
For a token with `decimals: 6`, `"1000000"` raw units represents 1 token, and `"1500000"` represents 1.5 tokens. `meta-pool.near` uses 24 decimals, so `"1000000000000000000000000"` raw units represents 1 STNEAR.
> [!NOTE]
>
> Use the token's metadata when converting amounts, but keep raw balances and transfer arguments as integer strings.
***
## Get balance
Call `ft_balance_of` with the account ID to get its raw token balance.
> [tab] NEAR CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract call-function as-read-only meta-pool.near ft_balance_of json-args '{"account_id": "root.near"}' network-config mainnet now
>
> # Returns:
> # "1387952532024477011546901"
> ```
> [tab] RPC
>
> You can [call a contract function](/api/rpc/contracts#call-a-contract-function) using the `query` RPC endpoint. Below is an example using HTTPie:
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http post https://rpc.mainnet.near.org jsonrpc=2.0 id=ftbalance method=query \
> params:='{
> "request_type": "call_function",
> "finality": "final",
> "account_id": "meta-pool.near",
> "method_name": "ft_balance_of",
> "args_base64": "eyJhY2NvdW50X2lkIjoicm9vdC5uZWFyIn0="
> }'
> ```
>
> Returns:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "block_hash": "8cwU7ukBxmzFqejV9U75MiRmw4RENnweqT8egx2Tz2s3",
> "block_height": 219151015,
> "logs": [],
> "result": [34, 49, 51, 56, 55, 57, 53, 50, 53, 51, 50, 48, 50, 52, 52, 55, 55, 48, 49, 49, 53, 52, 54, 57, 48, 49, 34]
> },
> "id": "ftbalance"
> }
> ```
>
> [Decoded result](/api/rpc/contracts#decode-the-result):
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> "1387952532024477011546901"
> ```
NEP-141 returns balances as base-10 integer strings to preserve amounts larger than JavaScript's safe integer limit (`2^53 - 1`). Decode the JSON string and use integer arithmetic for balances and transfers.
***
## Simple transfer
Before calling `ft_transfer`, register the receiver with the token contract so the contract can store its balance.
### Storage registration
Check `storage_balance_of` for the receiver. A `null` result means it is unregistered; query `storage_balance_bounds` and attach its `min` amount in yoctoNEAR when calling `storage_deposit`. The queries below show that `root.near` is already registered with `meta-pool.near`, whose minimum is `0.00125 NEAR`.
> [tab] NEAR CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract call-function as-read-only meta-pool.near storage_balance_of json-args '{"account_id":"root.near"}' network-config mainnet now
> # Result: {"total":"1250000000000000000000","available":"0"}
>
> near contract call-function as-read-only meta-pool.near storage_balance_bounds json-args '{}' network-config mainnet now
> # Result: {"min":"1250000000000000000000","max":"1250000000000000000000"}
>
> ```
>
> For an unregistered receiver, deposit the returned minimum:
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract call-function as-transaction meta-pool.near storage_deposit json-args '{"account_id":"","registration_only":true}' prepaid-gas '30 Tgas' attached-deposit '0.00125 NEAR' sign-as network-config mainnet sign-with-keychain send
> ```
> [tab] RPC
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http post https://rpc.mainnet.near.org jsonrpc=2.0 id=storagebalanceof method=query \
> params:='{"request_type":"call_function","finality":"final","account_id":"meta-pool.near","method_name":"storage_balance_of","args_base64":"eyJhY2NvdW50X2lkIjoicm9vdC5uZWFyIn0="}'
>
> http post https://rpc.mainnet.near.org jsonrpc=2.0 id=storagebalancebounds method=query \
> params:='{"request_type":"call_function","finality":"final","account_id":"meta-pool.near","method_name":"storage_balance_bounds","args_base64":"e30="}'
> ```
>
> [Decoded results](/api/rpc/contracts#decode-the-result), respectively:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {"total":"1250000000000000000000","available":"0"}
> ```
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {"min":"1250000000000000000000","max":"1250000000000000000000"}
> ```
>
> To register an unregistered receiver, [create and sign a transaction](/integrations/create-transactions#low-level-create-a-transaction) addressed to `meta-pool.near` with a `FunctionCall` action: `method_name: "storage_deposit"`, JSON arguments `{"account_id":"","registration_only":true}`, and `deposit: "1250000000000000000000"` yoctoNEAR. Submit the signed payload with [`send_tx`](/api/rpc/transactions#send-transaction) and `wait_until: "FINAL"`.
### Transfer tokens
Call `ft_transfer` with the receiver's account ID and an integer-string amount in the token's smallest unit. Attach exactly **1 yoctoNEAR**. With STNEAR's 24 decimals, the amount below transfers 1 STNEAR to `root.near`.
> [tab] NEAR CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract call-function as-transaction meta-pool.near ft_transfer json-args '{"receiver_id":"root.near","amount":"1000000000000000000000000"}' prepaid-gas '30 Tgas' attached-deposit '1 yoctoNEAR' sign-as network-config mainnet sign-with-keychain send
> ```
> [tab] RPC
>
> [Create and sign a transaction](/integrations/create-transactions#low-level-create-a-transaction) addressed to `meta-pool.near` with a `FunctionCall` action: `method_name: "ft_transfer"`, JSON arguments `{"receiver_id":"root.near","amount":"1000000000000000000000000"}`, and `deposit: "1"` yoctoNEAR.
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http post https://rpc.mainnet.near.org jsonrpc=2.0 id=transfer method=send_tx \
> params:='{"signed_tx_base64":"REPLACE_WITH_SIGNED_TRANSACTION_BASE64","wait_until":"FINAL"}'
> ```
>
> A successful `ft_transfer` returns an empty `status.SuccessValue`; see [decoded transaction results](/api/rpc/contracts#transaction-return-values). Execution errors appear in `status.Failure`.
Require `final_execution_status === "FINAL"` and a successful token-call receipt before confirming the transfer. An insufficient token balance or an unregistered receiver causes execution failure; inspect the error before retrying.
### Deposit accounting
For general deposit accounting, use an [indexer](/data-infrastructure/indexers) to inspect [NEP-300 events](https://github.com/near/NEPs/blob/master/neps/nep-0300.md) in successful finalized token-contract outcomes: `EVENT_JSON:` with `standard: "nep141"`, `version: "1.0.0"`, and `event: "ft_transfer"`.
Authenticate `executor_id` against the approved token contract; another contract can print the same log.
***
## Transfer and call
The `ft_transfer_call` method allows a user to transfer tokens to a contract while simultaneously triggering a function call on the receiving contract.
Let's call `ft_transfer_call` function on `ft` contract (receiver) and examine successful and unsuccessful scenarios.
### Successful transfer and call
Let's send 10 raw FT units to a `DEFI` contract that uses only 9. These are smallest-unit amounts, not NEAR or necessarily ten displayed tokens; apply the token's approved decimals for display.
> [tab] NEAR CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract call-function as-transaction ft_transfer_call json-args '{"receiver_id": "", "amount": "10", "msg": "take-my-money"}' prepaid-gas '100.0 Tgas' attached-deposit '1 yoctoNEAR' sign-as network-config testnet sign-with-keychain send
> ```
> [tab] RPC
>
> Transaction representation:
>
> ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
> Transaction: {
> block_hash: `456…abc`,
> signer_id: "serhii.testnet",
> public_key: "ed25519:789…def",
> nonce: 123,
> receiver_id: "dev-1623333795623-21399959778159",
> actions: [
> FunctionCall(
> FunctionCallAction {
> method_name: ft_transfer_call,
> args: `{"receiver_id":"dev-1623693121955-71667632531176","amount":"10","msg":"take-my-money"}`,
> gas: 100000000000000,
> deposit: 1,
> },
> ),
> ]
> }
> ```
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=send_tx \
> params:='{"signed_tx_base64":"REPLACE_WITH_FRESH_SIGNED_TRANSACTION_BASE64","wait_until":"FINAL"}'
> ```
>
> To get details of this transaction:
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http post https://archival-rpc.testnet.near.org jsonrpc=2.0 method=EXPERIMENTAL_tx_status \
> params:='{"tx_hash":"5n1kwA3TQQyFTkddR2Jau3H1Pt8ebQNGaov6aCQ6TDp1","sender_account_id":"serhii.testnet","wait_until":"FINAL"}' id=myid
> ```
>
>
> **Example Response:**
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "final_execution_status": "FINAL",
> "receipts": [
> {
> "predecessor_id": "serhii.testnet",
> "priority": 0,
> "receipt": {
> "Action": {
> "actions": [
> {
> "FunctionCall": {
> "args": "eyJyZWNlaXZlcl9pZCI6ImRldi0xNjIzNjkzMTIxOTU1LTcxNjY3NjMyNTMxMTc2IiwiYW1vdW50IjoiMTAiLCJtc2ciOiJ0YWtlLW15LW1vbmV5In0=",
> "deposit": "1",
> "gas": 100000000000000,
> "method_name": "ft_transfer_call"
> }
> }
> ],
> "gas_price": "186029458",
> "input_data_ids": [],
> "is_promise_yield": false,
> "output_data_receivers": [],
> "signer_id": "serhii.testnet",
> "signer_public_key": "ed25519:5UfEFyve3RdqKkWtALMreA9jzsAGDgCtwEXGNtkGeruN"
> }
> },
> "receipt_id": "Hw6z8kJ7CSaC6SgyQzcmXzNX9gq1gaAnLS169qgyZ2Vk",
> "receiver_id": "dev-1623333795623-21399959778159"
> },
> {
> "predecessor_id": "dev-1623333795623-21399959778159",
> "priority": 0,
> "receipt": {
> "Action": {
> "actions": [
> {
> "FunctionCall": {
> "args": "eyJzZW5kZXJfaWQiOiJzZXJoaWkudGVzdG5ldCIsImFtb3VudCI6IjEwIiwibXNnIjoidGFrZS1teS1tb25leSJ9",
> "deposit": "0",
> "gas": 70000000000000,
> "method_name": "ft_on_transfer"
> }
> }
> ],
> "gas_price": "186029458",
> "input_data_ids": [],
> "is_promise_yield": false,
> "output_data_receivers": [
> {
> "data_id": "EiDQi54XHfdD1KEcgiNzogXxXuwTpzeQfmyqVwbq7H4D",
> "receiver_id": "dev-1623333795623-21399959778159"
> }
> ],
> "signer_id": "serhii.testnet",
> "signer_public_key": "ed25519:5UfEFyve3RdqKkWtALMreA9jzsAGDgCtwEXGNtkGeruN"
> }
> },
> "receipt_id": "EB69xtJiLRh9RNzAHgBGmom8551hrK2xSRreqbjvJgu5",
> "receiver_id": "dev-1623693121955-71667632531176"
> },
> {
> "predecessor_id": "system",
> "priority": 0,
> "receipt": {
> "Action": {
> "actions": [
> {
> "Transfer": {
> "deposit": "13116953530949529501760"
> }
> }
> ],
> "gas_price": "0",
> "input_data_ids": [],
> "is_promise_yield": false,
> "output_data_receivers": [],
> "signer_id": "serhii.testnet",
> "signer_public_key": "ed25519:5UfEFyve3RdqKkWtALMreA9jzsAGDgCtwEXGNtkGeruN"
> }
> },
> "receipt_id": "AkwgvxUspRgy255fef2hrEWMbrMWFtnTRGduSgDRdSW1",
> "receiver_id": "serhii.testnet"
> },
> {
> "predecessor_id": "dev-1623333795623-21399959778159",
> "priority": 0,
> "receipt": {
> "Action": {
> "actions": [
> {
> "FunctionCall": {
> "args": "eyJzZW5kZXJfaWQiOiJzZXJoaWkudGVzdG5ldCIsInJlY2VpdmVyX2lkIjoiZGV2LTE2MjM2OTMxMjE5NTUtNzE2Njc2MzI1MzExNzYiLCJhbW91bnQiOiIxMCJ9",
> "deposit": "0",
> "gas": 5000000000000,
> "method_name": "ft_resolve_transfer"
> }
> }
> ],
> "gas_price": "186029458",
> "input_data_ids": [
> "EiDQi54XHfdD1KEcgiNzogXxXuwTpzeQfmyqVwbq7H4D"
> ],
> "is_promise_yield": false,
> "output_data_receivers": [],
> "signer_id": "serhii.testnet",
> "signer_public_key": "ed25519:5UfEFyve3RdqKkWtALMreA9jzsAGDgCtwEXGNtkGeruN"
> }
> },
> "receipt_id": "4Tc8MsrJZSMpNZx7u4jSqxr3WhRzqxaNHxLJFqz8tUPR",
> "receiver_id": "dev-1623333795623-21399959778159"
> },
> {
> "predecessor_id": "system",
> "priority": 0,
> "receipt": {
> "Action": {
> "actions": [
> {
> "Transfer": {
> "deposit": "761030677610514102464"
> }
> }
> ],
> "gas_price": "0",
> "input_data_ids": [],
> "is_promise_yield": false,
> "output_data_receivers": [],
> "signer_id": "serhii.testnet",
> "signer_public_key": "ed25519:5UfEFyve3RdqKkWtALMreA9jzsAGDgCtwEXGNtkGeruN"
> }
> },
> "receipt_id": "9rxcC9o8x4RX7ftsDCfxK8qnisYv45rA1HGPxhuukWUL",
> "receiver_id": "serhii.testnet"
> },
> {
> "predecessor_id": "system",
> "priority": 0,
> "receipt": {
> "Action": {
> "actions": [
> {
> "Transfer": {
> "deposit": "2137766093631769060520"
> }
> }
> ],
> "gas_price": "0",
> "input_data_ids": [],
> "is_promise_yield": false,
> "output_data_receivers": [],
> "signer_id": "serhii.testnet",
> "signer_public_key": "ed25519:5UfEFyve3RdqKkWtALMreA9jzsAGDgCtwEXGNtkGeruN"
> }
> },
> "receipt_id": "H7YWFkvx16Efy2keCQ7BQ67BMEsdgdYLqJ99G4H3dR1D",
> "receiver_id": "serhii.testnet"
> }
> ],
> "receipts_outcome": [
> {
> "block_hash": "B9yZz1w3yzrqQnfBFAf17S4TLaHakXJWqmFDBbFxaEiZ",
> "id": "Hw6z8kJ7CSaC6SgyQzcmXzNX9gq1gaAnLS169qgyZ2Vk",
> "outcome": {
> "executor_id": "dev-1623333795623-21399959778159",
> "gas_burnt": 20612680932083,
> "logs": [
> "Transfer 10 from serhii.testnet to dev-1623693121955-71667632531176"
> ],
> "metadata": {
> "gas_profile": null,
> "version": 1
> },
> "receipt_ids": [
> "EB69xtJiLRh9RNzAHgBGmom8551hrK2xSRreqbjvJgu5",
> "4Tc8MsrJZSMpNZx7u4jSqxr3WhRzqxaNHxLJFqz8tUPR",
> "H7YWFkvx16Efy2keCQ7BQ67BMEsdgdYLqJ99G4H3dR1D"
> ],
> "status": {
> "SuccessReceiptId": "4Tc8MsrJZSMpNZx7u4jSqxr3WhRzqxaNHxLJFqz8tUPR"
> },
> "tokens_burnt": "2061268093208300000000"
> },
> "proof": []
> },
> {
> "block_hash": "7Z4LHWksvw7sKYKwpQfjEMG8oigjtRXKa3EopN7hS2v7",
> "id": "EB69xtJiLRh9RNzAHgBGmom8551hrK2xSRreqbjvJgu5",
> "outcome": {
> "executor_id": "dev-1623693121955-71667632531176",
> "gas_burnt": 3568066327145,
> "logs": [
> "Sender @serhii.testnet is transfering 10 tokens using ft_on_transfer, msg = take-my-money"
> ],
> "metadata": {
> "gas_profile": null,
> "version": 1
> },
> "receipt_ids": [
> "AkwgvxUspRgy255fef2hrEWMbrMWFtnTRGduSgDRdSW1"
> ],
> "status": {
> "SuccessValue": "IjEi"
> },
> "tokens_burnt": "356806632714500000000"
> },
> "proof": [
> {
> "direction": "Right",
> "hash": "5X2agUKpqmk7QkUZsDQ4R4HdX7zXeuPYpVAfvbmF5Gav"
> }
> ]
> },
> {
> "block_hash": "CrSDhQNn72K2Qr1mmoM9j3YHCo3wfZdmHjpHJs74WnPk",
> "id": "AkwgvxUspRgy255fef2hrEWMbrMWFtnTRGduSgDRdSW1",
> "outcome": {
> "executor_id": "serhii.testnet",
> "gas_burnt": 0,
> "logs": [],
> "metadata": {
> "gas_profile": null,
> "version": 1
> },
> "receipt_ids": [],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "0"
> },
> "proof": [
> {
> "direction": "Right",
> "hash": "4WG6hF5fTAtM7GSqU8mprrFwRVbChGMCV2NPZEjEdnc1"
> }
> ]
> },
> {
> "block_hash": "CrSDhQNn72K2Qr1mmoM9j3YHCo3wfZdmHjpHJs74WnPk",
> "id": "4Tc8MsrJZSMpNZx7u4jSqxr3WhRzqxaNHxLJFqz8tUPR",
> "outcome": {
> "executor_id": "dev-1623333795623-21399959778159",
> "gas_burnt": 6208280264404,
> "logs": [
> "Refund 1 from dev-1623693121955-71667632531176 to serhii.testnet"
> ],
> "metadata": {
> "gas_profile": null,
> "version": 1
> },
> "receipt_ids": [
> "9rxcC9o8x4RX7ftsDCfxK8qnisYv45rA1HGPxhuukWUL"
> ],
> "status": {
> "SuccessValue": "Ijki"
> },
> "tokens_burnt": "620828026440400000000"
> },
> "proof": [
> {
> "direction": "Left",
> "hash": "BzT8YhEDDWSuoGGTBzH2Cj5GC4c56uAQxk41by4KVnXi"
> }
> ]
> },
> {
> "block_hash": "3Q2Zyscj6vG5nC2vdoYfcBHU9RVaAwoxHsHzAKVcAHZ6",
> "id": "9rxcC9o8x4RX7ftsDCfxK8qnisYv45rA1HGPxhuukWUL",
> "outcome": {
> "executor_id": "serhii.testnet",
> "gas_burnt": 0,
> "logs": [],
> "metadata": {
> "gas_profile": null,
> "version": 1
> },
> "receipt_ids": [],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "0"
> },
> "proof": []
> },
> {
> "block_hash": "7Z4LHWksvw7sKYKwpQfjEMG8oigjtRXKa3EopN7hS2v7",
> "id": "H7YWFkvx16Efy2keCQ7BQ67BMEsdgdYLqJ99G4H3dR1D",
> "outcome": {
> "executor_id": "serhii.testnet",
> "gas_burnt": 0,
> "logs": [],
> "metadata": {
> "gas_profile": null,
> "version": 1
> },
> "receipt_ids": [],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "0"
> },
> "proof": [
> {
> "direction": "Left",
> "hash": "61ak42D3duBBunCz3w4xXxoEeR2N7oav5e938TnmGFGN"
> }
> ]
> }
> ],
> "status": {
> "SuccessValue": "Ijki"
> },
> "transaction": {
> "actions": [
> {
> "FunctionCall": {
> "args": "eyJyZWNlaXZlcl9pZCI6ImRldi0xNjIzNjkzMTIxOTU1LTcxNjY3NjMyNTMxMTc2IiwiYW1vdW50IjoiMTAiLCJtc2ciOiJ0YWtlLW15LW1vbmV5In0=",
> "deposit": "1",
> "gas": 100000000000000,
> "method_name": "ft_transfer_call"
> }
> }
> ],
> "hash": "5n1kwA3TQQyFTkddR2Jau3H1Pt8ebQNGaov6aCQ6TDp1",
> "nonce": 47589658000040,
> "priority_fee": 0,
> "public_key": "ed25519:5UfEFyve3RdqKkWtALMreA9jzsAGDgCtwEXGNtkGeruN",
> "receiver_id": "dev-1623333795623-21399959778159",
> "signature": "ed25519:256qp2jAGXhhw2t2XfUAjWwzz3XcD83DH2v9THwDPsZjCLWHU8QJd6cuA773NP9yBmTd2ZyYiFHuxVEkYqnbsaSb",
> "signer_id": "serhii.testnet"
> },
> "transaction_outcome": {
> "block_hash": "96k8kKzFuZWxyiUnT774Rg7DC3XDZNuxhxD1qEViFupd",
> "id": "5n1kwA3TQQyFTkddR2Jau3H1Pt8ebQNGaov6aCQ6TDp1",
> "outcome": {
> "executor_id": "serhii.testnet",
> "gas_burnt": 2428149065268,
> "logs": [],
> "metadata": {
> "gas_profile": null,
> "version": 1
> },
> "receipt_ids": [
> "Hw6z8kJ7CSaC6SgyQzcmXzNX9gq1gaAnLS169qgyZ2Vk"
> ],
> "status": {
> "SuccessReceiptId": "Hw6z8kJ7CSaC6SgyQzcmXzNX9gq1gaAnLS169qgyZ2Vk"
> },
> "tokens_burnt": "242814906526800000000"
> },
> "proof": []
> }
> },
> "id": "myid"
> }
> ```
>
>
> For the [decoded result](/api/rpc/contracts#transaction-return-values), decode the successful `SuccessValue` as described in the RPC reference.
Now, let's try to follow the steps described in the previous section and determine if these transactions was successful. In addition to being successful, let's analyze the various receipts in the series of cross-contract calls to determine how many fungible tokens were transferred. This will be the most complex case we'll look at.
1. Check that `result` » `transaction_outcome` » `outcome` » `status` has `SuccessReceiptId` as a key. If not, this transaction-processing step did not produce the expected receipt; inspect the actual failure and all available outcomes.
2. Take the value of the `SuccessReceiptId` key. In the case above it's `Hw6z8kJ7CSaC6SgyQzcmXzNX9gq1gaAnLS169qgyZ2Vk`.
3. Now, under `result` » `receipts` loop through the array until you find a receipt where the `receipt_id` matches the value from step 2. (Note that in the receipt, under `Actions` there's an element mentioning calling the `method_name: "ft_transfer_call"`.) On the same level of JSON, there's an `args` key. That's a base64-encoded value of the arguments passed to the method. When decoded it is:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{"receiver_id":"dev-1623693121955-71667632531176","amount":"10","msg":"take-my-money"}
```
4. Loop through `result` » `receipts_outcome` until finding the object where `id` is equal to the value from step 2. Similar to step 1, this object will also contain a `status` field that should contain the key `SuccessReceiptId`. For this example, follow `SuccessReceiptId` to the resolver. In general, inspect success/failure and receipt dependencies rather than treating the absence of this particular key as proof that no tokens moved. In the above example, this value is `4Tc8MsrJZSMpNZx7u4jSqxr3WhRzqxaNHxLJFqz8tUPR`.
5. Similar to the previous step, loop through the `result` » `receipts_outcome` until you find the object where the `id` matches the value from step 4. In that object check that `outcome` » `status` has the `SuccessValue` field. This resolver’s `SuccessValue` reports how many fungible-token units were used, not the unused amount returned by `ft_on_transfer`. Note that in the example above the value is `Ijki`, which is the base64-encoded version of `"9"`. In this example, 10 raw token units were sent (from step 3), 9 were used, and 1 was refunded.
For additional clarity, let's take a look at one more optional aspect. In step 4 we isolated an object in `result` » `receipts_outcome`. There's an array of `receipt_ids` that's particularly interesting. In this example, receipt `EB69xtJiLRh9RNzAHgBGmom8551hrK2xSRreqbjvJgu5` executes `ft_on_transfer`. Identify that role from the receipt’s executor and method, not its position in the array. If we loop through the `result` » `receipts_outcome` and find this as the value for the `id` key, we'll see what happened in the function `ft_on_transfer` which takes place in the contract receiving the fungible tokens. In this object the `status` » `SuccessValue` is `IjEi` which is the base64-encoded value of `"1"`.
In summary:
1. A user called the fungible token contract with the method `ft_transfer_call` specifying the receiver account, how many tokens to send, and custom info.
2. The receiver account implemented `ft_on_transfer`, returning `"1"` to the callback function on the fungible token contract.
3. The fungible token contract's callback is `ft_resolve_transfer` and receives this value of `"1"`. It attempts to refund the 1 unused unit, subject to the receiver’s remaining token balance, and subtracts the actual refund from the 10 initially transferred. It then returns to the user how many tokens were used in this back-and-forth series of cross-contract calls: `"9"`.
Wait for finalized resolver execution before releasing a transfer-and-call deposit. An initial transfer event can be followed by a refund event. For a conventional NEP-141 implementation:
| Callback result | Resolution when the full unused balance is refundable |
| - | - |
| `"0"` unused | 10 units used, no refund |
| `"1"` unused | 9 units used, 1 refunded |
| `"10"` unused | 0 used, 10 refunded |
| Callback `Failure` | Resolver attempts to refund all 10 |
A failed callback does not roll back the initial token receipt. The resolver can refund only the available balance; forwarded or spent tokens and account unregistration can change the result. Inspect finalized transfer/refund/burn effects and reconcile the final balance. Support this route only with a reviewed receiving-contract routing and callback policy.
### Failed transfer and call
Let's try to send more tokens than the account has:
> [tab] NEAR CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract call-function as-transaction ft_transfer_call json-args '{"receiver_id": "", "amount": "1000000000", "msg": "take-my-money"}' prepaid-gas '100.0 Tgas' attached-deposit '1 yoctoNEAR' sign-as network-config testnet sign-with-keychain send
> ```
> [tab] RPC
>
> Transaction representation:
>
> ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
> Transaction: {
> block_hash: `456…abc`,
> signer_id: "serhii.testnet",
> public_key: "ed25519:789…def",
> nonce: 123,
> receiver_id: "dev-1623333795623-21399959778159",
> actions: [
> FunctionCall(
> FunctionCallAction {
> method_name: ft_transfer_call,
> args: `{"receiver_id":"dev-1623333916368-58707434878533","amount":"1000000000","msg":"take-my-money"}`,
> gas: 100000000000000,
> deposit: 1,
> },
> ),
> ]
> }
> ```
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=send_tx \
> params:='{"signed_tx_base64":"REPLACE_WITH_FRESH_SIGNED_TRANSACTION_BASE64","wait_until":"FINAL"}'
> ```
>
> To get details of this transaction:
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http post https://archival-rpc.testnet.near.org jsonrpc=2.0 method=EXPERIMENTAL_tx_status \
> params:='{"tx_hash":"FQsh44pvEsK8RS9AbK868CmGwfhUU2pUrizkQ6wCWTsB","sender_account_id":"serhii.testnet","wait_until":"FINAL"}' id=myid
> ```
>
>
> **Example response**:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "final_execution_status": "FINAL",
> "receipts": [
> {
> "predecessor_id": "serhii.testnet",
> "priority": 0,
> "receipt": {
> "Action": {
> "actions": [
> {
> "FunctionCall": {
> "args": "eyJyZWNlaXZlcl9pZCI6ImRldi0xNjIzMzMzOTE2MzY4LTU4NzA3NDM0ODc4NTMzIiwiYW1vdW50IjoiMTAwMDAwMDAwMCIsIm1zZyI6InRha2UtbXktbW9uZXkifQ==",
> "deposit": "1",
> "gas": 100000000000000,
> "method_name": "ft_transfer_call"
> }
> }
> ],
> "gas_price": "186029458",
> "input_data_ids": [],
> "is_promise_yield": false,
> "output_data_receivers": [],
> "signer_id": "serhii.testnet",
> "signer_public_key": "ed25519:5UfEFyve3RdqKkWtALMreA9jzsAGDgCtwEXGNtkGeruN"
> }
> },
> "receipt_id": "83AdQ16bpAC7BEUyF7zoRsAgeNW7HHmjhZLvytEsrygo",
> "receiver_id": "dev-1623333795623-21399959778159"
> },
> {
> "predecessor_id": "system",
> "priority": 0,
> "receipt": {
> "Action": {
> "actions": [
> {
> "Transfer": {
> "deposit": "1"
> }
> }
> ],
> "gas_price": "0",
> "input_data_ids": [],
> "is_promise_yield": false,
> "output_data_receivers": [],
> "signer_id": "system",
> "signer_public_key": "ed25519:11111111111111111111111111111111"
> }
> },
> "receipt_id": "Euy4Q33DfvJTXD8HirE5ACoXnw9PMTQ2Hq47aGyD1spc",
> "receiver_id": "serhii.testnet"
> },
> {
> "predecessor_id": "system",
> "priority": 0,
> "receipt": {
> "Action": {
> "actions": [
> {
> "Transfer": {
> "deposit": "18681184841157733814920"
> }
> }
> ],
> "gas_price": "0",
> "input_data_ids": [],
> "is_promise_yield": false,
> "output_data_receivers": [],
> "signer_id": "serhii.testnet",
> "signer_public_key": "ed25519:5UfEFyve3RdqKkWtALMreA9jzsAGDgCtwEXGNtkGeruN"
> }
> },
> "receipt_id": "6ZDoSeV3gLFS2NXqMCJGEUR3VwBpSxBEPjnEEaAQfmXL",
> "receiver_id": "serhii.testnet"
> }
> ],
> "receipts_outcome": [
> {
> "block_hash": "BohRBwqjRHssDVS9Gt9dj3SYuipxHA81xXFjRVLqgGeb",
> "id": "83AdQ16bpAC7BEUyF7zoRsAgeNW7HHmjhZLvytEsrygo",
> "outcome": {
> "executor_id": "dev-1623333795623-21399959778159",
> "gas_burnt": 3734715409940,
> "logs": [],
> "metadata": {
> "gas_profile": null,
> "version": 1
> },
> "receipt_ids": [
> "Euy4Q33DfvJTXD8HirE5ACoXnw9PMTQ2Hq47aGyD1spc",
> "6ZDoSeV3gLFS2NXqMCJGEUR3VwBpSxBEPjnEEaAQfmXL"
> ],
> "status": {
> "Failure": {
> "ActionError": {
> "index": 0,
> "kind": {
> "FunctionCallError": {
> "ExecutionError": "Smart contract panicked: The account doesn't have enough balance"
> }
> }
> }
> }
> },
> "tokens_burnt": "373471540994000000000"
> },
> "proof": []
> },
> {
> "block_hash": "4BzTmMmTjKvfs6ANS5gmJ6GQzhqianEGWq7SaxSfPbdC",
> "id": "Euy4Q33DfvJTXD8HirE5ACoXnw9PMTQ2Hq47aGyD1spc",
> "outcome": {
> "executor_id": "serhii.testnet",
> "gas_burnt": 0,
> "logs": [],
> "metadata": {
> "gas_profile": null,
> "version": 1
> },
> "receipt_ids": [],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "0"
> },
> "proof": [
> {
> "direction": "Right",
> "hash": "5ipmcdgTieQqFXWQFCwcbZhFtkHE4PL4nW3mknBchpG6"
> }
> ]
> },
> {
> "block_hash": "4BzTmMmTjKvfs6ANS5gmJ6GQzhqianEGWq7SaxSfPbdC",
> "id": "6ZDoSeV3gLFS2NXqMCJGEUR3VwBpSxBEPjnEEaAQfmXL",
> "outcome": {
> "executor_id": "serhii.testnet",
> "gas_burnt": 0,
> "logs": [],
> "metadata": {
> "gas_profile": null,
> "version": 1
> },
> "receipt_ids": [],
> "status": {
> "SuccessValue": ""
> },
> "tokens_burnt": "0"
> },
> "proof": [
> {
> "direction": "Left",
> "hash": "9tcjij6M8Ge4aJcAa97He5nw8pH7PF8ZjRHVahBZD2VW"
> }
> ]
> }
> ],
> "status": {
> "Failure": {
> "ActionError": {
> "index": 0,
> "kind": {
> "FunctionCallError": {
> "ExecutionError": "Smart contract panicked: The account doesn't have enough balance"
> }
> }
> }
> }
> },
> "transaction": {
> "actions": [
> {
> "FunctionCall": {
> "args": "eyJyZWNlaXZlcl9pZCI6ImRldi0xNjIzMzMzOTE2MzY4LTU4NzA3NDM0ODc4NTMzIiwiYW1vdW50IjoiMTAwMDAwMDAwMCIsIm1zZyI6InRha2UtbXktbW9uZXkifQ==",
> "deposit": "1",
> "gas": 100000000000000,
> "method_name": "ft_transfer_call"
> }
> }
> ],
> "hash": "FQsh44pvEsK8RS9AbK868CmGwfhUU2pUrizkQ6wCWTsB",
> "nonce": 47589658000031,
> "priority_fee": 0,
> "public_key": "ed25519:5UfEFyve3RdqKkWtALMreA9jzsAGDgCtwEXGNtkGeruN",
> "receiver_id": "dev-1623333795623-21399959778159",
> "signature": "ed25519:2cPASnxKtCoQtZ9NFq63fg8RzpjvmmE8hL4s2jk8zuhnBCD3AnYQ6chZZrUBGwu7WrsGuWUyohP1bEca4vfbsorC",
> "signer_id": "serhii.testnet"
> },
> "transaction_outcome": {
> "block_hash": "FwHUeqmYpvgkL7eBrUUAEMCuaQshcSy5vm4AHchebhK1",
> "id": "FQsh44pvEsK8RS9AbK868CmGwfhUU2pUrizkQ6wCWTsB",
> "outcome": {
> "executor_id": "serhii.testnet",
> "gas_burnt": 2428166952740,
> "logs": [],
> "metadata": {
> "gas_profile": null,
> "version": 1
> },
> "receipt_ids": [
> "83AdQ16bpAC7BEUyF7zoRsAgeNW7HHmjhZLvytEsrygo"
> ],
> "status": {
> "SuccessReceiptId": "83AdQ16bpAC7BEUyF7zoRsAgeNW7HHmjhZLvytEsrygo"
> },
> "tokens_burnt": "242816695274000000000"
> },
> "proof": []
> }
> },
> "id": "myid"
> }
> ```
>
>
> For the [decoded result](/api/rpc/contracts#transaction-return-values), decode the successful `SuccessValue` as described in the RPC reference.
Let's examine this response.
* `result` » `transaction_outcome` » `outcome` » `status` » `SuccessReceiptId` is `83AdQ16bpAC7BEUyF7zoRsAgeNW7HHmjhZLvytEsrygo`
* Find the outcome whose `id` matches that receipt ID, then inspect `outcome.status.Failure`. A missing outcome is pending; array position `0` is not a reliable receipt identifier.
# Nodes & RPC
Source: https://docs.near.org/integrations/nodes
Node configuration, archival history, health checks, and network upgrades for exchange integrations.
NEAR nodes provide RPC access to the network: exchanges use them to query balances, read blocks and receipt outcomes, and submit transactions.
There are two types of RPC nodes: regular and archival.
A [regular RPC node](https://near-nodes.io/rpc) keeps approximately 36 hours of history - 5 epochs of the NEAR blockchain, meanwhile, archival RPC nodes preserve older blocks, and account states for queries at earlier blocks.
Exchanges can operate a regular RPC node and use its own archival node or an archival RPC provider for older data.
| Capability | Regular RPC node | Archival RPC node |
| - | - | - |
| Current balances and transaction submission | Supported | Supported |
| Blocks, outcomes, and state queries at earlier heights | Last \~36 hours by default | From genesis when initialized with a complete archive |
| History retention | 5 epochs (\~36 hours) by default; configurable | All history retained in the archive |
| Recommended mainnet storage | 4 TB NVMe SSD | 3 TB hot SSD + 115 TB cold disk; grows over time |
| Exchange use cases | Deposit monitoring, withdrawals, current balance checks | Backfilling deposits, investigating older transactions, reconciliation at earlier blocks |
Storage recommendations: [RPC hardware](https://near-nodes.io/rpc/hardware-rpc) · [Archival hardware](https://near-nodes.io/archival/hardware-archival).
***
## Regular RPC Node
A regular RPC node provides a gateway for day-to-day exchange operations. Use it to:
* Read finalized blocks and receipt outcomes to monitor incoming deposits.
* Submit withdrawals and track their execution.
* Query current native and fungible-token balances for reconciliation.
### Resources
* [Hardware requirements and history retention](https://near-nodes.io/rpc/hardware-rpc)
* [Set up and run an RPC node](https://near-nodes.io/rpc)
* [Bootstrap with Epoch Sync](https://near-nodes.io/intro/node-epoch-sync)
***
## Archival Node
An archival RPC node provides past blocks, transaction and receipt outcomes, and account and contract states. Use it to:
* Backfill deposits after downtime that exceeds a regular RPC node's retention window.
* Investigate older deposits, withdrawals, and their receipt chains.
* Query native or fungible-token balances at older block heights for reconciliation.
### Resources
* [Set up and run a split-storage archival node](https://near-nodes.io/archival/split-storage-archival)
* [Archival hardware requirements](https://near-nodes.io/archival/hardware-archival)
***
## Running Private Nodes
Exchanges running RPC nodes can reduce public exposure and unsolicited peer connections by restricting RPC access and disabling inbound peering. This setup ensures that only authorized applications or nodes can interact with the RPC node, thus enhancing security.
RPC access and peering are configured separately. Add the relevant settings below into the node's `config.json`, then restart `neard`.
### Private RPC Access
Bind RPC to the loopback interface to prevent direct access from other hosts:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"rpc": {
"addr": "127.0.0.1:3030"
}
}
```
For applications on other hosts, bind RPC to a private interface and restrict access through a firewall or VPN.
### Outbound-only Peering
A node can initiate its ordinary peer connections and exchange blocks and transactions over those connections. Disable inbound connections from ordinary peers with:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"network": {
"experimental": {
"inbound_disabled": true
}
}
}
```
NEAR nodes accept inbound peer connections on TCP port `24567` by default - configured through `network.addr`. Once your node is synchronized, you can close this port in the firewall while keeping `inbound_disabled: true`.
### State Sync Caveats
Nodes can follow the chain and catch up over outbound peer connections (i.e. `inbound_disabled: true`) while the inbound peering port is closed.
However, if your node is too far behind, you can open the inbound peering port temporarily to allow incoming connections and catch up more efficiently.
Open the port and follow the [Epoch Sync setup](https://near-nodes.io/intro/node-epoch-sync) to refresh `network.boot_nodes` before starting `neard`. Once synchronization completes, you can close the peering port to new inbound connections again.
> [accordion] State Sync on Archival Nodes
>
> Archival nodes download and process missing blocks instead of using Epoch Sync and state sync to skip ahead. They can use outbound-only peering, but need peers that retain the missing history. Recovery after extended downtime can be slow. Follow [archival setup](https://near-nodes.io/archival/split-storage-archival) for storage configuration and historical data requirements.
***
## Frequently Asked Questions
> [accordion] Can regular and archival RPC nodes run with inbound peering disabled?
>
> Yes. Set `network.experimental.inbound_disabled` to `true` and restrict RPC access separately. Regular nodes need inbound connectivity for peer state sync during setup or recovery after falling far behind. Archival nodes process missing blocks and need peers that retain that history. See [Running Private Nodes](#running-private-nodes) for configuration and recovery caveats.
> [accordion] Can a node be configured to archive all blockchain data since genesis?
>
> Yes, with an archival configuration and a complete history source. The run flag is:
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> ./target/release/neard run --archive
> ```
>
> Follow [split-storage archival setup](https://near-nodes.io/archival/split-storage-archival) for the network and supported node version. The flag preserves history as the node processes it; it does not restore data missing from an existing pruned database. Epoch Sync and state sync do not provide a complete archive.
> [accordion] Can a node be configured to expose an RPC (ex: HTTP) interface?
>
> Yes. JSON-RPC can be enabled or disabled; configure its listening address with `rpc.addr` in the node's `config.json` file.
> [accordion] Can a node be gracefully terminated and restarted (using archived data on disk to continue syncing)?
>
> Yes.
> [accordion] Does a node expose an interface for retrieving health telemetry in a structured format (ex: JSON) over RPC?
>
> Yes. `GET /status` and `GET /health` provide this interface.
>
> * `/status`: node version, block context, and syncing status. Use [network RPC](/api/rpc/introduction) for peer information.
> * `/health`: success/failure if node is up running & progressing
> [accordion] Can a node be started using a Dockerfile without human supervision?
>
> Yes. Use a supported `neard` release or container image, persist the node’s home and storage volumes, and supply the network’s genesis and configuration. Pin the release and follow [node operation guidance](https://near-nodes.io/).
> [accordion] What is the source of truth for current block height exposed via API?
>
> * MainNet
> * [https://nearblocks.io](https://nearblocks.io)
> * `https://rpc.mainnet.near.org/status`
> * TestNet
> * [https://testnet.nearblocks.io](https://testnet.nearblocks.io)
> * `https://rpc.testnet.near.org/status`
> [accordion] How can I quickly sync a node?
>
> For regular RPC nodes, follow the [Epoch Sync setup](https://near-nodes.io/intro/node-epoch-sync), then let the node download recent state through peer state sync. Archival nodes require the [archival setup](https://near-nodes.io/archival/split-storage-archival).
> [accordion] What is the network upgrade process?
>
> Nodes signal supported protocol versions, and upgrades activate according to the protocol upgrade rules. Normal upgrades preserve the chain’s genesis and history. Follow supported node releases and test your integration before an activation boundary.
# Accessing On-chain Data
Source: https://docs.near.org/integrations/on-chain-data
RPC queries, indexers, and hosted data APIs for exchange integrations.
Exchanges need on-chain data to detect deposits, track withdrawals, and reconcile balances. RPC provides queries for specific blocks, accounts, and transactions; indexers process blockchain data continuously and make it searchable across accounts and blocks.
| Approach | Exchange use cases |
| - | - |
| RPC | Check balances at a finalized block, submit withdrawals, and query transaction outcomes |
| Indexer | Track incoming transfers, process receipt outcomes and token events, and maintain a history for reconciliation |
| Hosted data API | Look up an account's assets, retrieve transfer history, and investigate transactions without operating an indexer |
***
## RPC Queries
Use RPC to query native NEAR balances with `view_account`, token balances through `ft_balance_of`, and transaction execution through status queries. For reconciliation, query balances at the same finalized block. Access to older blocks and state depends on the provider's retained history.
Resources:
* [RPC reference](/api/rpc/introduction)
* [Nodes and archival access](/integrations/nodes)
* [Balances & Reconciliation](/integrations/balance-changes)
* [Blocks & Finality](/integrations/blocks-and-finality)
***
## Indexers
An indexer processes blocks, receipts, execution outcomes, and contract events, and can store relevant movements in a database. For an exchange, this supports continuous deposit monitoring and queries across many blocks, such as all transfers into a customer's account.
Process finalized outcomes across all shards, including receipts generated by contract calls. Save a processing checkpoint so monitoring can resume after an interruption, and deduplicate movements when replaying data. For fungible tokens, identify transfers using events emitted by the supported token contract.
Resources:
* [Introduction to indexers](/data-infrastructure/indexers)
* [NEAR Indexer](/data-infrastructure/near-indexer)
* [Receiving Deposits](/integrations/deposits)
* [Fungible-token deposit accounting](/integrations/fungible-tokens#deposit-accounting)
***
## Hosted Data APIs
Hosted APIs expose indexed data through HTTP endpoints, allowing an integration to query account assets and history without running its own indexing infrastructure.
| Service | Available data |
| - | - |
| [FastNEAR API](https://docs.fastnear.com/api) | Account assets, staking pools, and public-key-to-account lookups |
| [Pikespeak API](https://api.pikespeak.ai/docs) | Account balances, NEAR and token transfers, contract events, and analytics |
| [NearBlocks API](https://api.nearblocks.io/api-docs/) | Account information, transactions, receipts, and token transfer history |
Check the selected API's network coverage, indexing delay, pagination, and how far back its data extends. Before crediting a deposit, establish finality and successful receipt execution; see [Receiving Deposits](/integrations/deposits). Use a finalized block checkpoint when reconciling balances.
For additional examples, see [Data APIs](/data-infrastructure/data-api).
# Staking & Delegation
Source: https://docs.near.org/integrations/staking
Validator selection, delegation, withdrawal availability, and staking-pool custody.
NEAR delegation uses staking-pool contracts to manage delegated funds and distribute rewards. For an exchange, this requires tracking balances held in each pool and when unstaked funds become available for withdrawal.
***
## Balances and Withdrawals
Query the staking-pool contract for the account's delegated balance. In the reference pool, the following read-only methods take `{"account_id":""}` and return balances in yoctoNEAR:
| Method | Result |
| - | - |
| `get_account_staked_balance` | Staked balance |
| `get_account_unstaked_balance` | Unstaked balance, which may still be waiting for withdrawal |
| `get_account_total_balance` | Sum of staked and unstaked balances |
| `is_account_unstaked_balance_available` | Whether the unstaked balance can be withdrawn in the current epoch |
Unstaking and withdrawing are separate operations. The [reference staking pool](https://github.com/near/core-contracts/blob/master/staking-pool/src/lib.rs) waits four epochs before withdrawal becomes available; query the selected pool’s withdrawal availability.
Use `unstake` or `unstake_all` to unstake, then `withdraw` or `withdraw_all` to return available funds to the delegator's account. See [Staking NEAR Tokens](/protocol/tutorials/staking-tokens) for commands and [Balances & Reconciliation](/integrations/balance-changes) for account balance queries.
***
## Validator Participation
Anyone can become a validator by meeting the network’s stake requirements and following the protocol’s validator selection process.
Submit a staking proposal and inspect the current and upcoming validator sets through the [network RPC](/api/rpc/introduction). Selection changes take effect at epoch boundaries. See [validators](/protocol/network/validators) for current requirements.
***
## Frequently Asked Questions
> [accordion] How long does a validator remain a validator?
>
> A validator will stop being a validator for the following reasons:
>
> * Not producing enough blocks or chunks.
> * Not getting elected in the auction for next epoch because their stake is not large enough.
>
> A validator can continue while meeting the election and performance requirements. Slashing is not enabled in nearcore 2.13.4.
>
> Validator election happens in [epochs](/protocol/network/epoch). Validator assignments are determined ahead of the epoch in which they apply. Query upcoming validator sets to determine when a staking proposal takes effect.
> [accordion] What is the penalty for misbehaving validators?
>
> Validators are not slashed for being offline but they do miss out on the rewards of validating. Validators who miss too many blocks or chunks will be removed from the validation set in the next auction and not get any reward (but, again, without slashing).
# Testing an Integration
Source: https://docs.near.org/integrations/testing
Test an integration on NEAR testnet or in a local sandbox.
Use testnet to exercise deposit detection, withdrawal submission, and reconciliation before enabling mainnet operations.
> [!TIP]
>
> Testnet tokens are free to use and can be easily obtained from the [testnet faucet](/getting-started/faucet).
***
## Testnet Setup
Generate test accounts using the [Accounts](/integrations/accounts) examples and fund them through the [testnet faucet](/getting-started/faucet). The faucet page also links to a faucet for testnet fungible tokens.
* RPC endpoints:
* `https://rpc.testnet.near.org`
* `https://test.rpc.fastnear.com`
* [More Testnet RPC providers](/api/rpc/providers#testnet)
* Explorer: [Testnet NearBlocks](https://testnet.nearblocks.io/)
* Node and archival access: [Nodes](/integrations/nodes)
***
## Local Sandbox Testing
For local development and automated tests, a sandbox is also an option. It runs a local NEAR network where you can create test accounts, deploy contracts, and test transfers in a controlled environment. See [sandbox tests](/smart-contracts/testing/integration-test) for setup and examples.
# Transaction Lifecycle
Source: https://docs.near.org/integrations/transaction-lifecycle
How NEAR transactions are signed, validated, included in chunks, and executed.
A NEAR transaction passes through signing, validation, and chunk inclusion before execution outcomes are available. The steps below describe this lifecycle; see [Blocks & Finality](/integrations/blocks-and-finality) for when execution can be treated as final.
***
## The Life of a Transaction
**1. Create and sign**
A client creates a transaction, computes the transaction hash and signs this hash to get a signed transaction. Now this signed transaction can be sent to a node.
**2. Route to the signer’s shard**
The RPC node uses `signer_id` to identify the signer’s shard. Transactions are forwarded to upcoming chunk producers for that shard.
**3. Validate and propagate**
The receiving node checks transaction metadata, including the signature, before forwarding it. A chunk producer tracking the signer’s shard validates it against available state, including access-key permissions, nonce, and balance. Invalid transactions can be rejected before inclusion; see [transaction execution](/protocol/transactions/transaction-execution).
**4. Add to the transaction pool**
Valid transactions are added to the transaction pool (every validating node has its own independent copy of a transaction pool). The transaction pool maintains transactions that are not yet discarded and not yet included into the chain.
**5. Select transactions for a chunk**
A pool iterator is used to pick transactions from the pool one at a time, with increasing nonces for each access key (there is no global ordering across accounts), until the pool is drained or some chunk limit is reached (max number of transactions per chunk or max gas burnt per chunk to process transactions). Please refer to [transaction execution](/protocol/transactions/transaction-execution) and [gas](/protocol/transactions/gas) documentation for more details.
Transactions that cannot fit in the current chunk can remain pending. Admission to a node’s pool does not guarantee inclusion or execution; do not use pool admission as a settlement signal.
**6. Validate before chunk production**
Before producing a chunk, transactions are ordered and validated again. This is done to produce chunks with only valid transactions across a distributed system.
**7. Execute receipts**
When the included transaction is processed on the signer’s shard, it charges the signer and creates an action receipt. That receipt executes on the receiver’s shard; function calls can generate further receipts, including cross-contract calls, callbacks, and refunds. Execution may span multiple blocks.
**8. Read execution outcomes**
Execution errors are recorded in transaction and receipt outcomes. Read these outcomes through RPC; a successful HTTP response or initial transaction outcome does not prove that later receipts succeeded.
***
## Frequently Asked Questions
> [accordion] How are transactions constructed and signed?
>
> Transactions are a collection of related data that is composed and cryptographically signed by the sender using their private key. The related public key is part of the transaction and used for signature verification. Only signed transactions may be sent to the network for processing.
>
> Transactions can be constructed and signed offline. Signing itself does not require a node, but the mandatory recent block hash and access-key nonce must be obtained beforehand. Use a fresh finalized block and a nonce reserved for that key; see [transaction construction](/integrations/create-transactions).
>
> See [transactions](/protocol/transactions) in the concepts section of our documentation.
> [accordion] How is the hash preimage generated? Which fields does the raw transaction consist of?
>
> For a transaction, we sign the hash of the transaction. More specifically, what is signed is the `sha256` of the transaction object serialized in borsh ([https://github.com/near/borsh](https://github.com/near/borsh)).
> [accordion] How do transactions work on the NEAR platform?
>
> A `Transaction` is made up of one or more `Action`s. Common action types include `CreateAccount`,
> `DeployContract`, `FunctionCall`, `Transfer`, `Stake`, `AddKey`, `DeleteKey` and `DeleteAccount`. Delegation, global-contract, deterministic-initialization, and gas-key actions are also supported; consult the [versioned action definitions](https://github.com/near/nearcore/blob/2.13.4/core/primitives/src/action/mod.rs). Transactions are composed by a sender and then signed using the private keys of a valid NEAR account to create a `SignedTransaction`. This signed transaction is considered ready to send to the network for processing.
>
> Transactions are received via our JSON-RPC endpoint and routed to the shard where the `sender` account lives. This "home shard" for the sender account is then responsible for processing the transaction and generating related receipts to be applied across the network.
>
> Once received by the network, signed transactions are verified (using the embedded public key of the signer) and processed into an initial action receipt containing the transaction’s action list; function calls can generate additional receipts. `Action Receipt`s carry actions to execute, while `Data Receipt`s carry execution results to dependent calls, such as callbacks.
>
> These receipts are then propagated around the network using the receiver account's "home shard" since each account lives on one and only one shard. The receiving shard schedules receipt execution subject to dependencies and execution limits.
>
> Receipts may generate other, new receipts which in turn are propagated around the network until all receipts have been applied. If an action fails, state changes within that receipt are rolled back. Earlier successful receipts remain committed, and gas can still be charged. Refunds and callbacks execute as separate receipts; inspect their finalized outcomes.
>
> For more detail, see the documentation on [transactions](/protocol/transactions), [actions](/protocol/transactions/transaction-anatomy#actions), and [receipts](/protocol/transactions/transaction-execution)
> [accordion] How does NEAR serialize transactions?
>
> We use a simple binary serialization format that's deterministic: [https://borsh.io](https://borsh.io)
> [accordion] How old can the referenced block hash be before it's invalid?
>
> Query the network’s protocol configuration at a finalized block:
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=EXPERIMENTAL_protocol_config \
> params:='{"finality":"final"}'
> # Replace testnet with mainnet to query mainnet.
> ```
>
> Use `transaction_validity_period`, measured in blocks, from the [`protocol_config` RPC endpoint](/api/rpc/protocol#protocol-config). For example, `86400` blocks at a 600ms cadence correspond to approximately 14.4 hours; validity is determined by blocks, not a fixed wall-clock deadline.
# Decentralized Autonomous Organizations
Source: https://docs.near.org/primitives/dao
Learn about Decentralized Autonomous Organizations (DAOs) on NEAR - self-organized groups that coordinate membership, decision-making, and funding through smart contract voting.
Decentralized Autonomous Organizations (DAOs) are self-organized groups that form around common purposes. Membership, decision-making, and funding are coordinated by publicly voting on proposals through a smart contract.

In contrast with [FT](./ft/ft) and [NFT](./nft/nft), DAO contract's are not standardized. Because of this, on this page we will use as
reference the [sputnik dao contract](https://github.com/near-daos/sputnik-dao-contract). The main concepts covered here should
easily generalizable to other DAO implementations.
> [!TIP]
>
> The examples below use `testnet` so you can try them safely without spending
> real funds.
The WebApp examples use the local `useNearWallet` hook from the [Hello NEAR provider setup](/web3-apps/quickstart#context-provider).
***
## Create a DAO
You can create a DAO by interacting with the `sputnik-dao` contract:
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const DAO_FACTORY_CONTRACT_ADDRESS = 'sputnikv2.testnet';
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: DAO_FACTORY_CONTRACT_ADDRESS,
> method: 'create',
> args: {
> name: 'primitives',
> args: btoa({
> config: {
> name: 'Primitives',
> purpose: 'Building primitives on NEAR',
> metadata: '',
> },
> policy: ['your-account.testnet'],
> }),
> },
> gas: 300000000000000,
> deposit: 6000000000000000000000000,
> });
> ```
>
> > [!NOTE]
> >
> > The full list of roles and permissions you can find [here](https://github.com/near-daos/sputnik-dao-contract#roles-and-permissions).
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> export COUNCIL='["your-account.testnet"]'
> export ARGS=`echo '{"config": {"name": "Primitives", "purpose": "Building primitives on NEAR", "metadata":""}, "policy": '$COUNCIL'}' | base64`
>
> near call sputnikv2.testnet create "{\"name\": \"primitives\", \"args\": \"$ARGS\"}" --useAccount your-account.testnet --amount 6 --gas 150000000000000
> ```
>
> > [!NOTE]
> >
> > The full list of roles and permissions you can find [here](https://github.com/near-daos/sputnik-dao-contract#roles-and-permissions).
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/dao/create-dao.json)
>
> > [!NOTE]
> >
> > You can find the complete list of [roles and permissions here](https://github.com/near-daos/sputnik-dao-contract#roles-and-permissions).
> [tab] 📄 Contract
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Validator interface, for cross-contract calls
> #[ext_contract(ext_dao_factory_contract)]
> trait ExternalDaoFactoryContract {
> fn create(&mut self, name: AccountId, args: Base64VecU8) -> Promise;
> }
>
> // Implement the contract structure
> #[near]
> impl Contract {
> #[payable]
> pub fn create_dao(&mut self, name: AccountId, args: Base64VecU8) -> Promise {
> let promise = ext_dao_factory_contract::ext(self.dao_factory_contract.clone())
> .with_attached_deposit(env::attached_deposit())
> .with_static_gas(Gas(30*TGAS))
> .create(name, args);
>
> return promise.then( // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .with_static_gas(Gas(50*TGAS))
> .external_common_callback()
> )
> }
>
> #[private] // Public - but only callable by env::current_account_id()
> pub fn external_common_callback(&self, #[callback_result] call_result: Result<(), PromiseError>) {
> // Check if the promise succeeded
> if call_result.is_err() {
> log!("There was an error contacting external contract")
> }
> }
> }
> ```
> [!WARNING]
>
> Replace `your-account.testnet` in the `policy` with an account you control.
> The accounts in the policy become the DAO's council — if you leave a
> placeholder (or someone else's account), you won't be able to control the DAO
> you create, and any funds sent to it could become inaccessible.
***
### Using Global Contract
You can deploy a new DAO using our global contract - a pre-deployed [a Sputnik DAO contract](https://github.com/near-daos/sputnik-dao-contract/tree/main/sputnikdao2) that you can reuse. [Global contracts](../smart-contracts/global-contracts) are deployed once and can be reused by any account without incurring high storage costs.
> [tab] account
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract deploy use-global-account-id dao.globals.primitives.testnet \
> with-init-call new \
> json-args '{"config": {"name": "Primitives", "purpose": "Building primitives on NEAR", "metadata":""}, "policy": [""]}' \
> prepaid-gas '100.0 Tgas' \
> attached-deposit '0 NEAR' \
> network-config testnet \
> sign-with-keychain \
> send
> ```
> [tab] hash
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract deploy use-global-hash Ea8tHXFSQVszVwGASyzAfLq65DjcRDhkfab4FcPaRpgD \
> with-init-call new \
> json-args '{"config": {"name": "Primitives", "purpose": "Building primitives on NEAR", "metadata":""}, "policy": [""]}' \
> prepaid-gas '100.0 Tgas' \
> attached-deposit '0 NEAR' \
> network-config testnet \
> sign-with-keychain \
> send
> ```
> [!NOTE]
>
> Deploying by **hash** creates an immutable contract that never changes.
> Deploying by **account ID** creates an updatable contract that changes when
> the referenced account's contract is updated. Choose based on whether you want
> your FT contract to be updatable or permanent.
***
### Voting policy
Currently, DAOs support two different types of [voting policies](https://github.com/near-daos/sputnik-dao-contract#voting-policy): `TokenWeight`, and `RoleWeight`.
When the vote policy is `TokenWeight`, the council votes using [tokens](./ft/ft). The weigh of a vote is the proportion of tokens used for voting over the token's total supply.
When the vote policy is `RoleWeight(role)`, the vote weigh is computed as "one over the total number of people with the role".
> [accordion] Voting Threshold
>
> Both voting policies further include a `threshold` for passing a proposal, which can be a ratio or a fixed number.
>
> The ratio indicates that you need a proportion of people/tokens to approve the proposal (e.g. half the people need to vote, and to vote positively). A fixed number indicated that you need a specific number of votes/tokens to pass the proposal (e.g. 3 people/tokens are enough to approve the proposal).
***
## List of DAOs
Query the list of DAOs existing in Sputnik Dao.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const DAO_FACTORY_CONTRACT_ADDRESS = 'sputnik-dao.near';
> const { viewFunction } = useNearWallet();
>
> await viewFunction({
> method: 'get_dao_list',
> args: {},
> contractId: DAO_FACTORY_CONTRACT_ADDRESS,
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near view sputnik-dao.near get_dao_list '{}'
> ```
>
> > [accordion] Example response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > [
> > 'ref-finance.sputnik-dao.near'
> > 'gaming-dao.sputnik-dao.near',
> > ...
> > ]
> > ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/dao/dao-list.json)
>
> > [accordion] Example response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > [
> > 'ref-finance.sputnik-dao.near'
> > 'gaming-dao.sputnik-dao.near',
> > ...
> > ]
> > ```
***
## Query Existing Proposals
These snippets will enable you to query the proposals existing in a particular DAO.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const DAO_CONTRACT_ADDRESS = 'nearweek-news-contribution.sputnik-dao.near';
> const { viewFunction } = useNearWallet();
>
> await viewFunction({
> method: 'get_proposals',
> args: { from_index: 9262, limit: 2 },
> contractId: DAO_CONTRACT_ADDRESS,
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near view nearweek-news-contribution.sputnik-dao.near get_proposals '{"from_index": 9262, "limit": 2}'
> ```
>
> > [accordion] Example response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > [
> > {
> > id: 9262,
> > proposer: 'pasternag.near',
> > description: 'NEAR, a top non-EVM blockchain, has gone live on Router’s Testnet Mandara. With Router Nitro, our flagship dApp, users in the NEAR ecosystem can now transfer test tokens to and from NEAR onto other supported chains. $$$$https://twitter.com/routerprotocol/status/1727732303491961232',
> > kind: {
> > Transfer: {
> > token_id: '',
> > receiver_id: 'pasternag.near',
> > amount: '500000000000000000000000',
> > msg: null
> > }
> > },
> > status: 'Approved',
> > vote_counts: { council: [ 1, 0, 0 ] },
> > votes: { 'brzk-93444.near': 'Approve' },
> > submission_time: '1700828277659425683'
> > },
> > {
> > id: 9263,
> > proposer: 'fittedn.near',
> > description: 'How to deploy BOS component$$$$https://twitter.com/BitkubAcademy/status/1728003163318563025?t=PiN6pwS380T1N4JuQXSONA&s=19',
> > kind: {
> > Transfer: {
> > token_id: '',
> > receiver_id: 'fittedn.near',
> > amount: '500000000000000000000000',
> > msg: null
> > }
> > },
> > status: 'InProgress',
> > vote_counts: { 'Whitelisted Members': [ 1, 0, 0 ] },
> > votes: { 'trendheo.near': 'Approve' },
> > submission_time: '1700832601849419123'
> > }
> > ]
> > ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/dao/query-exist-proposals.json)
>
> > [accordion] Example response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > [
> > {
> > "id": 9262,
> > "proposer": "pasternag.near",
> > "description": "NEAR, a top non-EVM blockchain, has gone live on Router’s Testnet Mandara. With Router Nitro, our flagship dApp, users in the NEAR ecosystem can now transfer test tokens to and from NEAR onto other supported chains. $$$$https://twitter.com/routerprotocol/status/1727732303491961232",
> > "kind": {
> > "Transfer": {
> > "token_id": "",
> > "receiver_id": "pasternag.near",
> > "amount": "500000000000000000000000",
> > "msg": null
> > }
> > },
> > "status": "Approved",
> > "vote_counts": {
> > "council": [1, 0, 0]
> > },
> > "votes": {
> > "brzk-93444.near": "Approve"
> > },
> > "submission_time": "1700828277659425683"
> > },
> > {
> > "id": 9263,
> > "proposer": "fittedn.near",
> > "description": "How to deploy BOS component$$$$https://twitter.com/BitkubAcademy/status/1728003163318563025?t=PiN6pwS380T1N4JuQXSONA&s=19",
> > "kind": {
> > "Transfer": {
> > "token_id": "",
> > "receiver_id": "fittedn.near",
> > "amount": "500000000000000000000000",
> > "msg": null
> > }
> > },
> > "status": "Expired",
> > "vote_counts": {
> > "Whitelisted Members": [2, 0, 0]
> > },
> > "votes": {
> > "trendheo.near": "Approve",
> > "vikash.near": "Approve"
> > },
> > "submission_time": "1700832601849419123"
> > }
> > ]
> > ```
***
## Create proposal
Create a proposal so other users can vote in favor or against it.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const DAO_CONTRACT_ADDRESS = 'primitives.sputnikv2.testnet';
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: DAO_CONTRACT_ADDRESS,
> method: 'add_proposal',
> args: {
> proposal: {
> description: 'My first proposal',
> kind: {
> Transfer: {
> token_id: '',
> receiver_id: 'your-account.testnet',
> amount: '10000000000000000000000000',
> },
> },
> },
> },
> gas: 300000000000000,
> deposit: 100000000000000000000000,
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call primitives.sputnikv2.testnet add_proposal '{"proposal": {"description": "My first proposal", "kind": { "Transfer": {"token_id": "", "receiver_id": "your-account.testnet", "amount": "10000000000000000000000000"}}}}' --deposit 0.1 --gas 300000000000000 --useAccount your-account.testnet
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/dao/create-proposal.json)
> [tab] 📄 Contract
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Account ID that represents a token in near-sdk v3
> // Need to keep it around for backward compatibility
> pub type OldAccountId = String;
>
> // How the voting policy votes get weighted.
> #[near(serializers = [json, borsh]) #[derive(Clone, PartialEq)] #[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
> pub enum WeightKind {
> // Using token amounts and total delegated at the moment.
> TokenWeight,
> // Weight of the group role. Roles that don't have scoped group are not supported.
> RoleWeight,
> }
>
> // Direct weight or ratio to total weight, used for the voting policy
> #[near(serializers = [json, borsh]) #[derive(Clone)] #[cfg_attr(not(target_arch = "wasm32"), derive(Debug, PartialEq))] #[serde(untagged)]
> pub enum WeightOrRatio {
> Weight(U128),
> Ratio(u64, u64),
> }
>
> // Defines configuration of the vote
> #[near(serializers = [json, borsh]) #[derive(Clone)] #[cfg_attr(not(target_arch = "wasm32"), derive(Debug, PartialEq))]
> pub struct VotePolicy {
> // Kind of weight to use for votes.
> pub weight_kind: WeightKind,
> // Minimum number required for vote to finalize.
> // If weight kind is TokenWeight - this is minimum number of tokens required.
> // This allows to avoid situation where the number of staked tokens from total supply is too small.
> // If RoleWeight - this is minimum number of votes.
> // This allows to avoid situation where the role is got too small but policy kept at 1/2, for example.
> pub quorum: U128,
> // How many votes to pass this vote.
> pub threshold: WeightOrRatio,
> }
>
> #[near(serializers = [json, borsh])] #[derive(Clone)] #[cfg_attr(not(target_arch = "wasm32"), derive(Debug, PartialEq))]
> pub enum RoleKind {
> // Matches everyone, who is not matched by other roles.
> Everyone,
> // Member greater or equal than given balance. Can use `1` as non-zero balance.
> Member(U128),
> // Set of accounts.
> Group(HashSet),
> }
>
> #[near(serializers = [json, borsh])] #[derive(Clone)] #[cfg_attr(not(target_arch = "wasm32"), derive(Debug, PartialEq))]
> pub struct RolePermission {
> // Name of the role to display to the user.
> pub name: String,
> // Kind of the role: defines which users this permissions apply.
> pub kind: RoleKind,
> // Set of actions on which proposals that this role is allowed to execute.
> // :
> pub permissions: HashSet,
> // For each proposal kind, defines voting policy.
> pub vote_policy: HashMap,
> }
>
> // Defines voting / decision making policy of this DAO
> #[near(serializers = [json, borsh])] #[derive(Clone)] #[cfg_attr(not(target_arch = "wasm32"), derive(Debug, PartialEq))]
> pub struct Policy {
> // List of roles and permissions for them in the current policy.
> pub roles: Vec,
> // Default vote policy. Used when given proposal kind doesn't have special policy.
> pub default_vote_policy: VotePolicy,
> // Proposal bond.
> pub proposal_bond: U128,
> // Expiration period for proposals.
> pub proposal_period: U64,
> // Bond for claiming a bounty.
> pub bounty_bond: U128,
> // Period in which giving up on bounty is not punished.
> pub bounty_forgiveness_period: U64,
> }
>
> // Versioned policy
> #[near(serializers = [json, borsh])] #[derive(Clone)] #[cfg_attr(not(target_arch = "wasm32"), derive(Debug, PartialEq))]
> pub enum VersionedPolicy {
> // Default policy with given accounts as council.
> Default(Vec),
> Current(Policy),
> }
>
> // Function call arguments
> #[near(serializers = [json, borsh])] #[cfg_attr(not(target_arch = "wasm32"), derive(Clone, Debug))]
> pub struct ActionCall {
> method_name: String,
> args: Base64VecU8,
> deposit: U128,
> gas: U64,
> }
>
> // Bounty information.
> #[near(serializers = [json, borsh])] #[derive(Clone)] #[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
> pub struct Bounty {
> /// Description of the bounty.
> pub description: String,
> /// Token the bounty will be paid out.
> /// Can be "" for `$NEAR` or a valid account id.
> pub token: OldAccountId,
> /// Amount to be paid out.
> pub amount: U128,
> /// How many times this bounty can be done.
> pub times: u32,
> /// Max deadline from claim that can be spend on this bounty.
> pub max_deadline: U64,
> }
>
> // Info about factory that deployed this contract and if auto-update is allowed
> #[near(serializers = [json, borsh])] #[cfg_attr(not(target_arch = "wasm32"), derive(Clone, Debug))]
> pub struct FactoryInfo {
> pub factory_id: AccountId,
> pub auto_update: bool,
> }
>
> // Function call arguments
> #[near(serializers = [json, borsh])] #[cfg_attr(not(target_arch = "wasm32"), derive(Clone, Debug))]
> pub struct PolicyParameters {
> pub proposal_bond: Option,
> pub proposal_period: Option,
> pub bounty_bond: Option,
> pub bounty_forgiveness_period: Option,
> }
>
> // Votes recorded in the proposal
> #[near(serializers = [json, borsh])] #[derive(Clone, Debug)]
> pub enum Vote {
> Approve = 0x0,
> Reject = 0x1,
> Remove = 0x2,
> }
>
> // Configuration of the DAO
> #[near(serializers = [json, borsh])] #[derive(Clone, Debug)]
> pub struct Config {
> // Name of the DAO.
> pub name: String,
> // Purpose of this DAO.
> pub purpose: String,
> // Generic metadata. Can be used by specific UI to store additional data.
> // This is not used by anything in the contract.
> pub metadata: Base64VecU8,
> }
>
> // Kinds of proposals, doing different action
> #[near(serializers = [json, borsh])] #[cfg_attr(not(target_arch = "wasm32"), derive(Clone, Debug))]
> pub enum ProposalKind {
> // Change the DAO config.
> ChangeConfig { config: Config },
> // Change the full policy.
> ChangePolicy { policy: VersionedPolicy },
> // Add member to given role in the policy. This is short cut to updating the whole policy.
> AddMemberToRole { member_id: AccountId, role: String },
> // Remove member to given role in the policy. This is short cut to updating the whole policy.
> RemoveMemberFromRole { member_id: AccountId, role: String },
> // Calls `receiver_id` with list of method names in a single promise.
> // Allows this contract to execute any arbitrary set of actions in other contracts.
> FunctionCall {
> receiver_id: AccountId,
> actions: Vec,
> },
> // Upgrade this contract with given hash from blob store.
> UpgradeSelf { hash: Base58CryptoHash },
> // Upgrade another contract, by calling method with the code from given hash from blob store.
> UpgradeRemote {
> receiver_id: AccountId,
> method_name: String,
> hash: Base58CryptoHash,
> },
> // Transfers given amount of `token_id` from this DAO to `receiver_id`.
> // If `msg` is not None, calls `ft_transfer_call` with given `msg`. Fails if this base token.
> // For `ft_transfer` and `ft_transfer_call` `memo` is the `description` of the proposal.
> Transfer {
> // Can be "" for `$NEAR` or a valid account id.
> token_id: OldAccountId,
> receiver_id: AccountId,
> amount: U128,
> msg: Option,
> },
> // Sets staking contract. Can only be proposed if staking contract is not set yet.
> SetStakingContract { staking_id: AccountId },
> // Add new bounty.
> AddBounty { bounty: Bounty },
> // Indicates that given bounty is done by given user.
> BountyDone {
> bounty_id: u64,
> receiver_id: AccountId,
> },
> // Just a signaling vote, with no execution.
> Vote,
> // Change information about factory and auto update.
> FactoryInfoUpdate { factory_info: FactoryInfo },
> // Add new role to the policy. If the role already exists, update it. This is short cut to updating the whole policy.
> ChangePolicyAddOrUpdateRole { role: RolePermission },
> // Remove role from the policy. This is short cut to updating the whole policy.
> ChangePolicyRemoveRole { role: String },
> // Update the default vote policy from the policy. This is short cut to updating the whole policy.
> ChangePolicyUpdateDefaultVotePolicy { vote_policy: VotePolicy },
> // Update the parameters from the policy. This is short cut to updating the whole policy.
> ChangePolicyUpdateParameters { parameters: PolicyParameters },
> }
>
> #[near(serializers = [json])]
> pub struct ProposalInput {
> /// Description of this proposal.
> pub description: String,
> /// Kind of proposal with relevant information.
> pub kind: ProposalKind,
> }
>
> // Validator interface, for cross-contract calls #[ext_contract(ext_dao_contract)]
> trait ExternalDaoContract {
> fn add_proposal(&mut self, proposal: ProposalInput) -> Promise;
> }
>
> // Implement the contract structure #[near]
> impl Contract { #[payable]
> pub fn create_proposal(&mut self, proposal: ProposalInput) -> Promise {
> let promise = ext_dao_contract::ext(self.dao_contract.clone())
> .with_attached_deposit(env::attached_deposit())
> .with_static_gas(Gas(5\*TGAS))
> .add_proposal(proposal);
>
> return promise.then( // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .with_static_gas(Gas(50*TGAS))
> .external_proposal_callback()
> )
> }
>
> #[private] // Public - but only callable by env::current_account_id()
> pub fn external_proposal_callback(&self, #[callback_result] call_result: Result) -> Option {
> if call_result.is_err() {
> log!("There was an error contacting external contract");
> return None;
> }
>
> // Return the proposal id
> let id = call_result.unwrap();
> return Some(id);
> }
>
> }
>
> ```
> [!NOTE]
>
> By default, only **council members** can create proposals.
> [!WARNING]
>
> The attached `deposit` must match the DAO's `proposal_bond` exactly, or the
> call fails with `ERR_MIN_BOND`. The bond is set per DAO in its policy (the
> Sputnik DAO default is `0.1` NEAR, but many DAOs use a different value, e.g.
> `1` NEAR). Check the DAO's policy with `near view get_policy` and use
> that `proposal_bond` as the deposit.
***
## Vote for proposal
These snippet will enable your users to cast a vote for proposal of a particular DAO.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const DAO_CONTRACT_ADDRESS = 'primitives.sputnikv2.testnet';
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: DAO_CONTRACT_ADDRESS,
> method: 'act_proposal',
> args: { id: 0, action: 'VoteApprove' },
> gas: 300000000000000,
> });
> ```
>
> > [!NOTE]
> >
> > Available vote options: `VoteApprove`, `VoteReject`, `VoteRemove`.
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call primitives.sputnikv2.testnet act_proposal '{"id": 0, "action": "VoteApprove"}' --gas 300000000000000 --useAccount your-account.testnet
> ```
>
> > [!NOTE]
> >
> > Available vote options: `VoteApprove`, `VoteReject`, `VoteRemove`.
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/dao/vote-proposal.json)
>
> > [!NOTE]
> >
> > Available vote options: `VoteApprove`, `VoteReject`, `VoteRemove`.
> [tab] 📄 Contract
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Set of possible action to take
> #[near(serializers = [json, borsh])]
> #[derive(Debug)]
> pub enum Action {
> // Action to add proposal. Used internally.
> AddProposal,
> // Action to remove given proposal. Used for immediate deletion in special cases.
> RemoveProposal,
> // Vote to approve given proposal or bounty.
> VoteApprove,
> // Vote to reject given proposal or bounty.
> VoteReject,
> // Vote to remove given proposal or bounty (because it's spam).
> VoteRemove,
> // Finalize proposal, called when it's expired to return the funds
> // (or in the future can be used for early proposal closure).
> Finalize,
> // Move a proposal to the hub to shift into another DAO.
> MoveToHub,
> }
>
> // Validator interface, for cross-contract calls #[ext_contract(ext_dao_contract)]
> trait ExternalDaoContract {
> fn act_proposal(&mut self, id: u64, action: Action, memo: Option) -> Promise;
> }
>
> // Implement the contract structure #[near]
> impl Contract { #[payable]
> pub fn act_proposal(&mut self, id: u64, action: Action, memo: Option) -> Promise {
> let promise = ext_dao_contract::ext(self.dao_contract.clone())
> .with_attached_deposit(env::attached_deposit())
> .with_static_gas(Gas(10\*TGAS))
> .act_proposal(id, action, memo);
>
> return promise.then( // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .external_common_callback()
> )
>
> }
>
> #[private] // Public - but only callable by env::current_account_id()
> pub fn external_common_callback(&self, #[callback_result] call_result: Result<(), PromiseError>) {
> // Check if the promise succeeded
> if call_result.is_err() {
> log!("There was an error contacting external contract")
> }
> }
> }
>
> ```
***
## Additional Resources
1. [NEAR Treasury](https://neartreasury.com/) - a Treasury management web app built on top of the Sputnik DAO Contract. Allows users to create and manage treasury funds with ease.
# Decentralized Exchanges (DEX)
Source: https://docs.near.org/primitives/dex
Learn how to interact with decentralized exchanges on NEAR Protocol, including token swapping, liquidity pools, and integration with Rhea Finance DEX.
A Decentralized Exchange (DEX) is an application that allows users to trade tokens (native & fungible tokens) through smart contracts.

In brief, DEXs work by having [pools of token pairs](https://guide.rhea.finance/products/overview/pooling) (e.g. NEAR-USDC) that users can deposit tokens into.
The ratio of the tokens in the pool determines the exchange rate for a swap. Indeed, swapping is adding tokens to one side of the pool while removing tokens from the other side of the pool.
> [!NOTE]
>
> This docs refer to [Rhea Finance](https://rhea.finance/) (formerly Ref Finance), a community built DEX in NEAR.
>
> Please check their [docs](https://guide.rhea.finance/) for more information.
The WebApp examples use the local `useNearWallet` hook from the [Hello NEAR provider setup](/web3-apps/quickstart#context-provider).
***
## Query Token Exchange Rate
One can query the exchange rate of a token pair by calling the `get-token-price` method on the DEX contract.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const tokenContract = 'token.v2.ref-finance.near';
> const tokenPriceResult = await fetch(
> `https://indexer.ref.finance/get-token-price?token_id=${tokenContract}`,
> );
> const tokenPriceValue = await tokenPriceResult.json();
> ```
>
> > [accordion] Example response
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "token_contract_id": "token.v2.ref-finance.near",
> > "price": "0.08153090"
> > }
> > ```
>
> > [!TIP]
> >
> > Rhea Finance has a method to [get all token prices at once](https://indexer.ref.finance/list-token-price).
***
## Query Whitelisted Tokens
Anyone list tokens for sale in the DEX. This is why, in order to protect users, the DEX contract has a list of whitelisted tokens that can be traded.
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near view v2.ref-finance.near get_whitelisted_tokens
> ```
>
> > [accordion] Examples Response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > 'wrap.near',
> > 'usdt.tether-token.near',
> > 'berryclub.ek.near',
> > 'farm.berryclub.ek.near',
> > 'token.v2.ref-finance.near',
> > 'token.paras.near',
> > 'marmaj.tkn.near',
> > 'meta-pool.near',
> > ...
> > ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/dex/whitelist-tokens.json)
>
> > [accordion] Examples Response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > 'wrap.near',
> > 'usdt.tether-token.near',
> > 'berryclub.ek.near',
> > 'farm.berryclub.ek.near',
> > 'token.v2.ref-finance.near',
> > 'token.paras.near',
> > 'marmaj.tkn.near',
> > 'meta-pool.near',
> > ...
> > ```
***
## Register in the DEX
In order to use the contract, make sure to register your account in the DEX by paying for the storage you will use in order to keep track of your balances.
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call v2.ref-finance.near storage_deposit '' --useAccount --amount 0.1
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/dex/register-dex.json)
***
## Deposit funds
In order to swap tokens, one must first deposit tokens into the DEX. For this, you will need to transfer the FT you want to swap to the DEX contract.
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call token.v2.ref-finance.near ft_transfer_call {"receiver_id": "v2.ref-finance.near", "amount": "1000000000000", "msg": ""} --gas 300000000000000 --depositYocto 1 --useAccount
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/dex/deposit-funds.json)
> [!WARNING]
>
> Do **NOT** transfer **NEAR** tokens to Rhea Finance. Instead, call `near_deposit` in the [`wrap.near`](https://nearblocks.io/address/wrap.near) contract, attaching the amount of NEAR you want to swap.
>
> This will mint `wrap.near` for you, which you can then transfer to Rhea Finance.
***
## Get Deposit Balances
Query your deposit balances by calling the `get_deposits` method:
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const AMM_CONTRACT_ADDRESS = 'v2.ref-finance.near';
>
> const { viewFunction } = useNearWallet();
>
> await viewFunction({
> method: 'get_deposits',
> args: {
> account_id: 'bob.near',
> },
> contractId: AMM_CONTRACT_ADDRESS,
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
>
> > [accordion] Example response
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "token.v2.ref-finance.near": "0",
> > "wrap.near": "0"
> > }
> > ```
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near view v2.ref-finance.near get_deposits '{"account_id": "bob.near"}'
> ```
>
> > [accordion] Example response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > 'token.v2.ref-finance.near': '0',
> > 'wrap.near': "0"
> > }
> > ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/dex/deposit-balance.json)
>
> > [accordion] Example response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > 'token.v2.ref-finance.near': '0',
> > 'wrap.near': "0"
> > }
> > ```
> [tab] 📄 Contract
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Validator interface, for cross-contract calls
> #[ext_contract(ext_amm_contract)]
> trait ExternalAmmContract {
> fn get_deposits(&self, account_id: AccountId) -> Promise;
> }
>
> // Implement the contract structure
> #[near]
> impl Contract {
> #[private] // Public - but only callable by env::current_account_id()
> pub fn external_get_deposits_callback(&self, #[callback_result] call_result: Result, PromiseError>) -> Option> {
> // Check if the promise succeeded
> if call_result.is_err() {
> log!("There was an error contacting external contract");
> return None;
> }
>
> // Return the pools data
> let deposits_data = call_result.unwrap();
> return Some(deposits_data);
> }
>
> pub fn get_contract_deposits(&self) -> Promise {
> let promise = ext_amm_contract::ext(self.amm_contract.clone())
> .get_deposits(env::current_account_id());
>
> return promise.then( // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .external_get_deposits_callback()
> )
> }
> }
> ```
***
### Query Pools
DEXs work by having multiple pools of token pairs (e.g. NEAR-USDC) that users can deposit tokens into.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const AMM_CONTRACT_ADDRESS = 'v2.ref-finance.near';
>
> const { viewFunction } = useNearWallet();
>
> await viewFunction({
> method: 'get_pools',
> args: {
> from_index: 0,
> limit: 1000,
> },
> contractId: AMM_CONTRACT_ADDRESS,
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
>
> > [accordion] Example response
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > [
> > {
> > pool_kind: 'SIMPLE_POOL',
> > token_account_ids: ['token.skyward.near', 'wrap.near'],
> > amounts: ['51865812079751349630100', '6254162663147994789053210138'],
> > total_fee: 30,
> > shares_total_supply: '1305338644973934698612124055',
> > amp: 0,
> > },
> > {
> > pool_kind: 'SIMPLE_POOL',
> > token_account_ids: [
> > 'c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2.factory.bridge.near',
> > 'wrap.near',
> > ],
> > amounts: ['783621938569399817', '1100232280852443291118200599'],
> > total_fee: 30,
> > shares_total_supply: '33923015415693335344747628',
> > amp: 0,
> > },
> > ];
> > ```
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near view v2.ref-finance.near get_pools '{"from_index": 0, "limit": 1000}'
> ```
>
> > [accordion] Example response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > [
> > {
> > pool_kind: 'SIMPLE_POOL',
> > token_account_ids: [ 'token.skyward.near', 'wrap.near' ],
> > amounts: [ '51865812079751349630100', '6254162663147994789053210138' ],
> > total_fee: 30,
> > shares_total_supply: '1305338644973934698612124055',
> > amp: 0
> > },
> > {
> > pool_kind: 'SIMPLE_POOL',
> > token_account_ids: [
> > 'c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2.factory.bridge.near',
> > 'wrap.near'
> > ],
> > amounts: [ '783621938569399817', '1100232280852443291118200599' ],
> > total_fee: 30,
> > shares_total_supply: '33923015415693335344747628',
> > amp: 0
> > }
> > ]
> > ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/dex/query-pools.json)
>
> > [accordion] Example response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > [
> > {
> > pool_kind: 'SIMPLE_POOL',
> > token_account_ids: [ 'token.skyward.near', 'wrap.near' ],
> > amounts: [ '51865812079751349630100', '6254162663147994789053210138' ],
> > total_fee: 30,
> > shares_total_supply: '1305338644973934698612124055',
> > amp: 0
> > },
> > {
> > pool_kind: 'SIMPLE_POOL',
> > token_account_ids: [
> > 'c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2.factory.bridge.near',
> > 'wrap.near'
> > ],
> > amounts: [ '783621938569399817', '1100232280852443291118200599' ],
> > total_fee: 30,
> > shares_total_supply: '33923015415693335344747628',
> > amp: 0
> > }
> > ]
> > ```
> [tab] 📄 Contract
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> #[near(serializers = [json])]
> pub struct PoolInfo {
> /// Pool kind.
> pub pool_kind: String,
> /// List of tokens in the pool.
> pub token_account_ids: Vec,
> /// How much NEAR this contract has.
> pub amounts: Vec,
> /// Fee charged for swap.
> pub total_fee: u32,
> /// Total number of shares.
> pub shares_total_supply: U128,
> pub amp: u64,
> }
>
> // Validator interface, for cross-contract calls
> #[ext_contract(ext_amm_contract)]
> trait ExternalAmmContract {
> fn get_pools(&self, from_index: u64, limit: u64) -> Promise;
> }
>
> // Implement the contract structure
> #[near]
> impl Contract {
> #[private] // Public - but only callable by env::current_account_id()
> pub fn external_get_pools_callback(&self, #[callback_result] call_result: Result, PromiseError>) -> Option> {
> // Check if the promise succeeded
> if call_result.is_err() {
> log!("There was an error contacting external contract");
> return None;
> }
>
> // Return the pools data
> let pools_data = call_result.unwrap();
> return Some(pools_data);
> }
>
> pub fn get_amm_pools(&self, from_index: u64, limit: u64) -> Promise {
> let promise = ext_amm_contract::ext(self.amm_contract.clone())
> .get_pools(from_index, limit);
>
> return promise.then( // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .external_get_pools_callback()
> )
> }
> }
> ```
***
## Swap tokens
In order to swap a token for another, you need to [have funds](#deposit-funds), and there needs to [**exist a pool**](#query-pools) that has **both tokens** on it.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const AMM_CONTRACT_ADDRESS = 'v2.ref-finance.near';
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: AMM_CONTRACT_ADDRESS,
> method: 'swap',
> args: {
> actions: [
> {
> pool_id: 79,
> token_in: 'token.v2.ref-finance.near',
> token_out: 'wrap.near',
> amount_in: '100000000000000000',
> min_amount_out: '1',
> },
> ],
> },
> gas: 300000000000000,
> deposit: 1,
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
>
> > [accordion] Example response
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > "5019606679394603179450"
> > ```
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call v2.ref-finance.near swap "{\"actions\": [{\"pool_id\": 79, \"token_in\": \"token.v2.ref-finance.near\", \"amount_in\": \"100000000000000000\", \"token_out\": \"wrap.near\", \"min_amount_out\": \"1\"}]}" --gas 300000000000000 --depositYocto 1
> --useAccount bob.near
> ```
>
> > [accordion] Example response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > '5019606679394603179450'
> > ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/dex/swap-tokens.json)
>
> > [accordion] Example response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > '5019606679394603179450'
> > ```
> [tab] 📄 Contract
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> #[near(serializers = [json])]
> pub struct SwapAction {
> /// Pool which should be used for swapping.
> pub pool_id: u64,
> /// Token to swap from.
> pub token_in: AccountId,
> /// Amount to exchange.
> /// If amount_in is None, it will take amount_out from previous step.
> /// Will fail if amount_in is None on the first step.
> pub amount_in: Option,
> /// Token to swap into.
> pub token_out: AccountId,
> /// Required minimum amount of token_out.
> pub min_amount_out: U128,
> }
>
> // Validator interface, for cross-contract calls
> #[ext_contract(ext_amm_contract)]
> trait ExternalAmmContract {
> fn swap(&self, actions: Vec) -> Promise;
> }
>
> // Implement the contract structure
> #[near]
> impl Contract {
> #[private] // Public - but only callable by env::current_account_id()
> pub fn external_call_callback(&self, #[callback_result] call_result: Result) {
> // Check if the promise succeeded
> if call_result.is_err() {
> log!("There was an error contacting external contract");
> }
> }
>
> #[payable]
> pub fn swap_tokens(&mut self, pool_id: u64, token_in: AccountId, token_out: AccountId, amount_in: U128, min_amount_out: U128) -> Promise {
> assert_eq!(env::attached_deposit(), 1, "Requires attached deposit of exactly 1 yoctoNEAR");
>
> let swap_action = SwapAction {
> pool_id,
> token_in,
> token_out,
> amount_in: Some(amount_in),
> min_amount_out
> };
>
> let mut actions = Vec::new();
> actions.push(swap_action);
>
> let promise = ext_amm_contract::ext(self.amm_contract.clone())
> .with_static_gas(Gas(150*TGAS))
> .with_attached_deposit(YOCTO_NEAR)
> .swap(actions);
>
> return promise.then( // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .with_static_gas(Gas(100*TGAS))
> .external_call_callback()
> )
> }
> }
> ```
# Decentralized Identifiers (DIDs)
Source: https://docs.near.org/primitives/didnear
Learn about W3C-compliant identity resolution on NEAR.
This document details how to use the `did:near` method for decentralized identifiers on the NEAR blockchain, how it complies with [W3C DID Core](https://www.w3.org/TR/did-core/), and how it integrates with verifiable credentials (VCs), proof registries, and resolution tooling.
***
## What is a DID?
A **Decentralized Identifier (DID)** is a persistent, unique identifier that does not require a centralized registry. On NEAR, DIDs are created based on either account names or raw public keys, and they are fully compatible with the W3C DID standard.
> [accordion] Authors
>
> Built in collaboration with NTT DATA Innovation Center Web3
***
## The `did:near` Method
This method supports two types of DIDs with different resolution strategies:
| Type | Example | Description |
| - | - | - |
| Named Account | `did:near:alice.testnet` or `did:near:alice.near` | Resolved directly from on-chain NEAR account keys (FullAccess keys) |
| Registry DID (Base58) | `did:near:CF5RiJYh4EVmEt8UADTjoP3XaZo1NPWxv6w5TmkLqjpR` | Resolved via smart contract registry using `identity_owner` method |
***
## DID Document Format
Example output from resolving a `did:near`:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"@context": [
"https://www.w3.org/ns/did/v1",
"https://w3id.org/security/suites/ed25519-2018/v1"
],
"id": "did:near:alice.testnet",
"verificationMethod": [
{
"id": "did:near:alice.testnet#owner",
"type": "Ed25519VerificationKey2018",
"controller": "did:near:alice.testnet",
"publicKeyBase58": "7WLUHT69sw5UpYK9xAY5cbdWKf4vSMruXzwfbL999zXo"
}
],
"authentication": ["did:near:alice.testnet#owner"],
"assertionMethod": ["did:near:alice.testnet#owner"]
}
```
This structure follows the [W3C DID Core Spec](https://www.w3.org/TR/did-core/), including:
* A DID identifier (`id`)
* Key references (`verificationMethod`)
* Authentication and assertion capabilities
* Base58-encoded Ed25519 public keys
***
## ⚙️ Repositories
| Component | Repository URL |
| - | - |
| DID Registry (contract) | [https://github.com/DTI-web3/did-near](https://github.com/DTI-web3/did-near) |
| ProofType Contract | [https://github.com/DTI-web3/did-near-prooftype](https://github.com/DTI-web3/did-near-prooftype) |
| ProofType SDK | [https://www.npmjs.com/package/@kaytrust/prooftypes](https://www.npmjs.com/package/@kaytrust/prooftypes) |
| DID Resolver SDK | [https://github.com/DTI-web3/did-near-resolver](https://github.com/DTI-web3/did-near-resolver) |
***
## How Resolution Works
The resolver uses different strategies based on DID format:
### Named Account DIDs (`did:near:alice.testnet`)
1. Parse the account ID from the DID (e.g., `alice.testnet`).
2. Determine the network from the suffix (`.testnet` → testnet, `.near` → mainnet).
3. Query the NEAR RPC using `near-api-js` to fetch account access keys.
4. Filter for keys with `permission: "FullAccess"`.
5. Construct the DID document with all FullAccess public keys as verification methods.
### Registry DIDs (`did:near:CF5RiJYh4EVmEt8UADTjoP3XaZo1NPWxv6w5TmkLqjpR`)
1. Identify the DID as Base58 format (44-50 character string matching `[1-9A-HJ-NP-Za-km-z]+`).
2. Call the `identity_owner` view method on the configured registry contract.
3. Retrieve the owner DID registered for that Base58 identifier.
4. Construct the DID document with the public key from the registry.
***
## How to Use
### Create a DID
#### Named Account DID (Direct Resolution)
If using a NEAR wallet account, the DID is derived directly from the account name:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
const did = "did:near:yourname.testnet"; // For testnet
const did = "did:near:yourname.near"; // For mainnet
```
#### Registry DID (Contract-Based)
If using a Base58-encoded identifier registered in a smart contract:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
const did = "did:near:CF5RiJYh4EVmEt8UADTjoP3XaZo1NPWxv6w5TmkLqjpR";
```
#### Network-Specific DIDs
You can explicitly specify the network:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
const did = "did:near:testnet:CF5RiJYh4EVmEt8UADTjoP3XaZo1NPWxv6w5TmkLqjpR"; // Explicitly targets testnet
const did = "did:near:near:CF5RiJYh4EVmEt8UADTjoP3XaZo1NPWxv6w5TmkLqjpR"; // Explicitly targets mainnet
```
***
## Issuing and Verifying Credentials
### Step 1 – Hash the Credential
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
const cid = SHA256(JSON.stringify(credential)).toString(CryptoJS.enc.Base64);
```
### Step 2 – Issue on NEAR
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
await proofType.generateProof(credential, {
wallet,
cid
});
```
This records the hash (`cid`) on-chain with the `subject_did`.
### Step 3 – Verify On-chain
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
const isValid = await proofType.verifyProof("did:near:subject|bafy..."); // returns true or false
```
***
## SDK Usage
### Resolver SDK
#### Standalone Usage
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { NearDIDResolver } from '@kaytrust/did-near-resolver';
const resolver = new NearDIDResolver({
networks: [
{
networkId: 'testnet',
rpcUrl: 'https://rpc.testnet.near.org',
contractId: 'neardidregistry.testnet' // Optional: only for Registry DIDs
},
{
networkId: 'mainnet', // You can use 'near' for mainnet (or 'mainnet', both are equivalent)
rpcUrl: 'https://rpc.mainnet.near.org',
contractId: 'neardidregistry.near' // Optional
}
]
});
const doc = await resolver.resolveDID("did:near:alice.testnet");
console.log(doc.id); // "did:near:alice.testnet"
```
#### Integration with `did-resolver`
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { Resolver } from 'did-resolver';
import { getResolver } from '@kaytrust/did-near-resolver';
const nearResolver = getResolver({
networks: [
{
networkId: 'testnet',
rpcUrl: 'https://rpc.testnet.near.org',
contractId: 'neardidregistry.testnet'
}
]
});
const resolver = new Resolver({
...nearResolver,
// ... other DID methods
});
const result = await resolver.resolve('did:near:alice.testnet');
console.log(result.didDocument);
```
### ProofType SDK
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { ProofTypeNear } from '@kaytrust/prooftypes';
const proofType = new ProofTypeNear();
const proof = await proofType.generateProof(vcPayload, { wallet, cid });
const isValid = await proofType.verifyProof(proof);
```
***
## Security & Compliance
* Each `(did, cid)` pair can only be registered once.
* Issuer is linked to the signer account via NEAR transaction.
* DID resolution and structure is fully W3C-compliant.
* `cid` is always a Base64-encoded SHA-256 hash of the VC content.
* **Key Security**: Only `FullAccess` keys are included in the DID document's `verificationMethod` array, ensuring that only keys with complete account authority are used for authentication.
* Public keys are handled securely via NEAR native accounts or custom registries.
* **Multi-Network Support**: The resolver automatically routes requests to the correct network (mainnet/testnet) based on the DID suffix.
***
## Testnet Deployment
* Registry Contract: `neardidregistry.testnet`
* ProofType Contract: `neardtiprooftype.testnet`
* Network: `testnet`
* Language: Rust (`near-sdk`)
***
## Conclusion
The `did:near` method enables full-stack decentralized identity flows on NEAR, including:
* Account- and key-based identifiers
* W3C-compliant DID documents
* Smart contract-backed credential proofs
* SDKs for resolution and attestation
Use this stack to build portable, verifiable, and secure Web3 identity solutions on NEAR.
# Using FTs
Source: https://docs.near.org/primitives/ft/ft
Learn how to create, transfer, and integrate FT in your dApp
Wanting to use Fungible Tokens (FT) in your dApp? Here you will find all the information you need to get started creating your own tokens, registering users, querying balances, transferring tokens, and integrating them into your smart contracts.
The WebApp examples use the local `useNearWallet` hook from the [Hello NEAR provider setup](/web3-apps/quickstart#context-provider).
***
## Creating a New Token
Use the existing global FT contract to create a token. Reuse its deployed code and configure the owner, initial supply, and metadata through initialization arguments.
### Global Contracts
You can deploy a new Fungible Token using our global FT contract - a pre-deployed [standard FT contract](https://github.com/near-examples/FT) that you can reuse. [Global contracts](../../smart-contracts/global-contracts) are deployed once and can be reused by any account without incurring high storage costs.
| Network | Global FT contract |
| - | - |
| Mainnet | `ft.globals.primitives.near` |
| Testnet | `ft.globals.primitives.testnet` |
> [tab] By Account
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract deploy use-global-account-id ft.globals.primitives.testnet \
> with-init-call \
> new_default_meta \
> json-args '{"owner_id": "", "total_supply": "100000000000000000000000000000"}' \
> prepaid-gas '100.0 Tgas' \
> attached-deposit '0 NEAR' \
> network-config testnet \
> sign-with-keychain send
> ```
> [tab] By Hash
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract deploy use-global-hash 3vaopJ7aRoivvzZLngPQRBEd8VJr2zPLTxQfnRCoFgNX \
> with-init-call \
> new_default_meta \
> json-args '{"owner_id": "", "total_supply": "100000000000000000000000000000"}' \
> prepaid-gas '100.0 Tgas' \
> attached-deposit '0 NEAR' \
> network-config testnet \
> sign-with-keychain send
> ```
> [!NOTE]
>
> Deploying by **hash** creates an immutable contract that never changes. Deploying by **account ID** creates an updatable contract that changes when the referenced account's contract is updated. Choose based on whether you want your FT contract to be updatable or permanent.
***
## Creating a Token with a Factory
You can also create a Fungible Token by interacting with a factory contract, to which you provide the owner, initial supply, and token metadata. The factory will automatically deploy and initialize a [canonical FT contract](https://github.com/near-examples/FT).
| Network | Factory | Token account |
| - | - | - |
| Mainnet | `token.primitives.near` | `.token.primitives.near` |
| Testnet | `token.primitives.testnet` | `.token.primitives.testnet` |
Both factories expose `get_required` and `create_token`, and both methods take `{ args }` on either network. The token account is the symbol in lowercase, e.g. `TTTEST` becomes `tttest.token.primitives.near`, so pick a symbol that has not been taken yet.
> [accordion] Manual Interaction
>
> Creating a token takes two steps: call `get_required` to quote the storage deposit (which depends on the metadata size, including the required icon), then call `create_token` attaching that amount. `total_supply` is a string in the smallest token units: multiply the number of whole tokens by 10^decimals.
>
> > [tab] 🌐 WebApp
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > import { useNearWallet } from "@/components/near-provider";
> > import { NetworkId as network } from "@/config";
> >
> > const FACTORY = { mainnet: 'token.primitives.near', testnet: 'token.primitives.testnet' };
> >
> > const { signedAccountId: accountId, viewFunction, callFunction } = useNearWallet();
> > const contractId = FACTORY[network];
> >
> > const args = {
> > owner_id: accountId,
> > total_supply: '1000000000',
> > metadata: {
> > spec: 'ft-1.0.0',
> > name: 'Test Token',
> > symbol: 'TTTEST',
> > icon: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
> > decimals: 18,
> > },
> > };
> >
> > // 1. Quote the required deposit
> > const deposit = await viewFunction({
> > contractId,
> > method: 'get_required',
> > args: { args },
> > });
> >
> > // 2. Create the token
> > await callFunction({
> > contractId,
> > method: 'create_token',
> > args: { args },
> > gas: '300000000000000',
> > deposit,
> > });
> > ```
> >
> > Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
>
> > [tab] 🖥️ CLI
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > # Mainnet: quote, then create
> > near contract call-function as-read-only token.primitives.near get_required \
> > json-args '{"args":{"owner_id":"bob.near","total_supply":"1000000000","metadata":{"spec":"ft-1.0.0","name":"Test Token","symbol":"TTTEST","icon":"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","decimals":18}}}' \
> > network-config mainnet now
> >
> > near contract call-function as-transaction token.primitives.near create_token \
> > json-args '{"args":{"owner_id":"bob.near","total_supply":"1000000000","metadata":{"spec":"ft-1.0.0","name":"Test Token","symbol":"TTTEST","icon":"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","decimals":18}}}' \
> > prepaid-gas '300.0 Tgas' attached-deposit ' yoctoNEAR' \
> > sign-as bob.near network-config mainnet sign-with-keychain send
> > ```
>
> > [tab] Lantstool
> >
> > Try it out on
> > [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/ft/create-ft-via-factory.json)
***
## Querying Metadata
You can query the FT's metadata by calling the `ft_metadata`.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const TOKEN_CONTRACT_ADDRESS = 'token.v2.ref-finance.near';
>
> const { viewFunction } = useNearWallet();
>
> await viewFunction({
> method: 'ft_metadata',
> args: {},
> contractId: TOKEN_CONTRACT_ADDRESS,
> });
> ```
>
> > [accordion] Example response
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "spec": "ft-1.0.0",
> > "name": "Ref Finance Token",
> > "symbol": "REF",
> > "icon": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='16 24 248 248' style='background: %23000'%3E%3Cpath d='M164,164v52h52Zm-45-45,20.4,20.4,20.6-20.6V81H119Zm0,18.39V216h41V137.19l-20.6,20.6ZM166.5,81H164v33.81l26.16-26.17A40.29,40.29,0,0,0,166.5,81ZM72,153.19V216h43V133.4l-11.6-11.61Zm0-18.38,31.4-31.4L115,115V81H72ZM207,121.5h0a40.29,40.29,0,0,0-7.64-23.66L164,133.19V162h2.5A40.5,40.5,0,0,0,207,121.5Z' fill='%23fff'/%3E%3Cpath d='M189 72l27 27V72h-27z' fill='%2300c08b'/%3E%3C/svg%3E%0A",
> > "reference": null,
> > "reference_hash": null,
> > "decimals": 18
> > }
> > ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near view token.v2.ref-finance.near ft_metadata
> ```
>
> > [accordion] Example response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > spec: "ft-1.0.0",
> > name: "Ref Finance Token",
> > symbol: "REF",
> > icon: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='16 24 248 248' style='background: %23000'%3E%3Cpath d='M164,164v52h52Zm-45-45,20.4,20.4,20.6-20.6V81H119Zm0,18.39V216h41V137.19l-20.6,20.6ZM166.5,81H164v33.81l26.16-26.17A40.29,40.29,0,0,0,166.5,81ZM72,153.19V216h43V133.4l-11.6-11.61Zm0-18.38,31.4-31.4L115,115V81H72ZM207,121.5h0a40.29,40.29,0,0,0-7.64-23.66L164,133.19V162h2.5A40.5,40.5,0,0,0,207,121.5Z' fill='%23fff'/%3E%3Cpath d='M189 72l27 27V72h-27z' fill='%2300c08b'/%3E%3C/svg%3E%0A",
> > reference: null,
> > reference_hash: null,
> > decimals: 18
> > }
> > ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/ft/query-ft-metadata.json)
***
## Checking Balance
To know how many coins a user has you will need to query the method `ft_balance_of`.
> [tab] 🌐 WebApp
>
> > [!NOTE]
> >
> > Remember about fungible token precision. You may need this value to show a response of balance requests in an understandable-to-user way in your app. How to get precision value (decimals) you may find [here](#querying-metadata).
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const TOKEN_CONTRACT_ADDRESS = 'token.v2.ref-finance.near';
>
> const { viewFunction } = useNearWallet();
>
> await viewFunction({
> method: 'ft_balance_of',
> args: {
> account_id: 'bob.near',
> },
> contractId: TOKEN_CONTRACT_ADDRESS,
> });
> ```
>
> > [accordion] Example response
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > "3479615037675962643842"
> > ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near view token.v2.ref-finance.near ft_balance_of '{"account_id": "bob.near"}'
> ```
>
> > [accordion] Example response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > '376224322825327177426'
> > ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/ft/check-ft-balance.json)
***
## Registering a User
In order for a user to own and transfer tokens they need to first **register** in the contract. This is done by calling `storage_deposit` and attaching 0.00125Ⓝ.
By calling this `storage_deposit` the user can register themselves or **register other users**.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const TOKEN_CONTRACT_ADDRESS = 'token.v2.ref-finance.near';
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: TOKEN_CONTRACT_ADDRESS,
> method: 'storage_deposit',
> args: {
> account_id: 'alice.near',
> },
> deposit: 1250000000000000000000,
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call token.v2.ref-finance.near storage_deposit '{"account_id": "alice.near"}' --depositYocto 1250000000000000000000 --useAccount bob.near
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/ft/register-user.json)
> [!NOTE]
>
> You can make sure a user is registered by calling `storage_balance_of`.
> [!TIP]
>
> After a user calls the `storage_deposit` the FT will appear in their Wallets.
***
## Transferring Tokens
To send FT to another account you will use the `ft_transfer` method, indicating the receiver and the amount of FT you want to send.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const TOKEN_CONTRACT_ADDRESS = 'token.v2.ref-finance.near';
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: TOKEN_CONTRACT_ADDRESS,
> method: 'ft_transfer',
> args: {
> receiver_id: 'alice.near',
> amount: '100000000000000000',
> },
> deposit: 1,
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call token.v2.ref-finance.near ft_transfer '{"receiver_id": "alice.near", "amount": "100000000000000000"}' --depositYocto 1 --useAccount bob.near
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/ft/transfer-tokens.json)
> [tab] 📄 Contract
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> #[near]
> impl Contract {
> #[payable]
> pub fn send_tokens(&mut self, receiver_id: AccountId, amount: U128) -> Promise {
> assert_eq!(env::attached_deposit(), 1, "Requires attached deposit of exactly 1 yoctoNEAR");
>
> let promise = ext(self.ft_contract.clone())
> .with_attached_deposit(YOCTO_NEAR)
> .ft_transfer(receiver_id, amount, None);
>
> return promise.then( // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .with_static_gas(Gas(30*TGAS))
> .external_call_callback()
> )
> }
>
> #[private] // Public - but only callable by env::current_account_id()
> pub fn external_call_callback(&self, #[callback_result] call_result: Result<(), PromiseError>) {
> // Check if the promise succeeded
> if call_result.is_err() {
> log!("There was an error contacting external contract");
> }
> }
> }
> ```
>
> *This snippet assumes that the contract is already holding some FTs and that you want to send them to another account.*
***
## Attaching FTs to a Call
Natively, only NEAR tokens (Ⓝ) can be attached to a function calls. However, the FT standard enables to **attach fungible tokens** in a call by using the FT-contract as intermediary.
This means that, instead of you attaching tokens directly to the call, you ask the FT-contract to do both a transfer and a function call in your name.
Let's assume that you need to deposit FTs on [Rhea Finance](https://rhea.finance/).
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const TOKEN_CONTRACT_ADDRESS = 'token.v2.ref-finance.near';
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: TOKEN_CONTRACT_ADDRESS,
> method: 'ft_transfer_call',
> args: {
> receiver_id: 'v2.ref-finance.near',
> amount: '100000000000000000',
> msg: '',
> },
> gas: 300000000000000,
> deposit: 1,
> });
> ```
>
> > [accordion] Example response
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > "100000000000000000"
> > ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call token.v2.ref-finance.near ft_transfer_call '{"receiver_id": "v2.ref-finance.near", "amount": "100000000000000000", "msg": ""}' --gas 300000000000000 --depositYocto 1 --useAccount bob.near
> ```
>
> > [accordion] Example response
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > '100000000000000000'
> > ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/ft/attach-ft-to-call.json)
> [tab] 📄 Contract
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> #[payable]
> pub fn call_with_attached_tokens(&mut self, receiver_id: AccountId, amount: U128) -> Promise {
> assert_eq!(env::attached_deposit(), 1, "Requires attached deposit of exactly 1 yoctoNEAR");
>
> let promise = ext(self.ft_contract.clone())
> .with_static_gas(Gas(150*TGAS))
> .with_attached_deposit(YOCTO_NEAR)
> .ft_transfer_call(receiver_id, amount, None, "".to_string());
>
> return promise.then( // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .with_static_gas(Gas(100*TGAS))
> .external_call_callback()
> )
> }
> ```
How it works:
1. You call `ft_transfer_call` in the FT contract passing: the receiver, a message, and the amount.
2. The FT contract transfers the amount to the receiver.
3. The FT contract calls `receiver.ft_on_transfer(sender, msg, amount)`
4. The FT contract handles errors in the `ft_resolve_transfer` callback.
5. The FT contract returns you how much of the attached amount was actually used.
***
## Handling Deposits
If you want your contract to handle deposit in FTs you have to implement the `ft_on_transfer` method. When executed, such method will know:
* Which FT was transferred, since it is the predecessor account.
* Who is sending the FT, since it is a parameter
* How many FT were transferred, since it is a parameter
* If there are any parameters encoded as a message
The `ft_on_transfer` must return how many FT tokens have to **be refunded**, so the FT contract gives them back to the sender.
Here is an example from our [auctions tutorial](../../web3-apps/tutorials/mastering-near/3.2-ft) where we implement `ft_on_transfer` to handle bids in FTs:
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub fn ft_on_transfer(&mut self, sender_id: AccountId, amount: U128, msg: String) -> U128 {
require!(
env::block_timestamp() < self.auction_end_time.into(),
"Auction has ended"
);
let ft = env::predecessor_account_id();
require!(ft == self.ft_contract, "The token is not supported");
// Last bid
let Bid {
bidder: last_bidder,
bid: last_bid,
} = self.highest_bid.clone();
// Check if the deposit is higher than the current bid
require!(amount > last_bid, "You must place a higher bid");
// Update the highest bid
self.highest_bid = Bid {
bidder: sender_id,
bid: amount,
};
// Transfer FTs back to the last bidder
ft_contract::ext(self.ft_contract.clone())
.with_attached_deposit(NearToken::from_yoctonear(1))
.with_static_gas(Gas::from_tgas(30))
.ft_transfer(last_bidder, last_bid);
U128(0)
}
```
[See code on GitHub](https://github.com/near-examples/auctions-tutorial/blob/4678765ea7f2a584b1a6569786d497dcf75f5261/contract-rs/03-bid-with-fts/src/lib.rs#L56-L87)
*Note: The [`near_contract_standards::fungible_token::receiver`](https://docs.rs/near-contract-standards/latest/near_contract_standards/fungible_token/receiver/trait.FungibleTokenReceiver.html) module exposes a `FungibleTokenReceiver` trait that you could implement on your contract*
***
## Burn Tokens
While the FT standard does not define a `burn` method, you can simply transfer tokens to an account that no one controls, such as [`0000000000000000000000000000000000000000000000000000000000000000`](https://nearblocks.io/es/address/0000000000000000000000000000000000000000000000000000000000000000) (64 zeros).
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: 'token.v2.ref-finance.near',
> method: 'ft_transfer',
> args: {
> receiver_id: '0000000000000000000000000000000000000000000000000000000000000000',
> amount: '100000000000000000',
> },
> deposit: 1,
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call token.v2.ref-finance.near ft_transfer '{"receiver_id": "0000000000000000000000000000000000000000000000000000000000000000", "amount": "100000000000000000"}' --depositYocto 1 --useAccount bob.near
> ```
***
## Additional Application Behavior
Use the global FT contract by default. Only if your application truly requires behavior it does not provide, use [`near-contract-standards`](https://github.com/near/near-sdk-rs/tree/master/near-contract-standards) or [`near-sdk-contract-tools`](/primitives/ft/sdk-contract-tools) for the token implementation. Keep balances, transfers, storage management, and transfer resolution in these libraries; do not implement the FT standard by hand.
## Additional Resources
1. [NEP-141 standard](https://github.com/near/NEPs/tree/master/neps/nep-0141.md)
2. [NEP-148 standard](https://github.com/near/NEPs/tree/master/neps/nep-0148.md)
3. [FT Event Standards](https://github.com/near/NEPs/blob/master/neps/nep-0300.md)
4. [FT reference implementation](https://github.com/near-examples/FT)
5. [FT with Contract Tools](/primitives/ft/sdk-contract-tools) - library-provided token functionality when a global contract cannot meet the application’s needs.
# Creating a FT Contract
Source: https://docs.near.org/primitives/ft/sdk-contract-tools
Learn how to create a fungible token (FT) using Contract Tools package
In this tutorial, we will create a fungible token (FT) using the [NEAR SDK Contract Tools](https://github.com/near/near-sdk-contract-tools) package. This package is a collection of common tools and patterns to simplify smart contract development, including:
* Storage fee management
* Escrow pattern and derive macro
* Owner pattern and derive macro
* Pause pattern and derive macro
* Role-based access control
* Derive macros for [NEP standards](/primitives/ft/standard)
* NEP-141 (fungible token), extension NEP-148
* NEP-145 (storage management), and integrations for the fungible token and non-fungible token standards
* NEP-171 (non-fungible token), extensions NEP-177, NEP-178, NEP-181
* NEP-297 (events)
***
## Introduction
Use the [existing global FT contract](/primitives/ft/ft#global-contracts) by default. Use this guide only if your application truly requires behavior the global contract does not provide. Use `near-contract-standards` or `near-sdk-contract-tools` for the token implementation; do not implement the FT standard by hand.
`near-sdk-contract-tools` provides derive macros for FT standards and access control, allowing us to focus on custom logic such as minting and burning.
In this example, the contract starts with zero supply and wraps deposited NEAR into tokens. Only the current owner can mint tokens by depositing NEAR or burn tokens from their own balance to redeem NEAR. Other accounts can hold and transfer tokens using the standard FT methods.
***
## Basic FT Methods
To derive basic FT methods to our contract, we need to derive `FungibleToken` macro to our contract struct:
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[derive(Default, Owner, FungibleToken)]
#[fungible_token(transfer_hook = "TransferHook")]
#[near(contract_state)]
pub struct MyFtContract {}
```
[See code on GitHub](https://github.com/near-examples/ft-contract-tools/blob/5093d505fa56fb8c4feb62aab4bc119014881660/src/lib.rs#L9-L12)
This adds the FT interface, metadata, and storage management methods to our contract:
* `ft_balance_of`
* `ft_metadata`
* `ft_total_supply`
* `storage_balance_bounds`
* `storage_balance_of`
* `ft_resolve_transfer`
* `ft_transfer`
* `ft_transfer_call`
* `storage_deposit`
* `storage_unregister`
* `storage_withdraw`
To bring basic owner methods to our contract, we can also derive the `Owner` macro which adds the following methods:
* `own_get_owner`
* `own_get_proposed_owner`
* `own_accept_owner`
* `own_propose_owner`
* `own_renounce_owner`
***
## Initialization
To initialize the basic FT contract with a custom owner, metadata, and storage bounds, we implement the `new` method. The `owner_id` account can be different from the account where the contract is deployed. Calling `Owner::init` records that account as the current owner:
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl MyFtContract {
#[init]
pub fn new(
owner_id: AccountId,
/* total_supply: U128, */
metadata: ContractMetadata,
) -> Self {
let mut contract = Self {};
// Set metadata
contract.set_metadata(&metadata);
// Initialize owner
Owner::init(&mut contract, &owner_id);
contract.set_storage_balance_bounds(&StorageBalanceBounds {
min: NearToken::from_yoctonear(2500000000000000000000),
max: Some(NearToken::from_yoctonear(2500000000000000000000)),
});
/*
This contract wraps the deposited NEAR tokens, so it should have an initial supply of 0.
However, if you want your contract to start with an initial FT supply,
you can uncomment the following line and pass total_supply to the new method.
let _ = contract.deposit_unchecked(&owner_id, total_supply.0);
*/
contract
}
}
```
[See code on GitHub](https://github.com/near-examples/ft-contract-tools/blob/5093d505fa56fb8c4feb62aab4bc119014881660/src/lib.rs#L14-L45)
***
## Transfer Hook
Use a transfer hook to run application logic before or after the library-provided transfer. Keep the standard `ft_transfer` implementation in the library:
```rust title="transfer_hook.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub struct TransferHook;
impl Hook> for TransferHook {
fn hook(
contract: &mut MyFtContract,
transfer: &Nep141Transfer<'_>,
f: impl FnOnce(&mut MyFtContract) -> R,
) -> R {
// Log, check preconditions, save state, etc.
log!(
"NEP-141 transfer from {} to {} of {} tokens",
transfer.sender_id,
transfer.receiver_id,
transfer.amount
);
let storage_usage_before = env::storage_usage();
let r = f(contract); // execute wrapped function
let storage_usage_after = env::storage_usage();
log!(
"Storage delta: {}",
storage_usage_after - storage_usage_before
);
r
}
}
```
[See code on GitHub](https://github.com/near-examples/ft-contract-tools/blob/5093d505fa56fb8c4feb62aab4bc119014881660/src/transfer_hook.rs#L5-L33)
Then derive it to our contract struct:
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[derive(Default, Owner, FungibleToken)]
#[fungible_token(transfer_hook = "TransferHook")]
#[near(contract_state)]
pub struct MyFtContract {}
```
[See code on GitHub](https://github.com/near-examples/ft-contract-tools/blob/5093d505fa56fb8c4feb62aab4bc119014881660/src/lib.rs#L9-L12)
***
## Minting
The FT standards do not define a minting method, so we implement our own `mint` method. It takes no arguments and mints tokens for the owner based on the attached NEAR deposit.
We import the `Owner` trait and call `self.assert_owner()` before making any changes. This checks that the account calling the method is the current owner recorded by the contract:
```rust title="mint.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
use crate::{MyFtContract, MyFtContractExt};
use near_sdk::{env, near};
use near_sdk_contract_tools::{ft::*, owner::Owner};
#[near]
impl MyFtContract {
#[payable]
pub fn mint(&mut self) {
self.assert_owner();
let mut amount_to_mint = env::attached_deposit();
// Check account's storage balance and deposit if necessary
let storage_balance_bounds = self.get_storage_balance_bounds();
let storage_balance = self
.get_storage_balance(&env::predecessor_account_id())
.unwrap_or_else(|_| StorageBalance::default());
if storage_balance.total < storage_balance_bounds.min {
// Deposit storage if necessary
self.storage_deposit(Some(env::predecessor_account_id()), None);
amount_to_mint = amount_to_mint.saturating_sub(storage_balance_bounds.min);
}
// Mint tokens
Nep141Controller::mint(
self,
&Nep141Mint {
amount: amount_to_mint.as_yoctonear(),
receiver_id: env::predecessor_account_id().into(),
memo: None,
},
)
.unwrap_or_else(|e| env::panic_str(&e.to_string()));
}
}
```
[See code on GitHub](https://github.com/near-examples/ft-contract-tools/blob/5093d505fa56fb8c4feb62aab4bc119014881660/src/mint.rs#L1-L35)
If the owner is not registered to hold tokens, the method reserves the minimum storage deposit of 0.0025 NEAR from the attached deposit and mints from the remainder. To mint a positive amount on this first call, we attach more than the storage minimum. If the owner is already registered, the full attached deposit is used for minting.
Each token unit represents one yoctoNEAR. For example, an unregistered owner attaching 1 NEAR receives `997500000000000000000000` token units, while a registered owner receives `1000000000000000000000000` token units.
> [!TIP]
>
> You can add further restrictions to this method, for example, to allow minting only when the contract is not paused using [`Pausable`](https://github.com/near/near-sdk-contract-tools/tree/develop?tab=readme-ov-file#macro-combinations), or to limit the amount the owner can mint.
***
## Burning
The FT standards do not define a burning method either. We implement a `burn` method that removes `amount` token units from the owner's balance and refunds the corresponding NEAR.
As with minting, `self.assert_owner()` restricts the call to the current owner. The caller must attach [exactly 1 yoctoNEAR](/smart-contracts/security/one_yocto), and `amount` is passed as a base-10 string in the smallest token units:
```rust title="burn.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
use crate::{MyFtContract, MyFtContractExt};
use near_sdk::{NearToken, Promise, assert_one_yocto, env, json_types::U128, near};
use near_sdk_contract_tools::{
ft::{Nep141Burn, Nep141Controller},
owner::Owner,
};
#[near]
impl MyFtContract {
#[payable]
pub fn burn(&mut self, amount: U128) {
self.assert_owner();
// Assert that the attached deposit is exactly 1 yocto NEAR
assert_one_yocto();
// Burn tokens
Nep141Controller::burn(
self,
&Nep141Burn {
amount: amount.0,
owner_id: env::predecessor_account_id().into(),
memo: None,
},
)
.unwrap_or_else(|e| env::panic_str(&e.to_string()));
let amount_to_refund = NearToken::from_yoctonear(amount.0);
Promise::new(env::predecessor_account_id()).transfer(amount_to_refund);
}
}
```
[See code on GitHub](https://github.com/near-examples/ft-contract-tools/blob/5093d505fa56fb8c4feb62aab4bc119014881660/src/burn.rs#L1-L30)
Burning reduces both the owner's balance and the total supply by `amount`, then schedules a transfer of `amount` yoctoNEAR to the owner. For example, `{"amount": "1000000000000000000000000"}` burns token units representing 1 NEAR and refunds 1 NEAR. The owner must have enough tokens in their balance to burn the requested amount.
The owner checks in both methods follow ownership transfers through `own_propose_owner` and `own_accept_owner`. Once the new owner accepts, only that account can mint or burn. Token holders who are not the current owner can still transfer tokens, but cannot mint or redeem them through these methods.
***
## Testing the Contract
From the [example repository](https://github.com/near-examples/ft-contract-tools), run:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cargo install cargo-near --version 0.21.1 --locked --no-default-features
cargo test --locked -- --test-threads=2
```
The tests build the FT contract and DeFi receiver from source, then use `near-sandbox` and `near-api` to check minting, burning, ownership transfers, storage refunds, and cross-contract transfers.
***
## Conclusion
Using `near-sdk-contract-tools` is a very simple and flexible way to create FT contract with minimal boilerplate which allows us to focus on the business logic.
You can further extend this contract with more features like pausing, role-based access control, escrow pattern, and more by deriving corresponding macros from the package.
> [!TIP]
>
> **Need help?**
>
> Visit our [community channels](/communities) if you have questions or need support.
# The Standard
Source: https://docs.near.org/primitives/ft/standard
Learn how Fungible Tokens (FT) are defined on NEAR
Besides the native NEAR token, users have access to a multitude of tokens created by institutions and other users known as fungible tokens.
In contrast with the native token, fungible token (FT) are **not stored** in the user's account, but rather in a smart contract. Such contract is in charge of doing **bookkeeping**, i.e. to track how many tokens each user has, and to handle transfers internally.

In order for a contract to be considered a FT contract it has to follow the [**NEP-141**](https://github.com/near/NEPs/tree/master/neps/nep-0141.md) and [**NEP-148 standards**](https://github.com/near/NEPs/tree/master/neps/nep-0148.md)which define the **minimum interface** required to be implemented, as well as the expected functionality.
***
## NEP-141 (Fungible Token Interface)
[NEP-141](https://github.com/near/NEPs/tree/master/neps/nep-0141.md) is the blueprint for all fungible tokens (e.g. stablecoins, governance tokens, etc.) on NEAR.
It defines a **common set of rules** and **functions** that the contract MUST implement to be considered a fungible token contract.
> [!TIP]
>
> Notice that the NEP-141 defines the **interface** and **expected behavior** of a fungible token contract, but it does not dictate how the internal logic should be implemented
>
> Different FT contracts can have different internal implementations while still adhering to the NEP-141 standard
### Interface
#### `ft_total_supply` (*read-only*)
Returns the total supply of the token
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
ft_total_supply(): string
```
#### `ft_balance_of` (*read-only*)
Returns the balance of a given account
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
ft_balance_of(account_id: string): string
```
#### `ft_transfer`
Transfers `amount` of tokens from the account calling the function to a `receiver_id`, optionally the function can include a `memo` field to provide additional information to the contract
> *Requirement: The caller must attach [exactly 1 yoctoNEAR](../../smart-contracts/security/one_yocto) to the call*
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
ft_transfer(receiver_id: string, amount: string, memo: string?): void
```
#### `ft_transfer_call`
The function transfers `amount` of tokens to the `receiver_id` **and calls the method `ft_on_transfer(sender_id, amount, msg)`** on `receiver_id`.
Optionally the function can include a `memo` for the FT contract, and a `msg` field to which will be sent to the receiver contract.
> 📖 This function is useful to transfer tokens to a contract and trigger some action on the receiver side in a single transaction, thus acting as **attaching fungible tokens to a function call**.
> *Requirement: The caller must attach [exactly 1 yoctoNEAR](../../smart-contracts/security/one_yocto) to the call*
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
ft_transfer_call(receiver_id: string, amount: string, memo: string?, msg: string): void
```
> [accordion] ft\_on\_transfer
>
> Smart contracts expecting to **receive** Fungible Tokens **must** implement this method.
>
> The method **must** return the amount of tokens that were **NOT used** by the receiver, so that the **sender can be refunded**.
>
> ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
> ft_on_transfer(sender_id: string, amount: string, msg: string): string
> ```
>
> ⚠️ Note that this method does not need to be implemented by the FT contract itself, but rather by any contract that expects to receive fungible tokens
>
> See a reference implementation in the [using FTs page](./ft#handling-deposits)
#### `ft_resolve_transfer`
This method is used as a [callback](../../smart-contracts/anatomy/crosscontract#callback-function) to resolve the `ft_transfer_call` transaction, handling refunds if necessary.
```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
ft_resolve_transfer(sender_id: string, receiver_id: string, amount: string): string
```
***
## NEP-145 (Storage Management)
On NEAR, accounts need to pay for the storage they use on the network. As more users hold tokens on a fungible token contract, more information needs to be stored, and thus the contract needs to reserve more storage.
[NEP-145](https://github.com/near/NEPs/blob/master/neps/nep-0145.md) is a standard that defines a common interface for registering users, allowing FT contracts to **charge users for the storage they use**.
> [!TIP]
>
> While not mandatory, it is highly recommended for FT contracts to implement the NEP-145 standard to avoid running out of storage
### Interface
#### `storage_balance_bounds` (*read-only*)
Returns the minimum and maximum storage balance required for an account to be registered with the contract
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
storage_balance_bounds(): { min: string, max?: string} | null
```
#### `storage_balance_of` (*read-only*)
Returns the storage balance of a given account, or `null` if the account is not registered
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
storage_balance_of(account_id: string): { total: string, available: string } | null
```
#### `storage_unregister`
Removes all information from an account from the contract, returning the storage deposit to the user. The function can only be called by the user themselves.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
storage_unregister(force?: boolean): boolean
```
#### `storage_deposit`
Registers an account with the contract, reserving enough storage to keep track of the user's balance. The function can be called by the user themselves **or by a third party** on behalf of the user.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
storage_deposit(account_id?: string, registration_only?: boolean): { total: string, available: string }
```
#### `storage_withdraw`
Unregisters an account from the contract, returning the storage deposit to the user. The function can only be called by the user themselves.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
storage_withdraw(amount: string): { total: string, available: string }
```
***
## NEP-148 (Token Metadata)
[NEP-148](https://github.com/near/NEPs/tree/master/neps/nep-0141.md) is an extension to the NEP-141 standard that defines the fungible tokens **metadata**.
Metadata provides **key information** about the token, such as its **name, symbol, and decimal precision**, particularly, the following fields MUST be included in the token's metadata:
* `spec`: a string. Should be `ft-1.0.0` to indicate that a Fungible Token contract adheres to the current versions of this Metadata and the \[Fungible Token Core]\[FT Core] specs
* `name`: the human-readable name of the token
* `symbol`: the abbreviation, like wETH or AMPL
* `decimals`: used in frontends to show the proper significant digits of a token
The metadata is useful for wallets and other user interfaces to display the token correctly, for example if a token is defined as:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"spec": "ft-1.0.0",
"name": "My Awesome Token",
"symbol": "MAT",
"decimals": 4
}
```
A balance of `123456` units of such token should be displayed in a user interface as `12.3456 MAT`.
# Using Linkdrops
Source: https://docs.near.org/primitives/linkdrop/linkdrop
Learn about linkdrops following NEP-452 standard - distribute assets and onboard users to Web3 apps through simple web links using access keys and the Keypom platform.
Wanting to use Linkdrops in your dApp? Here you will find all the information you need to get started.
> [!TIP]
>
> The simplest way to create a linkdrop is by interacting with our LinkDrop Generator
The WebApp examples use the local `useNearWallet` hook from the [Hello NEAR provider setup](/web3-apps/quickstart#context-provider).
***
## AccessKeys
In order to create any kind of drop, you need to first generate key pairs. You will need to create **one key per drop**.
* The `linkdrop` contract will store the **`public`** part of the key.
* You will give the `private` part of the key to the user you want to receive the drop.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { KeyPair } from 'near-api-js';
>
> const newKeyPair = KeyPair.fromRandom('ed25519');
> newKeyPair.public_key = newKeyPair.publicKey.toString();
> ```
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near generate-key
>
> # Key pair with ed25519:33Vn9VtNEtWQPPd1f4jf5HzJ5weLcvGHU8oz7o5UnPqy public key for an account "1e5b1346bdb4fc5ccd465f6757a9082a84bcacfd396e7d80b0c726252fe8b3e8"
> ```
> [tab] Lantstool
>
> Generate a new key on [Lantstool](https://app.lantstool.dev/)
>
> 
***
## `$NEAR` Drops
To create a `$NEAR` drop you will ask the contract to create a drop (`create_drop`), passing the public part of the keys you generated, and how much you want to drop on each key use (`deposit_per_use`).
The contract will create a drop and **return the numerical ID** that identifies it.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const KEYPOM_CONTRACT_ADDRESS = "v2.keypom.near";
> const DROP_AMOUNT = "10000000000000000000000"; // 0.1 NEAR
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: KEYPOM_CONTRACT_ADDRESS,
> method: "create_drop",
> args: {
> public_keys: state.publicKeys,
> deposit_per_use: DROP_AMOUNT,
> },
> deposit: "23000000000000000000000", // state.publicKeys.length * dropAmount + 3000000000000000000000
> gas: "100000000000000",
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call v2.keypom.near create_drop '{"public_keys": , "deposit_per_use": "10000000000000000000000"}' --depositYocto 23000000000000000000000 --gas 100000000000000 --useAccount bob.near
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/linkdrop/create-near-drop.json)
> [!NOTE]
>
> To claim the drop, you will need to send the user a [link with the private key](#building-drop-links)
***
## NFT Drops
To drop an existing NFT, you will (1) create a drop, and then (2) **transfer the NFT** to keypom.
#### 1. Creating the Drop
To create an NFT drop, you will call the `create_drop` method, now passing a `nft` argument, which will tell the linkdrop contract to wait for an NFT to be transferred.
The contract will then create a drop and **return the numerical ID** that identifies it.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const KEYPOM_CONTRACT_ADDRESS = "v2.keypom.near";
> const NFT_CONTRACT_ADDRESS = "nft.primitives.near";
> const DROP_AMOUNT = "10000000000000000000000";
>
> const { callFunction, signedAccountId: accountId } = useNearWallet();
>
> await callFunction({
> contractId: KEYPOM_CONTRACT_ADDRESS,
> method: "create_drop",
> args: {
> public_keys: state.publicKeys,
> deposit_per_use: DROP_AMOUNT,
> nft: {
> // Who will be sending the NFTs to the Keypom contract
> sender_id: accountId,
> // NFT Contract Id that the tokens will come from
> contract_id: NFT_CONTRACT_ADDRESS,
> },
> },
> deposit: "23000000000000000000000", // state.publicKeys.length * dropAmount + 3000000000000000000000
> gas: "100000000000000",
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call v2.keypom.near create_drop '{"public_keys": , "deposit_per_use": "10000000000000000000000", "nft": {"sender_id": "bob.near", "contract_id": "nft.primitives.near"}}' --depositYocto 23000000000000000000000 --gas 100000000000000 --useAccount bob.near
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/linkdrop/create-nft-drop.json)
#### 2. Transferring the NFT
Having the Drop ID, you now need to transfer the NFT to the linkdrop contract, specifying to which drop you want to add it.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const KEYPOM_CONTRACT_ADDRESS = "v2.keypom.near";
> const NFT_CONTRACT_ADDRESS = "nft.primitives.near";
> const NFT_TOKEN_ID = "1";
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: NFT_CONTRACT_ADDRESS,
> method: "nft_transfer_call",
> args: {
> receiver_id: KEYPOM_CONTRACT_ADDRESS,
> token_id: NFT_TOKEN_ID,
> msg: dropId.toString()
> },
> deposit: 1,
> gas: "100000000000000",
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call nft.primitives.near nft_transfer_call '{"receiver_id": "v2.keypom.near", "token_id": , "msg": }' --depositYocto 1 --gas 100000000000000 --useAccount bob.near
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/linkdrop/transfer-nft-to-v2keypomnear.json)
> [!TIP]
>
> The `linkdrop` contract will validate that you are transferring the NFT to a drop that belongs to you
> [!TIP]
>
> The simplest way to create a linkdrop is by interacting with our LinkDrop Generator
***
## FT Drops
The process to drop a Fungible Token is very similar to that of creating an [NFT drop](#nft-drops). You will first create the drop, and then fund it with FTs.
#### 1.Creating a drop
To create a FT drop you will call the `create_drop` method, now passing a `ftData` argument, which will tell the linkdrop contract to wait for a certain amount of FT to be transferred.
The contract will then create a drop and **return the numerical ID** that identifies it.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const KEYPOM_CONTRACT_ADDRESS = "v2.keypom.near";
> const FT_CONTRACT_ADDRESS = "ft.primitives.near";
> const DROP_AMOUNT = "10000000000000000000000";
>
> const { callFunction, signedAccountId: accountId } = useNearWallet();
>
> await callFunction({
> contractId: KEYPOM_CONTRACT_ADDRESS,
> method: "create_drop",
> args: {
> public_keys: state.publicKeys,
> deposit_per_use: DROP_AMOUNT,
> ftData: {
> contractId: FT_CONTRACT_ADDRESS,
> senderId: accountId,
> // This balance per use is balance of human readable FTs per use.
> amount: "1"
> // Alternatively, you could use absoluteAmount, which is dependent on the decimals value of the FT
> // ex. if decimals of an ft = 8, then 1 FT token would be absoluteAmount = 100000000
> },
> },
> deposit: "23000000000000000000000", // state.publicKeys.length * dropAmount + 3000000000000000000000
> gas: "100000000000000",
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call v2.keypom.near create_drop '{"public_keys": , "deposit_per_use": "10000000000000000000000", "ftData": {"contractId": "ft.primitives.near","senderId": "bob.near", "amount": "1"}}}' --depositYocto 23000000000000000000000 --gas 100000000000000 --useAccount bob.near
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/linkdrop/create-ft-drop.json)
#### 2. Transferring FT
Having the Drop ID, you now need to transfer the fungible tokens to the linkdrop contract.
> [!NOTE]
>
> To transfer FTs to an account, you need to first [register](/primitives/ft/ft#registering-a-user) the receiver account (e.g. the keypom contract) on the FT contract.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const KEYPOM_CONTRACT_ADDRESS = "v2.keypom.near";
> const FT_CONTRACT_ADDRESS = "ft.primitives.near";
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: FT_CONTRACT_ADDRESS,
> method: "ft_transfer",
> args: {
> receiver_id: KEYPOM_CONTRACT_ADDRESS,
> amount: "1"
> },
> deposit: "1",
> gas: "100000000000000"
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call ft.primitives.near ft_transfer '{"receiver_id": "v2.keypom.near", "amount": "1"}' --depositYocto 1 --gas 100000000000000 --useAccount bob.near
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/linkdrop/transfer-ft-to-v2keypomnear.json)
> [!TIP]
>
> The simplest way to create a linkdrop is by interacting with our LinkDrop Generator
***
## Function Call Drop
Linkdrop contracts allow to create `function call` drops. These drops will execute one or more methods on a contract when the user claims the drop.
> [!TIP]
>
> Function call drops can be thought as the abstract version of other drops: you can create a drop that will mint an NFT, register a user in a DAO, or pay for a service.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const KEYPOM_CONTRACT_ADDRESS = "v2.keypom.near";
> const NFT_CONTRACT_ADDRESS = "nft.primitives.near";
> const NFT_TOKEN_ID = "1";
> const DROP_AMOUNT = "10000000000000000000000";
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: KEYPOM_CONTRACT_ADDRESS,
> method: "create_drop",
> args: {
> public_keys: state.publicKeys,
> deposit_per_use: DROP_AMOUNT,
> fcData: {
> // 2D array of function calls. In this case, there is 1 function call to make for a key use
> // By default, if only one array of methods is present, this array of function calls will be used for all key uses
> methods: [
> // Array of functions for Key use 1.
> [{
> receiverId: NFT_CONTRACT_ADDRESS,
> methodName: "nft_mint",
> args: JSON.stringify({
> // Change this token_id if it already exists -> check explorer transaction
> token_id: NFT_TOKEN_ID,
> metadata: {
> title: "My NFT drop",
> description: "",
> media: "",
> }
> }),
> accountIdField: "receiver_id",
> // Attached deposit for when the receiver makes this function call
> attachedDeposit: "10000000000000000000000"
> }]
> ]
> }
> },
> deposit: "23000000000000000000000", // state.publicKeys.length * dropAmount + 3000000000000000000000
> gas: "100000000000000",
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call v2.keypom.near create_drop '{"public_keys": , "deposit_per_use": "10000000000000000000000", "fcData": {"methods": [[{"receiverId": "nft.primitives.near","methodName": "nft_mint","args": {"token_id": "1", "metadata": {"title": "My NFT drop","description": "","media": ""}, "accountIdField": "receiver_id", "attachedDeposit": "10000000000000000000000"}]]}}' --depositYocto 23000000000000000000000 --gas 100000000000000 --useAccount bob.near
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/linkdrop/create-function-call-drop.json)
***
## Building drop links
To create a linkdrop link, simply append the private key to the `claim` page:
```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
http://localhost:3001/claim/linkdrop?id=ed25519:5Ly2arHZ4niWBVyEuzpN3J8QQX1BrYfWsirGqdYR3JfqUDhJ3SRK7JeQfVsh4UL8Wn6uf8RzWE4RPHymkePywVVd
```
# The Standard
Source: https://docs.near.org/primitives/linkdrop/standard
Learn how Linkdrops are defined on NEAR
Linkdrops allow users to distribute assets and onboard people to Web3 apps through a simple web link.

They work by storing assets and linking [AccessKeys](../../protocol/accounts-contracts/access-keys) to them. The `AccessKeys` are then distributed to users in the form of web links. These links take users to a website that automatically uses the keys to call the `claim` method in the `linkdrop` contract.
In order for a contract to be considered a Linkdrop-contract it has to follow the [**NEP-452 standard**](https://github.com/near/NEPs/blob/master/neps/nep-0452.md). The **NEP-452** explains the **minimum interface** required to be implemented, as well as the expected functionality.
***
## NEP-452 (Linkdrop Standard)
[NEP-452](https://github.com/near/NEPs/blob/master/neps/nep-0452.md) is the blueprint for all linkdrop contracts on NEAR. It defines a **common set of rules** and **functions** that the contract MUST implement to be considered a linkdrop contract.
> [!TIP]
>
> Notice that the NEP-452 defines the **interface** and **expected behavior** of a linkdrop contract, but it does not dictate how the internal logic should be implemented
>
> Different linkdrop contracts can have different internal implementations while still adhering to the NEP-452 standard
### Interface
#### `get_key_balance` (*read-only*)
Allows to query the amount of NEAR tokens assigned to a specific linkdrop key
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
get_key_balance(key: string): string;
```
#### `get_key_information` (*read-only*)
Returns information about a specific linkdrop key, including the amount of NEAR tokens assigned to it, the receiver ID, and whether the key has been claimed
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
interface NFTData {
contract_id: string;
token_id: string;
}
interface FTData {
contract_id: string;
amount: string;
}
get_key_information(key: string): { required_gas: string, yoctonear: string, nft_list: NFTData[], ft_list: FTData[] };
```
#### `claim`
Allows a user to claim the assets associated with a specific key. The function transfers the NEAR tokens, NFTs, and FTs assigned to the provided `account_id`, which MUST exist prior to calling this method.
> ⚠️ Users need to call this method signing the transaction with the **linkdrop key they received**.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
claim(account_id: string): boolean;
```
#### `create_account_and_claim`
Allows a user to **create a new account** and **claim the assets** associated with a specific key. The function creates the new account with the provided `new_account_id` and transfers the NEAR tokens, NFTs, and FTs assigned to it.
> ⚠️ Users need to call this method signing the transaction with the **linkdrop key they received**.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
create_account_and_claim(new_account_id: string, new_public_key: string): Promise;
```
# Deploying Your Own Contract
Source: https://docs.near.org/primitives/liquid-staking/deploy-your-own-contract
Learn how to deploy your own Liquid Staking Contract on NEAR
At its core, the Liquid Staking Contract issues a token that follows the [Fungible Token (NEP-141)](https://github.com/near/NEPs/blob/master/neps/nep-0141.md) standard.
When you stake `NEAR`, you don’t just lock it away — you receive a liquid token (for example, `rNEAR`) that behaves like any other fungible token on the network. You can transfer it, swap it, or use it inside DeFi protocols exactly the same way you would with any other token.
And, because it’s fully NEP-141 compatible, this token integrates seamlessly with wallets, DEXs, and other smart contracts. That compatibility is what enables the early-exit mechanism — you can instantly convert your liquid token back to `NEAR` by swapping it on an exchange. The swap rate is determined by market supply and demand and usually sits slightly below the on-chain rate (roughly 0.5% lower), which represents the small cost of immediate liquidity.
Behind the scenes, the exchange rate of the liquid token is continuously adjusted based on rewards earned by validators.
It’s calculated as `exchange_rate = total_staked_near / total_liquid_token_supply` and as staking rewards accumulate each epoch, the total amount of staked `NEAR` grows, while the token supply changes only when users deposit or withdraw. That’s why the exchange rate, and therefore the token’s value, steadily increases over time, even if you hold the same balance.
***
## Storage Deposit (NEP-145)
Because the liquid staking contract issues a [NEP-141 token](https://github.com/near/NEPs/blob/master/neps/nep-0141.md), it also implements the [Storage Management (NEP-145)](https://github.com/near/NEPs/blob/master/neps/nep-0145.md) standard.
Whenever you interact with the contract for the first time, for example, when you deposit `NEAR` and get liquid tokens in return, you need to attach a tiny storage deposit. This deposit covers the space your account information takes up in the contract’s storage. The good thing is that this money isn’t spent, it just stays reserved while you’re using the contract. And if you ever stop using it, you can get your deposit back by unregistering your account.
In short, it’s a way to make sure the contract doesn’t pay for users’ data out of its own balance, while still letting everyone safely recover their deposit whenever they leave.
***
## Deploying a Liquid Staking Contract
The Liquid Staking Contract can be deployed directly from the [repository](https://github.com/ref-finance/rnear-contract), which contains the implementation maintained by the Rhea.finance team. This contract follows the same principles described above and is already optimized for production use.
Before deployment, make sure the target account has at least 20.5 `NEAR` available on its balance. This amount covers the initial storage costs, the minimum staking liquidity required for initialization, and a small gas buffer.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Clone the repository
git clone https://github.com/ref-finance/rnear-contract.git
cd rnear-contract/contracts/lst
## Create and fund the liquid staking account
near create-account --useAccount --initialBalance
# Build and deploy the liquid staking contract
cargo near deploy build-non-reproducible-wasm with-init-call new json-args '{
"metadata": {
"decimals": 24,
"name": "Test Liquid Near Staking Token",
"spec": "ft-1.0.0",
"symbol": "tNEAR"
},
"owner_id": "owner.near"
}' prepaid-gas '100.0 Tgas' attached-deposit '0 NEAR'
```
### Setting Validator Whitelist Account
Before you can add validators, you first need to set the validator whitelist account. This account acts as a single source of truth for which validators are allowed to be used by the contract.
The validator whitelist account must implement the following interface that allows the contract to verify if a given validator is approved.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[ext_contract(ext_whitelist)]
pub trait ExtWhitelist {
fn is_whitelisted(&self, staking_pool_account_id: AccountId) -> bool;
}
```
To update the validator whitelist account, please run the following command:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction set_whitelist_contract_id json-args '{
"account_id": "whitelist_source.near"
}' prepaid-gas '30.0 Tgas' attached-deposit '1 yoctoNEAR'
```
### Adding Validators
After the whitelist account is in place, you can register a list of validators that the contract will delegate tokens to, along with their weights. Each weight defines a proportion of how much of the total stake should go to a particular validator compared to the others.
To add validators, please run the following comand:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction add_validators json-args '{
"validator_ids": ["validator1.pool.near", "validator2.pool.near", "validator3.pool.near"],
"weights": [40, 35, 25]
}' prepaid-gas '30.0 Tgas' attached-deposit '1 yoctoNEAR'
```
***
## Token
In this section, we’ll go through a few of the most commonly used methods. To explore all available methods, please refer to the full definition of [NEP-141](https://github.com/near/NEPs/blob/master/neps/nep-0141.md).
### Storage Deposit
Before you can hold or receive any liquid tokens, your account needs to be registered in the contract’s storage. You only need to do this once, and the amount is fully refundable if you ever unregister your account.
To register the account, run the following command:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction storage_deposit json-args '{
"account_id":"",
"registration_only": true
}' prepaid-gas '30.0 Tgas' attached-deposit '0.00125 NEAR'
```
### Check Balance
To check how many liquid tokens (e.g., `tNEAR`) you own, run the following command:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-read-only ft_balance_of json-args '{"account_id": ""}'
```
### Check Total Supply
To check the total supply of the liquid token (e.g., `tNEAR`), run the following command:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-read-only ft_total_supply json-args '{}'
```
### Transfer Tokens
To transfer tokens to another account directly, run the following command:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction ft_transfer json-args '{
"amount": "10000000000000000000000000",
"receiver_id":""
}' prepaid-gas '30.0 Tgas' attached-deposit '1 yoctoNEAR'
```
### Check Token Price
While most methods follow the NEP-141 standard, the liquid staking contract also provides an additional helper method called `ft_price`. This method isn’t part of the standard itself — it’s implemented specifically for this contract to make it easier to check the current exchange rate between the liquid token and `NEAR`, since the price of the token is determined by the formula: `exchange_rate = total_staked_near / total_liquid_token_supply`
To query the current price, run the following command:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-read-only ft_price json-args '{}'
```
The returned number shows how much `yoctoNEAR` one unit of the liquid token is currently worth.
***
## Additional Resources
For more information, explore the official resources below:
* [Liquid Staking Contract Repository](https://github.com/ref-finance/rnear-contract)
* [NEAR CLI](https://github.com/near/near-cli-rs)
# Using Liquid Staking
Source: https://docs.near.org/primitives/liquid-staking/liquid-staking
Learn about Liquid Staking on NEAR — a smart contract that issues a fungible token representing staked NEAR, enabling instant liquidity and validator diversification.
Liquid staking is a modern alternative to regular staking on NEAR that solves the problem of delayed withdrawing. In regular staking, you can't immediately withdraw funds from a staking pool - first, you need to request an unstake and then wait for 4 epochs (roughly 24-28 hours) before your funds become available for withdrawal.
And the liquid staking contract addresses this limitation by giving a flexible approach that keeps your assets liquid.
> [!TIP]
>
> Are you looking to delegate NEAR Tokens to a **liquid staking provider**? Check out the [Metapool](https://www.metapool.app/es/stake?token=near), [Rhea Finance](https://app.rhea.finance/stake)
***
## Staking Pool
The liquid staking contract implements a staking pool interface. From a developer’s perspective, interacting with a liquid staking contract feels almost identical to working with a regular staking pool.
You can call familiar methods like `deposit_and_stake`, `unstake`, and `withdraw`, and they follow the same lifecycle - the only difference is that your stake is represented by a liquid token instead of being locked inside a single pool.
Behind the scenes, the contract delegates tokens across multiple validators, usually selected from the top-performing ones on the network. These validators are actively maintained and closely monitored, which makes them far less likely to experience downtime or performance issues. And because your stake is distributed among many of them, the risk of losing rewards due to a single validator going offline becomes extremely low.
It’s also worth noting that, since your stake is spread across several validators, the average reward rate will typically be slightly lower than if you delegated directly to a single, high-performing validator. But in return, you gain better security against validator outages and the ability to exchange your liquid token back to `NEAR` at any time without waiting through the unstaking delay. It’s a balanced trade-off between maximum yield and maximum flexibility.
***
## Using Liquid Staking
Below are the most common commands you’ll use to interact with the staking flow, alongside with the contracts for major liquid staking providers on NEAR.
| Provider | Testnet Account | Mainnet Account |
| - | - | - |
| Metapool | `meta-v2.pool.testnet` | `meta-pool.near` |
| Rhea Finance | | `lst.rhealab.near` |
| Linear | `linear-protocol.testnet` | `linear-protocol.near` |
### Deposit and Stake Tokens
To stake your `NEAR` and receive the liquid token, run the command:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction deposit_and_stake json-args '{}' prepaid-gas '30.0 Tgas' attached-deposit '10 NEAR'
```
From that point, your tokens begin generating rewards through the underlying validators.
### Unstake
When you feel ready, simply request unstake with the following command. You will need to wait standard delay of 4 epochs (24-28 hours) for funds to become available for withdrawal.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction unstake_all json-args '{}' prepaid-gas '30.0 Tgas' attached-deposit '0 NEAR'
```
> [!TIP]
>
> If you need your `NEAR` immediately, you don’t have to wait 4 epochs — you can simply swap your liquid tokens for `NEAR` on DEX like Rhea.finance.
### Withdraw
As soon as 4 epochs have gone by, run the following command to withdraw `NEAR` tokens back.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction withdraw_all json-args '{}' prepaid-gas '30.0 Tgas' attached-deposit '0 NEAR'
```
At this point, your liquid tokens will be burned, and you’ll receive the equivalent amount of `NEAR` based on the current exchange rate.
# Introduction
Source: https://docs.near.org/primitives/lockup/introduction
Learn about Lockup contracts on NEAR – smart contracts that escrow tokens with time-based release schedules, supporting lockups, vesting, staking, and termination by foundation.
Lockup contracts act as escrows that hold tokens and release them gradually over time. They are widely used to manage employee compensation, investor vesting schedules, or long-term token allocations.
Lockup contracts restrict token liquidity until predefined conditions are met by combining two key mechanisms:
* **Lockup** – tokens remain locked until a certain date is reached.
* **Vesting** – tokens are made available to the user, but might be released gradually.
Through lockup and vesting, projects can enforce predictable token release schedules that align incentives and improve transparency.
***
## Lockup Schedule
A lockup defines how tokens are released linearly over time. It is described by:
* `lockup_timestamp` – when unlocking begins.
* `release_duration` – how long the unlocking lasts.\
By the end, all tokens are available.
* `finish_timestamp = lockup_timestamp + release_duration`
```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
---
config:
theme: "neutral"
xyChart:
width: 800
height: 300
showDataLabel: true
themeVariables:
xyChart:
plotColorPalette: '#000000, #FF0000'
---
xychart
title "Linear Schedule"
x-axis [before, lockup_timestamp, finish_timestamp, after]
y-axis "Tokens Unlocked (in %)" 0 --> 100
line [0, 0, 100, 100]
```
***
## Vesting Schedule
Vesting adds additional conditions, typically used for employment or investment agreements:
* `start_timestamp` – when vesting starts (e.g. hire date).
* `cliff_timestamp` – the first time tokens vest (e.g. 1 year).
* `end_timestamp` – when vesting completes.
Example:
A **4-year vesting** with a **1-year cliff** means:
* Year 1: nothing vests.
* At 1-year mark: 25% vests at once.
* Remaining 75% vests linearly for the remaining 3 years.
```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
---
config:
theme: "neutral"
xyChart:
width: 800
height: 300
showDataLabel: true
themeVariables:
xyChart:
plotColorPalette: '#000000'
---
xychart
title "Vested Schedule"
x-axis [before, start_timestamp, cliff_timestamp, cliff_timestamp, end_timestamp, after]
y-axis "Tokens Unlocked (in %)" 0 --> 100
line [0, 0, 0, 25, 100, 100]
```
***
## Combined Schedule
Lockup and vesting can be combined. Tokens become liquid only when both conditions allow:
`liquidity_timestamp = max(lockup_timestamp, cliff_timestamp)`
Depending on which event comes first, the outcome for the token release differs.
### Scenario A: Lockup before Cliff
In this case, the lockup timestamp occurs earlier than the cliff timestamp. Although the lockup schedule would normally allow tokens to start unlocking, the vesting cliff has not yet passed. As a result, no tokens are liquid until the cliff.
It introduces three key timestamps:
* `lockup_timestamp` – occurs earlier than the vesting cliff
* `cliff_timestamp` – comes later, so vesting delays liquidity
* `end_timestamp` – when vesting fully completes
```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
---
config:
theme: "neutral"
xyChart:
width: 800
height: 300
showDataLabel: true
themeVariables:
xyChart:
plotColorPalette: '#000000'
---
xychart
title "Combined Schedule: #A"
x-axis [before, lockup_timestamp, cliff_timestamp, cliff_timestamp, end_timestamp, after]
y-axis "Tokens Unlocked (in %)" 0 --> 100
line [0, 0, 0, 25, 100, 100]
```
### Scenario B: Cliff before Lockup
In this case, by the time the cliff is reached, 25% of tokens are considered vested. However, liquidity is still blocked because the lockup period has not ended.
It introduces three key timestamps:
* `cliff_timestamp` – occurs earlier than lockup
* `lockup_timestamp` – comes later and delays liquidity unlock
* `end_timestamp` – when vesting fully completes
```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
---
config:
theme: "neutral"
xyChart:
width: 800
height: 300
showDataLabel: true
themeVariables:
xyChart:
plotColorPalette: '#000000'
---
xychart
title "Combined Schedule: #B"
x-axis [before,cliff_timestamp, lockup_timestamp, lockup_timestamp, end_timestamp, after]
y-axis "Tokens Unlocked (in %)" 0 --> 100
line [0, 0, 0, 25, 100, 100]
```
***
## Termination by Foundation
When the `foundation_account_id` is specified at initialization, this account is granted the right to terminate vesting before its natural completion. The effect of termination depends on whether it happens before or after the vesting cliff.
* If termination occurs before the cliff date, none of the tokens are considered vested and the entire allocation is refunded back to the foundation.
* If termination happens after the cliff, the portion that has already vested up to that point remains with the owner, while all of the remaining unvested tokens are returned to the foundation.
This ensures that the owner never receives more than what has already vested, while giving the foundation a mechanism to reclaim the locked portion in case of early termination of the agreement.
You’ll discover real examples as you continue reading.
***
## Staking with Locked Tokens
The Lockup contract allows the owner to delegate tokens to a whitelisted staking pool, and it lets the owner to earn additional rewards while their base tokens remain locked.
The process works as follows:
* The owner selects a validator from the whitelist and stakes tokens through the lockup contract.
* The staked amount itself remains locked according to the lockup and vesting schedules.
* The validator generates staking rewards over time.
A crucial distinction is that staking rewards are liquid immediately. They are not bound by the original lockup or vesting conditions. For example, if 1000 NEAR are locked and staked for one month, and 10 NEAR are earned as rewards, when the owner decides to unstake, the original 1000 NEAR follow the normal lockup and vesting restrictions, while any rewards already earned can be transferred directly to your account.
# Lockup Contracts
Source: https://docs.near.org/primitives/lockup/lockup
Learn about Lockup contracts on NEAR – smart contracts that escrow tokens with time-based release schedules, supporting lockups, vesting, staking, and termination by foundation.
Looking to manage token vesting and lockup schedules? NEAR's Lockup contracts provide a robust solution for escrowing tokens with time-based release mechanisms.
***
## Deploying a Lockup Contract
The simplest way to deploy a new lockup contract is to use the existing [global contract](../../smart-contracts/global-contracts) already published on NEAR.
It is important to understand that the **total amount of tokens to be locked is determined by the balance of the account at the moment of deployment**.
Whatever tokens are in the account once you deploy the contract will become locked under the schedule you define.
This means that you must always **first create and fund the lockup account** with the intended amount of tokens, and only after that deploy the contract.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Create and fund the lockup account
near create-account --useAccount --initialBalance
# Deploy the lockup contract
near contract deploy use-global-hash CAvU5MYQ4xk1SjFvbnQDQUj6qehuW5YhU3FXA6GMddCx with-init-call new json-args '{
"owner_account_id": "employee.near",
"lockup_duration": "0",
"lockup_timestamp": "1535760000000000000",
"release_duration": "126230400000000000",
"transfers_information": {
"TransfersEnabled": {
"transfers_timestamp": "1602614338293769340"
}
},
"vesting_schedule": {
"VestingSchedule": {
"start_timestamp": "1535760000000000000",
"cliff_timestamp": "1567296000000000000",
"end_timestamp": "1661990400000000000"
}
},
"staking_pool_whitelist_account_id": "staking-pool-whitelist",
"foundation_account_id": "foundation.near"
}' prepaid-gas '30.0 Tgas' attached-deposit '0 NEAR'
```
> [!TIP]
>
> * To use lockup only: omit the `vesting_schedule` property.
>
> * To use vesting only: set `lockup_timestamp` and `release_duration` to 0 and provide only the `vesting_schedule`.
### Checking Balance
To see the owner’s balance, run the following command. The returned amount includes both the total amount of tokens in the contract and any staking rewards that are available for withdrawal.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-read-only get_owners_balance json-args '{}'
```
To see the liquid balance, run the following command. This will return the amount that is available for withdrawal, including unlocked tokens and staking rewards.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-read-only get_liquid_owners_balance json-args '{}'
```
### Withdraw Tokens
To transfer unlocked tokens to your account, please run the following command.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction transfer json-args '{
"amount": "10000000000000000000000000",
"receiver_id":"owner.near"
}' prepaid-gas '30.0 Tgas' attached-deposit '0 NEAR'
```
> [!WARNING]
>
> Requesting to withdraw amount that is greater than liquid won't go through
### Withdraw Tokens Once Fully Unlocked
Once all tokens are fully vested and unlocked, you can convert your lockup account into a regular NEAR account by adding a full access key. This allows you to manage the account directly and withdraw the remaining tokens by leveraging the power of advanced technique, which includes deleting it account completely and specifying your account as beneficiary.
Generate a new key pair and run the following command to add it as full access key to account, once the vesting/locking schedule is finished.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction add_full_access_key json-args '{
"new_public_key": "ed25519:8W9CiyPPehz2GRW8AYho9nx1z1GLdeZQCyn2wqYgJjiG"
}' prepaid-gas '30.0 Tgas' attached-deposit '0 NEAR'
```
> [!WARNING]
>
> Keep in mind that you never should use the key from the command above. Generate your own key pair.
Once the key is added, you’ll be able to delete it and transfer remaining funds to your account (replace `owner.near` with your address) with the following command.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near account delete-account beneficiary owner.near
```
> [!CAUTION]
>
> Make sure all staked tokens are fully withdrawn before attempting to delete the account. If any tokens remain delegated to a staking pool, they will be lost once the account is deleted.
***
## Staking
The Lockup contract allows the owner to delegate tokens to a whitelisted staking pool, and it lets the owner to earn additional rewards while their base tokens remain locked.
Let’s walk through each step slowly, in the order you will typically execute the commands.
### Select Staking Pool
Choose a validator from the whitelist configured at initialization, then set it on the lockup contract.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction select_staking_pool json-args '{
"staking_pool_account_id": "pool.testnet"
}' prepaid-gas '30.0 Tgas' attached-deposit '0 NEAR'
```
### Deposit and Stake Tokens
Stake part of tokens, available on the lockup contract. The amount must be passed over in yoctoNEAR (1 NEAR = 10^24 yoctoNEAR).
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction deposit_and_stake json-args '{
"amount": "1000000000000000000000000000"
}' prepaid-gas '125.0 Tgas' attached-deposit '0 NEAR'
```
### Refresh Staking Pool Balance
The rewards from staking pool won't be automatically reflected in the contract. This command synchronizes the contract’s internal balance with the staking pool.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction refresh_staking_pool_balance json-args '{}' prepaid-gas '30.0 Tgas' attached-deposit '0 NEAR'
```
Once that's done, notice that [liquid balance](#checking-balance) has changed.
### Unstake
When you feel ready, simply request unstake with the following command. You will need to wait standard delay of 4 epochs for funds to become withdrawable from the pool.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call unstake_all json-args '{}' prepaid-gas '125.0 Tgas' attached-deposit '0 NEAR'
```
### Withdraw
As soon as 4 epochs have gone by, run the following command to move the funds from the staking pool back to the contract, including earned rewards.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call withdraw_all_from_staking_pool json-args '{}' prepaid-gas '175.0 Tgas' attached-deposit '0 NEAR'
```
Once that's done, earned rewards become part of liquid balance and [can be withdrawn to your account immediately](#withdraw-tokens).
***
## Termination (for Foundations)
The lockup can be terminated early by a `foundation_account_id`, if it was specified during the initialization. Before the cliff, the entire allocation is refunded to the foundation. After the cliff, only the unvested portion is refunded, while the vested part remains with the owner.
During termination, some owner actions are temporarily paused until the process completes.
### Initiate
Start the termination process. After initiation, the contract may restrict owner actions until termination is finalized.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction terminate_vesting json-args '{}' prepaid-gas '25.0 Tgas' attached-deposit '0 NEAR'
```
### Check Status
The status tells you which step is safe to run next and prevents failed calls.
For example, a deficit status means there're some tokens left on the staking pool and it [requires additional actions](#resolve-deficit-if-staked) from you.
And, once the contract reports "Ready To Withdraw" status, the foundation can proceed to withdraw.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-read-only get_termination_status json-args '{}'
```
### Resolve Deficit (if staked)
If some tokens are staked and the contract shows a deficit (not enough liquid balance to refund the unvested portion), prepare the funds.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction termination_prepare_to_withdraw json-args '{}' prepaid-gas '175.0 Tgas' attached-deposit '0 NEAR'
```
> [!WARNING]
>
> You need to call it twice — once to start unstaking, and again after the 4 epoch delay to withdraw your funds.
### Withdraw Unvested
Once the status is ready, withdraw the unvested portion to the foundation account.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction termination_withdraw json-args '{
"receiver_id": "foundation.near"
}' prepaid-gas '75.0 Tgas' attached-deposit '0 NEAR'
```
***
## Additional Resources
For more information, explore the official resources below:
* [Lockup Contract Repository](https://github.com/near/core-contracts/tree/master/lockup)
* [NEAR CLI](https://github.com/near/near-cli-rs)
# Using NFTs
Source: https://docs.near.org/primitives/nft/nft
Learn about NEAR non-fungible tokens (NFT) following NEP-171 and NEP-177 standards - mint, transfer, query, and trade unique digital assets with comprehensive examples.
Wanting to use Non-Fungible Tokens (NFT) in your dApp? Here you will find all the information you need to get started creating your own tokens, registering users, transferring tokens, and integrating them into your smart contracts.
The WebApp examples use the local `useNearWallet` hook from the [Hello NEAR provider setup](/web3-apps/quickstart#context-provider).
***
## Deploying a NFT Contract
Use the existing global NFT contract. Reuse its deployed code and configure the owner and collection metadata through initialization arguments.
### Global Contract
You can deploy a new Non-Fungible Token using our global NFT contract - a pre-deployed [standard NFT contract](https://github.com/near-examples/NFT) that you can reuse. [Global contracts](../../smart-contracts/global-contracts) are deployed once and can be reused by any account without incurring high storage costs.
| Network | Global NFT contract |
| - | - |
| Mainnet | `nft.globals.primitives.near` |
| Testnet | `nft.globals.primitives.testnet` |
The following commands attach the global code to `` and initialize that account's collection with its own owner and metadata. Call `nft_mint` on `` to mint NFTs in that collection.
> [tab] By Account (Mainnet)
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract deploy use-global-account-id nft.globals.primitives.near \
> with-init-call new \
> json-args '{"owner_id": "", "metadata": {"spec": "nft-1.0.0", "name": "MY_NFT", "symbol": "NFT2000"}}' \
> prepaid-gas '100.0 Tgas' \
> attached-deposit '0 NEAR' \
> network-config mainnet \
> sign-with-keychain send
> ```
> [tab] By Account (Testnet)
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract deploy use-global-account-id nft.globals.primitives.testnet \
> with-init-call new \
> json-args '{"owner_id": "", "metadata": {"spec": "nft-1.0.0", "name": "MY_NFT", "symbol": "NFT2000"}}' \
> prepaid-gas '100.0 Tgas' \
> attached-deposit '0 NEAR' \
> network-config testnet \
> sign-with-keychain \
> send
> ```
> [tab] By Hash
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract deploy use-global-hash ivu1e9obVRnMJLSvVPRgtYefUYUS1L3f5eYHjS86zL9 \
> with-init-call new \
> json-args '{"owner_id": "", "metadata": {"spec": "nft-1.0.0", "name": "MY_NFT", "symbol": "NFT2000"}}' \
> prepaid-gas '100.0 Tgas' \
> attached-deposit '0 NEAR' \
> network-config testnet \
> sign-with-keychain \
> send
> ```
> [!NOTE]
>
> Deploying by **hash** creates an immutable contract that never changes. Deploying by **account ID** creates an updatable contract that changes when the referenced account's contract is updated. Choose based on whether you want your NFT contract to be updatable or permanent.
***
## Minting a NFT
To create a new NFT (a.k.a. minting it) you will call the `nft_mint` method passing as arguments the metadata that defines the NFT.
> [accordion] Manual Interaction
>
> You don't need to deploy your own NFT contract. NEAR has a shared NFT contract that anyone can mint on: `nft.primitives.near` on mainnet and `nft.primitives.testnet` on testnet. Here's how to call it from your application:
>
> > [tab] 🌐 WebApp
> >
> > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > import { useNearWallet } from "@/components/near-provider";
> >
> > const CONTRACT_ADDRESS = 'nft.primitives.near';
> >
> > const { callFunction } = useNearWallet();
> >
> > await callFunction({
> > contractId: CONTRACT_ADDRESS,
> > method: 'nft_mint',
> > args: {
> > token_id: '1',
> > receiver_id: 'bob.near',
> > token_metadata: {
> > title: 'NFT Primitive Token',
> > description: 'Awesome NFT Primitive Token',
> > media: 'string', // URL to associated media, preferably to decentralized, content-addressed storage
> > },
> > },
> > deposit: 10000000000000000000000,
> > });
> > ```
> >
> > Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
>
> > [tab] 🖥️ CLI
> >
> > ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > near call nft.primitives.near nft_mint '{"token_id": "1", "receiver_id": "bob.near", "token_metadata": {"title": "NFT Primitive Token", "description": "Awesome NFT Primitive Token", "media": "string"}}' --depositYocto 10000000000000000000000, --useAccount bob.near
> > ```
>
> > [tab] Lantstool
> >
> > Try it out on
> > [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/nft/mint-nft-reference.json)
>
> > [tab] 📄 Contract
> >
> > ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > // Validator interface, for cross-contract calls
> > #[ext_contract(ext_nft_contract)]
> > trait ExternalNftContract {
> > fn nft_mint(&self, token_series_id: String, receiver_id: AccountId) -> Promise;
> > }
> >
> > // Implement the contract structure
> > #[near]
> > impl Contract {
> > #[payable]
> > pub fn nft_mint(&mut self, token_series_id: String, receiver_id: AccountId) -> Promise {
> > let promise = ext_nft_contract::ext(self.nft_contract.clone())
> > .with_static_gas(Gas(30*TGAS))
> > .with_attached_deposit(env::attached_deposit())
> > .nft_mint(token_series_id, receiver_id);
> >
> > return promise.then( // Create a promise to callback query_greeting_callback
> > Self::ext(env::current_account_id())
> > .with_static_gas(Gas(30*TGAS))
> > .nft_mint_callback()
> > )
> > }
> >
> > #[private] // Public - but only callable by env::current_account_id()
> > pub fn nft_mint_callback(&self, #[callback_result] call_result: Result) -> Option {
> > // Check if the promise succeeded
> > if call_result.is_err() {
> > log!("There was an error contacting NFT contract");
> > return None;
> > }
> >
> > // Return the token data
> > let token_id: TokenId = call_result.unwrap();
> > return Some(token_id);
> > }
> > }
> > ```
>
> > [!NOTE]
> >
> > See the [metadata standard](https://github.com/near/NEPs/tree/master/neps/nep-0177.md) for the full list of `TokenMetadata` parameters.
>
> > [!WARNING]
> >
> > Values of gas and deposit might vary depending on which NFT contract you are calling.
***
### Minting Collections
Many times people want to create multiple 100 copies of an NFT (this is called a collection). In such cases, what you actually need to do is to mint 100 different NFTs with the same metadata (but different `token-id`).
***
### Royalties
You might have noticed that one of the parameters is a structure called royalties. Royalties enable you to create a list of users that should get paid when the token is sell in a marketplace. For example, if `anna` has `5%` of royalties, each time the NFT is sell, `anna` should get a 5% of the selling price.
***
## Querying NFT data
You can query the NFT's information and metadata by calling the `nft_token`.
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const CONTRACT_ADDRESS = 'nft.primitives.near';
>
> const { viewFunction } = useNearWallet();
>
> const response = await viewFunction({
> contractId: CONTRACT_ADDRESS,
> method: 'nft_token',
> args: {
> token_id: '1',
> },
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
>
> > [accordion] Example response
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "token_id": "1",
> > "owner_id": "bob.near",
> > "metadata": {
> > "title": "string", // ex. "Arch Nemesis: Mail Carrier" or "Parcel #5055"
> > "description": "string", // free-form description
> > "media": "string", // URL to associated media, preferably to decentralized, content-addressed storage
> > "media_hash": "string", // Base64-encoded sha256 hash of content referenced by the `media` field. Required if `media` is included.
> > "copies": 1, // number of copies of this set of metadata in existence when token was minted.
> > "issued_at": 1642053411068358156, // When token was issued or minted, Unix epoch in milliseconds
> > "expires_at": 1642053411168358156, // When token expires, Unix epoch in milliseconds
> > "starts_at": 1642053411068358156, // When token starts being valid, Unix epoch in milliseconds
> > "updated_at": 1642053411068358156, // When token was last updated, Unix epoch in milliseconds
> > "extra": "string", // anything extra the NFT wants to store on-chain. Can be stringified JSON.
> > "reference": "string", // URL to an off-chain JSON file with more info.
> > "reference_hash": "string" // Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included.
> > }
> > }
> > ```
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near view nft.primitives.near nft_token '{"token_id": "1"}'
> ```
>
> > [accordion] Example response
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "token_id": "1",
> > "owner_id": "bob.near",
> > "metadata": {
> > "title": "string", // ex. "Arch Nemesis: Mail Carrier" or "Parcel #5055"
> > "description": "string", // free-form description
> > "media": "string", // URL to associated media, preferably to decentralized, content-addressed storage
> > "media_hash": "string", // Base64-encoded sha256 hash of content referenced by the `media` field. Required if `media` is included.
> > "copies": 1, // number of copies of this set of metadata in existence when token was minted.
> > "issued_at": 1642053411068358156, // When token was issued or minted, Unix epoch in milliseconds
> > "expires_at": 1642053411168358156, // When token expires, Unix epoch in milliseconds
> > "starts_at": 1642053411068358156, // When token starts being valid, Unix epoch in milliseconds
> > "updated_at": 1642053411068358156, // When token was last updated, Unix epoch in milliseconds
> > "extra": "string", // anything extra the NFT wants to store on-chain. Can be stringified JSON.
> > "reference": "string", // URL to an off-chain JSON file with more info.
> > "reference_hash": "string" // Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included.
> > }
> > }
> > ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/nft/query-nft-data-reference.json)
>
> > [accordion] Example response
> >
> > ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > {
> > "token_id": "1",
> > "owner_id": "bob.near",
> > "metadata": {
> > "title": "string", // ex. "Arch Nemesis: Mail Carrier" or "Parcel #5055"
> > "description": "string", // free-form description
> > "media": "string", // URL to associated media, preferably to decentralized, content-addressed storage
> > "media_hash": "string", // Base64-encoded sha256 hash of content referenced by the `media` field. Required if `media` is included.
> > "copies": 1, // number of copies of this set of metadata in existence when token was minted.
> > "issued_at": 1642053411068358156, // When token was issued or minted, Unix epoch in milliseconds
> > "expires_at": 1642053411168358156, // When token expires, Unix epoch in milliseconds
> > "starts_at": 1642053411068358156, // When token starts being valid, Unix epoch in milliseconds
> > "updated_at": 1642053411068358156, // When token was last updated, Unix epoch in milliseconds
> > "extra": "string", // anything extra the NFT wants to store on-chain. Can be stringified JSON.
> > "reference": "string", // URL to an off-chain JSON file with more info.
> > "reference_hash": "string" // Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included.
> > }
> > }
> > ```
> [tab] 📄 Contract
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Validator interface, for cross-contract calls
> #[ext_contract(ext_nft_contract)]
> trait ExternalNftContract {
> fn nft_token(&self, token_id: TokenId) -> Promise;
> }
>
> // Implement the contract structure
> #[near]
> impl Contract {
> pub fn nft_token(&self, token_id: TokenId) -> Promise {
> let promise = ext_nft_contract::ext(self.nft_contract.clone())
> .nft_token(token_id);
>
> return promise.then( // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .nft_token_callback()
> )
> }
>
> #[private] // Public - but only callable by env::current_account_id()
> pub fn nft_token_callback(&self, #[callback_result] call_result: Result) -> Option {
> // Check if the promise succeeded
> if call_result.is_err() {
> log!("There was an error contacting NFT contract");
> return None;
> }
>
> // Return the token data
> let token_data: Token = call_result.unwrap();
> return Some(token_data);
> }
> }
> ```
***
## Transferring a NFT
Transferring an NFT can happen in two scenarios: (1) you ask to transfer an NFT, and (2) an [authorized account](#approving-users) asks to transfer the NFT.
In both cases, it is necessary to invoke the `nft_transfer` method, indicating the token id, the receiver, and an (optionally) an [approval\_id](https://github.com/near/NEPs/tree/master/neps/nep-0178.md).
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const CONTRACT_ADDRESS = 'nft.primitives.near';
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: CONTRACT_ADDRESS,
> method: 'nft_transfer',
> args: {
> token_id: '1',
> receiver_id: 'bob.near',
> },
> deposit: 1,
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call nft.primitives.near nft_transfer '{"token_id": "1", "receiver_id": "bob.near"}' --useAccount bob.near --deposit 0.000000000000000000000001
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/nft/transfer-nft-reference.json)
> [tab] 📄 Contract
>
> > [!NOTE]
> >
> > Please notice that a contract can only transfer an NFT that they own, or an NFT that they were approved to transfer.
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const YOCTO_NEAR: u128 = 1;
>
> #[ext_contract(ext_nft_contract)]
> trait ExternalNftContract {
> fn nft_transfer(&self, receiver_id: AccountId, token_id: TokenId) -> Promise;
> }
>
> impl Contract {
> #[payable]
> pub fn nft_transfer(&mut self, receiver_id: AccountId, token_id: TokenId) -> Promise {
> let promise = ext_nft_contract::ext(self.nft_contract.clone())
> .with_attached_deposit(YOCTO_NEAR)
> .nft_transfer(receiver_id, token_id);
>
> return promise.then( // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .nft_transfer_callback()
> )
> }
>
> #[private] // Public - but only callable by env::current_account_id()
> pub fn nft_transfer_callback(&self, #[callback_result] call_result: Result<(), PromiseError>) {
> // Check if the promise succeeded
> if call_result.is_err() {
> log!("There was an error contacting NFT contract");
> }
> }
> }
> ```
***
## Attaching NFTs to a Call
Natively, only NEAR tokens (Ⓝ) can be attached to a function calls. However, the NFT standard enables to attach a non-fungible tokens in a call by using the NFT-contract as intermediary. This means that, instead of you attaching tokens directly to the call, you ask the NFT-contract to do both a transfer and a function call in your name.
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call nft_transfer_call '{"receiver_id": "", "token_id": "", "msg": ""}' --useAccount --depositYocto 1
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/nft/attach-nft-to-call.json)
> [!NOTE]
>
> Optionally, a [`memo` parameter](https://github.com/near/NEPs/tree/master/neps/nep-0171.md#nft-interface) can be passed to provide more information to your contract.
***
### How Does it Work?
Assume you want to attach an NFT (🎫) to a call on the receiver contract. The workflow is as follows:
1. You call `nft_transfer_call` in the NFT-contract passing: the receiver, a message, and the token-id of 🎫.
2. The NFT contract transfers the NFT 🎫 to the receiver.
3. The NFT contract calls **`receiver.nft_on_transfer(sender, token-owner, token-id, msg)`**.
4. The NFT contract handles errors in the `nft_resolve_transfer` callback.
5. The NFT contract returns `true` if it succeeded.
#### The nft\_on\_transfer method
From the workflow above it follows that the receiver we want to call needs to implement the `nft_on_transfer` method. When executed, such method will know:
* Who is sending the NFT, since it is a parameter
* Who is the current owner, since it is a parameter
* Which NFT was transferred, since it is a parameter.
* If there are any parameters encoded as a message
The `nft_on_transfer` **must return true** if the NFT has to be **returned to the sender**.
***
## Approving Users
You can authorize other users to transfer an NFT you own. This is useful, for example, to enable listing your NFT in a marketplace. In such scenario, you **trust** that the marketplace will only transfer the NFT upon receiving a certain amount of money in exchange.
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call nft_approve '{
> "token_id": "",
> "account_id": "",
> "msg": ""
> }' --useAccount --depositYocto 1
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/nft/approve-user.json)
> [!NOTE]
>
> If the `msg` parameter is included, then a cross-contract call will be made to `.nft_on_approve(msg)`. Which in turn will make a callback to `nft_resolve_transfer` in your NFT contract.
***
## Burn Tokens
While the NFT standard does not define a `burn` method, you can simply transfer tokens to an account that no one controls, such as [`0000000000000000000000000000000000000000000000000000000000000000`](https://nearblocks.io/es/address/0000000000000000000000000000000000000000000000000000000000000000) (64 zeros).
> [tab] 🌐 WebApp
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import { useNearWallet } from "@/components/near-provider";
>
> const { callFunction } = useNearWallet();
>
> await callFunction({
> contractId: 'nft.primitives.near',
> method: 'nft_transfer',
> args: {
> token_id: '1',
> receiver_id: '0000000000000000000000000000000000000000000000000000000000000000',
> },
> deposit: 1,
> });
> ```
>
> Learn more about setting up the [NEAR provider](/web3-apps/quickstart#context-provider) in your application
> [tab] 🖥️ CLI
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call nft.primitives.near nft_transfer '{"token_id": "1", "receiver_id": "0000000000000000000000000000000000000000000000000000000000000000"}' --useAccount bob.near --deposit 0.000000000000000000000001
> ```
***
## Additional Application Behavior
Use the global NFT contract by default. Only if your application truly requires behavior it does not provide, use [`near-contract-standards`](https://github.com/near/near-sdk-rs/tree/master/near-contract-standards) or [`near-sdk-contract-tools`](/primitives/nft/sdk-contract-tools) for the NFT implementation. Keep ownership, transfers, approvals, and transfer resolution in these libraries; do not implement the NFT standard by hand.
# Creating a NFT Contract
Source: https://docs.near.org/primitives/nft/sdk-contract-tools
Learn how to create a non-fungible token (NFT) using Contract Tools package
In this tutorial, you will create a non-fungible token (NFT) using the [NEAR SDK Contract Tools](https://github.com/near/near-sdk-contract-tools) package. This package is a collection of common tools and patterns to simplify smart contract development, including:
* Storage fee management
* Escrow pattern and derive macro
* Owner pattern and derive macro
* Pause pattern and derive macro
* Role-based access control
* Derive macros for [NEP standards](./standard)
* [NEP-141](https://github.com/near/NEPs/blob/master/neps/nep-0141.md) (fungible token), extension [NEP-148](https://github.com/near/NEPs/blob/master/neps/nep-0148.md)
* [NEP-145](https://github.com/near/NEPs/blob/master/neps/nep-0145.md) (storage management), and integrations for the fungible token and non-fungible token standards
* [NEP-171](https://github.com/near/NEPs/blob/master/neps/nep-0171.md) (non-fungible token), extensions [NEP-177](https://github.com/near/NEPs/blob/master/neps/nep-0177.md), [NEP-178](https://github.com/near/NEPs/blob/master/neps/nep-0178.md), [NEP-181](https://github.com/near/NEPs/blob/master/neps/nep-0181.md)
* [NEP-297](https://github.com/near/NEPs/blob/master/neps/nep-0297.md) (events)
***
## Introduction
Use the [existing global NFT contract](/primitives/nft/nft#global-contract) by default. Use this guide only if your application truly requires behavior the global contract does not provide. Use `near-contract-standards` or `near-sdk-contract-tools` for the token implementation; do not implement the NFT standard by hand.
`near-sdk-contract-tools` allows you to implement the minting/burning logic, access control, and other NFT standards by simply deriving macros on the contract's `struct`, as `OpenZeppelin` does for Ethereum contracts.
***
## Basic NFT Methods
To derive basic NFT methods to your smart contract, you need to derive the `NonFungibleToken` macro to the contract's `struct`:
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[derive(PanicOnDefault, Owner, NonFungibleToken)]
#[non_fungible_token(transfer_hook = "TransferHook")]
#[near(contract_state)]
pub struct MyNftContract {}
```
[See code on GitHub](https://github.com/near-examples/nft-contract-tools/blob/7384b258fac5a3c8ffb7400db8bf71740c00cb70/src/lib.rs#L9-L12)
This will bring all the basic NFT methods to the contract:
* `new`
* `contract_source_metadata`
* `nft_is_approved`
* `nft_metadata`
* `nft_supply_for_owner`
* `nft_token`
* `nft_tokens`
* `nft_tokens_for_owner`
* `nft_total_supply`
* `nft_approve`
* `nft_resolve_transfer`
* `nft_revoke`
* `nft_revoke_all`
* `nft_transfer`
* `nft_transfer_call`
* `storage_balance_bounds`
* `storage_balance_of`
* `storage_deposit`
* `storage_unregister`
* `storage_withdraw`
To bring basic owner methods to the contract, you also need to derive the `Owner` macro, which adds the following methods:
* `own_get_owner`
* `own_get_proposed_owner`
* `own_accept_owner`
* `own_propose_owner`
* `own_renounce_owner`
***
## Initialization
To initialize the basic NFT contract with a custom owner, metadata, and storage bounds, implement the `new` method:
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl MyNftContract {
#[init]
pub fn new(owner_id: AccountId, metadata: ContractMetadata) -> Self {
let mut contract = Self {};
Owner::init(&mut contract, &owner_id);
contract.set_contract_metadata(&metadata);
contract.set_storage_balance_bounds(&StorageBalanceBounds {
min: NearToken::from_yoctonear(7000000000000000000000),
max: Some(NearToken::from_yoctonear(21000000000000000000000)),
});
contract
}
}
```
[See code on GitHub](https://github.com/near-examples/nft-contract-tools/blob/7384b258fac5a3c8ffb7400db8bf71740c00cb70/src/lib.rs#L14-L31)
***
## Transfer Hook
Use a transfer hook to run application logic before or after the library-provided transfer. Keep the standard `nft_transfer` implementation in the library:
```rust title="transfer_hook.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub struct TransferHook;
impl Hook> for TransferHook {
fn hook(
contract: &mut MyNftContract,
transfer: &Nep171Transfer<'_>,
f: impl FnOnce(&mut MyNftContract) -> R,
) -> R {
// Log, check preconditions, save state, etc.
log!(
"NEP-171 transfer from {} to {} of {} tokens",
transfer.sender_id,
transfer.receiver_id,
transfer.token_id
);
let storage_usage_before = env::storage_usage();
let r = f(contract); // execute wrapped function
let storage_usage_after = env::storage_usage();
log!(
"Storage delta: {}",
storage_usage_after - storage_usage_before
);
r
}
}
```
[See code on GitHub](https://github.com/near-examples/nft-contract-tools/blob/7384b258fac5a3c8ffb7400db8bf71740c00cb70/src/transfer_hook.rs#L5-L33)
Then derive it to our contract struct:
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[derive(PanicOnDefault, Owner, NonFungibleToken)]
#[non_fungible_token(transfer_hook = "TransferHook")]
#[near(contract_state)]
pub struct MyNftContract {}
```
[See code on GitHub](https://github.com/near-examples/nft-contract-tools/blob/7384b258fac5a3c8ffb7400db8bf71740c00cb70/src/lib.rs#L9-L12)
***
## Minting
By default, the NFT standards do not include a minting method. However, you can easily mint tokens for the owner by implementing an `nft_mint` method:
```rust title="mint.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[payable]
pub fn nft_mint(
&mut self,
token_id: TokenId,
metadata: TokenMetadata,
owner_id: Option,
) {
// Check account's storage balance and deposit if necessary
let storage_balance_bounds = self.storage_balance_bounds();
log!("Storage balance bounds: {:?}", storage_balance_bounds);
let storage_balance = self
.storage_balance_of(owner_id.clone().unwrap_or(env::predecessor_account_id()))
.unwrap_or_default();
log!("Storage balance: {:?}", storage_balance);
if storage_balance.total < storage_balance_bounds.min {
// Deposit storage if necessary
self.storage_deposit(
Some(owner_id.clone().unwrap_or(env::predecessor_account_id())),
None,
);
}
Nep177Controller::mint_with_metadata(
self,
&token_id,
&owner_id.unwrap_or(env::predecessor_account_id()),
&metadata,
)
.unwrap_or_else(|e| env::panic_str(&e.to_string()));
}
```
[See code on GitHub](https://github.com/near-examples/nft-contract-tools/blob/7384b258fac5a3c8ffb7400db8bf71740c00cb70/src/mint.rs#L10-L40)
> [!TIP]
>
> You can modify this method as you need, for example, to allow minting only when the contract is not paused (requires deriving [`Pausable`](https://github.com/near/near-sdk-contract-tools/tree/develop?tab=readme-ov-file#macro-combinations) hook), or to enable minting only to specific accounts with a certain role or from a whitelist with custom limitations.
***
## Burning
In the same way that minting is not included in the NFT standards, burning is also not included. However, you can also easily implement it.
To allow users to burn their tokens, you can add a `burn` method:
```rust title="burn.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl MyNftContract {
#[payable]
pub fn nft_burn(&mut self, token_id: TokenId) {
assert_one_yocto();
Nep177Controller::burn_with_metadata(self, &token_id, &env::predecessor_account_id())
.unwrap_or_else(|e| env::panic_str(&e.to_string()));
}
}
```
[See code on GitHub](https://github.com/near-examples/nft-contract-tools/blob/7384b258fac5a3c8ffb7400db8bf71740c00cb70/src/burn.rs#L5-L14)
***
## Conclusion
Using `near-sdk-contract-tools` is a simple and flexible way to create an NFT contract with minimal boilerplate, which allows you to focus on the business logic.
You can further extend this contract with more features like pausing, role-based access control, escrow pattern, and more by deriving corresponding macros from the package.
# The Standard
Source: https://docs.near.org/primitives/nft/standard
Learn how Non-Fungible Tokens (NFT) are defined on NEAR
In contrast with fungible tokens, non-fungible tokens (NFT) are unitary and therefore unique. This makes NFTs ideal to represent ownership of assets such as a piece of digital content, or a ticket for an event.
As with fungible tokens, NFTs are **not stored** in the user's wallet, instead, each NFT lives in a **NFT contract**. The NFT contract works as a bookkeeper, being in charge of creating, storing and transferring NFTs.
> [!NOTE]
>
> **NFT & Marketplaces**
>
> Be mindful of not confusing an NFT with an NFT-marketplace. NFT simply store information (metadata), while NFT-marketplaces are contracts where NFT can be listed and exchanged for a price.
***
## NEP-171 (NFT Interface)
[NEP-171](https://github.com/near/NEPs/tree/master/neps/nep-0171.md) is the blueprint for all non-fungible tokens on NEAR. It defines a **common set of rules** and **functions** that the contract MUST implement to be considered a non-fungible token contract.
> [!TIP]
>
> Notice that the NEP-171 defines the **interface** and **expected behavior** of a non-fungible token contract, but it does not dictate how the internal logic should be implemented
>
> Different NFT contracts can have different internal implementations while still adhering to the NEP-171 standard
### Interface
#### `nft_token` (*read-only*)
Returns the token information for a given `token_id`
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
nft_token(token_id: string): { token_id: string, owner_id: string } | null
```
#### `nft_transfer`
Transfers the `token_id` from the caller to the `receiver_id`, optionally the function can include a `memo` field to provide additional information to the contract
The caller must be the **either** the current owner of the token or an **account** that has been **approved to transfer** the token on behalf of the owner, such as a marketplace contract. The approval mechanism is defined in the [NEP-178 standard](https://github.com/near/NEPs/blob/master/neps/nep-0178.md).
> *Requirement: The caller must attach [exactly 1 yoctoNEAR](../../smart-contracts/security/one_yocto) to the call*
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
nft_transfer(receiver_id: string, token_id: string, approval_id?: number, memo: string?): void
```
#### `nft_transfer_call`
The function transfers the `token_id` to the `receiver_id` **and calls the method `nft_on_transfer(sender_id, previous_owner_id, token_id, msg)`** on `receiver_id`.
Optionally the function can include a `memo` for the NFT contract, and a `msg` field to which will be sent to the receiver contract.
> 📖 This function is useful to transfer NFTs to a contract and trigger some action on the receiver side in a single transaction, thus acting as **attaching NFTs to a function call**
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
nft_transfer_call(receiver_id: string, token_id: string, approval_id?: number, memo?: string, msg: string): Promise {}
```
> [accordion] nft\_on\_transfer
>
> Smart contracts expecting to **receive** Non-Fungible Tokens **must** implement this method.
>
> The method **must** return a boolean value indicating whether the token should be returned to the sender (`true`) or not (`false`).
>
> ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
> nft_on_transfer(sender_id: string, previous_owner_id: string, token_id: string, msg: string): boolean
> ```
>
> ⚠️ Note that this method does not need to be implemented by the NFT contract itself, but rather by any contract that expects to receive non-fungible tokens
#### `nft_resolve_transfer`
This method is used as a [callback](../../smart-contracts/anatomy/crosscontract#callback-function) to resolve the `nft_transfer_call` transaction, handling refunds if necessary.
It must return `true` if the token was successfully transferred to `receiver_id`, or `false` if the token was returned to `owner_id`.
```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
nft_resolve_transfer(owner_id: string, receiver_id: string, token_id: string, approved_account_ids?: Record): boolean
```
***
## NEP-177 (NFT Metadata)
[NEP-177](https://github.com/near/NEPs/blob/master/neps/nep-0177.md) is an extension to the NEP-171 standard that defines the **metadata** for both non-fungible tokens and non-fungible token contracts.
Metadata provides **key information** , such as the contract's **name** or the NFT's **title**. Particularly, the following fields MUST be included in the smart contract and token's metadata:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
type NFTContractMetadata = {
spec: string, // required, essentially a version like "nft-1.0.0"
name: string, // required, ex. "Mochi Rising — Digital Edition" or "Metaverse 3"
symbol: string, // required, ex. "MOCHI"
icon: string|null, // Data URL
base_uri: string|null, // Centralized gateway known to have reliable access to decentralized storage assets referenced by `reference` or `media` URLs
reference: string|null, // URL to a JSON file with more info
reference_hash: string|null, // Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included.
}
type TokenMetadata = {
title: string|null, // ex. "Arch Nemesis: Mail Carrier" or "Parcel #5055"
description: string|null, // free-form description
media: string|null, // URL to associated media, preferably to decentralized, content-addressed storage
media_hash: string|null, // Base64-encoded sha256 hash of content referenced by the `media` field. Required if `media` is included.
copies: number|null, // number of copies of this set of metadata in existence when token was minted.
issued_at: number|null, // When token was issued or minted, Unix epoch in milliseconds
expires_at: number|null, // When token expires, Unix epoch in milliseconds
starts_at: number|null, // When token starts being valid, Unix epoch in milliseconds
updated_at: number|null, // When token was last updated, Unix epoch in milliseconds
extra: string|null, // anything extra the NFT wants to store on-chain. Can be stringified JSON.
reference: string|null, // URL to an off-chain JSON file with more info.
reference_hash: string|null // Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included.
}
```
***
## NEP-178 (NFT Approval Management)
[NEP-178](https://github.com/near/NEPs/blob/master/neps/nep-0178.md) is an extension to the NEP-171 standard that defines the **approval management** for non-fungible tokens.
The approval mechanism allows the owner of an NFT to authorize another account (for example, a marketplace contract) to transfer the token on their behalf.
### Interface
#### `nft_is_approved` (*read-only*)
Returns whether an `approved_account_id` is actually approved to transfer the `token_id` on behalf of the token owner. If `approval_id` is provided, it will also check that the approval ID matches.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
nft_is_approved(token_id: string, approved_account_id: string, approval_id?: number): boolean
```
#### `nft_approve`
Grants approval to `account_id` to transfer the `token_id` on behalf of the token owner. Optionally, the function can include a `msg` field to provide additional information to the contract.
> *Requirement: The caller must attach a deposit of at least `1 yoctoNEAR` plus the storage cost for adding the new approval*
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
nft_approve(token_id: string, account_id: string, msg?: string): void
```
#### `nft_revoke`
Revokes approval for `account_id` to transfer the `token_id` on behalf of the token owner.
> *Requirement: The caller must attach [exactly 1 yoctoNEAR](../../smart-contracts/security/one_yocto) to the call*
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
nft_revoke(token_id: string, account_id: string): void
```
#### `nft_revoke_all`
Revokes all approvals for the `token_id`.
> *Requirement: The caller must attach [exactly 1 yoctoNEAR](../../smart-contracts/security/one_yocto) to the call*
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
nft_revoke_all(token_id: string): void
```
# OutLayer
Source: https://docs.near.org/primitives/off-chain-compute/outlayer
OutLayer is a verifiable off-chain compute platform for NEAR. Run Rust/WASM code inside Intel TDX enclaves with built-in VRF, secrets, MPC vaults, and payment keys.
[OutLayer](https://outlayer.fastnear.com) is a verifiable off-chain compute platform for NEAR, built by [FastNEAR](https://fastnear.com). Smart contracts delegate work to **Intel TDX** enclaves that return results with a cryptographic attestation proving the exact code ran on the exact inputs.
* **Website:** [outlayer.fastnear.com](https://outlayer.fastnear.com)
* **Source:** [github.com/fastnear/near-outlayer](https://github.com/fastnear/near-outlayer)
***
## How it works
1. You write code in **Rust** and compile it to **WebAssembly** (WASI Preview 1 or 2).
2. The binary is hosted on GitHub. OutLayer clones, compiles, and caches it.
3. A NEAR contract calls OutLayer using NEAR's `yield`/`resume` flow — or any client can call the HTTPS API directly.
4. The worker runs the WASM inside a **TDX enclave** and returns the result with a TEE attestation (code hash, input hash, output, signed by the hardware).
***
## Features
| Feature | Description |
| - | - |
| **WASI runtime** | Run any Rust code compiled to `wasm32-wasi`. |
| **TEE attestation** | Cryptographic proof of code + input + output, signed by Intel TDX. |
| **VRF** | Verifiable randomness with Ed25519 signatures. |
| **Secrets** | Encrypted API keys and credentials, decrypted only inside the enclave. |
| **Confidential Key Derivation** | Keys that exist only inside your TEE code and persist across upgrades. |
| **MPC Vaults** | Multi-party computation for shared key custody. |
| **Payment Keys** | USDC-based metering for monetized HTTPS endpoints. |
| **Persistent storage** | Encrypted storage between executions. |
***
## Example use cases
The [examples gallery](https://outlayer.fastnear.com/docs/examples) ships 14+ production-ready demos. A few highlights:
* **Price & weather oracles** — fetch off-chain data with a proof of source.
* **Coin-flip / lottery** — VRF-based randomness for fair on-chain games.
* **AI calls** — invoke OpenAI/GPT from a contract with verifiable output.
* **Cross-chain reads** — query Ethereum state without a bridge.
* **Private DAO voting** — tally votes inside the enclave; only the result is published.
* **NEAR Intents swaps** — execute Intent flows from off-chain logic.
* **Encrypted email & CAPTCHA** — end-to-end use cases requiring secrets.
> [!TIP]
>
> Start with the [Getting Started guide](https://outlayer.fastnear.com/docs/getting-started) and the [Dev Guide](https://outlayer.fastnear.com/docs/dev-guide) to set up your first WASM module and call it from a NEAR contract.
***
## Deployed services built on OutLayer
| Name | Description | Reference |
| - | - | - |
| **Price Oracle** | TEE-secured, Pyth-compatible price feed on `price-oracle.near`. | See [Oracles](/primitives/oracles#price-oracle-by-outlayer) |
> [!NOTE]
>
> OutLayer is a third-party platform. As with any external service, evaluate its operational guarantees, attestation verification flow, and key custody model before relying on it for production assets.
# Off-chain Compute
Source: https://docs.near.org/primitives/off-chain-compute/what-is
Learn how NEAR smart contracts can delegate heavy or impossible-on-chain work to verifiable off-chain computation running inside Trusted Execution Environments (TEEs).
Smart contracts run inside a deterministic VM and pay gas for every instruction. That makes some workloads impractical (heavy cryptography, ML inference) and others outright impossible (HTTP requests, accessing API keys, generating true randomness).
**Off-chain compute** moves these workloads outside the chain while keeping cryptographic proof that the right code ran on the right inputs. On NEAR, this is typically achieved with **Trusted Execution Environments (TEEs)** — secure enclaves (e.g. Intel TDX) that produce signed attestations of execution.
> [!NOTE]
>
> A TEE attestation proves three things: the **code** that ran (hash of the binary), the **inputs** it received, and the **output** it produced — all signed by hardware the operator cannot tamper with.
***
## What it unlocks
* **HTTP requests** — fetch from any Web2 API directly from contract logic.
* **Secrets management** — encrypted API keys and private keys, only decrypted inside the enclave.
* **Verifiable randomness (VRF)** — provably-fair random numbers signed with Ed25519.
* **AI integration** — call LLMs and ML models with a proof the result is genuine.
* **Cross-chain reads** — query Ethereum or other chains without a bridge contract.
* **Heavy cryptography** — zero-knowledge proofs, MPC, custom signature schemes.
***
## How it integrates with NEAR
A contract calls into the off-chain layer using NEAR's **`yield`/`resume`** mechanism: the contract pauses, the off-chain worker executes the code in a TEE, then resolves the promise with the result and its attestation — all within a single logical transaction.
For workloads that don't need a contract at all, the same compute can also be triggered via direct HTTPS, which is useful for Web2 backends or frontends.
***
## Platforms
> [card] [OutLayer](/primitives/off-chain-compute/outlayer)
>
> A verifiable off-chain compute platform for NEAR by FastNEAR. Code runs in Intel TDX enclaves with built-in support for VRF, secrets, MPC vaults, and payment keys.
# Oracles
Source: https://docs.near.org/primitives/oracles
Learn about blockchain oracles on NEAR Protocol, including price feeds, data integration, and using oracle services like Outlayer Price Oracle and Pyth Network.
[Blockchain Oracles](https://en.wikipedia.org/wiki/Blockchain_oracle) serve as intermediaries that connect smart contracts with external (off-chain) data.
`Example:`
* **Price Feeds:** Real-time pricing for cryptocurrencies, stocks, or commodities.
* **Event Information:** Updates on real-world events like sports results or weather conditions.
* **API Access:** Connections to external web services and systems.
> [!NOTE]
>
> Oracles, being external third-party services, require careful consideration of their reliability, security, and decentralization to avoid risks such as incorrect data, manipulation, or single points of failure.
***
## Deployed Oracles on NEAR
Here is a directory of third-party oracle services deployed on the NEAR blockchain:
| Name | Creator | Description |
| - | - | - |
| [Outlayer Price Oracle](#price-oracle-by-outlayer) | [Outlayer](https://github.com/zavodil/oracle-ark) | TEE-Secured Price Oracle based on Outlayer |
| [Pyth Network Oracle](#pyth-network-oracle) | [Pyth Network](https://pyth.network/) | High-frequency, low-latency oracle for price feeds |
| **[\[Your Project Here\]](https://github.com/near/docs/edit/master/primitives/oracles.mdx)** | - | - |
***
## Price Oracle by Outlayer
* **Creator:** [Outlayer](https://github.com/fastnear/near-outlayer)
* **Official Documentation:** [Price Oracle Outlayer](https://price-oracle.outlayer.ai/docs/)
* **Codebase Repository:** [zavodil/oracle-ark](https://github.com/zavodil/oracle-ark)
* **Deployed Addresses:**
* **Mainnet:** [price-oracle.near](https://nearblocks.io/address/price-oracle.near)
* **Testnet:** [price-oracle.testnet](https://testnet.nearblocks.io/address/price-oracle.testnet)
### How to use / integrate
The `price-oracle.near` implements Pyth-compatible view methods natively (see [Pyth Network Oracle](#pyth-network-oracle) below). DeFi contracts using `pyth-oracle.near` can migrate by changing one contract address — no code changes needed.
> [!TIP]
>
> This price oracle is one of several services built on OutLayer, a general-purpose verifiable off-chain compute platform. See [OutLayer](/primitives/off-chain-compute/outlayer) for VRF, AI calls, cross-chain reads, and other off-chain primitives.
***
## Pyth Network Oracle
* **Creator:** [Pyth Network](https://pyth.network)
* **Official Documentation:** [Pyth NEAR Docs](https://docs.pyth.network/price-feeds/use-real-time-data/near)
* **Codebase Repository:** [pyth-network/pyth-crosschain](https://github.com/pyth-network/pyth-crosschain/tree/main/target_chains/near)
* **Deployed Addresses:**
* **Mainnet:** [pyth-oracle.near](https://nearblocks.io/address/pyth-oracle.near)
* **Testnet:** [pyth-oracle.testnet](https://testnet.nearblocks.io/address/pyth-oracle.testnet)
***
## Using Pyth Network Oracle
> Pyth Network's NEAR smart contract has two core methods to update & get price feeds of your choice.
1. [`update_price_feeds`](#update_price_feeds)
*(updates Pyth smart contract with the price feed you provide)*
* args: `data`
* type: `object`
* example: `{ "data": "504e41...' }`
2. [`get_price`](#get_price) (fetches the most recent price stored in the contract)\_
* args: `price_identifier`
* type: `object`
* example: `{ price_identifier: 'f9c0172ba10dfa8...' }`
> [!NOTE]
>
> For a complete list of endpoints to interact with, see [Pyth's `receiver` contract](https://github.com/pyth-network/pyth-crosschain/blob/main/target_chains/near/receiver/src/ext.rs).
### Getting Started
To get started with Pyth oracle you will need to gather the following information which differ between networks:
* Price ID(s)
* HermesAPI Endpoint
* Smart contract address
| Network | Price Feed IDs | Hermes API Address | Contract Address |
| - | - | - | - |
| `testnet` | [NEAR `testnet` Price Feed IDs](https://www.pyth.network/developers/price-feed-ids#near-testnet) | `hermes-beta.pyth.network` | [pyth-oracle.testnet](https://testnet.nearblocks.io/address/pyth-oracle.testnet) |
| `mainnet` | [NEAR `mainnet` Price Feed IDs](https://www.pyth.network/developers/price-feed-ids#near-mainnet) | `hermes.pyth.network` | [pyth-oracle.near](https://nearblocks.io/address/pyth-oracle.near) |
> [!NOTE]
>
> When using Price Feed IDs, you will need to remove the `0x` prefix.
>
> `Price Feed ID Example (testnet):`
>
> ```typescript title="pyth-oracle-update.js" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> 'f9c0172ba10dfa4d19088d94f5bf61d3b54d5bd7483a322a982e1373ee8ea31b', // BTC/USD price id
> 'ca80ba6dc32e08d06f1aa886011eed1d77c77be9eb761cc10d72b7d0a2fd57a6', // ETH/USD price id
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-js/blob/bc1f91419a3c8f1f6ca694f53bb14c57d4ce3c46/node-js/oracle-example/pyth-oracle-update.js#L14-L15)
***
### `update_price_feeds`
> Updates the Pyth Oracle contract data with the price feed you provide.
* args: `data` *(off-chain hex-encoded price feed)*
* type: `object`
* example: `{ "data": "504e41...' }`
Update the Pyth Oracle contract with new price feed data in two main steps:
1. [Fetch off-chain price feed](#1-fetching-off-chain-price-feed)
2. [Update Pyth Oracle contract with off-chain price feed](#2-update-pyth-oracle-contract-price-feed)
#### 1) Fetching off-chain price feed
You can obtain an off-chain price feed using Pyth's [Hermes API](https://docs.pyth.network/api-reference/hermes/latest-price-updates).
To use these endpoints, you will need to provide a Price Feed ID and ensure you are targeting the correct network. See [Getting Started](#getting-started) for more information.
Here is a node.js example of fetching the latest price feed using `/v2/updates/price/latest` endpoint:
```javascript title="fetch-hermes-price-data.js" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
const axios = require('axios');
// There are separate endpoints for testnet and mainnet
const HERMES_TESTNET_URL = 'https://hermes-beta.pyth.network';
const HERMES_MAINNET_URL = 'https://hermes.pyth.network';
async function getHermesPriceData(priceId, network) {
try {
let url;
network === 'testnet'
? (url = HERMES_TESTNET_URL)
: (url = HERMES_MAINNET_URL);
// Fetch the price data from the Hermes API
const response = await axios.get(`${url}/v2/updates/price/latest?ids[]=${priceId}`);
return response.data.binary.data[0];
} catch (error) {
console.error('Error:', error.response ? error.response.data : error.message);
}
}
module.exports = { getHermesPriceData };
```
[See code on GitHub](https://github.com/near-examples/near-js/blob/bc1f91419a3c8f1f6ca694f53bb14c57d4ce3c46/node-js/utils/fetch-hermes-price-data.js)
#### 2) Update Pyth Oracle Contract Price Feed
After [fetching an off-chain price feed](#1-fetching-off-chain-price-feed), you can now perform a contract call to the Pyth Oracle to update the price feed on-chain.
Call `update_price_feeds` on the Pyth Oracle contract with `data` as your arguments.
`example args:`
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"data": "504e41550100000000a00100000000010070b0ee3a00d1a3c07ee440887eb34a5a35860e6f4b9230fd62f0593fe35c8a3561735a6a37d269c5f166b84ead8918f710dc1be2ee6b51db5b22340ea2c173fc01673d544b00000000001ae101faedac5851e32b9b23b5f9411a8c2bac4aae3ed4dd7b811dd1a72ea4aa7100000000061bc18c014155575600000000000ab0f04600002710f41bc8c224ed983c68dbf5dab7dd34c9129fecfa03005500ca80ba6dc32e08d06f1aa886011eed1d77c77be9eb761cc10d72b7d0a2fd57a600000047e2eb4ef0000000000692480ffffffff800000000673d544b00000000673d544b00000048200e66a00000000005e495a60bb9370c458dd50558b34699b5b179f45e56be22f0a1a0feb1db8469adc8c5efeb53988495bac07bf9efed07f5eee43818150c55055882f6872a228e8e9bc78459ed3ea7fe0b86f3048f6bf0aad34befc46063ab7d200beb8bc9fe5839844d2233546f0742bb665f1e610370fcf8ce5be83d0f47e584b685af87cf3ebcb79e714827dcb99dba579e1a03785052ab3c7c7147d3f7bba822b04dbda159670e9a8d29e7ccf68474b2ca85e00224d29bf65b06b09f95e91703313e053b697b48ac1e4d1c57605a71ab77e7ef276bfe8a369c268333b9a37461bf2b7cb7fd4c005500ecf553770d9b10965f8fb64771e93f5690a182edc32be4a3236e0caaa6e0581a0000000e2ba8cd280000000001b40517fffffff800000000673d544b00000000673d544b0000000e3ea44c6800000000016aee120b47b853f55949284cb8ba0b63824ff9b48cd1da8417f45421b79ee3195fc8d107540a0bbb95c2445b66065754f135cb842db09a7e7ab33f79c546a48db872bd7197b04e3d7b52fbb55b3b9f51707c5a55fac3707cb563dbcde4aadeecc3649c237454cecf519dc567c0da03d81808523aa4fa71815eab25ce7da61b48647bac645d403208135002aab5fde2d7ab3c7c7147d3f7bba822b04dbda159670e9a8d29e7ccf68474b2ca85e00224d29bf65b06b09f95e91703313e053b697b48ac1e4d1c57605a71ab77e7ef276bfe8a369c268333b9a37461bf2b7cb7fd4c"
}
```
Example of updating the Pyth Oracle contract's price feed using `near-js/client` and node.js:
```javascript title="updatePythContract" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
// near-js imports
// https://www.npmjs.com/package/@near-js/client
const { nearConnect } = require('../utils/connect');
const { getHermesPriceData } = require('../utils/fetch-hermes-price-data');
const { functionCall } = require('@near-js/client');
const sender = 'your-account.testnet';
const receiver = 'pyth-oracle.testnet';
const network = 'testnet';
const PRICE_IDS = [
// Price ids can be found at https://www.pyth.network/developers/price-feed-ids#near-testnet
// NOTE: Ensure you are using NEAR specific price ids & remove the '0x' prefix before using them
'f9c0172ba10dfa4d19088d94f5bf61d3b54d5bd7483a322a982e1373ee8ea31b', // BTC/USD price id
'ca80ba6dc32e08d06f1aa886011eed1d77c77be9eb761cc10d72b7d0a2fd57a6', // ETH/USD price id
];
async function updatePythContractPriceFeeds(network) {
// Connect to the NEAR network
const { rpcProvider, signer } = nearConnect(sender, network);
// Get the price data from the Hermes API
// See /utils/fetch-hermes-price-data.js for more details
const hermesData = await getHermesPriceData( PRICE_IDS[0], network);
// Update the Pyth Oracle contract with the price data
// Performs a NEAR function call to the Pyth Oracle contract
// Deposit for transaction fee (balance will be refunded)
const result = await functionCall({
sender,
receiver,
method: 'update_price_feeds',
args: { data: hermesData },
deposit: 10000000000000000000000,
deps: { rpcProvider, signer },
});
console.log(
`Transaction 👉 https://testnet.nearblocks.io/txns/${result.outcome.transaction.hash}`
);
return result;
}
updatePythContractPriceFeeds(network);
```
[See code on GitHub](https://github.com/near-examples/near-js/blob/bc1f91419a3c8f1f6ca694f53bb14c57d4ce3c46/node-js/oracle-example/pyth-oracle-update.js)
```javascript title="getHermesPriceData" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
const axios = require('axios');
// There are separate endpoints for testnet and mainnet
const HERMES_TESTNET_URL = 'https://hermes-beta.pyth.network';
const HERMES_MAINNET_URL = 'https://hermes.pyth.network';
async function getHermesPriceData(priceId, network) {
try {
let url;
network === 'testnet'
? (url = HERMES_TESTNET_URL)
: (url = HERMES_MAINNET_URL);
// Fetch the price data from the Hermes API
const response = await axios.get(`${url}/v2/updates/price/latest?ids[]=${priceId}`);
return response.data.binary.data[0];
} catch (error) {
console.error('Error:', error.response ? error.response.data : error.message);
}
}
module.exports = { getHermesPriceData };
```
[See code on GitHub](https://github.com/near-examples/near-js/blob/bc1f91419a3c8f1f6ca694f53bb14c57d4ce3c46/node-js/utils/fetch-hermes-price-data.js)
```javascript title="nearConnect" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
// node.js imports
const { join } = require('node:path');
const { homedir } = require('node:os');
// near.js imports
const { getTestnetRpcProvider, getSignerFromKeystore } = require('@near-js/client');
const { UnencryptedFileSystemKeyStore } = require('@near-js/keystores-node');
// initialize RPC provider and signer
const nearConnect = (sender, network) => ({
rpcProvider: getTestnetRpcProvider(),
signer: getSignerFromKeystore(
sender,
network,
new UnencryptedFileSystemKeyStore(join(homedir(), '.near-credentials'))
)
});
module.exports = { nearConnect };
```
[See code on GitHub](https://github.com/near-examples/near-js/blob/bc1f91419a3c8f1f6ca694f53bb14c57d4ce3c46/node-js/utils/connect.js)
> [!NOTE]
>
> Although unused deposit will be refunded, you can calculate an estimate by calling the `get_update_fee_estimate` method against the Pyth contract.
***
### `get_price`
> Fetches the most recent price feed stored in the Pyth Oracle contract. Is a view method, so does not require a signature or payment.
* args: `price_identifier` *(unique price feed identifier)*
* type: `object`
* example: `{ price_identifier: 'f9c0172ba10dfa8...' }`
After [updating the price feed](#update_price_feeds), you can view the feed on-chain by calling `get_price` on the Pyth Oracle contract. Note that this is a view method and does not require a signature or deposit.
`Example:`
```javascript title="pyth-oracle-view.js" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
// near-js import
// https://www.npmjs.com/package/@near-js/client
const { getTestnetRpcProvider, view } = require('@near-js/client');
const PRICE_IDS = [
// Price ids can be found at https://www.pyth.network/developers/price-feed-ids#near-testnet
// NOTE: Ensure you are using NEAR specific price ids & remove the '0x' prefix before using them
'f9c0172ba10dfa4d19088d94f5bf61d3b54d5bd7483a322a982e1373ee8ea31b', // BTC/USD price id
'ca80ba6dc32e08d06f1aa886011eed1d77c77be9eb761cc10d72b7d0a2fd57a6', // ETH/USD price id
];
async function getPrice(price_ID, symbol) {
try {
const rpcProvider = getTestnetRpcProvider();
const result = await view({
account: 'pyth-oracle.testnet',
method: 'get_price',
args: { price_identifier: price_ID },
deps: { rpcProvider },
});
console.log(symbol, result);
} catch (error) {
console.error(`Error fetching ${symbol} price:`, error.message);
}
}
getPrice(PRICE_IDS[0], 'BTC/USD:');
```
[See code on GitHub](https://github.com/near-examples/near-js/blob/bc1f91419a3c8f1f6ca694f53bb14c57d4ce3c46/node-js/oracle-example/pyth-oracle-view.js)
# Social
Source: https://docs.near.org/primitives/social
Learn how to build social features on NEAR - profiles, posts, follows, likes and notifications - using SocialDB (social.near) and the near-social-js SDK.
[SocialDB](https://github.com/NearSocial/social-db) is a smart contract deployed at `social.near` that stores social data on the NEAR blockchain: profiles, posts, follows, likes, comments and more. It powers [near.social](https://near.social) and is widely used across the ecosystem.
> [!NOTE]
>
> While the BOS framework (components/widgets) is deprecated, the social graph stored in SocialDB is still live and maintained. This page covers how to read and write that data directly, independently of BOS.
The easiest way to interact with `social.near` is through the [`near-social-js`](https://nearbuilders.github.io/near-social-js/) SDK, which wraps the contract with helper methods for common social features.
***
## Add the SDK to a project
```bash npm2yarn theme={"theme":{"light":"github-light","dark":"github-dark"}}
npm install near-social-js
```
The SDK exposes two classes:
* `Social` — high-level helpers for profiles, posts, follows, likes and notifications.
* `Graph` — low-level access to the raw `social.near` contract (custom keys, storage, permissions). `Social` extends `Graph`.
### Reading (no wallet)
Reads are free and require no signer:
```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { Social } from 'near-social-js';
const social = new Social(); // defaults to social.near on mainnet
```
### Writing (requires a signer)
Writes return a transaction builder that you send with a signer. Pass a configured [`near-kit`](https://www.npmjs.com/package/near-kit) instance:
```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { Social } from 'near-social-js';
import { Near } from 'near-kit';
const near = new Near({ network: 'mainnet' });
const social = new Social({ near });
```
To target testnet, point the SDK at the testnet contract:
```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const social = new Social({
network: 'testnet',
contractId: 'v1.social08.testnet',
});
```
***
## Profile
A profile is stored under the `/profile/**` key and holds the user's name, description, image and links.
### Get a profile
```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const profile = await social.getProfile('alice.near');
console.log(profile?.name); // "Alice"
console.log(profile?.description); // "Hello world!"
```
### Set a profile
Only the account itself (the signer) can update its own profile:
```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const tx = await social.setProfile('alice.near', {
name: 'Alice',
description: 'Building on NEAR',
});
await tx.send();
```
***
## Posts
Posts live under the `/post/main` key and are addressed by the block height at which they were created.
### Create a post
`createPost` automatically extracts `@mentions` and `#hashtags` and indexes them so other users get notified:
```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const tx = await social.createPost('alice.near', {
text: 'My first post on NEAR! cc @bob.near #near',
});
await tx.send();
```
### Get posts from a user
```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Recent posts by a single account
const feed = await social.getAccountFeed('alice.near', { limit: 20 });
// A specific post by block height
const post = await social.getPost('alice.near', 123456789);
```
Other feed helpers are available for broader queries:
```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
await social.getActivityFeed({ limit: 20 }); // all recent posts
await social.getHashtagFeed('near', { limit: 20 }); // posts tagged #near
```
***
## Interactions
```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Follow / unfollow (sends a notification to the target)
await (await social.follow('alice.near', 'bob.near')).send();
await (await social.unfollow('alice.near', 'bob.near')).send();
const following = await social.getFollowing('alice.near');
const followers = await social.getFollowers('alice.near');
// Like / repost a post or comment
const item = { type: 'social', path: 'bob.near/post/main', blockHeight: 123456789 };
await (await social.like('alice.near', item)).send();
await (await social.repost('alice.near', item)).send();
const likes = await social.getLikes(item);
```
***
## Indexer
SocialDB exposes an **index** API: writes can be tagged with an `action` and `key`, and anyone can later query all entries for that pair, ordered by block height. This is how feeds and notifications are built — there is no off-chain indexer to run.
### Index an action
High-level methods (`createPost`, `follow`, `like`, `repost`) write index entries for you. To write a custom one, send a notification with `notify`:
```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const tx = await social.notify(
'alice.near', // signer
'bob.near', // account to notify
{ type: 'social', path: 'alice.near/post/main', blockHeight: 123456789 },
'like', // notification type
);
await tx.send();
```
### Retrieve indexed actions
Query the raw index by `action` + `key` with the low-level `index` method:
```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const entries = await social.index({
action: 'like',
key: 'bob.near/post/main',
order: 'desc',
limit: 20,
});
// → [{ accountId, blockHeight, value }, ...]
```
### Get notifications
`getNotifications` reads the `notify` index for an account and returns mentions, likes, comments, follows and reposts:
```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const notifications = await social.getNotifications('alice.near', { limit: 20 });
for (const n of notifications) {
console.log(n.value.type, 'from', n.accountId);
}
// Only the posts where the account was mentioned
const mentions = await social.getMentionedFeed('alice.near', { limit: 20 });
```
***
## Additional resources
* [near-social-js SDK docs](https://nearbuilders.github.io/near-social-js/) — full API reference
* [near-social-js on GitHub](https://github.com/NEARBuilders/near-social-js) — SDK source code
* [social-db contract](https://github.com/NearSocial/social-db) — the `social.near` smart contract
* [near.social](https://near.social) — the live social network
# Tokenized Vaults
Source: https://docs.near.org/primitives/tokenized-vaults
Learn how Tokenized Vaults (NEP-621) are defined on NEAR
A tokenized vault is a smart contract that accepts deposits of an underlying [fungible token (FT)](/primitives/ft/standard) and, in exchange, issues shares that represent proportional ownership of the assets held by the vault.
The underlying asset can be any [NEP-141](https://github.com/near/NEPs/tree/master/neps/nep-0141.md) compliant token (e.g. a stablecoin or a yield-bearing token). When a user deposits, the vault mints new shares based on the current exchange rate between the vault's total assets and its total shares in circulation. When a user redeems, the vault burns those shares and returns the equivalent amount of the underlying asset.
The shares themselves are also NEP-141 compliant fungible tokens, so they can be transferred between accounts or traded on DEXs, and integrated into broader DeFi use cases such as collateral in lending protocols, liquidity provision, or composable yield strategies.
This interface is defined by [NEP-621](https://github.com/near/NEPs/tree/master/neps/nep-0621.md), and is heavily inspired by the [ERC-4626](https://eips.ethereum.org/EIPS/eip-4626) standard widely used on Ethereum. Standardizing the vault interface improves interoperability, reduces integration costs, and encourages consistent, secure vault implementations across the NEAR ecosystem.
> [!TIP]
>
> NEP-621 defines the interface and the expected behavior of a vault contract, but it does not dictate how the internal logic (yield strategy, fees, accounting) should be implemented.
>
> Unlike ERC-4626, deposits and mints on NEAR are handled through the `ft_on_transfer` callback (as defined by NEP-141), rather than by direct method calls, to fit NEAR's asynchronous execution model.
***
## NEP-621 (Vault Interface)
A vault contract MUST implement the `VaultCore` trait, which extends:
* [`FungibleTokenCore`](/primitives/ft/standard#nep-141-fungible-token-interface) — to provide NEP-141 functionality for the shares.
* `FungibleTokenReceiver` — to receive the underlying NEP-141 asset.
In other words, a vault is itself a fungible token (the shares) that can also receive another fungible token (the underlying asset).
### Asset Information
#### `asset_contract_id` (*read-only*)
Returns the account ID of the underlying asset's NEP-141 contract. Should be stored as an immutable configuration value.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
asset_contract_id(): string
```
#### `total_asset_amount` (*read-only*)
Returns the vault's total managed value, denominated in the underlying asset, represented by all shares in existence.
> 📖 This is the vault's total managed value, *not* just the balance held in the contract. If assets are staked, lent, or deployed elsewhere, this returns the estimated total equivalent value, net of any deposit/withdrawal fees.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
total_asset_amount(): string
```
***
### Conversion Helpers
These are view-only estimations. They do not update state and ignore user-specific constraints such as limits or fees. They MUST never panic, returning `0` if conversion is not possible.
#### `convert_to_shares` (*read-only*)
Converts an amount of underlying assets to the equivalent number of shares.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
convert_to_shares(asset_amount: string): string
```
#### `convert_to_asset_amount` (*read-only*)
Converts an amount of shares to the equivalent amount of underlying assets.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
convert_to_asset_amount(shares: string): string
```
> [!TIP]
>
> Use `convert_*` for generic price quotes, and the `preview_*` methods below when you need an estimate that also accounts for per-user limits and fees.
***
### Deposit & Redemption Limits
All limit and preview methods are read-only and MUST never panic, returning `0` when the operation is not currently allowed. Limit methods should return `U128::MAX` to signal "unlimited".
#### `max_deposit_amount` (*read-only*)
Maximum amount of underlying assets that `receiver_id` can deposit.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
max_deposit_amount(receiver_id: string): string
```
#### `preview_deposit_shares` (*read-only*)
Simulates depositing exactly `asset_amount` and returns the number of shares that would be minted, accounting for per-user deposit limits and fees.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
preview_deposit_shares(asset_amount: string): string
```
#### `max_mint_shares` (*read-only*)
Maximum number of shares that `receiver_id` can mint.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
max_mint_shares(receiver_id: string): string
```
#### `preview_asset_amount_required_to_mint_shares` (*read-only*)
Simulates minting exactly `shares` and returns the amount of underlying assets required.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
preview_asset_amount_required_to_mint_shares(shares: string): string
```
#### `max_redeem_shares` (*read-only*)
Maximum number of shares that `owner_id` can redeem (considering balance, withdrawal restrictions, and lock-ups).
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
max_redeem_shares(owner_id: string): string
```
#### `preview_redeem_amount` (*read-only*)
Simulates redeeming `shares` and returns the amount of assets that would be received, factoring in the owner's balance, withdrawal limits, and fees.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
preview_redeem_amount(shares: string): string
```
#### `max_withdraw_amount` (*read-only*)
Maximum amount of assets that `owner_id` can withdraw.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
max_withdraw_amount(owner_id: string): string
```
#### `preview_shares_deducted_for_withdraw` (*read-only*)
Simulates withdrawing exactly `asset_amount` and returns the number of shares that would be burned.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
preview_shares_deducted_for_withdraw(asset_amount: string): string
```
***
### Deposit & Mint
Following the NEP-141 standard, assets are sent to the vault via [`ft_transfer_call`](/primitives/ft/standard#ft_transfer_call) on the underlying asset's contract, which invokes `ft_on_transfer` on the vault. Both the ERC-4626 `deposit` and `mint` operations are handled through this single entrypoint.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
ft_on_transfer(sender_id: string, amount: string, msg: string): string
```
Upon a successful deposit, the vault MUST emit a [`VaultDeposit`](#events) event and should also emit an `FtMint` event for the issued shares.
The `msg` parameter carries the deposit options. While implementers are free to define their own schema, the suggested convention is a JSON-encoded message:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub struct DepositMessage {
/// Minimum shares that must be received for the deposit to succeed (slippage control).
min_shares: Option,
/// Maximum shares that can be minted, used for `mint` operations.
max_shares: Option,
/// Account that should receive the minted shares.
receiver_id: Option,
/// Optional memo for logging or off-chain indexing.
memo: Option,
/// If `true`, the transfer is treated as a donation and no shares are minted.
donate: Option,
}
```
As required by NEP-141, `ft_on_transfer` must return the number of tokens to refund to the sender: `0` if all tokens were accepted, or a non-zero value otherwise.
***
### Redemption & Withdrawal
#### `redeem`
Burns `shares` from the caller and returns the equivalent amount of underlying assets. If `receiver_id` is omitted, assets are sent to the caller. Set `min_amount_out` to `0` to ignore slippage, or to a reasonable value to protect against it.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
redeem(shares: string, min_amount_out: string, receiver_id: string?): string
```
#### `withdraw`
Withdraws exactly `asset_amount` of underlying tokens, burning the required number of shares. If `receiver_id` is omitted, assets are sent to the caller. Provide `max_shares_deducted` to protect against slippage.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
withdraw(asset_amount: string, max_shares_deducted: string?, receiver_id: string?): string
```
Upon a successful withdrawal, the vault MUST emit a [`VaultWithdraw`](#events) event.
***
## Events
Vaults emit standardized events so wallets, indexers, and other DeFi applications can track deposits and withdrawals.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
/// Emitted when a deposit is received by the vault and shares are minted to `owner_id`.
pub struct VaultDeposit {
/// Account that sends the deposit (payer of the assets).
pub sender_id: AccountId,
/// Account that receives the minted shares.
pub owner_id: AccountId,
/// Amount of underlying assets deposited into the vault.
pub asset_amount: U128,
/// Amount of shares minted and issued to `owner_id`.
pub shares: U128,
/// Optional memo provided by the sender for off-chain use.
pub memo: Option,
}
/// Emitted when shares are redeemed: the vault burns shares from `owner_id`
/// and transfers the equivalent assets to `receiver_id`.
pub struct VaultWithdraw {
/// Account that owns the shares being redeemed (burned).
pub owner_id: AccountId,
/// Account receiving the underlying assets.
pub receiver_id: AccountId,
/// Amount of shares redeemed (burned from the vault).
pub shares: U128,
/// Amount of underlying assets withdrawn from the vault.
pub asset_amount: U128,
/// Optional memo provided by the redeemer for off-chain use.
pub memo: Option,
}
```
Because transactions on NEAR are non-atomic, a vault should emit `VaultWithdraw` in one of two ways:
1. Emit `VaultWithdraw` when the fee is deducted, and emit a compensating `VaultDeposit` if the withdrawal later fails; or
2. Emit `VaultWithdraw` only if the withdrawal succeeds.
> In the [reference implementation](https://github.com/Meteor-Wallet/tokenized-vault-nep-implementation), an `FtBurn` event is emitted when `withdraw` is called. On success, a `VaultWithdraw` event is emitted in the `resolve_withdraw` callback; on failure, an `FtMint` event restores the user's balance.
***
## Security Considerations
When implementing a vault, keep the following risks in mind:
* **Exchange rate manipulation (inflation attacks):** if the vault has a permissionless donation mechanism, an attacker can donate assets to inflate the share price and steal value from later depositors. Mitigate by seeding a non-trivial initial deposit and/or using a virtual decimal offset on issued shares (demonstrated in the [reference implementation](https://github.com/Meteor-Wallet/tokenized-vault-nep-implementation)).
* **Cross-contract calls:** `redeem` and `withdraw` perform asynchronous FT transfers, opening the door to reentrancy. Use proper state management, callback security, and rollback mechanisms for failed operations.
* **Rounding direction:** always round in favor of the vault — round *down* when issuing shares or transferring assets out, round *up* when calculating shares/assets required for a given amount. This prevents value extraction through repeated micro-transactions.
* **Oracle and external price dependencies:** stale oracle data creates temporal windows for exploitation. Include staleness checks, prevent operations during oracle updates, and consider fallback pricing for oracle failures.
***
## Reference Implementation
A reference implementation is available at [Meteor-Wallet/tokenized-vault-nep-implementation](https://github.com/Meteor-Wallet/tokenized-vault-nep-implementation).
# What are Primitives?
Source: https://docs.near.org/primitives/what-is
Learn about blockchain primitives including Fungible Tokens (FT), Non-Fungible Tokens (NFT), Decentralized Autonomous Organizations (DAO), and LinkDrops as building blocks for applications.
Primitives are fundamental building blocks that can be combined to create a fully functional application. Blockchain primitives include [Fungible Tokens (FT)](#fungible-tokens-ft), [Non Fungible Tokens (NFT)](#non-fungible-tokens-nft), [Decentralized Autonomous organizations (DAO)](#decentralized-autonomous-organizations-dao), [Link Drops](#linkdrops) and more.

***
#### Fungible Tokens (FT)
[Fungible tokens](./ft/ft) represent an **asset** on a blockchain that is **interchangeable**. Besides the native NEAR token, users can issue their own fungible tokens or use those that are already present in the ecosystem.
> [!TIP]
>
> Fungible Tokens are ideal to create **reward systems**, **fair tickets** and any other type of **token**.
#### Non Fungible Tokens (NFT)
In contrast with fungible tokens, each [non-fungible token (NFT)](./nft/nft) is **unitary** and therefore **unique**. Users can create their own non-fungible token, transfer to other users, or exchange them in marketplaces.
> [!TIP]
>
> NFTs are ideal to represent **ownership of assets** such as **collectibles**, **event tickets** and other unique assets.
#### Decentralized Autonomous organizations (DAO)
[Decentralized Autonomous Organizations (DAOs)](./dao) are **self-organized groups** that form around common purposes. Membership, decision making, and funding are **coordinated** by **publicly voting** on proposals through a smart contract.
> [!TIP]
>
> DAOs are ideal to create **decentralized governance**, **funding**, and **decision-making** tools.
### LinkDrops
[LinkDrops](./linkdrop/linkdrop) are an easy way to **distribute digital assets** (NFTs, FTs) via links. You simply **provide a link** for users and they can **claim** your drop.
> [!TIP]
>
> LinkDrops are ideal to do **drops**, and **onboard new users** into Web3 apps.
# Access Keys
Source: https://docs.near.org/protocol/accounts-contracts/access-keys
NEAR has a rich access key system, allowing fine-grained control over accounts
In NEAR, accounts can **hold multiple keys**, each key has its own **set of permissions** and specific **signature schemes** to sign transactions. Keys can be **added** or **removed** as needed, allowing flexible and secure account management.

NEAR distinguishes two types of permissions for access keys: **Function Call keys** can only sign transactions calling a specific contract, while **Full Access keys** have unrestricted control over the account.
Meanwhile, the protocol supports **multiple types of signature schemes**, allowing it to be compatible with a variety of other ecosystems and cryptographic standards.
> [!TIP]
>
> Applications that need to send many transactions in parallel would benefit from using [gas keys](/protocol/accounts-contracts/gas-keys) as they provide a prepaid gas balance and independent nonce lanes.
***
## Function-Call Keys
`Function-Call` keys can only sign transactions calling a **specific contract**, and do **not allow** to **attach NEAR tokens** to the call.
They are defined by three attributes:
1. `receiver_id`: The **only contract** which the key allows to call, no other contract can be called with this key
2. `method_names` (Optional): The contract's **methods** the key allows to call. If omitted, all contract's methods can be called
3. `allowance` (Optional): The **amount of NEAR** allowed to be spent on [gas](/protocol/transactions/gas). If omitted, the key can consume **unlimited** gas
`Function Call Keys` are meant to be shared with applications, so third-parties can make contract calls in your name. This is useful in multiple scenarios as we will see below.
> [!TIP]
>
> `Function-Call` keys are secure to share, as they only permit calls to a specific contract and prohibit NEAR token transfers
***
## Full-Access Keys
As the name suggests, `Full-Access` keys have full control of an account, meaning they can be used to sign [transactions](/protocol/transactions) doing any action in your account's behalf:
1. Transfer NEAR Ⓝ
2. Delete your account or create sub-accounts of it
3. Add or remove Access Keys
4. Deploy a smart contract in the account
5. Call methods on any contract
You should never share your `Full-Access`, otherwise you are giving **total control over the account**.
> [!TIP]
>
> [Implicit accounts](./account-id#implicit-address) already have a `Full-Access Key` by default, while for [`named accounts`](./account-id#named-address) their first `Full-Access Key` is added on creation
***
## Signature Schemes
Independently of its permission level, every access key is a cryptographic key pair belonging to one of NEAR's supported **signature schemes**. A public key is written as `:`, where the prefix identifies the scheme — for example `ed25519:CQLP1o1F3Jbdttek3GoRJYhzfT...`.
| Scheme | Public key prefix | Public key size | Quantum-resistant |
| - | - | - | - |
| Ed25519 | `ed25519:` | 32 bytes | No |
| secp256k1 | `secp256k1:` | 64 bytes | No |
| ML-DSA-65 | `ml-dsa-65:` | 1952 bytes | Yes |
`ed25519` is the most used scheme in NEAR wallets and tooling, since it can be used to derive [implicit accounts](./account-id#implicit-address).
`secp256k1` is used mainly for [chain signatures](/chain-abstraction/chain-signatures) and Ethereum-compatible flows.
`ml-dsa-65` is a **post-quantum** signature scheme, standardized by NIST as [FIPS 204](https://csrc.nist.gov/pubs/fips/204/final). It is designed to resist attacks from quantum computers, which - if sufficiently powerful - could derive private keys from `ed25519` or `secp256k1` public keys.
> [!TIP]
>
> All NEAR accounts can hold multiple keys from different schemes at the same time, allowing for a mix of classical and post-quantum keys if desired.
> [accordion] 🧑💻 Technical: How post-quantum keys are stored
>
> An `ml-dsa-65` public key is large — **1952 bytes**, versus 32 for `ed25519` — and its signatures are **3309 bytes**. To keep accounts cheap to store, NEAR does **not** keep the full public key on-chain; instead it stores a 32-byte [SHA3-256](https://en.wikipedia.org/wiki/SHA-3) hash of it — the same size as an `ed25519` public key — which keeps the per-key [storage cost](/protocol/storage/storage-staking) close to that of a classical key.
>
> Because only the hash is stored, listing an account's keys returns the **hash**, not the full key, for `ml-dsa-65` entries. When you query an account's keys (for example with [`view_access_key_list`](/api/rpc/contracts#view-access-key-list)), `ml-dsa-65` keys appear with an `ml-dsa-65-hash:` prefix instead of `ml-dsa-65:`:
>
> ```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
> ml-dsa-65-hash:7Xx2X... # base58-encoded 32-byte SHA3-256 digest
> ```
>
> To recognize one of your own post-quantum keys in such a list, derive the same handle from your public key: it is the [SHA3-256](https://en.wikipedia.org/wiki/SHA-3) hash of the domain-separation tag `near:ml-dsa-65-pubkey-hash:v1` **followed by** the raw 1952-byte public key. Hashing the key without that prefix will not match the returned value. To look up a specific key directly with [`view_access_key`](/api/rpc/contracts#view-access-key), pass the **full** `ml-dsa-65:` public key and the network hashes it for you.
***
## Limited Access Key Caveats
Function-call keys restrict what applications can do, but relying on them alone can leave an account unable to manage its keys or assets.
### Using Only Function-Call Keys
If an account has **no full-access keys** and only function-call keys, it becomes effectively restricted:
* It **cannot** transfer NEAR, delete itself, or manage its own keys
* It can **only** perform the specific contract calls defined by the key's `receiver_id` and `method_names`
This is useful for creating restricted sub-accounts (e.g. for [chain signatures](../../chain-abstraction/chain-signatures)), but be aware the account cannot be recovered or reconfigured through standard transactions.
> [!WARNING]
>
> Creating a sub-account with only a single function-call key means that account will **never** be able to remove itself, transfer NEAR out, or add new keys — unless the target contract provides a method to do so.
### Allowance Exhaustion
The `allowance` field defines how much NEAR the key can spend on gas fees:
* If set to a specific amount and fully consumed → the key becomes **unusable** and no new transactions can be signed
* If omitted (`null`) → **unlimited** allowance (the key has no gas budget restriction)
* If set to `0` in an `AddKey` action → a zero budget, so every transaction signed with the key fails with `NotEnoughAllowance`
> [!WARNING]
>
> There is one exception. When a contract adds a key with the `promise_batch_action_add_key_with_function_call` host function, an allowance of `0` means unlimited.
The allowance is charged at the [buy price](/protocol/transactions/gas#buying-vs-burning-gas) and credited back when the gas refund arrives, so a key needs more allowance than the final transaction cost.
> [!WARNING]
>
> If an account has only function-call keys and their allowance runs out, the account cannot sign any more transactions. Adding NEAR to the account does not help, because the allowance belongs to the key, not to the account balance. To avoid this, leave the allowance unset so it is unlimited. The allowance of an existing key cannot be changed. To get a new allowance, add a new key. To add a key, you need a full access key, or a method in the account's own contract that adds keys.
***
## Locked Accounts
If you remove all keys from an account, then the account will become **locked**, meaning that no external actor can perform transactions in the account's name.
In practice, this means that only the account's smart contract can transfer assets, create sub-accounts, or update its code.
Locking an account is very useful when one wants to deploy a contract, and let the community be assured that only the contract is in control of the account.
> [!TIP]
>
> To lock an implicit account, remove all its keys, including the `ed25519` key from which its address is derived.
> [!WARNING]
>
> A locked account can still add keys to itself if its contract provides a method to do so. This is only possible if the contract was deployed before the account was locked.
# Address (Account ID)
Source: https://docs.near.org/protocol/accounts-contracts/account-id
Learn all about NEAR account addresses
NEAR accounts are identified by a unique address, which can take multiple forms:
1. [**Implicit address**](#implicit-address), which are 64 characters long (e.g. `fb9243ce...`)
2. [**Named address**](#named-address), which are simpler to remember (e.g. `alice.near`, `sub.account.testnet`)
3. An ethereum-like account (e.g. `0x85f17cf997934a597031b2e18a9ab6ebd4b9f6a4`)
4. [**Deterministic address**](#deterministic-address), which are 42 characters long and start with `0s` (e.g. `0s85f17cf997934a597031b2e18a9ab6ebd4b9f6a4`)
5. [**Universal address**](#universal-address), which are 54 characters long and start with `0u` (e.g. `0u0000000000000000000000000000000000000000000000000000`)
> [accordion] Valid Account IDs
>
> In NEAR, accounts can actually be any string as long as they meet the following criteria:
>
> * It must have at least 2 characters and can go up to 64 characters
> * It can only use lowercase letters (`a-z`), digits (`0-9`), and separators (`.`, `-`, `_`)
>
> This means that all `root`, `some-unique-string`, `something-to-remember-later`, `0x85f17....`, `fb9243ce` and `user.name` are **all valid account IDs**.
>
> Accounts can be created with named, implicit, Ethereum-like, deterministic, or universal addresses.
> [!TIP]
>
> **Searching to create an account?**
>
> See our guide on [creating an account](/getting-started/create-account).
> [!NOTE]
>
> **Building an app that accepts a recipient account from the user?**
>
> Read [Validating Recipient Accounts](../../web3-apps/tutorials/account-validation) for the best practices wallets apply to prevent typos and lost funds.
***
## Implicit Address
Implicit accounts are denoted by a 64 character address, which corresponds to a unique `ed25519` public/private key-pair. Whoever controls the [private key](./access-keys) of the implicit account controls the account.
For example:
* The private key: `ed25519:4qAaptksph8QbpNKU8TBDL65nh95AXGkSiXnDbdcoJ2SmtMrsihyqQdyiMoz38g38B3Lfo5MpPFveFgtLpjz1FpG`
* Corresponds to the public key: `ed25519:5NkxGL5fD497rn5o3SQmSeBggraAT6hfSivb1JdtFC1J`
* And controls the account: `4101a46f3ba21613263de3decc83b1a79f745a9a791f570c0bc6df086cb43dbd`
While you can always derive an implicit address, if you want to sign any transaction you will need to initialize the account by sending some NEAR - can be 0 NEAR, which will create the account with no balance - to it.
> [!TIP]
>
> In NEAR, you can delete the private key of an implicit account, which effectively locks the account and prevents anyone to control it
See [Creating Implicit & Named Accounts](/protocol/tutorials/creating-implicit-and-named-accounts#create-an-implicit-account) to generate a key pair and fund the account.
> [accordion] 🧑💻 Technical: How to derive an implicit account from a public key
>
> You can derive the implicit account address from a public key by removing the `ed25519:` prefix, decoding the resulting Base58 string into bytes, and then converting those bytes into a hexadecimal string.
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // vanilla js
> import bs58 from 'bs58';
> Buffer.from(bs58.decode(publicKey.replace('ed25519:', ''))).toString('hex')
>
> // or using near-api-js
> import { keyToImplicitAddress } from 'near-api-js';
> keyToImplicitAddress(publicKey);
> ```
***
## Named Address
Users can register **named accounts** (e.g. `bob.near`) which are easy to remember and share.
A feature of named accounts is that they can create **sub-accounts** of themselves, effectively working as domains:
1. The [`registrar`](https://nearblocks.io/address/registrar) account can create top-level accounts (e.g. `near` or `sweat`).
2. The `near` account can create sub-accounts such as `bob.near` or `alice.near`
3. `bob.near` can create sub-accounts of itself, such as `app.bob.near`
4. Accounts cannot create sub-accounts of other accounts
* `near` **cannot** create `app.bob.near`
* `account.near` **cannot** create `sub.another-account.near`
5. Accounts have **no control** over their sub-account, they are different entities
See [Creating Implicit & Named Accounts](/protocol/tutorials/creating-implicit-and-named-accounts#create-a-named-account) to create a named account using the CLI, a faucet, or an existing funded account.
***
## Ethereum-like Address
NEAR also supports Ethereum-like accounts which are identified by a hexadecimal address (e.g. `0x85f17cf997934a597031b2e18a9ab6ebd4b9f6a4`). These accounts are automatically created when a user signs in on a NEAR application using an Ethereum wallet such as MetaMask.
***
## Deterministic Address
Deterministic addresses are a special type of address, derived from accounts with a pre-defined initial contract and storage.
They start with `0s`, followed by 40 hex characters **deterministically derived** from the **initial code and storage** of the account - e.g. `0sfa485e3a3e4d6c4ab18b2df9f26631f1485f13c0` represents a `Hello World` contract initialized with the greeting "Howdy".
> [!TIP]
>
> Deterministic accounts are useful for protocols and applications that need to reference a contract address before deployment.
> [accordion] 🧑💻 Technical: How is the address derived?
>
> The deterministic account ID is computed by:
>
> 1. Constructing a `DeterministicAccountStateInit::V1` value. The type is a versioned enum, and `V1` is its only version. The value contains:
> * **Code**: a global contract, referenced by its code hash, or by account ID if it was [deployed by account ID](/smart-contracts/global-contracts). The global contract must already exist, or the action fails with `GlobalContractDoesNotExist`.
> * **Initial data**: a key-value mapping pre-populating the contract's storage. Each key can be at most 2 KiB (2048 bytes) and each value at most 4 MiB. From protocol version 87 (nearcore 2.14.0), the state init actions in one receipt can hold at most 1,500 entries in total.
> 2. Borsh-encoding that value into bytes. The encoding starts with the version byte `0`. The code reference starts with `0` for a code hash or `1` for an account ID. The data entries are sorted by key.
> 3. Applying the formula: `'0s' + keccak256(bytes)[12:32].hex()`
>
> This guarantees that two accounts with identical code and initial state will always have the same address.
> [accordion] 🧑💻 Technical: How are deterministic accounts created?
>
> Deterministic accounts are created using the `DeterministicStateInit` action — **not** the standard `CreateAccount` action. The protocol validates that the supplied account ID matches the hash of the provided initial state.
>
> See [Creating Deterministic Accounts](/protocol/tutorials/creating-deterministic-accounts) for a walkthrough, or use [smart contracts](/smart-contracts/anatomy/actions#create-deterministic-accounts) and [NEAR API libraries such as `near-kit`](/tools/near-api#create-deterministic-account).
>
> Any NEAR attached beyond the required storage deposit is refunded to the sender.
> [!NOTE]
>
> A NEAR transfer to a `0s` address that does not exist yet creates the account with a balance, but no code, keys, or storage. Its contract and initial storage are installed when a matching `DeterministicStateInit` action arrives.
> [!NOTE]
>
> A deterministic account has no access keys when it is created, and creating it does not give the sender any control over it. Only the account itself can deploy new code, add keys, or delete the account. At first, this can happen only through the account's own contract. If the contract adds a full-access key, the holder of that key can also do these things. A function-call key does not give this control. The contract can still change its storage like any other contract.
>
> The code comes from a global contract. If the initial state names the global contract by code hash, the code stays as initialized unless the account itself changes it, through its contract or through a full-access key that the contract added. If it names the global contract by account ID, the owner of that account can publish new code at any time, and the deterministic account then runs the new code without a change of address. If a deterministic account is deleted, anyone can create it again with the same initial state.
***
## Universal Address
Similar to deterministic addresses, universal addresses are derived from an account's initial state. However, the initial state can also contain **access keys**.
They start with `0u` followed by 52 lowercase characters (54 characters total) - e.g. `0uvjkhh8nsdtth98wq1k8hka97gw9e0yvga4a4th3vj0jqwa91y4yg` is the address of an account with a single `post-quantum` key (`ml-dsa-65:NJ7gjn5UMGPZ…MtbZ9pmk`) with no contract.
> [!NOTE]
>
> **How is this different from a deterministic account?**
>
> Deterministic accounts are derived solely from `code` plus an `initial storage`, with no keys, so they can only be controlled through their contract's own logic. Universal accounts, meanwhile, hash code, storage, **and** a set of access keys together, so a universal account can be a key-controlled account with no contract at all, similar to an implicit account.
>
> One important difference though is that universal accounts can be created with [post-quantum (`ml-dsa-65`)](./access-keys#signature-schemes) keys, while implicit accounts can be created with `ed25519` keys only.
> [accordion] 🧑💻 Technical: How is the address derived?
>
> The universal account ID is computed by:
>
> 1. Constructing a `UniversalStateInit` value containing:
> * **Code** (optional, omitted for a key-only account): a global contract, referenced by its code hash, or by account ID if it was deployed by account ID
> * **Data**: a key-value mapping pre-populating the contract's storage, empty for a key-only account
> * **Access keys**: a set of access-key handles the account starts with, empty for a contract-only account. A handle is the full public key for `ed25519`/`secp256k1`, or the 32-byte hash for `ml-dsa-65` — the same [compact form](./access-keys#signature-schemes) used everywhere else
> 2. Borsh-encoding that value into bytes
> 3. Applying the formula: `'0u' + crockford_base32(sha3_256(bytes))`
>
> Unlike the `0s` scheme, the protocol does not re-serialize the bytes into a canonical form before hashing: the id commits to the **exact bytes supplied** — but those bytes must themselves already be the one canonical encoding (`data` and `access_keys` entries sorted with no duplicates, and no trailing bytes), or the state init is rejected outright rather than accepted under a different id.
> [accordion] 🧑💻 Technical: How are universal accounts created?
>
> Universal accounts are created using the `UniversalStateInit` action, a distinct action from `CreateAccount` - used for named accounts - and `DeterministicStateInit` - used for deterministic accounts.
>
> See [Creating Universal Accounts](/protocol/tutorials/creating-universal-accounts) for creation flows and code examples, or [Create universal accounts](/smart-contracts/anatomy/actions#create-universal-accounts) for the host functions used by smart contracts.
> [!NOTE]
>
> A NEAR transfer to a `0u` address that does not exist yet **auto-creates it as uninitialized**: it holds the transferred balance but has no code, keys, or storage until a matching `UniversalStateInit` arrives. See [The uninitialized account](/protocol/tutorials/creating-universal-accounts#the-uninitialized-account) for what an uninitialized account can and can't do.
# NEAR Accounts
Source: https://docs.near.org/protocol/accounts-contracts/account-model
A unique account model that supports multiple types of addresses, access keys, and smart contracts.
Users participate in the NEAR ecosystem through their NEAR accounts. These accounts are identified by a [unique address](./account-id), can optionally hold a [smart contract](/smart-contracts/what-is), and are controlled through [Access Keys](./access-keys).
By signing [transactions](../transactions) with their account, users can:
1. Send and receive **digital assets** (such as tokens or collectibles)
2. Create and interact with on-chain applications known as **smart contracts**
3. Control accounts in **other chains** (such as Ethereum or Bitcoin) ✨
4. Help onboard new users by **covering the costs** of their transactions (gas fees)
> [!TIP]
>
> **Want to create an account?**
>
> Check out our tutorial on [Creating a NEAR Account](/getting-started/create-account) to get started!
***
## Account Model Overview
Let's take a closer look at the different elements that compose the NEAR account model.

### Account ID
NEAR **natively** implements multiple [types of addresses](/protocol/accounts-contracts/account-id), including:
1. **Named accounts** such as `alice.near`, which are simple to remember and share
2. **Implicit accounts** such as `fb924c...` (64 chars), derived from an `ed25519` private key
3. **Ethereum-like accounts**, controlled by Ethereum wallets
4. **Deterministic accounts** such as `0s85f17...` (42 chars), derived from their initial code and storage
5. **Universal accounts** such as `0u0000...` (54 chars), derived from their initial code, storage, and keys
### Multiple Keys
NEAR accounts can have [multiple keys](/protocol/accounts-contracts/access-keys), each with their own set of permissions:
* You can easily swap keys if one gets compromised
* You can use keys as authorization tokens for third-party applications
### Smart Contracts
NEAR accounts can optionally hold an application - known as a [smart contract](/smart-contracts/what-is) - which can store data and expose functions to interact with it.
***
## Comparison With Ethereum
If you're familiar with development on Ethereum, it's worth making a quick note about how accounts are different. The table below summarizes some key differences:
| | Ethereum Account | NEAR Account |
| - | - | - |
| Account ID | Public Key (`0x123...`) | - Native named accounts (`alice.near`) - Implicit accounts (`0x123...`) |
| Secret Key | Private Key (`0x456...`) | Multiple key-pairs with permissions: - `FullAccess` key - `FunctionCall` key |
| Smart Contracts | Synchronous execution | Asynchronous execution |
| Gas Fees | In the order of dollars | In the order of tenths of a cent |
| Block Time | \~12 seconds | \~600 milliseconds |
# Gas Keys
Source: https://docs.near.org/protocol/accounts-contracts/gas-keys
Send transactions in parallel using access keys with a prepaid gas balance and independent nonce lanes.
Gas keys ([NEP-611](https://github.com/near/NEPs/pull/611)) are [access keys](/protocol/accounts-contracts/access-keys) designed for **sending many transactions in parallel**. They were introduced in nearcore 2.13 (protocol version 86) and differ from regular access keys in two ways:
1. **Prepaid gas balance**: a gas key holds its own NEAR balance, and transactions signed with it pay gas from that balance instead of the account's main balance
2. **Parallel nonces**: a gas key has up to **1,024 independent nonces** (called *nonce lanes*), so many transactions can be in flight at once without nonce collisions
A gas key can have either `FullAccess` or `FunctionCall` permission, with one restriction: a function-call gas key cannot set an `allowance` — its prepaid balance already serves as the gas budget.
> [!TIP]
>
> Gas keys are ideal for **programmatic senders** — relayers, bots, exchanges, or a fleet of agents operating one account — which previously had to juggle many separate access keys just to avoid nonce collisions, and risked draining the account's main balance on gas.
***
## Lifecycle of a Gas Key
A gas key is managed with the same actions as any other key, plus two new actions to move NEAR in and out of its balance:
1. **Create**: an `AddKey` action with a gas-key permission creates the key, specifying its number of nonces (`num_nonces`, between 1 and 1,024). The key is always created with **zero balance**
2. **Fund**: a `TransferToGasKey` action moves NEAR from the account's balance into the gas key's balance. It can be used repeatedly to top up the key
3. **Use**: transactions signed with the gas key specify a `nonce_index` selecting which nonce lane to use, and consume gas from the key's balance
4. **Withdraw**: a `WithdrawFromGasKey` action moves NEAR from the key's balance back to the account. Only the account itself can withdraw
5. **Delete**: a `DeleteKey` action removes the key. Any remaining balance is **burned**, so the action fails if the key holds more than 1 NEAR — withdraw first, then delete
> [!WARNING]
>
> Deleting a gas key **burns** whatever balance is left on it — this is a protocol-level protection against spam attacks, not a bug. Always `WithdrawFromGasKey` before deleting. The deletion (and likewise `DeleteAccount`) fails if more than 1 NEAR would be burned, protecting you from losing significant funds by accident.
***
## How Gas Keys Pay for Transactions
When a transaction is signed with a gas key:
* The **gas costs** (both burned gas and gas prepaid for function calls) are charged to the **gas key's balance**
* Any **attached NEAR** (deposits, transfers) is still paid from the **account's main balance**
* **Gas refunds** for unspent gas return to the **gas key's balance**, so the key sustains itself between top-ups, while balance refunds go to the account
If the gas key's balance cannot cover a transaction's gas, the transaction is rejected. If the gas is covered but the account cannot pay the attached deposit at execution time, the transaction fails and **the gas burned to process it is still charged** to the gas key. The gas that was attached to the receipt is refunded.
> [!NOTE]
>
> Gas is [bought at a price that can be higher than the price it burns at](/protocol/transactions/gas#buying-vs-burning-gas), so a gas key has to hold more than its transactions finally cost. The difference comes back to the key as a refund, but it has to be on the key upfront.
***
## Using Nonce Lanes
Each of the key's `num_nonces` lanes keeps its own independent nonce. A transaction signed with a gas key picks a lane through a `nonce_index` field (from `0` to `num_nonces - 1`), and only that lane's nonce advances. Two transactions on different lanes can never conflict, so a sender can run one lane per worker and submit transactions concurrently — with a single key to manage.
You can inspect a gas key's lanes with the [`view_gas_key_nonces`](/api/rpc/contracts#view-gas-key-nonces) RPC query, and gas keys appear in [`view_access_key`](/api/rpc/contracts#view-access-key) with their `balance` and `num_nonces`.
> [!NOTE]
>
> **Tooling support**
>
> You can create and manage gas keys with the [NEAR CLI](/tools/cli#gas-keys) (`near account add-key ... grant-gas-key-full-access`, `fund-gas-key`, `withdraw-from-gas-key`, `view-gas-key-nonces`) and from your app with the [`near-kit`](https://github.com/r-near/near-kit) (TypeScript) and [`near-kit-rs`](https://github.com/r-near/near-kit-rs) (Rust) libraries — both cover creating, funding, withdrawing, signing on a nonce lane, and reading a key's lanes via `view_gas_key_nonces`. Contracts can also add and fund gas keys through batch-promise host functions — though only the account's own transactions can withdraw from one.
***
## Meta transactions
> [!WARNING]
>
> From protocol version 87, gas keys cannot sign the inner delegate action of a [meta transaction](/protocol/transactions/meta-tx#delegatev2-meta-transactions-with-gas-keys). Users must use a regular access key. Relayers can still sign the outer transaction with a full access gas key to pay for gas.
# NEAR Data Flow
Source: https://docs.near.org/protocol/data-flow/near-data-flow
Learn how data flows in NEAR Protocol, including transactions, receipts, shards, and cross-shard communication.
NEAR Protocol blockchain data flow might be a bit tricky at a glance. But it is pretty straightforward and follows well-defined rules. In this article, we are going to have a closer look at how the data flows in NEAR Protocol blockchain.
[YouTube video player](https://www.youtube.com/embed/VSBJ-A69Km4)
> [!NOTE]
>
> **Data flow**
>
> In this video we give a quick overview on the main concept of how the data flows across the NEAR Protocol blockchain.
In fact, any blockchain flow can be represented as an infinite timeline that has a start but has no end.

And a block appears on that timeline with some interval. Each of these blocks holds the information about the previous one, thus, creating a *chain of blocks*.
NEAR Protocol has a sharded nature, meaning that more than one parallel network, called a `Shard`, can be live at any moment. And each Shard produces a chunk of a block at a given interval. A Block in NEAR Blockchain is a collection of the block chunks from all shards. Block chunk is shortened to `Chunk` in NEAR Protocol documentation.
Returning to the data flow itself. The best we can do is to imagine tracks like we could see in audio/video editing apps. Each Shard has its own set of tracks. The top track is for Chunks. They appear no matter what at a given interval, for NEAR Blockchain the interval is about one second. Chunks are being produced even if nothing is happening on the blockchain.

But what do we mean by saying something is happening? We mean that something has triggered some changes in the blockchain. And the most well-known method to trigger any changes is to send a `Transaction` to the blockchain with instructions of what we want to change and who has requested those changes.
A transaction needs to be constructed, signed and sent to the blockchain. Once it is executed we expect to have a result - `ExecutionOutcome`. Oh, that is simple. But it’s not really accurate for NEAR Blockchain.

In the beginning there is a `Transaction`, it contains instructions we want to be executed on the blockchain. Transaction is sent to NEAR Blockchain.
And yes, it is executed there immediately BUT the immediate result of the transaction execution is always just *an acknowledgment that it will be executed on the chain;* this internal execution request is known as `Receipt`. You can think of the `Receipt` as an internal transaction that exists to pass information across shards.
Let’s get back to the tracks to look at the example.
Assuming we have two accounts living on different `Shards` **alice.near** and **bob.near**. **alice.near** creates a `Transaction` to send a few tokens to **bob.near**. The `Transaction` is immediately executed and the `ExecutionOutcome` for the `Transaction` is always a `Receipt`.
But this `Receipt` cannot be executed here, because **bob.near** doesn’t live on the same Shard as **alice.near**, so **the Receipt must be executed on the receiver’s Shard**. So the Receipt is moving to the Shard where **bob.near** belongs to.
On the destination Shard the Receipt is executed and the process is considered as done.
> [!NOTE]
>
> **The explanation here is simplified**
>
> Please refer to the [Token transfer](/protocol/data-flow/token-transfer-flow) flow article
So the final scheme will look like:

***
## Summary
We have learnt the main principles of how data is flowing in NEAR Protocol. We have found out that `Transaction` execute and the `ExecutionOutcome` of the Transaction is always a `Receipt`.
Now we know that `Receipt` is a main internal asset for NEAR Protocol blockchain and it has a power of traveling between `Shards`. We learnt the NEAR Data flow on a simple example. Of course in real life with more complex transactions that involve cross-contract calls, there will be more Receipts and ExecutionOutcomes.
We hope this article is useful and you will be able to build your dApps and indexers easily with the knowledge of how data is flowing in NEAR Protocol.
# Token transfer flow
Source: https://docs.near.org/protocol/data-flow/token-transfer-flow
Learn all steps involved on a token transfer.
This section explains the flow of token transfers in the NEAR Protocol, detailing how tokens are moved between accounts, the role of receipts, and the importance of gas refunds in the process.
# Token Transfer flow
In the [previous article](/protocol/data-flow/near-data-flow) we saw an example of token transfer between accounts found in different shards. That example was simplified and missed a few steps in the process. That was intentional, to keep the article and the video short yet explanatory, in order to give you a bigger picture for understanding concepts.
In this article we're going to have a look at the same data flow, but in detail and we will consider two additional scenarios:
* Token transfer between accounts found in different shards
* Token transfer between accounts found in the same shard
You may be asking what was missing in the previous explanation. The short answer is: **Gas Refunds** or simply **Refunds**.
If you don't know what **Gas** is, please [first read the article about Gas](/protocol/transactions/gas) from our docs.
As for *Refunds*, here's a quote from the [Gas](/protocol/transactions/gas) article:
> Attach extra gas; get refunded!
>
> ...
>
> * If you attach more gas than needed, you'll get refunded
>
> ...
>
> *From NEAR Protocol docs [Gas. Attach extra gas; get refunded!](/protocol/transactions/gas)*
> [!NOTE]
>
> **What refunds mean in terms of data flow**
>
> It means that literally every Transaction includes a refund.
OK, this should be enough for introduction, now let's move on to examples.
***
## Token transfer between accounts found in different shards
Basically it is an extension of the example from the [NEAR Data Flow](/protocol/data-flow/near-data-flow) article.
Assume we have two accounts **alice.near** and **bob.near**. They belong to different `Shards`. **alice.near** sends a few tokens to **bob.near**.
A `Transaction` signed by **alice.near** is sent to the network. It is immediately executed, `ExecutionOutcome` is the output or result from converting the transaction into a `Receipt`.

During the above process **alice.near**, the sender, was charged a fee (gas). The `Receipt` created as result of the `Transaction` follows these rules:
1. It will be executed not earlier than next `Block`
2. It **must** be executed on the receiver's `Shard`
So, in our case the receiver is **bob.near** and that account belongs to a different `Shard` that's why the `Receipt` moves to the receiver's Shard and is put in the execution queue.
In our example the Receipt is executed in the very next Block.

Almost done. Remember the refund? So the `ExecutionOutcome` for the Receipt will be another Receipt that is refunding the Gas to the sender. **bob.near** has received tokens from **alice.near**. Now, **alice.near** becomes the receiver for a new (and last) Receipt (keep in mind the sender in this Receipt is always **system**).
Keep in mind rule #2: the Receipt must be executed on the receiver's Shard. So this Receipt moves to the Shard where **alice.near** belongs to. And it is the last execution in this process.

This is it. Tokens have been transferred from the account on one Shard to the account on a different Shard, and the initial sender, **alice.near**, received a refund of Gas.
***
## Token transfer between accounts found on the same shard
Let's have a look at the example where both accounts are on the same `Shard`. The process is the same as in the previous example, except there are no Receipts moving from one Shard to another.
A `Transaction` signed by **alice.near** is sent to the network. It is immediately executed, `ExecutionOutcome` is the result of converting the transaction into a `Receipt`.

The Receipt is already on the receiver's Shard, so it is put in the execution queue of the next `Block`. It is executed in the next Block, and the `ExecutionOutcome` result is a new Receipt with the refund to the initial sender, **alice.near**.
The Same rules apply to this Receipt, it is put into the execution queue and executed in the next Block.

This is it. You may wonder why the process is overcomplicated for the same Shard case. The answer is: **the same rules are always applied**. Also, this mechanism allows to build the NEAR Protocol data flow by only one set of rules, no matter how many Shards exist. Also, we avoid a lot of "ifs" and we don't have to keep in mind different corner cases because the process always follows the same rules.
# Architectural Overview
Source: https://docs.near.org/protocol/network/architecture
Understand NEAR's accounts, transactions, data flow, tokens, storage, and network.
NEAR is a blockchain for applications built with smart contracts. Users interact with these applications through accounts and transactions, while validators process their activity across parallel parts of the network called shards.
***
## Accounts and smart contracts
An **account** holds a NEAR balance, access keys, and optionally a smart contract with its own storage. Access keys determine who can sign transactions and what those transactions can do.
A **smart contract** is code deployed to an account. Applications call its methods to update stored data, transfer assets, or interact with other contracts.
Learn more about [Accounts](/protocol/accounts-contracts/account-model) and [Access Keys](/protocol/accounts-contracts/access-keys).
***
## Transactions and receipts
A user signs a **transaction** to request actions, such as sending NEAR or calling a contract. NEAR processes these actions through **receipts**, internal messages that can produce further receipts when contracts call each other.
This means a transaction can lead to several steps of execution across the network. The [runtime](/protocol/network/runtime) applies the rules for executing these actions and updating account state.
See [Transactions](/protocol/transactions) and [Lifecycle of a Transaction](/protocol/transactions/transaction-execution) for the full process, and [Gas](/protocol/transactions/gas) for execution fees.
***
## Shards and data flow
NEAR distributes accounts across **shards** so the network can process activity in parallel. Accounts on different shards communicate through receipts.
See [NEAR Data Flow](/protocol/data-flow/near-data-flow) for how activity moves across shards, or follow a [Token Transfer](/protocol/data-flow/token-transfer-flow) through the network.
***
## Tokens
The [native NEAR token](/protocol/network/tokens) pays transaction fees, covers on-chain storage, and secures the network through validator staking.
Smart contracts can also define **fungible tokens**, **NFTs**, and **MultiTokens**. Shared [Token Standards](/protocol/network/token-standards) define how wallets and applications query and transfer these assets.
***
## Storage
Accounts and contracts store data on-chain, such as access keys, token balances, and application records. **Storage staking** reserves NEAR to cover the space this data occupies. Removing data releases the corresponding storage stake.
See [Storage Staking](/protocol/storage/storage-staking) for how storage is priced and managed.
***
## Network
[Validators](/protocol/network/validators) secure NEAR through proof of stake, producing and validating blocks and shard chunks. Validator assignments are updated in periods called [epochs](/protocol/network/epoch).
Applications run on [mainnet, testnet, or a local network](/protocol/network/networks). Mainnet is the live network; testnet and local networks let developers experiment before deploying there.
> [!NOTE]
>
> **Looking for the low-level details?**
>
> The [Nomicon](https://nomicon.io/) is where `nearcore` developers document the protocol specification - data structures, chain, network, runtime, and economics - and how `nearcore` works internally. You don't need it to build on NEAR.
# Epoch
Source: https://docs.near.org/protocol/network/epoch
Learn about epochs in NEAR Protocol, including their duration, role in validator selection, and how they affect network operations and data retention.
This section explains the concept of an **epoch** in the NEAR Protocol, which is a unit of time when validators of the network remain constant. It describes how epochs are measured, their duration, and their significance in the network's operation.
An **epoch** is a unit of time when validators of the network remain constant. It is measured in blocks:
* Both `testnet` and `mainnet` have an epoch duration of 43,200 blocks. Ideally epochs last 7.2 hours, since blocks are created every 0.6 seconds (in reality, they can take slightly shorter or longer to be created).
* You can view this setting by querying the **[`protocol_config`](/api/rpc/protocol#protocol-config)** RPC endpoint and searching for `epoch_length`.
**Note:** Nodes garbage collect blocks after 5 epochs (\~1.5 days) unless they are [archival nodes](https://near-nodes.io/intro/node-types#archival-node).
**Example:**
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "EXPERIMENTAL_protocol_config",
> "params": {
> "finality": "final"
> }
> }
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=EXPERIMENTAL_protocol_config \
> params:='{
> "finality": "final"
> }'
> ```
**Example Response:**
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"jsonrpc": "2.0",
"result": {
"protocol_version": 44,
"genesis_time": "2020-07-21T16:55:51.591948Z",
"chain_id": "mainnet",
"genesis_height": 9820210,
"num_block_producer_seats": 100,
"num_block_producer_seats_per_shard": [
100
],
"avg_hidden_validator_seats_per_shard": [
0
],
"dynamic_resharding": false,
"protocol_upgrade_stake_threshold": [
4,
5
],
"epoch_length": 43200,
"gas_limit": 1000000000000000,
"min_gas_price": "1000000000",
"max_gas_price": "10000000000000000000000",
"block_producer_kickout_threshold": 90,
"chunk_producer_kickout_threshold": 90,
// ---- snip ----
}
```
You can learn more about how epochs are used to manage network validation in the [Validator FAQ](https://github.com/near/wiki/blob/master/Archive/validators/faq.md#what-is-an-epoch).
# NEAR Networks
Source: https://docs.near.org/protocol/network/networks
Explore the different networks available in NEAR
NEAR Protocol operates on several networks, each with its own independent validators and unique state. These networks are designed to serve different purposes, from production-ready applications to testing and development environments.
***
## Overview of NEAR Networks
* [`mainnet`](/protocol/network/networks#mainnet)
* [`testnet`](/protocol/network/networks#testnet)
* [`localnet`](/protocol/network/networks#localnet)
***
## Mainnet
`mainnet` is for production ready smart contracts and live token transfers. Contracts ready for `mainnet` should have gone through rigorous testing and independent security reviews if necessary. `mainnet` is the only network where state is guaranteed to persist over time *(subject to the typical security guarantees of the network's validation process)*.
* Status: `https://rpc.mainnet.near.org/status`
* \[ [NearBlocks Explorer](https://nearblocks.io) ]
* \[ [Wallet](https://wallet.near.org) ]
* \[ [Epoch Sync](https://near-nodes.io/intro/node-epoch-sync) ]
***
## Testnet
`testnet` is a public network and the final testing network for `nearcore` changes before deployment to `mainnet`. `testnet` is intended for testing all aspects of the NEAR platform prior to `mainnet` deployment. From account creation, mock token transfers, development tooling, and smart contract development, the `testnet` environment closely resembles `mainnet` behavior. All `nearcore` changes are deployed as release candidates on first testnet, before the changes are released on `mainnet`. A number of `testnet` validators validate transactions and create new blocks. dApp developers deploy their applications on `testnet` before deploying on `mainnet`. It is important to note that `testnet` has its own transactions and states.
* Status: `https://rpc.testnet.near.org/status`
* \[ [Explorer](https://testnet.nearblocks.io) ]
* \[ [Create a Wallet](/getting-started/create-account#using-a-wallet) ]
* \[ [Epoch Sync](https://near-nodes.io/intro/node-epoch-sync) ]
***
## Localnet
`localnet` is intended for developers who want to work with the NEAR platform independent of the public blockchain. You will need to generate nodes yourself. `localnet` gives you the total control over accounts, economics, and other factors for more advanced use cases (including making changes to `nearcore`). For developers, `localnet` is the right choice if you prefer to avoid leaking information about your work during the development process.
More on local development [here](https://near-nodes.io/validator/running-a-node)
***
# Runtime
Source: https://docs.near.org/protocol/network/runtime
Explore NEAR Protocol's runtime system, including core runtime operations, cross-contract calls, action and data receipts, and state management.
The runtime applies NEAR's execution rules to transactions and receipts. It checks permissions, executes actions and smart contract code, updates account state, and accounts for gas and fees.
NEAR separates this execution logic from the blockchain layer, which handles consensus, block and chunk production, validator selection, and routing messages between shards. The sections below explain their responsibilities and include code walkthrough videos.
***
## Runtime Overview
The blockchain layer determines which transactions and receipts to process, and the runtime computes the resulting state changes. Keeping these responsibilities separate lets execution rules be described independently of how nodes communicate and reach consensus.
| Component | Responsibilities |
| - | - |
| Blockchain layer | Consensus, blocks and chunks, shard routing, state synchronization, and validator coordination |
| Runtime layer | Account permissions, action execution, contract execution, storage updates, and fee and reward accounting |
For example, the runtime creates an outgoing receipt addressed to a receiver account. The blockchain layer determines where to deliver it.
The video below walks through the runtime implementation.
[https://www.youtube-nocookie.com/embed/Xi\_8PapFCjo](https://www.youtube-nocookie.com/embed/Xi_8PapFCjo)
***
## Runtime Action and Data Receipts
Users submit signed transactions, while the runtime creates receipts when processing transactions or other receipts. Action receipts request operations on a receiver account; data receipts carry results needed by dependent calls.
During a contract call, the contract can read and write its own storage. It cannot directly access another account's contract storage, even when both accounts are on the same shard. Interactions with other contracts use asynchronous calls and callbacks, so applications should not depend on accounts being colocated.
See [Cross-contract Calls](/smart-contracts/anatomy/crosscontract) for the programming model and [Lifecycle of a Transaction](/protocol/transactions/transaction-execution) for execution stages.
The video below reviews how the runtime implements these interactions.
[https://www.youtube-nocookie.com/embed/RBb3rJGtqOE](https://www.youtube-nocookie.com/embed/RBb3rJGtqOE)
***
## Runtime State
Account state includes the NEAR balance, balance locked for validator staking, access keys, contract code or a reference to global code, and contract storage. Each account is assigned to a shard, which processes changes to that account's state.
NEAR stores shard state in **tries**, tree structures that associate keys with values and use hashes to verify their contents. Execution reads and updates this state; the blockchain layer handles synchronizing and validating state across nodes.
Contracts access their storage through the runtime's [storage functions](https://nomicon.io/RuntimeSpec/Components/BindingsSpec/TrieAPI.html). For implementation details, see [Trie Storage](https://nomicon.io/architecture/storage/trie_storage.html).
The video below explains how the runtime works with state.
[https://www.youtube-nocookie.com/embed/JCkSNL4ie1U](https://www.youtube-nocookie.com/embed/JCkSNL4ie1U)
# Avoiding Token Loss
Source: https://docs.near.org/protocol/network/token-loss
Learn about scenarios that can lead to token loss in NEAR Protocol and how to prevent them, including key management, account deletion, and smart contract failures.
This document outlines the common errors that can lead to token loss and how to avoid them.
> [!WARNING]
>
> Careful! Losing tokens means losing money!
> [!NOTE]
>
> **Building a frontend?**
>
> If your application lets users enter a recipient account, follow the [Validating Recipient Accounts](../../web3-apps/tutorials/account-validation) guide to catch typos and non-existent accounts before broadcasting a transaction.
Token loss is possible under multiple scenarios. These scenarios can be grouped into a few related classes:
1. Improper key management
2. Refunding deleted accounts
3. Failed function calls in batches
***
## Improper key management
Improper key management may lead to token loss. Mitigating such scenarios may be done by issuing backup keys
allowing for recovery of accounts whose keys have been lost or deleted.
### Loss of `FullAccess` key
A user may lose their private key of a `FullAccess` key pair for an account with no other keys.
No one will be able to recover the funds. Funds will remain locked in the account forever.
### Loss of `FunctionCall` access key
An account may have its one and only `FunctionCall` access key deleted.
No one will be able to recover the funds. Funds will remain locked in the account forever.
***
## Refunding deleted accounts
System refunds require an existing receiving account. If a refund cannot be delivered because the account no longer exists, its amount is burned.
### Deleting account with non-existent beneficiary
> [!WARNING]
>
> Never use `DeleteAccount` as a replacement for `Transfer`, including when moving an account's entire balance. If the beneficiary does not exist, the remaining balance is burned.
Deleting an account and paying its beneficiary happen in separate receipts:
1. Account `A` is deleted with account `B` as its beneficiary.
2. The runtime sends `A`'s remaining balance to `B` in a system payout receipt.
3. If `B` does not exist when that receipt executes, the payout fails and its amount is burned. The deletion of `A` is not rolled back.
Unlike an ordinary transfer, this system payout does not create an implicit account or generate another refund on failure. See the runtime's [account deletion](https://github.com/near/nearcore/blob/2.13.4/runtime/runtime/src/actions.rs#L399) and [failed system refund handling](https://github.com/near/nearcore/blob/2.13.4/runtime/runtime/src/lib.rs#L929).
To move funds and then close the source account:
1. Send a normal `Transfer`, leaving enough NEAR for transaction fees and any required storage balance.
2. Wait for finalized success and for all outstanding receipts and refunds to complete. If the transfer fails, resolve the failure before deleting the account.
3. Verify that the beneficiary exists, then submit a separate `DeleteAccount` transaction to send the remaining account balance, including any dust or released storage balance, to that beneficiary. Check the payout's finalized outcome as well.
Before deletion, also [withdraw any gas key balances](/integrations/errors/introduction#deleting-gas-keys-or-accounts-that-hold-gas-key-balances); they are not included in the beneficiary payout.
### Account deleted before it receives a refund
If an account is explicitly deleted while refunds are outstanding, those refunds can become undeliverable and be burned. Keep the account until all outstanding receipts and refund outcomes have finalized.
***
## Failed function calls in batches
> [!WARNING]
>
> When designing a smart contract, you should always consider the asynchronous nature of NEAR Protocol.
If a contract function `f1` calls two (or more) other functions `f2` and `f3`, and at least one of these functions, `f2` and `f3` fails, then tokens will be refunded from the function that failed, but tokens will be appropriately credited to the function(s) which succeed.
The successful call's tokens may be considered lost depending on your use case if a single failure in the batch means the whole batch failed.
# Token Standards
Source: https://docs.near.org/protocol/network/token-standards
Compare NEAR's smart contract standards for fungible tokens, NFTs, and MultiTokens.
Beyond the [native NEAR token](/protocol/network/tokens), smart contracts can define their own tokens. NEAR provides standards for fungible tokens, non-fungible tokens (NFTs), and MultiTokens, so wallets and applications can interact with them consistently.
Unlike native NEAR balances, these token balances and ownership records are stored in the **token contract**, which handles transfers and tracks each account's holdings.
| Token type | What it represents | Core standard |
| - | - | - |
| Fungible token (FT) | Interchangeable units, such as stablecoins or governance tokens | [NEP-141](https://github.com/near/NEPs/blob/master/neps/nep-0141.md) |
| Non-fungible token (NFT) | Individually identified assets, such as collectibles or event tickets | [NEP-171](https://github.com/near/NEPs/blob/master/neps/nep-0171.md) |
| MultiToken (MT) | Multiple token types managed by one contract, including fungible and non-fungible assets | [NEP-245](https://github.com/near/NEPs/blob/master/neps/nep-0245.md) |
***
## Fungible tokens
Each FT contract tracks balances of one fungible token. Units of that token are interchangeable: transferring 10 units reduces the sender's balance by 10 and increases the receiver's balance by 10.
See the [FT standard](/primitives/ft/standard) for the interface, or [Using FTs](/primitives/ft/ft) for querying balances and transferring tokens.
***
## Non-fungible tokens
An NFT contract tracks individually identified tokens and their owners. Each token has a unique ID within its contract and can carry metadata describing the asset it represents.
See the [NFT standard](/primitives/nft/standard) for the interface, or [Using NFTs](/primitives/nft/nft) for querying and transferring NFTs.
***
## MultiTokens
A MultiToken contract manages multiple token types, each identified by a token ID, and tracks each account's balance for each ID. It can represent fungible, non-fungible, and semi-fungible assets in one contract and transfer multiple token types in a batch.
See [NEP-245](https://github.com/near/NEPs/blob/master/neps/nep-0245.md) for the MultiToken interface and extensions.
# NEAR Native Token
Source: https://docs.near.org/protocol/network/tokens
Use NEAR to pay transaction fees, cover on-chain storage, and secure the network through staking.
NEAR (Ⓝ) is the native token of NEAR Protocol. You can transfer it between accounts, use it to pay for network resources, and stake it to help secure the network.
***
## Transaction fees
Transactions consume **gas**, which measures the computation needed to execute their actions. The sender pays for gas in NEAR.
See [Gas and execution fees](/protocol/transactions/gas) for how fees are calculated.
***
## Storage staking
Accounts must maintain enough NEAR to cover the data they store on-chain. These tokens remain locked while the storage is in use; removing data releases the corresponding storage stake.
See [Storage Staking](/protocol/storage/storage-staking) for storage costs and requirements.
***
## Validator staking
NEAR uses proof of stake to secure the network. Token holders can delegate NEAR to validators, which process transactions and produce blocks, and receive a share of staking rewards.
See [Validators](/protocol/network/validators) for how validators work, or follow [Staking NEAR Tokens](/protocol/tutorials/staking-tokens) to delegate and withdraw tokens.
> [!TIP]
>
> Smart contracts can also define their own tokens. See [Token Standards](/protocol/network/token-standards) for fungible tokens, NFTs, and MultiTokens.
# Validators
Source: https://docs.near.org/protocol/network/validators
Learn about NEAR Protocol validators, their roles in network security, consensus mechanisms, validator economics, and how to become a validator.
At its core, NEAR Protocol is a decentralized blockchain that operates on a network of independent participants called validators who process transactions and secure the network.
These validators must reach consensus, meaning they need to agree on which transactions are valid and should be added to the blockchain. This ensures no one steals funds, double-spend tokens, or manipulates the system.
NEAR validators use [Proof-of-Stake (PoS)](https://en.wikipedia.org/wiki/Proof_of_stake), a consensus mechanism that secures the network through economic incentives rather than energy-intensive computational power. Unlike Bitcoin's [proof-of-work](https://en.wikipedia.org/wiki/Proof_of_work) system that requires massive amounts of electricity, PoS makes the network environmentally sustainable while maintaining robust security.
In Proof-of-Stake, users demonstrate support for specific validators by delegating their NEAR tokens through a process called staking. The principle is straightforward: validators with more delegated tokens are trusted by the community to keep the network safe. Validators that produce too few of their assigned blocks, chunks, or chunk endorsements earn less or no reward, and can be removed from the validator set.
### Securing the Network
Validators have two main jobs. The first is to validate and execute transactions, aggregating them in the blocks that form the blockchain. Their second job is to oversee other validators, making sure no one produces an invalid block or creates an alternative chain (eg. with the goal of creating a double spend).
NEAR does not slash (burn) staked tokens. A validator that is offline or underperforms loses its rewards and can be removed from the validator set.
Every block needs approvals from block producers that hold more than two thirds of the block producers' stake. To produce blocks without the other validators, an attacker would need validators with that much stake, which requires a huge amount of capital. If block producers that hold one third or more of that stake stop sending approvals, no new blocks can be produced.
### Validator's Economy
In exchange for servicing the network, validators are rewarded with NEAR every epoch. The yearly reward budget is 2.5% of the total supply. 10% of the reward budget goes to the protocol treasury. The rest is shared by validators, as described under Block & Chunk producers below.
The system burns the transaction fees collected in each epoch. On protocol version 86 and earlier, contracts receive 30% of the gas they burn as a rebate, so that part is not burned. From protocol version 87 (nearcore 2.14.0), all of it is burned. The inflationary reward is paid out to validators at the same rate regardless of the number of fees collected or burned.
***
## Intro to Validators
[Validators](https://www.near.org/papers) are responsible for producing and validating blocks and chunks, ensuring the security and integrity of the NEAR network.
The hardware requirements for running a validator node vary depending on the staking position. Detailed specifications can be found here: [the hardware requirements](https://near-nodes.io/validator/hardware-validator).
> [!NOTE]
>
> The `public_key` in a [`Stake` action](/protocol/transactions/transaction-anatomy#actions) is the validator's block-production key and must use `ed25519`. This is separate from the access key that signs the transaction, which can use any [supported signature scheme](/protocol/accounts-contracts/access-keys#signature-schemes), including `ml-dsa-65`.
You can view the list of currently active validators on platforms like [NEAR-STAKING](https://near-staking.com/stats). Mainnet has 500 validator seats. If 500 or more proposals pass the minimum stake ratio, the seat price is one yoctoNEAR more than the stake of the 500th largest proposal. Otherwise the seat price is set by the minimum stake ratio: a validator's stake must be more than 1/62,500 of the total stake of all selected validators. There is no fixed minimum amount in `$NEAR`. The current seat price to join the active validator set is updated in real-time on [NEAR BLOCKS](https://nearblocks.io/node-explorer). Any validator node with a stake greater than the current seat price can join the set of active validators.
> [!TIP]
>
> **Is there a plan to support GPU compute if certain validator nodes can offer that or is it just CPU?**
>
> We don't need GPU support as we are a POS chain and we require very little compute power.
>
> You can read more about our consensus strategy on our [Validator Quickstart](https://github.com/near/wiki/blob/master/Archive/validators/about.md) and [Staking FAQ](https://github.com/near/wiki/blob/master/Archive/validators/faq.md).
***
## Block & Chunk producers
The top 100 validators are responsible for producing and validating blocks, as well as producing chunks. Under normal circumstances, each validator is assigned to a single shard, for which it produces chunks.
The yearly reward budget is 2.5% of the total supply. 10% of the budget goes to the protocol treasury, and validators share the rest in proportion to stake. A validator's yearly yield is therefore about 2.25% times the total supply divided by the total stake. Validators with less than 90% uptime in an epoch get no reward for that epoch, and the reward is reduced between 90% and 99% uptime. Rewards that validators do not earn are not minted.
***
## Chunk Validators
\[Note] Block & Chunk producers also serve as chunk validators.
Non-top 100 validators take on the role of chunk validators, which has lower hardware and staking requirements, making it more accessible. This role helps expand the network's validator set, increasing opportunities to earn rewards and strengthen the security of the NEAR ecosystem.
Chunk validators do not track shards. Their responsibilities are focused solely on validating and endorsing chunks.
Chunk validators earn rewards from the same pool as block and chunk producers, in proportion to stake. There is no guaranteed minimum rate. A chunk validator that sends at least 70% of its expected chunk endorsements in an epoch gets its full share. Below 70% it gets no reward and is normally removed from the validator set. For more details on validator economics, check out [NEAR’s Economics Explained](https://near.org/blog/near-protocol-economics/).
***
## Sunsetting a staking pool
If you operate a pool and want to wind it down, follow [Sunsetting a Staking Pool](/protocol/tutorials/sunsetting-a-staking-pool) to pause staking and help delegators withdraw their funds.
***
## Dedicated Validator Documentation Site
If you'd like to further explore Validators and Nodes in general, you can visit the [Dedicated Validator Documentation Site](https://near-nodes.io/).
> [!TIP]
>
> **If a developer writes a vulnerable or malicious dApp, is a validator implicitly taking on risk?**
>
> No. We have handled the potential damages to the network on the protocol level. For example, we have a lot of limiters that constrain how much data you can pass into a function call or how much compute you can do in one function call, etc.
>
> That said, smart contract developers will need to be responsible for their own dApps, as there is no stage gate or approval process. All vulnerabilities can only damage the smart contract itself. Luckily, updating smart contracts is very smooth on NEAR, so vulnerabilities can be updated/patched to an account in ways that cannot be done on other blockchains.
# Storage
Source: https://docs.near.org/protocol/storage/storage-staking
Learn about NEAR Protocol's storage staking mechanism, including costs, storage pricing, attack prevention, and strategies for managing on-chain data storage.
NEAR's storage staking is a mechanism that ensures the network remains efficient and secure by requiring smart contract owners to stake tokens based on the amount of data their contracts store. This helps maintain the integrity of the network while providing a predictable cost structure for developers.
> When you deploy a smart contract to NEAR, you pay for the storage that this contract requires using a mechanism called storage staking.
>
> In storage staking (sometimes called *state* staking), the account that owns a smart contract must stake (or lock) tokens according to the amount of data stored in that smart contract, effectively reducing the balance of the contract's account.
***
## How does NEAR's design align incentives?
Storage-staked tokens are unavailable for other uses, such as validation staking. This increases the yield that validators will receive. Learn more in [the economics whitepaper](https://pages.near.org/papers/economics-in-sharded-blockchain/).
***
## When do tokens get staked?
On each incoming transaction that adds data.
Let's walk through an example:
1. You launch [a guest book app](https://github.com/near-examples/guest-book-examples), deploying your app's smart contract to the account `example.near`
2. Visitors to your app can add messages to the guest book. This means your users will, [by default](/protocol/transactions/gas#understanding-gas-fees), pay a small gas fee to send their message to your contract.
3. When such a call comes in, NEAR will check that `example.near` has a large enough balance that it can stake an amount to cover the new storage needs. If it does not, the transaction will fail.
***
## The "million cheap data additions" attack
Note that this can create an attack surface. To continue the example above, if sending data to your guest book costs users close to nothing while costing the contract owner significantly more, then a malicious user can exploit the imbalance to make maintaining the contract prohibitively expensive.
Take care, then, when designing your smart contracts to ensure that such attacks cost potential attackers more than it would be worth.
***
## btw, you can remove data to unstake some tokens
People familiar with the "immutable data" narrative about blockchains find this surprising. While it's true that an *indexing node* will keep all data forever, *validating nodes* (that is, the nodes run by most validators in the network) do not. Smart contracts can provide ways to delete data, and this data will be purged from most nodes in the network within a few [epochs](../network/epoch).
Note that a call to your smart contract to remove data has an associated gas fee. Given NEAR's gas limit, this creates an upper limit on how much data can be deleted in a single transaction.
***
## How much does it cost?
Storage staking is priced in an amount set by the network, which is set to **1E19 yoctoNEAR per byte**, or **100kb per NEAR token (Ⓝ)**. [\[1\]](https://gov.near.org/t/storage-staking-price/399) [\[2\]](https://github.com/near/nearcore/pull/3881)
NEAR's JSON RPC API provides [a way to query this initial setting](/api/rpc/protocol#genesis-config) as well as a [a way to query the live config / recent blocks](/api/rpc/protocol#protocol-config).
> [!NOTE]
>
> An account can occupy up to `770` bytes without staking anything. That allowance is paid for once, with the fixed `0.007Ⓝ` charged when [creating the account](/protocol/transactions/gas#creating-an-account).
***
## Example cost breakdown
Let's walk through an example.
A [non-fungible token](https://github.com/near/NEPs/pull/4) is unique, which means each token has its own ID. The contract must store a mapping from token IDs to owners' account ID.
If such an NFT is used to track **1 million** tokens, how much storage will be required for the token-ID-to-owner mapping? And how many tokens will need to be staked for that storage?
Let's calculate the storage needs when using a `PersistentMap` that stores data as UTF-8 strings.
Here's our `PersistentMap`:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
type AccountId = string;
type TokenId = u64;
const tokenToOwner = new PersistentMap("t2o");
```
Behind the scenes, all data stored on the NEAR blockchain is saved in a key-value database. That `'t2o'` variable that's passed to `PersistentMap` helps it keep track of all its values. If your account `example.near` owns token with ID `0`, then at the time of writing, here's the data that would get saved to the key-value database:
* key: `t2o::0`
* value: `example.near`
So for 1 million tokens, here are all the things we need to add up and multiply by 1 million:
1. The prefix, `t2o`, will be serialized as three bytes in UTF-8, and the two colons will add another two. That's 5 bytes.
2. For an implementation where `TokenId` auto-increments, the values will be between `0` and `999999`, which makes the average length 5 bytes.
3. Let's assume well-formed NEAR `AccountId`s, and let's guess that NEAR Account IDs follow the approximate pattern of domain names, which [average about 10 characters](https://www.gaebler.com/Domain-Length-Research.htm), plus a top-level name like `.near`. So a reasonable average to expect might be about 15 characters; let's keep our estimate pessimistic and say 25. This will equal 25 bytes, since NEAR account IDs must use characters from the ASCII set.
4. The protocol adds a fixed 40 bytes for every key-value record (the `storage_num_extra_bytes_record` parameter), on top of the key and value bytes.
So:
1\_000\_000 \* (5 + 5 + 25 + 40)
That is 75 million bytes. At 1e19 yoctoNEAR per byte (1 NEAR per 100,000 bytes), the `tokenToOwner` mapping needs 7.5e26 yoctoNEAR, or Ⓝ750, kept on the account balance.
Note that you can get this down to Ⓝ730 just by changing the prefix from `t2o` to a single character. Or get rid of it entirely! One collection in your contract can have a zero-length prefix. If this map had one, its keys would keep only the two colons, and you could get it down to Ⓝ720. The 40 bytes per record cannot be avoided, so fewer, larger records cost less than many small ones.
***
## Calculate costs for your own contract
Doing manual byte math as shown above is difficult and error-prone. Good news: you don't have to!
You can test the storage used using the [SDK environment](../../smart-contracts/anatomy/environment) and checking `env.storage_usage()`
***
## Other ways to keep costs down
Storing data on-chain isn't cheap for the people running the network, and NEAR passes on this cost to developers. So, how do you, as a developer, keep your costs down? There are three popular approaches:
1. Don't store what you can index or derive
2. Use a binary serialization format, rather than JSON
3. Store data off-chain
### Don't store what you can index or derive
The cheapest data is the data you never store. Transactions already record every call to your contract, including its arguments and attached tokens, so data that your app only displays can be read back with an [indexer or data service](/data-infrastructure/what-is). Likewise, never store values you can compute from other stored values. See [A contract is not a backend](/smart-contracts/what-is#a-contract-is-not-a-backend).
### Use a binary serialization format, rather than JSON
The core NEAR team maintains a library called [borsh](https://borsh.io/),
which is used automatically when you use `near-sdk-rs`.
Imagine that you want to store an array like `[0, 1, 2, 3]`. You could serialize it as a JSON string and store it as UTF-8 bytes. Cutting out spaces, you end up using 9 bytes.
Using borsh, this same array gets saved as 8 bytes:
\u0004\u0000\u0000\u0000\u0000\u0001\u0002\u0003
At first glance, saving 1 byte might not seem significant. But let's look closer.
The first four bytes here, `\u0004\u0000\u0000\u0000`, tell the serializer that this is a `u32` array of length `4` using little-endian encoding. The rest of the bytes are the literal numbers of the array – `\u0000\u0001\u0002\u0003`. As you serialize more elements, each will add one byte to the data structure. With JSON, each new element requires adding two bytes, to represent both another comma and the number.
In general, Borsh is faster, uses less storage, and costs less gas. Use it if you can.
### Store data off-chain
For large files or user-generated content, store the data off-chain and keep only a content identifier or hash in your contract. This keeps on-chain records small and storage costs predictable.
You can use decentralized storage such as [IPFS](https://docs.ipfs.tech/), [Arweave](https://docs.arweave.org/), or [Crust](https://wiki.crust.network/). Follow the provider's documentation for uploading data and keeping it available.
***
## Summary
NEAR's structure incentivizes network operators while giving flexibility and predictability to contract developers. Managing storage is an important aspect of smart contract design, and NEAR's libraries make it easy to figure out how much storage will cost for your application.
***
## Footnotes
1. [Storage staking price](https://gov.near.org/t/storage-staking-price/399)
2. [Lower storage cost 10x](https://github.com/near/nearcore/pull/3881)
# Gas (Execution Fees)
Source: https://docs.near.org/protocol/transactions/gas
Learn about NEAR's gas system - execution fees that prevent spam and use deterministic gas units with dynamic pricing.
This section explains how gas works in the NEAR Protocol, including how it is calculated and charged.
On every transaction the NEAR network charges a tiny fee known as **gas**. This fee is a simple mechanism that allows us to:
1. **Prevent** bad actors from **spamming** the network with useless transactions
2. **Burn** a minuscule fraction of the **token supply** on each transaction
3. Implement a **wall time** by capping how much gas each chunk can burn to `1000Tgas` (\~`1000ms` of compute time)
On protocol version 86 and earlier, contracts also receive 30% of the gas they burn while executing. From protocol version 87 (nearcore 2.14.0), all of it is burned.
Gas in NEAR is computed on [**gas units**](/protocol/transactions/gas#gas-units) and charged using `$NEAR` tokens based on the network's [**gas price**](/protocol/transactions/gas#gas-price).
> [!TIP]
>
> **Did you know?**
> In NEAR, attaching extra gas to a transaction does **not** make it faster. Actions cost a fixed amount of gas, and any extra gas attached is simply sent back to the user
***
## Understanding Gas Fees
For every transaction, users get charged a small NEAR fee which has to be paid **upfront**. This fee is calculated using deterministic **gas units**, and transformed into a cost in NEAR using the network's **gas price**.
### Gas Units
Every action in NEAR costs a fixed amount of **gas units**, meaning that the same operation will always cost the **same amount of gas units**.
Gas units were engineered in such a way that they can be translated into compute resources, where `1Tgas` gets you approx. `1ms` of compute time.
Each chunk can burn at most `1000Tgas`, i.e. about `1000ms` of compute, which is what allows the network to produce a new block approximately **every second**.
A single transaction can attach at most **1 PGas (1,000 TGas)** in total across all its function-call actions. It may spend that gas in one receipt or spread it over the receipts it spawns across several blocks. This gas limit is separate from the [1.5 MiB transaction size limit](/protocol/transactions/transaction-anatomy#transaction-limits).
> [!TIP]
>
> Gas units encapsulate not only compute/CPU time but also bandwidth/network time and storage/IO time
### Gas Price
To determine the actual NEAR fee, the cost of all actions in the transaction is multiplied by a **gas price**.
The gas price is **recalculated each block** based on the network's demand and floor at `1Tgas = 0.0001Ⓝ`.
If the previous block is **more than half full** the price goes up by 1%, otherwise it goes down by 1% (until it reaches the floor).
> [accordion] What is the gas price now?
>
> You can query how much a gas unit costs in `yoctoNEAR` (1Ⓝ = `1e24` yocto) through the [`RPC`](/api/rpc/gas#gas-price). To convert in `Tgas` per `NEAR`, you can use the following formula: `gas_price * 1e12 / 1e24`.
>
> Right now, 1 Tgas costs: Ⓝ
### Buying vs. Burning Gas
Gas is **bought** at one price and **burned** at another. There's `min_gas_purchase_price = 0.001Ⓝ per Tgas`.
* **Buy price**: `max(current_gas_price, min_gas_purchase_price)`. This is what is deducted from your account upfront for the gas attached to the transaction
* **Burn price**: `min(buy_price, current_gas_price)` - This is what the gas actually costs while executing. The gas price at the moment of execution, but never higher than the buy price.
You buy gas at a price that can be higher than the price it burns at, and **the difference is always refunded to you**. The cost of a transaction is therefore the same as if there were a single price - you just need the larger amount in your account at the moment you send it.
> [!TIP]
>
> At the minimum gas price (`0.0001Ⓝ` per `Tgas`), buying `100Tgas` deducts `0.1Ⓝ` from your balance. If the transaction burns `50Tgas`, you get `0.095Ⓝ` back: `0.05Ⓝ` for the gas you didn't use, and `0.045Ⓝ` for the price difference on the gas you did. You paid `0.005Ⓝ`, exactly what those `50Tgas` are worth at the gas price.
The point of buying above the burn price is that it leaves the protocol a refund it can charge from **after** it has seen what a transaction actually did. That is how [creating an account](#creating-an-account) is priced.
### Cost for Common Actions
Knowing that actions have a fixed cost in gas units, we can calculate the cost of common operations at the minimum gas price of `1Tgas = 0.0001Ⓝ`.
| Action | TGas | Fee (Ⓝ) |
| - | - | - |
| Create Account\*\*\* | 7.92 | 0.00707 |
| Transfer NEAR | 0.45 | 0.000045 |
| Add Full Access Key | 0.42 | 0.000042 |
| Delete Key | 0.41 | 0.000041 |
| Function Call\* | ≤ 1000 | ≤ 0.1 |
| Deploying a `16`kb contract | 2.65 | 0.000265 |
| Deploying a `X`kb contract\*\* | 0.58 + 0.13`X` | |
*Note that the fee is in NEAR, to obtain the cost in dollars multiply by the current price of `$NEAR`*
> [!TIP]
>
> **Function Calls\***
> The cost of calling a function will depend on how complex the function is, but will be consistent across function calls. Learn more below.
> [!TIP]
>
> **Deploying a Contract\*\***
> Note that this covers the gas cost of uploading and writing bytes to storage, but does **not** cover the cost of holding them in storage (which is `1Ⓝ ~ 100kb`).
> [!TIP]
>
> **Creating an Account\*\*\***
> Most of this fee is not gas: creating an account costs a fixed `0.007Ⓝ` that pays for the state the account permanently occupies. See [below](#creating-an-account).
> [accordion] Where do these numbers come from?
>
> NEAR is [configured](https://github.com/near/nearcore/blob/master/core/parameters/res/runtime_configs/parameters.yaml) with base costs. An example:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> transfer_cost: {
> send_sir: 115123062500,
> send_not_sir: 115123062500,
> execution: 115123062500
> },
> deploy_contract_cost: 184765750000,
> deploy_contract_cost_per_byte: 64572944
> ```
>
> The "sir" here stands for "sender is receiver". Yes, these are all identical, but that could change in the future.
>
> When you make a request to transfer funds, NEAR immediately deducts the appropriate `send` amount from your account. Then it creates a [*receipt*, an internal book-keeping mechanism](./transaction-execution). Creating a receipt has its own associated costs:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> action_receipt_creation_config: {
> send_sir: 108059500000,
> send_not_sir: 108059500000,
> execution: 108059500000
> }
> ```
>
> You can query this value by using the [`protocol_config`](/api/rpc/protocol#protocol-config) RPC endpoint and search for `action_receipt_creation_config`.
>
> The appropriate amount for creating this receipt is also immediately deducted from your account.
>
> The "transfer" action won't be finalized until the next block. At this point, the `execution` amount for each of these actions will be deducted from your account.
>
> Gas prices can change between the time of purchase and the time of execution, but a transaction is not affected by that. The `execution` part is bought at the [buy price](#buying-vs-burning-gas) and burned at `gas_price`, with the difference refunded, so what you end up paying is:
>
> ```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
> (
> transfer_cost.send_not_sir + action_receipt_creation_config.send_not_sir + transfer_cost.execution + action_receipt_creation_config.execution
> ) * gas_price
> ```
### Creating an Account
Creating an account costs a **fixed `0.007Ⓝ`**, which is burned.
This is not a gas fee. The protocol charges it by **making the refund smaller**: when a receipt creates an account, it keeps back enough of the [price difference refund](#buying-vs-burning-gas) to bring the total cost of the creation up to `0.007Ⓝ`. You don't pay an extra fee, you simply get less back.
If the gas burned while creating the account is already worth more than `0.007Ⓝ` - which happens when the network's gas price is high - nothing is kept back and you just pay the gas.
The charge applies however the account is created: a `CreateAccount` action, a transfer to a [not-yet-existing implicit account](/protocol/accounts-contracts/account-id#implicit-address), a `DeterministicStateInit` action, or a contract creating a sub-account.
> [!NOTE]
>
> **Why does creating an account cost extra?**
>
> Every account occupies state that the nodes running its shard have to keep forever. An account can occupy up to `770` bytes without a [storage deposit](/protocol/storage/storage-staking), and at the storage price of `1Ⓝ` per `100kb` that space is worth about `0.0077Ⓝ`. The charge makes sure that space is paid for. It lands slightly below `0.0077Ⓝ` because the protocol can only hold back as much as the price difference on the gas burned while creating the account.
***
## How Do I Buy Gas?
You don't buy gas, instead, the gas fee is automatically removed from your account's balance when the transaction [is first processed](./transaction-execution#block-1-the-transaction-arrives) based on the action's gas cost and the [buy price](#buying-vs-burning-gas).
> [!NOTE]
>
> Transactions signed with a [gas key](/protocol/accounts-contracts/gas-keys) instead pay their gas fee from the key's own prepaid balance, and gas refunds return to the key.
The only exception to this rule is when you make a function call to a contract. In this case, you need to define how many gas units to use, up to a maximum value of `1000Tgas`. This amount will be converted to NEAR using the [buy price](#buying-vs-burning-gas) and deducted from your account's balance.
Anything you overpaid is **refunded to your account** one block later. This covers both the gas you attached but did not use, and the difference between the buy price and the burn price. Because of that second part, **almost every transaction gets a refund**, even one that attached exactly the right amount of gas.
> [accordion] Gas Refund Fee
>
> Since protocol version 78, the unspent gas at the end of receipt execution is subject to a gas refund fee. The fee is still at 0 while we give projects time to adapt. The plan is to move to a fee calculated as `max(1 Tgas, 0.05 * unspent_gas) * gas_price`. The gas price used is the burn price.
>
> *But why introducing such a fee instead of refunding all gas?*
>
> The reason is that attaching too much gas to function calls makes the network less efficient.
>
> Congestion control between shards gets tricky when transactions have much more gas attached than they actually use. The network limits how many cross contract calls can target a single shard per chunk, to avoid huge queues of incoming receipts on a shard. This limit sees the attached gas as an upper boundary for how much work the receipt causes on the receiving shard. Attaching too much gas can cause this limit to become too restrictive, which stalls shards unnecessarily.
>
> The other inefficiency comes from the refund receipts that are created for essentially every function call. While each of them is relatively cheap to execute, in the sum they are a significant part of the global traffic on NEAR Protocol. Note that a refund receipt is needed for essentially every function call anyway, to return the price difference, so the fee only helps with congestion control.
> [!TIP]
>
> In other chains, paying a higher gas price gets your transaction processed faster. In NEAR, **gas costs are deterministic**, and you **can't pay to get priority**. Any extra gas attached to a transaction is refunded, minus some fee for attaching unnecessary gas.
***
## Estimating Costs for a Call
If you're developing a smart contract, you might want to estimate how much gas a function call will consume. This is useful to estimate limits for your function and avoid running into out-of-gas errors.
One of the most accurate ways to estimate gas costs is by running your function in `testnet`. To know exactly how much gas a specific part of your function uses, you can use the `used_gas` method from our SDK.
For local tests, use [`near-sandbox` with `near-api`](/smart-contracts/testing/integration-test) to deploy and call your contract on a local NEAR node. Inspect the transaction and receipt outcomes to measure the gas burnt, including any cross-contract calls.
# Transactions
Source: https://docs.near.org/protocol/transactions/index
Learn how users interact with NEAR through transactions composed of actions, signed with private keys, and processed by the network with deterministic gas costs.
Users interact with NEAR by creating transactions. Specifically, users use their account's [private keys](../accounts-contracts/access-keys) to sign transactions, which are then broadcasted and processed by the network.

A transaction is composed of one or more [`Actions`](./transaction-anatomy), and each action costs a deterministic amount of [gas units](./gas). These gas units are translated into a cost in NEAR tokens, which the user must pay for the transaction to be processed.
> [!TIP]
>
> You can use an [Explorer](https://nearblocks.io/) to inspect transactions in the NEAR network
# Meta Transactions
Source: https://docs.near.org/protocol/transactions/meta-tx
Learn about NEP-366 meta transactions on NEAR, allowing users to execute transactions without owning gas tokens by using relayers to cover transaction fees.
[NEP-366](https://github.com/near/NEPs/pull/366) introduced the concept of meta transactions to Near Protocol. This feature allows users to execute transactions on NEAR without owning any gas or tokens. In order to enable this, users construct and sign transactions off-chain. A third party (the relayer) is used to cover the fees of submitting and executing the transaction.
***
## Overview

*Credits for the diagram go to the NEP authors Alexander Fadeev and Egor
Uleyskiy.*
The graphic shows an example use case for meta transactions. Alice owns an
amount of the fungible token `$FT`. She wants to transfer some to John. To do
that, she needs to call `ft_transfer("john", 10)` on an account named `FT`.
The problem is, Alice has no NEAR tokens. She only has a NEAR account that
someone else funded for her and she owns the private keys. She could create a
signed transaction that would make the `ft_transfer("john", 10)` call. But
validator nodes will not accept it, because she does not have the necessary Near
token balance to purchase the gas.
With meta transactions, Alice can create a `DelegateAction`, which is very
similar to a transaction. It also contains a list of actions to execute and a
single receiver for those actions. She signs the `DelegateAction` and forwards
it (off-chain) to a relayer. The relayer wraps it in a transaction, of which the
relayer is the signer and therefore pays the gas costs. If the inner actions
have an attached token balance, this is also paid for by the relayer.
On chain, the `SignedDelegateAction` inside the transaction is converted to an
action receipt with the same `SignedDelegateAction` on the relayer's shard. The
receipt is forwarded to the account from `Alice`, which will unpacked the
`SignedDelegateAction` and verify that it is signed by Alice with a valid Nonce,
etc. If all checks are successful, a new action receipt with the inner actions
as body is sent to `FT`. There, the `ft_transfer` call finally executes.
***
## Relayer
Meta transactions only work with an off-chain service known as `relayer`. Think of it as a server that accepts a `SignedDelegateAction`, does some checks on them and eventually forwards it inside a transaction to the network.
> [!TIP]
>
> Want to build a relayer? Check out the [Relayer Guide](/web3-apps/tutorials/meta-transactions)
A relayer may choose to offer their service for free but that's not going to be
financially viable long-term. But they could easily have the user pay using
other means, outside of Near blockchain. And with some tricks, it can even be
paid using fungible tokens on Near.
In the example visualized above, the payment is done using $FT. Together with
the transfer to John, Alice also adds an action to pay 0.1 $FT to the relayer.
The relayer checks the content of the `SignedDelegateAction` and only processes
it if this payment is included as the first action. In this way, the relayer
will be paid in the same transaction as John.
> [!WARNING]
>
> **Keep in mind**
> The payment to the relayer is still not guaranteed. It could be that
> Alice does not have sufficient `$FT` and the transfer fails. To mitigate, the
> relayer should check the `$FT` balance of Alice first.
Unfortunately, this still does not guarantee that the balance will be high
enough once the meta transaction executes. The relayer could waste NEAR gas
without compensation if Alice somehow reduces her \$FT balance in just the right
moment. Some level of trust between the relayer and its user is therefore
required.
> [accordion] Technical Details
>
> Technically, the end user (client) creates a `SignedDelegateAction` that contains the data necessary to construct a `Transaction`, signs the `SignedDelegateAction` using their key, and send it to the relayer service.
>
> When the request is received, the relayer uses its own key to sign a `Transaction` using the fields in the `SignedDelegateAction` as input to create a `SignedTransaction`.
>
> The `SignedTransaction` is then sent to the network via RPC call, and the result is sent back to the client. The `Transaction` is executed in such a way that the relayer pays the GAS fees. The inner actions run with the user as the predecessor (`predecessor_account_id`), but the signer (`signer_account_id` and `signer_account_pk`) is still the relayer. A contract that should accept meta transactions must identify the user by `predecessor_account_id`, not by `signer_account_id`.
> [accordion] Why using a relayer?
>
> There are multiple reasons to use a relayer:
>
> 1. Your users are new to NEAR and don't have any gas to cover transactions
> 2. Your users have an account on NEAR, but only have a Fungible Token Balance. They can now use the FT to pay for gas
> 3. As an enterprise or a large startup you want to seamlessly onboard your existing users onto NEAR without needing them to worry about gas costs and seed phrases
> 4. As an enterprise or large startup you have a user base that can generate large spikes of user activity that would congest the network. In this case, the relayer acts as a queue for low urgency transactions
> 5. In exchange for covering the gas fee costs, relayer operators can limit where users spend their assets while allowing users to have custody and ownership of their assets
> 6. Capital Efficiency: Without relayer if your business has 1M users they would have to be allocated 0.25 NEAR to cover their gas costs totalling 250k NEAR. However, only \~10% of the users would actually use the full allowance and a large amount of the 250k NEAR is just sitting there unused. So using the relayer, you can allocate 50k NEAR as a global pool of capital for your users, which can refilled on an as needed basis.
***
## DelegateV2: Meta Transactions with Gas Keys
> [!WARNING]
>
> Protocol version 86 allowed users to sign `DelegateV2` actions with [gas keys](/protocol/accounts-contracts/gas-keys) to create meta transactions. From protocol version 87 (nearcore 2.14), `DelegateV2` is removed and new transactions containing it are rejected with `RemovedProtocolFeature`.
>
> Users must sign the inner delegate action with a regular access key. Relayers can still sign the wrapping transaction with their own gas keys to pay for gas.
***
## Limitations
Relayers can cover transaction fees, but the sender still needs an initialized account, and each meta transaction targets a single receiver.
### Single receiver
A meta transaction, like a normal transaction, can only have one receiver. It's
possible to chain additional receipts afterwards. But crucially, there is no
atomicity guarantee and no roll-back mechanism.
### Accounts must be initialized
Any transaction, including meta transactions, must use NONCEs to avoid replay
attacks. The NONCE must be chosen by Alice and compared to a NONCE stored on
chain. This NONCE is stored on the access key information that gets initialized
when creating an account.
The user must sign the delegate action with a regular access key and use that key's nonce.
***
## Constraints on the actions inside a meta transaction
A transaction is only allowed to contain one single delegate action. Nested
delegate actions are disallowed and so are delegate actions next to each other
in the same receipt.
***
## Gas costs for meta transactions
Meta transactions challenge the traditional ways of charging gas for actions.
Let's assume Alice uses a relayer to
execute actions with Bob as the receiver.
1. The relayer purchases the gas for all inner actions, plus the gas for the
delegate action wrapping them.
2. The cost of sending the inner actions and the delegate action from the
relayer to Alice's shard will be burned immediately. The condition `relayer == Alice` determines which action `SEND` cost is taken (`sir` or `not_sir`).
Let's call this `SEND(1)`.
3. On Alice's shard, the delegate action is executed, thus the `EXEC` gas cost
for it is burned. Alice sends the inner actions to Bob's shard. Therefore, we
burn the `SEND` fee again. This time based on `Alice == Bob` to figure out
`sir` or `not_sir`. Let's call this `SEND(2)`.
4. On Bob's shard, we execute all inner actions and burn their `EXEC` cost.
Each of these steps should make sense and not be too surprising. But the
consequence is that the implicit costs paid at the relayer's shard are
`SEND(1)` + `SEND(2)` + `EXEC` for all inner actions plus `SEND(1)` + `EXEC` for
the delegate action. This might be surprising but hopefully with this
explanation it makes sense now!
***
## Gas refunds in meta transactions
Gas refund receipts work exactly like for normal transactions. At every step, the
difference between the price at which the gas was bought and the price at which it
was burned is refunded. At the end of the last step, all remaining gas is also
refunded at the buy price. The gas refunds go to the signer of the original
transaction, in this case the relayer. This is only fair, since the relayer also
paid for it.
Note that the relayer has to hold more NEAR upfront than the meta transaction
finally costs, because gas is
[bought at a price that can be higher than the price it burns at](/protocol/transactions/gas#buying-vs-burning-gas).
***
## Balance refunds in meta transactions
Unlike gas refunds, the protocol sends balance refunds to the predecessor
(a.k.a. sender) of the receipt. This makes sense, as we deposit the attached
balance to the receiver, who has to explicitly reattach a new balance to new
receipts they might spawn.
In the world of meta transactions, this assumption is also challenged. If an
inner action requires an attached balance (for example a transfer action) then
this balance is taken from the relayer.
The relayer can see what the cost will be before submitting the meta transaction
and agrees to pay for it, so nothing wrong so far. But what if the transaction
fails execution on Bob's shard? At this point, the predecessor is `Alice` and
therefore she receives the token balance refunded, not the relayer. This is
something relayer implementations must be aware of since there is a financial
incentive for Alice to submit meta transactions that have high balances attached
but will fail on Bob's shard.
***
## Function Call Access Keys in Meta Transactions
[Function Call Access Keys](../accounts-contracts/access-keys#function-call-keys)
are limited to signing transactions for specific methods on a specific contract.
Additionally, they can have an allowance, which limits the amount of tokens that
can be spent on GAS fees. This limit however can be circumvented by using meta
transactions.
When a `DelegateAction` is processed in the network, the access key of the sender
is checked against the receiver and the methods called. If the access key is allowed to
make the call, the action is executed.
The allowance however is not checked, as all costs have been covered by the
relayer. Hence, the action will be executed even if the allowance is insufficient
to cover the costs.
# Anatomy of a Transaction
Source: https://docs.near.org/protocol/transactions/transaction-anatomy
Learn about the structure and components of NEAR Protocol transactions, including signers, receivers, actions, and transaction validation fields.
This section explains the anatomy of a transaction in the NEAR Protocol, describing its structure, components, and the actions that can be performed within a transaction.
A transaction is a request from a user to the network to perform a set of actions. To create a transaction, the user must specify the following fields:
* `Signer`: the account that signs the transaction
* `Actions`: the set of actions to be performed (see below)
* `Receiver`: the account on which to perform the actions
In addition, a transaction has the following fields to ensure its integrity and validity:
* `PublicKey`: the public key used to sign the transaction (so the network can verify the signature)
* `Nonce`: a number that is incremented for each transaction sent by the `Signer`
* `BlockHash`: the hash of a recent block, to limit the time-validity of the transaction
Users create transactions and sign them with their private keys. Then, the **transaction and its signature** are broadcast together to the network, where they are validated and processed.
> [!TIP]
>
> Each transaction has exactly one `Signer` and `Receiver`, but can have multiple `Actions`.
> [!NOTE]
>
> **About nonce values**
>
> * When adding a key, the `nonce` is automatically assigned - particularly, it is given the value `block height * 10^6` - so the value in the `ADD_KEY` action is ignored
> * A transaction is accepted only if the `nonce` value is in the range of:
> * `[(current_nonce_of_access_key + 1) .. (block_height * 10^6)]`
> * Once a transaction is accepted, the access key's `nonce` is set to the `nonce` value of the included transaction
> * A transaction signed with a [gas key](/protocol/accounts-contracts/gas-keys) additionally specifies a `nonce_index` selecting one of the key's parallel nonce lanes; the same rules then apply to that lane's nonce independently
***
## Transaction limits
A signed transaction must fit within both of these limits:
| Limit | Maximum |
| - | - |
| Serialized size of the signed transaction | **1.5 MiB (1,572,864 bytes)** |
| Total gas attached to all function-call actions in the transaction | **1 PGas (1,000 TGas)** |
The size limit includes the entire signed transaction: account IDs, public key, nonce, block hash, actions (including function-call arguments or contract code), and signature. The space available for your payload is therefore smaller than 1.5 MiB. Nodes reject larger transactions with `TransactionSizeExceeded`.
The size and [gas limits](/protocol/transactions/gas#gas-units) are separate: attaching more gas does not let you upload more bytes. To upload larger data, split it across transactions if your contract supports incremental uploads.
These limits are configured by `max_transaction_size` and `max_total_prepaid_gas` in the [protocol configuration](/api/rpc/protocol#protocol-config).
***
## Actions
Each transaction can have **one or multiple** [`Actions`](https://nomicon.io/RuntimeSpec/Actions.html), which are the actual operations to be performed on the `Receiver` account. There are different types of actions that can be performed:
1. [`FunctionCall`](https://nomicon.io/RuntimeSpec/Actions.html#functioncallaction): to invoke a function on a contract (optionally attaching NEAR to the call)
2. [`Transfer`](https://nomicon.io/RuntimeSpec/Actions.html#transferaction): to transfer tokens to another account
3. [`DeployContract`](https://nomicon.io/RuntimeSpec/Actions.html#deploycontractaction): to deploy a contract in the account
4. [`DeployGlobalContract`](https://nomicon.io/RuntimeSpec/Actions.html#deployglobalcontractaction): registers a global contract referenced by its contract hash or by its account ID
5. [`UseGlobalContract`](https://nomicon.io/RuntimeSpec/Actions.html#useglobalcontractaction): uses a registered global contract by contract hash or account ID
6. [`CreateAccount`](https://nomicon.io/RuntimeSpec/Actions.html#createaccountaction): to create a new sub-account (e.g. `ana.near` can create `sub.ana.near`)
7. [`DeleteAccount`](https://nomicon.io/RuntimeSpec/Actions.html#deleteaccountaction): to delete the account (transferring the remaining balance to a beneficiary)
8. [`AddKey`](https://nomicon.io/RuntimeSpec/Actions.html#addkeyaction): to add a new key to the account (either `FullAccess` or `FunctionCall` access, optionally as a [gas key](/protocol/accounts-contracts/gas-keys))
9. [`DeleteKey`](https://nomicon.io/RuntimeSpec/Actions.html#deletekeyaction): to delete an existing key from the account
10. [`TransferToGasKey`](/protocol/accounts-contracts/gas-keys): to fund a gas key's prepaid gas balance with NEAR
11. [`WithdrawFromGasKey`](/protocol/accounts-contracts/gas-keys): to move NEAR from a gas key's balance back to the account
12. [`DelegateActions`](https://nomicon.io/RuntimeSpec/Actions.html#delegate-actions): to create a [meta-transaction](/protocol/transactions/meta-tx) (`Delegate`). `DelegateV2`, which lets a gas key sign the delegate action, is rejected from protocol version 87
13. [`Stake`](https://nomicon.io/RuntimeSpec/Actions.html#stakeaction): special action to express interest in becoming a network validator (its own `public_key` field — the validator's block-production key — [must stay `ed25519`](/protocol/network/validators#intro-to-validators), regardless of what key signed the transaction)
14. [`DeterministicStateInit`](https://nomicon.io/RuntimeSpec/Actions.html#deterministicstateinitaction): special action to create a deterministic account (an advanced kind of implicit account)
15. [`UniversalStateInit`](/protocol/tutorials/creating-universal-accounts): special action to create a [universal account](/protocol/accounts-contracts/account-id#universal-address), installing its code, storage, and access keys in one step
> [!WARNING]
>
> Never use `DeleteAccount` as a replacement for `Transfer`. If the beneficiary does not exist, the remaining balance is burned. Transfer first, wait for finalized success and outstanding refunds, then delete the account if needed. See [safe account deletion](/protocol/network/token-loss#deleting-account-with-non-existent-beneficiary).
For example, `bob.near` can bundle the following actions in a single transaction:
* Create the account `contract.bob.near`
* Transfer 5 NEAR to `contract.bob.near`
* Deploy a contract in `contract.bob.near`
* Call the function `init` in `contract.bob.near`
The `Actions` are executed in the **order they are specified in the transaction**. If any of the **actions fails**, the transaction is discarded and none of the actions take effect.
> [!WARNING]
>
> **One Receiver**
>
> Notice that all actions are performed on the same account. It is **not possible** to perform actions on multiple accounts in a single transaction, because transactions can have **only one receiver**
# Lifecycle of a Transaction
Source: https://docs.near.org/protocol/transactions/transaction-execution
Learn how NEAR transactions are executed and finalized
`Transactions` are constructed by users to express the intent of performing actions in the network. Once in the network, transactions are converted into `Receipts`, which are messages exchanged between network nodes.
On this page, we will explore the lifecycle of a transaction, from its creation to its final status.
> [!TIP]
>
> **Recommended Reading**
>
> To dig deeper into transaction routing, we recommend reading the [nearcore documentation](https://near.github.io/nearcore/architecture/how/tx_routing.html)
***
## Receipts & Finality
Let's walk through the lifecycle of a complex transaction using blocks as **time units**. The block numbers below illustrate execution stages; transaction-pool delays, receipt dependencies, and congestion can spread them over additional blocks. Execution and consensus finality progress independently.
#### Block #1: The Transaction Arrives
Once a validated transaction is included in a chunk, processing it creates a single action `Receipt` containing all the [actions](./transaction-anatomy) to be executed.
While creating the `Receipt`, the `signer` gets `$NEAR` deducted from its balance to **pay for the gas** and **any attached NEAR**.
If the `signer` and `receiver` coincide - e.g. the `signer` is adding a Key - the local `Receipt` can execute in the same chunk. This completes those actions, but consensus finality and any remaining receipts must still be checked.
#### Block #2: The Receipt is Processed
If the `signer` and `receiver` differ - e.g. the `signer` transfers NEAR to the `receiver` - the `Receipt` is routed to the receiver’s shard for execution, which can occur in a subsequent block.
During this process a `FunctionCall` could span a **cross-contract call**, creating one or multiple new `Receipts`.
#### Block #3...: Function Calls
Receipts created by a function call can execute in later blocks. Function-call receipts can spawn additional receipts; callbacks wait for their dependencies before executing.
#### Final Block: Gas is Refunded
A final `Receipt` is processed in a new block, refunding any extra gas paid by the user. Almost every transaction ends with one of these, since the [buy price](./gas#buying-vs-burning-gas) is usually higher than the burn price.
### Waiting for a Transaction
When using our libraries (or directly contacting the RPC), you can specify how long you want to wait for a transaction to be processed using a `wait_until` parameter.
After a transaction is submitted, it first gets validated by the RPC node. If the transaction fails structural checks it will be immediately rejected. Otherwise, two things progress independently:
* **Execution**: the receipts spawned by the transaction are executed across shards
* **Finality**: the blocks containing the transaction and its receipts are finalized by consensus
These two axes combine to give you the following `wait_until` levels:
| `wait_until` | Receipts executed? | Tx block final? | Receipt outcomes in response? |
| - | - | - | - |
| `None` | — | — | No |
| `Included` | — | — | No |
| `ExecutedOptimistic` | Yes (non-refund) | No | Yes |
| `IncludedFinal` | Not necessarily | Yes | Partial |
| `Executed` | Yes (non-refund) | Yes | Yes |
| `Final` | Yes (all, including refunds) | Yes (all blocks) | Yes |
Notice that `ExecutedOptimistic` and `IncludedFinal` are not ordered relative to each other — they represent progress on different axes. `ExecutedOptimistic` guarantees all non-refund receipt outcomes are available but the blocks aren’t final yet. `IncludedFinal` guarantees the transaction’s block is final but some receipts may still be pending, so you may only get a partial set of receipt outcomes.
#### Refund receipts
When a receipt executes, NEAR can generate refund receipts for unused gas and the difference between the gas buy and burn prices, subject to the protocol’s refund rules. Failed actions can also generate refunds of attached NEAR. `ExecutedOptimistic` and `Executed` don’t wait for refund receipts; `Final` does. If a system refund’s receiving account has been deleted, the undeliverable amount is burned; see [refunding deleted accounts](/integrations/errors/introduction#refunding-deleted-accounts).
> [!TIP]
>
> Simple transactions can execute their action and refund receipts in a few blocks. These examples illustrate receipt execution rather than a guaranteed time to consensus finality:
>
> * [One block](https://testnet.nearblocks.io/txns/8MAvH96aMfDxPb3kVDrgj8nvJS7CAXP1GgtiivKAMGkF#execution) if the `signer` and `receiver` coincide - e.g. when adding a key
> * [Three blocks](https://testnet.nearblocks.io/txns/B7gxJNxav1A9WhWvaNWYLrSTub1Mkfj3tAudoASVM5tG#) if the `signer` and `receiver` differ, since the first block creates the `Receipt`, and the last reimburses gas
>
> Function calls might take longer, as they can spawn multiple receipts. Network congestion can also increase the time to process a receipt and, thus, a transaction.
***
## Transaction Status
As the `Receipts` of a `Transaction` are processed, they get a status:
* `Success`: the actions on the receipt were executed successfully
* `Failed`: an action on the receipt failed
* `Unknown`: the receipt is not known by the network
If an action in a `Receipt` fails, all the actions in that `Receipt` are rolled back. Notice that we are talking about the `Receipt` status, and not the `Transaction` status.
The status of a transaction starts at its first receipt, which contains all its actions. If any of the actions in the first receipt fail, the transaction is marked as failed.
Each successful action in a receipt replaces the receipt's result, so the last action decides it. If the last action is a function call that returns a promise, the transaction takes the status of the receipt that the promise resolves to, and so on down the chain. Other receipts do not change the transaction status. This includes a promise that a function call creates but does not return, and a returned promise that a later action in the same receipt replaces. So a transaction can be marked as successful even though one of its receipts fails.
See the examples below for more details.
> [accordion] Status Examples
>
> #### Example: Transaction with Transfer
>
> 1. `bob.near` creates a transaction to transfer 10 NEAR to `alice.near`
> 2. The transaction is converted into a receipt
> 3. The conversion fails because `bob.near` does not have enough balance
> 4. The transaction is marked as failed ⛔
>
> #### Example: Deploying a Contract
>
> 1. `bob.near` creates a transaction to:
> * create the account `contract.bob.near`
> * transfer 5 NEAR to `contract.bob.near`
> * deploy a contract in `contract.bob.near`
> 2. The transaction is transformed into one receipt
> 3. The account is created, the money transfer and the contract deployed
> 4. The transaction is marked as successful ✅
>
> #### Example: Deploying a Contract Fails
>
> 1. `bob.near` creates a transaction to:
> * create the account `contract.bob.near`
> * transfer 5 NEAR to `contract.bob.near`
> * deploy a contract in `contract.bob.near`
> 2. The transaction is transformed into one receipt
> 3. The account is created, but the transfer fails because `bob.near` does not have enough balance
> 4. The whole process is reverted (i.e. no account is created)
> 5. The transaction is marked as failed ⛔
>
> #### Example: Calling a Function
>
> 1. `bob.near` creates a transaction to call the function `cross-call` in `contract.near`
> 2. The transaction is transformed into one receipt
> 3. The function `cross-call` creates a promise to call the function `external-call` in `external.near`
> 4. The function finishes correctly and the transaction is marked as successful ✅
> 5. A new receipt is created to call the function `external-call` in `external.near`
> 6. The function `external-call` fails
> 7. The original transaction is still marked as successful ✅, because `cross-call` did not return the promise. If `cross-call` returned the promise, the transaction would be marked as failed ⛔
> [!TIP]
>
> You can check the status of a transaction using the [NearBlocks explorer](https://nearblocks.io/)
***
## Nonce values
The `nonce` is a number that is incremented for each transaction sent by the transaction's `Signer`.
On a valid transaction, the `nonce` value should follow these rules:
* When adding a key, the `nonce` is automatically assigned - particularly, it is given the value `block height * 10^6` - so the value in the `ADD_KEY` action is ignored
* A transaction is accepted only if the `nonce` value is in the range of:
* `[(current_nonce_of_access_key + 1) .. (block_height * 10^6)]`
* Once a transaction is accepted, the access key's `nonce` is set to the `nonce` value of the included transaction
* [Gas keys](/protocol/accounts-contracts/gas-keys) hold one nonce per lane (up to 1,024 lanes); a transaction signed with a gas key selects a lane with its `nonce_index`, and the rules above apply to that lane's nonce independently of all other lanes
# Creating Deterministic Accounts
Source: https://docs.near.org/protocol/tutorials/creating-deterministic-accounts
Create a deterministic fungible-token account using a published global contract and initial storage.
A [deterministic account](/protocol/accounts-contracts/account-id#deterministic-address) starts with contract code and initial storage, but no access keys. Its `0s` address is derived from that initial state, so you can calculate it before creating the account.
This tutorial uses the [NEAR CLI](/tools/cli#installation) on **testnet**. You need a funded signer account. We will use the [global contract](/smart-contracts/global-contracts) already published at `ft.globals.primitives.testnet` to create a [fungible token](/primitives/ft/standard).
***
## Choose the code and initial storage
You can reference a global contract by its publisher's account ID or by its code hash. Here, the code reference is `ft.globals.primitives.testnet`.
The initial storage defines a token named **Example Token** (`EXAMPLE`), with **6 decimals** and a supply of **1,000,000 tokens**, all assigned to `alice.testnet`. The supply is stored as `1000000000000` smallest units.
The FT contract needs three storage entries:
| Key | Purpose |
| - | - |
| `STATE` | Contract state: balance-map prefix, total supply, storage usage per registered account, and metadata key |
| `0x00` followed by the Borsh-encoded owner account ID | The owner's token balance |
| `0x01` | Token metadata, including its name, symbol, and decimals |
***
## Generate the initial storage
The state-init action writes storage entries directly, so we need to serialize the same state that the FT contract's `new` method would create. This includes the token's metadata, total supply, and initial holder's balance—not just the arguments you would pass to `new`.
The [published FT source](https://github.com/near-examples/FT/blob/c5d39784fd8549d2006bf802354b75bcaf04c894/src/lib.rs) uses **Borsh** to serialize these values. The CLI expects each storage key and value as a **Base64-encoded string** in a JSON object.
Save the following as `build-ft-state.py`. It builds the three entries described above and encodes them for the CLI:
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import base64
import json
import struct
# Token configuration: change these values to define your own token.
owner_id = "alice.testnet"
name = "Example Token"
symbol = "EXAMPLE"
decimals = 6
total_supply = 1_000_000 * 10**decimals
# Borsh encodes byte arrays and strings with a little-endian u32 length.
def vec(value):
return struct.pack(" ft-state.json
cat ft-state.json
```
With the example configuration, the output is:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"U1RBVEU=": "AQAAAAAAEKXU6AAAAAAAAAAAAAAAfQAAAAAAAAABAAAAAQ==",
"AA0AAABhbGljZS50ZXN0bmV0": "ABCl1OgAAAAAAAAAAAAAAA==",
"AQ==": "CAAAAGZ0LTEuMC4wDQAAAEV4YW1wbGUgVG9rZW4HAAAARVhBTVBMRQAAAAY="
}
```
The file now contains the contract's initial storage, ready for the state-init action. Changing the owner, supply, or metadata changes these bytes and therefore the derived address. If the global publisher changes the contract's storage layout, the serializer must match that layout.
***
## Derive the address
Run this local computation, which does not submit a transaction:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract state-init use-global-account-id ft.globals.primitives.testnet \
data-from-file ft-state.json inspect account-id
```
For the exact storage above, the derived address is:
```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
0sa2e1be2454698caaada11defd5812d7bfd61eea2
```
***
## Create the account
Use the same code reference and storage. Replace `alice.testnet` in the command with the funded account signing the transaction; the initial token holder is determined separately by `ft-state.json`.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract state-init use-global-account-id ft.globals.primitives.testnet \
data-from-file ft-state.json execute '0.1 NEAR' \
sign-as alice.testnet network-config testnet sign-with-keychain send
```
The CLI derives the receiver address and submits a `DeterministicStateInit` action. The attached deposit covers any missing storage stake; unused NEAR is refunded.
You do not need a separate `CreateAccount`, `DeployContract`, or call to `new`: the state-init action installs the referenced code and the already-initialized FT storage together.
***
## Check the token
Query the new account's metadata:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near view 0sa2e1be2454698caaada11defd5812d7bfd61eea2 ft_metadata '{}' --networkId testnet
```
The metadata identifies **Example Token** with symbol `EXAMPLE` and 6 decimals. Check the total supply and the owner's balance:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near view 0sa2e1be2454698caaada11defd5812d7bfd61eea2 ft_total_supply '{}' --networkId testnet
near view 0sa2e1be2454698caaada11defd5812d7bfd61eea2 ft_balance_of '{"account_id":"alice.testnet"}' --networkId testnet
```
Both return `"1000000000000"`, representing 1,000,000 tokens. If you customized the initial storage, use your derived address and token holder instead.
***
## Create accounts from an application or contract
See [NEAR API Libraries](/tools/near-api#create-deterministic-account) for a `near-kit` example, or [Create deterministic accounts](/smart-contracts/anatomy/actions#create-deterministic-accounts) for the host functions used by smart contracts.
# Creating Implicit & Named Accounts
Source: https://docs.near.org/protocol/tutorials/creating-implicit-and-named-accounts
Create implicit accounts through transfers and named accounts through parent-account contracts or CreateAccount actions.
You can create an account from a key pair or choose a readable name like alice.testnet. This guide walks through both options: creating [implicit accounts](/protocol/accounts-contracts/account-id#implicit-address) and [named accounts](/protocol/accounts-contracts/account-id#named-address).
> [!NOTE]
>
> Install the [NEAR CLI](/tools/cli#installation) before starting. The examples below use **testnet**.
***
## Create an implicit account
Creating an implicit account takes two steps: generate a key pair locally, then send a transfer to its derived address.
### Generate a key pair
The simplest way to obtain a public / private key pair is using the [NEAR CLI](/tools/cli):
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near account create-account fund-later use-auto-generation save-to-folder ~/.near-credentials/implicit
# The file "~/.near-credentials/implicit/cf4342372b583606057805490c97d4778bc4ac444a76f32154634558ab57c3c5.json" was saved successfully
cat ~/.near-credentials/implicit/cf4342372b583606057805490c97d4778bc4ac444a76f32154634558ab57c3c5.json
# {"implicit_account_id":"cf4342372b583606057805490c97d4778bc4ac444a76f32154634558ab57c3c5","master_seed_phrase":"kit creek invite deputy fetch resource marble sweet camp thumb mushroom swift","private_key":"ed25519:5uJtH8hdYKPEhLVTn9EoxaneLpKh11qLEWDVvG6tKTeMUzsmf7isHYxXixhNcupRhUNQ2fHFgtKXy94YUXHfbxiG","public_key":"ed25519:Ex4stLtTe43ynFmxGweGzMWLvRmRSUP6EjU6nvAdY2vg","seed_phrase_hd_path":"m/44'/397'/0'"}
```
The file contains the generated key pair and implicit account ID. Your generated ID will differ from the example above. Keep the private key secret.
You can also generate a key pair using the `near-seed-phrase` library:
```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { generateSeedPhrase } from "near-seed-phrase";
const { seedPhrase, publicKey, secretKey } = generateSeedPhrase();
```
Note that generating the key pair runs locally; the account will only be created on-chain when it receives a transfer.
### Fund the account
Send NEAR to the derived address from a wallet or an existing funded account:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
export SENDER_ID=alice.testnet
export IMPLICIT_ACCOUNT_ID=your-64-character-implicit-account-id
near tokens "$SENDER_ID" send-near "$IMPLICIT_ACCOUNT_ID" '0.1 NEAR' \
network-config testnet sign-with-keychain send
```
After the transfer is confirmed, the implicit account is created on-chain and its public key is registered as a full-access key. You can then use the saved credentials to sign transactions from this account.
> [!TIP]
>
> You can initialize an account by making a transfer of `0 NEAR`. This is because the cost of creating an account is covered **through GAS fees**, and not the attached NEAR amount.
***
## Create a named account
Named accounts are created through the `top level` accounts `near` in mainnet, and `testnet` in testnet. Both accounts possess smart contracts that expose the `create_account`.
> [!TIP]
>
> You can also simply use the NEAR CLI command `near create-account` to create a named account without manually interacting with the parent account's contract.
### Call the parent account's contract
To create `alice.testnet` with `0.1 NEAR`, call `create_account` on `testnet` using an existing account such as `funding-account.testnet`:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near call testnet create_account '{"new_account_id": "alice.testnet", "new_public_key": "ed25519:"}' --useAccount funding-account.testnet --deposit 0.1 --networkId testnet
```
Replace `ed25519:` with the public key generated above. The contract creates and funds `alice.testnet` and adds the `new_public_key` as a full-access key to the account.
> [!NOTE]
>
> If you are not going through an intermediary such as a wallet, you can generate an implicit account, fund it, and call `create_account` on `near` / `testnet`.
> [!TIP]
>
> You can initialize an account by using a deposit of `0 NEAR`. This is because the cost of creating an account is covered **through GAS fees**, and not the attached NEAR amount.
### Create a direct sub-account
If you control `alice.testnet`, you can trigger the `CreateAccount` action yourself to create a direct sub-account:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near create-account app.alice.testnet --useAccount alice.testnet --networkId testnet
```
The CLI builds the transaction that creates the account and adds its first key. You can add `--initialBalance ` to set its initial balance.
> [!NOTE]
>
> A parent account has no control over its sub-accounts after creation. Control depends on the access keys and contract installed on each account.
### Use the testnet faucet
A faucet can create and fund a named testnet account for you, so you don't need an existing funded account. Choose an available `.testnet` name and run:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
export ACCOUNT_ID=your-unique-name.testnet
near account create-account sponsor-by-faucet-service "$ACCOUNT_ID" \
autogenerate-new-keypair save-to-keychain network-config testnet create
```
The CLI generates and saves your key pair, then asks the faucet service to create the account with that public key. Faucet-sponsored creation is available on testnet only.
***
## Create accounts from an application or contract
See [NEAR API Libraries](/tools/near-api#create-named-account) for named-account creation and [Create a Sub Account](/smart-contracts/anatomy/actions#create-a-sub-account) for creating accounts from a smart contract.
# Creating Universal Accounts
Source: https://docs.near.org/protocol/tutorials/creating-universal-accounts
Three ways to create and initialize a 0u universal account: relayer-assisted, self-signed bootstrap, and from inside a smart contract, with code and RPC examples.
A [universal account](/protocol/accounts-contracts/account-id#universal-address)'s address is the hash of its own initial state, so creating one is always the same underlying operation: submit a `UniversalStateInit` action carrying that state — the code, storage, and access keys the account will start with. What differs between the three flows below is **who signs** the transaction that carries it, and **when** the account starts existing.
This page assumes you're familiar with [Universal Address](/protocol/accounts-contracts/account-id#universal-address) and [Access Keys](/protocol/accounts-contracts/access-keys).
> [!WARNING]
>
> Universal accounts need protocol version 88 or later (nearcore 2.14.0). On a network with an earlier protocol version, a `UniversalStateInit` action is rejected, and a `Transfer` to a `0u` address fails without creating an account. To see a network's protocol version, call the `status` RPC method and read `protocol_version`. As of October 2026, testnet supports universal accounts and mainnet does not yet.
> [!NOTE]
>
> This is a protocol-level walkthrough using raw transactions and RPC calls. Dedicated SDK helpers for building a `UniversalStateInit` action are expected to follow in `near-api-js` and `near-kit` — check [NEAR API](/tools/near-api) for the latest tooling before hand-rolling this in production.
***
## Choosing a flow
| Flow | Who signs | Who pays gas | Good for |
| - | - | - | - |
| [Relayer-assisted](#relayer-assisted-creation) | An existing, already-funded account | The signer | Onboarding someone who doesn't hold any NEAR yet |
| [Self-signed bootstrap](#self-signed-bootstrap) | The new account's own key | The new account itself | The owner already generated their key pair and can fund the address directly |
| [Contract-triggered](#contract-triggered-creation) | A deployed contract, via a promise | The calling contract | Factory patterns: a contract creating new accounts on demand |
***
## The uninitialized account
Before any state init runs, a `0u` address can already receive NEAR: a plain `Transfer` to an address that doesn't exist yet silently creates it as **uninitialized** — it holds a balance, but has no code, access keys, or storage.
> [!WARNING]
>
> An uninitialized account accepts exactly one thing: a `UniversalStateInit` action whose state init hashes to that same address. Every other action — `AddKey`, `FunctionCall`, `DeployContract`, `Stake`, and so on — fails with `AccountNotInitialized`, and leaves the account untouched.
Querying an uninitialized account looks like this:
> [tab] JSON
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "id": "dontcare",
> "method": "query",
> "params": {
> "request_type": "view_account",
> "finality": "final",
> "account_id": "0u0000000000000000000000000000000000000000000000000000"
> }
> }
> ```
> [tab] JavaScript
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> 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: '0u0000000000000000000000000000000000000000000000000000',
> });
> ```
> [tab] HTTPie
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> http POST https://rpc.testnet.near.org \
> jsonrpc=2.0 id=dontcare method=query \
> params:='{"request_type":"view_account","finality":"final","account_id":"0u0000000000000000000000000000000000000000000000000000"}'
> ```
> [accordion] Example response (uninitialized)
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "amount": "3000000000000000000000000",
> "locked": "0",
> "code_hash": "11111111111111111111111111111111",
> "storage_usage": 100,
> "state": "uninitialized",
> "bootstrap_nonce": 187440903000000,
> "block_hash": "56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW",
> "block_height": 187440904
> },
> "id": "dontcare"
> }
> ```
>
> `bootstrap_nonce` is seeded as `(block_height - 1) * 1,000,000` — the block the account was created at, using the exact same formula and multiplier NEAR uses for a freshly added access key's starting nonce (see the [nonce values](/protocol/transactions/transaction-anatomy#actions) note on the Transaction Anatomy page).
Once its state init runs, the same account looks like any other: `state` and `bootstrap_nonce` disappear from the response entirely, rather than flipping to `"initialized"` / `null`.
> [accordion] Example response (initialized)
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
> "jsonrpc": "2.0",
> "result": {
> "amount": "3000000000000000000000000",
> "locked": "0",
> "code_hash": "11111111111111111111111111111111",
> "storage_usage": 182,
> "block_hash": "8n1QWQyc7sTZDDxLBSyMWzquv9uUFrjEXFf4ZjZwUwjE",
> "block_height": 187440920
> },
> "id": "dontcare"
> }
> ```
> [!NOTE]
>
> **Why `bootstrap_nonce` matters**
>
> An uninitialized account has no access key yet, so there's no `view_access_key` query to ask for a nonce. `bootstrap_nonce` — seeded from the block height the account was created at — is the *only* place to learn the value a [self-signed bootstrap](#self-signed-bootstrap) transaction's nonce is based on: the transaction itself must use `bootstrap_nonce + 1`, the same "+1" rule as any other nonce.
***
## Relayer-assisted creation
An existing, funded account creates and pays for someone else's universal account in a single transaction. This is the pattern for onboarding: the new owner doesn't need to hold any NEAR up front.
**1. Build the state init and derive the address**
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_crypto::PublicKeyHandle;
use near_primitives::universal_state_init::{UniversalStateInit, UniversalStateInitV1};
use near_primitives::utils::derive_universal_account_id;
use std::collections::{BTreeMap, BTreeSet};
let state_init = UniversalStateInit::V1(UniversalStateInitV1 {
code: None, // key-only account, no contract
data: BTreeMap::new(),
access_keys: BTreeSet::from([PublicKeyHandle::from(owner_public_key)]),
});
let raw = state_init.to_raw();
let account_id = derive_universal_account_id(&raw);
```
`PublicKeyHandle` is the compact form an access key takes in a state init: the full public key for `ed25519`/`secp256k1`, or the 32-byte SHA3-256 hash for [`ml-dsa-65`](/protocol/accounts-contracts/access-keys#signature-schemes) — `PublicKeyHandle::from(public_key)` picks the right variant for you.
Control over the account is entirely decided by whichever keys end up in `access_keys` at this step — there's no separate "owner" concept. A relayer building this state init could just as well name its own key alongside (or instead of) the future owner's; whoever holds any key committed here controls the account from the moment it initializes.
**2. Sign one transaction with UniversalStateInit and Transfer**
The relayer signs a transaction from **its own** account, targeting the derived id, bundling the state init with a funding transfer:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_primitives::action::{Action, UniversalStateInitAction};
use near_primitives::transaction::{SignedTransaction, TransferAction};
use near_primitives::types::Balance;
let tx = SignedTransaction::from_actions(
relayer_nonce,
relayer_account_id,
account_id.clone(),
&relayer_signer,
vec![
Action::UniversalStateInit(Box::new(UniversalStateInitAction {
state_init: raw,
deposit: Balance::ZERO,
})),
Action::Transfer(TransferAction { deposit: Balance::from_near(1) }),
],
recent_block_hash,
);
```
Either `UniversalStateInit` or `Transfer` can run first. The one that runs first creates the account, and the other one then applies to it. The order matters for storage stake. If `UniversalStateInit` runs first, the account starts with a zero balance, so the state init's own `deposit` must cover the storage stake of everything it installs. This is not needed when the account uses 770 bytes or less, as in this example. A `FunctionCall` can follow in the same batch too, to call into the contract the state init just installed.
> [!NOTE]
>
> **Why is `deposit` zero here, and `Transfer` used instead?** `UniversalStateInitAction.deposit` isn't a general funding mechanism. It only tops up the account's balance to cover its **storage stake**. This happens only the first time a state init initializes the account. A `UniversalStateInit` that lands on an already-initialized account always refunds the whole deposit, because there is nothing left for it to cover. A zero `deposit` works here because the new account uses 770 bytes or less, so it needs no storage stake. For a larger account, put the `Transfer` first, or set `deposit` to cover the storage stake. The `Transfer` sets the account's spendable balance.
**3. Broadcast it**
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"jsonrpc": "2.0",
"id": "dontcare",
"method": "send_tx",
"params": {
"signed_tx_base64": "DwAAAHJlbGF5ZXIudGVzdG5ldA...",
"wait_until": "EXECUTED_OPTIMISTIC"
}
}
```
> [!WARNING]
>
> **A relayer cannot make itself an owner.** If the batch also includes an `AddKey` for the relayer's own key, the whole receipt is rejected with `ActorNoPermission` — creating an account by funding it does not carry the creator's authority into it. Nothing in the batch takes effect: the account is never created either.
***
## Self-signed bootstrap
The future owner already holds a key pair and just needs somewhere to send funds to before that key exists on-chain as an access key. No relayer, no second party — the account initializes itself.
**1. Fund the address**
Anyone — typically the owner themselves, from another account or an exchange withdrawal — sends an ordinary transfer to the derived `0u` address. This is the exact mechanic described in [The uninitialized account](#the-uninitialized-account): the transfer alone brings the account into existence, uninitialized.
**2. Read the bootstrap nonce**
Query `view_account` (see the [example above](#the-uninitialized-account)) to confirm `state` is `"uninitialized"` and read `bootstrap_nonce`.
**3. Sign the state init with the account's own key**
The transaction's `signer_id` and `receiver_id` are both the new account itself, signed with the key that's *inside* `state_init.access_keys` — the same key pair the owner generated in step 1 of the relayer flow above:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_crypto::InMemorySigner;
let nonce = bootstrap_nonce + 1;
let signer = InMemorySigner::from_secret_key(account_id.clone(), owner_secret_key);
let tx = SignedTransaction::from_actions(
nonce,
account_id.clone(),
account_id.clone(),
&signer,
vec![Action::UniversalStateInit(Box::new(UniversalStateInitAction {
state_init: raw,
deposit: Balance::ZERO,
}))],
recent_block_hash,
);
```
**4. Broadcast it**
Same `send_tx` call as the relayer flow. Once it executes, the key that signed the bootstrap is a real full-access key, and the account behaves like any other.
> [!WARNING]
>
> Only a key that's actually committed inside `state_init.access_keys` is accepted as the signer of this bootstrap transaction — this is checked independently both when the transaction is admitted to the mempool and when it executes. An unrelated key cannot claim someone else's uninitialized account, even though the account technically has no access key on file yet.
***
## Contract-triggered creation
A deployed contract creates a universal account as part of its own execution — the pattern for factories that spin up new accounts on demand, or for airdrop/linkdrop-style contracts that pre-fund an address before its owner claims it.
> [!NOTE]
>
> Unlike `app.bob.near`, a universal account created this way is **not** a namespace child of the creating contract — its `0u` address is just a hash of its own state, unrelated to the contract's account id. "Spinning up an account" here means creating an independently-addressed account, not extending the contract's own domain the way named sub-accounts do.
**1. Derive the account id on-chain**
The contract asks the host to derive the id from the exact bytes it's about to use, so the promise it creates in the next step is guaranteed to target the right receiver. The call also validates the bytes and reports the result, instead of silently deriving an id for anything:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[allow(unused)]
unsafe extern "C" {
fn universal_state_init_to_account_id(state_init_len: u64, state_init_ptr: u64, register_id: u64) -> u64;
fn promise_batch_action_universal_state_init(
promise_idx: u64,
state_init_len: u64,
state_init_ptr: u64,
amount_ptr: u64,
);
}
```
These are the raw host-function imports — there's no `near-sdk-rs` ergonomic wrapper for them yet, so this is what you write directly, the same low-level way you'd import any other host function it doesn't wrap.
`universal_state_init_to_account_id` returns a status instead of always succeeding. `0` means the id was derived and written to the register. `1` means the bytes don't decode into a `UniversalStateInit`, which includes bytes with extra data at the end. `2` means they decode but aren't the one canonical encoding: unsorted or duplicate `data` keys or `access_keys`. On anything but `0`, the register is left unwritten. Check the status before moving on. Otherwise this is a pure computation: no side effects, and it can run inside a view call.
**2. Append the UniversalStateInit action to a promise**
If step 1 returned a status other than `0`, do not create the promise.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
let promise_idx = unsafe { promise_batch_create(receiver_len, receiver_ptr) };
unsafe {
promise_batch_action_universal_state_init(
promise_idx,
state_init_len,
state_init_ptr,
amount_ptr, // pointer to a little-endian u128 yoctoNEAR deposit
);
}
```
Like in the relayer flow, this `amount_ptr` deposit only tops up the account's **storage stake**, and only on the state init that actually initializes the account, refunding the rest back to the calling contract. A state init that lands on an account that's already initialized — a repeat, idempotent call — always refunds the **whole** deposit, since there's no storage left for it to cover. It doesn't unconditionally add to the account's balance the way a `Transfer` action does; if you want the new account to end up with a specific spendable balance, batch a `Transfer` action onto the same promise as well.
> [!NOTE]
>
> There's no host function to build up a `UniversalStateInit`'s `data` map incrementally the way `set_state_init_data_entry` does for a [deterministic account](/protocol/accounts-contracts/account-id#deterministic-address). If your contract needs to populate initial storage, it has to construct the whole Borsh-encoded state init itself before calling `promise_batch_action_universal_state_init` — the two host functions here only derive an id from bytes and attach an action, they don't help build the bytes.
**3. Invalid input fails your function call**
If the contract creates the promise with input that fails validation, the contract's own function call fails with `NewReceiptValidationError`. The failed call's state changes are rolled back. None of the receipts it created run, including callbacks.
`promise_batch_action_universal_state_init` does not check the bytes or the receiver when the contract calls it. The runtime checks them when the contract's function call finishes, together with every other receipt that the call created. The inner `ActionsValidation` error says which check failed:
| Check | Inner error |
| - | - |
| The promise's receiver is the id that the bytes derive to | `InvalidUniversalStateInitReceiver` |
| The bytes decode into a `UniversalStateInit` and are the canonical encoding | `MalformedUniversalStateInit` |
| The state init actions of the receipt have at most 1,500 storage entries in total | `TotalNumberOfStateInitEntriesExceeded` |
| The state init actions of the receipt have at most 1,024 access keys in total | `TotalNumberOfStateInitKeysExceeded` |
| Each storage key is at most 2,048 bytes | `UniversalStateInitKeyLengthExceeded` |
| Each storage value is at most 4,194,304 bytes | `UniversalStateInitValueLengthExceeded` |
The receiver check runs before the decoding check. A status of `0` from step 1 does not check the size limits in the last four rows.
A promise that passes all checks is sent. The state init can still fail when it runs, for example if the account balance and the deposit together do not cover the storage stake. If your contract's logic depends on the account having been created, check the outcome of the cross-contract call.
> [!NOTE]
>
> Both host functions are gated by the `UniversalAccounts` protocol feature, stable from protocol version 88. Calling them on a network that hasn't reached that version fails to link, the same way any other protocol-gated host function does.
# Staking NEAR Tokens
Source: https://docs.near.org/protocol/tutorials/staking-tokens
Learn how to stake NEAR, delegate to validators, track rewards, and withdraw staked tokens safely.
You can delegate NEAR tokens to a validator to help secure the network and earn staking rewards.
This tutorial shows you how to stake tokens, check balances, unstake, and withdraw using the [NEAR CLI](/tools/cli).
> [!NOTE]
>
> **Contract source code**
>
> You can review the Staking pool smart contract source code in [this GitHub repository](https://github.com/near/core-contracts/tree/master/staking-pool).
***
## Delegate NEAR tokens
Before delegating, you need to choose a validator (a node that participates in staking).
Check [NearBlocks](https://nearblocks.io/node-explorer), [Pikespeak](https://pikespeak.ai/validators/overview) or [Near Staking](https://near-staking.com/), and look for validators with a good track record, uptime, and reasonable commission rates.
> [accordion] List validators using CLI
>
> If you prefer, you can get the list of current validators by using the [`near-validator`](/tools/cli#validator-extension) CLI:
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near-validator validators network-config mainnet now
> ```
### Stake Tokens
> [tab] Staking CLI
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near staking delegation deposit-and-stake '100 NEAR' network-config mainnet sign-with-keychain
> ```
> [tab] Function Call
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call deposit_and_stake --useAccount --deposit 100
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/staking/deposit-and-stake.json)
> [!TIP]
>
> You will start earning staking rewards after the next epoch
### Staked Balance
To check your staked balance on the `` pool for the `` account, run the following command:
> [tab] Staking CLI
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near staking delegation view-balance network-config mainnet now
> ```
> [tab] Function Call
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near view get_account_staked_balance '{"account_id": ""}'
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/staking/account-staked-balance.json)
> [accordion] Staking pool balances
>
> You can view additional information and balances from the staking pool using the following CLI commands:
>
> #### Total staked balance of the entire pool
>
> > [tab] 🖥️ CLI
> >
> > ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > near view get_total_staked_balance '{}'
> > ```
>
> > [tab] Lantstool
> >
> > Try it out on
> > [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/staking/pool-total-staked-balance.json)
>
> #### Owner of the staking pool
>
> > [tab] 🖥️ CLI
> >
> > ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > near view get_owner_id '{}'
> > ```
>
> > [tab] Lantstool
> >
> > Try it out on
> > [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/staking/pool-owner.json)
>
> #### Current reward fee
>
> > [tab] 🖥️ CLI
> >
> > ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > near view get_reward_fee_fraction '{}'
> > ```
>
> > [tab] Lantstool
> >
> > Try it out on
> > [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/staking/reward-fee.json)
>
> #### Owner's balance
>
> > [tab] 🖥️ CLI
> >
> > ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > near view get_account_total_balance '{"account_id": "owner"}'
> > ```
>
> > [tab] Lantstool
> >
> > Try it out on
> > [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/staking/owner-balance.json)
>
> #### Staking key
>
> > [tab] 🖥️ CLI
> >
> > ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > near view get_staking_key '{}'
> > ```
>
> > [tab] Lantstool
> >
> > Try it out on
> > [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/staking/staking-key.json)
***
## Withdrawing Staked Tokens
To withdraw your staked tokens, you will first need to "un-delegate" them from the validator.
Your tokens will enter a 4-epoch unbonding period before they can be withdrawn.
### Unstake Tokens
> [tab] Staking CLI
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near staking delegation unstake '1 NEAR' network-config mainnet sign-with-keychain
> ```
>
> > [!NOTE]
> >
> > Use the `unstake-all` command to unstake all tokens at once:
> >
> > ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > near staking delegation unstake-all network-config mainnet sign-with-keychain
> > ```
> [tab] Function Call
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call unstake '{"amount": "100000000000000000000000000"}' --useAccount
> ```
>
> > [!NOTE]
> >
> > Call the `unstake_all` method to unstake all tokens at once
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/staking/unstake.json)
### Query Unstaked Balance
> [tab] Staking CLI
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near staking delegation view-balance network-config mainnet now
> ```
> [tab] Function Call
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near view get_account_unstaked_balance '{"account_id": ""}'
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/staking/account-unstaked-balance.json)
### Withdraw Tokens
Once the unbonding period has passed, you can withdraw your unstaked tokens:
> [tab] Staking CLI
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near staking delegation withdraw '1 NEAR' network-config mainnet sign-with-keychain
> ```
>
> > [!NOTE]
> >
> > If you want to withdraw all available tokens, you can use the `withdraw-all` command:
> >
> > ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> > near staking delegation withdraw-all network-config mainnet sign-with-keychain
> > ```
> [tab] Function Call
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call withdraw '{"amount": "100000000000000000000000000"}' --useAccount
> ```
> [tab] Lantstool
>
> Try it out on
> [Lantstool](https://app.lantstool.dev/import/gh/lantstool/examples.near-protocol/main/docs/2.build/5.primitives/staking/withdraw-unstaked-tokens.json)
***
## Tools and Resources
* Supported wallets for staking and managing your tokens:
* [Ecosystem Wallets](https://wallet.near.org/)
* To explore validators and staking pools:
* [NearBlocks](https://nearblocks.io/)
* [Pikespeak](https://pikespeak.ai/)
* [NEAR Staking](https://near-staking.com/)
# Sunsetting a Staking Pool
Source: https://docs.near.org/protocol/tutorials/sunsetting-a-staking-pool
Wind down a staking pool, pause staking, and help delegators withdraw their tokens.
If you are a stake pool owner and want to wind down your validator service, follow these steps to ensure delegators can safely recover their funds.
***
## Step 1: Notify Delegators
Before making any changes, inform your delegators that the pool is shutting down. Give them enough time to unstake and withdraw their tokens. They need to:
1. Call `unstake_all` on the pool.
2. Wait for the **4-epoch unbonding period**.
3. Call `withdraw_all` to retrieve their tokens.
Share the [unstaking and withdrawal commands](/protocol/tutorials/staking-tokens#withdrawing-staked-tokens) with your delegators.
***
## Step 2: Pause Staking
Call `pause_staking` from the pool owner account. The pool then sends a stake of 0 to the protocol and stops restaking. It does not change any account's shares in the contract or the reward calculations.
```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
near call pause_staking '{}' --useAccount --networkId mainnet
```
Do not attach a deposit. `pause_staking` and `resume_staking` do not accept one, and the call fails if you add it.
> [!NOTE]
>
> The pool sends a stake of 0 right away. It stays in the validator set for the rest of the current epoch and for the next epoch. It leaves the set in the epoch after that. Keep the validator node running until the pool is no longer in the validator set. If the node stops earlier, the pool misses blocks and chunks, and it earns less or no rewards for those epochs.
>
> The pool's locked balance becomes liquid at the start of the third epoch after the call. Pausing does not unstake anyone's shares in the contract. Delegators still see their shares and can unstake and withdraw normally.
***
## Step 3: Withdraw Owner Balance
Pausing does not unstake your own balance in the pool. This balance includes the shares that the pool pays you as its reward fee. The pool keeps earning rewards, and paying you the fee, until it leaves the validator set. Wait until the pool is no longer in the validator set, from the second epoch after the pause. Then unstake your balance from the owner account:
> [tab] Staking CLI
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near staking delegation unstake-all network-config mainnet sign-with-keychain
> ```
> [tab] Function Call
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call unstake_all '{}' --useAccount --networkId mainnet
> ```
After the 4-epoch unbonding period, withdraw it:
> [tab] Staking CLI
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near staking delegation withdraw-all network-config mainnet sign-with-keychain
> ```
> [tab] Function Call
>
> ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near call withdraw_all '{}' --useAccount --networkId mainnet
> ```
> [!NOTE]
>
> The balance that the pool held when it was created does not belong to any account. No one can unstake or withdraw it. It stays in the pool account, together with the rewards it earned. Pools created through `poolv1.near` start with at least 30 NEAR.
***
## Step 4: Resume (Optional)
If you decide to keep the pool running again, you can re-enable staking at any time:
```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
near call resume_staking '{}' --useAccount --networkId mainnet
```
# Transfers & Actions
Source: https://docs.near.org/smart-contracts/anatomy/actions
Learn how contracts can make transfers, call other contracts, and more
This page describes the different types of actions that a smart contract can perform on NEAR like transferring NEAR, calling other contracts, creating sub-accounts, and deploying contracts. It also explains how to add access keys to accounts.
Smart contracts can perform specific `Actions` such as transferring NEAR, or calling other contracts.
An important property of `Actions` is that they can be batched together when acting on the same contract. **Batched actions** act as a unit: they execute in the same [receipt](/protocol/transactions/transaction-execution#receipts--finality), and if **any fails**, then they **all get reverted**.
> [!NOTE]
>
> `Actions` can be batched only when they act on the **same contract**. You can batch calling two methods on a contract,
> but **cannot** call two methods on different contracts.
***
## Transfer NEAR Ⓝ
You can send `$NEAR` from your contract to any other account on the network. The gas cost of a transfer is set by the protocol's runtime parameters, and it depends on the type of the receiver:
| Receiver | Gas cost |
| - | - |
| Named account, for example `alice.near` | about `0.45 TGas` |
| Ethereum-like (`0x`) or deterministic (`0s`) address | about `8.15 TGas` |
| Universal (`0u`) address, from protocol version 88 (nearcore 2.14.0) | about `8.15 TGas` |
| 64-hex implicit account | about `8.35 TGas` |
For every receiver except a named account, the cost includes the fee for creating the account, even if the account already exists. For a 64-hex implicit account, it also includes the fee for adding its full access key.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_sdk::{near, AccountId, Promise, NearToken};
#[near(contract_state)]
#[derive(Default)]
pub struct Contract { }
#[near]
impl Contract {
pub fn transfer(&self, to: AccountId, amount: NearToken){
Promise::new(to).transfer(amount);
}
}
```
> [!TIP]
>
> **Why is there no callback?**
> The only case where a transfer will fail is if the receiver account does **not** exist.
> [!WARNING]
>
> Remember that your balance is used to cover for the contract's storage. When sending money, make sure you always leave enough to cover for future storage needs.
***
## Function Call
Your smart contract can call methods in another contract. In the snippet below we call a method
in a deployed [Hello NEAR](../quickstart) contract, and check if everything went
right in the callback.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_sdk::{near, env, log, Promise, Gas, PromiseError};
use serde_json::json;
#[near(contract_state)]
#[derive(Default)]
pub struct Contract { }
const HELLO_NEAR: &str = "hello-nearverse.testnet";
const NO_DEPOSIT: u128 = 0;
const CALL_GAS: Gas = Gas(5_000_000_000_000);
#[near]
impl Contract {
pub fn call_method(&self){
let args = json!({ "message": "howdy".to_string() })
.to_string().into_bytes().to_vec();
Promise::new(HELLO_NEAR.parse().unwrap())
.function_call("set_greeting".to_string(), args, NO_DEPOSIT, CALL_GAS)
.then(
Promise::new(env::current_account_id())
.function_call("callback".to_string(), Vec::new(), NO_DEPOSIT, CALL_GAS)
);
}
pub fn callback(&self, #[callback_result] result: Result<(), PromiseError>){
if result.is_err(){
log!("Something went wrong")
}else{
log!("Message changed")
}
}
}
```
> [!WARNING]
>
> The snippet showed above is a low level way of calling other methods. We recommend make calls to other contracts as explained in the [Cross-contract Calls section](/smart-contracts/anatomy/crosscontract).
***
## Create a Sub Account
Your contract can create direct sub accounts of itself, for example, `user.near` can create `sub.user.near`.
Accounts do **NOT** have control over their sub-accounts, since they have their own keys.
Sub-accounts are simply useful for organizing your accounts (e.g. `dao.project.near`, `token.project.near`).
> [!NOTE]
>
> Creating an account costs a fixed [`0.007Ⓝ`](/protocol/transactions/gas#creating-an-account), or about `0.00707Ⓝ` in total once the send fees are added. That `0.007Ⓝ` already includes the gas burned while creating the account, and it is taken out of the transaction's gas refund, not out of the deposit you attach for storage.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_sdk::{near, env, Promise, NearToken};
#[near(contract_state)]
#[derive(Default)]
pub struct Contract { }
const MIN_STORAGE: NearToken = NearToken::from_millinear(1); //0.001Ⓝ
#[near]
impl Contract {
pub fn create(&mut self, prefix: String) {
let account_id = prefix + "." + &env::current_account_id().to_string();
Promise::new(account_id.parse().unwrap())
.create_account()
.transfer(MIN_STORAGE);
}
}
```
> [!TIP]
>
> Notice that in the snippet we are transferring some money to the new account for storage
> [!WARNING]
>
> When you create an account from within a contract, it has no keys by default. If you don't explicitly [add keys](#add-keys) to it or [deploy a contract](#deploy-a-contract) on creation then it will be [locked](../../protocol/accounts-contracts/access-keys#locked-accounts).
***
#### Creating `.testnet` / `.near` Accounts
Accounts can only create immediate sub-accounts of themselves.
If your contract wants to create a `.mainnet` or `.testnet` account, then it needs to [call](#function-call)
the `create_account` method of `near` or `testnet` root contracts.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_sdk::{near, Promise, Gas, NearToken };
use serde_json::json;
#[near(contract_state)]
#[derive(Default)]
pub struct Contract { }
const CALL_GAS: Gas = Gas::from_gas(28_000_000_000_000);
const MIN_STORAGE: NearToken = NearToken::from_yoctonear(1_820_000_000_000_000_000_000); //0.00182Ⓝ
#[near]
impl Contract {
pub fn create_account(&mut self, account_id: String, public_key: String){
let args = json!({
"new_account_id": account_id,
"new_public_key": public_key,
}).to_string().into_bytes().to_vec();
// Use "near" to create mainnet accounts
Promise::new("testnet".parse().unwrap())
.function_call("create_account".to_string(), args, MIN_STORAGE, CALL_GAS);
}
}
```
***
## Create deterministic accounts
Your contract can create a [deterministic account](/protocol/accounts-contracts/account-id#deterministic-address) whose `0s` address is derived from its initial code and storage. Use the `DeterministicStateInit` action instead of `CreateAccount`; the protocol validates that the supplied account ID matches the hash of the provided initial state.
Smart contracts can build this action using the following host functions:
* `promise_batch_action_state_init` — creates a `DeterministicStateInit` action referencing a code hash
* `promise_batch_action_state_init_by_account_id` — creates the action referencing an existing account's code
* `set_state_init_data_entry` — adds a key-value entry to the account's initial storage
* `current_contract_code` — returns the calling contract's own code hash, useful for deploying clones
Any NEAR attached beyond the required storage deposit is refunded to the sender.
***
## Create universal accounts
Your contract can create a [universal account](/protocol/accounts-contracts/account-id#universal-address) whose `0u` address is derived from its initial code, storage, and access keys. Use the `UniversalStateInit` action instead of `CreateAccount`.
Smart contracts can build this action using two host functions:
* `universal_state_init_to_account_id` — derives the `0u` account ID from a state init and reports whether the bytes are valid, with no side effects
* `promise_batch_action_universal_state_init` — appends a `UniversalStateInit` action to a promise, with an attached deposit that tops up the account's storage stake if needed. Any unused amount is refunded; use a separate `Transfer` action to add to the account's balance.
See [Creating Universal Accounts](/protocol/tutorials/creating-universal-accounts#contract-triggered-creation) for a contract example and [relayer-assisted creation](/protocol/tutorials/creating-universal-accounts#relayer-assisted-creation) for details on funding.
***
## Deploy a Contract
When creating an account you can also batch the action of deploying a contract to it. Note that for this, you will need to pre-load the byte-code you want to deploy in your contract.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_sdk::{near, env, Promise, NearToken};
#[near(contract_state)]
#[derive(Default)]
pub struct Contract { }
const MIN_STORAGE: NearToken = NearToken::from_millinear(1100); //1.1Ⓝ
const HELLO_CODE: &[u8] = include_bytes!("./hello.wasm");
#[near]
impl Contract {
pub fn create_hello(&self, prefix: String){
let account_id = prefix + "." + &env::current_account_id().to_string();
Promise::new(account_id.parse().unwrap())
.create_account()
.transfer(MIN_STORAGE)
.deploy_contract(HELLO_CODE.to_vec());
}
}
```
> [!TIP]
>
> If an account with a contract deployed does **not** have any access keys, this is known as a locked contract. When the account is locked, it cannot sign transactions therefore, actions can **only** be performed from **within** the contract code.
***
## Add Keys
When you use actions to create a new account, the created account does not have any [access keys](../../protocol/accounts-contracts/access-keys), meaning that it **cannot sign transactions** (e.g. to update its contract, delete itself, transfer money).
There are two options for adding keys to the account:
1. `add_access_key`: adds a key that can only call specific methods on a specified contract.
2. `add_full_access_key`: adds a key that has full access to the account.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_sdk::{near, env, Promise, NearToken, PublicKey};
#[near(serializers = [json, borsh])]
#[derive(Default)]
pub struct Contract { }
const MIN_STORAGE: NearToken = NearToken::from_millinear(1100); //1.1Ⓝ
const HELLO_CODE: &[u8] = include_bytes!("./hello.wasm");
#[near]
impl Contract {
pub fn create_hello(&self, prefix: String, public_key: PublicKey){
let account_id = prefix + "." + &env::current_account_id().to_string();
Promise::new(account_id.parse().unwrap())
.create_account()
.transfer(MIN_STORAGE)
.deploy_contract(HELLO_CODE.to_vec())
.add_full_access_key(public_key);
}
}
```
Notice that what you actually add is a "public key". Whoever holds its private counterpart, i.e. the private-key, will be able to use the newly access key.
> [!NOTE]
>
> The `public_key` can use any of NEAR's [signature schemes](/protocol/accounts-contracts/access-keys#signature-schemes) — `ed25519`, `secp256k1`, or the post-quantum `ml-dsa-65`. Adding an `ml-dsa-65` key needs no code changes: pass an `ml-dsa-65:...` key exactly like the examples above.
> [!TIP]
>
> If an account with a contract deployed does **not** have any access keys, this is known as a locked contract. When the account is locked, it cannot sign transactions therefore, actions can **only** be performed from **within** the contract code.
***
## Delete Account
There are two scenarios in which you can use the `delete_account` action:
1. As the **last** action in a chain of batched actions.
2. To make your smart contract delete its own account.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_sdk::{near, env, Promise, NearToken, AccountId};
#[near(contract_state)]
#[derive(Default)]
pub struct Contract { }
const MIN_STORAGE: NearToken = NearToken::from_millinear(1); //0.001Ⓝ
#[near]
impl Contract {
pub fn create_delete(&self, prefix: String, beneficiary: AccountId){
let account_id = prefix + "." + &env::current_account_id().to_string();
Promise::new(account_id.parse().unwrap())
.create_account()
.transfer(MIN_STORAGE)
.delete_account(beneficiary);
}
pub fn self_delete(beneficiary: AccountId){
Promise::new(env::current_account_id())
.delete_account(beneficiary);
}
}
```
> [!WARNING]
>
> **Token Loss**
>
> If the beneficiary account does not exist the funds will be [**dispersed among validators**](../../protocol/network/token-loss).
> [!WARNING]
>
> **Token Loss**
>
> Do **not** use `delete` to try fund a new account. Since the account doesn't exist the tokens will be lost.
# Basic Anatomy
Source: https://docs.near.org/smart-contracts/anatomy/anatomy
Learn the basic anatomy of all smart contracts.
Let's illustrate the basic anatomy of a simple "Hello World" contract. The code on this page comes from our [Hello NEAR repository](https://github.com/near-examples/hello-near-examples) on GitHub.
## Importing the SDK
All contracts will import the **NEAR SDK**, enabling them to [access the execution environment](./environment), [call other contracts](./crosscontract), [transfer tokens](./actions), and much more.
You can also use third-party libraries, though some might not work due to the limitations of the contract runtime.
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_sdk::{log, near};
```
[See code on GitHub](https://github.com/near-examples/hello-near-examples/blob/be63c9f326b47d881dddaea87564fe578bcd844e/contract-rs/src/lib.rs#L2-L2)
## Contract's Main Structure
The contract is described through a structure:
* The attributes define which data the contract stores
* The functions define its public (and private) interface
Note that the contract's struct definition and the implementation are decorated with macros
The `#[near(contract_state)]` macro tells the SDK that this structure defines the contract's state, so it knows:
1. What to fetch from storage when the contract is loaded
2. What to store when the contract is done executing
The `#[near]` macro tells the SDK which functions are exposed to the outside world.
> [!NOTE]
>
> Only one struct can be decorated with the `#[near(contract_state)]` macro.
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near(contract_state)]
pub struct Contract {
greeting: String,
}
```
[See code on GitHub](https://github.com/near-examples/hello-near-examples/blob/be63c9f326b47d881dddaea87564fe578bcd844e/contract-rs/src/lib.rs#L5-L8)
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl Contract {
// Public method - returns the greeting saved, defaulting to DEFAULT_GREETING
pub fn get_greeting(&self) -> String {
self.greeting.clone()
}
// Public method - accepts a greeting, such as "howdy", and records it
pub fn set_greeting(&mut self, greeting: String) {
log!("Saving greeting: {}", greeting);
self.greeting = greeting;
}
}
```
[See code on GitHub](https://github.com/near-examples/hello-near-examples/blob/be63c9f326b47d881dddaea87564fe578bcd844e/contract-rs/src/lib.rs#L20-L32)
> [accordion] Interaction with other macros
>
> When `near` is built for the wasm32 target, it generates the external NEAR contract bindings. To achieve this it is actually generating another function with the signature `pub extern "C" fn function_name()` that first deserializes the contract struct from NEAR storage and then calls the `contract.function_name(parameter1, parameter2, ...)`.
>
> If you have annotated your function with any attribute-like macros, these are then executed *twice*. Specifically if the attribute like macro makes any modification to the function signature, or inserts any code that depends on the contract struct (in the form of `&self`, `&mut self`, or `self`) this will fail in the second invocation, because the externally exposed function does not have any concept of this struct.
>
> It is possible to detect this by checking which build target you are building for and limit the execution of the macro to operate only on the first pass.
## Storage (State)
We call the data stored in the contract [the contract's state](./storage).
In our Hello World example, the contract stores a single string (`greeting`), and the state starts initialized with the default value `"Hello"`.
> [!NOTE]
>
> We will cover more about the contract's state in the [state section](./storage).
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub struct Contract {
greeting: String,
}
```
[See code on GitHub](https://github.com/near-examples/hello-near-examples/blob/be63c9f326b47d881dddaea87564fe578bcd844e/contract-rs/src/lib.rs#L6-L8)
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
impl Default for Contract {
fn default() -> Self {
Self {
greeting: "Hello".to_string(),
}
}
}
```
[See code on GitHub](https://github.com/near-examples/hello-near-examples/blob/be63c9f326b47d881dddaea87564fe578bcd844e/contract-rs/src/lib.rs#L11-L17)
## Read Only Functions
Contract's functions can be read-only, meaning they don't modify the state. Calling them is free for everyone, and does not require to have a NEAR account.
> [!NOTE]
>
> We will cover more about function types in the [functions section](./functions).
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Public method - returns the greeting saved, defaulting to DEFAULT_GREETING
pub fn get_greeting(&self) -> String {
self.greeting.clone()
}
```
[See code on GitHub](https://github.com/near-examples/hello-near-examples/blob/be63c9f326b47d881dddaea87564fe578bcd844e/contract-rs/src/lib.rs#L22-L25)
## State Mutating Functions
Functions that modify the state or call other contracts are considered state mutating functions. It is necessary to have a NEAR account to call them, as they require a transaction to be sent to the network.
> [!NOTE]
>
> We will cover more about function types in the [functions section](./functions).
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Public method - accepts a greeting, such as "howdy", and records it
pub fn set_greeting(&mut self, greeting: String) {
log!("Saving greeting: {}", greeting);
self.greeting = greeting;
}
```
[See code on GitHub](https://github.com/near-examples/hello-near-examples/blob/be63c9f326b47d881dddaea87564fe578bcd844e/contract-rs/src/lib.rs#L27-L31)
# Best Practices
Source: https://docs.near.org/smart-contracts/anatomy/best-practices
A collection of best practices for writing smart contracts on NEAR.
This page provides a collection of best practices for writing smart contracts on NEAR. These practices are designed to help you write secure, efficient, and maintainable code.
# Best practices
Here we lay out some best practices for writing smart contracts on NEAR, such as:
* [Keep state minimal](#keep-state-minimal)
* [Store Account IDs efficiently](#store-account-ids-efficiently)
* [Enable overflow checks](#enable-overflow-checks)
* [Use `require!` early](#use-require-early)
* [Use `log!`](#use-log)
* [Return `Promise`](#return-promise)
* [Reuse crates from `near-sdk`](#reuse-crates-from-near-sdk)
* [The difference between `std::panic!` and `env::panic`](#stdpanic-vs-envpanic)
* [Test with Sandbox](#test-with-sandbox)
***
## Keep state minimal
Only store the data your contract needs to enforce its rules. Data your app only displays, such as messages or history, is already recorded in the transactions that call your contract and can be read with an indexer. Never store values you can derive from other stored values, such as a premium flag next to the amount that defines it. See [A contract is not a backend](/smart-contracts/what-is#a-contract-is-not-a-backend).
***
## Store Account IDs efficiently
You can save on smart contract storage if using NEAR Account IDs by encoding them using base32. Since they consist of `[a-z.-_]` characters with a maximum length of 64 characters, they can be encoded using 5 bits per character, with terminal `\0`. Going to a size of 65 \* 5 = 325 bits from the original (64 + 4) \* 8 = 544 bits. This is a 40% reduction in storage costs
## Enable overflow checks
It's usually helpful to panic on integer overflow. To enable it, add the following into your `Cargo.toml` file:
```toml theme={"theme":{"light":"github-light","dark":"github-dark"}}
[profile.release]
overflow-checks = true
```
## Use `require!` early
Try to validate the input, context, state and access using `require!` before taking any actions. The earlier you panic, the more [gas](/protocol/transactions/gas) you will save for the caller.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl Contract {
pub fn set_fee(&mut self, new_fee: Fee) {
require!(env::predecessor_account_id() == self.owner_id, "Owner's method");
new_fee.assert_valid();
self.internal_set_fee(new_fee);
}
}
```
**Note**: If you want debug information in the panic message or if you are using an SDK version before `4.0.0-pre.2`,
the Rust `assert!` macro can be used instead of `require!`.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl Contract {
pub fn set_fee(&mut self, new_fee: Fee) {
assert_eq!(env::predecessor_account_id(), self.owner_id, "Owner's method");
new_fee.assert_valid();
self.internal_set_fee(new_fee);
}
}
```
## Use `log!`
Use logging for debugging and notifying user.
When you need a formatted message, you can use the following macro:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
log!("Transferred {} tokens from {} to {}", amount, sender_id, receiver_id);
```
It's equivalent to the following message:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
env::log_str(format!("Transferred {} tokens from {} to {}", amount, sender_id, receiver_id).as_ref());
```
## Return `Promise`
If your method makes a cross-contract call, you probably want to return the newly created `Promise`.
This allows the caller (such as a near-cli or near-api-js call) to wait for the result of the promise instead of returning immediately.
Additionally, if the promise fails for some reason, returning it will let the caller know about the failure, as well as enabling NEAR Explorer and other tools to mark the whole transaction chain as failing.
This can prevent false-positives when the first or first few transactions in a chain succeed but a subsequent transaction fails.
E.g.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl Contract {
pub fn withdraw_100(&mut self, receiver_id: AccountId) -> Promise {
Promise::new(receiver_id).transfer(100)
}
}
```
## Reuse crates from `near-sdk`
`near-sdk` re-exports the following crates:
* `borsh`
* `base64`
* `bs58`
* `serde`
* `serde_json`
Most common crates include `borsh` which is needed for internal STATE serialization and
`serde` for external JSON serialization.
When marking structs with `serde::Serialize` you need to use `#[serde(crate = "near_sdk::serde")]`
to point serde to the correct base crate.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
/// Main contract structure serialized with Borsh
#[near(contract_state)]
#[derive(PanicOnDefault)]
pub struct Contract {
pub pair: Pair,
}
/// Implements both `serde` and `borsh` serialization.
/// `serde` is typically useful when returning a struct in JSON format for a frontend.
#[near(serializers = [json, borsh])]
pub struct Pair {
pub a: u32,
pub b: u32,
}
#[near]
impl Contract {
#[init]
pub fn new(pair: Pair) -> Self {
Self {
pair,
}
}
pub fn get_pair(self) -> Pair {
self.pair
}
}
```
## `std::panic!` vs `env::panic`
* `std::panic!` panics the current thread. It uses `format!` internally, so it can take arguments.
SDK sets up a panic hook, which converts the generated `PanicInfo` from `panic!` into a string and uses `env::panic` internally to report it to Runtime.
This may provide extra debugging information such as the line number of the source code where the panic happened.
* `env::panic` directly calls the host method to panic the contract.
It doesn't provide any other extra debugging information except for the passed message.
## Test with Sandbox
Use `near-sandbox` to run sandbox tests against a local NEAR node, and `near-api` to create accounts, deploy contracts, and send transactions. Test cross-contract calls, callback failures, refunds, and state changes as well as successful calls.
See the [sandbox-testing guide](/smart-contracts/testing/integration-test) for source-backed examples.
# Collections
Source: https://docs.near.org/smart-contracts/anatomy/collections
Efficiently store, access, and manage data in smart contracts.
When deciding on data structures it is important to understand their tradeoffs. Choosing the wrong structure can create a bottleneck as the application scales, and migrating the state to the new data structures will come at a cost.
You can choose between two types of collections:
1. Native Rust collections (e.g. `Vec`, `HashMap`, `HashSet`), provided by the language
2. Persistent collections (e.g. `IterableMap`, `Vector`), provided by `near_sdk::store`
> [!TIP]
>
> **Native vs SDK Collections**
>
> Use native collections for small amounts of data that need to be accessed altogether, and SDK collections for large amounts of data that do not need to be accessed altogether.
>
> If your collection has up to 100 entries, it's acceptable to use the native collection. For larger ones, prefer to use SDK collection. For comparison please refer to [this benchmark](https://www.github.com/volodymyr-matselyukh/near-benchmarking).
***
## Storage Management
Each time the contract is executed, the first thing it will do is to read the values and [deserialize](./serialization) them into memory, and after the function finishes, it will [serialize](./serialization) and write the values back to the database.
For native collections, the contract will fully load the collection into memory before any method executes. This happens even if the method you invoke does not use the collection. Know that this will have impact on GAS you spend for methods in your contract.
> [accordion] Storage Cost
>
> Your contract needs to lock a portion of their balance proportional to the amount of data they stored in the blockchain. This means that:
>
> * If more data is added the **storage increases ↑**, and your contract's **balance decreases ↓**.
> * If data is deleted the **storage decreases ↓**, and your contract's **balance increases ↑**.
>
> Currently, it costs approximately **1 Ⓝ** to store **100kb** of data.
> [accordion] Storage Constraints on NEAR
>
> For storing data on-chain it’s important to keep in mind the following:
>
> * A [single transaction](/protocol/transactions/transaction-anatomy#transaction-limits) can be at most 1.5 MiB (1,572,864 bytes), including its arguments or contract code
>
> Let’s say for example, someone wants to put an NFT purely on-chain (rather than IPFS or some other decentralized storage solution) you’ll have almost an unlimited amount of storage but will have to pay 1 `$NEAR` per 100kb of storage used.
>
> Each transaction is limited to 1.5 MiB in size. This is a size limit, separate from the gas limit. The maximum amount of gas you can attach to a transaction is 1 PGas (1,000 TGas). Before protocol version 83 (nearcore 2.11.0), the limit was 300 TGas.
> [!WARNING]
>
> Your contract will panic if you try to store data but don't have NEAR to cover its storage cost
> [!CAUTION]
>
> Be mindful of potential [small deposit attacks](../security/storage)
***
## Native Collections
Native collections are those provided by the language, such as `Vec`, `HashMap`, `HashSet` in Rust.
All entries in a native collection are **serialized into a single value** and **stored together** into the state. This means that every time a function execute, the SDK will read and **deserialize all entries** in the native collection.
> [accordion] Serialization & Storage Example
>
> The array `[1,2,3,4]` will be serialized into the Borsh byte-stream `[0,0,0,4,1,2,3,4]` before being stored
> [!TIP]
>
> **When to use them**
>
> Native collections are useful if you are planning to store smalls amounts of data that need to be accessed all together
> [!CAUTION]
>
> **Keep Native Collections Small**
>
> As the native collection grows, deserializing it from memory will cost more and more gas. If the collections grows too large, your contract might expend all the gas trying to read its state, making it fail on each function call
***
## SDK Collections
The Rust SDK exposes `near_sdk::store` collections that are optimized for random access of large amounts of data. SDK collections are instantiated using a "prefix", which is used as an index to split the data into chunks. This way, SDK collections can defer reading and writing to the store until needed.
> [accordion] Serialization & Storage Example
>
> The sdk array `[1,2,3,4]` with prefix `"p"` will be stored as the string `"p"` in the contract's attribute, and create four entries in the contract's storage: `p-0:1`, `p-1:2`...
> [accordion] SDK Collections' Features
>
> | Type | SDK Module | Iterable | Clear All Values | Preserves Insertion Order | Range Selection |
> | - | :-: | :-: | :-: | :-: | :-: |
> | `Vector` | `near_sdk::store` | ✅ | ✅ | ✅ | ✅ |
> | `LookupSet` | `near_sdk::store` | | | | |
> | `IterableSet` | `near_sdk::store` | ✅ | ✅ | | ✅ |
> | `LookupMap` | `near_sdk::store` | | | | |
> | `IterableMap` | `near_sdk::store` | ✅ | ✅ | | ✅ |
> [accordion] SDK Collections' Time Complexities
>
> | Type | Access | Insert | Delete | Search | Traverse | Clear |
> | - | :-: | :-: | :-: | :-: | :-: | :-: |
> | `Vector` | O(1) | O(1)\* | O(1)\*\* | O(n) | O(n) | O(n) |
> | `LookupSet` | O(1) | O(1) | O(1) | O(1) | N/A | N/A |
> | `IterableSet` | O(1) | O(1) | O(1) | O(1) | O(n) | O(n) |
> | `LookupMap` | O(1) | O(1) | O(1) | O(1) | N/A | N/A |
> | `IterableMap` | O(1) | O(1) | O(1) | O(1) | O(n) | O(n) |
>
> *\* - to insert at the end of the vector using `push`*
> *\*\* - to delete from the end of the vector using `pop`, or delete using `swap_remove` which swaps the element with the last element of the vector and then removes it.*
These collections are built to have an interface similar to native collections.
> [!TIP]
>
> **when to use them**
>
> SDK collections are useful when you are planning to store large amounts of data that do not need to be accessed all together
### Instantiation
All structures need to be initialized using a **unique `prefix`**, which will be used to index the collection's values in the account's state
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Define the contract structure
#[near(contract_state)]
pub struct StorageExample {
pub vector: Vector,
pub lookup_set: LookupSet,
pub iterable_set: IterableSet,
pub lookup_map: LookupMap,
pub iterable_map: IterableMap,
pub nested: LookupMap>,
}
// Define the default, which automatically initializes the contract
impl Default for StorageExample {
fn default() -> Self {
Self {
vector: Vector::new(Prefix::Vector),
lookup_set: LookupSet::new(Prefix::LookupSet),
iterable_set: IterableSet::new(Prefix::IterableSet),
lookup_map: LookupMap::new(Prefix::LookupMap),
iterable_map: IterableMap::new(Prefix::IterableMap),
nested: LookupMap::new(Prefix::Root),
}
}
}
```
[See code on GitHub](https://github.com/near-examples/storage-examples/blob/9dfeb4e29c77f04ff4de220d241e56f1502a587b/collections-rs/store/src/lib.rs#L24-L47)
> [!TIP]
>
> Notice how the `BorshStorageKey` enum gives each collection a distinct prefix. Variants carrying data, such as `Nested(String)`, include that data in their serialized prefix.
> [!WARNING]
>
> If you see a `unresolved import near_sdk::BorshIntoStorageKey` compiler error, your code is following an outdated pattern from `near-sdk < 4.0`.
>
> To fix it, derive [`BorshStorageKey`](https://docs.rs/near-sdk/latest/near_sdk/derive.BorshStorageKey.html) on your prefix enum.
> [!CAUTION]
>
> Be careful of not using the same prefix in two collections, otherwise, their storage space will collide, and you might overwrite information from one collection when writing in the other
***
### Vector
Implements a [vector/array](https://en.wikipedia.org/wiki/Array_data_structure) that persists in the contract's storage. See the [Rust SDK collections reference](https://docs.rs/near-sdk/latest/near_sdk/store/index.html) for its complete interface.
```rust title="vector.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl StorageExample {
pub fn push(&mut self, value: i32) {
self.vector.push(value);
}
pub fn get(&self, index: u32) -> i32 {
self.vector[index]
}
pub fn replace(&mut self, index: u32, value: i32) {
self.vector[index] = value;
}
pub fn len(&self) -> u32 {
self.vector.len()
}
pub fn iter(&self, from_index: i32, limit: i32) -> Vec<&i32> {
self.vector
.iter()
.skip(from_index as usize)
.take(limit as usize)
.collect()
}
}
```
[See code on GitHub](https://github.com/near-examples/storage-examples/blob/9dfeb4e29c77f04ff4de220d241e56f1502a587b/collections-rs/store/src/vector.rs#L4-L29)
***
### LookupMap
Implements a [map/dictionary](https://en.wikipedia.org/wiki/Associative_array) that persists in the contract's storage. See the [Rust SDK collections reference](https://docs.rs/near-sdk/latest/near_sdk/store/index.html) for its complete interface.
```rust title="lookup_map.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl StorageExample {
pub fn insert_map(&mut self, key: String, value: i32) {
self.lookup_map.insert(key, value);
}
pub fn remove_map(&mut self, key: String) {
self.lookup_map.remove(&key);
}
pub fn get_map(&self, key: String) -> i32 {
self.lookup_map[&key]
}
pub fn contains_key_map(&self, key: String) -> bool {
self.lookup_map.contains_key(&key)
}
}
```
[See code on GitHub](https://github.com/near-examples/storage-examples/blob/9dfeb4e29c77f04ff4de220d241e56f1502a587b/collections-rs/store/src/lookup_map.rs#L4-L22)
***
### IterableMap
Implements a [map/dictionary](https://en.wikipedia.org/wiki/Associative_array) that persists in the contract's storage. See the [Rust SDK collections reference](https://docs.rs/near-sdk/latest/near_sdk/store/index.html) for its complete interface.
```rust title="iterable_map.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl StorageExample {
pub fn insert_iterable_map(&mut self, key: String, value: i32) {
self.iterable_map.insert(key, value);
}
pub fn remove_iterable_map(&mut self, key: String) {
self.iterable_map.remove(&key);
}
pub fn get_iterable_map(&self, key: String) -> i32 {
self.iterable_map[&key]
}
pub fn contains_key_iterable_map(&self, key: String) -> bool {
self.iterable_map.contains_key(&key)
}
pub fn iter_iterable_map(&self, from_index: i32, limit: i32) -> Vec<(&String, &i32)> {
self.iterable_map
.iter()
.skip(from_index as usize)
.take(limit as usize)
.collect()
}
}
```
[See code on GitHub](https://github.com/near-examples/storage-examples/blob/9dfeb4e29c77f04ff4de220d241e56f1502a587b/collections-rs/store/src/iterable_map.rs#L4-L29)
***
### LookupSet
Implements a [set](https://en.wikipedia.org/wiki/Set_\(abstract_data_type\)) that persists in the contract's storage. See the [Rust SDK collections reference](https://docs.rs/near-sdk/latest/near_sdk/store/index.html) for its complete interface.
```rust title="lookup_set.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl StorageExample {
pub fn insert_set(&mut self, value: i32) {
self.lookup_set.insert(value);
}
pub fn remove_set(&mut self, value: i32) {
self.lookup_set.remove(&value);
}
pub fn contains_set(&self, value: i32) -> bool {
self.lookup_set.contains(&value)
}
}
```
[See code on GitHub](https://github.com/near-examples/storage-examples/blob/9dfeb4e29c77f04ff4de220d241e56f1502a587b/collections-rs/store/src/lookup_set.rs#L4-L18)
***
### IterableSet
Implements a [set](https://en.wikipedia.org/wiki/Set_\(abstract_data_type\)) that persists in the contract's storage. See the [Rust SDK collections reference](https://docs.rs/near-sdk/latest/near_sdk/store/index.html) for its complete interface.
```rust title="iterable_set.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl StorageExample {
pub fn insert_iterable_set(&mut self, value: i32) {
self.iterable_set.insert(value);
}
pub fn remove_iterable_set(&mut self, value: i32) {
self.iterable_set.remove(&value);
}
pub fn contains_iterable_set(&self, value: i32) -> bool {
self.iterable_set.contains(&value)
}
pub fn iter_iterable_set(&self, from_index: i32, limit: i32) -> Vec<&i32> {
self.iterable_set
.iter()
.skip(from_index as usize)
.take(limit as usize)
.collect()
}
}
```
[See code on GitHub](https://github.com/near-examples/storage-examples/blob/9dfeb4e29c77f04ff4de220d241e56f1502a587b/collections-rs/store/src/iterable_set.rs#L4-L26)
***
## Nesting Collections
When nesting SDK collections, be careful to **use different prefixes** for all collections, including the nested ones.
```rust title="nested.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl StorageExample {
pub fn insert_nested(&mut self, key: String, value: i32) {
if self.nested.contains_key(&key) {
let vector = self.nested.get_mut(&key).expect("Wrong key");
vector.push(value);
} else {
let mut vector = Vector::new(Prefix::Nested(key.clone()));
vector.push(value);
self.nested.insert(key, vector);
}
}
pub fn remove_nested(&mut self, key: String) {
let vector = self.nested.get_mut(&key).expect("Wrong key");
vector.clear();
self.nested.remove(&key);
}
pub fn get_nested(&self, key: String) -> Vec<&i32> {
self.nested[&key].iter().collect()
}
pub fn contains_key_nested(&self, key: String) -> bool {
self.nested.contains_key(&key)
}
}
```
[See code on GitHub](https://github.com/near-examples/storage-examples/blob/9dfeb4e29c77f04ff4de220d241e56f1502a587b/collections-rs/store/src/nested.rs#L4-L30)
> [!TIP]
>
> Notice how we use `enums` that take a `String` argument to ensure all collections have a different prefix
***
## Error prone patterns
Because the values are not kept in memory and are lazily loaded from storage, it's important to make sure if a collection is replaced or removed, that the storage is cleared. In addition, it is important that if the collection is modified, the collection itself is updated in state because most collections will store some metadata.
Some error-prone patterns to avoid that cannot be restricted at the type level are:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_sdk::store::IterableMap;
let mut m = IterableMap::::new(b"m");
m.insert(1, "test".to_string());
assert_eq!(m.len(), 1);
assert_eq!(m.get(&1), Some(&"test".to_string()));
// Bug 1: Should not replace any collections without clearing state, this will reset any
// metadata, such as the number of elements, leading to bugs. If you replace the collection
// with something with a different prefix, it will be functional, but you will lose any
// previous data and the old values will not be removed from storage.
m = IterableMap::new(b"m");
assert!(m.is_empty());
assert_eq!(m.get(&1), Some(&"test".to_string()));
// Bug 2: Should not use the same prefix as another collection
// or there will be unexpected side effects.
let m2 = IterableMap::::new(b"m");
assert!(m2.is_empty());
assert_eq!(m2.get(&1), Some(&"test".to_string()));
// Bug 3: forgetting to save the collection in storage. When the collection is attached to
// the contract state (`self` in `#[near]`) this will be done automatically, but if
// interacting with storage manually or working with nested collections, this is relevant.
use near_sdk::store::Vector;
// Simulate roughly what happens during a function call that initializes state.
{
let v = Vector::::new(b"v");
near_sdk::env::state_write(&v);
}
// Simulate what happens during a function call that just modifies the collection
// but does not store the collection itself.
{
let mut v: Vector = near_sdk::env::state_read().unwrap();
v.push(1);
// The bug is here that the collection itself if not written back
}
let v: Vector = near_sdk::env::state_read().unwrap();
// This will report as if the collection is empty, even though the element exists
assert!(v.get(0).is_none());
assert!(
near_sdk::env::storage_read(&[b"v".as_slice(), &0u32.to_le_bytes()].concat()).is_some()
);
// Bug 4 (only relevant for `near_sdk::store`): These collections will cache writes as well
// as reads, and the writes are performed on [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html)
// so if the collection is kept in static memory or something like `std::mem::forget` is used,
// the changes will not be persisted.
use near_sdk::store::IterableSet;
let mut m: IterableSet = IterableSet::new(b"l");
m.insert(1);
assert!(m.contains(&1));
// This would be the fix, manually flushing the intermediate changes to storage.
// m.flush();
std::mem::forget(m);
m = IterableSet::new(b"l");
assert!(!m.contains(&1));
```
***
## Pagination
Persistent collections such as `IterableMap`, `IterableSet`, and `Vector` may
contain more elements than the amount of gas available to read them all.
In order to expose them all through view calls, we can use pagination.
With Rust this can be done using iterators with [`Skip`](https://doc.rust-lang.org/std/iter/struct.Skip.html) and [`Take`](https://doc.rust-lang.org/std/iter/struct.Take.html). This will only load elements from storage within the range.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near(contract_state)]
#[derive(PanicOnDefault)]
pub struct Contract {
pub status_updates: IterableMap,
}
#[near]
impl Contract {
/// Retrieves multiple elements from the `IterableMap`.
/// - `from_index` is the index to start from.
/// - `limit` is the maximum number of elements to return.
pub fn get_updates(&self, from_index: usize, limit: usize) -> Vec<(AccountId, String)> {
self.status_updates
.iter()
.skip(from_index)
.take(limit)
.map(|(account_id, update)| (account_id.clone(), update.clone()))
.collect()
}
}
```
## Running the Examples
The [Rust collection examples](https://github.com/near-examples/storage-examples) include unit tests and a local sandbox test covering the `near_sdk::store` collections shown above. The sandbox test builds the contract from source and uses `near-sandbox` with `near-api` to check collection operations through contract calls.
From the repository root, run:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cargo install cargo-near --version 0.21.1 --locked --no-default-features
cargo test --locked
```
# Cross-Contract Calls
Source: https://docs.near.org/smart-contracts/anatomy/crosscontract
Contract can interact with other contracts on the network
NEAR contracts can interact with other deployed contracts, querying information and executing functions on them through cross-contract calls.
Since NEAR is a sharded blockchain, its cross-contract calls behave differently than in other chains. In NEAR, cross-contract calls are **asynchronous** and **independent**.
> [!TIP]
>
> **Asynchronous**
> The **calling function** and the **callback** execute in **different blocks** (typically 1-2 blocks apart). During this time, the contract remains active and can receive other calls.
> [!TIP]
>
> **Independent**
>
> Each function — the one making the call, the external function, and the callback — executes in its own context. If the external call fails, the calling function has already completed successfully; there's no automatic rollback. You must handle failures explicitly in the callback.
***
## Snippet: Querying Information
While making your contract, it is likely that you will want to query information from another contract. Below, you can see a basic example in which we query the greeting message from our [Hello NEAR](../quickstart) example.
> [tab] low\_level.rs
>
> ```rust title="low_level.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Public - query external greeting
> pub fn ll_query_greeting(&self) -> Promise {
> // Create a promise to call HelloNEAR.get_greeting()
> let hello_promise = Promise::new(self.hello_account.clone()).function_call(
> "get_greeting".to_owned(),
> NO_ARGS,
> NO_DEPOSIT,
> TEN_TGAS,
> );
>
> hello_promise.then(
> // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .with_static_gas(TEN_TGAS)
> .ll_query_greeting_callback(),
> )
> }
>
> #[private] // Public - but only callable by env::current_account_id()
> pub fn ll_query_greeting_callback(
> &self,
> #[callback_result] call_result: Result,
> ) -> String {
> // Check if the promise succeeded by calling the method outlined in external.rs
> if call_result.is_err() {
> log!("There was an error contacting Hello NEAR");
> return "".to_string();
> }
>
> // Return the greeting
> let greeting: String = call_result.unwrap();
> greeting
> }
> ```
>
> [See code on GitHub](https://github.com/near-examples/cross-contract-calls/blob/f33e6ded02103ed987ffbc381b3ffc6307986a7a/contract-simple-rs/src/low_level.rs#L7-L39)
> [tab] high\_level.rs
>
> ```rust title="high_level.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Public - query external greeting
> pub fn hl_query_greeting(&self) -> Promise {
> // Create a promise to call HelloNEAR.get_greeting()
> let promise = hello_near::ext(self.hello_account.clone())
> .with_static_gas(FIVE_TGAS)
> .get_greeting();
>
> promise.then(
> // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .with_static_gas(FIVE_TGAS)
> .hl_query_greeting_callback(),
> )
> }
>
> #[private] // Public - but only callable by env::current_account_id()
> pub fn hl_query_greeting_callback(
> &self,
> #[callback_result] call_result: Result,
> ) -> String {
> // Check if the promise succeeded by calling the method outlined in external.rs
> if call_result.is_err() {
> log!("There was an error contacting Hello NEAR");
> return "".to_string();
> }
>
> // Return the greeting
> let greeting: String = call_result.unwrap();
> greeting
> }
> ```
>
> [See code on GitHub](https://github.com/near-examples/cross-contract-calls/blob/f33e6ded02103ed987ffbc381b3ffc6307986a7a/contract-simple-rs/src/high_level.rs#L8-L37)
>
> The high level API makes use of the interface defined in the [ext\_contract.rs](https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-rs/src/external_contract.rs)
***
## Snippet: Sending Information
Calling another contract passing information is also a common scenario. Below you can see a function that interacts with the [Hello NEAR](../quickstart) example to change its greeting message.
> [tab] low\_level.rs
>
> ```rust title="low_level.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Public - change external greeting
> pub fn ll_change_greeting(&mut self, new_greeting: String) -> Promise {
> let args = json!({ "greeting": new_greeting }).to_string().into_bytes();
> let hello_promise = Promise::new(self.hello_account.clone()).function_call(
> "set_greeting".to_owned(),
> args,
> NO_DEPOSIT,
> TEN_TGAS,
> );
>
> hello_promise.then(
> // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .with_static_gas(TEN_TGAS)
> .ll_change_greeting_callback(),
> )
> }
>
> #[private]
> pub fn ll_change_greeting_callback(
> &mut self,
> #[callback_result] call_result: Result<(), PromiseError>,
> ) -> bool {
> // Return whether or not the promise succeeded using the method outlined in external.rs
> if call_result.is_err() {
> env::log_str("set_greeting failed...");
> false
> } else {
> env::log_str("set_greeting was successful!");
> true
> }
> }
> ```
>
> [See code on GitHub](https://github.com/near-examples/cross-contract-calls/blob/f33e6ded02103ed987ffbc381b3ffc6307986a7a/contract-simple-rs/src/low_level.rs#L41-L72)
> [tab] high\_level.rs
>
> ```rust title="high_level.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Public - change external greeting
> pub fn hl_change_greeting(&mut self, new_greeting: String) -> Promise {
> // Create a promise to call HelloNEAR.set_greeting(message:string)
> hello_near::ext(self.hello_account.clone())
> .with_static_gas(FIVE_TGAS)
> .set_greeting(new_greeting)
> .then(
> // Create a callback change_greeting_callback
> Self::ext(env::current_account_id())
> .with_static_gas(FIVE_TGAS)
> .hl_change_greeting_callback(),
> )
> }
>
> #[private]
> pub fn hl_change_greeting_callback(
> &mut self,
> #[callback_result] call_result: Result<(), PromiseError>,
> ) -> bool {
> // Return whether or not the promise succeeded using the method outlined in external.rs
> if call_result.is_err() {
> env::log_str("set_greeting failed...");
> false
> } else {
> env::log_str("set_greeting was successful!");
> true
> }
> }
> ```
>
> [See code on GitHub](https://github.com/near-examples/cross-contract-calls/blob/f33e6ded02103ed987ffbc381b3ffc6307986a7a/contract-simple-rs/src/high_level.rs#L39-L66)
>
> The high level API makes use of the interface defined in the [ext\_contract.rs](https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-rs/src/external_contract.rs)
***
## Promises
Cross-contract calls work by creating two promises in the network:
1. A promise to execute code in the external contract - `Promise.create`
2. **Optional**: A promise to call another function with the result - `Promise.then`
Both promises will contain the following information:
* The **address** of the contract you want to interact with
* The **function** that you want to execute
* The arguments to pass to the function
* The amount of **GAS** to use (deducted from the **attached Gas**)
* The NEAR **deposit** to attach (deducted from **your contract's balance**)
> [!TIP]
>
> The callback can be made to **any** contract. Meaning that the result could potentially be handled by another contract
***
## Creating a Cross Contract Call
To create a cross-contract call with a callback, create two promises and use the `.then` method to link them:
> [tab] High Level API
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> #[ext_contract(external_trait)]
> trait Contract {
> fn function_name(&self, param1: T, param2: T) -> T;
> }
>
> external_trait::ext("external_address")
> .with_attached_deposit(DEPOSIT)
> .with_static_gas(GAS)
> .function_name(arguments)
> .then(
> // this is the callback
> Self::ext(env::current_account_id())
> .with_attached_deposit(DEPOSIT)
> .with_static_gas(GAS)
> .callback_name(arguments)
> );
>
> ```
> [tab] Low Level API
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> let arguments = json!({ "foo": "bar" })
> .to_string()
> .into_bytes();
>
> let promise = Promise::new("external_address").function_call(
> "function_name".to_owned(),
> arguments,
> DEPOSIT,
> GAS
> );
>
> promise.then(
> // Create a promise to callback query_greeting_callback
> Self::ext(env::current_account_id())
> .with_static_gas(GAS)
> .callback_name(),
> );
> ```
> [accordion] Concatenating Promises
>
> ✅ You can concatenate promises: `P1.then(P2).then(P3)`: `P1` executes, then `P2` executes with the result of `P1`, then `P3` executes with the result of `P2`
>
> ✅ You can join promises: `(P1.and(P2)).then(P3)`: `P1` and `P2` execute in parallel, after they finish `P3` will execute and have access to **both their results**
>
> ⛔ You cannot **return** a joint promise without a callback: `return P1.and(P2)` is invalid, you need to add a `.then()`
>
> ⛔ You cannot join promises within a `then`: `P1.then(P2.join([P3]))` is invalid
>
> ⛔ You cannot use a `then` within a `then`: `P1.then(P2.then(P3))` is invalid
> [!NOTE]
>
> If a function returns a promise, then it will delegate the return value and status of transaction execution, but if you return a value or nothing, then the `Promise` result will not influence the transaction status
> [!WARNING]
>
> The Promises you are creating will **not execute immediately**. In fact, they will be queued in the network an:
>
> * The cross-contract call will execute 1 or 2 blocks after your function finishes **correctly**.
### Attaching gas
Each promise in a cross-contract call needs enough gas to execute. This includes the external call and any callback you attach with `.then`.
> [!TIP]
>
> Always reserve gas for the callback. It executes in a separate receipt, so it can fail independently if it does not receive enough gas.
In the high level API, `with_static_gas(gas)` reserves a fixed amount of gas for a promise:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
const CALL_GAS: Gas = Gas::from_tgas(10);
const CALLBACK_GAS: Gas = Gas::from_tgas(5);
external_trait::ext("external_address")
.with_static_gas(CALL_GAS)
.function_name(arguments)
.then(
Self::ext(env::current_account_id())
.with_static_gas(CALLBACK_GAS)
.callback_name(arguments)
);
```
The high level API also exposes `with_unused_gas_weight(weight)`, which gives a promise a proportional share of the gas left after all static gas has been reserved.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
external_trait::ext("external_address")
.with_static_gas(Gas::from_tgas(10))
.with_unused_gas_weight(2)
.function_name(arguments)
.then(
Self::ext(env::current_account_id())
.with_static_gas(Gas::from_tgas(5))
.with_unused_gas_weight(0)
.callback_name(arguments)
);
```
The default unused gas weight is `1`. Set the weight to `0` when you want a promise to receive only its static gas reservation.
For example, if `100 Tgas` is left when you create two promises:
| Promise | Static gas | Unused gas weight |
| - | - | - |
| A | `20 Tgas` | `1` |
| B | `10 Tgas` | `3` |
The runtime reserves `30 Tgas` as static gas, then distributes the remaining `70 Tgas` by weight:
* **A** gets `20 + (1/4) * 70 = 37.5 Tgas`
* **B** gets `10 + (3/4) * 70 = 62.5 Tgas`
> [!WARNING]
>
> If you forget that the default weight is `1`, a callback or parallel promise can receive more of the remaining gas than you expected. For gas-sensitive calls, combine `with_static_gas` with `with_unused_gas_weight(0)` on promises that should not draw from the unused gas pool.
The low level API (`Promise::new(...).function_call(...)`) takes a fixed gas value. It behaves like `with_static_gas` and does not use unused gas weights.
***
## Callback Function
If your function finishes correctly, the callback always runs, whether the **external contract fails or not**. If it failed, the callback receives `PromiseResult::Failed`.
In the callback function you will have access to the result, which will contain the status of the external function (if it worked or not), and the values in case of success.
```rust title="high_level.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[private] // Public - but only callable by env::current_account_id()
pub fn hl_query_greeting_callback(
&self,
#[callback_result] call_result: Result,
) -> String {
// Check if the promise succeeded by calling the method outlined in external.rs
if call_result.is_err() {
log!("There was an error contacting Hello NEAR");
return "".to_string();
}
// Return the greeting
let greeting: String = call_result.unwrap();
greeting
}
```
[See code on GitHub](https://github.com/near-examples/cross-contract-calls/blob/f33e6ded02103ed987ffbc381b3ffc6307986a7a/contract-simple-rs/src/high_level.rs#L23-L37)
> [!WARNING]
>
> **The callback always runs, but it can still fail**
>
> The callback can run out of gas, panic, or hit a runtime limit. If it fails, only its own state changes are reverted: anything your original function already changed stays. See [callbacks can fail](/smart-contracts/security/cross-contract-calls/callback-failures).
> [!TIP]
>
> Remember to mark your callback function as private using macros/decorators, so it can only be called by the contract itself
### What happens if the function I call fails?
If the external function fails (i.e. it panics), then your callback will be **executed anyway**. Here you need to **manually rollback** any changes made in your
contract during the original call. Particularly:
1. **Refund the predecessor** if needed: If the contract attached NEAR to the call, the funds are now back in **the contract's account**
2. **Revert any state changes**: If the original function made any state changes (i.e. changed or stored data), you need to manually roll them back. **They won't revert automatically**
> [!WARNING]
>
> If your original function finishes correctly then the callback executes **even if the external function panics**. Your state will **not** rollback automatically,
> and `$NEAR` will **not** be returned to the signer automatically. Always make sure to check in the callback if the external function failed, and manually rollback any
> operation if necessary.
***
## Calling Multiple Functions on the Same Contract
You can call multiple functions in the same external contract, which is known as a **batch call**.
An important property of batch calls is that they **act as a unit**: they execute in the same [receipt](/protocol/transactions/transaction-execution#receipts--finality), and if **any function fails**, then they **all get reverted**.
```rust title="batch_actions.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub fn batch_actions(&mut self) -> Promise {
let hi = json!({ "greeting": "hi" }).to_string().into_bytes();
let bye = json!({ "greeting": "bye" }).to_string().into_bytes();
// You can create one transaction calling multiple methods
// on a same contract
Promise::new(self.hello_account.clone())
.function_call("set_greeting".to_owned(), hi, NO_DEPOSIT, XCC_GAS)
.function_call("get_greeting".to_owned(), NO_ARGS, NO_DEPOSIT, XCC_GAS)
.function_call("set_greeting".to_owned(), bye, NO_DEPOSIT, XCC_GAS)
.function_call("get_greeting".to_owned(), NO_ARGS, NO_DEPOSIT, XCC_GAS)
.then(Self::ext(env::current_account_id()).batch_actions_callback())
}
```
[See code on GitHub](https://github.com/near-examples/cross-contract-calls/blob/f33e6ded02103ed987ffbc381b3ffc6307986a7a/contract-advanced-rs/src/batch_actions.rs#L8-L20)
> [!TIP]
>
> Callbacks only have access to the result of the **last function** in a batch call
***
## Calling Multiple Functions on Different Contracts
You can also call multiple functions in **different contracts**. These functions will be executed in parallel, and do not impact each other. This means that, if one fails, the others **will execute, and NOT be reverted**.
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub fn multiple_contracts(&mut self) -> Promise {
// We create a promise that calls the `get_greeting` function on the HELLO_CONTRACT
let hello_promise = Promise::new(self.hello_account.clone()).function_call(
"get_greeting".to_owned(),
NO_ARGS,
NO_DEPOSIT,
XCC_GAS,
);
// We create a promise that calls the `get_num` function on the COUNTER_CONTRACT
let counter_promise = Promise::new(self.counter_account.clone()).function_call(
"get_num".to_owned(),
NO_ARGS,
NO_DEPOSIT,
XCC_GAS,
);
// We create a promise that calls the `get_messages` function on the GUESTBOOK_CONTRACT
let args = json!({ "from_index": "0", "limit": 2 })
.to_string()
.into_bytes();
let guestbook_promise = Promise::new(self.guestbook_account.clone()).function_call(
"get_messages".to_owned(),
args,
NO_DEPOSIT,
XCC_GAS,
);
// We join all promises and chain a callback to collect their results.
hello_promise
.and(counter_promise)
.and(guestbook_promise)
.then(
Self::ext(env::current_account_id())
.with_static_gas(XCC_GAS)
.multiple_contracts_callback(),
)
}
```
[See code on GitHub](https://github.com/near-examples/cross-contract-calls/blob/f33e6ded02103ed987ffbc381b3ffc6307986a7a/contract-advanced-rs/src/multiple_contracts.rs#L17-L55)
> [!TIP]
>
> Callbacks have access to the result of **all functions** in a parallel call
***
## Security Concerns
While writing cross-contract calls there is a significant aspect to keep in mind: all the calls are **independent** and **asynchronous**. In other words:
* The function in which you make the call and function for the callback are **independent**.
* There is a **delay between the call and the callback**, in which people can still interact with the contract
This has important implications on how you should handle the callbacks. Particularly:
1. Make sure you don't leave the contract in a exploitable state between the call and the callback.
2. Manually rollback any changes to the state in the callback if the external call failed.
3. Make sure the contract stays safe if the callback itself fails. See [callbacks can fail](/smart-contracts/security/cross-contract-calls/callback-failures).
We have a whole [security section](/smart-contracts/security/cross-contract-calls/callbacks) dedicated to these specific errors, so please go and check it.
> [!WARNING]
>
> Not following these basic security guidelines could expose your contract to exploits. Please check the [security section](/smart-contracts/security/cross-contract-calls/callbacks), and if still in doubt, [join us in Discord](https://near.chat).
# Environment
Source: https://docs.near.org/smart-contracts/anatomy/environment
Know which account called you, how much gas and tokens were attached, and more.
The environment is a set of variables and functions that are available to your smart contract when it is executed. It provides information such as who called the method, how much money was attached to the call, and how many computational resources are available.
Every method execution has an environment associated with information such as:
1. Who called the method
2. How much money is attached to the call
3. How many computational resources are available
4. The current timestamp
5. Helper functions for Public Key derivation, for example
***
## Environment Variables
| Variable Name | SDK Variable | Description |
| - | - | - |
| Predecessor | `env::predecessor_account_id()` | Account ID that called this method |
| Current Account | `env::current_account_id()` | Account ID of this smart contract |
| Signer | `env::signer_account_id()` | Account ID that signed the transaction leading to this execution |
| Attached Deposit | `env::attached_deposit()` | Amount in yoctoNEAR attached to the call by the predecessor |
| Account Balance | `env::account_balance()` | Balance of this smart contract (including Attached Deposit) |
| Prepaid Gas | `env::prepaid_gas()` | Amount of gas available for execution |
| Timestamp | `env::block_timestamp()` | Current timestamp (number of non-leap-nanoseconds since January 1, 1970 0:00:00 UTC) |
| Current Epoch | `env::epoch_height()` | Current epoch in the blockchain |
| Block Index | `env::block_index()` | Current block index (a.k.a. block height) |
| Storage Used | `env::storage_usage()` | Current storage used by this smart contract in bytes |
| Storage Byte Cost | `env::storage_byte_cost()` | Current storage cost per byte in yoctoNEAR |
| Used Gas | `env::used_gas()` | Amount of gas used for execution |
| Signer Public Key | `env::signer_account_pk()` | Sender Public Key |
| Account Locked Balance | `env::account_locked_balance()` | Balance of this smart contract that is locked |
***
## Who is Calling? Who am I?
The environment gives you access to 3 important users: the `current_account`, the `predecessor`, and the `signer`.
### Current Account
The `current_account` contains the address in which your contract is deployed. This is very useful to implement ownership, e.g. making a public method only callable by the contract itself.
### Predecessor and Signer
The `predecessor` is the account that called the method in the contract. Meanwhile, the `signer` is the account that *signed* the initial transaction.
During a simple transaction (no [cross-contract calls](../anatomy/crosscontract)) the `predecessor` is the same as the `signer`. For example, if **alice.near** calls **contract.near**, from the contract's perspective, **alice.near** is both the `signer` and the `predecessor`. However, if **contract.near** creates a [cross-contract call](../anatomy/crosscontract), then the `predecessor` changes down the line. In the example below, when **pool.near** executes, it would see **contract.near** as the `predecessor` and **alice.near** as the `signer`.

*You can access information about the users interacting with your smart contract*
> [!TIP]
>
> Use the predecessor to authorize the account calling the current method. For example, a token receiver uses it to check which [FT contract](/primitives/ft/ft#attaching-fts-to-a-call) or [NFT contract](/primitives/nft/nft#attaching-nfts-to-a-call) called it. The signer identifies the account that signed the original transaction, which can differ from the contract making the current call.
> [!NOTE]
>
> `signer_account_pk` returns the signer's public key as a near-sdk-rs `PublicKey` — not a preformatted `:` string. If the transaction was signed with a post-quantum [`ml-dsa-65`](/protocol/accounts-contracts/access-keys#signature-schemes) key, that public key is much larger — 1952 bytes, versus 32 for `ed25519` — so keep that in mind if your contract stores, compares, or serializes signer public keys.
***
## Balances and Attached NEAR
The environment gives you access to 3 token-related parameters, all expressed in yoctoNEAR (1 Ⓝ = 1024yⓃ):
### Attached Deposit
`attached_deposit` represents the amount of yoctoNEAR the predecessor attached to the call.
This amount is **already deposited** in your contract's account, and is **automatically returned** to the `predecessor` if your **method panics**.
> [!WARNING]
>
> If you make a [cross-contract call](../anatomy/crosscontract) and it panics, the funds are sent back to **your contract**. See how to handle this situation in the [callback section](../anatomy/crosscontract#what-happens-if-the-function-i-call-fails)
### Account Balance
`account_balance` represents the balance of your contract (`current_account`).
It includes the `attached_deposit`, since it was deposited when the method execution started.
If the contract has any locked `$NEAR`, it will appear in `account_locked_balance`.
***
### Storage Used
`storage_used` represents the amount of [storage](../anatomy/storage) that is currently being used by your contract.
> [!TIP]
>
> If you want to know how much storage a structure uses, print the storage before and after storing it.
***
## Telling the Time
The environment exposes three different ways to tell the pass of time, each representing a different dimension of the underlying blockchain.
### Timestamp
The `timestamp` attribute represents the approximated **UNIX timestamp** in **nanoseconds** at which this call was executed. It quantifies time passing in a human way, enabling us to check if a specific date has passed or not.
### Current Epoch
The NEAR blockchain groups blocks in [Epochs](../../protocol/network/epoch). The `current_epoch` attribute measures how many epochs have passed so far. It is very useful to coordinate with other contracts that measure time in epochs, such as the [validators](../../protocol/network/validators).
### Block Index
The `block_index` represents the index of the block in which this transaction will be added to the blockchain.
***
## Gas
Your contract has a **limited number of computational resources** to use on each call. Such resources are measured in [Gas](/protocol/transactions/gas).
Gas can be thought of as wall time, where 1 PetaGas (1\_000 TGas) is \~1 second of compute time.
Each code instruction costs a certain amount of Gas, and if you run out of it, the execution halts with the error message `Exceeded the prepaid gas`.
The environment gives you access to two gas-related arguments: `prepaid_gas` and `used_gas`.
### Prepaid Gas
`prepaid_gas` represents the amount of Gas the `predecessor` attached to this call. It cannot exceed the limit 300TGas (300 \* 1012 Gas).
### Used Gas
`used_gas` contains the amount of Gas that has been used so far. It is useful to estimate the Gas cost of running a method.
> [!WARNING]
>
> During [cross-contract calls](./crosscontract) give the callback enough Gas for its worst case, not its average. See [callbacks can fail](/smart-contracts/security/cross-contract-calls/callback-failures).
> [!TIP]
>
> If you already [estimated the Gas](../../protocol/transactions/gas#estimating-costs-for-a-call) a method needs, you can ensure it never runs out of Gas by using `assert`
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const REQUIRED_GAS: Gas = Gas(20_000_000_000_000); // 20 TGas
> assert!(env::prepaid_gas() >= REQUIRED_GAS, "Please attach at least 20 TGas");
> ```
***
## Environment Functions
Besides environmental variables, the SDK also exposes some functions to perform basic cryptographic operations
| Function Name | SDK method | Description |
| - | - | - |
| SHA 256 | `env::sha256(value)` | Hashes a sequence of bytes using sha256. |
| Keccak 256 | `env::keccak256(value)` | Hashes a sequence of bytes using keccak256. |
| Keccak 512 | `env::keccak512(value)` | Hashes a sequence of bytes using keccak512. |
| SHA 256 (Array) | `env::sha256_array(value)` | Hashes the bytes using the SHA-256 hash function. This returns a 32 byte hash. |
| Keccak 256 (Array) | `env::keccak256_array(value)` | Hashes the bytes using the Keccak-256 hash function. This returns a 32 byte hash. |
| Keccak 512 (Array) | `env::keccak512_array(value)` | Hashes the bytes using the Keccak-512 hash function. This returns a 64 byte hash. |
| RIPEMD 160 (Array) | `env::ripemd160_array(value)` | Hashes the bytes using the RIPEMD-160 hash function. This returns a 20 byte hash. |
| EC Recover | `env::ecrecover(hash, signature, v, malleability_flag)` | Recovers an ECDSA signer address from a 32-byte message `hash` and a corresponding `signature` along with `v` recovery byte. Takes in an additional flag to check for malleability of the signature which is generally only ideal for transactions. Returns 64 bytes representing the public key if the recovery was successful. |
| Panic String | `env::panic_str(message)` | Terminates the execution of the program with the UTF-8 encoded message. |
| Log String | `env::log_str(message)` | Logs the string message. This message is stored on chain. |
| Validator Stake | `env::validator_stake(account_id)` | For a given account return its current stake. If the account is not a validator, returns 0. |
| Validator Total Stake | `env::validator_total_stake()` | Returns the total stake of validators in the current epoch. |
***
# Contract Events
Source: https://docs.near.org/smart-contracts/anatomy/events
Emit structured events from your contract so indexers and frontends can track on-chain activity.
Smart contracts can emit **events** — structured log messages that follow [NEP-297](https://nomicon.io/Standards/EventsFormat) and are stored on-chain. Events allow indexers, frontends, and external services to track meaningful contract activity without parsing arbitrary log strings.
Events are most useful when several contracts must report the same kind of activity in a standard format, as the FT and NFT standards do. If you only need to read the calls made to your own contract, an indexer can read their arguments directly from the transactions. See [A contract is not a backend](/smart-contracts/what-is#a-contract-is-not-a-backend).
An event is a log line prefixed with `EVENT_JSON:` followed by a JSON object with a fixed schema:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
EVENT_JSON:{"standard":"nep171","version":"1.0.0","event":"nft_mint","data":[{"owner_id":"alice.near","token_ids":["1"]}]}
```
***
## Defining and Emitting Events
The `near-sdk` provides a high-level macro-based API for defining and emitting events. Annotate an enum with `#[near(event_json(standard = "..."))]` and mark each variant with `#[event_version("...")]`.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_sdk::near;
use near_sdk::serde::Serialize;
#[derive(Serialize)]
pub struct MintData {
pub owner_id: String,
pub token_ids: Vec,
}
#[derive(Serialize)]
pub struct TransferData {
pub old_owner_id: String,
pub new_owner_id: String,
pub token_ids: Vec,
}
#[near(event_json(standard = "nep171"))]
pub enum NftEvent {
#[event_version("1.0.0")]
NftMint(Vec),
#[event_version("1.0.0")]
NftTransfer(Vec),
}
```
Call `.emit()` on an event variant to write it to the on-chain log:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_sdk::near;
#[near(contract_state)]
#[derive(Default)]
pub struct Contract {}
#[near]
impl Contract {
pub fn mint(&mut self, owner_id: String, token_id: String) {
// ... minting logic ...
NftEvent::NftMint(vec![MintData {
owner_id,
token_ids: vec![token_id],
}])
.emit();
}
pub fn transfer(&mut self, old_owner_id: String, new_owner_id: String, token_id: String) {
// ... transfer logic ...
NftEvent::NftTransfer(vec![TransferData {
old_owner_id,
new_owner_id,
token_ids: vec![token_id],
}])
.emit();
}
}
```
The macro automatically serializes the enum variant to the `EVENT_JSON:` format and calls `env::log_str` under the hood.
> [!TIP]
>
> You can emit multiple data entries in a single event by passing a `Vec` with more than one element. This keeps gas costs lower than emitting one event per entry.
***
## Custom Events
You are not limited to standard NEP events. Define your own standard name for application-specific activity:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_sdk::near;
use near_sdk::serde::Serialize;
#[derive(Serialize)]
pub struct OrderPlaced {
pub order_id: u64,
pub buyer: String,
pub amount: u128,
}
#[near(event_json(standard = "my-marketplace"))]
pub enum MarketplaceEvent {
#[event_version("1.0.0")]
OrderPlaced(Vec),
}
// In your contract method:
MarketplaceEvent::OrderPlaced(vec![OrderPlaced {
order_id: 42,
buyer: "alice.near".to_string(),
amount: 1_000_000,
}])
.emit();
```
***
## Standard Events (FT & NFT)
If you are implementing Fungible Tokens or Non-Fungible Tokens, the standard events are already defined:
* **NEP-141 (FT):** `ft_transfer`, `ft_mint`, `ft_burn` — see the [Fungible Token](/primitives/ft) docs.
* **NEP-171 (NFT):** `nft_mint`, `nft_transfer`, `nft_burn` — see the [Non-Fungible Token](/primitives/nft) docs.
Using the standard event names ensures compatibility with explorers and indexers that already know how to parse them.
***
## Consuming Events with Indexers
Emitted events are stored as transaction logs on-chain and can be consumed by any indexer that listens for `EVENT_JSON:` prefixed log lines. See the [indexing guide](/data-infrastructure/indexers) to choose a data source for consuming these events.
# Types and Interface
Source: https://docs.near.org/smart-contracts/anatomy/functions
Learn how to define your contract's interface and use Rust and SDK types in its inputs, outputs, and state.
Smart contracts expose functions so users can interact with them. There are different types of functions including `read-only`, `private` and `payable`.
## Contract's Interface
All **public** functions in the contract are part of its **interface**. They can be called by anyone, and are the only way to interact with the contract.
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub fn get_highest_bid(&self) -> Bid {
self.highest_bid.clone()
}
pub fn get_auction_end_time(&self) -> U64 {
self.auction_end_time
}
pub fn get_auctioneer(&self) -> AccountId {
self.auctioneer.clone()
}
pub fn get_claimed(&self) -> bool {
self.claimed
}
```
[See code on GitHub](https://github.com/near-examples/auctions-tutorial/blob/4678765ea7f2a584b1a6569786d497dcf75f5261/contract-rs/01-basic-auction/src/lib.rs#L77-L91)
> [accordion] Exposing trait implementations
>
> Functions can also be exposed through trait implementations. This can be useful if implementing a shared interface or standard for a contract. This code generation is handled very similarly to basic `pub` functions, but the `#[near]` macro only needs to be attached to the trait implementation, not the trait itself:
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> pub trait MyTrait {
> fn trait_method(&mut self);
> }
>
> #[near]
> impl MyTrait for MyContractStructure {
> fn trait_method(&mut self) {
> // .. method logic here
> }
> }
> ```
## Initialization Functions
A contract can opt to have an initialization function. If present, this function must be called before any other to [initialize the contract](./storage).
The initialization function is marked with the `#[init]` macro.
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[init]
pub fn init(end_time: U64, auctioneer: AccountId) -> Self {
Self {
highest_bid: Bid {
bidder: env::current_account_id(),
bid: NearToken::from_yoctonear(1),
},
auction_end_time: end_time,
claimed: false,
auctioneer,
}
}
```
[See code on GitHub](https://github.com/near-examples/auctions-tutorial/blob/4678765ea7f2a584b1a6569786d497dcf75f5261/contract-rs/01-basic-auction/src/lib.rs#L23-L34)
## State Changing Functions
The functions that modify the [state](./storage) or perform [actions](./actions) need to be called by a user with a NEAR account, since a transaction is required to execute them.
State changing functions are those that take a **mutable** reference to `self` in Rust.
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[payable]
pub fn bid(&mut self) -> Promise {
// Assert the auction is still ongoing
require!(
env::block_timestamp() < self.auction_end_time.into(),
"Auction has ended"
);
// Current bid
let bid = env::attached_deposit();
let bidder = env::predecessor_account_id();
// Last bid
let Bid {
bidder: last_bidder,
bid: last_bid,
} = self.highest_bid.clone();
// Check if the deposit is higher than the current bid
require!(bid > last_bid, "You must place a higher bid");
// Update the highest bid
self.highest_bid = Bid { bidder, bid };
// Transfer tokens back to the last bidder
Promise::new(last_bidder).transfer(last_bid)
}
```
[See code on GitHub](https://github.com/near-examples/auctions-tutorial/blob/4678765ea7f2a584b1a6569786d497dcf75f5261/contract-rs/01-basic-auction/src/lib.rs#L36-L62)
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub fn claim(&mut self) -> Promise {
require!(
env::block_timestamp() > self.auction_end_time.into(),
"Auction has not ended yet"
);
require!(!self.claimed, "Auction has already been claimed");
self.claimed = true;
// Transfer tokens to the auctioneer
Promise::new(self.auctioneer.clone()).transfer(self.highest_bid.bid)
}
```
[See code on GitHub](https://github.com/near-examples/auctions-tutorial/blob/4678765ea7f2a584b1a6569786d497dcf75f5261/contract-rs/01-basic-auction/src/lib.rs#L64-L75)
> [!TIP]
>
> The SDK provides [contextual information](./environment), such as which account is calling the function, or what time it is.
## Read-Only Functions
Contract's functions can be read-only, meaning they don't modify the state. Calling them is free for everyone, and does not require to have a NEAR account.
Read-only functions are those that take an **immutable** reference to `self` in Rust.
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub fn get_highest_bid(&self) -> Bid {
self.highest_bid.clone()
}
pub fn get_auction_end_time(&self) -> U64 {
self.auction_end_time
}
pub fn get_auctioneer(&self) -> AccountId {
self.auctioneer.clone()
}
pub fn get_claimed(&self) -> bool {
self.claimed
}
```
[See code on GitHub](https://github.com/near-examples/auctions-tutorial/blob/4678765ea7f2a584b1a6569786d497dcf75f5261/contract-rs/01-basic-auction/src/lib.rs#L77-L91)
## Private Functions
Many times you will want to have functions that **are exposed** as part of the contract's interface, but **should not be called directly** by users.
Besides initialization functions, [callbacks from cross-contract calls](./crosscontract) should always be `private`.
These functions are marked as `private` in the contract's code, and can only be called by the contract itself.
Private functions are marked using the `#[private]` macro in Rust.
## Payable Functions
By default, functions will panic if the user attaches NEAR Tokens to the call. Functions that accept NEAR Tokens must be marked as `payable`.
Within the function, the user will have access to the [attached deposit](./environment).
Payable functions are marked using the `#[payable]` macro in Rust.
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[payable]
pub fn bid(&mut self) -> Promise {
// Assert the auction is still ongoing
require!(
env::block_timestamp() < self.auction_end_time.into(),
"Auction has ended"
);
// Current bid
let bid = env::attached_deposit();
let bidder = env::predecessor_account_id();
```
[See code on GitHub](https://github.com/near-examples/auctions-tutorial/blob/4678765ea7f2a584b1a6569786d497dcf75f5261/contract-rs/01-basic-auction/src/lib.rs#L36-L46)
## Internal Functions
All the functions we covered so far are part of the interface, meaning they can be called by an external actor.
However, contracts can also have private internal functions - such as helper or utility functions - that are **not exposed** to the outside world.
To create internal private methods in a Rust contract, do not declare them as public (`pub fn`).
> [accordion] Separate impl block
>
> Another way of not exporting methods is by having a separate `impl Contract` section, that is not marked with `#[near]`.
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> #[near]
> impl Contract {
> pub fn increment(&mut self) {
> self.internal_increment();
> }
> }
> impl Contract {
> /// This methods is still not exported.
> pub fn internal_increment(&mut self) {
> self.counter += 1;
> }
> }
> ```
***
## SDK types
Smart contracts can receive, store, and return data using native Rust types such as strings, integers, booleans, maps, and vectors. The SDK also provides types for values that need special handling at the contract boundary.
### Large integers
Contracts can store `u64` and `u128` values directly, but JSON consumers cannot always represent them without losing precision. Use the SDK's `U64` and `U128` wrapper types for public inputs and outputs that need to be serialized as strings.
> [!WARNING]
>
> JavaScript numbers cannot represent every integer above `2^53 - 1`. Keep native integer types in internal contract logic, and use the JSON wrapper types at the external interface when necessary.
### Complex objects
Contracts can receive and return complex Rust structures. Objects used as JSON inputs or outputs need JSON serialization, while structures stored in contract state need Borsh serialization.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near(serializers = [json])]
pub struct Bid {
pub bidder: AccountId,
pub amount: U128,
}
```
See [serialization](/smart-contracts/anatomy/serialization) for the difference between interface and state serialization.
### Tokens and accounts
Use `NearToken` to represent NEAR amounts. It provides constructors and accessors for yoctoNEAR, millinear, and NEAR values.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
let deposit = NearToken::from_near(1);
let amount = deposit.as_yoctonear();
```
The SDK's `AccountId` type validates NEAR account IDs when values enter the contract. Prefer it to a plain `String` whenever a value represents an account.
# Production Builds
Source: https://docs.near.org/smart-contracts/anatomy/reduce-size
Reduce contract size and create reproducible builds that users can verify against the deployed code.
In this page, we will explore strategies for reducing the size of smart contracts on NEAR. This is particularly useful for developers who want to optimize their contracts for deployment, especially in scenarios where contract size limits are a concern.
# Reducing a contract's size
## Advice & examples
This page is made for developers familiar with lower-level concepts who wish to reduce their contract size significantly, perhaps at the expense of code readability.
Some common scenarios where this approach may be helpful:
* contracts intended to be tied to one's account management
* contracts deployed using a factory
* future advancements similar to the EVM on NEAR
There have been a few items that may add unwanted bytes to a contract's size when compiled. Some of these may be more easily swapped for other approaches while others require more internal knowledge about system calls.
## Small wins
### Using flags
When compiling a contract make sure to pass flag `-C link-arg=-s` to the rust compiler:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release
```
Here is the parameters we use for the most examples in `Cargo.toml`:
```toml theme={"theme":{"light":"github-light","dark":"github-dark"}}
[profile.release]
codegen-units = 1
opt-level = "s"
lto = true
debug = false
panic = "abort"
overflow-checks = true
```
You may want to experiment with using `opt-level = "z"` instead of `opt-level = "s"` to see if generates a smaller binary. See more details on this in [The Cargo Book Profiles section](https://doc.rust-lang.org/cargo/reference/profiles.html#opt-level). You may also reference this [Shrinking .wasm Size](https://rustwasm.github.io/book/reference/code-size.html#tell-llvm-to-optimize-for-size-instead-of-speed) resource.
### Removing `rlib` from the manifest
Ensure that your manifest (`Cargo.toml`) doesn't contain `rlib` unless it needs to. Some NEAR examples have included this:
> [!WARNING]
>
> **Adds unnecessary bloat**
>
> ```toml theme={"theme":{"light":"github-light","dark":"github-dark"}}
> [lib]
> crate-type = ["cdylib", "rlib"]
> ```
when it could be:
> [!TIP]
>
> ```toml theme={"theme":{"light":"github-light","dark":"github-dark"}}
> [lib]
> crate-type = ["cdylib"]
> ```
3. When using the Rust SDK, you may override the default JSON serialization to use [Borsh](https://borsh.io) instead. See [overriding interface serialization](/smart-contracts/anatomy/serialization#overriding-interface-serialization) for more information and an example.
4. When using assertions or guards, avoid using the standard `assert` macros like [`assert!`](https://doc.rust-lang.org/std/macro.assert.html), [`assert_eq!`](https://doc.rust-lang.org/std/macro.assert_eq.html), or [`assert_ne!`](https://doc.rust-lang.org/std/macro.assert_ne.html) as these may add bloat for information regarding the line number of the error. There are similar issues with `unwrap`, `expect`, and Rust's `panic!()` macro.
Example of a standard assertion:
> [!WARNING]
>
> **Adds unnecessary bloat**
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> assert_eq!(contract_owner, predecessor_account, "ERR_NOT_OWNER");
> ```
when it could be:
> [!TIP]
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> if contract_owner != predecessor_account {
> env::panic(b"ERR_NOT_OWNER");
> }
> ```
Example of removing `expect`:
> [!WARNING]
>
> **Adds unnecessary bloat**
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> let owner_id = self.owner_by_id.get(&token_id).expect("Token not found");
> ```
when it could be:
> [!TIP]
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> fn expect_token_found(option: Option) -> T {
> option.unwrap_or_else(|| env::panic_str("Token not found"))
> }
> let owner_id = expect_token_found(self.owner_by_id.get(&token_id));
> ```
Example of changing standard `panic!()`:
> [!WARNING]
>
> **Adds unnecessary bloat**
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> panic!("ERR_MSG_HERE");
> ```
when it could be:
> [!TIP]
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> env::panic_str("ERR_MSG_HERE");
> ```
## Ready to use script
We have prepared a simple `bash` script that can be used to minify `.wasm` contract file. You can find it [here](https://github.com/near/near-sdk-rs/blob/master/minifier/minify.sh).
The current approach to minification is the following:
1. Snip (i.e. just replace with unreachable instruction) few known fat functions from the standard library (such as float formatting and panic-related) with `wasm-snip`.
2. Run `wasm-gc` to eliminate all functions reachable from the snipped functions.
3. Strip unneeded sections, such as names with `wasm-strip`.
4. Run `binaryen wasm-opt`, which cleans up the rest.
### Requirements to run the script:
* install [wasm-snip](https://docs.rs/wasm-snip/0.4.0/wasm_snip/) and [wasm-gc](https://docs.rs/crate/wasm-gc/0.1.6) with Cargo:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cargo install wasm-snip wasm-gc
```
* install [binaryen](https://github.com/WebAssembly/binaryen) and [wabt](https://github.com/WebAssembly/wabt) on your system. For Ubuntu and other Debian based Linux distributions run:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
apt install binaryen wabt
```
> [!CAUTION]
>
> Minification could be rather aggressive, so you must test the contract after minification. Standalone NEAR runtime could be helpful [here](https://github.com/nearprotocol/nearcore/tree/master/runtime/near-vm-runner).
## Lower-level approach
For a `no_std` approach to minimal contracts, observe the following examples:
* [Tiny contract](https://github.com/near/nearcore/tree/1e7c6613f65c23f87adf2c92e3d877f4ffe666ea/runtime/near-test-contracts/tiny-contract-rs)
* [NEAR ETH Gateway](https://github.com/ilblackdragon/near-eth-gateway/blob/master/proxy/src/lib.rs)
* [This YouTube video](https://youtu.be/Hy4VBSCqnsE) where Eugene demonstrates a fungible token in `no_std` mode. The code for this [example lives here](https://github.com/near/core-contracts/pull/88).
* [Examples using a project called `nesdie`](https://github.com/austinabell/nesdie/tree/main/examples).
* Note that Aurora has found success using [rjson](https://crates.io/crates/rjson) as a lightweight JSON serialization crate. It has a smaller footprint than [serde](https://crates.io/crates/serde) which is currently packaged with the Rust SDK. See [this example of rjson](https://github.com/aurora-is-near/aurora-engine/blob/65a1d11fcd16192cc1bda886c62005c603189a24/src/json.rs#L254) in an Aurora repository, although implementation details will have to be gleaned by the reader and won't be expanded upon here. [This nesdie example](https://github.com/austinabell/nesdie/blob/bb6beb77e32cd54077ac54bf028f262a9dfb6ad0/examples/multisig/src/utils/json/vector.rs#L26-L30) also uses the [miniserde crate](https://crates.io/crates/miniserde), which is another option to consider for folks who choose to avoid using the Rust SDK.
> [!NOTE]
>
> **Information on system calls**
>
> The [`near_sys` crate](https://docs.rs/near-sys/latest/near_sys/) exposes the low-level host functions available to contracts that interact directly with the runtime. See its reference for function signatures.
>
> The SDK's [`env` module](https://github.com/near/near-sdk-rs/blob/2728185be188fd2975dd9ce0a77012638c36cab4/near-sdk/src/environment/env.rs) provides higher-level wrappers around these functions.
***
## Reproducible builds
Reproducible builds let different people build the same program and get the exact same output. They help users verify that a deployed contract corresponds to its published source code.
Building the same contract on different machines can produce similar but non-identical binaries because the artifact can be affected by the locale, timezone, build path, and other parts of the build environment. NEAR addresses this with [NEP-330 source metadata](https://github.com/near/NEPs/blob/master/neps/nep-0330.md), [cargo-near](https://github.com/near/cargo-near), Docker, and SourceScan.
> [!NOTE]
>
> You need [Docker](https://docker.com) to use the reproducible-build workflow.
When you initialize a project with `cargo near new`, its `Cargo.toml` includes the build environment and repository metadata:
```toml theme={"theme":{"light":"github-light","dark":"github-dark"}}
repository = "https://github.com//"
[package.metadata.near.reproducible_build]
image = "sourcescan/cargo-near:0.13.5-rust-1.85.1"
image_digest = "sha256:3b0272ecdbb91465f3e7348330d7f2d031d27901f26fb25b4eaf1560a60c20f3"
passed_env = []
container_build_command = [
"cargo",
"near",
"build",
"non-reproducible-wasm",
"--locked",
]
```
When you deploy with `cargo near deploy`, this information is used to clone the repository and compile the contract in a Docker container. The build adds a `contract_source_metadata` method without changing the contract's logic.
After deployment, inspect that metadata with:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near view contract_source_metadata
```
## Verify and publish
To verify and publish the contract's code, open its account page in [NearBlocks](https://nearblocks.io), select the **Contract** tab, and use **Verify and Publish**. After verification, the source and metadata are available under **Contract → Contract Code**.

For a complete walkthrough, see the [SourceScan verification guide](https://github.com/SourceScan/verification-guide).
# Serialization
Source: https://docs.near.org/smart-contracts/anatomy/serialization
Learn how contract serialize data for function calls and storage.
Smart contracts need to be able to **communicate complex data** in a simple way, while also **reading and storing** such data into their states efficiently.
To achieve such simple communication and efficient storage, smart contracts morph the data
from their complex representation into simpler ones.
This process of translating **complex objects into simpler single-value** representations is called
**serialization**. NEAR uses two serialization formats: [JSON](https://www.json.org/json-en.html) and
[Borsh](https://borsh.io/).
1. [JSON](https://www.json.org/json-en.html) is used to serialize the contract's input/output during a function call
2. [Borsh](https://borsh.io/) is used to serialize the contract's state.
***
## Overview of Serialization Formats
Let's give a quick overview of both serialization formats, including their pros and cons, as well as
an example of what their serializations look like.
***
### [JSON](https://www.json.org/json-en.html): Objects to Strings
#### Features
* Self-describing format
* Easy interoperability with JavaScript
* Multiple implementations readily available
* But... it is not efficient both in computational times and resulting size
#### Example
```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
Example{
number: i32 = 2;
arr: Vector = [0, 1];
}
// serializes to
"{\"number\": 2, \"arr\": [0, 1]}"
```
***
### [Borsh](https://borsh.io/): Objects to Bytes
#### Features
* Compact, binary format built to be efficiently (de)serialized
* Strict and canonical binary representation
* Less overhead: it does not need to store attributes names
* But... it is necessary to know the schema to (de)serialize the data
#### Example
```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
Example{
number: i32 = 2;
arr: Vector = [0, 1];
}
// serializes into
[2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
```
***
## Serializing Input & Output
NEAR contracts can implement methods that both take and return complex objects.
In order to handle this data in a simple way, JSON serialization is used.
Using JSON makes it easier for everyone to talk with the contracts, since most
languages readily implement a JSON (de)serializer.
#### Example
Let's look at this example, written only for educational purposes:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near(serializers = [json])]
pub struct A {
pub a_number: i32,
pub b_number: u128
}
#[near(serializers = [json])]
pub struct B {
pub success: bool,
pub other_number: i32
}
pub fn method(&self, struct_a: A): B {
B {
success: true,
other_number: 0
}
}
```
#### Receiving Data
When a user calls the `method`, the contract receives the arguments encoded as a JSON string
(e.g. `"{\"a_number\":0, \"b_number\":\"100\"}"`), and proceed to (de)serialize them into
the correct object (`A{0, 100}`) .
#### Returning Data
When returning the result, the contract will automatically encode the object `B{true, 0}`
into its JSON serialized value: `"{\"success\":true, \"other_number\":0}"` and return this
string.
> [!WARNING]
>
> **JSON Limitations**
> Since JSON is limited to `52 bytes` numbers, you cannot use `u64`/`u128` as input
> or output. JSON simply cannot serialize them. Instead, you must use `Strings`.
>
> The `NEAR SDK RS` currently implements the `near_sdk::json_types::{U64, I64, U128, I128}`
> that you can use for input / output of data.
***
## Borsh: State Serialization
Under the hood smart contracts store data using simple **key/value pairs**. This means that
the contract needs to translate complex states into simple key-value pairs.
For this, NEAR contracts use [borsh](https://borsh.io) which is optimized for (de)serializing
complex objects into smaller streams of bytes.
#### Example
Let's look at this example, written only for educational purposes:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near(serializers = [json, borsh])]
#[derive(PanicOnDefault)]
pub struct Contract {
string: String,
vector: Vector
}
#[near]
impl Contract {
#[init]
pub fn init(string: String, first_u8: u8) -> Self {
let mut vector: Vector = Vector::new("prefix".as_bytes());
vector.push(&first_u8);
Self { string, vector }
}
pub fn change_state(&mut self, string: String, number: u8) {
self.string = string;
self.vector.push(&number);
}
}
```
#### Empty State On Deploy
If we deploy the contract into a new account and immediately ask for the state we will see
it is empty:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near view-state $CONTRACT --finality optimistic
# Result is: []
```
#### Initializing the State
If we initialize the state we can see how Borsh is used to serialize the state
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# initialize with the string "hi" and 0
near call $CONTRACT init '{"string":"hi", "first_u8":0}' --useAccount $CONTRACT
# check the state
near view-state $CONTRACT --utf8 --finality optimistic
```
> [accordion] Result
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> [
> {
> key: 'STATE',
> value: '\x02\x00\x00\x00hi\x01\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00prefix'
> },
> { key: 'prefix\x00\x00\x00\x00\x00\x00\x00\x00', value: '\x00' }
> ]
> ```
The first key-value is:
```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
key: 'STATE'
value: '\x02\x00\x00\x00hi\x01\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00prefix'
```
Since the `Contract` has a structure `string, Vector` the value is interpreted as:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
[2, 0, 0, 0, "h", "i"] -> The `string` has 2 elements: "h" and "i".
[1, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, "prefix"] -> The Vector has 1 element, and to see the values search for keys that start with (the 6 bytes prefix): "prefix"
```
Then, the second key-value shows the entries of the `Vector` denoted by the `"prefix"` string:
```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
key: 'prefix\x00\x00\x00\x00\x00\x00\x00\x00'
value: '\x00'
```
#### Modifying the State
If we modify the stored string and add a new number, the state changes accordingly:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near call $CONTRACT change_state '{"string":"bye", "number":1}' --useAccount $CONTRACT
```
> [accordion] Result
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> [
> {
> key: 'STATE',
> value: '\x03\x00\x00\x00bye\x02\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00prefix'
> },
> { key: 'prefix\x00\x00\x00\x00\x00\x00\x00\x00', value: '\x00' },
> { key: 'prefix\x01\x00\x00\x00\x00\x00\x00\x00', value: '\x01' }
> ]
> ```
We can see that the `STATE` key changes to reflect the storage of the new string (`bye`), and that
the vector now has 2 elements.
At the same time, a new key-value was added adding the new vector entry: the `1u8` we just added.
***
### Deserialization Error
When somebody invokes a smart contract method, the first step for the contract is to deserialize
its own state.
In the example used above, the contract will start by reading the `STATE` key and
try to deserialize its value into an object `Contract{string: String, vector: Vector}`.
If you deploy a contract into the account with a different Contract structure, then the
contract will fail to deserialize the `STATE` key and panic `Cannot deserialize the contract state`.
To solve this, you can either:
1. Rollback to the previous contract code
2. Implement a method to [migrate the contract's state](../release/upgrade)
***
## Overriding interface serialization
JSON is the default format for contract parameters and return values. You can opt into Borsh when smaller payloads and lower serialization costs are more important than a human-readable interface.
The parameter and result serializers can be selected separately, but all parameters of a method must use the same format:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[result_serializer(borsh)]
pub fn sum_borsh(
#[serializer(borsh)] a: u32,
#[serializer(borsh)] b: u32,
) -> u32 {
a + b
}
```
When calling a Borsh-serialized method through the CLI, pass its serialized bytes as Base64 arguments:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near contract call-function as-transaction rust-status-message.demo.testnet set_status_borsh base64-args 'DAAAAEFsb2hhIGhvbnVhIQ==' prepaid-gas '30 TeraGas' attached-deposit '0 NEAR' sign-as demo.testnet network-config testnet sign-with-keychain send
```
Use the same serialization format on both sides of a cross-contract call. JSON remains the better default when the interface is also used by frontends, scripts, or other languages.
## JSON wrapper types
The SDK provides wrapper types in `near_sdk::json_types` for Rust values whose default JSON representation is inconvenient.
### Large integers
JSON consumers cannot always represent `u64` and `u128` values without losing precision. `U64` and `U128` serialize those values as strings while retaining their native integer representation inside the contract.
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near]
impl Contract {
pub fn mult(&self, a: U64, b: U64) -> U128 {
U128(u128::from(a.0) * u128::from(b.0))
}
}
```
### Byte arrays
A `Vec` normally serializes to an array of JSON integers. Use `Base64VecU8` to expose those bytes as a compact Base64 string:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near(contract_state)]
#[derive(PanicOnDefault)]
pub struct Contract {
pub data: Vec,
}
#[near]
impl Contract {
#[init]
pub fn new(data: Base64VecU8) -> Self {
Self { data: data.into() }
}
pub fn get_data(self) -> Base64VecU8 {
self.data.into()
}
}
```
# State
Source: https://docs.near.org/smart-contracts/anatomy/storage
Explore how NEAR smart contracts manage their state.
Smart contracts store data in their account's state, which is public on the chain. The storage starts **empty** until a contract is deployed and the state is initialized.
It is important to know that the account's **code** and account's **storage** are **independent**. [Updating the code](../release/upgrade) does **not erase** the state.
## Defining the State
The attributes of the `struct` marked as the contract define the data that will be stored.
> [!WARNING]
>
> **Store only what the contract needs.** Contract state is not a database for your app: storage requires staking NEAR, and data your app only displays can be read from the contract's transactions with an indexer. Never store values you can derive from other stored values. See [A contract is not a backend](/smart-contracts/what-is#a-contract-is-not-a-backend).
The contract can store all native types (e.g. `u8`, `string`, `HashMap`, `Vector`) as well as complex objects.
For example, our Auction contract stores when the auction ends, and an object representing the highest bid.
> [!NOTE]
>
> The structures that will be saved need a special macro that tells the SDK to store them [serialized in Borsh](./serialization).
> [!NOTE]
>
> The SDK also provides [collections](./collections) to efficiently store collections of data.
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near(serializers = [json, borsh])]
#[derive(Clone)]
pub struct Bid {
pub bidder: AccountId,
pub bid: NearToken,
}
#[near(contract_state)]
#[derive(PanicOnDefault)]
pub struct Contract {
highest_bid: Bid,
auction_end_time: U64,
auctioneer: AccountId,
claimed: bool,
}
```
[See code on GitHub](https://github.com/near-examples/auctions-tutorial/blob/4678765ea7f2a584b1a6569786d497dcf75f5261/contract-rs/01-basic-auction/src/lib.rs#L5-L19)
> [!WARNING]
>
> Contracts pay for their storage by locking part of their balance.
>
> It currently costs \~**1Ⓝ** to store **100KB** of data.
## Initializing the State
After the contract is deployed, its state is empty and needs to be initialized with
some initial values.
There are two ways to initialize a state:
1. By creating an initialization function
2. By setting default values
### I. Initialization Functions
An option to initialize the state is to create an `initialization` function, which needs to be called before executing any other function.
In our Auction example, the contract has an initialization function that sets when the auction ends. The contract derives the `PanicOnDefault`, which forces the user to call the init method denoted by the `#[init]` macro.
> [!NOTE]
>
> It is a good practice to mark initialization functions as private. We will cover function types in the [functions section](./functions).
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near(contract_state)]
#[derive(PanicOnDefault)]
pub struct Contract {
highest_bid: Bid,
auction_end_time: U64,
auctioneer: AccountId,
claimed: bool,
}
```
[See code on GitHub](https://github.com/near-examples/auctions-tutorial/blob/4678765ea7f2a584b1a6569786d497dcf75f5261/contract-rs/01-basic-auction/src/lib.rs#L12-L19)
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[init]
pub fn init(end_time: U64, auctioneer: AccountId) -> Self {
Self {
highest_bid: Bid {
bidder: env::current_account_id(),
bid: NearToken::from_yoctonear(1),
},
auction_end_time: end_time,
claimed: false,
auctioneer,
}
}
```
[See code on GitHub](https://github.com/near-examples/auctions-tutorial/blob/4678765ea7f2a584b1a6569786d497dcf75f5261/contract-rs/01-basic-auction/src/lib.rs#L23-L34)
### II. Default State
Another option to initialize the state is to create a `Default` version of our contract's `struct`.
For example, our "Hello World" contract has a default state with a `greeting` set to `"Hello"`.
The first time the contract executes, the `Default` will be stored in the state, and the state will be considered initialized.
> [!NOTE]
>
> The state can only be initialized once.
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[near(contract_state)]
pub struct Contract {
greeting: String,
}
```
[See code on GitHub](https://github.com/near-examples/hello-near-examples/blob/be63c9f326b47d881dddaea87564fe578bcd844e/contract-rs/src/lib.rs#L5-L8)
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
impl Default for Contract {
fn default() -> Self {
Self {
greeting: "Hello".to_string(),
}
}
}
```
[See code on GitHub](https://github.com/near-examples/hello-near-examples/blob/be63c9f326b47d881dddaea87564fe578bcd844e/contract-rs/src/lib.rs#L11-L17)
> [!NOTE]
>
> **Lifecycle of the State**
>
> When a function is called, the contract's state is loaded from the storage and put into memory.
>
> The state is actually [stored serialized](./serialization), and the SDK takes a bit of time to deserialize it before the method can access it.
>
> When the method finishes executing successfully, all the changes to the state are serialized, and saved back to the storage.
> [!WARNING]
>
> **State and Code**
>
> In NEAR, the contract's code and contract's storage are **independent**.
>
> Updating the code of a contract does **not erase** the state, and can indeed lead to unexpected behavior or errors.
>
> Make sure to read the [updating a contract](../release/upgrade) if you run into issues.
# Yield and Resume
Source: https://docs.near.org/smart-contracts/anatomy/yield-resume
Wait for an external response and resume execution
NEAR smart contracts can **yield** execution, until an **external** service **resumes** them. In practice, the contract yields a **cross-contract call** to itself, until an external service executes a function and the contract decides to resume.
This allows contracts to wait for external events, such as a response from an oracle, before continuing execution.
> [!NOTE]
>
> This example uses `near-sdk` 5.29.1. The contract can wait for 200 blocks, after which the yielded function executes with a timeout error if no response has arrived.
***
## Yielding a Promise
Let's look at an example that takes a prompt from a user (e.g. "What is 2+2"), and yields the execution until an external service provides a response.
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub fn request(&mut self, prompt: String) -> Promise {
// internal variable to keep track of the requests
self.request_id += 1;
// create the yielded promise and its resumption ID
let (yield_promise, yield_id) = Promise::new_yield(
"return_external_response",
&json!({ "request_id": self.request_id })
.to_string()
.into_bytes(),
Gas::from_tgas(5),
GasWeight::default(),
);
// store the request, so we can delete it later
let request = Request { yield_id, prompt };
self.requests.insert(self.request_id, request);
// return the yield promise
yield_promise
}
```
[See code on GitHub](https://github.com/near-examples/yield-resume/blob/0b00fa1a672131b396138f4794e085501c172bb5/contract/src/lib.rs#L41-L61)
#### Creating a Yielded Promise
In the example above, we are creating a [`Promise`](/smart-contracts/anatomy/crosscontract#promises) to call the contract's function `return_external_response`.
`Promise::new_yield` returns both the yielded `Promise` and a `YieldId` that identifies it. The callback name, arguments, and gas allocation are passed when creating the promise.
#### Storing the Yielded Promise ID
We store the `yield_id` and the user's `prompt` so the external service can query them using `list_requests`. A `YieldId` is serialized as a base64 string in JSON; the service passes that value unchanged when responding.
#### Returning the Promise
Finally, we return the `Promise` from `request`. The callback will **not execute immediately**: it waits until the external service provides a response or the promise times out.
> [accordion] What is that `self.request_id` in the code?
>
> The `self.request_id` is an internal unique identifier that we use to keep track of stored requests. This way, we can delete the request once the external service provides a response (or the wait times out)
>
> Since we only use it to simplify the process of keeping track of the requests, you can remove it if you have a different way of tracking requests (e.g. an indexer)
***
## Signaling the Resume
The `YieldId::resume` method allows us to signal which yielded promise should execute and pass a response to the callback.
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub fn respond(&mut self, yield_id: YieldId, response: String) {
// resume computation with the response
yield_id
.resume(serde_json::to_vec(&response).unwrap())
.expect("yielded promise not found or already resolved");
}
```
[See code on GitHub](https://github.com/near-examples/yield-resume/blob/0b00fa1a672131b396138f4794e085501c172bb5/contract/src/lib.rs#L63-L68)
In the example above, an external service calls `respond`, passing the `yield_id` from `list_requests` and the response to the prompt. The response is serialized as JSON bytes so the callback can deserialize it as a `String`.
`YieldId::resume` returns an error if the yielded promise is no longer available. In this example, `expect` makes `respond` fail in that case, such as when a response arrives after the timeout callback has completed.
> [!WARNING]
>
> **Gatekeeping the Resume**
>
> Since the function used to signal the resume is public, developers must make sure to guard it properly to avoid unwanted calls. This can be done by simply checking the caller of the function
***
## The Function that Resumes
The callback receives the arguments passed when creating the yielded promise and the result of waiting for the external response.
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[private]
pub fn return_external_response(
&mut self,
request_id: u32,
#[callback_result] response: Result,
) -> Response {
self.requests.remove(&request_id);
match response {
Ok(answer) => Response::Answer(answer),
Err(_) => Response::TimeOutError,
}
}
```
[See code on GitHub](https://github.com/near-examples/yield-resume/blob/0b00fa1a672131b396138f4794e085501c172bb5/contract/src/lib.rs#L70-L82)
In the example above, the `return_external_response` receives parameters:
1. A `request_id` - passed on [creation](#creating-a-yielded-promise) - which is used to remove the request from the state
2. A `response` - obtained through `#[callback_result]` - which is `Ok(answer)` when the external service [signals the resume](#signaling-the-resume), or `Err(PromiseError::Failed)` if the promise times out while waiting
> [!TIP]
>
> **There's plenty of time**
>
> The contract can wait for 200 blocks before timing out.
> [!NOTE]
>
> In this example, we return `Response::Answer` when there is a response and `Response::TimeOutError` when the callback receives an error.
>
> Both paths remove the stored request. Panicking in the callback would revert that removal, so we return a value to preserve the cleanup.
***
## Managing State
When using yield and resume, it's important that you carefully manage the contract's state. The function that creates the yielded promise finishes before the callback executes, and its state changes are already committed.
If you change the state of the contract in the function where you yield the promise (the `request` function here), then you need to make sure that you clean up the pending state in the function that resumes (the `return_external_response` function here) in the case that the promise times out or the response is invalid.
It is best practice to check the validity of the response within the function where the resume is signaled (the `respond` function here) and panic if the response is not valid; the external service can attempt to respond again before the promise times out. You should not panic in `return_external_response` as this is only called when the promise has been resolved (it was resumed or timed out), meaning it can't be resumed again, and the state changes made in `request` have already been committed. You should gracefully complete the callback and clean up the pending state.
> [!NOTE]
>
> Read [asynchronous-call security](/smart-contracts/security/cross-contract-calls/callbacks) to avoid common pitfalls when dealing with callbacks and pending state.
## Testing Yield and Resume
The [example's sandbox tests](https://github.com/near-examples/yield-resume/blob/main/contract/tests/yield_resume.rs) build the contract from source and use `near-sandbox` with `near-api` to verify both an external response and a timeout. The timeout test fast-forwards the local node. Both tests check that pending requests are removed and that completed requests cannot be resumed again.
From the repository's `contract` directory, run:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cargo install cargo-near --version 0.21.1 --locked --no-default-features
cargo test --locked
```
# Global Contracts
Source: https://docs.near.org/smart-contracts/global-contracts
Deploy a contract once and reuse it across accounts.
Global contracts allow contract code to be deployed once and reused across multiple accounts. With regular deployments, each account pays the full storage deposit for its own copy of the Wasm code. With global contracts, each account stores a reference to shared code instead, reducing storage costs.
[NEP-0591](https://github.com/near/NEPs/blob/master/neps/nep-0591.md) introduces this code-sharing mechanism. Each account that uses the code keeps its own application state.
> [!TIP]
>
> Publishing a global contract under an account ID makes that ID a reference to reusable code. **It does not deploy an executable contract on that account.** To call methods on the account, you must separately deploy a regular contract there or attach global code with `UseGlobalContract`.
## Key Features
These are the features that make Global Contracts special:
* **Global Addressing**: Code is identified by its hash or publisher account ID. Accounts reference that identifier through `UseGlobalContract`, then receive calls at their own account IDs.
* **Code Versioning**: A reference by hash pins immutable code. A reference by publisher account ID follows updates published under that ID.
* **Shared Infrastructure**: Global contracts can act as canonical libraries, utility hubs, or standards for other contracts to rely on, simplifying development and reducing duplication.
* **Independent Instances**: Accounts reuse the same code while keeping separate storage, balances, and application state. Calls between instances follow the usual cross-contract execution model.
### Use Cases
* **Standard Libraries**: Reusable components for math, string operations, or token interfaces.
* **DeFi Protocols**: Global contracts can anchor DEXs, lending markets, oracles—shared across all applications.
* **DAO Frameworks**: Shared governance modules that any DAO can plug into, ensuring consistency and reliability.
* **Identity & Credentials**: Accounts can reuse identity verification and access management code while keeping their own state.
* **Multi-part dApps**: Complex applications can split responsibilities across shards while accessing a common logic core.
## Solution
Global Contracts solve the inefficiency of duplicate deployments by allowing the same contract code to be shared across multiple accounts, so storage cost is paid only once.
There are two ways to reference a global contract:
* **[By Account](#reference-by-account)**: an upgradable contract is published globally under a specific account ID.
* **[By Hash](#reference-by-hash)**: an immutable contract is deployed globally and identified by its code hash.
> [!NOTE]
>
> * The contract code is distributed across all shards in the Near Protocol network, not stored inside any specific account’s storage.
> * The account is charged 10x more for deploying a Global Contract, at the rate 10 NEAR per 100KB.
> * This amount is entirely burnt and cannot be recovered later, unlike regular deployments where Near is simply locked.
> * The total fee is typically under 0.001 NEAR for a user to use a Global Contract, since only a few bytes are needed for the reference that is stored in the account's storage.
### Reference by Account
When using a reference **by account**, the contract code is tied to another account. If that account later deploys a new version of the contract, your account will automatically start using the updated code, with no need for redeployment.
### Reference by Hash
When using a reference **by hash**, you reference the global contract by its immutable code hash. This ensures you're always using the exact same version, and it will never change unless you explicitly redeploy with a different hash.
## When to use Global Contracts
Ask yourself the following questions before deciding how to deploy your contracts:
* ***Are you working in a local environment?***
If you're just testing or building a prototype, [regular deployments](/smart-contracts/release/deploy) are simpler and more flexible. There's no need to burn tokens or register global references — just deploy and iterate.
* ***Is the contract supposed to be deployed on many accounts?***
If the same contract will be reused across many independent accounts — say, 10 or more — Global Contracts can significantly reduce overall cost and complexity. But if only a few accounts are involved, regular deployment remains the more economical choice.
* ***Are these accounts managed by your team?***
If all target accounts are under your infrastructure, you may prefer regular deployments for flexibility and cost recovery.
* ***Are there more than 10 accounts?***
Global Contracts become financially efficient when reused at scale. If you're deploying the same contract to more than 10 accounts, it's likely worth considering.
* ***Do you need to upgrade the contract across many accounts in one step, even if it requires burning tokens?***
If you want to be able to push updates to all deployed instances at once, then go with Global Contracts by Account ID, but keep in mind that the deployment cost is non-refundable.
* ***Does your use case require the contract to be permanently immutable?***
If the contract must never change, for example, due to security, compliance, or user trust, then using a Global Contract by Code Hash ensures immutability at the protocol level.
## Deploying a Global Contract
> [!NOTE]
>
> Publishing a global contract under an account ID makes that ID a reference to reusable code. **It does not deploy an executable contract on that account.** To call methods on the account, you must separately deploy a regular contract there or attach global code with `UseGlobalContract`.
Global contracts can be deployed by hash or by account ID. Contracts deployed by hash are immutable. When a contract is deployed by account ID, its owner can redeploy the code and update every account that uses that reference.
> [!NOTE]
>
> Deploying a global contract incurs high storage costs. Tokens are burned to compensate for storing the contract on-chain, unlike regular contracts where tokens are locked based on contract size.
> [tab] CLI
>
> Deploy by account ID:
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract deploy-as-global use-file as-global-account-id network-config testnet sign-with-keychain send
> ```
>
> Deploy by hash:
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract deploy-as-global use-file as-global-hash network-config testnet sign-with-keychain send
> ```
> [tab] Rust
>
> Use `deploy_global_contract_code` with `as_account_id` to deploy by account:
>
> ```rust title="global_contract_accountid.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> let global_account_id: AccountId = account_id_string.parse().unwrap();
> let global_code = std::fs::read("../contracts/contract.wasm").unwrap();
> let global_signer = Signer::from_secret_key(private_key).unwrap();
>
> // Deploy the global contract code using the account ID `nft-contract.testnet`
> // This will deploy the contract to the specified account ID
> // and return the final execution outcome
> let result = Contract::deploy_global_contract_code(global_code)
> .as_account_id(global_account_id.clone())
> .with_signer(global_signer.clone())
> .send_to_testnet()
> .await
> .unwrap();
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-api-examples/blob/fe8a9b52688965ef272fc2e199fcd46111ff3ade/near-api-rs/examples/global_contract_accountid.rs#L16-L28)
>
> Use `deploy_global_contract_code` with `as_hash` to deploy by hash:
>
> ```rust title="global_contract_hash.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> let account_id: AccountId = account_id_string.parse().unwrap();
> let code = std::fs::read("../contracts/contract.wasm").unwrap();
> let signer = Signer::from_secret_key(private_key).unwrap();
>
> // Deploy the global contract code using a hash
> // This will deploy the contract to the global contract hash
> // and return the final execution outcome
> let result = Contract::deploy_global_contract_code(code.clone())
> .as_hash()
> .with_signer(account_id.clone(), signer.clone())
> .send_to_testnet()
> .await
> .unwrap();
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-api-examples/blob/fe8a9b52688965ef272fc2e199fcd46111ff3ade/near-api-rs/examples/global_contract_hash.rs#L16-L28)
## Using a Global Contract
After the global code is deployed, attach it to an account with the `UseGlobalContract` action, referencing the publisher account ID or code hash. The CLI commands below create this action for ``; subsequent function calls target ``.
If the contract requires initialization, attach the code and call its initializer in the same transaction with `with-init-call`, as shown in the [NFT deployment guide](/primitives/nft/nft#global-contract). This prevents another caller from initializing your instance first. The `without-init-call` examples below only attach the code; they do not initialize contract state.
> [tab] CLI
>
> Use a contract published by account ID:
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract deploy use-global-account-id without-init-call network-config testnet
> ```
>
> Use a contract published by hash:
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near contract deploy use-global-hash without-init-call network-config testnet
> ```
> [tab] Rust
>
> Reference a global contract by account ID with `use_global_account_id`:
>
> ```rust title="global_contract_accountid.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Please note that you have to trust the account-id that you are providing. As the code is mutable, the owner of the referenced account can
> // change the code at any time which might lead to unexpected behavior or malicious activity.
> let my_signer = Signer::from_secret_key(private_key).unwrap();
>
> let result = Contract::deploy(new_account_id)
> .use_global_account_id(global_account_id)
> .without_init_call()
> .with_signer(my_signer)
> .send_to_testnet()
> .await
> .unwrap();
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-api-examples/blob/fe8a9b52688965ef272fc2e199fcd46111ff3ade/near-api-rs/examples/global_contract_accountid.rs#L61-L71)
>
> To reference a global contract by hash, calculate its code hash and call `use_global_hash`:
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> let code = std::fs::read("../contracts/contract.wasm").unwrap();
> let global_hash = near_api::CryptoHash::hash(&code);
> ```
>
> ```rust title="global_contract_hash.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Prepare a transaction to deploy a contract to the provided account using an immutable hash reference to the code from the global contract code storage.
> let my_signer = Signer::from_secret_key(private_key).unwrap();
>
> let result = Contract::deploy(new_account_id)
> .use_global_hash(global_hash)
> .without_init_call()
> .with_signer(my_signer)
> .send_to_testnet()
> .await
> .unwrap();
> ```
>
> [See code on GitHub](https://github.com/near-examples/near-api-examples/blob/fe8a9b52688965ef272fc2e199fcd46111ff3ade/near-api-rs/examples/global_contract_hash.rs#L62-L71)
> [!TIP]
>
> See the [NEAR API examples](/tools/near-api#deploy-a-global-contract) for complete Rust deployment and usage flows.
### Updating global contracts
If a contract is expected to get upgrades from time to time, then it should be rolled out using the `Account Id` strategy. Using a Global Contract by `Hash` is for immutable contracts that are supposed to stay the same forever.
Keep in mind, when using a Global Contract by [account ID](#reference-by-account), the one that handles the contract update is the original account, so they're responsible for contract state upgrading too.
# Your First Smart Contract
Source: https://docs.near.org/smart-contracts/quickstart
Create your first Rust smart contract, test it locally with NEAR Sandbox, and deploy it to testnet when ready to share.
Welcome! [NEAR accounts](../protocol/accounts-contracts/account-model) can store small apps known as smart contracts. In this tutorial, we'll guide you through creating and testing your first contract on NEAR.
Create an auction contract that allows users to place bids, track the highest bidder, and claim tokens at the end of the auction.
***
## Prerequisites
Before starting, make sure to set up your development environment.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Install Rust: https://www.rust-lang.org/tools/install
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Contracts will be compiled to wasm, so we need to add the wasm target
rustup target add wasm32-unknown-unknown
# Install NEAR CLI-RS to deploy and interact with the contract
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/near-cli-rs/releases/latest/download/near-cli-rs-installer.sh | sh
# Install cargo near to help building the contract
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/cargo-near/releases/latest/download/cargo-near-installer.sh | sh
```
***
## Creating the contract
Create a smart contract with the `cargo near` scaffolding tool by following its instructions:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Create a new contract called "auction"
cargo near new auction
# Navigate into the project directory
cd auction
```

> [!TIP]
>
> For this tutorial, we chose to name the project `auction`, but feel free to use any name you prefer.
***
## How bidding works
The contract in `src/lib.rs` stores the highest bid and the auction's end time. Its `bid` method accepts a deposit, checks that the auction is still open and the new bid is higher, then records the bid and refunds the previous bidder:
```rust title="lib.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[payable]
pub fn bid(&mut self) -> Promise {
// Assert the auction is still ongoing
require!(
env::block_timestamp() < self.auction_end_time.into(),
"Auction has ended"
);
// Current bid
let bid = env::attached_deposit();
let bidder = env::predecessor_account_id();
// Last bid
let Bid {
bidder: last_bidder,
bid: last_bid,
} = self.highest_bid.clone();
// Check if the deposit is higher than the current bid
require!(bid > last_bid, "You must place a higher bid");
// Update the highest bid
self.highest_bid = Bid { bidder, bid };
// Transfer tokens back to the last bidder
Promise::new(last_bidder).transfer(last_bid)
}
```
[See code on GitHub](https://github.com/near-examples/auctions-tutorial/blob/4678765ea7f2a584b1a6569786d497dcf75f5261/contract-rs/01-basic-auction/src/lib.rs#L36-L62)
See the [auction tutorial](/web3-apps/tutorials/mastering-near/1.1-basic) for an in-depth guide on the contract's initialization, view methods, and claiming logic.
***
## Test the contract locally
The project includes unit tests and sandbox tests. The sandbox tests build the contract and test it in a local Sandbox, that allows you to simulate a full NEAR environment locally without needing to create a testnet account or use real tokens.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cargo test
```
The test builds the contract, starts a local blockchain, and prepares a signer for transactions:
```rust title="tests/test_basics.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
let contract_wasm_path = cargo_near_build::build_with_cli(Default::default())?;
let contract_wasm = std::fs::read(contract_wasm_path)?;
let sandbox = near_sandbox::Sandbox::start_sandbox().await?;
let network = near_api::NetworkConfig::from_rpc_url("sandbox", sandbox.rpc_addr.parse()?);
let signer = near_api::Signer::from_secret_key(
near_sandbox::config::DEFAULT_GENESIS_ACCOUNT_PRIVATE_KEY.parse()?,
)?;
```
It creates funded accounts for two bidders, the auctioneer, and the contract. All accounts belong to this local sandbox:
```rust title="tests/test_basics.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
let alice = create_subaccount(&sandbox, "alice.sandbox").await?;
let bob = create_subaccount(&sandbox, "bob.sandbox").await?;
let auctioneer = create_subaccount(&sandbox, "auctioneer.sandbox").await?;
let contract = create_subaccount(&sandbox, "contract.sandbox").await?.as_contract();
```
Next, it deploys and initializes the contract locally, setting the auction to end in one minute:
```rust title="tests/test_basics.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)?.as_secs();
near_api::Contract::deploy(contract.account_id().clone())
.use_code(contract_wasm)
.with_init_call("init", json!({
"end_time": ((now + 60) * 1_000_000_000).to_string(),
"auctioneer": auctioneer.account_id(),
}))?
.with_signer(signer.clone())
.send_to(&network).await?.assert_success();
```
Alice bids 1 NEAR, then Bob bids 2 NEAR. After each transaction, the test reads the highest bid and checks both the bidder and the amount:
```rust title="tests/test_basics.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
for (bidder, amount) in [(&alice, 1), (&bob, 2)] {
contract.call_function("bid", ())
.transaction()
.deposit(NearToken::from_near(amount))
.with_signer(bidder.account_id().clone(), signer.clone())
.send_to(&network).await?.assert_success();
// Check the highest bid after each transaction
let highest_bid: Bid = contract.call_function("get_highest_bid", ())
.read_only().fetch_from(&network).await?.data;
assert_eq!(&highest_bid.bidder, bidder.account_id());
assert_eq!(highest_bid.bid, NearToken::from_near(amount));
}
```
The sandbox can advance the blockchain so the auction ends without waiting a minute. The auctioneer can then claim the proceeds:
```rust title="tests/test_basics.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
sandbox.fast_forward(200).await?;
contract.call_function("claim", ())
.transaction()
.gas(NearGas::from_tgas(30))
.with_signer(auctioneer.account_id().clone(), signer.clone())
.send_to(&network).await?.assert_success();
```
Finally, the test checks that the auctioneer's balance includes the winning 2 NEAR bid, minus gas fees, on top of the initial 10 NEAR:
```rust title="tests/test_basics.rs" lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
let balance = auctioneer.tokens().near_balance().fetch_from(&network).await?.total;
assert!(balance > NearToken::from_millinear(11_990));
assert!(balance <= NearToken::from_near(12));
```
Run `cargo test` throughout development to check these interactions locally. Learn more about [unit tests](/smart-contracts/testing/unit-test) and [sandbox tests](/smart-contracts/testing/integration-test).
***
## Deploy and initialize on testnet
When you are ready to make the contract available to others, build it and deploy it to a testnet account. Testnet uses test tokens with no real value.
### Build and create an account
From the `auction` directory, build the contract and create an account to host it. Replace `your-auction.testnet` with your desired account name:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cargo near build non-reproducible-wasm
CONTRACT_ID=your-auction.testnet
near create-account "$CONTRACT_ID" --useFaucet --networkId testnet
```
> [!TIP]
>
> **Already have a testnet account?**
>
> If you already have a `testnet` account and would like to use it instead, you can log in with the command `near login`. Set `CONTRACT_ID` to that account's name.
> [accordion] Got an error on Windows?
>
> When working in `WSL`—or another headless Linux environment—you might encounter issues creating an account because the CLI tries to save keys to the system keychain.
>
> In such cases, you can try the following command to create the account:
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> near account create-account sponsor-by-faucet-service "$CONTRACT_ID" autogenerate-new-keypair save-to-legacy-keychain network-config testnet create
> ```
### Deploy and initialize the auction
The contract's `init` function sets the auction end time and the auctioneer who receives the winning bid. Here, we set the end time to five minutes from now, in nanoseconds, and use the contract account as the auctioneer. You can set `AUCTIONEER_ID` to another existing testnet account if you prefer.
Deploy and initialize in the same transaction so the auction is ready to use as soon as it is deployed:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
AUCTIONEER_ID="$CONTRACT_ID"
END_TIME=$(( ($(date +%s) + 300) * 1000000000 ))
near contract deploy "$CONTRACT_ID" \
use-file ./target/near/auction.wasm \
with-init-call init json-args "{\"end_time\":\"$END_TIME\",\"auctioneer\":\"$AUCTIONEER_ID\"}" \
prepaid-gas '100 Tgas' attached-deposit '0 NEAR' \
network-config testnet sign-with-keychain send
```
The command uses the contract account's key to sign the transaction. After the transaction succeeds, your auction is deployed and initialized on testnet.
### Try placing a bid
To try the auction through the CLI, create a bidder account and place a bid before the five-minute auction ends. Replace `your-bidder.testnet` with your desired account name:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
BIDDER_ID=your-bidder.testnet
near create-account "$BIDDER_ID" --useFaucet --networkId testnet
# Bid 0.01 NEAR
near call "$CONTRACT_ID" bid '{}' --deposit 0.01 --useAccount "$BIDDER_ID" --networkId testnet
# Check the highest bid
near view "$CONTRACT_ID" get_highest_bid '{}' --networkId testnet
```
The result should show your bidder account and a bid of `"10000000000000000000000"` yoctoNEAR, equal to `0.01` NEAR.
## That's it!
You can now interact with the contract through a [frontend](/web3-apps/tutorials/mastering-near/2.1-frontend) or [call its functions directly using the CLI](/smart-contracts/release/deploy#calling-the-contract).
***
## Frequently Asked Questions
> [accordion] What about mainnet?
>
> Once your contract is ready for release, follow the [deployment guide](/smart-contracts/release/deploy) to deploy to mainnet.
> [accordion] How much does it cost to deploy?
>
> The cost of deploying a contract depends on its size: approximately 1 Ⓝ per 100 KB.
> [accordion] Can I update a contract after deploying?
>
> Yes. Redeploy with `near deploy `. The account stays the same, and the code is updated.
> [accordion] How do I test without deploying?
>
> Run `cargo test` from your project directory. The sandbox tests handle local accounts and contract setup for you, so you can test the contract without a testnet account.
> [accordion] Which SDK should I use to write smart contracts?
>
> Use [near-sdk-rs](/tools/sdk), NEAR's only official smart-contract SDK. It provides the Rust APIs used throughout this guide.
***
## Moving forward
> [card] [Create a Frontend](/web3-apps/tutorials/mastering-near/2.1-frontend)
>
> Check the auction frontend tutorial to learn how to build a simple web app that interacts with the auction contract.
> [card] [Extend the Contract](/web3-apps/tutorials/mastering-near/3.1-nft)
>
> Follow the auction NFT tutorial to award the highest bidder a Non-Fungible Token (NFT) and allow users to bid using Fungible Tokens (FT).
> [card] [Learn More about the SDK](/smart-contracts/anatomy/anatomy)
>
> Check our Anatomy of a Contract page to understand the different components that make up a NEAR smart contract.
# Deploying
Source: https://docs.near.org/smart-contracts/release/deploy
Deploy a contract to the network.
After your contract is ready you can deploy it in the NEAR network for everyone to use it.
Let us guide you on how to use the [NEAR CLI](../../tools/cli) to deploy your contract
and call its methods.
> [!NOTE]
>
> On this page, we will only cover the basics of NEAR CLI. For more information visit the
> [NEAR CLI documentation page](../../tools/cli).
***
## Deploying the Contract
Thanks to the `NEAR CLI` deploying a contract is as simple as:
1. Compiling the contract to wasm.
2. [Create an account](../../tools/cli#create) and [deploy the contract](../../tools/cli#deploy) into it using `NEAR CLI`.
### Compile the Contract
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cargo near build
```
### Create an Account and Deploy
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Create a new account pre-funded by a faucet
near create-account --useFaucet
# deploy the contract
near deploy
```
### Deploy in an Existing Account
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# login into your account
near login
# deploy the contract
near deploy
```
> [!TIP]
>
> You can overwrite a contract by deploying another on top of it. In this case, the account's logic
> will change, but the state will persist
> [!NOTE]
>
> By default `near-cli` uses the `testnet` network. Define `NEAR_ENV=mainnet` to deploy into `mainnet`.
> [!NOTE]
>
> **Naming Convention for Public-Facing Methods**
> Once the contract is deployed to the network, anyone and any other contract (i.e., any other account on NEAR) can interact with it by calling its methods. Furthermore, any transactions involving the contract will also be included in the network's data stream, which means its activity can also be visible to any who listens to particular events.
>
> Considering this, we advise to name methods using `snake_case`, which is the convention across the NEAR ecosystem.
***
## Initializing the Contract
If your contract has an [initialization method](../anatomy/storage) you can call it to
initialize the state. This is not necessary if your contract implements `default` values for the state.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Call the initialization method (`init` in our examples)
near call [] --useAccount