Quickstart - Build a dApp with Botanix (Solidity, Hardhat)

INFORMATION

This page is based on the quickstart guide of Arbitrum as the building process is 100% the same

PUBLIC PREVIEW DOCUMENT

This document is currently in public preview and may change significantly as feedback is captured from readers like you. Join the Botanix Discord to share your feedback.

This quickstart is for web developers who want to start building decentralized applications (dApps) using Botanix. It makes no assumptions about your prior experience with the Ethereum Virtual Machine (EVM), Botanix, or Solidity. Familiarity with Javascript and yarn is expected. If you're new to the EVM, consider studying the Ethereum documentation before proceeding.

What we are building

We're going to build a digital cupcake vending machine using Solidity smart contracts. Our vending machine will follow two rules:

  1. The vending machine will distribute a cupcake to anyone who hasn't recently received one.

  2. The vending machine's rules can't be changed by anyone.

To run the following example, click on Run Pen, enter your name and click Cupcake Please!

Note that although this vending machine appears to follow the rules, it doesn't follow them as much as we'd like. The vending machine's business logic and data are hosted by a centralized service provider. We're trusting that this service provider isn't malicious, but:

  1. Our centralized service provider can deny access to particular users.

  2. A malicious actor can change the rules of the vending machine at any time, for example, to give their friends extra cupcakes.

Centralized third-party intermediaries represent a single point of failure that malicious actors may become incentivized to exploit. To mitigate this type of risk, we can decentralize our vending machine's business logic and data, rendering this type of exploitation infeasible.

This is one of Botanix's core value propositions to you, dear developer. Botanix makes it easy for you to deploy your vending machines to Bitcoin's permissionless, trustless, decentralized network of nodes while keeping costs low for you and your users.

Let's implement the "web3" version of the above vending machine using Botanix.

Prerequisites

  • VS Code: The IDE we'll use to build our vending machine. See code.visualstudio.com to install.

  • Metamask: The wallet we'll use to interact with our vending machine. See metamask.io to install.

  • Yarn: The package manager we'll use to install our dependencies. See yarnpkg.com to install.

We'll address remaining dependencies as we go.

Bitcoin, EVM and Botanix in a nutshell

Bitcoin

Bitcoin is a decentralized digital currency, created in 2009 by an unknown person or group of people using the pseudonym Satoshi Nakamoto. It operates on a peer-to-peer network, allowing users to send and receive payments directly without the need for intermediaries like banks or governments. Bitcoin transactions are verified by network nodes through cryptography and recorded on a public ledger called a blockchain. Unlike traditional currencies, Bitcoin has a limited supply, capped at 21 million coins, making it deflationary by nature. Its decentralized nature and blockchain technology offer security, transparency, and the potential to revolutionize the financial industry.

EVM

The Ethereum Virtual Machine or EVM is a piece of software that executes smart contracts and computes the state of the Botanix network after each new block is added to the chain.

The EVM sits on top of Botanix's hardware and node network layer. Its main purpose is to compute the network's state and to run and compile various types of smart contract code into a readable format called 'Bytecode.'

This makes it possible for smart contracts deployed on EVM-compatible chains like Polygon, Avalanche or Botanix to be recognized by the nodes, and allows developers to port their dapps or tokens over from Ethereum to other EVM-compatible chains with relative ease.

Solidity smart contracts benefit from the Lindy effect and experience higher levels of trust and familiarity. From a programming language perspective, Solidity has a strong footing in the crypto world and Botanix has therefore opted to leverage the tools that already exist in the EVM ecosystem.

For more information, visit

Botanix

Botanix Labs wants to build infrastructure to transform Bitcoin from the best money ever made to the programmable layer that will serve as the basis for the future of finance. Our approach is to build the first fully decentralized EVM-equivalent Layer 2 on Bitcoin, where the ease and versatility of EVM meets the decentralization and security of Bitcoin.

Leveraging Bitcoin's Proof-of-Work (PoW) as a Layer 1 for base settlement and decentralization, Botanix will use a Proof-of-Stake consensus model, where the stakes (represented by bitcoin) are securely stored on the Spiderchain, a distributed network of decentralized multisigs safeguarded by a randomized subset of participants. You will be able to stake your bitcoin on Bitcoin.


Let's review our vending machine's Javascript implementation, then convert it into a Solidity smart contract, then deploy it to Botanix.

We'll ask your smart contract for cupcakes using the vending machines on this page.

Review our Javascript vending machine

Here's our vending machine implemented as a Javascript class:

