January 27, 2022

How to Set Up a Near Project from Scratch

Overview

In this tutorial we will look at how we can setup a basic NEAR project from scratch, installing and configuring dependencies and customizing the project to work well with AssemblyScript.

We will first start by initializing our project with a package.json file using NPM, then setting up and configuring/customizing AssemblyScript for our NEAR contract development.

Prerequisites:
  • Node.js installed
  • Basic javascript/typescript knowledge
  • Enthusiasm to complete tutorial

Setting Up the project

In this section, we will initialize our project from a blank folder and install the necessary dependencies for our project to work. We first create our project folder and name it whatever we want. I’ll be naming mine nearfromscratch. With the folder opened in our editor, we run the npm init command which will run us through some questions like project version, author, etc. When we are done initializing our project, we see our package.json file in our project folder. Below is the information we have in our package.json file.

// package.json
{
  "name": "near-singleton-concept",
  "version": "1.0.0",
  "description": "Learn how the singleton concept works",
  "scripts": {
    "test": "asp"
  },
  "author": "Uma Victor",
  "license": "ISC",
}

Next, we install the SDK library used in building smart contracts in AssembyScript and interact with the NEAR blockchain.

yarn add -D near-sdk-as

Once the installation is done, a package.json and a yarn.lock file is created with all the configurations.

Since we are building with AssemblyScript, the AssemblyScript compiler expects us to put our contract file in an assembly folder in our root directory. Let’s do that.

mkdir assembly

We also need to create an asconfig.json file which is a configuration file with different configurations for our AssemblyScript compiler to understand. In the file, we paste the following:

// asconfig.json
{
    "extends": "near-sdk-as/asconfig.json"
}

We have set up the project, it’s now time to write our smart contract and compile it. We will do this in the next section.

Writing Our Contract

In this section, we will look at the different ways we can write a smart contract for NEAR using AssemblyScript and create a greeting smart contract.

Smart contracts on NEAR can be written with two programming languages, which are RUST and AssemblyScript. For this tutorial, we will be making use of the AssemblyScript language to write our contract.

The two ways we can create AssemblyScript NEAR smart contracts is by:

  1. Having a collection of exported functions in the contract interface
  2. The singleton method, which involves having a class and writing our smart contract methods in the class and then exporting it.

We will be using the singleton method for our contract. First, let us create an index.ts file in our assembly folder, and in it we have:

// index.ts
import {Context, storage, logging } from "near-sdk-as";
// --- contract code goes below
/*
 * This is an example of an assembly smart contract on NEAR using the singleton method
 *
 * 1. setGreeting: accepts a greeting, such as "howdy", and records it for the
 *    user (account_id) who sent the request
 * 2. getGreeting: accepts an account_id and returns the greeting saved for it,
 *    defaulting to "Hello"
 *
 * Learn more about writing NEAR smart contracts with AssemblyScript:
 * https://docs.near.org/docs/develop/contracts/as/intro
 *
 */
@nearBindgen
export class Greeting {
  private DEFAULT_MESSAGE: string = "hello world"
 getGreeting(accountId: string): string | null {
    // This uses raw `storage.get`, a low-level way to interact with on-chain
    // storage for simple contracts.
    // If you have something more complex, check out persistent collections:
    // https://docs.near.org/docs/concepts/data-storage#assemblyscript-collection-types
    return storage.get<string>(accountId, this.DEFAULT_MESSAGE)
  }
  setGreeting(message: string): void {
    const accountId = Context.sender
    // Use logging.log to record logs permanently to the blockchain!
    logging.log(`Saving greeting "${message}" for account "${accountId}"`)
    storage.set(accountId, message)
  }
}

The above greeting contract is written using the singleton method. The smart contract code is commented on so you can understand what is happening. You can learn more about building smart contracts on NEAR from their official docs. Then play around a bit with the code and see how you can write the contract interface by just exporting the contract functions.

