# Near

Source: https://developers.bitgo.com/docs/near

## Overview

NEAR Protocol is a decentralized blockchain platform designed to enable the creation and operation of scalable, high-performance decentralized applications (dApps). Utilizing a proof-of-stake (PoS) consensus mechanism, NEAR Protocol offers fast transaction finality and low transaction fees, making it suitable for a wide range of use cases.

NEAR is the native asset of the Near Protocol blockchain platform. It serves various purposes within the NEAR Protocol ecosystem, including transaction fees, staking, and governance. It utilizes the Account model.

## Explorer
<a href="https://nearblocks.io/" target="_blank" rel="noreferrer">https://nearblocks.io/</a>


## Ticker Symbols

| Mainnet | Testnet |
| ------- | ------- |
| NEAR    | TNEAR   |

## Wallets Types

BitGo enables holding Near in the following wallet types:

| | Multisig Cold | Multisig Hot | MPC Cold | MPC Hot |
|-| ------------- | ------------ | -------- | ------- |
| **Custody** | ❌ | N//A | ✅ | N/A |
| **Self-Custody** | ✅ | ❌ | N/A | ✅ |


## Faucet

Follow these steps to get NEAR testnet tokens:
1. Create a `<username>.testnet` wallet address on https://testnet.mynearwallet.com/
2. Get testnet tokens from https://near-faucet.io/ in the `<username>.testnet` wallet address created in step 1.
3. Send the testnet tokens from `<username>.testnet` wallet to the BitGo Test wallet.


## Units
The base unit of Near is `yocto`.
- 1 near = 10<sup>24</sup> yocto
- 1 yocto = 10<sup>-24</sup> near

To check the balance of a wallet:

```js JavaScript
const walletInstance = await bitgo.coin(coin).wallets().get({ id: walletId });

console.log('Wallet ID:', walletInstance.id());
console.log('Current Receive Address:', walletInstance.receiveAddress());
console.log('Balance:', walletInstance.balanceString());
console.log('Confirmed Balance:', walletInstance.confirmedBalanceString());
console.log('Spendable Balance:', walletInstance.spendableBalanceString());
```

## Tokens

The Near Protocol blockchain natively support tokens. To view all BitGo supported tokens on the Near Protocol Blockchain, see the [Near - NEP141 Tokens](/docs/near-nep141-tokens).

### Overview

BitGo wallets support fungible tokens on the NEAR protocol, adhering to the NEP-141 token standard. NEP-141 is the official Fungible Token (FT) standard on the NEAR Protocol, defining a common interface for fungible token contracts. This standard ensures interoperability across decentralized applications (dApps), wallets, and other ecosystem tools by mandating a consistent set of methods and behaviors.

Key aspects of NEP-141 include:

- **Token Operations**: It defines methods such as `ft_transfer`, `ft_transfer_call`, and `ft_balance_of`, which are essential for sending tokens, interacting with contracts, and querying balances.
The standard includes callback mechanisms to handle transactional logic safely, especially for cross-contract calls using `ft_transfer_call`.

- **Storage Management**: NEAR uses a storage staking model, so NEP-141 incorporates methods like `storage_deposit`, `storage_withdraw`, and `storage_balance_of` to manage account storage costs.
To receive a FT on an address, that address must be registered on that FT (registration requires a storage deposit).

- **Metadata Management**: An interface for a fungible token metadata. The goal is to keep the metadata future-proof as well as lightweight.

For the complete list of tokens onboarded, refer to: [Near - NEP141 Tokens](/docs/near-nep141-tokens).

### Enable Token

NEAR enforces a **storage staking model**, meaning storage on-chain costs real NEAR tokens (Ⓝ) to maintain. Smart contracts must ensure they have sufficient balance to cover the storage they use; otherwise, they may run out of funds or exceed gas limits during execution.

The `storage_deposit` method is a **payable function** defined in **NEP-141** (Fungible Token standard) that allows users to attach NEAR when interacting with a contract. This deposit reserves storage space for user-specific data, such as:

- Account registration
- Token balances
- Any other data the contract needs to store on behalf of the user

> ⚠️ **Warning:** Users must call `storage_deposit` before receiving or transferring tokens on a contract, or their transaction fails.

**How to Execute the `storage_deposit` Method for a BitGo Account**

