Skip to content

vandynem/hello-near-js

Repository files navigation

Hello Near JS Example

Overview

This simple example will demonstrate how to integrate a smart contract into a decentralized application, and how to store and retrieve information to and from the NEAR blockchain with call and view methods.

Installation & Setup

To clone run:

git clone https://github.com/near-examples/hello-near-js.git

enter the folder with:

cd hello-near-js

To download dependencies run:

yarn

or

npm i

Building Your Smart Contract

The Smart Contract consists of two methods available for the user to call.

    @call
    // Public method - accepts a greeting, such as "howdy", and records it
    set_greeting({ message }: { message: string }) {
        near.log(`Saving greeting ${message}`)
        this.message = message;
    }

    @view
    // Public method - returns the greeting saved, defaulting to DEFAULT_MESSAGE
    get_greeting(): string {
        return this.message;
    }

A call method stores or modifies information that exists in state on the NEAR blockchain. Call methods do incur a gas fee. Call methods return no values

A view method retrieves information stored on the blockchain. No fee is charged for a view method. View methods always return a value.

NearBindgen is a decorator that exposes the state and methods to the user.

To build your smart contract run

yarn build

or

npm run build

This build script will build and deploy your smart contract onto a dev account. Check the terminal logs t ofind the name of the dev account it was deployed to.

example:

dev-1659899566943-21539992274727

It will also initialize your smart contract for you.

Calling methods from terminal

This will store the string "hi user" onto the NEAR blockchain using the change method defined earlier

near call <dev account> set_greeting '{"message":"hi user"}' --accountId <your-account-name.testnet>

This will return and display your stored message

near view <dev account> get_greeting '{}' --accountId <your-account.testnet>

Running Frontend

To spin up the frontend run

yarn start

or

npm run start

From there you should be able to modify the greeting.

Run Tests

This example repo comes with integration tests written in rust and assembly type script.

To run tests run the following in your terminal:

yarn test

or

npm run test

Integration tests are generally written in javascript. They automatically deploy your contract and execute methods on it. In this way, integration tests simulate interactions from users in a realistic scenario. You will find the integration tests for hello-near in integration-tests/.