The Complete Guide To Full Stack Development On BSV Blockchain with React, sCrypt, Typescript and Panda.

bravolakmedia

Bravolakmedia

Posted on June 21, 2024

The Complete Guide To Full Stack Development On BSV Blockchain with React, sCrypt, Typescript and Panda.

PROJECT OVERVIEW.

This project utilize the following tools
Node JS: Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project!
Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This allows Node.js to be very performant.
A Node.js app runs in a single process, without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript code from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.

React: The client FrontEnd Framework

The sCrypt-CLI Tool: The sCrypt CLI tool is used to easily create, compile and publish sCrypt projects. The CLI provides best practice project scaffolding including dependencies such as sCrypt, a test framework (Mocha), code auto-formatting (Prettier), linting (ES Lint), & more.

TypeScript: We chose TypeScript as the host language because it provides an easy, familiar language (JavaScript), but with type safety, making it easy to get started writing safe smart contracts. There is no need to learn a new programming language or tools if you are already familiar with TypeScript/JavaScript. If you're new to TypeScript, check out this helpful introductory video.

Yours Wallet: Yours Wallet formerly called Panda Wallet is an open-source digital wallet for BSV and 1Sat Ordinals that enables access to decentralized applications developed on Bitcoin SV.

This guide specifically looks into how to create a Full Stack Hello World React dApp and integrate it with a smart contract Hello World as an example. It goes further to describe how to wrap your dApp with Yours Wallet integration in case you want to create a dApp with live Wallet integration. It covers basic installations, setting up of development environment, writing smart contracts with sCrypt, integration with Yours wallet, building FrontEnd with React and TypeScript, integrating smart contract with the FrontEnd and testing the dApp.

The project shows the basics of building a react dApp that integrates with contract writing with sCrypt on BSV blockchain.

BASIC INSTALLATIONS.

Install Node.js (require version >=16) and NPM on your machine by following the instructions over here.
Install Git.
NOTE
On Mac computers with Apple silicon like M1/M2, make sure Rosetta is installed. If not, it can be installed with the following command.
softwareupdate --install-rosetta --agree-to-license

  1. Install sCrypt-cli globally to your machine by running the code below: npm install -g scrypt-cli
  2. You can start playing with react since Node JS has been installed. The npm has been installed together which is a package manager for react. To learn more about react installation, check here.
  3. TypeScript comes preconfigured with Create React App, so you don't need to install it separately. In case you need to, TypeScript can be installed through three installation routes depending on how you intend to use it: an npm module, a NuGet package or a Visual Studio Extension. Since we are using Node.js, we will use npm version. If you are using MSBuild in your project, you want the NuGet package or Visual Studio extension. Run the code below: npm install -g typescript To learn more about typescript installation, check here.
  4. Create your Yours Wallet formerly called Panda wallet. You can get its chrome extension here.

SETTING UP DEVELOPMENT ENVIRONMENT

  1. Make sure you have Node.js and npm installed on your system. You can run the code below to check:
node --version
V20.11.0
npm --version
10.4.0 
Enter fullscreen mode Exit fullscreen mode

You will get output similar to the above if your Node.js and npm has been installed. Note that you need Node.Js version 16 and above. Check the installation guide links in case your Node.js is not properly installed.

CREATE YOUR BACKEND.

It is a good practice to always create a backend for a dApp project. The proper build and deployment of a backend gives better functionalities and directions on what the features of the backend that the frontend can better interact with. It can also give a clue on how to design the frontend.

  1. Create a new smart contract project “hello world” by running the following command in your visual studio code editor or on linux:

npx scrypt-cli project helloworld.

This will create the smart contract project “hello world” in HELLOWORLD directory on the local machine.
cd helloworld

This allowed us to migrate into the project directory hello world where we have the smart contract file.
npm install
This command installs the necessary dependencies we need for the smart contract in the project directory.
The resulting project will contain a sample smart contract src/contracts/helloworld.ts, along with all the scaffolding. Let's modify it to the following code:

import {
   assert,
   ByteString,
   method,
   prop,
   sha256,
   Sha256,
   SmartContract,
} from 'scrypt-ts'


export class Helloworld extends SmartContract {
   @prop()
   hash: Sha256


   constructor(hash: Sha256) {
       super(...arguments)
       this.hash = hash
   }


   @method()
   public unlock(message: ByteString) {
       assert(sha256(message) == this.hash, 'Hash does not match')
   }
}


Enter fullscreen mode Exit fullscreen mode

The Helloworld contract stores the sha256 hash of a message in the contract property hash. Only a message which hashes to the value set in this.hash will unlock the contract.
A smart contract extends SmartContract base class, it has @prop decorator which marks the helloworld contract property and @method decorator which marks the contract’s method that can be public or non-public.

  1. Compile the smart contract by running the command below:

npx scrypt-cli compile
This command will generate a contract artifact file at artifacts\helloworld.json.
In order to monitor for real time error detection you can run the following code:
npx scrypt-cli compile --watch