Most platforms that send NEAR tokens initiate the `storage_deposit` along with the token transfer in the **same transaction**.

- If the account **is not registered**, the sender must pay a small fee for registration.
- If the account **is already registered**, the sender receives a **refund** of the registration fee.

The **Enable Tokens** flow allows BitGo accounts/addresses to be registered with the fungible token contracts by calling `storage_deposit`.

To enable a token for a BitGo account:

1. Go to your Near wallet
2. Navigate to **Settings**
3. Click on the **Enable Token** option
4. Select the **token** and the **BitGo address**
5. Sign or raise the transaction to complete the registration

> 📘 **Note:**
> - The storage deposit enablement incurs a cost of approximately `0.00125 Ⓝ`.
> - BitGo recommends that users enable the token for the **root address** of their wallets.
> - Failure to enable storage deposit may lead to **consolidation transfer failures**.
> - If you encounter deposit failures of NEAR tokens to an address:
>   - Ensure the token is **supported by BitGo**
>   - Enable `storage_deposit` for the respective token on that address

### How to Do a Consolidation for NEAR and NEAR Tokens

To consolidate your **receive address balances** into the **root address** using the UI:

1. Go to the **Wallet** and then the **Address** page
2. Click on the **three-dot menu** next to the address
3. Select **Consolidate Balances**
4. Choose the coin:
    - `NEAR`
    - Or a NEAR token like `near:usdt`, `near:usdc`

### Gas Tank

To consolidate NEAR tokens from a receive address, the address must hold some NEAR to pay the transaction fee.

NEAR wallets on **BitGo** utilize a **Gas Tank** to cover token consolidation fees — but **not** other transaction fees.

- The estimated gas required for a token consolidation transaction is approximately `0.000612 Ⓝ` (actual usage may be lower).
- Therefore, each receive address must maintain at least `0.000612 Ⓝ` **per unique token** that is to be consolidated.

When a receive address receives a token deposit, the Gas Tank:
- Calculates the amount of NEAR required for consolidation
- Initiates a transaction to fund the address with the calculated **differential amount**

#### Example Scenarios:

- ✅ If a receive address gets **USDC** and has `0 Ⓝ`: → Gas Tank funds it with `0.052612 Ⓝ`
`0.052 Ⓝ` is the **one-time reserve fee**,
`0.000612 Ⓝ` is the **per-token consolidation fee**

- ✅ If a receive address gets **USDC** and already has `0.052 Ⓝ`: → Gas Tank funds it with `0.000612 Ⓝ`

- ✅ If a receive address gets **USDC and USDT** and has `0 Ⓝ`: → Gas Tank funds it with `0.053224 Ⓝ`
`0.052 Ⓝ` for reserve + `0.001224 Ⓝ` for 2 tokens

- ✅ If a receive address gets **USDC and USDT** and has `0.053 Ⓝ`: → Gas Tank funds it with `0.000224 Ⓝ`

> 📘 **Note:**
> - The Gas Tank funds receive addresses **only** when BitGo detects a token deposit to a NEAR wallet address under the enterprise **and** the gas tank has sufficient funds.
> - If the gas tank balance is **low**, the funding action **fails**.
> - Replenishing the Gas Tank does **not automatically** fund affected receive addresses.
>   → Users must manually deposit NEAR to any impacted address.
> - BitGo recommends maintaining a **minimum Gas Tank balance of `1 Ⓝ`**.
> - Users receive a **low balance notification** once in 24 hours when the gas tank drops below `1 Ⓝ`.

## Fees

On every transaction you send to the network NEAR charges a fee (also known as gas fee). The network measures fees in gas units but pays them in NEAR. Gas units are deterministic, the same transaction costs the same gas units. Multiplying gas units by a gas price converts them to NEAR.

- Min. gas price = <code>10<sup>-16</sup> NEAR</code> per gas unit
- 1 TGas (10¹² gas units) ≈ 1 ms of "compute" time. ≈ <code>0.0001 NEAR</code>
- The gas price is not fixed: the network recalculates it each block depending on network demand. If the previous block is more than half full the price goes up, otherwise it goes down. The price cannot change by more than 1% each block.
- A maximum of ```300 TGas``` can be attached to a transaction.
- Attaching extra gas does NOT make the transaction faster; the network simply returns unused gas.


