Skip to main content

Handling NEAR Types

When calling methods in a contract or receiving results from them, you will need to encode/decode parameters correctly. For this, it is important to know how the contracts encode timestamps, balances, and gas.

Searching for Smart Contract Data Types?

Check the Smart Contract Data Types section for more information on how to handle data types within smart contracts.


Time

The block timestamp in a smart contract is encoded using nanoseconds (i.e. 19 digits: 1655373910837593990).

Date.now() returns a timestamp in milliseconds (i.e 13 digits: 1655373910837). Make sure to convert between milliseconds and nanoseconds to properly handle time variables.


Deposits

Smart contracts handle NEAR amounts always using yoctoNEAR (1Ⓝ = 10^24yocto). This means that when interacting with contract's or the user's balance you will need to convert between NEAR and yoctoNEAR.

Under the hood, the network (and contracts) represent balances as u128, which are encoded as strings (since JSON cannot handle more than 52 bit integers).

Remember to always send amounts as strings (e.g. "1000000000000000000000000" for 1Ⓝ) and never as number (e.g. 1000000). Consequently, convert amounts from string whenever you want to display them to the user.

In javascript, you can use the near-api-js library to convert between NEAR and yoctoNEAR:

import { NEAR } from '@near-js/tokens'

const units = NEAR.fromDecimal('1.5') // 1.5Ⓝ
console.log(units) // "1500000000000000000000000"

const decimal = NEAR.fromUnits('1500000000000000000000000', 2)
console.log(decimal) // 1.5

Gas

When calling a contract method, you can specify how much gas you want to attach to the call. Within the network, the Gas is represented as a u64, which is encoded as a string (since JSON cannot handle more than 52 bit integers).

As a rule of thumb, functions that consume little computation can be called with 30 Tgas or less, while more complex functions may require up to 300 Tgas.

In javascript there is no built-in library to handle gas units, but you can easily convert between them as follows:

const TGAS = 1000000000000; // 1 Tgas = 10^12 gas units

function toTgas(gas) {
return (gas * TGAS).toString();
}

function fromTgas(tgas) {
return (parseInt(tgas) / TGAS).toFixed(2);
}