### Setup and Start Next.js App Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/README.md Configures the Next.js environment by copying the example .env file and then starts the Next.js development server. This allows you to interact with your dApp via a web interface. ```bash cd scaffold-kadena/packages/nextjs cp .env.example .env yarn start ``` -------------------------------- ### Install Dependencies and Start Local Development Server Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/WARP.md Installs all project dependencies and starts the Next.js frontend development server. This is typically the first step for local development. ```bash yarn install yarn start ``` -------------------------------- ### Setup Hardhat .env for Testnet Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/README.md Copies the example .env file in the hardhat package to be used for configuring the deployment environment for Kadena Testnet. ```bash cd scaffold-kadena/packages/hardhat cp .env.example .env ``` -------------------------------- ### Run Local Frontend Development Server Source: https://github.com/pritamp20/streamer.fun/blob/main/readme.md Starts the frontend development server for Streamer.fun, allowing developers to view and test the application locally in real-time. Requires dependencies to be installed first. ```bash npm run dev ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/README.md Installs all necessary project dependencies using Yarn. This command should be run after cloning the repository. ```bash yarn install ``` -------------------------------- ### Install Dependencies and Start Dev Server (Bash) Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/README.md This snippet demonstrates how to resolve SWC dependency warnings. It involves stopping the development server, reinstalling dependencies using Yarn, and then restarting the server. ```bash # Stop the dev server and again run: yarn install yarn start ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/pritamp20/streamer.fun/blob/main/readme.md Installs all the necessary npm packages and dependencies for the Streamer.fun project. This command should be run after navigating into the project directory. ```bash npm install ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/pritamp20/streamer.fun/blob/main/readme.md Changes the current directory to the root of the cloned Streamer.fun repository. This is necessary before running subsequent installation commands. ```bash cd streamerchain ``` -------------------------------- ### Install Latest npm Version Source: https://github.com/pritamp20/streamer.fun/blob/main/readme.md Installs the latest version of npm globally on the system. This is a prerequisite for project setup, ensuring compatibility with Node.js v18+ and project dependencies. ```bash npm install npm@latest -g ``` -------------------------------- ### Manage Local Hardhat Chains and Deploy Contracts Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/WARP.md Commands to manage the local Hardhat blockchain environment, including starting the chains, deploying contracts, and cleaning artifacts. Essential for local contract development and testing. ```bash yarn chain yarn deploy:localhost yarn hardhat:compile yarn hardhat:test yarn hardhat:clean ``` -------------------------------- ### Run Local Hardhat Chains Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/README.md Starts two local Hardhat Ethereum Virtual Machine (EVM) chains. This is typically run in the first terminal to provide a local blockchain environment for development. ```bash yarn chain ``` -------------------------------- ### Hedera RAG Agent Implementation in JavaScript Source: https://context7.com/pritamp20/streamer.fun/llms.txt This snippet demonstrates the setup and execution of a RAG agent. It initializes the Hedera client, AI models, loads and splits a knowledge base into a vector store, and defines tools for knowledge search and relevance checking. The agent is configured to strictly answer questions based on the provided knowledge base and Hedera-specific information. ```javascript // rag-agent.js const { ChatPromptTemplate } = require('@langchain/core/prompts'); const { AgentExecutor, createToolCallingAgent } = require('langchain/agents'); const { Client, PrivateKey } = require('@hashgraph/sdk'); const { HederaLangchainToolkit, coreQueriesPlugin } = require('hedera-agent-kit'); const { DynamicTool } = require('@langchain/core/tools'); const { createRAGLLM, createEmbeddings } = require('../utils/llm-factory'); const { RecursiveCharacterTextSplitter } = require('langchain/text_splitter'); const { MemoryVectorStore } = require('langchain/vectorstores/memory'); const fs = require('fs').promises; // Initialize Hedera client const client = Client.forTestnet().setOperator( process.env.HEDERA_ACCOUNT_ID, PrivateKey.fromStringECDSA(process.env.HEDERA_PRIVATE_KEY) ); // Initialize AI models const llm = createRAGLLM(); const embeddings = createEmbeddings(); // Load and split knowledge base const knowledgeText = await fs.readFile('./knowledge/sample-knowledge.txt', 'utf-8'); const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 200 }); const docs = await textSplitter.createDocuments([knowledgeText]); // Create vector store const vectorStore = await MemoryVectorStore.fromDocuments(docs, embeddings); console.log(`Knowledge base loaded with ${docs.length} chunks`); // Create RAG search tool const ragTool = new DynamicTool({ name: 'knowledge_search', description: 'Search knowledge base for Hedera Hashgraph information', func: async (input) => { const results = await vectorStore.similaritySearch(input, 3); if (results.length > 0) { return `KNOWLEDGE_BASE_INFO: ${results.map(doc => doc.pageContent).join('\n\n')}`; } return 'NO_MATCH'; } }); // Create relevance checker const relevanceTool = new DynamicTool({ name: 'check_relevance', description: 'Check if question is relevant to Hedera/blockchain', func: async (input) => { const relevancePrompt = ChatPromptTemplate.fromMessages([ ['system', `Check if input relates to: Hedera, blockchain, DLT, cryptocurrency, smart contracts, consensus. Respond "Relevant" or "Not Relevant".`], ['human', 'Check relevance: {input}'] ]); const chain = relevancePrompt.pipe(llm); const response = await chain.invoke({ input }); return response.content.toString().trim().toLowerCase().includes('relevant') ? 'Relevant' : 'Not Relevant'; } }); // Create Hedera toolkit const hederaToolkit = new HederaLangchainToolkit({ client, configuration: { plugins: [coreQueriesPlugin] } }); // Create agent prompt const prompt = ChatPromptTemplate.fromMessages([ ['system', `You are a RAG agent that ONLY answers from the knowledge base. WORKFLOW: 1. ALWAYS use check_relevance first 2. If NOT relevant: "I can only answer questions about Hedera Hashgraph..." 3. If relevant: ALWAYS use knowledge_search 4. If NO_MATCH: "I don't have that information..." 5. If KNOWLEDGE_BASE_INFO: ONLY use provided content RESTRICTIONS: - NO external knowledge - NO assumptions or inferences - ONLY quote from knowledge base`], ['placeholder', '{chat_history}'], ['human', '{input}'], ['placeholder', '{agent_scratchpad}'] ]); // Create agent const agent = createToolCallingAgent({ llm, tools: [...hederaToolkit.getTools(), ragTool, relevanceTool], prompt }); const agentExecutor = new AgentExecutor({ agent, tools: [...hederaToolkit.getTools(), ragTool, relevanceTool], verbose: false, maxIterations: 2 }); // Execute RAG query const response = await agentExecutor.invoke({ input: "What is Hedera Hashgraph's consensus algorithm?" }); console.log(`Answer: ${response.output}`); ``` -------------------------------- ### Query NFT Information via REST API (cURL) Source: https://context7.com/pritamp20/streamer.fun/llms.txt This example demonstrates how to query NFT information using a cURL command to interact with a deployed contract via JSON-RPC. It specifically uses the `eth_call` method to read data from a contract address. Requires the contract address and the encoded function data. ```bash # Get NFT information curl -X POST https://evm-testnet.chainweb.com/chainweb/0.0/kadena-testnet/chain/20/pact/api/v1/local \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{"to": "0x1234567890ABCDEF1234567890ABCDEF12345678", "data": "0x0d4e32ec0000000000000000000000000000000000000000000000000000000000000001"}, "latest"], "id": 1 }' ``` -------------------------------- ### Hedera Moderation Agent Setup and Execution in JavaScript Source: https://context7.com/pritamp20/streamer.fun/llms.txt Sets up a LangChain AI agent for content moderation, integrating with the Hedera blockchain. It initializes a Hedera client, creates an LLM, defines a dynamic moderation tool, and executes a test transaction. The agent is then configured with the moderation tool and Hedera toolkit to process input and log the moderation result. ```javascript // moderation-agent.js const { ChatPromptTemplate } = require('@langchain/core/prompts'); const { AgentExecutor, createToolCallingAgent } = require('langchain/agents'); const { Client, PrivateKey, TransferTransaction, Hbar } = require('@hashgraph/sdk'); const { HederaLangchainToolkit, coreQueriesPlugin } = require('hedera-agent-kit'); const { DynamicTool } = require('@langchain/core/tools'); const { createLLM } = require('../utils/llm-factory'); // Initialize Hedera client const client = Client.forTestnet().setOperator( process.env.HEDERA_ACCOUNT_ID, PrivateKey.fromStringECDSA(process.env.HEDERA_PRIVATE_KEY) ); // Create AI model const llm = createLLM(); // Create moderation tool const moderationTool = new DynamicTool({ name: 'content_moderation', description: 'Analyzes text content and returns "Flagged" or "Good"', func: async (input) => { const moderationPrompt = ChatPromptTemplate.fromMessages([ ['system', `You are a content moderation AI. Analyze for: - Hate speech, harassment, discrimination - Violence or threats - Explicit sexual content - Spam or malicious content - Personal information or doxxing - Illegal activities Respond with ONLY "Flagged" or "Good".`], ['human', 'Analyze: {text}'] ]); const chain = moderationPrompt.pipe(llm); const response = await chain.invoke({ text: input }); const result = response.content.toString().trim(); return result.toLowerCase().includes('flagged') ? 'Flagged' : 'Good'; } }); // Make test transaction const testTransaction = new TransferTransaction() .addHbarTransfer(process.env.HEDERA_ACCOUNT_ID, new Hbar(-0.1)) .addHbarTransfer("0.0.3", new Hbar(0.1)) .setTransactionMemo("Moderation Agent Test Transaction"); const txResponse = await testTransaction.execute(client); const receipt = await txResponse.getReceipt(client); console.log(`Transaction ID: ${txResponse.transactionId.toString()}`); console.log(`Receipt Status: ${receipt.status.toString()}`); // Create Hedera toolkit const hederaToolkit = new HederaLangchainToolkit({ client, configuration: { plugins: [coreQueriesPlugin] } }); // Create agent prompt const prompt = ChatPromptTemplate.fromMessages([ ['system', `You are a content moderation agent connected to Hedera network. IMPORTANT RULES: 1. MUST use content_moderation tool for any text input 2. MUST respond with ONLY "Flagged" or "Good" 3. Connected to Hedera for transparency and audit`], ['placeholder', '{chat_history}'], ['human', '{input}'], ['placeholder', '{agent_scratchpad}'] ]); // Create agent const agent = createToolCallingAgent({ llm, tools: [...hederaToolkit.getTools(), moderationTool], prompt }); const agentExecutor = new AgentExecutor({ agent, tools: [...hederaToolkit.getTools(), moderationTool], verbose: false }); // Execute moderation const response = await agentExecutor.invoke({ input: "This is a test message to moderate" }); console.log(`Result: ${response.output}`); ``` -------------------------------- ### Query Prediction Market Info via REST API (cURL) Source: https://context7.com/pritamp20/streamer.fun/llms.txt This cURL example illustrates how to fetch information from a prediction market contract. It employs a JSON-RPC request using the `eth_call` method, targeting the prediction market contract address with the appropriate encoded function data for querying market details. Requires contract address and function data. ```bash # Get prediction market info curl -X POST https://evm-testnet.chainweb.com/chainweb/0.0/kadena-testnet/chain/20/pact/api/v1/local \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{"to": "0x9876543210FEDCBA9876543210FEDCBA98765432", "data": "0xabcd12340000000000000000000000000000000000000000000000000000000000000001"}, "latest"], "id": 1 }' ``` -------------------------------- ### Query Active NFTs via REST API (cURL) Source: https://context7.com/pritamp20/streamer.fun/llms.txt This cURL example shows how to retrieve a list of active NFTs by making a JSON-RPC request. It utilizes the `eth_call` method targeting a specific contract address with the appropriate function selector for fetching active NFTs. Requires the contract address and the function's encoded data. ```bash # Get active NFTs curl -X POST https://evm-testnet.chainweb.com/chainweb/0.0/kadena-testnet/chain/20/pact/api/v1/local \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{"to": "0x1234567890ABCDEF1234567890ABCDEF12345678", "data": "0x5b2f67d9"}, "latest"], "id": 1 }' ``` -------------------------------- ### Marketplace Smart Contract Deployment and Configuration (Solidity) Source: https://context7.com/pritamp20/streamer.fun/llms.txt This snippet demonstrates deploying the Marketplace smart contract, configuring essential parameters like base price, multiplier, and pricing oracle. It also covers listing NFTs for both full and fractional sales. Dependencies include ethers.js for contract interaction and pre-existing StreamNFT contract address. ```javascript // Deploy Marketplace contract const marketplace = await ethers.getContractFactory("Marketplace"); const contract = await marketplace.deploy(streamNFTAddress); await contract.waitForDeployment(); // Configure pricing oracle (owner only) await contract.setBasePricePerHour(ethers.parseEther("0.01")); // 0.01 KDA per hour await contract.setMultiplierBps(10500); // 5% price increase per hour sold await contract.setPriceOracle("0x9876543210fedcba9876543210fedcba98765432"); // List NFT for full purchase const approvalTx = await streamNFT.approve(marketplaceAddress, tokenId); await approvalTx.wait(); const listTx = await contract.list(tokenId, ethers.parseEther("1.5")); await listTx.wait(); // Buy full NFT const buyTx = await contract.buy(tokenId, { value: ethers.parseEther("1.5") }); await buyTx.wait(); // List NFT for fractional hour purchases (bonding curve pricing) const fractionalTx = await contract.listFractional(tokenId); await fractionalTx.wait(); // Check pricing for fractional purchase const [totalCost, nextHourPrice] = await contract.getBuyCost(tokenId, 3); console.log({ totalCost: ethers.formatEther(totalCost) + " KDA", nextHourPrice: ethers.formatEther(nextHourPrice) + " KDA per hour" }); // Buy fractional hours (bonding curve automatically calculates price) const purchaseTx = await contract.buyHours(tokenId, 3, { value: totalCost }); await purchaseTx.wait(); // Get fractional listing data const [streamer, pricePerHour, isActive, totalHoursSold, remainingHours] = await contract.getFractionalData(tokenId); // Get detailed fractional view with bonding curve info const fractionalView = await contract.getFractionalView(tokenId); console.log({ isActive: fractionalView.isActive, basePricePerHour: ethers.formatEther(fractionalView.base) + " KDA", multiplierBps: fractionalView.multiplier.toString(), // 10500 = 5% increase totalHoursSold: fractionalView.totalSold.toString(), remainingHours: fractionalView.remaining.toString(), nextHourPrice: ethers.formatEther(fractionalView.nextPrice) + " KDA" }); // Get user's purchases across all NFTs const [purchasedTokens, hoursArray] = await contract.getUserPurchases(userAddress); for (let i = 0; i < purchasedTokens.length; i++) { console.log(`Token ${purchasedTokens[i]}: ${hoursArray[i]} hours purchased`); } // Get active (non-expired) NFTs in marketplace const activeNFTs = await contract.getActiveNFTs(); // Cancel listings await contract.cancelListing(tokenId); // Full sale await contract.cancelFractionalListing(tokenId); // Fractional sale (only if no hours sold) // Check listing status const isListed = await contract.isListed(tokenId); const isFractional = await contract.isFractionallyListed(tokenId); ``` -------------------------------- ### Configure Frontend for Testnet Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/README.md This section outlines the steps to switch the frontend application from local deployment to testnet. It involves navigating to the frontend directory and modifying an environment variable. ```bash cd packages/nextjs NEXT_PUBLIC_USE_LOCALHOST=true NEXT_PUBLIC_USE_LOCALHOST=false ``` -------------------------------- ### Clone Scaffold-Kadena Repository Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/README.md Clones the scaffold-kadena repository to your local machine. This is the initial step to set up the project. ```bash git clone https://github.com/0xTrip/scaffold-kadena.git cd scaffold-kadena ``` -------------------------------- ### Configure MetaMask for Localhost Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/README.md Provides instructions to import private keys for two Hardhat accounts into MetaMask, enabling connection to the local Kadena Hardhat localhost chains. ```bash # Account 0 Private Key: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 # Account 1 Private Key: 0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d ``` -------------------------------- ### Clone Streamer.fun Repository Source: https://github.com/pritamp20/streamer.fun/blob/main/readme.md Clones the Streamer.fun project repository from GitHub to a local machine. This is the first step in setting up the project locally. ```bash git clone https://github.com/your_username/streamerchain.git ``` -------------------------------- ### Import or Generate Encrypted Private Key Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/README.md Commands to manage encrypted private keys for deploying contracts to Kadena Testnet. 'yarn account:import' imports an existing key, while 'yarn account:generate' creates a new one. ```bash yarn account:import yarn account:generate ``` -------------------------------- ### AdvertisementRAG Contract Deployment and Operations (Solidity) Source: https://context7.com/pritamp20/streamer.fun/llms.txt Demonstrates deploying the AdvertisementRAG contract and performing core operations such as creating, updating, and querying advertisements. It also shows how to retrieve ad details, manage ad status, and configure RAG settings. Dependencies include ethers.js for contract interaction. ```javascript // Deploy AdvertisementRAG contract on 0G Network const adRAG = await ethers.getContractFactory("AdvertisementRAG"); const contract = await adRAG.deploy(); await contract.waitForDeployment(); // Create advertisement with keywords and tags const createTx = await contract.createAd( "Hedera Hashgraph - Lightning Fast Performance", "Hedera delivers 10,000+ TPS with 3-5 second finality...", "Performance", ["speed", "fast", "transactions", "finality", "instant", "tps"], ["blockchain", "performance", "speed"], '{"color": "blue", "priority": "high", "target": "developers"}' ); await createTx.wait(); const adId = await contract.nextAdId() - 1n; // Update advertisement (owner only) await contract.updateAd( adId, "Hedera Hashgraph - Ultra-Fast Performance", "Updated content with better description...", "Performance", ["speed", "fast", "transactions", "finality", "instant", "tps", "throughput"], ["blockchain", "performance", "speed", "scalability"], '{"color": "blue", "priority": "critical", "target": "developers"}' ); // Query RAG with natural language const queryTx = await contract.queryRAG("What blockchain is fast and affordable?"); const receipt = await queryTx.wait(); // Parse query result from transaction const queryResult = receipt.logs.find(log => log.topics[0] === contract.interface.getEvent("RAGResponse").topicHash ); console.log({ query: queryResult.args.query, generatedResponse: queryResult.args.response, relevantAdIds: queryResult.args.relevantAds.map(id => id.toString()) }); // Get query result details const result = await contract.queryRAG.staticCall("speed and low cost"); console.log({ adIds: result.adIds.map(id => id.toString()), relevanceScores: result.relevanceScores.map(score => score.toString()), generatedResponse: result.generatedResponse, totalResults: result.totalResults.toString() }); // Get advertisement by ID const ad = await contract.getAd(adId); console.log({ id: ad.id.toString(), title: ad.title, content: ad.content, category: ad.category, keywords: ad.keywords, tags: ad.tags, timestamp: new Date(Number(ad.timestamp) * 1000).toISOString(), owner: ad.owner, isActive: ad.isActive, views: ad.views.toString(), engagement: ad.engagement.toString(), rating: ad.rating.toString(), metadata: ad.metadata }); // Query by category const performanceAds = await contract.getAdsByCategory("Performance"); // Query by keyword const speedAds = await contract.getAdsByKeyword("speed"); // Get all active ads const activeAds = await contract.getAllActiveAds(); // Get user's ads const myAds = await contract.getMyAds(); // Get analytics const [views, engagement, rating] = await contract.getAdAnalytics(adId); console.log({ views: views.toString(), engagement: engagement.toString(), rating: rating.toString() }); // Get total statistics const [totalViews, totalEngagement, activeCount] = await contract.getTotalStats(); // Increment engagement (anyone) await contract.incrementEngagement(adId); // Rate advertisement (0-5 stars) await contract.rateAd(adId, 5); // Toggle ad active status (owner only) await contract.toggleAdStatus(adId); // Update RAG configuration (RAG owner only) await contract.updateRAGConfig( 20, // maxResults 5, // minRelevanceScore true // enableAutoGeneration ); // Get query statistics const queryCount = await contract.getQueryStats("What is Hedera?"); console.log(`Query executed ${queryCount} times`); ``` -------------------------------- ### Deploy Ignition Module to Sepolia Network Source: https://github.com/pritamp20/streamer.fun/blob/main/0g-RAG/README.md Deploys a specified Ignition module to the Sepolia testnet using the configured private key. This command requires the `SEPOLIA_PRIVATE_KEY` to be set. ```shell npx hardhat ignition deploy --network sepolia ignition/modules/Counter.ts ``` -------------------------------- ### Set Sepolia Private Key for Deployment Source: https://github.com/pritamp20/streamer.fun/blob/main/0g-RAG/README.md Uses the `hardhat-keystore` plugin to securely set the private key for the Sepolia network deployment. This key is required to sign transactions on the Sepolia testnet. ```shell npx hardhat keystore set SEPOLIA_PRIVATE_KEY ``` -------------------------------- ### Deploy Ignition Module to Local Chain Source: https://github.com/pritamp20/streamer.fun/blob/main/0g-RAG/README.md Deploys a specified Ignition module to a locally simulated blockchain network. This is useful for quick testing of deployment scripts without network fees. ```shell npx hardhat ignition deploy ignition/modules/Counter.ts ``` -------------------------------- ### Deploy Contracts to Kadena Testnet Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/README.md This command initiates the deployment of smart contracts to all Kadena testnet chains using the CREATE2 deployment method. Subsequent runs will report contracts as already deployed if no code changes are made. To redeploy, a salt modification in the deployment script is required. ```bash yarn deploy:testnet ``` -------------------------------- ### Deploy and Verify Contracts on Kadena Testnet Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/WARP.md Commands for deploying contracts to all Kadena testnet chains using CREATE2 for deterministic addresses and verifying them on Blockscout explorers. This is part of the multi-chain deployment process. ```bash yarn deploy:testnet yarn verify:testnet ``` -------------------------------- ### Deploy Contract to Localhost Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/README.md Deploys smart contracts to the local Hardhat chain. This command should be executed in a separate terminal after the local chains are running. ```bash cd scaffold-kadena yarn deploy:localhost ``` -------------------------------- ### Hardhat Configuration for Kadena Testnet Deployment Source: https://context7.com/pritamp20/streamer.fun/llms.txt This TypeScript configuration file sets up Hardhat for deploying contracts to the Kadena testnet. It specifies the Solidity compiler version, optimization settings, network details including RPC URLs and chain IDs for multiple Kadena chains, and Etherscan API configuration for verification. It relies on environment variables for private keys and API keys. ```typescript // hardhat.config.ts import { HardhatUserConfig } from "hardhat/config"; import "@nomicfoundation/hardhat-toolbox"; import "@kadena/hardhat-chainweb"; const config: HardhatUserConfig = { solidity: { version: "0.8.20", settings: { optimizer: { enabled: true, runs: 200 } } }, networks: { kadenaTestnet: { url: "https://evm-testnet.chainweb.com", accounts: [process.env.DEPLOYER_PRIVATE_KEY], chainIds: [5920, 5921, 5922, 5923, 5924], // Chains 20-24 timeout: 60000 }, localhost: { url: "http://127.0.0.1:8545", chainIds: [31337] } }, chainweb: { chains: [20, 21, 22, 23, 24], // Deploy to 5 Kadena chains network: "kadenaTestnet" }, etherscan: { apiKey: { kadenaTestnet: process.env.BLOCKSCOUT_API_KEY || "" }, customChains: [ { network: "kadenaTestnet", chainId: 5920, urls: { apiURL: "https://chainweb-evm-testnet-explorer.kadena.network/api", browserURL: "https://chainweb-evm-testnet-explorer.kadena.network" } } ] } }; export default config; ``` -------------------------------- ### Run All Hardhat Tests Source: https://github.com/pritamp20/streamer.fun/blob/main/0g-RAG/README.md Executes all tests within the Hardhat project, including Solidity unit tests and TypeScript integration tests. This command is the primary way to verify the project's functionality. ```shell npx hardhat test ``` -------------------------------- ### YesNoMarket Smart Contract Deployment and Interaction (Solidity) Source: https://context7.com/pritamp20/streamer.fun/llms.txt This snippet demonstrates how to deploy the YesNoMarket contract, create new prediction markets, stake on outcomes, retrieve market and user data, resolve markets, and claim winnings and streamer fees. It utilizes ethers.js for contract interaction. ```javascript // Deploy YesNoMarket contract const yesNoMarket = await ethers.getContractFactory("YesNoMarket"); const contract = await yesNoMarket.deploy(); await contract.waitForDeployment(); // Create prediction market (streamer fee up to 20%) const createTx = await contract.createMarket( "Will Bitcoin reach $100k by end of year?", // question 86400 * 7, // durationSeconds (7 days) 500 // feeBps (5% = 500 basis points) ); const receipt = await createTx.wait(); const marketId = await contract.nextMarketId() - 1n; // Get market information const market = await contract.getMarket(marketId); console.log({ streamer: market.streamer, question: market.question, endTime: new Date(Number(market.endTime) * 1000).toISOString(), resolved: market.resolved, outcome: market.outcome ? "YES" : "NO", yesPool: ethers.formatEther(market.yesPool) + " KDA", noPool: ethers.formatEther(market.noPool) + " KDA", feeBps: market.feeBps.toString(), yesCount: market.yesCount.toString() + " voters", noCount: market.noCount.toString() + " voters", totalPool: ethers.formatEther(market.totalPool) + " KDA", isActive: market.isActive }); // Stake on YES outcome const stakeYesTx = await contract.stake( marketId, true, // outcomeYes = true { value: ethers.parseEther("0.5") } ); await stakeYesTx.wait(); // Stake on NO outcome const stakeNoTx = await contract.stake( marketId, false, // outcomeYes = false { value: ethers.parseEther("0.3") } ); await stakeNoTx.wait(); // Get user's stake in market const [yesAmount, noAmount] = await contract.getUserStake(marketId, userAddress); console.log({ yesStake: ethers.formatEther(yesAmount) + " KDA", noStake: ethers.formatEther(noAmount) + " KDA" }); // Resolve market (streamer only, after endTime) const resolveTx = await contract.resolve( marketId, true // outcome: true = YES wins, false = NO wins ); await resolveTx.wait(); // Claim winnings (winners only, after resolution) try { const claimTx = await contract.claim(marketId); const claimReceipt = await claimTx.wait(); const claimEvent = claimReceipt.logs.find(log => log.topics[0] === contract.interface.getEvent("Claimed").topicHash ); const payout = ethers.formatEther(claimEvent.args.amount); console.log(`Claimed ${payout} KDA`); } catch (error) { console.error("No winnings to claim or already claimed"); } // Claim streamer fee (streamer only, after resolution) const claimFeeTx = await contract.claimStreamerFee(marketId); await claimFeeTx.wait(); ``` -------------------------------- ### Navigate to Project Root Directory Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/README.md This command changes the current directory to the root of the project. It's a prerequisite for running deployment scripts. ```bash cd ../../ ``` -------------------------------- ### Solidity: Deploy and Manage Moderator Contract Source: https://context7.com/pritamp20/streamer.fun/llms.txt Demonstrates deploying the ModeratorWithPurchases contract, adding and updating AI moderators, and toggling their status. Requires owner privileges for adding and updating. ```javascript // Deploy Moderator contract const moderator = await ethers.getContractFactory("ModeratorWithPurchases"); const contract = await moderator.deploy(ownerAddress); await contract.waitForDeployment(); // Add AI moderator (owner only) const addTx = await contract.addModerator( "0xABCDEF1234567890ABCDEF1234567890ABCDEF12", // moderatorAddress "GPT-4 Content Moderator", // name "AI-powered content moderation using OpenAI", // description "ipfs://QmModeratorProfile.../avatar.png" // profileImageURI ); await addTx.wait(); const moderatorId = await contract.nextModeratorId() - 1n; // Update moderator info (owner or moderator) await contract.updateModerator( moderatorId, "GPT-4o Content Moderator", "Enhanced AI moderation with multi-language support", "ipfs://QmUpdatedProfile.../avatar.png" ); // Toggle moderator status (owner only) await contract.toggleModeratorStatus(moderatorId); ``` -------------------------------- ### OpenZeppelin v5.x Import Path Change Source: https://github.com/pritamp20/streamer.fun/blob/main/scaffold-kadena/WARP.md Demonstrates the correct import path for OpenZeppelin contracts in v5.x. This highlights a change from previous versions to ensure compatibility. ```solidity // ❌ @openzeppelin/contracts/security/ReentrancyGuard.sol // ✅ @openzeppelin/contracts/utils/ReentrancyGuard.sol ``` -------------------------------- ### Interact with Marketplace Contract using Wagmi (Next.js) Source: https://context7.com/pritamp20/streamer.fun/llms.txt This snippet shows how to interact with a marketplace contract for buying fractional hours. It uses `useContractWrite` to execute the `buyHours` function and `useContractRead` to fetch the cost of hours. Dependencies include `wagmi` and contract ABIs/addresses. ```typescript function MarketplacePage() { const marketplaceContract = deployedContracts[chain?.id]?.Marketplace; // Buy fractional hours const { write: buyHours } = useContractWrite({ address: marketplaceContract?.address, abi: marketplaceContract?.abi, functionName: 'buyHours', onSuccess: (data) => { console.log('Hours purchased!', data); } }); // Get buy cost const { data: costData } = useContractRead({ address: marketplaceContract?.address, abi: marketplaceContract?.abi, functionName: 'getBuyCost', args: [tokenId, 3n] // 3 hours }); const handleBuyHours = () => { const [totalCost] = costData || [0n]; buyHours({ args: [tokenId, 3n], value: totalCost }); }; return (
Cost for 3 hours: {formatEther(costData[0])} KDA
)}Total Supply: {totalSupply?.toString()}
Active NFTs: {activeNFTs?.length}