Let us see how we can set up our type configuration for our greeting smart contract and compile the the contract in the next section.

Setting Up Type Configuration And Compiling Our Contract

In this section, we will look at how to set up type configuration for typescript so the assembly script compiler can understand. Also, we will compile our contract into a web assembly file. The reason we are setting up the type configuration is due to the presence of certain types from the AssemblyScript language that the typescript compiler can’t understand. To do this, we create a tsconfig.json file at the root of our directory and paste the following configuration

// tsconfig.json
{
    "extends": "../node_modules/assemblyscript/std/assembly.json",
    "include": ["./**/*.ts"]
}

Now, we can compile our contract by running the command:

npx asb

This command compiles our index.ts file down to a .wasm file which can now be deployed on the NEAR blockchain. The compiled wasm file is located in the build folder created as we run the command. In the next section we will be running our tests and compiling our contracts.

Writing Tests For Our Contract

When writing smart contracts on NEAR, or any blockchain, writing tests can be very helpful because of the immutable nature of blockchain. That is why in this section, we will look at how to set up a testing suite in the AssemblyScript NEAR contract. To get started, let us first initialize a sample test with this command:

npx asp --init

When we run the command, we can see that an as-pect.config.js file is created in the root of our project and a __test__ folder is also created in the same directory as our index.ts file. In the as-pect.config.js, we configure our test to work with NEAR by pasting this config in the file:

module.exports = require("near-sdk-as/imports");
module.exports.include.push("**/*.unit.spec.ts");

In the __test__ folder we have example.spec.ts file which contains the sample test for our contract. We can clear the content of the file and now paste the actual tests for the contract we wrote:

// example.spec.ts 
/*
 *import the Greeting class we created in our index.ts file
 */
import { Greeting } from '..'
import { storage, Context } from 'near-sdk-as'
let greeting: Greeting
describe('Greeting ', () => {
  it('should be set and read', () => {
    greeting.setGreeting('hello world')
  })
})


The code above makes sure we set our greetings to hello world. To learn more about unit tests with AssemblyScript, you can read up on this tutorial. Now if we run the npx asp command, our test passes and we are good to go.

Deploying Our NEAR Contract Locally

In the last section, we looked at how to test our contract. All our tests are passing and in this section, we will look at how to deploy our contract and interact with the contract methods using the near-cli. To deploy our contract we need to compile it first. To compile our contract, we run this command:

npx asb

The command compiles our AssemblyScript contract into a Wasm file before it can be deployed to the NEAR blockchain. This wasm file is located in our build/release folder and is ready to be deployed to the NEAR blockchain.

Before we can continue, we need the near-cli installed. The near-cli is a node.js command-line interface that makes use of the NEAR API to connect and interact with the NEAR blockchain.

To install, run:

npm install -g near-cli

NOTE: make sure you have Node version 12 or higher installed.

Login to NEAR
Now that we have the near-cli installed, we need to create a testnet account that we can log into while we are deploying our contract to production. To deploy to production we first need to create a testnet account by visiting here.


Click on Create Account, follow the prompts and you’ll have your testnet accountId created in less than a minute.

Your accountId identifies you and your wallet on the NEAR blockchain. You’ll be using your testnet accountId to log into the near-cli and also deploying your contracts to it.

We have created a testnet account and the near-cli installed globally, next we run the command:

near login

The near login command redirects us to a browser window where we select the account we just created.


Then we click next. On the next page, we click on connect and we see a pop-up window prompting us to paste our accountId:


We click on confirm and we see a message on our screen telling us we are logged in successfully. In the terminal we can also see that we have logged in:


It is now time to deploy our contract. To deploy, run the command:

near dev-deploy build/release/<your contract name here>.wasm

Once the command is done running, we can see that a folder neardev appears in the root of our project folder, containing a text file and an env file, with the contract dev account it was deployed.

Deploying Our Contract In Production