VendingMachine.js
class VendingMachine {
  // state variables = internal memory of the vending machine
  cupcakeBalances = {};
  cupcakeDistributionTimes = {};

  // Vend a cupcake to the caller
  giveCupcakeTo(userId) {
    if (this.cupcakeDistributionTimes[userId] === undefined) {
      this.cupcakeBalances[userId] = 0;
      this.cupcakeDistributionTimes[userId] = 0;
    }

    // Rule 1: The vending machine will distribute a cupcake to anyone who hasn't recently received one.
    const fiveSeconds = 5000;
    const userCanReceiveCupcake = this.cupcakeDistributionTimes[userId] + fiveSeconds <= Date.now();
    if (userCanReceiveCupcake) {
      this.cupcakeBalances[userId]++;
      this.cupcakeDistributionTimes[userId] = Date.now();
      console.log(`Enjoy your cupcake, ${userId}!`);
      return true;
    } else {
      console.error(
        'HTTP 429: Too Many Cupcakes (you must wait at least 5 seconds between cupcakes)',
      );
      return false;
    }
  }

  getCupcakeBalanceFor(userId) {
    return this.cupcakeBalances[userId];
  }
}

The VendingMachine class uses state variables and functions to implement predefined rules. This implementation is useful because it automates cupcake distribution, but there's a problem: it's hosted by a centralized server controlled by a third-party service provider.

Let's decentralize our vending machine's business logic and data by porting the above Javascript implementation into a Solidity smart contract.

Configure your project directory

Create a decentralized-cupcakes directory for your project and install hardhat using VS Code's integrated terminal:

mkdir decentralized-cupcakes
cd decentralized-cupcakes
yarn init -y
yarn add hardhat @nomicfoundation/hardhat-toolbox -D

If you get an error such as:

error @nomicfoundation/ethereumjs-evm@2.0.4: The engine "node" is incompatible with this module. Expected version ">=18". Got "16.20.2"

error Found incompatible module.

You can easily change the node version with nvm use 18

This installs two packages: hardhat lets us write, test and deploy our smart contracts, and hardhat-toolbox is a bundle of popular Hardhat plugins that we'll use later.

Next, run yarn hardhat init to configure Hardhat. Select Create a JavaScript project when prompted. Make sure you specify your decentralized-cupcakes directory as the project root when asked.

At this point, you should see the following items (among others) in your decentralized-cupcakes project directory:

ItemDescription

contracts/

Contains your smart contracts. You should see the Lock.sol contract here.

scripts/

Contains scripts that you can use to interact with your smart contracts. You should see deploy.js here.

hardhat.config.js

Contains the configuration settings for Hardhat.

Replace the contents of hardhat.config.js with the following:

hardhat.config.js
require('@nomicfoundation/hardhat-toolbox');

// NEVER record important private keys in your code - this is for demo purposes
const BOTANIX_TESTNET_PRIVATE_KEY = '';

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  solidity: '0.8.24',
  networks: {
    hardhat: {
      chainId: 31337,
    },
    botanixTestnet: {
      url: 'https://node.botanixlabs.dev',
      chainId: 3636,
      //accounts: [BOTANIX_TESTNET_PRIVATE_KEY]
    },
  },
};

Before compiling the default contracts, you will need to install additional dependencies. Run yarn hardhat compile and expect it to fail for the first time β€” follow those instructions, then run yarn hardhat compile again until it runs successfully. You should see Compiled 1 Solidity file successfully in the terminal output. You should also see a new decentralized-cupcakes/artifacts/ directory. This directory contains the compiled smart contract.

Open scripts/deploy.js and replace its contents with the following:

scripts/deploy.js
const hre = require('hardhat');

async function main() {
  const vendingMachine = await hre.ethers.deployContract('VendingMachine');
  await vendingMachine.waitForDeployment();
  console.log(`Cupcake vending machine deployed to ${vendingMachine.target}`);
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});

We'll use this to deploy our smart contract in a moment. Next, delete contracts/Lock.sol and replace it with contracts/VendingMachine.sol, the smarter alternative to our Javascript implementation:

VendingMachine.sol
pragma solidity ^0.8.24;