3:35:32 PM - Starting compilation in watch mode...


3:36:01 PM - Found 0 errors. Watching for file changes.

Enter fullscreen mode Exit fullscreen mode

The message above is a similar message you will get in your terminal, meaning that auto compilation is working.

  1. Deploy your contract: Before deploying your contract, you need to generate a Bitcoin key by running the command below:

npm run genprivkey
then follow the instructions to fund the key.
**Next, start deploying and calling the contract:

  1. To deploy a smart contract, simply call its deploy method.
  2. To call a smart contract, call one of its public method.** We need to overwrite “deploy.ts” in the root of the project with the following code to deploy and call the Helloworld contract as shown below:
import { Helloworld } from './src/contracts/helloworld'
import { getDefaultSigner } from './tests/utils/txHelper'
import { toByteString, sha256 } from 'scrypt-ts'


;(async () => {
   // set network env
   process.env.NETWORK = 'testnet'


   const message = toByteString('hello world', true)


   await Helloworld.loadArtifact()
   const instance = new Helloworld(sha256(message))


   // connect to a signer
   await instance.connect(getDefaultSigner())


   // deploy the contract and lock up 42 satoshis in it
   const deployTx = await instance.deploy(42)
   console.log('Helloworld contract deployed: ', deployTx.id)


   // contract call
   const { tx: callTx } = await instance.methods.unlock(message)
   console.log('Helloworld contract `unlock` called: ', callTx.id)
})()
Enter fullscreen mode Exit fullscreen mode

Run the following command to deploy the smart contract:
npx ts-node deploy.ts
You will see an output like this

helloworld contract successful deployed diagram
You can check this deployed contract on chain at https://test.whatsonchain.com/tx/e39961a0f783cf4da7e24c7b9e0f3490e2444ef87d7c3b96fde6e732392f6184

CREATE YOUR FRONTEND.

  1. Create a react app named hello. Note that we are creating our frontend as "hello" not "helloworld" to prevent conflict in files like package.json, node_modules and src files. Run the following code:

npx create-react-app hello --template typescript
We will do most work under the src directory.
Run the init command of the CLI to add sCrypt support in your project.
cd hello
npx scrypt-cli init
This will install all the dependencies and configures the contract development environment in our react dApp. But you need to run
git add .
git commit -m “Your commit message”
git push
To commit your changes to master or main if you are working in git remote repository before you can run “npx scrypt-cli init”
A successful initialization will give you “src/contracts/hello.ts” file in your react app as shown below:

Diagram showing successful initialization of

  1. Load and Compile the smart contract in the dApp. Copy and paste “helloworld.ts” from the backend helloworld into the “src/contracts/hello.ts” in the front end “hello” directory. We will now compile the contract by running the following command: npx scrypt-cli compile A successful compilation will generate “artifacts/hello.json” file as shown below:

Diagram showing successful generation of artifacts/hello.json file

We will now load the artifact file directly in the index.tsx file as shown below

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Helloworld } from './contracts/helloworld'; //loading artifact //file
import artifact from '../artifacts/helloworld.json';
Helloworld.loadArtifact(artifact);
const message = toByteString('hello world', true)  // creating instance //from contract class.
const instance = new Helloworld(sha256(message))


const root = ReactDOM.createRoot(
 document.getElementById("root") as HTMLElement
);
root.render(
 <React.StrictMode>
   <App />
 </React.StrictMode>
);


// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();


Enter fullscreen mode Exit fullscreen mode

Just like that we are done integrating our smart contract with the front end. We can now go further to customize the React dApp e.g by styling.

INTEGRATE YOURS WALLET

Follow this link to integrate Yours Wallet formerly known as Panda Wallet.
Request access to the wallet, by using the requestAuth method below:

const signer = new PandaSigner(provider);

// request authentication
const { isAuthenticated, error } = await signer.requestAuth();
if (!isAuthenticated) {
 // something went wrong, throw an Error with `error` message
 throw new Error(error);
}


// authenticated
// you can show user's default address
const userAddress = await signer.getDefaultAddress();
// ...
Enter fullscreen mode Exit fullscreen mode

Now you can connect the wallet to the contract instance as before using the code below:

await instance.connect(signer);
Enter fullscreen mode Exit fullscreen mode

The sample code use in this write up can be found in the repository and the whole write up is a basic guide for creating a complete dApp on BSV blockchain using sCrypt-cli.

REFERENCES.

  1. Official sCrypt Documentation https://docs.scrypt.io.
  2. Introduction To Node.JS https://nodejs.org/en/learn/getting-started/introduction-to-nodejs

  3. sCrypt CLI Tools For Creating and Managing Scrypt Projects https://github.com/sCrypt-Inc/scrypt-cli

  4. TypeScript https://www.typescriptlang.org/

  5. Getting Started Installing Git, https://git-scm.com/book/en/v2/Getting-Started-Installing-Git

💖 💪 🙅 🚩
bravolakmedia
Bravolakmedia

Posted on June 21, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related