add tutorials

This commit is contained in:
nadeemb53 2024-10-28 01:37:05 +05:30
parent 2e1c23b4ca
commit 99adbc5e9c
No known key found for this signature in database
GPG Key ID: 92A926811E383A76
5 changed files with 813 additions and 5 deletions

View File

@ -1 +1,84 @@
# Add Status Network
# Add Status Network
This guide shows how to add the **Status Network** to your wallet.
## Testnet
To add **Status Network Testnet** as a custom network to MetaMask:
1. **Open MetaMask**:
- Click on the MetaMask extension icon in your browser to open it.
2. **Access the Network Settings**:
- Click on the network selection dropdown at the top of the MetaMask window.
3. **Add a New Network**:
- Click on **"Add network"**.
- In the new window, click on **"Add a network manually"**.
4. **Enter Network Details**:
- Fill in the following information:
| Name | Value |
|------------------|------------------------------------------|
| **Network Name** | Status Network Testnet |
| **RPC URL** | |
| **Chain ID** | |
| **Currency Symbol** | `ETH` |
| **Block Explorer URL** | |
5. **Save the Network**:
- Click **"Save"** to add the Status Network Testnet to your MetaMask wallet.
You should now be able to connect to the Status Network Testnet by selecting it from the network dropdown menu.
---
## Mobile Wallets
### Adding Status Network to MetaMask Mobile
1. **Open MetaMask Mobile App**:
- Launch the MetaMask app on your mobile device.
2. **Access Settings**:
- Tap on the hamburger menu (three horizontal lines) in the top left corner.
- Select **"Settings"**.
3. **Add a New Network**:
- Tap on **"Networks"**.
- Tap on **"Add Network"**.
4. **Enter Network Details**:
- Input the same network details as mentioned above for Testnet.
5. **Save the Network**:
- Tap **"Add"** to save the new network.
---
## Additional Information
- **Official Links**:
- [Status Network Website](https://status.network/)
- [Status Network Documentation](https://docs.status.network/)
- [Status Network Explorer](#)
- **Need Help?**
- If you encounter any issues, please reach out to our [Support Team](mailto:nadeem@status.im) or join our [Community Discord](#).
---
By following this guide, you've successfully added the Status Network to your MetaMask wallet!

View File

@ -27,7 +27,7 @@ For the sake of this tutorial, we will be deploying the `SimpleStorage.sol` smar
Here's the sample code:
```solidity
// SPDX-License-Identifier: GPL-3.0
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

View File

@ -1 +1,320 @@
# Using Hardhat
# 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**.
---
## 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.
---
## 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.
---
## Steps
### 1. Initialize a Hardhat TypeScript Project
Open your terminal and create a new directory for your project, then navigate into it:
```bash
mkdir my-hardhat-project && cd my-hardhat-project
```
Initialize an npm project:
```bash
npm init -y
```
Install the necessary packages for Hardhat and TypeScript:
```bash
npm install --save-dev hardhat ts-node typescript @nomiclabs/hardhat-ethers ethers @typechain/ethers-v5 @typechain/hardhat typechain
```
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`:
```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. Configuring Hardhat for Status Network
Edit the `hardhat.config.ts` file to include Status Network Testnet settings:
```typescript
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
const config: HardhatUserConfig = {
networks: {
statusTestnet: {
url: "https://testnet.status.network",
chainId: 2020,
accounts: ["YOUR_PRIVATE_KEY_HERE"], // BE VERY CAREFUL, DO NOT SHARE THIS
},
},
solidity: "0.8.24",
};
export default config;
```
- Replace `YOUR_PRIVATE_KEY_HERE` with your Status Network Testnet private key (without quotes).
> **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`.
---
### 4. Compilation
Compile the smart contract:
```bash
npx hardhat compile
```
You should see output indicating that the compilation was successful.
---
### 5. Deployment
In the `scripts` directory, create a new file named `deploy.ts`:
```typescript
import { ethers } from "hardhat";
async function main() {
const HelloWorld = await ethers.getContractFactory("HelloWorld");
const helloWorld = await HelloWorld.deploy();
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!");
await tx.wait();
// Read the updated greeting
const newGreet = await helloWorld.getGreet();
console.log("Updated Greet:", newGreet);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
```
Run the script:
```bash
npx hardhat run scripts/interact.ts --network statusTestnet
```
---
## 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).
- **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:
- **Support**: [support@statusnetwork.io](mailto:nadeem@status.network)
- **Community Discord**: [Join Our Discord](https://discord.gg/status_im)
---
**Happy Coding!**

View File

@ -1 +1,407 @@
# Interacting with Smart Contracts using ethers.js
# 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 (
<div className="app">
{/* Header */}
<header>
<h1>BidBoard</h1>
<p>Status: {status}</p>
</header>
{/* Current Advertisement */}
<section className="current-ad-section">
<h2>Current Advertisement</h2>
<p className="ad-message">"{currentAd}"</p>
<p className="ad-details">
<strong>Advertiser:</strong> {advertiser}
</p>
<p className="ad-details">
<strong>Current Bid:</strong> {currentBid} ETH
</p>
</section>
{/* Submit a New Bid */}
<section className="new-bid-section">
<h2>Submit a New Bid</h2>
<input
type="text"
value={newAd}
onChange={(e) => setNewAd(e.target.value)}
placeholder="Your Ad Message"
/>
<input
type="number"
value={bidAmount}
onChange={(e) => setBidAmount(e.target.value)}
placeholder="Bid Amount in ETH"
/>
<button onClick={submitBid}>Submit Bid</button>
</section>
{/* Footer */}
<footer>
<p>
<a
href="https://github.com/your-repo"
target="_blank"
rel="noopener noreferrer"
>
GitHub Repository
</a>
</p>
</footer>
</div>
);
```
---
## 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).
- **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!**

View File

@ -234,7 +234,7 @@ h1, h2, h3, h4, h5, h6 {
box-shadow: 0 4px 12px rgba(67, 96, 223, 0.2);
position: relative;
overflow: hidden;
margin-right: 16px;
margin-right: 10px;
}
.hub-button::before {