An Intro To Near Dapp Development With Rust, WASM, Parcel and React -Part 3.

Panasthetik
Coinmonks
Published in
12 min readMar 29, 2022

--

This article introduces existing Web3 developers to the Near Protocol with a simple, functional, start-to-finish example in three parts.

For those who are just joining us, feel free to look over the first two parts of this tutorial to get up to speed:

Part 1 can be found here, and Part 2 is located here.

The entire code repository for these articles can be found here.

Last time, we continued our developer journey on the Near blockchain by writing some Rust unit tests to run against our smart contract. We then created a deployment sub-account in Near-CLI, deployed our contract to Near Testnet, and were able to interact with it in the developer console.

For this week’s session, we will integrate our deployed smart contract with a simple React front end. This JavaScript portion of our tutorial can then be adapted to your needs as a starter template (for example, you may choose to build a more comprehensive and responsive interface with Next.js or another framework in the future).

Some follow-up items before we switch to React / JavaScript

As noted at the end of the last session, there are a couple of “loose ends” to tie up with our contract deployment before we proceed with our front end. One of these is addressing how we can “upgrade” our smart contract on Near when there are changes to the Rust code or if something doesn’t work as expected.

One of the advantages of developing on the Near blockchain is this ability to rewrite Rust code, recompile to WASM, and replace contracts completely when we need to at the same contract address.

If you recall how we first created a sub-account on the Near Testnet before we actually deployed the contract, you will notice the following code for sub-account creation in VSCode terminal:

In fact, the process for updating the smart contract first depends on deleting this sub-account — once the sub-account is deleted, the contract is gone from Near Testnet and can be replaced. In the VSCode terminal, enter:

Notice that you don’t have to state “masterAccount” here like you did with sub-account creation. As long as you’re still signed into Near with the master account, you have the authority to delete any sub-addresses you have created with it like above.

Upgrading / replacing a smart contract on Near

The first thing we need to do now is re-create the same sub-account again using the identical process as before (also shown above):

Of course you could name the new sub-account differently, or keep alternate versions of the contract itself under separate sub-account names on the Testnet.

However — it’s generally good practice to delete and re-create the smart contract sub-account like shown each time you upgrade, to keep things more organized on Near. This way, we reduce wasteful, duplicate contracts out on the blockchain that aren’t in use!

IMPORTANT: Now that we have an empty account created again to contain the smart contract, we can make our changes back in Rust. I will leave any potential edits up to the developer, but once we change the Rust code we will also need to DELETE the WASM file in the “res” folder before we re-compile it with our build script. Double check the “res” folder and make sure it is empty before proceeding!

After deleting the following from the “res” folder after your Rust changes…

“res/near_starter_dapp.wasm”

Let’s recompile our new revised Rust code with the same build script we’ve been using all along in our tutorial:

After the compilation finishes you should have a new, updated WASM file in “res”. We can then run a deploy command again, as before:

And if all goes smoothly, you should again see the confirmation screen for deployment like last time in your terminal:

NOTE: Your specific transaction ID will be different from the above!

To round out our “loose ends”, the last question(s) that come up from time to time when developing on Near are:

“Where is that long hexadecimal string for my deployed contract address out on the blockchain?”

“You know, the one that I need to call in my React application?”

“I don’t see that big hex string confirmed in the terminal like in Truffle/Hardhat on an EVM chain (or even like in Anchor on Solana, which is also a long hex string).”

The answer is: there isn’t a long, complicated hex string on Near for the contract instance — we already reserved a human-readable address for our contract! Remember, to deploy a contract on Near, we created the following sub-account:

This is the actual address we will paste into our React application to call our functions — no complicated hex strings to keep track of here! It would be the same type of readable contract address on Near Mainnet as well, as long as it was available. For example, it could be something like this:

So now that we have learned how to “upgrade” our smart contract on the Near Testnet, and we know more about how contract addresses work, we’re ready to switch over to React/JavaScript to integrate with a simple front end template!

Setting up the directories and config files for the front end integration

The first thing we need to do is move up one level in our folder structure, out of the “contract” folder (the one that holds the Rust/WASM part of the project) and into our root directory:

Once we change into this root directory (near-starter-dapp) let’s create a “package.json” file with the following dependencies like below:

As we can see, this list is very concise and minimal compared to some other tutorials out there. The reason is that I used Parcel 2.0+ for bundling, transpiling and the dev server, which eliminates the need for “Babel”, “Bundler” and a number of other common dependencies.

This gives you a basic, working dev template that runs in the browser on a local port, and it can be enhanced later for a final production version.

Let’s now run our JS dependencies install in Yarn (or NPM if your prefer — I will use Yarn here):

Now that our project dependencies are installed, we need to create two more files that act similarly to other config files you will find in Anchor, Hardhat or Truffle. Usually these are the “config” files in other frameworks, and they identify network information, wallet configuration, and the contract ID for the front end.

In the root directory (near-starter-dapp), create an “src” folder:

For our Near configuration files, the first of these should be the following inside our new “src” directory. We will name this file “config.js”:

config.js

This file does two things:

  1. It defines the smart contract that will be called by our Dapp by contract address (CONTRACT_NAME). You can see that the named contract address at the top is the same as the address we reserved / deployed to! In all cases, this should match whatever address you use when deploying.
  2. It lists network configurations for Near. In our case, we are only using the Testnet configuration (which is the same as “development” in the config), but it’s good to have all of the options (including Mainnet) in this file for future reference.

The next file we will create in our “src” folder is an API connector file. It initializes the wallet, active account ID, and the smart contract itself. It also defines the functions we will call with our Dapp. We’ll name this file “utils.js” as shown below:

