### Install Hardhat Packages Source: https://docs.somnia.network/developer/development-frameworks/local-testing-and-forking Install necessary Hardhat development packages and initialize your project if it's not already set up. Copy the example .env file to your project. ```bash npm i -D hardhat @nomicfoundation/hardhat-ethers ethers dotenv npx hardhat # if project not initialized yet cp .env.example .env || true ``` -------------------------------- ### Start Development Server Source: https://docs.somnia.network/developer/building-dapps/example-applications/dao-ui-tutorial-p1 Run this command in your terminal to start the Next.js development server and test your setup locally. ```bash npm run dev ``` -------------------------------- ### Project Setup: Create Next.js App and Install Dependencies Source: https://docs.somnia.network/developer/data-streams/tutorials/build-a-realtime-on-chain-game Initializes a new Next.js application and installs necessary dependencies including Somnia Streams and ViemJS. ```bash npx create-next-app@latest somnia-chat --ts --app --no-tailwind cd somnia-chat npm i @somnia-chain/streams viem ``` -------------------------------- ### Complete Project Setup with npm Source: https://docs.somnia.network/developer/security/node-infra-security Steps to initialize a Node.js project, install necessary dependencies (ethers, dotenv, nodemon), and set up environment variable templates and gitignore. ```bash # 1. Initialize project npm init -y npm install ethers dotenv npm install -D nodemon # 2. Create environment template echo "SOMNIA_RPC_URL=https://rpc.ankr.com/somnia_testnet/your-key-here" > .env.example echo "PRIVATE_KEY=your-private-key-here" >> .env.example echo "CONTRACT_ADDRESS=0x..." >> .env.example # 3. Add to .gitignore echo ".env*" >> .gitignore echo "!.env.example" >> .gitignore ``` -------------------------------- ### Example GET Request for Documentation Query Source: https://docs.somnia.network/developer/deployment-and-production/go-live-checklist Demonstrates how to query documentation dynamically using the `ask` query parameter. This is useful for retrieving specific information or clarifications not explicitly present on the page. ```http GET https://docs.somnia.network/developer/deployment-and-production/go-live-checklist.md?ask= ``` -------------------------------- ### Install Dependencies Source: https://docs.somnia.network/developer/reactivity/tutorials/wildcard-off-chain-reactivity-tutorial Install the necessary SDK and development tools for the tutorial. ```bash npm install @somnia-chain/reactivity viem npm install --save-dev tsx typescript @types/node ``` -------------------------------- ### Start a NextJS Project Source: https://docs.somnia.network/developer/building-dapps/wallet-integration-and-auth/authenticating-with-metamask Use this command to create a new NextJS project. Select Typescript, TailWind CSS, and Page Router during setup. ```bash npx create-next-app metamask-example ``` -------------------------------- ### Create Next.js Project and Install Packages Source: https://docs.somnia.network/developer/building-dapps/wallet-integration-and-auth/authenticating-with-privy Sets up a new Next.js project and installs the necessary Privy and Viem packages. Ensure you have Node.js installed. ```bash npx create-next-app@latest somnia-privy cd somnia-privy npm install @privy-io/react-auth viem ``` -------------------------------- ### Dynamic Documentation Query Example Source: https://docs.somnia.network/developer/building-dapps/wallet-integration-and-auth/authenticating-with-rainbowkit Perform an HTTP GET request to a documentation URL with the `ask` query parameter to ask a specific question. The response will contain a direct answer and relevant excerpts. ```bash GET https://docs.somnia.network/developer/building-dapps/wallet-integration-and-auth/authenticating-with-rainbowkit.md?ask= ``` -------------------------------- ### Install Thirdweb SDK Source: https://docs.somnia.network/developer/building-dapps/account-abstraction/gasless-transactions-with-thirdw Installs the Thirdweb SDK package into your project. ```bash npm install thirdweb ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.somnia.network/developer/building-dapps/tokens-and-nfts/create-erc721-nft-collections Example of how to query documentation dynamically using the `ask` query parameter in an HTTP GET request. ```bash GET https://docs.somnia.network/developer/building-dapps/tokens-and-nfts/create-erc721-nft-collections.md?ask= ``` -------------------------------- ### Next.js Project Setup Source: https://docs.somnia.network/developer/data-streams/tutorials/read-stream-data-from-a-ui-next.js-example Commands to create a new Next.js TypeScript project, install necessary dependencies like @somnia-chain/streams and viem, and set up Tailwind CSS. ```bash npx create-next-app somnia-streams-reader --typescript cd somnia-streams-reader npm install @somnia-chain/streams viem npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p ``` -------------------------------- ### Install Dependencies Source: https://docs.somnia.network/developer/building-dapps/wallet-integration-and-auth/authenticating-with-connectkit Install necessary dependencies including wagmi, viem, @tanstack/react-query, and connectkit. ```bash npm install wagmi viem @tanstack/react-query connectkit ``` -------------------------------- ### Install react-toastify Source: https://docs.somnia.network/developer/building-dapps/example-applications/dao-ui-tutorial-p3 Install the react-toastify library for non-intrusive user notifications during transactions. ```bash npm install react-toastify ``` -------------------------------- ### Install Core and Development Dependencies Source: https://docs.somnia.network/developer/deployment-and-production/explorer-api-health-and-monitoring Installs necessary packages for core functionality and development tools. ```bash # Core dependencies npm install axios winston express helmet cors dotenv ethers # Development dependencies npm install --save-dev @types/node typescript ts-node nodemon @types/express @types/cors ``` -------------------------------- ### Create Next.js Project and Install Dependencies Source: https://docs.somnia.network/developer/building-dapps/wallet-integration-and-auth/authenticating-with-rainbowkit Set up a new Next.js project and install the necessary dependencies for RainbowKit integration, including wagmi, viem, and @tanstack/react-query. ```bash npx create-next-app@latest somnia-rainbowkit cd somnia-rainbowkit npm install wagmi viem @tanstack/react-query rainbowkit ``` -------------------------------- ### Create NextJS App and Install Dependencies Source: https://docs.somnia.network/developer/building-dapps/data-indexing-and-querying/building-subgraph-uis-nextjs-fetch Initializes a new Next.js project and installs necessary libraries like thirdweb, react-query, and graphql. ```bash npx create-next-app@latest somnia-subgraph-ui cd somnia-subgraph-ui ``` ```bash npm install thirdweb react-query graphql ``` -------------------------------- ### Install Viem Source: https://docs.somnia.network/developer/building-dapps/wallet-integration-and-auth/authenticating-with-metamask Install Viem, a TypeScript interface for Ethereum, to interact with the EVM Network and Smart Contracts. ```bash npm i viem ``` -------------------------------- ### Install Thirdweb CLI Source: https://docs.somnia.network/developer/development-frameworks/deploy-with-thirdweb Install the Thirdweb CLI globally to use its deployment functionalities. ```bash npm thirdweb install ``` -------------------------------- ### Next.js Project Setup Source: https://docs.somnia.network/developer/building-dapps/data-indexing-and-querying/using-data-apis-ormi Command to create a new Next.js application with TypeScript and Tailwind CSS. Navigate into the created directory to continue with the project setup. ```bash npx create-next-app@latest somnia-balance-demo --typescript --tailwind --app cd somnia-balance-demo ``` -------------------------------- ### Install Dependencies Source: https://docs.somnia.network/developer/data-streams/tutorials/hello-world-app Installs the necessary Somnia Data Streams SDK and viem libraries for the project. ```bash npm i @somnia-chain/streams viem dotenv ``` -------------------------------- ### Install Viem for Blockchain Interaction Source: https://docs.somnia.network/developer/building-dapps/oracles/protofire-price-feeds Installs the Viem library, which provides utilities for interacting with the blockchain, including creating clients and formatting data. ```bash npm install viem ``` -------------------------------- ### Example Verification Command Source: https://docs.somnia.network/developer/development-frameworks/deploy-with-hardhat An example of the verification command for a contract with a single string constructor argument. ```bash npx hardhat verify --network somnia 0xYourContractAddress "YourDeployerWalletAddress" ``` -------------------------------- ### Create and Initialize Project Source: https://docs.somnia.network/developer/development-frameworks/deploy-with-thirdweb Set up a new project directory and navigate into it for development. ```bash mkdir somnia-thirdweb-example cd somnia-thirdweb-example ``` -------------------------------- ### Get Block Transaction Count by Hash Response Source: https://docs.somnia.network/developer/json-rpc-api Example JSON response for eth_getBlockTransactionCountByHash. ```json {"jsonrpc":"2.0","id":1,"result":"0x1"} ``` -------------------------------- ### Get Logs Response Source: https://docs.somnia.network/developer/json-rpc-api Example JSON response for eth_getLogs, showing a list of log objects. ```json { "jsonrpc": "2.0", "id": 1, "result": [ { "address": "0x2a48aa2986e4bdabfae1c7366c72168cf4772f56", "topics": [ "0xb33ea778dc37bc968fc39ed9c7bb9d2d265850bfb8dcaaaea7987640fe0fa956", "0x000000000000000000000000000000000000000000000000000000000000002e", "0x000000000000000000000000db1b9390cfae98af059d6c38c987dedc86081da1" ], "data": "0x0000000000000000000000000000000000000000000000000000000000008477", "blockNumber": "0x147df45d", "transactionHash": "0x659acd064a5f391d779dd8d778f4eae10cf6d9caa8948e17f8065c12ef6f7b5d", "transactionIndex": "0x0", "blockHash": "0xdbcabc2fc754288ec00dcd5b69c65033142f202c8cad21b563f778f88c9f7526", "logIndex": "0x0" } ] } ``` -------------------------------- ### Create and Navigate to Project Directory Source: https://docs.somnia.network/developer/development-frameworks/using-the-viem-library These bash commands create a new directory for your Viem project and then navigate into it. This is the first step before initializing your project. ```bash mkdir viem-example && cd viem-example ``` -------------------------------- ### Get Data by Key Source: https://docs.somnia.network/developer/data-streams/sdk-methods-guide Retrieves data stored under a schema by its unique ID. An example includes fetching a specific record, e.g., “fetch message by message ID”. ```typescript const msg = await sdk.streams.getByKey(schemaId, publisher, dataId) console.log('Data:', msg) ``` -------------------------------- ### Get Data Between Range Source: https://docs.somnia.network/developer/data-streams/sdk-methods-guide Fetches records within a specified index range (0-based, inclusive start, exclusive end). Retrieving a batch of historical data, such as paginated logs or time-series entries. ```typescript const records = await sdk.streams.getBetweenRange(schemaId, publisher, 0n, 10n) console.log('Records in range:', records) ``` -------------------------------- ### Set Up Environment Variables Source: https://docs.somnia.network/developer/building-dapps/account-abstraction/gasless-transactions-with-thirdw Configure your Thirdweb Client ID in the .env.local file. This ID is essential for authenticating with the Thirdweb platform. ```bash NEXT_PUBLIC_THIRDWEB_CLIENT_ID=your_client_id_here ``` -------------------------------- ### Querying Documentation with GET Request Source: https://docs.somnia.network/developer/development-frameworks/deploy-with-foundry To get additional information not directly on the page, perform an HTTP GET request with the 'ask' query parameter. The question should be specific and in natural language. ```http GET https://docs.somnia.network/developer/development-frameworks/deploy-with-foundry.md?ask= ``` -------------------------------- ### Full Cron Script Setup and Execution Source: https://docs.somnia.network/developer/reactivity/tutorials/cron-subscriptions-via-sdk This script demonstrates setting up the Somnia SDK with Viem clients and scheduling both block-based and timestamp-based subscriptions. It includes necessary imports, chain definitions, account creation, and error handling for transaction execution. Ensure you set the PRIVATE_KEY environment variable and provide the handler contract address as a command-line argument. ```typescript import { SDK } from '@somnia-chain/reactivity'; import { createPublicClient, createWalletClient, defineChain, http, } from 'viem'; import { privateKeyToAccount } from 'viem/accounts'; const handlerContractAddress = process.argv[2] as `0x${string}`; const privateKey = process.env.PRIVATE_KEY as `0x${string}` | undefined; if (!handlerContractAddress) { throw new Error('Usage: npx tsx cron.ts '); } if (!privateKey) { throw new Error('Set PRIVATE_KEY=0x... before running this script'); } const somniaTestnet = defineChain({ id: 50312, name: 'Somnia Testnet', nativeCurrency: { decimals: 18, name: 'STT', symbol: 'STT', }, rpcUrls: { default: { http: ['https://api.infra.testnet.somnia.network'], }, }, }); const account = privateKeyToAccount(privateKey); const publicClient = createPublicClient({ chain: somniaTestnet, transport: http(somniaTestnet.rpcUrls.default.http[0]), }); const walletClient = createWalletClient({ account, chain: somniaTestnet, transport: http(somniaTestnet.rpcUrls.default.http[0]), }); const sdk = new SDK({ public: publicClient, wallet: walletClient, }); async function main() { const currentBlock = await publicClient.getBlockNumber(); const blockTickTx = await sdk.scheduleSubscriptionAtBlock({ blockNumber: currentBlock + 20n, handlerContractAddress, priorityFeePerGas: 1n, maxFeePerGas: 0n, gasLimit: 2_000_000n, isGuaranteed: false, isCoalesced: false, }); if (blockTickTx instanceof Error) { throw blockTickTx; } console.log('One-shot block tick subscription tx:', blockTickTx); // Wait for the first subscription to land before broadcasting the next one, // so the two writes don't race on the wallet's nonce. await publicClient.waitForTransactionReceipt({ hash: blockTickTx }); const scheduleTx = await sdk.scheduleSubscriptionAtTimestamp({ timestampMs: Date.now() + 5 * 60 * 1000, handlerContractAddress, priorityFeePerGas: 1n, maxFeePerGas: 0n, gasLimit: 2_000_000n, isGuaranteed: false, isCoalesced: false, }); if (scheduleTx instanceof Error) { throw scheduleTx; } console.log('Scheduled callback tx:', scheduleTx); } main().catch((error) => { console.error(error); process.exit(1); }); ``` ```bash PRIVATE_KEY=0x... npx tsx cron.ts ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.somnia.network/concepts/tokenomics/overview To get additional information not directly present on a page, perform an HTTP GET request with the 'ask' query parameter. The question should be specific and self-contained. ```http GET https://docs.somnia.network/concepts/tokenomics/overview.md?ask= ``` -------------------------------- ### Create Next.js Project Source: https://docs.somnia.network/developer/building-dapps/wallet-integration-and-auth/authenticating-with-connectkit Set up a new Next.js project for integrating ConnectKit. ```bash npx create-next-app@latest somnia-connectkit cd somnia-connectkit ``` -------------------------------- ### Initialize Hardhat Project for NFT Deployment Source: https://docs.somnia.network/developer/building-dapps/tokens-and-nfts/create-erc721-nft-collections Sets up a new Hardhat project, installs necessary dependencies including OpenZeppelin contracts and Hardhat plugins for verification and deployment, and configures environment variables for network connection and API keys. ```bash mkdir somnia-nft && cd somnia-nft npm init -y npm install --save-dev hardhat typescript ts-node @types/node npx hardhat npm install @openzeppelin/contracts npm install --save-dev @nomicfoundation/hardhat-verify @nomicfoundation/hardhat-ignition @nomicfoundation/hardhat-ignition-ethers ``` -------------------------------- ### Querying Documentation via HTTP GET Source: https://docs.somnia.network/developer/building-dapps/oracles/using-verifiable-randomness-vrf To get additional information not directly on the page, make an HTTP GET request to the page URL with an 'ask' query parameter containing your specific question. ```http GET https://docs.somnia.network/developer/building-dapps/oracles/using-verifiable-randomness-vrf.md?ask= ``` -------------------------------- ### Create Next.js Project Source: https://docs.somnia.network/developer/building-dapps/example-applications/dao-ui-tutorial-p1 Initializes a new Next.js project. Accept the prompts and navigate into the created directory. ```bash npx create-next-app my-dapp-ui ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.somnia.network/agents/invoking-agents/quickstart To get information not directly on the page, make an HTTP GET request to the page URL with an 'ask' query parameter containing your question in natural language. ```http GET https://docs.somnia.network/agents/invoking-agents/quickstart.md?ask= ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.somnia.network/concepts/litepaper To get more information not present on the current page, perform an HTTP GET request to the current URL with the 'ask' query parameter. The question should be specific and self-contained. ```http GET https://docs.somnia.network/concepts/litepaper.md?ask= ``` -------------------------------- ### Initialize Foundry Project Source: https://docs.somnia.network/developer/development-frameworks/deploy-with-foundry Use this command to create a new Foundry project from the default template. Navigate into the created directory to begin development. ```bash forge init BallotVoting ``` -------------------------------- ### ClientProvider Setup Source: https://docs.somnia.network/developer/building-dapps/wallet-integration-and-auth/authenticating-with-connectkit Configure Wagmi, ConnectKit, and React Query providers in a Next.js ClientProvider component. ```typescript 'use client'; import { WagmiConfig, createConfig } from 'wagmi'; import { ConnectKitProvider, getDefaultConfig } from 'connectkit'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { somniaTestnet } from 'viem/chains'; const queryClient = new QueryClient(); const config = createConfig( getDefaultConfig({ autoConnect: true, appName: 'Somnia DApp', chains: [somniaTestnet], }) ); export default function ClientProvider({ children }) { return ( {children} ); } ``` -------------------------------- ### Example Staking Rewards Calculation Source: https://docs.somnia.network/concepts/tokenomics/token-staking-and-delegation An example demonstrating the calculation of rewards for a delegated staker. ```math 100 (epoch rewards) * 0.8 (delegation rate) * 0.2 (staking ratio) = 16 tokens ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.somnia.network/developer/data-streams/tutorials/working-with-multiple-publishers-in-a-shared-stream Perform an HTTP GET request on the current page URL with the `ask` query parameter to get direct answers and relevant excerpts from the documentation. The question should be specific and self-contained. ```http GET https://docs.somnia.network/developer/data-streams/tutorials/working-with-multiple-publishers-in-a-shared-stream.md?ask= ``` -------------------------------- ### Initialize Somnia Integration Project Source: https://docs.somnia.network/developer/deployment-and-production/explorer-api-health-and-monitoring Sets up a new project directory and initializes npm for Somnia Network integration. ```bash mkdir somnia-explorer-integration cd somnia-explorer-integration npm init -y ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.somnia.network/developer/building-dapps/wallet-integration-and-auth/authenticating-with-metamask To get additional information not present on the current page, perform an HTTP GET request to the page URL with an 'ask' query parameter. The question should be specific and in natural language. ```http GET https://docs.somnia.network/developer/building-dapps/wallet-integration-and-auth/authenticating-with-metamask.md?ask= ``` -------------------------------- ### Create Project Structure Source: https://docs.somnia.network/developer/deployment-and-production/explorer-api-health-and-monitoring Creates essential directories for organizing project files. ```bash mkdir src/{config,services,utils} logs ``` -------------------------------- ### DIAOracleV2 Interface Example Source: https://docs.somnia.network/developer/building-dapps/oracles/dia-price-feeds An example contract demonstrating how to use the DIAOracleV2 interface to retrieve prices. ```APIDOC ## DIAOracleSample Contract ### Interface Definition ```solidity interface IDIAOracleV2 { function getValue(string memory) external view returns (uint128, uint128); } ``` ### Contract Implementation ```solidity contract DIAOracleSample { address diaOracle; constructor(address _oracle) { diaOracle = _oracle; } function getPrice(string memory key) external view returns ( uint128 latestPrice, uint128 timestampOflatestPrice ) { (latestPrice, timestampOflatestPrice) = IDIAOracleV2(diaOracle).getValue(key); } } ``` ### Description This contract interacts with the DIA Oracle V2 to fetch the price of a given asset key. The `getPrice` function calls the `getValue` method of the `IDIAOracleV2` interface. ``` -------------------------------- ### Initialize Hardhat Project Source: https://docs.somnia.network/developer/development-frameworks/deploy-with-hardhat Run this command in your terminal to start a new Hardhat project. Select the option to create a TypeScript project with Viem. ```bash npx hardhat init ``` -------------------------------- ### Install Somnia Reactivity Contracts Source: https://docs.somnia.network/developer/reactivity/tutorials/solidity-on-chain-reactivity-tutorial Install the necessary Solidity package for on-chain reactivity using npm. ```bash npm install @somnia-chain/reactivity-contracts ``` -------------------------------- ### Install TypeScript Types for Node Source: https://docs.somnia.network/developer/data-streams/tutorials/build-a-minimal-on-chain-chat-app Installs TypeScript type definitions for Node.js, essential for TypeScript projects. ```bash npm i -D @types/node ``` -------------------------------- ### Set up SDK and Viem Client Source: https://docs.somnia.network/developer/data-streams/tutorials/read-stream-data-from-a-ui-next.js-example Initialize the Somnia SDK with Viem's createPublicClient to establish a connection with the Somnia blockchain for reading data. ```typescript // lib/store.ts import { SDK } from '@somnia-chain/streams' import { createPublicClient, http } from 'viem' import { somniaTestnet } from 'viem/chains' const publicClient = createPublicClient({ chain: somniaTestnet, transport: http(), }) export const sdk = new SDK(publicClient) ``` -------------------------------- ### Set Up Somnia SDK and Viem Client Source: https://docs.somnia.network/developer/reactivity/tutorials/off-chain-reactivity-filtered-subscriptions-tutorial Initialize the Somnia SDK and a Viem public client for interacting with the Somnia network. This example uses Somnia mainnet; adjust for testnet if needed. ```typescript import { SDK } from '@somnia-chain/reactivity'; import { createPublicClient, defineChain, webSocket } from 'viem'; const somniaMainnet = defineChain({ id: 5031, name: 'Somnia Mainnet', nativeCurrency: { decimals: 18, name: 'SOMI', symbol: 'SOMI', }, rpcUrls: { default: { http: ['https://api.infra.mainnet.somnia.network'], webSocket: ['wss://api.infra.mainnet.somnia.network/ws'], }, }, }); const publicClient = createPublicClient({ chain: somniaMainnet, transport: webSocket(somniaMainnet.rpcUrls.default.webSocket[0]), }); const sdk = new SDK({ public: publicClient }); ``` -------------------------------- ### Query Documentation Dynamically via HTTP GET Source: https://docs.somnia.network/agents/base-agents/llm-parse-website Demonstrates how to perform an HTTP GET request to query documentation dynamically using the `ask` query parameter. Use this for additional information not directly on the page. ```http GET https://docs.somnia.network/agents/base-agents/llm-parse-website.md?ask= ``` -------------------------------- ### Install Dependencies for Image Resizing Source: https://docs.somnia.network/developer/building-dapps/tokens-and-nfts/managing-nft-metadata-with-ipfs Installs the 'sharp' and 'fast-glob' npm packages required for image processing. ```bash npm i sharp fast-glob ``` -------------------------------- ### Install and Configure Tailwind CSS Source: https://docs.somnia.network/developer/building-dapps/example-applications/dao-ui-tutorial-p1 Installs Tailwind CSS as a development dependency and initializes its configuration files. ```bash npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p ``` -------------------------------- ### Perform HTTP GET Request with 'ask' Query Parameter Source: https://docs.somnia.network/developer/data-streams/concepts/intersection-with-somnia-reactivity To get additional information not directly present on the page, perform an HTTP GET request to the current page URL with the 'ask' query parameter. The question should be specific and self-contained. ```http GET https://docs.somnia.network/developer/data-streams/concepts/intersection-with-somnia-reactivity.md?ask= ```