Learn more about fees at <a href="https://docs.near.org/protocol/transactions/gas" target="_blank" rel="noreferrer">Near docs</a>.


## Create Wallet
```shell cURL
export BITGO_EXPRESS_HOST="<YOUR_LOCALHOST>"
export COIN="[testnet ID all lowercase]"
export ACCESS_TOKEN="<YOUR_ACCESS_TOKEN>"
export LABEL="<DESIRED_WALLET_NAME>"
export PASSPHRASE="<YOUR_BITGO_LOGIN_PASSPHRASE>"
export ENTERPRISE_ID="<YOUR_ENTERPRISE_ID>"
export MULTISIGTYPE="tss"

curl -X POST \
  http://$BITGO_EXPRESS_HOST/api/v2/$COIN/wallet/generate \
  -H 'Content-Type: application/json' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -d '{
    "label": "'"$LABEL"'",
    "passphrase": "'"$PASSPHRASE"'",
    "enterprise": "'"$ENTERPRISE_ID"'",
    "disableTransactionNotifications": true,
    "disableKRSEmail": true,
    "multisigType": "'"$MULTISIGTYPE"'"
}'
```
```js JavaScript
const walletOptions: GenerateWalletOptions = {
  <label>,
  <passphrase>,
  passcodeEncryptionCode: <passphrase>,
  multisigType: 'tss',
  <enterprise>,
};

bitgo
  .coin(coin)
  .wallets()
  .generateWallet(walletOptions)
  .then(function (wallet) {
    console.log(JSON.stringify(wallet));
  });
```

## Create Address

```shell cURL
WALLET=585c51a5df8380e0e3082e46

curl -X POST \
-H "Authorization: Bearer $ACCESS_TOKEN" \
https://app.bitgo-test.com/api/v2/tnear/wallet/$WALLET/address
```
```js JavaScript
bitgo
  .coin('tnear')
  .wallets()
  .getWallet({ id: '585c51a5df8380e0e3082e46' })
  .then(function (wallet) {
    return wallet.createAddress();
  })
  .then(function (newAddress) {
    console.dir(newAddress);
  });
```


## Consolidate Balance
Near is an account-based asset and therefore requires consolidating to the base address to use the maximum spendable amount.

> 📘 **Note:** Near addresses require a minimum balance of `~0.052 NEAR`. This amount remains in the address after consolidation.


## Estimate Fee
```shell cURL
export COIN="tnear"
export ACCESS_TOKEN="<YOUR_ACCESS_TOKEN>"

curl -X GET \
  https://app.bitgo-test.com/api/v2/$COIN/tx/fee \
  -H 'Content-Type: application/json' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```
```js JavaScript
import { BitGoAPI } from '@bitgo/sdk-api';
import { TNear } from '@bitgo/sdk-coin-near';

const bitgo = new BitGoAPI({
  accessToken: <YOUR_ACCESS_TOKEN>,
  env: 'test',
});

const coin = 'tnear';
bitgo.register(coin, TNear.createInstance);

async function main() {
  const feeEstimate = await bitgo.coin(coin).feeEstimate({});
  console.log(feeEstimate);
}

main().catch((e) => console.error(e));
```