utils.js

Some important lines of code to pay attention to here are lines 19–24:

In this code block, we list each smart contract function we will need to call in our front end application — they are divided between “view methods” (methods that are read-only and do not change the contract state) and “change methods” (functions that initiate state change).

Of course as we expand our Rust code and build out our project, we can add to this function list, and then in React we can incorporate the corresponding functionality for our front end as well.

Just make sure you “upgrade” the contract out on Testnet (like we learned how to do above) if you make any further changes in Rust!

Writing the React components

Before we work on “App.js” and some component files for React, let’s first add some generic files we will need to our “src” directory — “index.js”, “index.html” and “global.css”:

index.js

index.html

global.css

With our basic files out of the way, we will now concentrate on our App.js file, the main entry file to our Dapp. In our “src” folder, add the following:

App.js

Once we have our App.js file completed, we can then add the final two files inside a new “components” sub-directory. First create a new folder “components” inside the “src” directory:

Inside our new “components” folder we will create the files, “CreateEvents.js” and “ListEvents.js” :

CreateEvents.js

ListEvents.js

If we refer back to our Rust code and the specific function calls and variables, we can identify in the above files the specific items we wrote in Rust:

Rust functions: add_event, add_vote, list_events

Rust variables: estimated_budget, total_votes, title, id, description

With all of these files created and added to the appropriate directories, our final file structure(s) should be:

Some thoughts on the React portion of this project

You will notice that this React example, based on an existing Near tutorial template you may have already seen out there, is a very bare minimum in terms of functionality and state management.

For instance, we rely solely on the “UseState” and “UseEffect” hooks for updating our contract state on the blockchain, with no server-side rendering (or more advanced routing) of our pages before we get to displaying them in the browser window.

As we will learn, this is definitely not ideal for production, because of some latency in refreshing this updated state information on the client side.

For the purposes of this tutorial, we assume that we may need to “refresh” the browser window from time to time to display updated contract state. Since we are only launching this locally on our machine, we are fine with this, but if it were a real production deployment, we would need to implement more advanced React — using Context, Router, and/or Redux, or some other “store” for state management (ex: Next.js with SSR) to pre-render the pages in a timely manner automatically.

We would also need to deploy to Digital Ocean, Vultr, Heroku, Vercel or some other hosting service that will handle advanced Node applications server-side.

However, this is beyond the scope of this tutorial. It is an excellent topic for another Near article in the future — specifically expanding a Near project with Next.js on the front end and deploying server-side to the cloud! I look forward to contributions from other developers in this area.

(Finally!) Launching our React Dapp on our local machine with Parcel

So let’s make sure we are in our root directory…

And then “npm start” or “yarn start”:

We should see the following in the VSCode Terminal:

NOTE: make sure you are completely “signed out” of any version of this Dapp you may have loaded previously. There is a bug in the Near wallet interface that will “force” a transaction approval repeatedly on a loop if the smart contract code changes or is replaced. The exact cause of this issue is currently being diagnosed.

If we confirm in the browser (Chrome or Firefox are recommended) on localhost:1234 you will see the “Sign-in” page for our Dapp.

Go ahead and sign in with the Near Wallet as usual (approve the “transaction” for signing into Near Testnet with the “localhost” app):

We proceed to the “Events” screen: hit the “Add An Event” button to fill in the drop-down toggle React form:

Fill in the event form with the Title, suggested Budget and Description of the event as shown and hit “Submit”:

Once we submit an event, there is a brief “reset” period (latency as described above) and you may need to refresh the browser before we will see the updated Events list on the home page:

To add a “vote” to a project, you can hit the “Vote” button, refresh the page again, and an updated vote count will appear for the project you voted on.

Some closing thoughts (and room for improvement)

So we have implemented a very basic end-to-end solution to get started on the Near Protocol, and I hope that this entire tutorial has been as enjoyable for you as it has for me.

One thing I have been thinking about is incorporating Rust-based checks and balances in our contract logic, and although this could be (yet another) article altogether, we might include the following in any upgrade:

  1. Allow-listing for addresses: we could implement checks in Rust to assemble a list of “approved” users if the contract owner requires some restriction of who can add to the Events list on the platform.
  2. Voter-checking: similar to the “allow-list”, this would enforce a logic in Rust of “not-yet-voted” and “already-voted” to make sure a voter can’t vote more than once, or that “owners” can’t vote on their own events.
  3. Native token contributions to projects on the Event platform: if a native token were to be minted for the platform with initial supply, and allowances were made for registered users, we can log their event donations accordingly. Token balances for project contributions can then be included in our Event data. This could all be done in Rust using the standard FT Token Contract standard for Near.
  4. Finally as I described above — a redesign of the React portion to incorporate something like Next.js, with its emphasis on Router, “GetStaticProps”, and some server-side rendering (SSR) in general would definitely make our app more responsive and ready for a real production deployment. For this, a multi-page setup would also make sense, since we could use “slugs []” in Next.js to generate a separate, unique page per Event.

This concludes the third and final part of our tutorial — thank you for completing the project. I encourage you to use this basic template as a foundation for your Near development journey, adapting it to your needs as you see fit for a more robust solution in the future.

Thanks again for reading, and see you next time!. — Panasthetik.

Resources:

Join Coinmonks Telegram Channel and Youtube Channel learn about crypto trading and investing

Also, Read

--

--

Panasthetik
Coinmonks

Web3 Developer and Researcher — Blockchain, Generative Art, Decentralized Identity.