In the last section, we looked at how to deploy our contract in development. Let us see how we can deploy to production in this section. To deploy we specify our contract name which is our accountId and the location of the contract wasm file we are to deploy. Look at the command below

near deploy --contractName=umamad.testnet --keyPath=./path-to/testnet/<accountId>.json --wasmFile=./build/release/<contractName>.wasm

When we run the command, our contract is deployed successfully. Now it’s time to interact with the contract by calling the methods we have.

Interacting With Our Deployed Contract

In the last section, we looked at how to compile and deploy our smart contract, and in this section, we will look at how we can interact with the smart contract. In the smart contract we wrote earlier, we have two methods we can interact with which are

  • getGreeting -which fetches the greetings we have.
  • setGreeting - which sets the greeting as an argument.

To set a greeting, you can run this command:

near call umamad.testnet setGreeting '{"message": "hello vicky"}' --accountId umamad.testnet

The code above calls the setGreeting function with the message argument. When we run the command we get this in our terminal


We have updated our state with the new greeting and we can view it on the near explorer by clicking on the link in the terminal. Now we want to get the greeting we just set to the state, so we call the getGreeting method. To get the greeting we set, we run:

near call umamad.testnet getGreeting --accountId umamad.testnet

And in our terminal, we see:


The command returns to the terminal the greeting that was set by the setGreeting method “hello vicky”.

umamad.testnet is the testnet account created for this tutorial, so make sure you use the accountId you created earlier and not umamad.testnet

In this section we interacted with the methods we created in our smart contract and returned the greeting we set.

Conclusion

We have finally come to the end of this tutorial. In the tutorial, we looked at how to setup a basic NEAR project from scratch, installing and configuring dependencies and running tests for the contract. Hope you enjoyed reading the tutorial and got a better understanding of how a NEAR project is set up. If you would like to learn more about NEAR you can read up on their documentation.

Subscribe to our newsletter for more articles and guides on Ethereum. If you have any feedback, feel free to reach out to us via Twitter. You can always chat with us on our Discord community server, featuring some of the coolest developers you’ll ever meet :)
Ready to try QuickNode? Start your 7-day free trial

Related articles 48

Apr 13, 2022 How to Send a Transaction On Solana Using JavaScript

Hello reader! Today is an exhilarating day because we are going on an expedition to the Solana Blockchain. Solana is an up-and-coming blockchain seeking to improve upon the current ecosystem's solutions to the complex problem of providing a secure, scalable, decentralized...

Continue reading
Dec 29, 2021 How to generate a new Ethereum address in PHP

PHP is very popular in developing the backend of websites or web applications. PHP has a huge crowd of developers trusting it as their go-to language. In this guide, we will see how we can generate a new Ethereum address in...

Continue reading
Apr 12, 2022 How to do a non-custodial transaction with QuickNode

Private keys are one of the most sensitive pieces of data when it comes to cryptography and the blockchain. However, there has always been debate/confusion about choosing between custodial wallets (where the wallet provider has custody of the user’s private key) and...

Continue reading
Apr 12, 2022 How to Setup Local Development Environment for Solidity

The success story of blockchain started with Bitcoin and was given wings by Ethereum. Ethereum was the first blockchain to introduce programmable software to the immutable ledger; these programs that live on the blockchain are called smart contracts. Solidity is the...

Continue reading
Apr 12, 2022 How to connect to Ethereum using .NET (Nethereum)

Dotnet or .NET is very popular for the development of desktop applications, most Windows desktop applications are built using .NET, and it also contributes largely to web application’s tech stack. In this guide, let’s see how we can connect to Ethereum using .NET and

Continue reading
Dec 29, 2021 How to generate a new Ethereum address in Ruby

With high usage in web applications and straightforward syntax, Ruby is used by a vast number of people. This guide will cover creating an Ethereum address in Ruby using ruby-eth...

Continue reading
Apr 12, 2022 Estimating gas price using pending transactions in Python

