Skip to content

anataliocs/polkavm-hardhat-examples

Repository files navigation

Polkadot Blockchain Academy Banner Img

✨ dApp Track Starter Project ✨

PBA Cohort 7 Bali

Student: Chris Anatalio

linkedin chris anatalio twitter chris anatalio

Ex ConsenSys, Ex Stellar Development Foundation, Author LinkedIn Learning/Pluralsight

Open in GitHub Codespaces


Tech Stack

rust,solidity,ts,wasm

Hardhat CodeQL

License: MIT WebStorm Polkadot Ethereum hardhat-badge

πŸ“ˆ Uniswap V2 Demoβ€”Polkadot Hub Smart Contract

Solidity Smart Contracts now on ✨ Polkadot Network

πŸ’» Create your own contract


Uniswap V2 Solidity Smart Contracts with PolkVM on the Polkadot Network

Demo dapp showcasing Uniswap V2 on Polkadot using PolkVM and @parity/hardhat-polkadot with Solidity smart contracts and hardhat. Leverage the power of the Polkadot ecosystem to build a decentralized exchange with PolkVM and standard tools like Hardhat and TypeScript with custom hardhat-polkadot plugins.

Contracts: uniswap/contracts

First Step: Choose Devcontainers or Local Setup

Β πŸ’–πŸ’–πŸ’– POLKVM === TRUE πŸ’–πŸ’–πŸ’–

Polkadot Smart Contracts


Get Started with Devcontainers for Polkadot

Read the GitHub Docs

  • Option 1: Create GitHub Codespace from the GitHub UI
  • Option 2: Use a template string: https://codespaces.new/OWNER/REPO-NAME
    • Replace OWNER with your GitHub name
    • Replace REPO-NAME with whatever you named this repo

Create an Open in GitHub Codespaces Badge:

  • Option 3: Replace the fields as indicated
[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/OWNER/REPO-NAME)

Local Environment Setup

Guide built for macOS

Setup Polkadot SDK Dependencies

Instructions available here: Local environment setup For support, visit the Discord

Setup

Install protobuf

brew update && brew install protobuf

Install SSL

brew install openssl

Install Rustup(Standard installation)

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Update terminal Example command for zsh users

if [ -r ~/.zshrc ]; then echo -e '. "$HOME/.cargo/env"' >> ~/.zshrc; \
  else echo -e '. "$HOME/.cargo/env"' >> ~/.zprofile; fi

Update Rust and set target

rustup default stable &&
 rustup update &&
 rustup target add wasm32-unknown-unknown &&
 rustup component add rust-src &&
 rustup show

Verify rust install

rustup show &&
 rustc --version &&
 cargo --version

Install cmake

brew install cmake

Download Server Runtimes (Optional)

  • You can also use Docker
  • This approach is experimental

Run Substrate Server

  • Spin up Substrate node
  • Start up eth adapter
pnpx hardhat node

Error Output:

starting server ...

  ------------------------------------------
  ⚑️ running in production (standard) mode ⚑️
  ------------------------------------------

ErrorEvent {
  type: 'error',
  defaultPrevented: false,
  cancelable: false,
  timeStamp: 1679.599333
}

Fork live Testnet

pnpx hardhat node --fork https://testnet-passet-hub.polkadot.io
\ --adapter-binary-path /Users/chrisanatalio/IdeaProjects/polkavm-hardhat-examples/uniswap/bin/eth-rpc

Or use the plugin native way to spin up a node

pnpx hardhat node-polkadot

Download Polkadot SDK GitHub Release binary

  • Westend Testnet Relay Chain Runtime
  • Saves wasm as filename: westend_runtime-v1019002.compact.compressed.wasm
  • Prints filename to console and adds to your .env file as SUBSTRATE_SERVER_FILE_NAME
curl --proto '=https' --tlsv1.2 -sSfLO \
 https://github.com/paritytech/polkadot-sdk/releases/download/polkadot-stable2506/westend_runtime-v1019002.compact.compressed.wasm -w "%{filename_effective}" \
 | xargs -0 -I {} echo "SUBSTRATE_SERVER_FILE_NAME={}" |tee .env

//TODO pull keys from https://github.com/paritytech/hardhat-polkadot/blob/main/packages/hardhat-polkadot-node/src/constants.ts#L22


148661419-419ad5b3-1b9f-480a-b723-3f292616730c

Section 2β€”Hardhat and Solidity


Verify your workspace is configured correctly:

