Calculate RAM cost in EOSio Blockchains with JavaScript

Categories ProgramaciónPosted on

RAM is a resource of the most precious on a blockchain. All the information we store on it, NFTs, smart contract, transaction information, etc. is stored in the blockchain RAM.

This is the memory of the database and, as such, it is finite, so rational use of it must be ensured.

Certainly WAX Blockchain is one of the fastest and cheapest chains we can work with but leaving access to resources totally free could lead to abuses that would jeopardize the viability of the entire project. That’s why a price is assigned to the available RAM in order to make use of it.

The price of RAM is allocated in a balanced way between the amount of existing RAM and the current value of the entire RAM sold and both data can be found in the rammarket table of the main smart contract of the WAX blockchain: eosio

EOS, Telos and WAX are independent blockchains created with EOSio technology. Don’t confuse EOS with EOSio!

To calculate the cost in WAX of 1 byte of RAM you have to divide quote between base

Using JavaScript to calculate RAM

We need to have node.js, npm and our favorite code editor installed.

For this exercise we will create a directory and place it inside to create the project:

npm init

This statement generates the package.json file with the project data you asked us during the process.

Below we add the function libraries that we need to access an EOSio blockchain:

npm install eosjs node-fetch

We create the index.js file and add the code:

The ramPrice function receives as an argument a number representing the NFTs for which we want to buy RAM (it is an example).

The function body consists of an asynchronous call to the get_table_rows function to read records from the rammarket table (only has 1 record)

Once the result is obtained we extract the base and quote values and with split we remove the suffixes ‘WAX’ and ‘RAM’ to be able to trade with numerical values.

The cost of 1 byte of RAM is equal to quota/base

WAX RAM buying and selling operations are subject to a small commission of 0.5% so we will increase the price by that percentage to cover the cost.

Finally, we return the rounded and formatted result to WAX by multiplying the cost per byte * 150 Bytes per NFT * total assets (in the example 35,000 NFTs)

To test the code we run:

node index.js

See you in an upcoming tutorial!


📚Books and recommended material:

💲Invest in cryptocurrencies:

My wax blockchain projects:

WAX Arena:

Rada Quest TCG: