For years, smart contracts have been described as "smart," but in reality, they have been static. They could move assets and follow rigid if/then rules, but they were "blind" to human language, nuance, and complex reasoning.
On the Somnia Network, that is changing. By integrating on-chain AI Agent invocation, we are moving from digital ledgers to Intelligent Agents. In this guide, we will build IdeaReview: a dApp that uses a high-performance LLM (Qwen3-30B) to provide brutal, structured, and consensus-verified feedback on startup ideas.
🌟 The Big Move: Why AI + Smart Contracts?
In a traditional Web3 setup, if you wanted AI to interact with a contract, you had to use a centralized oracle. This created a "trust gap."
Somnia AI Agents bridge this gap through Consensus-Based Inference:
- Intelligence as a Utility: Contracts can now "invoke" an AI brain as easily as they call a math library.
- From Data to Wisdom: Contracts no longer just store strings; they can interpret them.
- Decentralized Reasoning: The AI’s output is verified by multiple validators, ensuring the "opinion" is tamper-proof and decentralized.
⚙️ 1. Infrastructure & Agent Configuration
To build this, we utilize Somnia’s specialized LLM Inference Agent. This agent acts as the "brain" for our contract.
Agent Profile
- Agent Name: LLM Inference (Qwen3-30B)
-
Agent ID:
12847293847561029384 -
Platform Requester:
0x037Bb9C718F3f7fe5eCBDB0b600D607b52706776 -
Execution Method:
inferString(prompt, system, chainOfThought, allowedValues)
🛠 2. Environment Setup
We will use Hardhat with Viem for a modern, type-safe development experience.
Initialize Project
mkdir somnia-vc-agent && cd somnia-vc-agent
npm init -y
npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox @nomicfoundation/hardhat-viem viem dotenv
npx hardhat # Select "Create a TypeScript project"
hardhat.config.ts
We must enable viaIR to handle the complex memory operations required for AI data structures.
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
import "@nomicfoundation/hardhat-viem";
import "dotenv/config";
const config: HardhatUserConfig = {
solidity: {
version: "0.8.24",
settings: {
viaIR: true,
optimizer: { enabled: true, runs: 200 },
},
},
networks: {
somnia: {
url: "https://api.infra.testnet.somnia.network",
chainId: 50312,
accounts: process.env.PRIVATE_KEY ? [process.env.PRIVATE_KEY] : [],
},
},
};
export default config;
📄 3. The Smart Contract (IdeaReview.sol)
This contract handles the prompt engineering, the STT (Somnia Token) deposit, and the asynchronous callback.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "./interfaces/ISomniaAgents.sol";
contract IdeaReview {
IAgentRequester public constant PLATFORM = IAgentRequester(0x037Bb9C718F3f7fe5eCBDB0b600D607b52706776);
uint256 public constant LLM_AGENT_ID = 12847293847561029384;
struct Review { string idea; string result; bool completed; }
mapping(uint256 => Review) public reviews;
event IdeaRequested(uint256 indexed requestId, string idea);
event IdeaReviewed(uint256 indexed requestId, string review);
function reviewIdea(string calldata idea) external payable returns (uint256 requestId) {
// 1. Prompt Engineering: Wrapping the idea in a VC context
string memory prompt = string.concat(
"Critique this startup idea brutally. Format: \n",
"Summary: [1 sentence]\nStrengths: [Bullets]\nWeaknesses: [Bullets]\nScore: [X/10]\n\n",
"Idea: ", idea
);
// 2. Encode the Agent Payload
bytes memory payload = abi.encodeWithSelector(
ILLMAgent.inferString.selector,
prompt,
"You are a sophisticated VC investor.",
false, // chainOfThought
new string[](0) // no constraints
);
// 3. Handle Deposit & Request
uint256 deposit = PLATFORM.getRequestDeposit();
require(msg.value >= deposit, "Insufficient deposit");
requestId = PLATFORM.createRequest{value: deposit}(
LLM_AGENT_ID, address(this), this.handleReview.selector, payload
);
reviews[requestId] = Review(idea, "", false);
emit IdeaRequested(requestId, idea);
}
// 4. The Callback: Invoked by the Somnia platform after consensus
function handleReview(uint256 requestId, Response[] memory responses, ResponseStatus status, Request memory) external {
require(msg.sender == address(PLATFORM), "Only platform");
if (status == ResponseStatus.Success && responses.length > 0) {
string memory result = abi.decode(responses[0].result, (string));
reviews[requestId].result = result;
reviews[requestId].completed = true;
emit IdeaReviewed(requestId, result);
}
}
function getRequiredDeposit() external view returns (uint256) {
return PLATFORM.getRequestDeposit();
}
receive() external payable {}
}
🔍 Function Overview
-
reviewIdea: Converts a simple string into an AI-ready prompt. It calculates the necessary STT deposit and dispatches a non-blocking request. -
handleReview: The "ear" of the contract. It waits for the decentralized validators to finish "thinking" and safely decodes the AI's opinion. -
getRequiredDeposit: A critical helper that ensures users always know the real-time cost of AI inference.
🚀 4. Deployment & Invocation
Deployment (scripts/deploy.ts)
import hre from "hardhat";
async function main() {
const ideaReview = await hre.viem.deployContract("IdeaReview");
console.log(`✅ Idea Review deployed at: ${ideaReview.address}`);
}
main().catch(console.error);
High-Performance Invocation (scripts/invoke.ts)
Somnia is fast. This script uses a Sliding Window to poll for events, ensuring we don't hit the 1000-block RPC limit.
import hre from "hardhat";
import { formatUnits } from "viem";
async function main() {
const ideaReview = await hre.viem.getContractAt("IdeaReview", "YOUR_ADDRESS");
const publicClient = await hre.viem.getPublicClient();
const deposit = await ideaReview.read.getRequiredDeposit();
const hash = await ideaReview.write.reviewIdea(["AI-generated bedtime stories for parrots"], { value: deposit });
const receipt = await publicClient.waitForTransactionReceipt({ hash });
let lastBlock = receipt.blockNumber;
console.log("⏳ Waiting for the on-chain VC to respond...");
while (true) {
const currentBlock = await publicClient.getBlockNumber();
const fromBlock = (currentBlock - lastBlock > 999n) ? currentBlock - 999n : lastBlock;
const events = await ideaReview.getEvents.IdeaReviewed({}, { fromBlock, toBlock: currentBlock });
if (events.length > 0) {
console.log("\n📝 VC FEEDBACK RECEIVED:\n", events[0].args.review);
process.exit(0);
}
lastBlock = currentBlock;
await new Promise(r => setTimeout(r, 3000));
}
}
main().catch(console.error);
🏁 Conclusion: The Era of Intelligent Agents
We have moved beyond the "Static Age." By combining AI Agents with Somnia’s high-throughput network, smart contracts are no longer just digital ledgers—they are Autonomous Evaluators.
This "Big Move" means contracts can now:
- Understand human intent instead of just parsing numbers.
- Evaluate qualitative submissions (milestones, ideas, audits).
- Operate with trustless intelligence, verified by a decentralized network of validators.
On Somnia, your code doesn't just run; it thinks. Whether you’re building AI-governed DAOs, sentiment-driven DeFi, or automated startup critiques, the bridge between Neural Networks and Blockchain Networks is officially open.
About Author
Full Stack Blockchain Developer focused on DeFi, smart contracts, AI + blockchain systems, and scalable Web3 infrastructure.
Active across ecosystems like Monad, Somnia, Midnight, and Ethereum — contributing through production-grade dApps, developer tooling, hackathons, workshops, and technical content.
- 3+ years in Web3 development
- 30+ hackathon wins
- Developer Evangelist at Monad
- Technical Advocate at Somnia
Top comments (0)