// Rule 2: The vending machine's rules can't be changed by anyone.
contract VendingMachine {
    // state variables = internal memory of the vending machine
    mapping(address => uint) private _cupcakeBalances;
    mapping(address => uint) private _cupcakeDistributionTimes;

    function giveCupcakeTo(address userAddress) public returns (bool) {
        // this code is unnecessary, but we're keeping it here so you can compare it to the JS implementation
        if (_cupcakeDistributionTimes[userAddress] == 0) {
            _cupcakeBalances[userAddress] = 0;
            _cupcakeDistributionTimes[userAddress] = 0;
        }

        // Rule 1: The vending machine will distribute a cupcake to anyone who hasn't recently received one.
        uint fiveSecondsFromLastDistribution = _cupcakeDistributionTimes[userAddress] + 5 seconds;
        bool userCanReceiveCupcake = fiveSecondsFromLastDistribution <= block.timestamp;
        if (userCanReceiveCupcake) {
            _cupcakeBalances[userAddress]++;
            _cupcakeDistributionTimes[userAddress] = block.timestamp;
            return true;
        } else {
            revert("HTTP 429: Too Many Cupcakes (you must wait at least 5 seconds between cupcakes)");
        }
    }

    // Getter function for the cupcake balance of a user
    function getCupcakeBalanceFor(address userAddress) public view returns (uint) {
        return _cupcakeBalances[userAddress];
    }
}

Note that this smart contract is written in Solidity, a language that compiles to EVM bytecode. This means that it can be deployed to any Ethereum-compatible blockchain.

Run yarn hardhat compile again. You should see Compiled 1 Solidity file successfully in the terminal output. You should also see a new decentralized-cupcakes/artifacts/contracts/VendingMachine.sol directory.

Set up frontend

We'll need a frontend to interact with and we have provided the code for you. You can easily make a new folder by cloning the following repository using this command:

git clone https://github.com/jeffgeudens/free-cupcakes-frontend.git

After cloning the repository, open it in a new Visual Studio window and open up the built-in terminal. To run the frontend, simple run npm install and then npm run dev. This should spin up the frontend on http://127.0.0.1:5173/ and you should see the following.

Deploy the smart contract locally

To deploy our VendingMachine smart contract locally, go back to the Visual Studio window for decentralized-cupcakes. We'll use two terminal windows and a wallet:

  1. We'll use the first terminal window to run Hardhat's built-in local Ethereum node

  2. We'll then configure a wallet so we can interact with our smart contract after it's deployed to (1)

  3. We'll then use the second terminal window to deploy our smart contract to (1)'s node

Run a local Ethereum network and node

Run yarn hardhat node from your decentralized-cupcakes directory to begin running a local Ethereum network powered by a single node. This will mimic Ethereum's behavior on your local machine by using Hardhat's built-in Hardhat Network.

You should see something along the lines of Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/ in your terminal. You should also see a number of test accounts automatically generated for you:

...
Account #0: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 (10000 ETH)
Private Key: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80
...

NEVER SHARE YOUR PRIVATE KEYS

Your Ethereum Mainnet wallet's private key is the password to all of your money. Never share it with anyone; avoid copying it to your clipboard.

Note that in the context of this quickstart, "account" refers to a public wallet address and its associated private key.

Configure Metamask

Next, open Metamask and create or import a wallet by following the displayed instructions. By default, Metamask will connect to Ethereum mainnet. Your mainnet wallet won't have a balance on your local testnet's node, but we can import one of the test accounts into Metamask to gain access to 10,000 fake ETH. Copy the private key of one of the test accounts (it works with or without the 0x prefix, so e.g. 0xac0..f80 or ac0..f80) and import it into Metamask:

You should see a balance of 10,000 ETH. Keep your private key handy; we'll use it again in a moment.

Next, go to the frontend in the browser and click Connect Wallet. This will open up a MetaMask dialog and follow the instructions.

MetaMasks wants you to swap to the Botanix Testnet, just do this and we will change it shortly.

You have now connected your new account to the Botanix Testnet. Simply click Botanix Testnet and switch it to Hardhat. You should now see something like this.

Deploy the smart contract to your local testnet

From another terminal instance, run yarn add --dev @nomicfoundation/hardhat-ethers ethers hardhat-deploy hardhat-deploy-ethers to install additional dependencies needed for contract deployment. Then run yarn hardhat run scripts/deploy.js --network localhost. This command will deploy your smart contract to the local testnet's node. You should see something like Cupcake vending machine deployed to 0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512 in your terminal. 0xe7...512 is the address of your smart contract in your local testnet.

Claim your free cupcake on Hardhat

First, copy and paste your wallet address in the first field. Then copy and paste your contract address and click Get cupcake!. You should be prompted to sign a transaction that gives you a cupcake.

What's going on here?

Our first VendingMachine is labeled WEB2 because it demonstrates traditional n-tier web application architecture:

