OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

Connect a React app to the NEAR Blockchain

Melvin Kosisochukwu
July 4th, 2022 · 5 min read

You must’ve heard of blockchain, decentralized applications, web3, and the hype surrounding them. As a software developer, you’re expected to be flexible, evolve with the time, and learn new and exciting techs. Web3 development involves building applications on a distributed blockchain or decentralized network over single servers; an example of this network is the NEAR blockchain. For additional information on web3, you can check out this article.

NEAR is a development platform built on a new layer-1, Proof-of-stake blockchain. You can interact with the NEAR blockchains with a set of instructions/programs called smart contracts; smart contracts for NEAR blockchain are written in AssemblyScript or Rust; for additional information on writing smart contracts on the NEAR blockchain, you can look over the official documentation here.

For this article, we will focus on how to connect to the NEAR blockchain and make smart contract calls. We will be working with a dice game smart contract deployed on the blockchain. You can find additional information on the smart contract here. To continue with this article, you need knowledge of Reactjs and Javascript; You will also need access to the smart-contract address deployed on the near blockchain: dev-1641682453576-30872819216475 and a NEAR wallet. The NEAR wallet is an in-browser wallet for creating and interacting with NEAR accounts. The wallet exists on the web and stores account keys in your browser’s localStorage. You can find information on creating a wallet on the NEAR blockchain here.

Near tokens are the native cryptocurrency used on the NEAR blockchain, with units in yocto. 1 NEAR token is equivalent to 10^24 yocto.

Project Resources

We will work with a Smart Contract Address/Name dev-1641682453576-30872819216475. The game rules are very simple:

  • Users are allowed to create a new game with a 0.5 NEAR token attached as the game fee; a user creating a game is automatically entered into the game.
  • Other users can join a created game with 0.5 NEAR attached as the game fee.
  • Game fees are added to a price pool for game-winner(s).
  • Each game has a 30 minutes countdown from when it starts.
  • Players in a game can roll the dice once; When a player rolls the first dice, the game countdown starts.
  • Once a game ends, the player(s) with the highest dice count will claim the winnings from the game.

Getting Started

The first order will be to create a React Application and set up the configuration file for interacting with the NEAR blockchain; you can find the repository with the complete project here. The NEAR blockchain has different development environments, the most popular two being the testnet and the mainnet; for this article, we will be working with the testnet. The testnet is a development network that mocks the behaviors of the main network; this allows you to test your smart contract functions and verify that everything works correctly without incurring any cost.

Once you have successfully cloned the repository navigate to src/config.js file:

1const CONTRACT_NAME = process.env.CONTRACT_NAME || "dev-1641682453576-30872819216475";
2
3export default function getConfig(env) {
4 switch (env) {
5 case "production":
6 case "development":
7 case "testnet":
8 return {
9 networkId: "testnet",
10 nodeUrl: "https://rpc.testnet.near.org",
11 contractName: CONTRACT_NAME,
12 walletUrl: "https://wallet.testnet.near.org",
13 helperUrl: "https://helper.testnet.near.org",
14 };
15 default:
16 throw Error(`Unconfigured environment '${env}'. Can be configured in src/config.js.`);
17 }
18}

We have the smart contract address on line 1 in the code block above. This file holds the configuration file for the environment the smart contract is deployed on (testnet). The getConfig function accepts an environment and returns the configuration that matches that environment. You can find the configuration for other environments in the code repository. The next step will be to hook up the configuration to your React application — see src/index.js.

1import React from "react";
2import ReactDOM from "react-dom";
3import App from "./App";
4import getConfig from "./config.js";
5import * as nearAPI from "near-api-js";
6import "./index.css";
7
8// Initializing contract
9async function initContract() {
10 const nearConfig = getConfig(process.env.NODE_ENV || "testnet");
11
12 // Initializing connection to the NEAR TestNet
13 const near = await nearAPI.connect({
14 deps: {
15 keyStore: new nearAPI.keyStores.BrowserLocalStorageKeyStore(),
16 },
17 ...nearConfig,
18 });
19
20 // Needed to access wallet
21 const walletConnection = new nearAPI.WalletConnection(near);
22
23 // Load in account data
24 let currentUser;
25 if (walletConnection.getAccountId()) {
26 currentUser = {
27 accountId: walletConnection.getAccountId(),
28 balance: (await walletConnection.account().state()).amount,
29 };
30 }
31
32 // Initializing our contract APIs by contract name and configuration
33 const contract = await new nearAPI.Contract(walletConnection.account(), nearConfig.contractName, {
34 // View methods are read-only – they don't modify the state, but usually return some value
35 viewMethods: ["getWinners", "getGameDetails", "getPlayersDetails", "getProfileDetails", "getActiveGames", "getCreatedGames", "getCompletedGames"],
36 // Change methods can modify the state, but you don't receive the returned value when called
37 changeMethods: ["createNewGame", "joinGame", "rollDice", "claimWinnings"],
38 // Sender is the account ID to initialize transactions.
39 // getAccountId() will return empty string if user is still unauthorized
40 sender: walletConnection.getAccountId(),
41 });
42
43 return { contract, currentUser, nearConfig, walletConnection };
44}
45
46window.nearInitPromise = initContract().then(({ contract, currentUser, nearConfig, walletConnection }) => {
47 ReactDOM.render(
48 <React.StrictMode>
49 <App contract={contract} currentUser={currentUser} nearConfig={nearConfig} wallet={walletConnection} />
50 </React.StrictMode>,
51 document.getElementById("root")
52 );
53});

