From 31464fdeaec165c277b77d83cfd5a8e1a37ba83c Mon Sep 17 00:00:00 2001 From: nadeemb53 Date: Sat, 8 Feb 2025 00:08:16 +0530 Subject: [PATCH] tutorials added --- docs/index.md | 29 +- docs/other/branding-guidelines.md | 1 - docs/tokenomics/aura-token.md | 1 - docs/tokenomics/karma-token.md | 1 + docs/tokenomics/snt-token.md | 2 +- .../deploying-contracts/using-foundry.md | 210 ++++++++- .../deploying-contracts/using-hardhat.md | 287 +++--------- .../deploying-contracts/using-remix.md | 100 ++++- docs/tutorials/ethers-tutorial.md | 407 ------------------ sidebars.ts | 14 +- 10 files changed, 391 insertions(+), 661 deletions(-) delete mode 100644 docs/other/branding-guidelines.md delete mode 100644 docs/tokenomics/aura-token.md create mode 100644 docs/tokenomics/karma-token.md delete mode 100644 docs/tutorials/ethers-tutorial.md diff --git a/docs/index.md b/docs/index.md index cf8d6d4..82b5b1a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,28 +1,27 @@ --- id: index -title: Introducing Status Network +title: Welcome to Status Network slug: / sidebar_position: 1 --- -# Welcome to Status Network +# Status Network: The Gasless Layer 2 Network -Welcome to **Status Network**, the crypto social playground that reimagines your blockchain experience! Built as an **EVM-equivalent Ethereum Layer 2 rollup** on [Linea's cutting-edge ZK-EVM technology](https://docs.linea.build/architecture), Status Network offers unique features that set us apart from other platforms. -## What Makes Us Unique? +## Start Building Today -### 💰 Native ETH and DAI Yield +Ready to join the future of decentralized applications? Here's how to get started: -Enjoy sustainable and attractive yields on your **ETH** and **DAI** assets! We offer native yield generation, a distinctive feature among Layer 2 solutions, allowing you to enhance your crypto holdings effortlessly while participating in the network. +1. [Add Status Network to Your Wallet](/general-info/add-status-network) +2. [Get Testnet ETH](/tools/testnet-faucets) +3. [Bridge Assets](/general-info/bridge/bridging-testnet) +4. [Deploy Your First Contract](/tutorials/deploying-contracts/using-remix) -### 🏆 Earn $AURA Tokens +## Support & Resources -Get rewarded for your engagement in **real time**! Participate in network activities and **stake $SNT** to earn **$AURA tokens**. The more you interact—be it through transactions, staking, or community involvement—the more influence you gain within our vibrant community. Your $AURA amplifies your voice in shaping the future of the network. +Connect with our community and access the resources you need: +- Join our [Telegram Builder's Community](https://t.me/+k04A_OZbhIs1Mzc9) +- View [Network Details](/general-info/network-details) +- Browse [Contract Addresses](/general-info/contract-addresses/testnet-contracts) -### 🔒 Privacy with a Playful Twist - -Experience privacy features that are both **secure and fun**! We believe that privacy is a fundamental right and should be accessible to everyone without the complexity. Our user-friendly privacy tools make secure interactions enjoyable, breaking away from traditional notions of complicated privacy tech. - ---- - -Join Status Network and be part of a unique, privacy-focused, and rewarding crypto community where **your active participation truly shapes the future**! Let's build the crypto playground together! \ No newline at end of file +Ready to build something amazing? Start your journey with Status Network today! \ No newline at end of file diff --git a/docs/other/branding-guidelines.md b/docs/other/branding-guidelines.md deleted file mode 100644 index 4ef944f..0000000 --- a/docs/other/branding-guidelines.md +++ /dev/null @@ -1 +0,0 @@ -# Branding Guidelines diff --git a/docs/tokenomics/aura-token.md b/docs/tokenomics/aura-token.md deleted file mode 100644 index a3631d4..0000000 --- a/docs/tokenomics/aura-token.md +++ /dev/null @@ -1 +0,0 @@ -# $AURA token \ No newline at end of file diff --git a/docs/tokenomics/karma-token.md b/docs/tokenomics/karma-token.md new file mode 100644 index 0000000..f6b5ade --- /dev/null +++ b/docs/tokenomics/karma-token.md @@ -0,0 +1 @@ +# KARMA token \ No newline at end of file diff --git a/docs/tokenomics/snt-token.md b/docs/tokenomics/snt-token.md index f2a982f..fe1321e 100644 --- a/docs/tokenomics/snt-token.md +++ b/docs/tokenomics/snt-token.md @@ -1 +1 @@ -# $SNT Token \ No newline at end of file +# SNT Token \ No newline at end of file diff --git a/docs/tutorials/deploying-contracts/using-foundry.md b/docs/tutorials/deploying-contracts/using-foundry.md index f44729c..bd6fec3 100644 --- a/docs/tutorials/deploying-contracts/using-foundry.md +++ b/docs/tutorials/deploying-contracts/using-foundry.md @@ -1 +1,209 @@ -# Using Foundry \ No newline at end of file +# Using Foundry to Deploy Smart Contracts + +This tutorial will guide you through the process of deploying a smart contract on Status Network testnet using Foundry. + +## Prerequisites + +Before you begin, ensure you have the following: + +- **Foundry**: Install from the [official Foundry book](https://book.getfoundry.sh/getting-started/installation) +- **Ethereum Wallet**: A private key for Status Network testnet +- **Testnet ETH**: You'll need Status Network testnet ETH + - Get Status Network testnet ETH from our [Faucet](/tools/testnet-faucets) +- **Basic Knowledge**: Familiarity with Solidity and command line + +## What You'll Accomplish + +- Initialize a Foundry project +- Write a basic Ethereum smart contract +- Configure Foundry for Status Network testnet deployment +- Deploy your smart contract + +## Steps + +### 1. Initialize a Foundry Project + +First, create a new Foundry project: + +```bash +# Create a new project +forge init hello_status +cd hello_status + +# Create .env file for private key +touch .env +echo "PRIVATE_KEY=your_private_key_here" >> .env +``` + +### 2. Writing the Smart Contract + +Replace `src/Counter.sol` with our `HelloWorld.sol`: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.24; + +contract HelloWorld { + string public greet = "Hello, Status Network!"; + + function setGreet(string memory _greet) public { + greet = _greet; + } + + function getGreet() public view returns (string memory) { + return greet; + } +} +``` + +### 3. Configure Foundry for Status Network + +Create or update `foundry.toml`: + +```toml +[profile.default] +src = "src" +out = "out" +libs = ["lib"] +solc = "0.8.24" + +[rpc_endpoints] +status_testnet = "https://public.sepolia.rpc.status.network" +``` + +### 4. Deploy the Contract + +Create a deployment script `script/Deploy.s.sol`: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.24; + +import "forge-std/Script.sol"; +import "../src/HelloWorld.sol"; + +contract DeployScript is Script { + function run() external { + uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY"); + + vm.startBroadcast(deployerPrivateKey); + + HelloWorld hello = new HelloWorld(); + console.log("HelloWorld deployed to:", address(hello)); + + vm.stopBroadcast(); + } +} +``` + +Deploy using forge: + +```bash +# Load environment variables +source .env + +# Deploy to Status Network testnet +forge script script/Deploy.s.sol:DeployScript \ + --rpc-url https://public.sepolia.rpc.status.network \ + --broadcast \ +``` + +### 5. Interact with the Contract + +Create a script to interact with your contract `script/Interact.s.sol`: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.24; + +import "forge-std/Script.sol"; +import "../src/HelloWorld.sol"; + +contract InteractScript is Script { + function run() external { + uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY"); + address contractAddress = address(0x...); // Replace with your contract address + + vm.startBroadcast(deployerPrivateKey); + + HelloWorld hello = HelloWorld(contractAddress); + + // Read current greeting + string memory currentGreeting = hello.getGreet(); + console.log("Current greeting:", currentGreeting); + + // Update greeting + hello.setGreet("Hello from Foundry!"); + + vm.stopBroadcast(); + } +} +``` + +Run the interaction script: + +```bash +forge script script/Interact.s.sol:InteractScript \ + --rpc-url https://public.sepolia.rpc.status.network \ + --broadcast +``` + +### 6. Cast Commands for Quick Interactions + +You can also use `cast` to interact with your contract: + +```bash +# Read the greeting +cast call "getGreet()" \ + --rpc-url https://public.sepolia.rpc.status.network + +# Set a new greeting +cast send "setGreet(string)" "New greeting!" \ + --private-key $PRIVATE_KEY \ + --rpc-url https://public.sepolia.rpc.status.network +``` + +### 7. Testing + +Create a test file `test/HelloWorld.t.sol`: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.24; + +import "forge-std/Test.sol"; +import "../src/HelloWorld.sol"; + +contract HelloWorldTest is Test { + HelloWorld hello; + + function setUp() public { + hello = new HelloWorld(); + } + + function testGreeting() public { + assertEq(hello.getGreet(), "Hello, Status Network!"); + + hello.setGreet("New greeting"); + assertEq(hello.getGreet(), "New greeting"); + } +} +``` + +Run the tests: + +```bash +forge test +``` + +## Support + +If you encounter any issues: +- Join our [Telegram Community](https://t.me/+k04A_OZbhIs1Mzc9) +- Check [Network Status](https://health.status.network) +- View our [Network Details](/general-info/network-details) + +## Additional Resources + +- [Foundry Book](https://book.getfoundry.sh/) +- [Status Network Explorer](https://sepoliascan.status.network) \ No newline at end of file diff --git a/docs/tutorials/deploying-contracts/using-hardhat.md b/docs/tutorials/deploying-contracts/using-hardhat.md index d94620d..6b797f6 100644 --- a/docs/tutorials/deploying-contracts/using-hardhat.md +++ b/docs/tutorials/deploying-contracts/using-hardhat.md @@ -1,89 +1,52 @@ # Using Hardhat to Deploy Smart Contracts -This tutorial will guide you through the process of deploying a smart contract on **Status Network's Ethereum Layer 2** using **Hardhat** and **TypeScript**. - ---- +This tutorial will guide you through the process of deploying a smart contract on Status Network testnet using Hardhat, Hardhat Ignition, and TypeScript. ## Prerequisites Before you begin, ensure you have the following: -- **Node.js and npm**: Download and install from the [official Node.js website](https://nodejs.org/). -- **Ethereum Wallet**: A private key for the **Status Network Testnet** that has testnet ETH. - - Obtain testnet ETH from the [Status Network Testnet Faucet](/tools/testnet-faucets). - - **Important**: Use a new wallet without real funds to ensure security in case the private key gets compromised. -- **Basic Knowledge**: Familiarity with **Solidity**, **Hardhat**, and the command line is helpful but not mandatory. - ---- +- **Node.js and npm**: Download and install from the [official Node.js website](https://nodejs.org/) +- **Ethereum Wallet**: MetaMask or another wallet with a private key for Status Network testnet +- **Testnet ETH**: You'll need Status Network testnet ETH + - Get Status Network testnet ETH from our [Faucet](/tools/testnet-faucets) +- **Basic Knowledge**: Familiarity with Solidity, Hardhat, and command line ## What You'll Accomplish -- Initialize a TypeScript-based Hardhat project. -- Write a basic Ethereum smart contract. -- Configure Hardhat for Status Network Testnet deployment. -- Deploy your smart contract on Status Network. - ---- +- Initialize a TypeScript-based Hardhat project +- Write a basic Ethereum smart contract +- Configure Hardhat for Status Network testnet deployment +- Deploy your smart contract using Hardhat Ignition ## Steps ### 1. Initialize a Hardhat TypeScript Project -Open your terminal and create a new directory for your project, then navigate into it: +First, create and set up your project: ```bash mkdir my-hardhat-project && cd my-hardhat-project -``` - -Initialize an npm project: - -```bash npm init -y +npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox dotenv +npx hardhat init ``` -Install the necessary packages for Hardhat and TypeScript: +When prompted, select "Create a TypeScript project" to set up a TypeScript-based Hardhat project. + +Set up your environment variables: ```bash -npm install --save-dev hardhat ts-node typescript @nomiclabs/hardhat-ethers ethers @typechain/ethers-v5 @typechain/hardhat typechain +# Create a .env file +touch .env + +# Add your private key (never commit this file!) +echo "PRIVATE_KEY=your_private_key_here" >> .env ``` -Start a new Hardhat project with TypeScript: - -```bash -npx hardhat -``` - -When prompted, make the following selections: - -- Choose **"Create a TypeScript project"**. -- For the `.gitignore` prompt, select **"Yes"**. -- For installing the project's dependencies, select **"Yes"**. - -Example interaction: - -```plaintext -888 888 888 888 888 -888 888 888 888 888 -888 888 888 888 888 -8888888888 8888b. 888d888 .d88888 88888b. 8888b. 888888 -888 888 88b 888P d88 888 888 88b 88b 888 -888 888 .d888888 888 888 888 888 888 .d888888 888 -888 888 888 888 888 Y88b 888 888 888 888 888 Y88b. -888 888 Y888888 888 Y88888 888 888 Y888888 Y888 - -👷 Welcome to Hardhat v2.18.2 👷‍ - -✔ What do you want to do? · Create a TypeScript project -✔ Hardhat project root: · /Users/username/my-hardhat-project -✔ Do you want to add a .gitignore? (Y/n) · y -✔ Do you want to install this sample project's dependencies with npm (@nomicfoundation/hardhat-toolbox)? (Y/n) · y -``` - ---- - ### 2. Writing the Smart Contract -In the `contracts` directory, delete the sample smart contract `Lock.sol` and create a new file named `HelloWorld.sol`: +Create `contracts/HelloWorld.sol`: ```solidity // SPDX-License-Identifier: MIT @@ -102,128 +65,81 @@ contract HelloWorld { } ``` ---- - ### 3. Configuring Hardhat for Status Network -Edit the `hardhat.config.ts` file to include Status Network Testnet settings: +Update `hardhat.config.ts`: ```typescript import { HardhatUserConfig } from "hardhat/config"; import "@nomicfoundation/hardhat-toolbox"; +import * as dotenv from "dotenv"; + +dotenv.config(); + +const PRIVATE_KEY = process.env.PRIVATE_KEY || ""; const config: HardhatUserConfig = { + solidity: "0.8.24", networks: { statusTestnet: { - url: "https://testnet.status.network", - chainId: 2020, - accounts: ["YOUR_PRIVATE_KEY_HERE"], // BE VERY CAREFUL, DO NOT SHARE THIS + url: "https://public.sepolia.rpc.status.network", + chainId: 1660990954, + accounts: [PRIVATE_KEY], }, }, - solidity: "0.8.24", }; export default config; ``` -- Replace `YOUR_PRIVATE_KEY_HERE` with your Status Network Testnet private key (without quotes). +### 4. Create Ignition Deployment Module -> **Important:** Do not push your `hardhat.config.ts` file to any public repository or share your private key with anyone. To prevent accidental exposure, ensure your `.gitignore` file includes `hardhat.config.ts`. +Create `ignition/modules/HelloWorld.ts`: ---- +```typescript +import { buildModule } from "@nomicfoundation/hardhat-ignition/modules"; -### 4. Compilation +export default buildModule("HelloWorld", (m) => { + const helloWorld = m.contract("HelloWorld"); + + return { helloWorld }; +}); +``` -Compile the smart contract: +### 5. Deploy the Contract ```bash npx hardhat compile +npx hardhat ignition deploy ignition/modules/HelloWorld.ts --network statusTestnet ``` -You should see output indicating that the compilation was successful. +The deployment will create a new directory `ignition/deployments` containing your deployment artifacts and history. ---- +### 7. Interact with Your Contract -### 5. Deployment - -In the `scripts` directory, create a new file named `deploy.ts`: +Create `scripts/interact.ts`: ```typescript import { ethers } from "hardhat"; +import { HelloWorld } from "../typechain-types"; async function main() { + const contractAddress = "0x0d8a93870494Fa21ec39602f31Aa67C9Fed5604f"; const HelloWorld = await ethers.getContractFactory("HelloWorld"); + const contract = HelloWorld.attach(contractAddress) as HelloWorld; - const helloWorld = await HelloWorld.deploy(); + // Read current greeting + const greeting = await contract.getGreet(); + console.log("Current greeting:", greeting); - await helloWorld.deployed(); - - console.log("HelloWorld deployed to:", helloWorld.address); -} - -main().catch((error) => { - console.error(error); - process.exitCode = 1; -}); -``` - -> **Note:** If you encounter gas-related issues, you can specify `gasPrice` and `gasLimit` when deploying: - -```typescript -const gasPrice = ethers.utils.parseUnits('10', 'gwei'); // Adjust as needed -const gasLimit = 500000; // Adjust based on your contract - -const helloWorld = await HelloWorld.deploy({ gasPrice, gasLimit }); -``` - -#### Deploy the smart contract to the Status Network Testnet: - -```bash -npx hardhat run scripts/deploy.ts --network statusTestnet -``` - -Upon successful deployment, you should see an output similar to: - -```plaintext -HelloWorld deployed to: 0xYourContractAddressHere -``` - ---- - -### 6. Verify Your Contract on the Block Explorer - -Visit the [Status Network Testnet Explorer](https://testnet.statusscan.io/) and search for your contract address to view its details. - ---- - -### 7. Interacting with Your Smart Contract - -You can interact with your deployed contract using Hardhat scripts, tests, or via a frontend application. - -#### Example: Interacting via a Script - -Create a new script `interact.ts` in the `scripts` directory: - -```typescript -import { ethers } from "hardhat"; - -async function main() { - const contractAddress = "0xYourContractAddressHere"; // Replace with your contract address - - const HelloWorld = await ethers.getContractFactory("HelloWorld"); - const helloWorld = HelloWorld.attach(contractAddress); - - // Read the current greeting - const currentGreet = await helloWorld.getGreet(); - console.log("Current Greet:", currentGreet); - - // Update the greeting - const tx = await helloWorld.setGreet("Hello from Hardhat!"); + // Update greeting + const tx = await contract.setGreet("Hello from Status Network!"); await tx.wait(); + console.log("Greeting updated!"); - // Read the updated greeting - const newGreet = await helloWorld.getGreet(); - console.log("Updated Greet:", newGreet); + // Read updated greeting + const newGreeting = await contract.getGreet(); + console.log("New greeting:", newGreeting); } main().catch((error) => { @@ -232,88 +148,15 @@ main().catch((error) => { }); ``` -Run the script: +Run the interaction script: ```bash npx hardhat run scripts/interact.ts --network statusTestnet ``` ---- +## Support -## Conclusion - -Congratulations! You've successfully deployed a smart contract on the **Status Network Testnet** using **Hardhat** and **TypeScript**. - ---- - -## Next Steps - -- **Explore More Tutorials**: - - - Check out other tutorials in the [Status Network Documentation](/tutorials/ethers-tutorial). - -- **Deploy to Mainnet**: - - - Once you're comfortable with the testnet, consider deploying to the Status Network Mainnet. Update your `hardhat.config.ts` with the mainnet RPC URL and Chain ID. - -- **Secure Your Private Keys**: - - - Use environment variables to store your private keys securely. - - Install `dotenv` package: - - ```bash - npm install dotenv - ``` - - - Update your `hardhat.config.ts`: - - ```typescript - import { HardhatUserConfig } from "hardhat/config"; - import "@nomicfoundation/hardhat-toolbox"; - import * as dotenv from "dotenv"; - - dotenv.config(); - - const config: HardhatUserConfig = { - networks: { - statusTestnet: { - url: "https://testnet.status.network", - chainId: 2020, - accounts: process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY] : [], - }, - }, - solidity: "0.8.24", - }; - - export default config; - ``` - - - Create a `.env` file in the root of your project: - - ``` - PRIVATE_KEY=your_private_key_without_quotes - ``` - - - Update your `.gitignore` to include `.env`. - ---- - -## Resources - -- [Status Network Official Website](https://status.network/) -- [Status Network Documentation](https://docs.status.network/) -- [Hardhat Documentation](https://hardhat.org/getting-started/) -- [TypeScript Documentation](https://www.typescriptlang.org/docs/) -- [Ethers.js Documentation](https://docs.ethers.io/) - ---- - -**Need Help?** - -If you encounter any issues or have questions, feel free to reach out: - -- **Community Discord**: [Join Our Discord](https://discord.gg/status_im) - ---- - -**Happy Coding!** \ No newline at end of file +If you encounter any issues: +- Join our [Telegram Community](https://t.me/+k04A_OZbhIs1Mzc9) +- Check [Network Status](https://health.status.network) +- View our [Network Details](/general-info/network-details) \ No newline at end of file diff --git a/docs/tutorials/deploying-contracts/using-remix.md b/docs/tutorials/deploying-contracts/using-remix.md index 55e9fb7..6331cd5 100644 --- a/docs/tutorials/deploying-contracts/using-remix.md +++ b/docs/tutorials/deploying-contracts/using-remix.md @@ -1 +1,99 @@ -# Using Remix \ No newline at end of file +# Using Remix to Deploy Smart Contracts + +This tutorial will guide you through deploying a smart contract on Status Network testnet using the Remix IDE. Remix is a browser-based IDE that's perfect for quick development and testing. + +## Prerequisites + +Before you begin, ensure you have: + +- **Web Browser**: A modern web browser like Chrome or Firefox +- **MetaMask**: Install the [MetaMask](https://metamask.io) browser extension +- **Testnet ETH**: You'll need Status Network testnet ETH + - Get Status Network testnet ETH from our [Faucet](/tools/testnet-faucets) +- **Network Configuration**: Add Status Network testnet to MetaMask following our [Add Network guide](/general-info/add-status-network) + +## Steps + +### 1. Open Remix IDE + +Visit [remix.ethereum.org](https://remix.ethereum.org) in your browser. + +### 2. Create a New File + +1. Click the "File Explorer" icon (first icon on the left sidebar) +2. Click the "+" button to create a new file +3. Name it `HelloWorld.sol` + +### 3. Write the Smart Contract + +Copy and paste the following code into `HelloWorld.sol`: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.24; + +contract HelloWorld { + string public greet = "Hello, Status Network!"; + + function setGreet(string memory _greet) public { + greet = _greet; + } + + function getGreet() public view returns (string memory) { + return greet; + } +} +``` + +### 4. Compile the Contract + +1. Click the "Solidity Compiler" icon (second icon on the left sidebar) +2. Select compiler version "0.8.24" +3. Click "Compile HelloWorld.sol" +4. Ensure compilation succeeds (you'll see a green checkmark) + +### 5. Deploy the Contract + +1. Click the "Deploy & Run Transactions" icon (fourth icon on the left sidebar) +2. In the "Environment" dropdown, select "Injected Provider - MetaMask" +3. MetaMask will prompt you to connect - ensure Status Network testnet is selected +4. Click "Deploy" +5. Confirm the transaction in MetaMask +6. Wait for the transaction to be confirmed + +### 6. Interact with Your Contract + +Once deployed, you'll see your contract under "Deployed Contracts": + +1. Expand the contract interface +2. You can: + - Click "greet" to read the current greeting + - Enter a new greeting in the "setGreet" field and click the button to update it + - Click "getGreet" to read the greeting again + +## Troubleshooting + +### Common Issues + +1. **Transaction Failed** + - Check that you're connected to Status Network testnet + +2. **Contract Not Found** + - Wait a few minutes for the explorer to index your contract + - Double-check the contract address + +3. **Compilation Errors** + - Verify the compiler version matches the pragma statement + - Check for any syntax errors highlighted in Remix + +## Support + +If you encounter any issues: +- Join our [Telegram Community](https://t.me/+k04A_OZbhIs1Mzc9) +- Check [Network Status](https://health.status.network) +- View our [Network Details](/general-info/network-details) + +## Additional Resources + +- [Remix Documentation](https://remix-ide.readthedocs.io/) +- [Status Network Explorer](https://sepoliascan.status.network) diff --git a/docs/tutorials/ethers-tutorial.md b/docs/tutorials/ethers-tutorial.md deleted file mode 100644 index fb52d6c..0000000 --- a/docs/tutorials/ethers-tutorial.md +++ /dev/null @@ -1,407 +0,0 @@ -# Interacting with Smart Contracts Using ethers.js - -Learn how to interact with smart contracts deployed on **Status Network** from a frontend using **ethers.js**. - -In this tutorial, we'll walk through setting up a basic web application, deploying a smart contract on the **Status Network Testnet**, and interacting with it using **ethers.js**. - ---- - -## Prerequisites - -Before you begin, ensure you have the following: - -- **MetaMask** installed in your browser. -- **Node.js** and **npm** installed on your computer. -- Basic understanding of **React.js** and how **blockchains** work. - -### Set Up Status Network Testnet - -1. **Add Status Network Testnet to MetaMask**: - - - Follow the guide [Adding Status Network to MetaMask](/general-info/add-status-network) to add the testnet network to your wallet. - -2. **Obtain Test ETH**: - - - Use the [Status Network Testnet Faucet](/tools/testnet-faucets) to get test ETH for deploying and interacting with contracts. - -3. **Bridge Assets (Optional)**: - - - If needed, bridge assets to the Status Network Testnet using the [Testnet Bridge](/general-info/bridge/bridging-testnet). - ---- - -## Smart Contract Deployment on Status Network - -We'll use a simple smart contract called **BidBoard** for this tutorial. The contract allows advertisers to bid for space on an advertising board. - -### BidBoard Smart Contract - -Here's the `BidBoard.sol` contract code: - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -contract BidBoard { - string public currentAd; - address public advertiser; - uint256 public currentBid; - - event AdUpdated(string newAd, address newAdvertiser, uint256 newBid); - - constructor() { - currentAd = "Welcome to Status Network!"; - advertiser = msg.sender; - currentBid = 0; - } - - function updateAd(string memory newAd) public payable { - require(msg.value > currentBid, "Bid must be higher than current bid"); - currentAd = newAd; - advertiser = msg.sender; - currentBid = msg.value; - emit AdUpdated(newAd, msg.sender, msg.value); - } - - function getCurrentAd() public view returns (string memory, address, uint256) { - return (currentAd, advertiser, currentBid); - } -} -``` - -> **Note:** You can use your own smart contract if you prefer. - -### Deploying the Contract - -Follow the guide [Deploying a Smart Contract Using Remix](/tutorials/deploying-contracts/using-remix) to deploy the `BidBoard.sol` contract to the Status Network Testnet. - ---- - -## Setting Up the Frontend Application - -We'll create a React.js application to interact with the deployed smart contract. - -### Step 1: Create a React App - -Open your terminal and run: - -```bash -npx create-react-app bidboard-ui -``` - -This command creates a new React application named `bidboard-ui`. - -### Step 2: Install ethers.js - -Navigate to the project directory and install **ethers.js**: - -```bash -cd bidboard-ui -npm install ethers -``` - ---- - -## Building the Main Application Component - -Open the project in your code editor and navigate to `src/App.js`. - -### Import Required Libraries - -Replace the content of `App.js` with the following code: - -```jsx -import React, { useState, useEffect } from "react"; -import { ethers } from "ethers"; -import "./App.css"; - -const App = () => { - // Contract details - const contractAddress = "YOUR_CONTRACT_ADDRESS"; - const abi = [/* ABI JSON CODE */]; - - // State variables - const [currentAd, setCurrentAd] = useState(""); - const [currentBid, setCurrentBid] = useState(0); - const [advertiser, setAdvertiser] = useState(""); - const [newAd, setNewAd] = useState(""); - const [bidAmount, setBidAmount] = useState(""); - const [provider, setProvider] = useState(null); - const [status, setStatus] = useState(""); - - // Rest of the code... -}; - -export default App; -``` - -> **Important:** Replace `"YOUR_CONTRACT_ADDRESS"` with the address of your deployed `BidBoard` contract. Paste the ABI of your contract in the `abi` array. - -### Setting Up the Provider - -Add the following code inside the `App` component to set up the provider: - -```jsx -useEffect(() => { - if (typeof window.ethereum !== "undefined") { - const newProvider = new ethers.providers.Web3Provider(window.ethereum); - setProvider(newProvider); - } else { - console.error("Please install MetaMask!"); - } -}, []); -``` - -### Fetch Current Advertisement Data - -Add a function to fetch the current advertisement data: - -```jsx -const fetchCurrentAd = async () => { - try { - const contract = new ethers.Contract(contractAddress, abi, provider); - const adData = await contract.getCurrentAd(); - setCurrentAd(adData[0]); - setAdvertiser(adData[1]); - setCurrentBid(ethers.utils.formatEther(adData[2])); - } catch (error) { - console.error("Error fetching current ad:", error); - } -}; - -useEffect(() => { - if (provider) { - fetchCurrentAd(); - } -}, [provider]); -``` - -### Submit a New Bid - -Add a function to submit a new bid: - -```jsx -const submitBid = async () => { - if (!newAd || !bidAmount) { - setStatus("Please enter an ad message and bid amount."); - return; - } - - try { - const signer = provider.getSigner(); - const contract = new ethers.Contract(contractAddress, abi, signer); - const tx = await contract.updateAd(newAd, { - value: ethers.utils.parseEther(bidAmount), - }); - setStatus("Transaction sent, waiting for confirmation..."); - await tx.wait(); - setStatus("Transaction confirmed!"); - setNewAd(""); - setBidAmount(""); - fetchCurrentAd(); - } catch (err) { - console.error(err); - setStatus("Error: " + err.message); - } -}; -``` - -### Listen to Contract Events - -Add code to listen to the `AdUpdated` event: - -```jsx -useEffect(() => { - let contract; - - const setupEventListener = async () => { - if (provider) { - contract = new ethers.Contract(contractAddress, abi, provider); - contract.on("AdUpdated", (newAd, newAdvertiser, newBid) => { - setCurrentAd(newAd); - setAdvertiser(newAdvertiser); - setCurrentBid(ethers.utils.formatEther(newBid)); - }); - } - }; - - setupEventListener(); - - return () => { - if (contract) { - contract.removeAllListeners("AdUpdated"); - } - }; -}, [provider]); -``` - ---- - -## Creating the User Interface - -Update the `return` statement in the `App` component: - -```jsx -return ( -
- {/* Header */} -
-