To send a transaction on the Ethereum network, you need to pay fees for including the transaction in a block as well as the computation necessary in the transaction; this fee is called gas. The transactions are accepted into the block based on the amount of gas they are...

Continue reading
Dec 29, 2021 Como crear y lanzar un ERC-721 (NFT)

Coleccionables digitales que son compatibles con ERC-721 se han vuelto muy populares desde el lanzamiento de Cryptokitties y han ganado adopción masiva en los últimos meses. Esta guía cubrirá la parte de creación y lanzamiento...

Continue reading
Dec 29, 2021 How to Build Your DApp Using The Modern Ethereum Tech Stack: Hardhat and EthersJs

When building a smart contract on the Ethereum blockchain, new developers tend to reach out to tools like truffle and web3.js in building their smart contracts. This tutorial will look at how to use Hardhat and Ether.js, which are now becoming the standard in building...

Continue reading
Apr 12, 2022 How to connect to Ethereum network using Java / Web3j

We can say that Java is one of the most versatile languages out there, and it continues to be relevant in today's time. Java is so popular because of its massive user base and use cases. In this guide/tutorial, we'll learn how to connect to the Ethereum Blockchain network...

Continue reading
Apr 12, 2022 How to integrate IPFS with Ethereum

It can be costly to store massive files on a blockchain mainnet, and this is where decentralized file storing systems like IPFS can come in handy. Sometimes, NFTs use IPFS as well. In this guide, we’ll cover how we can integrate IPFS with...

Continue reading
Apr 12, 2022 How to connect to the Ethereum network using Ruby

Ruby has a huge fanbase. Ruby was developed by its creator with an intention to create a language people can have fun using. Ruby has been largely accepted by the developers all around the world since it’s launch, in fact, the biggest tech communities in many cities are...

Continue reading
Apr 12, 2022 How to Mint an NFT with Ethers.js

This guide demonstrates how to mint an NFT on the Polygon blockchain using the Ethers.js library and our Factory ERC-1155 contract we built in an earlier

Continue reading
Apr 12, 2022 How to connect to Ethereum network with ethers.js

When someone thinks of developing a dApp the first tool that comes to their mind is web3.js which is pretty common because of its popularity in the community and wide use cases, dApp development has been consistently growing and there are a lot of developers who want to...

Continue reading
Apr 12, 2022 How to Mint an NFT on Solana

Updated at: April 10, 2022Welcome to another QuickNode guide on Solana - the up-and-coming blockchain that seeks to solve the scalability issues of Ethereum. We will be walking through step-by-step how to create an NFT on Solana. NFT, short for Non Fungible Token,...

Continue reading
Apr 12, 2022 The Web3 Developer Stack

A developer stack is a bag of technologies a developer possesses. For example, MEAN (MongoDB, Express.js, AngularJS/Angular, and Node.js) and MERN (MongoDB, Express.js, React, and Node.js) are common web developer stacks. Similarly, today we will learn more about the web3...

Continue reading
Apr 12, 2022 How to deploy a smart contract with Brownie

Python is one of the most versatile programming languages; from researchers running their test models to developers using it in heavy production environments, it has use cases in every possible technical field. In today's guide, we will learn about Brownie, a Python-based...

Continue reading
Dec 29, 2021 Introduction to Scaffold-ETH 🏗

Developing applications involves juggling several moving pieces like front-ends, back-ends, and databases. But developing a decentralized application on a blockchain adds a few more elements like smart contracts and nodes that allow you to connect to the...

Continue reading
Dec 29, 2021 How to generate a new Bitcoin address in JavaScript

To do any type of transaction on the Bitcoin blockchain, you’ll need a public key or a Bitcoin address. In this guide, we’ll cover how to generate a new Bitcoin address in JavaScript using CyrptoCoinJS.

Continue reading
Dec 29, 2021 Como crear un NFT en SOLANA

