DEV Community

Cover image for The Complete Guide To Full Stack Bsv Development with sCrypt.
John Godwin
John Godwin

Posted on • Updated on

The Complete Guide To Full Stack Bsv Development with sCrypt.

Introducing sCrypt

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.

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.

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

The tools we will be using for this project include;

  • sCrypt language: 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.

  • sCrypt library: a comprehensive library for client-side seamless interaction with the Bsv blockchain

  • sCrypt Cli: 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.

  • React: the client-side framework.

  • Yours wallet: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.
  • Make sure all prerequisite are install;

    1. Install Node.js (require version >=16) and NPM on your machine by following the instructions over here

    2. Install Git

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

                   npm install -g scrypt-cli
      

    Creating a new project

    Run the following commands to create a new project:

                     npx scrypt-cli project helloworld
                     cd helloworld
    
    Enter fullscreen mode Exit fullscreen mode

    Install all necessary dependencies on your project:

                     npm install
    
    Enter fullscreen mode Exit fullscreen mode

    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.

    Compile Contract

    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.

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

                      await Helloworld.loadArtifact()
      

    Compile using the watch option

                        npx scrypt-cli compile --watch
    
    Enter fullscreen mode Exit fullscreen mode

    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

    Contract Deployment & Call

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

                        npm run genprivkey
    
    Enter fullscreen mode Exit fullscreen mode

    then follow the instruction to 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:

              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:

                  npx ts-node deploy.ts
    
    Enter fullscreen mode Exit fullscreen mode

    You will see some output like:

    description9

    You can view the deployment transaction using the WhatsOnChain blockchain explorer:

    description10
    You can also view the calling transaction

    description11
    Congrats! You have deployed and called your first Bitcoin smart contract, we will proceed on how to integrate a frontend to our smartcontract.

    Integrate With a Frontend

    This section, you will learn how to integrate your smart contract to a Frontend, so that users can interact with it.

    Step 1

    Create your frontend project.
    React
    Run the following command to create a React named helloworld.

               npx create-react-app helloworld --template typescript
    
    Enter fullscreen mode Exit fullscreen mode

    Step 2

    Run the init command of the CLI to add sCrypt support in your project.

                       cd helloworld
                       npx scrypt-cli init
    
    Enter fullscreen mode Exit fullscreen mode

    This installs all the dependencies and configures the contract development environment.

    Load Contract

    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.

    1. Compile Contract

    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
    Run the following command to compile the contract.

                 npx scrypt-cli compile
    
    Enter fullscreen mode Exit fullscreen mode

    description12
    After the compilation, you will get an JSON artifact file at artifacts/helloworld.json.

    description13

    2. Load Artifact

    Now with the contract artifact file, you directly load it in the index.tsx file.

              import { Helloworld } from './contracts/helloworld';
              import artifact from '../artifacts/helloworld.json';
              Helloworld.loadArtifact(artifact);
    
    Enter fullscreen mode Exit fullscreen mode

    Now you can create an instance from the contract class as before.

               const message = toByteString('hello world', true)
               const instance = new Helloworld(sha256(message))
    
    Enter fullscreen mode Exit fullscreen mode

    Integrate Wallet

    we will integrate Panda, a browser extension wallet similar to MetaMask, into the project
    To request access to the wallet, you can use its requestAuth method.

                  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();
                  // ...
    
    Enter fullscreen mode Exit fullscreen mode

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

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

    Afterwards, you can interact with the contract from the front end by calling its method

    Conclusion

    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

    Top comments (0)