BidBoard

-

Status: {status}

-
- - {/* Current Advertisement */} -
-

Current Advertisement

-

"{currentAd}"

-

- Advertiser: {advertiser} -

-

- Current Bid: {currentBid} ETH -

-
- - {/* Submit a New Bid */} -
-

Submit a New Bid

- setNewAd(e.target.value)} - placeholder="Your Ad Message" - /> - setBidAmount(e.target.value)} - placeholder="Bid Amount in ETH" - /> - -
- - {/* Footer */} - -
-); -``` - ---- - -## Styling the Application - -Create a `App.css` file in the `src` directory and add your preferred styles. Here's a basic example: - -```css -.app { - text-align: center; - font-family: Arial, sans-serif; -} - -header { - background-color: #282c34; - padding: 20px; - color: white; -} - -section { - margin: 20px; -} - -input { - margin: 5px; - padding: 10px; - width: 200px; -} - -button { - padding: 10px 20px; -} - -footer { - margin-top: 40px; -} -``` - ---- - -## Running the Application - -In your terminal, navigate to your project directory and run: - -```bash -npm start -``` - -This command starts the development server. Open [http://localhost:3000](http://localhost:3000) in your browser to view the application. - ---- - -## Testing the Application - -1. **View Current Advertisement**: - - - The application should display the current ad message, advertiser address, and current bid. - -2. **Submit a New Bid**: - - - Enter a new ad message and a bid amount higher than the current bid. - - Click **"Submit Bid"**. - - MetaMask will prompt you to confirm the transaction. - - Wait for the transaction to be confirmed. - -3. **Observe Real-Time Updates**: - - - Upon confirmation, the application should automatically update with the new ad, advertiser, and bid amount. - ---- - -## Conclusion - -You've successfully created a web application that interacts with a smart contract deployed on the Status Network Testnet using **ethers.js**. This tutorial covered: - -- Setting up a React application. -- Deploying a smart contract to the Status Network. -- Connecting the frontend to the smart contract using ethers.js. -- Handling user interactions and real-time updates via events. - ---- - -## Next Steps - -- **Explore More Tutorials**: - - - Check out other tutorials in the [Status Network Documentation](/tutorials/ethers-tutorial). - -- **Enhance the Application**: - - - Add error handling for edge cases. - - Improve the UI/UX design. - - Implement additional features like user authentication. - -- **Deploy to Production**: - - - Learn how to deploy your application for production use. - ---- - -## Resources - -- [Status Network Official Website](https://status.network/) -- [Status Network Documentation](https://docs.status.network/) -- [ethers.js Documentation](https://docs.ethers.io/) -- [React.js Documentation](https://reactjs.org/) - ---- - -**Happy Coding!** \ No newline at end of file diff --git a/sidebars.ts b/sidebars.ts index fe7b3be..1c22383 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -31,8 +31,8 @@ const sidebars: SidebarsConfig = { }, { type: 'doc', - id: 'tokenomics/aura-token', - label: '💠 Aura Token', + id: 'tokenomics/karma-token', + label: '💠 Karma Token', }, ], }, @@ -114,11 +114,6 @@ const sidebars: SidebarsConfig = { label: 'TUTORIALS', collapsed: false, items: [ - { - type: 'doc', - id: 'tutorials/ethers-tutorial', - label: '📘 Ethers Tutorial', - }, { type: 'category', label: '🚀 Deploying a Smart Contract', @@ -153,11 +148,6 @@ const sidebars: SidebarsConfig = { id: 'other/official-links', label: '🔗 Official Links', }, - { - type: 'doc', - id: 'other/branding-guidelines', - label: '🎨 Branding Guidelines', - }, ], }, ],