rustc --version && cargo version && nvm current

Node/npm setup

Setup steps:

  1. Setup Project
  2. Compile and Test your Contract
  3. Deploy contract and setup env
  4. Interact with a deployed contract

Next Step: Setup project


STEP 1: Setup

Install dependencies

pnpm install

Strict Mode(Catch potential errors at build time) This is optional, but recommended.

pnpm install --strict-peer-dependencies --no-optional && pnpm update

Next Step: Build/Test Contract


STEP 2: Compile & Test Contract

  • Compile your contract
  • Test your contract

Compile your contract(With type checking):

pnpx hardhat compile --typecheck

Run your tests:

pnpx hardhat test --network localNode

Verify:

Next Step: Deploy Contract


STEP 3: Deploy Contract and Update Env

pnpx hardhat vars set PRIVATE_KEY "INSERT_PRIVATE_KEY"

Deploy using Ignition Modules:


STEP 4: Interact with Deployed Contracts

  • Use the and from .env
  • Sets the output package to
  • Sets Deployed contract address to

We have included packages in our include statement in tsconfig.json

Verify your Deployed Contract:

Review

  • Your .env file with everything you need to build a dapp around your Contract

Invoking your Deployed Contract

Now let's invoke the deployed contract.

  • The id of the deployed contract, our default source account and the public key are stored in our .env file
  • Which will invoke the mint() function passing in the Owner public key as the recipient

Execute this command:

Output type(json):

Invoking your Contract with the PAPI JavaScript SDK

We showed you how to use the PAPI CLI to invoke your contract, now let's do it with the JavaScript SDK

Parameters:

  • contract_id (optional)β€”Deployed contract ID
  • SOURCE_KEYPAIR (optional)

Execute:


148661419-419ad5b3-1b9f-480a-b723-3f292616730c

Section 3--Javascript Clients and APIs


dApp Backend - Micro Indexer

We will now create a backend to provide data for your UI. We will take a flexible approach to building a dapp backend, giving your working examples of various ways to supply data to your client front-end.

Indexers extract and transform raw blockchain data and present the data in a format that is more easily consumable by a front-end client.

Indexers are generally provided as third-party services. The following nest.js service is a micro-indexer primarily built to consume contract events emitted by your contract and presents them to your front-end client in a streaming event-driven format.

Available Formats:

Mock Data vs Testnet:

  • Mock data streams allow you to quickly iterate on your front-end UI without having to stage data on-chain. This data will be generated according to the schema to ensure it works with live testnet data.
  • Testnet data streams will include the ability to invoke the mint() function to generate testnet data

Run locally


Choose a Testnet RPC Provider

Start locally:

pnpm start:dev

Backend:

  • Using SSE
  • Moves complex code from front-end to backend
  • Push JSON, HTML code, or React components or fragments to your front-end client

Front-end β†’ Single HTML file

  • Check out mock-sse.html or mock-sse-by-contractid.html for a working example
  • Requires running micro-indexer on port 3000

Backend SSE Example

  • This example uses RxJS to generate a stream of MessageEvents pushed to a front-end client
  • Example stream URL:
  @Sse('sse/:contractId')
  sse_by_contract_id(
    @Param('contractId') contractId: string,
  ): Observable<MessageEvent> {
    return interval(1000).pipe(
      map(
        this.stellarMockEventService.transformMessageEventWithContract(
          contractId,
        ),
      ),
    );
  }

Customizing your contract

Workflow

Update the contract to make it truly yours.

  1. Update the contract
  2. Re-build the contract
  3. Upgrade the deployed contract
  4. Re-generate contract bindings

Updating the Contract

Open up the contract uniswap/contracts/src/contract. Modify

Execute this command:

TODO

Opinionated Front-end Client Creation

The method of UI creation is a template that is actively maintained, 500+ deployments, and full test suite + static analysis with app generation test. 218 GitHub stars.


Related

Reference Links

//TODO Organize

Chainspec: https://raw.githubusercontent.com/paritytech/chainspecs/refs/heads/main/westend/parachain/asset-hub-next/chainspec.json


πŸ‘€ Want to learn more?

Feel free to check the documentation or jump into the Discord server.


148661419-419ad5b3-1b9f-480a-b723-3f292616730c

Built with love πŸ’—in the Polkadot Ecosystem

About

✨ Uniswap V2 Demo - Polkadot Hub Smart Contract Example ✨ polkavm === true. πŸ’–πŸ’–πŸ’–

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 7