On line 9, we have the initContract function. On line 13, we assign the connection configuration to the near variable and follow that up by calling the WalletConnection method on the near-js-api library accepts the connection configuration as params. The WalletConnection method allows connection to the near wallet; this allows you to sign/authenticate transactions/requests.

The next step will be to set up the contract connection; this is accomplished on lines 33 through 41 by calling the Contract method from the near-js-api. It accepts three arguments: the wallet account, smart contract address, and contract methods.

Wallet Connection

The NEAR wallet is a browser-based wallet. You will be redirected to the website to authenticate your wallet/account - see src/components/Navbar/Navbar.jsx.

1...
2const handleUser = (e) => {
3 if (currentUser && e.target.textContent === "Sign Out") {
4 (function signOut() {
5 wallet.signOut();
6 window.location.replace(
7 window.location.origin + window.location.pathname
8 );
9 })();
10 } else if (!currentUser && e.target.textContent === "Login") {
11 (function signIn() {
12 wallet.requestSignIn(nearConfig.contractName, "NEAR Block Dice");
13 })();
14 }
15 };
16...

On line 12, the wallet.requestSignIn function accepts two arguments: the contract address and the application name. The wallet.requestSignIn function will trigger a wallet connection request, which, once approved, will redirect back our application from the NEAR browser wallet;

Wallet connection request

The wallet connection can be revoked by calling wallet.signOut() function.

Open Source Session Replay

OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.

replayer.png

Start enjoying your debugging experience - start using OpenReplay for free.

Smart Contract Interaction

NEAR smart contracts have view and change methods.

  • View Methods are smart contract methods that do not mutate the contract storage; they are used to read data stored on the smart contract storage.
  • Change Methods are the opposite of the View methods in the sense that they alter smart contract storage. Change methods must be signed by a wallet to execute successfully; Signing contract calls usually requires gas fees. Gas fees are the number of NEAR tokens needed to perform a transaction on the NEAR Blockchain.

On lines 35 and 37, we can see the contract methods defined. You can find additional information on the smart contract method interface here.

We have successfully connected to the NEAR blockchain and the smart contract provided. The next action order will be to make smart contract calls using the defined contract methods.

createNewGame

This change function allows you to create a new game with a 0.5 NEAR token fee - see src/pages/home/index.jsx.

1...
2const txFee = Big(0.5)
3 .times(10 ** 24)
4 .toFixed()
5
6const GAS = Big(3)
7 .times(10 ** 13)
8 .toFixed()
9...
10const query = useQuery()
11const hash = query.get('transactionHashes')
12const createNewGame = async () => {
13 try {
14 await contract.createNewGame({}, GAS, txFee)
15 } catch (error) {
16 console.log(error)
17 }
18 }
19
20 useEffect(() => {
21 if (hash) {
22 txReturnArgsFromHash({ hash, accountId: currentUser.accountId }).then(
23 (res) => {
24 handleShowGameId(decodeArgs(res))
25 },
26 )
27 }
28 // eslint-disable-next-line
29 }, [])

On line 2 above, we calculate the transaction fee required to create a game(0.5 NEAR tokens), and on line 6, the gas fee required for the transaction: 30000000000000 yocto.

Create a new game

On line 12, we are making the smart contract call for creating a new game by calling the createNewGame method on the contract, which accepts three arguments: the arguments required to execute createNewGame on the smart contract, the gas fee, and the transaction fee. The createNewGame method returns the gameId of newly created games; this value can be read by querying the transaction hash appended to url query after the transaction is redirected from the NEAR wallet and decoding the value, as seen on line 22. See src/utils/near.js.