The WEB3-LOCALHOST architecture is similar to the WEB2 architecture, with one key difference: with the WEB3 version, the business logic and data live in an (emulated for now) decentralized network of nodes instead of a centralized network of servers.

Let's take a closer look at the differences between our VendingMachine implementations:

WEB2 (the first one)

WEB3-LOCALHOST (the latest one)

WEB3-BOT-TEST (the next one)

WEB3-BOT-MAINNET (the final one)

Data (cupcakes)

Stored only in your browser. (Usually, stored by centralized infrastructure.)

Stored on your device in an emulated Ethereum network (via smart contract).

Stored on Botanix's decentralized test network (via smart contract).

Stored on Botanix's decentralized mainnet network (via smart contract).

Logic (vending)

Served from Offchain's servers. Executed by your browser.

Stored and executed by your locally emulated Ethereum network (via smart contract).

Stored and executed by Botanix's decentralized test network (via smart contract).

Stored and executed by Botanix's decentralized mainnet network (via smart contract).

Presentation (UI)

Served from Offchain's servers. Rendered and executed by your browser.

Served from Offchain's servers. Rendered and executed by your browser.

Served from Offchain's servers. Rendered and executed by your browser.

Served from Offchain's servers. Rendered and executed by your browser.

Money

Devs and users pay centralized service providers for server access using fiat currency.

← same, but only for the presentation-layer concerns (code that supports frontend UI/UX).

← same, but devs and users pay testnet $BTC to testnet validators.

← same, but instead of testnet $BTC, they use mainnet $BTC.

Next, we'll deploy our smart contract to a network of real nodes: Botanix's testnet.

Deploy the smart contract to the Botanix testnet

We were able to deploy to a local testnet for free because we were using Hardhat's built-in Ethereum network emulator. Botanix's testnet is powered by a real network of real nodes, so we'll need to pay a small transaction fee to deploy our smart contract. This fee can be paid with the Botanix testnet's token, $BTC.

First, update the hardhat.config.js file to specify the private key of the test account that you'll use to deploy your smart contract (and pay the transaction fee):

hardhat.config.js
// ...
const BOTANIX_TESTNET_PRIVATE_KEY = ''; // <- this should **not** begin with "0x"
// ...
accounts: [BOTANIX_TESTNET_PRIVATE_KEY] // <- uncomment this line
// ...

How to find your private key?

Your BOTANIX_TESTNET_PRIVATE_KEY can be found in your MetaMask. The instructions on how to do this can be found at this link: MetaMask Support.

CAUTION

Note that we're adding a private key to a config file. This is not a best practice; we're doing it here for convenience. Consider using environment variables when working on a real project.

Next, let's deposit some $BTC into the wallet corresponding to the private key we added to hardhat.config.js. At the time of this quickstart's writing, the easiest way to acquire $BTC is to:

  1. Get funds from one of our faucets - See Step 2 - Get funds from a faucet

  2. Bridge Signet BTC to Botanix - See Step 3 - Bridge in

Once you've acquired some $BTC, you'll be able to deploy your smart contract to Botanix's testnet by issuing the following command:

yarn hardhat run scripts/deploy.js --network botanixTestnet

This tells hardhat to deploy the compiled smart contract through the RPC endpoint corresponding to botanixTestnet in hardhat.config.js. You should see the following output:

Cupcake vending machine deployed to 0xff825139321bd8fB8b720BfFC5b9EfDB7d6e9AB3

Claim your free cupcake on Hardhat

Go back to the frontend in the browser and switch the network to the Botanix Testnet. Next, copy and paste your wallet address in the first field. Then copy and paste your contract address and click Get cupcake!. You should be prompted to sign a transaction that gives you a cupcake.

Congratulations! You've just deployed business logic and data to Botanix. This logic and data will be hashed and submitted within a transaction to Botanix's network, and then it will be mirrored across all nodes in the Botanix network.

Deploy the smart contract to Botanix Mainnet

Under construction

This section will come later as we launch our mainnet

Summary

In this quickstart, we:

  • Identified two business rules: 1) fair and permissionless cupcake distribution, 2) immutable business logic and data.

  • Identified a challenge: These rules are difficult to follow in a centralized application.

  • Identified a solution: Arbitrum makes it easy for developers to decentralize business logic and data (using Ethereum mainnet as a settlement layer).

  • Converted a vending machine's Javascript business logic into a Solidity smart contract.

  • Deployed our smart contract to Hardhat's local development network, and then Botanix's testnet.

If you have any questions or feedback, reach out to us on Discord - we're listening!

Last updated