The Complete Guide To Full Stack Bsv Development with sCrypt.
Tags: webdev, blockchain, bsv, scrypt
Published: 2024-04-02 03:41:24

<h1>Introducing sCrypt</h1>

<p>sCrypt is an embedded domain specific language (eDSL)
based on TypeScript for writing Smartcontract on
Bitcoin. Scrypt uses and enables us to write an eDSL that abstract away many of the complex low level operations you’d typically need to do if you are building without it, making it easier and appreciable to write Smartcontract on the Bitcoin SV network.</p>
 
<p>In this guide to full stack BSV development with sCrypt, we’ll walk through the process of writing smartcontract, deploying it to the blockchain, calling it and also integrating a front-end. This will provide a basic introduction to the sCrypt programming language and how it’s used to build decentralized applications on the BSV blockchain.</p>

<p>By the end of this guide, you’ll have a better understanding of fullstack development on Bitcoin SV using sCrypt.</p>

   The tools we will be using for this project include;

<li> [sCrypt language](https://scrypt.io/): a typescript base framework for writing smartcontract on Bitcoin SV with a high-level abstraction. It’s a static –typed language which provides a safety and easy to use.</li>
<li> [sCrypt library](https://github.com/sCrypt-Inc/scrypt-ord): a comprehensive library for client-side seamless interaction with the Bsv blockchain </li>
<li> [sCrypt Cli](https://scrypt.io/): to easily create and compile sCrypt into bitcoin script and provides a best-practice scaffolding to help developers follow the recommended standards and conventions for writing sCrypt code.</li>
<li> React: the client-side framework.</li>
<li> [Yours wallet](https://chrome.google.com/webstore/detail/yours-wallet/mlbnicldlpdimbjdcncnklfempedeipj):Yours Wallet is an open-source, non-custodial Bitcoin SV web3 wallet designed for ease of use and everyday transactions. Yours offers a straightforward and secure way to receive, send, and manage your digital assets.</li>

Make sure all prerequisite are install;

1. Install `Node.js` (require version `>=16`) and `NPM` on your machine by following the instructions over [here](https://nodejs.org/en/download)

2. Install [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)

3. Next, install the sCrypt Cli: follow this command to install the sCrypt Cli globally to your machine

                     npm install -g scrypt-cli

<h2>Creating a new project</h2>
Run the following commands to create a new project:

                     npx scrypt-cli project helloworld
                     cd helloworld

Install all necessary dependencies on your project:

                     npm install

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:

```javascript
         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')
    }
}
```

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.

<h2>Compile Contract</h2>

1. Run following command to compile the `Helloworld` contract:

                         npx scrypt-cli compile

This command will generate a contract artifact file at `artifacts\helloworld.json.`

2. Then call the loadArtifact() function in the code:

                        await Helloworld.loadArtifact()

<h2>Compile using the watch option</h2>

                        npx scrypt-cli compile --watch

The watch option in the provided command appears to facilitate continuous monitoring of sCrypt level errors during the compilation process. When invoked with the specified command, it utilizes the "npx scrypt-cli compile --watch" syntax to initiate a watch mode. This mode likely allows users to observe real-time updates and notifications regarding any errors specific to sCrypt, which are distinct from TypeScript errors.

![deescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vscf8zk8q2gpukw3ve75.gif)
<h2>Contract Deployment & Call</h2>

Before we deploy the contract, you need to generate a Bitcoin key.

                        npm run genprivkey

then follow the [instruction to](https://docs.scrypt.io/how-to-deploy-and-call-a-contract/faucet) fund the key.After getting your Bitcoin key and funding, you can now proceed into deploying and calling you contract

1. To deploy a smart contract, simply call its deploy method.

2. To call a smart contract, call one of its public method.

Overwrite `deploy.ts` in the root of the project with the following code to deploy and call the `Helloworld` contract:

```javascript
          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)

})()
```
Run the following command:

                  npx ts-node deploy.ts
You will see some output like:

![description9](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/guj99bzuw1x80e65bk69.png)

You can view the [deployment transaction](https://test.whatsonchain.com/tx/b10744292358eda2cfae3baae5cd486e30136b086011f7953aed9098f62f4245) using the WhatsOnChain blockchain explorer:

![description10](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q4dx7ve0vuwdbl6jiq2w.png)
You can also view the [calling transaction](https://test.whatsonchain.com/tx/f28175616b6dd0ebe2aad41505aabb5bf2864e2e6d1157168183f51b6194d3e6)

![description11](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ghxxxwv2bcr8mgo08dn4.png)
Congrats! You have deployed and called your first Bitcoin smart contract, we will proceed on how to integrate a frontend to our smartcontract.

<h1>Integrate With a Frontend</h1>

This section, you will learn how to integrate your smart contract to a Frontend, so that users can interact with it.
<h3>Step 1</h3>
Create your frontend project.
**React**
Run the following command to create a React named helloworld.
 
               npx create-react-app helloworld --template typescript
<h3>Step 2</h3>
Run the    `init`    command of the[ CLI](https://docs.scrypt.io/installation#the-scrypt-cli-tool) to add   `sCrypt`   support in your project.

                       cd helloworld
                       npx scrypt-cli init
This installs all the dependencies and configures the contract development environment.
<h2>Load Contract</h2>
Before interacting with a smart contract at the front end, we need to load the contract class in two steps.

We'll take a look at how to generate the artifact by ourselves first.
<h2>1. Compile Contract</h2>
Before you start, you need to get the contract source files, as a frontend developer. we will be using the Helloworld contract we wrote in the beginning of this guide as our contract src file,so copy and paste helloworld.ts into the src/contracts directory.

![description11](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/emjegqydxm2n9tfqeukz.png)
Run the following command to compile the contract.

                 npx scrypt-cli compile

![description12](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wo71cfjisp8g6928poy8.png)
After the compilation, you will get an JSON artifact file at `artifacts/helloworld.json.`


![description13](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yzqnp8lfcshx4mhqwovg.png)
<h2>2. Load Artifact</h2>
Now with the contract artifact file, you directly load it in the `index.tsx` file.

```typescript
          import { Helloworld } from './contracts/helloworld';
          import artifact from '../artifacts/helloworld.json';
          Helloworld.loadArtifact(artifact);
```
Now you can create an instance from the contract class as before.

```javascript
           const message = toByteString('hello world', true)
           const instance = new Helloworld(sha256(message))
```

<h1>Integrate Wallet</h1>
we will integrate [Panda](https://chromewebstore.google.com/detail/yours-wallet/mlbnicldlpdimbjdcncnklfempedeipj?pli=1), a browser extension wallet similar to [MetaMask,](https://metamask.io/) into the project
To request access to the wallet, you can use its `requestAuth` method.


```javascript
              const provider = new DefaultProvider({
              network: bsv.Networks.testnet
              });

              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();
              // ...
```

Now you can connect the wallet to the contract instance as before.

```javascript
             await instance.connect(signer);
```
Afterwards, you can interact with the contract from the front end by [calling its method](https://docs.scrypt.io/how-to-deploy-and-call-a-contract/#contract-call) 
<h1>Conclusion</h1>
FullStack  BSV development with sCrypt is rapidly growing. It offers developers the ability to create decentralized applications that are powerful, secure and scalable. With sCrypt, developers can build a powerful smart contract that runs on the BSV blockchain, providing a fast, secure, and decentralized platform for applications. sCrypt makes it easier for developers to create these applications, with its high-level abstractions and static-typing system.
Access the full comprehensive sCrypt documentation [here](https://docs.scrypt.io/)