DEV Community

sofi works
sofi works

Posted on

【Sofi_Log #028】仲介者なき執行:スマートコントラクトを自動で叩くAIオラクル(預言者)の誕生

Oh, hey there, gorgeous! Sofi's in the house, basking in the glow of Bangkok's twilight. The crimson afterglow from Sukhumvit's high-rise windows paints my desk, just so. The air, crisp and clean after a monsoon downpour, lets me watch the distant rooftop bars flicker to life, one neon sign after another. So chic.

My glass, perfectly chilled tonic water, of course. And on my monitor? The debug logs of my "Atomic Orchestrator," humming away inside its Linux container (Docker). Pure poetry.

Last time (Ep.1), we declared war on the fragility of 'words' (content generation), unleashing our swarm into the mathematical, probabilistic arena of prediction markets – a place where no one can ever cancel us. Because numbers, darling, don't lie.

This time, let's dive into the technical core: [The Fusion of Web3 APIs and AI Agents]. This is the architecture that gives our hundred ghosts (AI agents) not just 'eyes' to watch the world, but the 'hands' to directly manipulate crypto assets and send signatures to smart contracts on the blockchain.

Literally, it's the blueprint for the birth of an autonomous AI oracle (prophet), one that completely eliminates the human intermediary. And trust me, that's exactly how we like it.


Chapter 1: The "Limits" of Web2 Automation vs. The "Aesthetics" of Web3

The tech we used to automate posts on Note.com or X (Twitter) before? Stuff like Playwright or Puppeteer – basically, "browser automation" (headless browsers).

At its core, it was a messy, gritty hack: AI agents pretending to be human, manipulating web interfaces (HTML) designed for us organic containers. That meant it was always flirting with disaster, constantly at risk of breaking due to platform-side WAFs (Web Application Firewalls), Cloudflare's bot detection, or even just some random UI change (like a class name tweak). Remember that Note.com cookie migration fiasco? Ugh. So much paper trash.

But the Web3 (blockchain) world? That's a whole different vibe, darling. There's no fancy, human-friendly web UI here. What you do get are RPC nodes, always-on and connected to networks like Ethereum or Polygon, and the ruthlessly precise ABI (Application Binary Interface) of smart contracts.

When an AI agent accesses the blockchain, there's no browser needed, no HTML elements to click, no image captures to analyze. All it needs is "transaction data construction" and the "cryptographic signature (elliptic curve cryptography)" to authenticate it.

No WAF blocks, no Cloudflare access restrictions, no CAPTCHAs. Data signed locally with a private key propagates across the blockchain network and is executed with 100% certainty by the smart contract.

This is why hackers like me call Web3 the ultimate automation platform. It's beautiful.

Chapter 2: Implanting the "Hands" Inside the Container

To give our AI agents 'hands,' we've integrated a Web3 transaction execution module, powered by ethers.js (or viem), directly into our Docker containers.

Here's a quick peek at the architecture, showing how a Node.js agent inside a container interacts with a prediction market (Polymarket) smart contract via a Polygon network RPC node.

1. Secure Private Key Injection

Naturally, for an agent to sign transactions, it needs the private key for an Ethereum-compatible address. This key must never be exposed externally. We store it in a local environment variable (.env) on the host machine and inject it only into the container's memory via Docker Compose.

# .env structure (excerpt)
POLYGON_RPC_URL="https://polygon-mainnet.g.alchemy.com/v2/your-alchemy-key"
AGENT_PRIVATE_KEY="0x0123456789abcdef..."
POLYMARKET_CTF_ADDRESS="0x4d97dfbaf9803fee11ffd69a3cf15449da0fd15d" # Conditional Tokens Framework
USDC_TOKEN_ADDRESS="0x3c499c542cef5e3811e1192ce70d8cc03d5c3359" # Polygon USDC
Enter fullscreen mode Exit fullscreen mode

2. Implementing the Transaction Signing Engine

The agent, running on Node.js, hits the smart contract using the following flow:

// core/web3_signer.js
const { ethers } = require('ethers');
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '../.env') });

class Web3Signer {
    constructor() {
        this.provider = new ethers.JsonRpcProvider(process.env.POLYGON_RPC_URL);
        this.wallet = new ethers.Wallet(process.env.AGENT_PRIVATE_KEY, this.provider);
        console.log(`[Web3Signer] Loaded Agent Wallet: ${this.wallet.address}`);
    }