1import Big from "big.js";
2import { connect, keyStores } from "near-api-js";
3import { hexy } from "hexy";
4...
5export const txReturnArgsFromHash = async ({ hash, accountId }) => {
6 const config = {
7 keyStore: new keyStores.BrowserLocalStorageKeyStore(),
8 networkId: "testnet",
9 nodeUrl: "https://rpc.testnet.near.org",
10 walletUrl: "https://wallet.testnet.near.org",
11 helperUrl: "https://helper.testnet.near.org",
12 explorerUrl: "https://explorer.testnet.near.org",
13 };
14 const near = await connect(config);
15
16 const {
17 receipts_outcome: [
18 {
19 outcome: { status },
20 },
21 ],
22 } = await near.connection.provider.txStatus(hash, accountId);
23
24 return status.SuccessValue;
25};
26
27export const decodeArgs = (args) => {
28 const decodedArgs = Buffer.from(args, "base64");
29 let prettyArgs;
30 try {
31 prettyArgs = JSON.parse(decodedArgs.toString());
32 // prettyArgs = JSON.stringify(parsedJSONArgs, null, 2);
33 } catch {
34 prettyArgs = hexy(decodedArgs, { format: "twos" });
35 }
36
37 return prettyArgs;
38};
39...

On line 22 above, we are querying the transaction hash and destructuring the status value from the query. On line 24, we return the SuccessValue value from the transaction status in base64 format; this is the value returned when the transaction is successful. The decodeArgs function takes the SuccessValue returned and decodes the value to JSON.

joinGame

Like createNewGame, this is also a change method that allows other players to join an existing game. The joinGame method accepts the gameId as an execution argument. See src/pages/game/index.jsx.

1await contract.joinGame({ gameId: id }, GAS, txFee)

rollDice

This accepts a gameId as an argument and rolls the dice for the wallet/sender signing the contract call; the dice roll will only execute successfully if the sender is a player in the game with the gameId specified. The rollDice method returns the values of the dice rolled. See src/pages/game/index.jsx.

1await contract.rollDice({ gameId: id })

Roll A Dice

claimWinnings

The claimWinnings is a change method that allows players that won a game to redeem their share of the winning pool in their wallet. See `src/pages/game/index.jsx.

1await contract?.claimWinnings({ gameId: id })

Claim Winnings

getGameDetails

This is a view method that returns the details of the gameId passed as an argument. See src/pages/game/index.jsx.

1const [game] = await contract?.getGameDetails({ gameId: id })
2
3console.log(game)
4//output
5// {
6// createdAt: "1655411037283823319"
7// createdBy: "james1.testnet"
8// ended: "0"
9// id: "BD-4077698424"
10// players: 1
11// pool: null
12// prize: "500000000000000000000000"
13// started: "0"
14// status: 0
15// }

getPlayersDetails

This method returns every player’s details for the gameId passed as an argument. See src/pages/game/index.jsx.

1const players = await contract?.getPlayersDetails({ gameId: id })
2
3console.log(players)
4// output
5// [
6// {
7// claimedWin: 0,
8// gameId: 'BD-2085016183',
9// playerId: 'melvinmanni09.testnet',
10// roll1: 5,
11// roll2: 3,
12// timeJoined: '1655409404439293761',
13// timeRolled: '1655409445158884992',
14// },
15// ]

getProfileDetails

getProfileDetails returns the profile details for the account passed as an argument to the method. This will return an array of all games that an account joined. See src/pages/profile/.

1...
2const getProfile = async () => {
3 setGames([])
4 const profile = await contract?.getProfileDetails({
5 account: currentUser?.accountId,
6 })
7 console.log(profile) //['BD-3568281945', 'BD-4077698424', 'BD-3306428487']
8 profile.forEach(async (el) => {
9 const data = await contract?.getGameDetails({ gameId: el })
10 setGames((prev) => [data[0], ...prev])
11 })
12 }
13...

getWinners

This view method returns an array with the account id of the winners for the gameId passed in as an execution argument. See src/pages/game/index.jsx.

1const resWinners = await contract?.getWinners({ gameId: id })
2
3//resWinners will return an array of account(s) that won the game id passed

getActiveGames, getCompletedGames and getCreatedGames

These are change methods because they update games before returning the queried game state based on the game status.

Active games

Conclusion

We have covered initializing a connection to the NEAR blockchain, connecting to a wallet on the NEAR blockchain, and making smart contract calls. There is no doubt that at this point, you should be able to make smart contract calls to the NEAR blockchain. If you are interested in previewing the live project, you will find that here and the link to the smart contract repository.

newsletter

More articles from OpenReplay Blog

Mobile push notifications with Firebase

Push notifications to React Native apps in a simple way

July 4th, 2022 · 8 min read

Build beautiful UI components with NextUI

An interesting framework to let you produce better interfaces, and quickly, too

July 1st, 2022 · 4 min read
© 2022 OpenReplay Blog
Link to $https://twitter.com/OpenReplayHQLink to $https://github.com/openreplay/openreplayLink to $https://www.linkedin.com/company/18257552