Count on NEAR dApp
Count on NEAR is a friendly decentralized app that is used to store a number and exposes methods to increment, decrement, and reset it. It is an example project that can help developers to learn how to build decentralized apps using the NEAR blockchain. The app has a frontend and a smart contract. The frontend code is located in the /frontend folder, while the smart contract code is in the /contract folder. The contract presents 4 methods: get_num, increment, decrement, and reset. The frontend is composed of a single HTML file, and the website’s logic lives in /assets/js/index.js, which communicates with the contract through /near-interface.js. There are unit and integration tests in the project that developers can use to test the code. The app can be started either by using Gitpod or by cloning the project locally.
Our counter example is a friendly decentralized app that stores a number and exposes methods to
Starting the Counter
You have two options to start the Counter:
Recommended: use the app through Gitpod (a web-based interactive environment)
Clone the project locally .
If you choose Gitpod, a new browser window will open automatically with the code. Give it a minute, and the frontend will pop up (ensure the pop-up window is not blocked).
If you are running the app locally, enter the directory where you cloned it and use
yarn to install dependencies, and
yarn start to start it.
cd counter yarn yarn deploy yarn start
Your contract will then be compiled and deployed to an account in the
testnet network. When done, a browser window should open.
Interacting With the Counter
Go ahead and login with your NEAR account. If you don’t have one, you will be able to create one in the moment. Once logged in, use the
- buttons to increase and decrease the counter. Then, use the Gameboy buttons to reset it and make the counter blink an eye!
Frontend of the Counter
Structure of a dApp
Now that you understand what the dApp does, let us take a closer look to its structure:
The frontend code lives in the
The smart contract code is in the
The contract presents 4 methods:
reset. The method
get_num retrieves the current value, and the rest modify it.
The frontend is composed by a single HTML file (
/index.html). This file defines the components displayed in the screen.
The website’s logic lives in
/assets/js/index.js, which communicates with the contract through
/near-interface.js. You will notice in
/assets/js/index.js the following code:
It indicates our app, when it starts, to check if the user is already logged in and execute either
When writing smart contracts it is very important to test all methods exhaustively. In this project you have two types of tests: unit and integration. Before digging in them, go ahead and perform the tests present in the dApp through the command
Unit tests check individual functions in the smart contract. Right now only Rust implements unit testing.