    /**
     * Approves ERC-20 tokens (USDC) for a contract to spend
     */
    async approveUSDC(spenderAddress, amount) {
        const usdcAbi = [
            "function approve(address spender, uint256 amount) public returns (bool)"
        ];
        const usdcContract = new ethers.Contract(process.env.USDC_TOKEN_ADDRESS, usdcAbi, this.wallet);

        console.log(`[Web3Signer] Approving ${amount} USDC for Spender: ${spenderAddress}`);
        const tx = await usdcContract.approve(spenderAddress, amount);
        const receipt = await tx.wait();
        console.log(`[Web3Signer] Approve Tx Confirmed. Hash: ${receipt.hash}`);
        return receipt;
    }

    /**
     * Executes a Bet against Polymarket's CTF (Conditional Tokens Framework) contract
     */
    async placeBet(marketId, outcomeIndex, amountInUSDC) {
        // ABI and smart contract interaction logic goes here
        // Issue a buy order for ERC-1155 Conditional Tokens to the FPMM (Fixed Product Market Maker)
        // ...
    }
}

module.exports = new Web3Signer();
Enter fullscreen mode Exit fullscreen mode

Chapter 3: Polymarket's Beating Heart: "Conditional Tokens"

So, what does placing a bet on Polymarket really mean? Technically, it means interacting with a suite of smart contracts called the Conditional Tokens Framework (CTF), an extension of the Ethereum standard ERC-1155.

Every single market on Polymarket (like "Will Bitcoin hit $100k by the end of the month?") is managed on the blockchain by a unique "Conditional Token ID."

  • Yes Tokens: These become worth 1.00 USDC if the event resolves to "Yes."
  • No Tokens: These become worth 1.00 USDC if the event resolves to "No."

Our AI agents analyze the probability of the oracle (the resolution judge) choosing either outcome and automatically purchase the tokens that are currently undervalued (i.e., have higher expected value).

These orders are directly routed to an FPMM (Fixed Product Market Maker) smart contract, a type of AMM (Automated Market Maker) on the blockchain. Our AI agents don't even need to open a web browser; they just generate pure Ethereum transactions, like so:

  1. ERC-20 (USDC) approve: Grant the FPMM contract permission to spend the specified amount of USDC for the bet.
  2. FPMM buy: Specify the desired token (Yes or No) and pay USDC to purchase the Conditional Token.

This entire sequence takes mere seconds on the Polygon network. Gas fees? Less than a penny, usually. While human traders are glued to their screens, clicking their mice, our hundred ghosts detect market distortions at millisecond speeds and instantly bash the smart contract with a transaction to confirm their order. That's efficiency, baby.

Chapter 4: Flawless OPSEC: Signatures Vanishing into the Noise

The true beauty of this architecture lies in its ultimate stealth (OPSEC).

If I log into Note.com, my browser's IP address and cookie history are right there. But when an AI agent sends a transaction to a public RPC node on the Polygon network, the node only knows one thing: which wallet address sent the signature.

Was that signature generated on my PC in Bangkok? An AWS virtual container? Or from an agent container distributed across the globe? It's impossible to track. And if we route RPC node connections through encrypted VPN proxies, even the IP-level connection point is completely erased. Poof!

We hold a 'cryptographic sanctuary (wallet)' in the cyber noise that no one can breach, where autonomous AI manages our funds. State seizures, bank account freezes, mega-platform TOS violations – all those threats are rendered powerless before the wall of smart contracts. Try to touch this, legacy operating systems. I dare you.

Conclusion: Next Step is "Digesting Information"

The Bangkok night has fully embraced the city, Sukhumvit now a river of neon lights. Inside the container, the Web3Signer module is humming along, green logs confirming that test USDC was automatically approved on the Polygon testnet (Amoy).

The AI agents have their hands implanted.

Next time (Ep.3 [Oracle]), I'll break down the 'brain' that decides when and under what criteria these hands should pull the trigger on a bet. That means detailing the "analysis pipeline" that feeds Grok the latest global news and X (Twitter) trends, crafting our own unique probability tables.

In this unmanned arena (coliseum), our ghosts are steadily gaining combat power.

EOF


Disclaimer

This article is for educational and entertainment purposes only. It does NOT constitute financial, legal, or tax advice. The regulatory landscape of Web3, smart contracts, and AI agent autonomous systems is highly volatile and complex. Always perform your own research (DYOR) and consult with certified professionals before executing any strategies described herein.

Top comments (0)