¡Hola querido lector! Bienvenidos a una nueva guía de Solana.Solana es una blockchain que promete mucho a la hora de intentar resolver los problemas de escalabilidad que podemos apreciar en otras blockchains, como Ethereum por...

Continue reading
Apr 12, 2022 How to create a token on Terra using Terra Station

Terra is the stablecoins framework with a pool of tokens to work with. Today in this guide, we will learn how to create our own token on the Terra blockchain network.PrerequisitesA Terra Bombay testnet...

Continue reading
Apr 12, 2022 How to Deploy an NFT on Solana Using Candy Machine V2

Hello readers, in this guide we are going to go into how to set up an NFT mint on Solana using Candy Machine v2. Previously we had a guide up on the V1, but it is now deprecated and is no longer in use for new mints.Candy Machine v2 has some...

Continue reading
Apr 12, 2022 How to get the balance of an ERC-20 token

When a new token is made on the Ethereum network, it usually follows a specification. The most popular of which is the ERC20 specification. To meet this ERC20 standard, one's token must have a multitude of...

Continue reading
Apr 12, 2022 How to Send an EIP-1559 Transaction

While Ethereum has been trying to scale, it has encountered some gas price issues. Many layer 2 solutions and sidechains sprang into existence to solve this problem, but Ethereum is the main chain, and at some point, it has to be improved. EIP-1559 was introduced to...

Continue reading
Apr 12, 2022 How to Create an Address in Solana using JavaScript

Hello reader! Welcome to QuickNode's first Solana guide. Solana is an up-and-coming blockchain that seeks to solve the scalability issues that Ethereum has been handling. You will walk through step-by-step how to create a Solana address using the @solana/web3.js...

Continue reading
Apr 12, 2022 How to create your own DAO with Aragon

Blockchain provides us with the power of decentralization. Decentralization means the transfer of power to users/members rather than having a single centralized authority governing everything; it enables various use cases in finance, governance, voting, fundraising, etc....

Continue reading
Apr 12, 2022 How to create and deploy a smart contract with Hardhat

Ethereum development environments like Truffle and Hardhat make it easier to work with smart contracts and Ethereum nodes. They provide a set of tools to seamlessly write, test, and deploy...

Continue reading
Apr 12, 2022 How to Connect to Terra with JavaScript using Terra.js

Stablecoins have been bridging the gap between traditional currencies and blockchains. Stablecoins offer stable price tokens pegged by a reserve asset which is often a fiat current like USD, EUR, GBP. The Terra protocol provides a framework to work with stablecoins. This...

Continue reading
Apr 12, 2022 How to connect to Ethereum network using Go

Go helps you make faster scalable backends and this guide will show you how to connect your backend to Ethereum (and make it even faster, more reliable, and globally accessible, all thanks to QuickNode’s global infrastructure). What is...

Continue reading
Apr 29, 2022 How to re-send a transaction with higher gas price using ethers.js

Sometimes, you submit a transaction on Ethereum without enough gas due to network congestion or too many pending transactions offering a higher gas price than you have offered on your transaction. If you have a high priority transaction but low gas, you could end up...

Continue reading
Apr 12, 2022 How To Fork Ethereum Mainnet with Hardhat

Forking the chain at an older block of the blockchain is helpful if you want to simulate the blockchain’s state at that block; Hardhat has this functionality built in. In this guide, let’s go through the process of forking the Ethereum Mainnet at an older...

Continue reading
Apr 12, 2022 How to connect to Ethereum using PHP

PHP is a very popular choice among developers and has a vast community due to its long presence in web development. In this guide, we’ll cover how to connect to Ethereum with PHP using the web3.php...

Continue reading
Apr 12, 2022 How to connect to the Ethereum network using Python using Web3.py