## Transact
```shell cURL
export BITGO_EXPRESS_HOST="<YOUR_LOCALHOST>"
export COIN="tnear"
export WALLET_ID="<YOUR_WALLET_ID>"
export ACCESS_TOKEN="<YOUR_ACCESS_TOKEN>"
export ADDRESS_1="<DESTINATION_ADDRESS_1>"
export ADDRESS_2="<DESTINATION_ADDRESS_2>"
export AMOUNT_1="<AMOUNT_1_IN_BASE_UNITS>"
export AMOUNT_2="<AMOUNT_2_IN_BASE_UNITS>"
export WALLET_PASSPHRASE="<YOUR_WALLET_PASSPHRASE>"

curl -X POST \
  http://$BITGO_EXPRESS_HOST/api/v2/$COIN/wallet/$WALLET_ID/sendmany \
  -H 'Content-Type: application/json' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -d '{
    "recipients": [
    {
      "address": "'"$ADDRESS_1"'",
      "amount": "'"$AMOUNT_1"'"
    },
    {
      "address": "'"$ADDRESS_2"'",
      "amount": "'"$AMOUNT_2"'"
    }
  ],
    "walletPassphrase": "'"$WALLET_PASSPHRASE"'",
    "type": "transfer",
    "isTss": "true"
}'
```
```js JavaScript
import { BitGo } from 'bitgo';

async function sendTx() {
  const coin = 'tnear';
  const env = 'test';

  // You can get this from User Settings > Developer Options > Add Access Token
  const accessToken = '<YOUR_ACCESS_TOKEN>';
  const walletId = '<YOUR_WALLET_ID>';
  const walletPassphrase = '<YOUR_WALLET_PASSPHRASE>';
  const otp = '000000';
  const receiveAddress = '<YOUR_RECEIVE_ADDRESS>';

  const bitgo = new BitGo({
    env: env,
    accessToken,
  });

  const basecoin = bitgo.coin(coin);
  bitgo.authenticateWithAccessToken({ accessToken });
  await bitgo.unlock({ otp: otp, duration: 3600 });

  const walletInstance = await basecoin.wallets().get({ id: walletId });
  const atomAmount = '2000000000000000000000000'; // 2 TNEAR
  const sendDetail = await walletInstance.sendMany({
    recipients: [
      {
        amount: atomAmount,
        address: receiveAddress,
      },
    ],
    walletPassphrase,
    type: 'transfer',
    isTss: true,
  });
  console.log(`${JSON.stringify(sendDetail)}`);
}

sendTx().catch((e) => console.error(e));
```


## Stake

For details specific to staking NEAR tokens, see the tables below:

<table border="0" style={{ textAlign: "left" }}>
    <thead>
        <tr>
            <th>Amounts</th>
            <th>Details</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Minimum</td>
            <td>None</td>
        </tr>
        <tr>
            <td>Maximum coin supply</td>
           <td>1,000,000,000 NEAR</td>
        </tr>
        <tr>
            <td>Do staked assets lock or stay liquid?</td>
           <td>Locked</td>
        </tr>
        <tr>
            <td>Fees</td>
           <td>Withdraw from wallet balance</td>
        </tr>
        <tr>
            <td></td>
           <td><br></br></td>
        </tr>
    </tbody>
    <thead>
        <tr>
            <th>Timeline</th>
            <th>Details</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Activation period</td>
            <td>4 epochs (36 hours)</td>
        </tr>
        <tr>
            <td>Unstaking period</td>
           <td>3 epochs (27 hours)</td>
        </tr>
        <tr>
            <td></td>
           <td><br></br></td>
        </tr>
    </tbody>
    <thead>
        <tr>
            <th>Rewards</th>
            <th>Details</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Rewards rate</td>
           <td>Decided by each validtor</td>
        </tr>
        <tr>
            <td>On-chain transactions for reward distributions?</td>
           <td>No</td>
        </tr>
        <tr>
            <td>Supports withdrawing rewards only?</td>
            <td>Yes</td>
        </tr>
        <tr>
            <td>Requires transaction to claim rewards?</td>
           <td>Yes</td>
        </tr>
        <tr>
            <td></td>
           <td><br></br></td>
        </tr>
    </tbody>
    <thead>
        <tr>
            <th>Validators</th>
            <th>Details</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Bring your own validator?</td>
            <td>Yes</td>
        </tr>
        <tr>
            <td>Stake to multiple validators simultaneously?</td>
           <td>No</td>
        </tr>
        <tr>
            <td>Stake multiple times to the same delegation?</td>
           <td>Yes</td>
        </tr>
        <tr>
            <td>Figment support?</td>
           <td>No</td>
        </tr>
        <tr>
            <td>Slashing?</td>
           <td>No</td>
        </tr>
        <tr>
            <td></td>
           <td><br></br></td>
        </tr>
    </tbody>
    <thead>
        <tr>
            <th>Integration</th>
            <th>Details</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Required transactions</td>
            <td>Delegation and redelegation</td>
        </tr>
        <tr>
            <td>Do staked assets leave wallet?</td>
           <td>No</td>
        </tr>
        <tr>
            <td>Number of transactions to unstake</td>
           <td>1</td>
        </tr>
        <tr>
            <td>Supports partial unstaking?</td>
           <td>Yes</td>
        </tr>
    </tbody>
</table>

## See Also

- [Staking Overview](/docs/stake-overview)
- [Trading Overview](/docs/trade-overview)
- [Consolidate Account Balance](/docs/wallets-consolidate)