You can build Ethereum applications in different programming languages. In this article, we will connect to the Ethereum network using Python.PrerequisiteEthereum Node (We will use QuickNode’s free...

Continue reading
Apr 12, 2022 How to use Subspace with QuickNode

In this guide, we'll understand a bit about reactive development and how to use Subspace with QuickNode.JavaScript is the programming language behind most of the internet apps and websites. JavaScript today has become one of the most used programming languages,...

Continue reading
Apr 12, 2022 How to fetch Ethereum event logs in Ruby

Ethereum log records are very useful to understand and keep track of smart contract events. In this guide, we are going to learn how to fetch ethereum event logs in Ruby using ethereum.rb ruby...

Continue reading
Apr 12, 2022 How to Fork Ethereum Blockchain with Ganache.

Forking and running a local simulated Ethereum environment is essential if you want to work with DeFi or do Ethereum development in general. In this guide, we’ll cover how to fork Ethereum Blockchain with

Continue reading
Apr 12, 2022 How to connect to Ethereum network with Web3.js

Libraries and frameworks make the development process a lot easier and faster. When it comes to Ethereum development, Web3.js is the go to library. That's because Web3.js is the official library, from the

Continue reading
Dec 27, 2021 How to Build a Wallet Generator for Solana in React

In this practical guide you will build a basic Wallet application with React and Web3 that will interact with Solana Network.This application will do the following operations:Connect to the...

Continue reading
Apr 12, 2022 Integrate Your Svelte App with a Smart Contract

Today we will be building a sample app in Svelte, and connecting it to a smart contract that we deploy on the Ropsten Network.Our frontend will be able to do the following:Allow the user to send a greeting message along with a wave to the...

Continue reading
Dec 29, 2021 How to Connect Your Dapp With MetaMask Using Ethers.js

In our dApp, we will have a simple react user interface that has a material button asking the user to connect to MetaMask. And if they do not have an account, they can create one or log in to their account. They will then view their wallet balance and address displayed on...

Continue reading
Dec 29, 2021 How to Build a One-Click Sign in Using MetaMask with PHP's Laravel

Social logins: we have all seen them, we have all used them. "Login with Facebook". "Login with Github".If you have been around the Web3 community you may have come across a more recent player in the game: "Login with MetaMask". For instance, this is...

Continue reading
Dec 29, 2021 How to generate a new Ethereum address in Go

Golang is very popular among backend developers for building infrastructures and microservices. Go is a procedural programming language. Developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google, then launched in 2009 as...

Continue reading
Dec 29, 2021 How to generate a new Ethereum address in Python

Python is one of the most versatile programming languages out there with an abundance of use cases; We can build many applications with Python from client-side to back end. In this guide, we will cover creating an Ethereum address in Python using the

Continue reading
Dec 29, 2021 How to generate a new Ethereum address in JavaScript

When it comes to programming, there’s hardly anyone who has not used or heard about JavaScript. JavaScript was initially created for client-side scripting but has become a full-featured Object-Oriented...

Continue reading
Dec 29, 2021 Como crear un NFT en Solana usando Candy Machine

¡Hola querido lector! Hemos recibido un montón de pedidos por otra guía de NFT en Solana. En la guia anterior no llegamos hasta la parte mas jugosa, que es la parte donde enlazamos una...

Continue reading
Jan 17, 2022 How to Mint an NFT on Solana Using Candy Machine

NOTE: This guide is based off of the V1 of Candy Machine. V1 has been deprecated. You can catch an up-to-date guide on V2 here

Continue reading
Apr 12, 2022 How to send a transaction on Terra using JavaScript and Terra.js

Terra has emerged as the choice of blockchain for developing a stablecoin based dApp. Terra provides a cutting-edge stablecoin framework for modern dApp development. In this guide, we will learn how to send a transaction on Terra using their javascript library...

Continue reading
Apr 12, 2022 How to Lazy Mint an NFT on Rarible with Rarepress

NFTs are great for creators to monetize their artwork and for people to get ownership of an item. But since gas prices are usually high given the highly in-demand space on Ethereum, minting an NFT or an NFT collection can become costly for a creator. Lazy minting solves...

Continue reading