### RainAA Setup Example Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/configuration.md Initializes RainAA with wallet client, Alchemy credentials, and chain information, then connects to derive a smart account address. ```typescript import { RainAA } from '@buidlrrr/rain-sdk'; import { arbitrum } from 'viem/chains'; import { createWalletClient, custom } from 'viem'; // 1. Create wallet client (assumes MetaMask or similar) const walletClient = createWalletClient({ account: userAddress, transport: custom(window.ethereum), chain: arbitrum }); // 2. Initialize RainAA with Alchemy credentials const rainAA = new RainAA({ walletClient: walletClient, alchemyApiKey: process.env.ALCHEMY_API_KEY, paymasterPolicyId: process.env.PAYMASTER_POLICY_ID, chain: arbitrum, rpcUrl: 'https://arb1.arbitrum.io/rpc' }); // 3. Connect (derive smart account) const smartAccountAddress = await rainAA.connect(); ``` -------------------------------- ### Install Rain SDK Source: https://github.com/rain1-labs/rain-sdk/blob/main/skills/rain-create-market/SKILL.md Install the Rain SDK and its peer dependency, viem. Ensure you are using version 2.0.0 or higher for viem. ```bash npm install @buidlrrr/rain-sdk # peer dep: viem ^2.0.0 ``` -------------------------------- ### Example Usage of RainSocket for Market Event Subscriptions Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/api-reference/RainSocket.md This example demonstrates connecting to RainSocket, subscribing to various market events like entering options, order creation, disputes, and reward claims, and includes logic for unsubscribing after a set time. ```typescript import { RainSocket } from '@buidlrrr/rain-sdk'; const socket = new RainSocket({ environment: 'production' }); // Connection lifecycle socket.onConnect(() => { console.log('Connected to Rain API'); }); socket.onDisconnect(() => { console.log('Disconnected'); }); // Subscribe to market events const marketId = '698c8f116e985bbfacc7fc01'; const unsubEnter = socket.onEnterOption(marketId, (data) => { console.log('New investment:', data.totalInvestmentWei); }); const unsubOrder = socket.onOrderCreated(marketId, (data) => { console.log(`${data.order.orderType} order @ ${data.order.pricePerShare}`); }); const unsubDispute = socket.onDisputeOpened(marketId, (data) => { console.log('Market disputed:', data.status); }); const unsubClaim = socket.onClaimReward(marketId, (data) => { console.log('Reward claimed by:', data.userId); }); // Cleanup setTimeout(() => { unsubEnter(); unsubOrder(); unsubDispute(); unsubClaim(); }, 60000); ``` -------------------------------- ### Install Rain SDK Source: https://github.com/rain1-labs/rain-sdk/blob/main/README.md Install the Rain SDK using npm. Ensure you have viem version 2.0.0 or higher as a peer dependency. ```bash npm install @buidlrrr/rain-sdk ``` -------------------------------- ### Install Rain SDK Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/README.md Installs the Rain SDK package using npm. Ensure peer dependencies like viem, ethers, and socket.io-client are also installed. ```bash npm install @buidlrrr/rain-sdk ``` -------------------------------- ### Configure RainSocket for Development and Production Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/configuration.md Examples of initializing RainSocket for different environments. ```typescript // Development const socket = new RainSocket({ environment: 'development' }); ``` ```typescript // Production const socket = new RainSocket({ environment: 'production' }); ``` -------------------------------- ### Quick Start: Initialize and Fetch Markets Source: https://github.com/rain1-labs/rain-sdk/blob/main/README.md Initialize the stateless `Rain` SDK and fetch public markets. No wallet is required for this step. ```typescript import { Rain, RainAA } from '@buidlrrr/rain-sdk'; // 1. Initialize (stateless — no wallet needed) const rain = new Rain({ environment: 'development' }); // 2. Fetch markets const markets = await rain.getPublicMarkets({ limit: 10 }); ``` -------------------------------- ### Quick Start Integration Source: https://github.com/rain1-labs/rain-sdk/blob/main/AGENTS.md Initialize the Rain client and build a buy transaction. The returned transaction is unsigned and must be signed by the caller. ```ts import { Rain } from '@buidlrrr/rain-sdk'; const rain = new Rain({ environment: 'production' }); // Fetch markets const markets = await rain.getPublicMarkets({ limit: 10 }); // Build a buy transaction (returns unsigned tx — caller signs and sends) const rawTx = rain.buildBuyOptionRawTx({ marketContractAddress: '0x...', selectedOption: 1n, buyAmountInWei: 10_000_000n, // 10 USDT (6 decimals) }); // Send via any provider await provider.sendTransaction(rawTx); ``` -------------------------------- ### Quick Start: Build and Execute Buy Transaction Source: https://github.com/rain1-labs/rain-sdk/blob/main/README.md Build a transaction to buy options on a market and execute it using your provider or RainAA. ```typescript // 3. Build a buy transaction const rawTx = rain.buildBuyOptionRawTx({ marketContractAddress: '0x...', selectedOption: 1n, buyAmountInWei: 10_000_000n, // 10 USDT (6 decimals) }); // 4. Execute via your provider, OR via RainAA: await yourProvider.sendTransaction(rawTx); ``` -------------------------------- ### Typical RainAA Workflow Example Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/api-reference/RainAA.md Demonstrates a complete workflow from wallet client creation and RainAA initialization to transaction building and submission with gas sponsorship. Includes optional cleanup. ```typescript import { Rain, RainAA } from '@buidlrrr/rain-sdk'; import { arbitrum } from 'viem/chains'; import { createWalletClient, custom } from 'viem'; // 1. Create wallet client (connects to user's MetaMask, etc.) const walletClient = createWalletClient({ account: userAddress, transport: custom(window.ethereum) }); // 2. Initialize RainAA const rainAA = new RainAA({ walletClient, alchemyApiKey: 'YOUR_ALCHEMY_KEY', paymasterPolicyId: 'YOUR_PAYMASTER_POLICY_ID', chain: arbitrum }); // 3. Connect (derive smart account) const smartAccountAddress = await rainAA.connect(); console.log('Smart account:', smartAccountAddress); // 4. Use Rain for transaction building const rain = new Rain({ environment: 'production' }); // 5. Build transaction const buyTx = rain.buildBuyOptionRawTx({ marketContractAddress: '0xd262abd3d58038e15736Ec32c4F7b020C2B21dB5', selectedOption: 1n, buyAmountInWei: 10_000_000n // 10 USDT }); // 6. Submit via RainAA (gas sponsored) const txHash = await rainAA.sendTransaction(buyTx); console.log('Transaction submitted:', txHash); // 7. Optional: cleanup rainAA.disconnect(); ``` -------------------------------- ### Market Query Example Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/README.md Fetches public markets and their details using the Rain SDK. Requires an initialized Rain client. ```typescript import { Rain } from '@buidlrrr/rain-sdk'; const rain = new Rain({ environment: 'production' }); // Fetch markets const markets = await rain.getPublicMarkets({ limit: 10 }); console.log(markets[0].title); // Get detailed data const details = await rain.getMarketDetails(markets[0].id); console.log(`Liquidity: ${details.totalLiquidity} wei`); ``` -------------------------------- ### Initialize Rain SDK Source: https://github.com/rain1-labs/rain-sdk/blob/main/skills/rain-trade/SKILL.md Initialize the Rain SDK with the desired environment. This setup is required before interacting with any market functions. ```typescript import { Rain } from '@buidlrrr/rain-sdk'; const rain = new Rain({ environment: 'production' }); ``` -------------------------------- ### Create WebSocket Client with Custom Configuration Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/configuration.md Initialize a WebSocket client using `createWsClient`. This example shows how to specify the WebSocket RPC URL, and configure auto-reconnect and keep-alive settings. ```typescript import { createWsClient } from '@buidlrrr/rain-sdk'; const wsClient = createWsClient({ wsRpcUrl: 'wss://arbitrum-one.publicnode.com', reconnect: { attempts: 5, delay: 1000 }, keepAlive: { interval: 30000 } }); ``` -------------------------------- ### Example Workflow: Rain and RainAA Interaction Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/README.md Demonstrates the typical workflow where Rain builds a transaction and RainAA submits it for execution, including smart account connection. ```typescript const rain = new Rain({ environment: 'production' }); const buyTx = rain.buildBuyOptionRawTx({ marketContractAddress: '0x...', selectedOption: 1n, buyAmountInWei: 10_000_000n }); const rainAA = new RainAA({...}); await rainAA.connect(); const txHash = await rainAA.sendTransaction(buyTx); ``` -------------------------------- ### Initialize Rain SDK Source: https://github.com/rain1-labs/rain-sdk/blob/main/skills/rain-data/SKILL.md Configure the Rain client. Use the minimal setup for basic on-chain reads, or provide API keys for advanced features like transaction history and analytics. ```ts import { Rain } from '@buidlrrr/rain-sdk'; // Minimal — market queries and on-chain reads const rain = new Rain({ environment: 'production' }); // Full — adds tx history, price charts, analytics, and live feeds const rain = new Rain({ environment: 'production', subgraphApiKey: 'YOUR_GRAPH_KEY', // needed for: getTransactions, getPriceHistory, getPnL, getLeaderboard wsRpcUrl: 'wss://arb-mainnet.g.alchemy.com/v2/KEY', // needed for: subscribeToMarketEvents, subscribePriceUpdates }); ``` -------------------------------- ### Portfolio Analysis Functions Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/README.md Examples of using the Rain SDK for portfolio analysis, including fetching all user positions, retrieving the Profit & Loss (PnL) for a specific market, and calculating the total portfolio value based on provided token addresses. ```typescript // Get all positions const positions = await rain.getPositions(address); // Get P&L for specific market const pnl = await rain.getPnL({ address, marketId: '698c8f116e985bbfacc7fc01' }); console.log(`Market P&L: ${pnl.formatted.totalPnL}`); // Get portfolio value const portfolio = await rain.getPortfolioValue({ address, tokenAddresses: ['0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9'] }); console.log(`Total position value: ${portfolio.totalPositionValue}`); ``` -------------------------------- ### Create, Resolve, and Claim Market Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/README.md A comprehensive example demonstrating the lifecycle of a market: building the transaction to create a market, sending it via RainAA, building and sending the transaction to resolve the market after trading ends, and finally building and sending the transaction to claim rewards. ```typescript // 1. Create market const createTxs = await rain.buildCreateMarketTx({ marketQuestion: 'Will BTC hit 100k?', marketOptions: ['Yes', 'No'], marketTags: ['crypto'], marketDescription: 'Prediction market for BTC price', isPublic: true, isPublicPoolResolverAi: false, creator: smartAccountAddress, startTime: 1770836400n, endTime: 1770922800n, no_of_options: 2n, inputAmountWei: 100_000_000n, barValues: [50, 50], baseToken: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9' }); for (const tx of createTxs) { await rainAA.sendTransaction(tx); } // 2. Wait for trading to end, then resolve const marketId = await rain.getMarketId(marketAddress); const resolveTxs = await rain.buildResolveMarketTx({ marketId, winningOption: 1 }); for (const tx of resolveTxs) { await rainAA.sendTransaction(tx); } // 3. Claim rewards const claimTx = await rain.buildClaimTx({ marketId, walletAddress: userAddress }); await rainAA.sendTransaction(claimTx); ``` -------------------------------- ### login Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/api-reference/Rain.md Authenticate wallet and get access token for protected operations. This method requires wallet details and a signature to generate an access token. ```APIDOC ## login ### Description Authenticate wallet and get access token for protected operations. This method requires wallet details and a signature to generate an access token. ### Method `async login(params: LoginParams): Promise` ### Endpoint None (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **signature** (`string`) - Yes - Signed message (personal_sign of lowercased wallet address) * **walletAddress** (`string`) - Yes - EOA wallet address * **smartWalletAddress** (`string`) - Yes - Smart account / AA wallet address * **referredBy** (`string`) - No - Optional referral code ### Request Example ```typescript import { signMessage } from 'viem'; const signature = await signMessage(client, { account: address, message: address.toLowerCase() }); const result = await rain.login({ signature, walletAddress: address, smartWalletAddress: smartAccountAddress }); console.log('Token:', result.accessToken); ``` ### Response #### Success Response (`LoginResult`) * **accessToken** (`string`) - JWT access token * **userId** (`string`) - User identifier #### Response Example ```json { "accessToken": "your_jwt_token", "userId": "user_id" } ``` ``` -------------------------------- ### Invalid Environment Configuration Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/configuration.md Shows an example of invalid configuration during SDK construction, specifically an unsupported environment value. The SDK will throw an error indicating the allowed values. ```typescript // Invalid environment const rain = new Rain({ environment: 'invalid' }); // Error: Invalid environment "invalid". Allowed values: development, stage, production ``` -------------------------------- ### Real-Time Price Updates Subscription Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/README.md Demonstrates how to subscribe to real-time price updates for a specific market using Rain. This includes setting up a callback function to handle price updates and an example of how to unsubscribe after a certain period. ```typescript const marketAddress = '0xd262abd3d58038e15736Ec32c4F7b020C2B21dB5'; const unsubscribe = rain.subscribePriceUpdates({ marketAddress, onPriceUpdate: (update) => { console.log('Prices updated:'); update.prices.forEach(p => { const percent = (Number(p.currentPrice) / 1e18) * 100; console.log(` ${p.optionName}: ${percent.toFixed(2)}%`); }); console.log(`Event: ${update.triggeredBy.eventName}`); } }); // Stop after 5 minutes setTimeout(() => unsubscribe(), 5 * 60 * 1000); ``` -------------------------------- ### Get Market ID by Address Source: https://github.com/rain1-labs/rain-sdk/blob/main/AGENTS.md Performs a reverse lookup to get the market ID from a given contract address. ```typescript const id = await rain.getMarketId('0xd262abd3d58038e15736Ec32c4F7b020C2B21dB5'); ``` -------------------------------- ### Build Create Market Transaction Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/api-reference/transaction-builders.md Builds transactions to create a new market. Returns approval and create transactions if an approval is needed. Ensure inputAmountWei is at least 10 tokens in wei, at least two options are provided, and the market end time is after the start time. ```typescript async buildCreateMarketTx(params: CreateMarketTxParams): Promise ``` ```typescript interface CreateMarketTxParams { marketQuestion: string; // Market title marketOptions: string[]; // Option names marketTags: string[]; // Category tags marketDescription: string; // Full description isPublic: boolean; isPublicPoolResolverAi: boolean; // AI oracle or manual creator: `0x${string}`; // Creator wallet startTime: bigint; // Unix timestamp (seconds) endTime: bigint; no_of_options: bigint; inputAmountWei: bigint; // Initial liquidity (min 10 tokens) barValues: number[]; // Probability distribution [50, 50] baseToken: `0x${string}`; // Token address (USDT) tokenDecimals?: number; // Optional: defaults to 6 factoryContractAddress?: `0x${string}`; apiUrl?: string; rpcUrl?: string; } ``` ```typescript const txs = await rain.buildCreateMarketTx({ marketQuestion: 'Will the Fed cut rates in Q1 2025?', marketOptions: ['Yes', 'No'], marketTags: ['macro', 'economics', 'fed'], marketDescription: 'This market resolves YES if...', isPublic: true, isPublicPoolResolverAi: true, // AI resolution creator: smartAccountAddress, startTime: 1770836400n, endTime: 1770922800n, no_of_options: 2n, inputAmountWei: 100_000_000n, // 100 USDT barValues: [50, 50], // 50-50 odds initially baseToken: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9' }); // Execute all transactions in order for (const tx of txs) { await provider.sendTransaction(tx); } ``` -------------------------------- ### Development Lifecycle Commands Source: https://github.com/rain1-labs/rain-sdk/blob/main/README.md Standard commands for building, developing, and testing the SDK. ```bash # Build cd rain-sdk && npm run build # Watch mode npm run dev # Run tests npm test # Integration tests npm run test:integration ``` -------------------------------- ### Get Current Option Prices Source: https://github.com/rain1-labs/rain-sdk/blob/main/README.md Fetch the current prices for all options within a given market. Prices are returned in Wei (1e18) and should be divided by 1e18 to get the decimal representation. ```typescript const prices = await rain.getMarketPrices('698c8f116e985bbfacc7fc01'); // Returns: OptionPrice[] // [{ choiceIndex: 0, optionName: 'Yes', currentPrice: 650000000000000000n }] // currentPrice is in 1e18 — divide by 1e18 for decimal (0.65 = 65%) ``` -------------------------------- ### GET /marketTransactions Source: https://github.com/rain1-labs/rain-sdk/blob/main/AGENTS.md Retrieves all trades that occurred on a specific market. ```APIDOC ## GET /marketTransactions ### Description Fetches all trade data for a specified market. ### Method GET ### Endpoint /marketTransactions ### Parameters #### Query Parameters - **marketAddress** (string) - Required - The address of the market to fetch trades for. - **first** (number) - Optional - The number of trades to return per page. Defaults to 50. - **skip** (number) - Optional - The number of trades to skip. ### Response #### Success Response (200) - **marketAddress** (string) - The address of the market. - **trades** (array) - An array of trade objects. Each trade object contains details like `type`, `id`, `marketAddress`, `transactionHash`, `blockNumber`, `timestamp`, `wallet`, `option`, `baseAmount`, `optionAmount`, `price`, `orderId`, `maker`, `taker`, `winnerOption`, `reward`, `liquidityReward`, `totalReward`. ### Request Example ```json { "marketAddress": "0x...", "first": 50 } ``` ### Response Example ```json { "marketAddress": "0x...", "trades": [ { "type": "buy", "id": "trade1", "marketAddress": "0x...", "transactionHash": "0xabc", "blockNumber": 123456, "timestamp": 1700000000, "wallet": "0x...", "baseAmount": 1000000000000000000, "optionAmount": 500000000000000000, "price": 2000000000000000000 } ] } ``` ``` -------------------------------- ### getMarketVolume Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/api-reference/Rain.md Get total and per-option trading volume for a given market. ```APIDOC ## GET /markets/{marketId}/volume ### Description Get total and per-option trading volume for a given market. ### Method GET ### Endpoint /markets/{marketId}/volume ### Parameters #### Path Parameters - **marketId** (string) - Required - The ID of the market to fetch volume for. ### Returns `MarketVolume` — MarketVolume with totalVolume and optionVolumes array. ### Usage ```typescript const volume = await rain.getMarketVolume('698c8f116e985bbfacc7fc01'); console.log(volume.totalVolume); ``` ``` -------------------------------- ### GET /leaderboard Source: https://github.com/rain1-labs/rain-sdk/blob/main/AGENTS.md Retrieves a list of top traders based on specified criteria. ```APIDOC ## GET /leaderboard ### Description Fetches a ranked list of top traders. This endpoint requires access to the subgraph. ### Method GET ### Endpoint /leaderboard ### Parameters #### Query Parameters - **timeframe** (string) - Required - The time period for the leaderboard. Possible values: '24h', '7d', '30d', 'all-time'. - **sortBy** (string) - Optional - The criteria to sort by. Currently only supports 'volume'. Defaults to 'volume'. - **limit** (number) - Optional - The maximum number of entries to return. Defaults to 10. ### Response #### Success Response (200) - **timeframe** (string) - The selected timeframe for the leaderboard. - **entries** (array) - An array of leaderboard entry objects. - **rank** (number) - The rank of the trader. - **address** (string) - The trader's wallet address. - **totalVolume** (bigint) - The total trading volume. - **tradesCount** (number) - The total number of trades made. - **marketsTraded** (number) - The number of unique markets traded. - **formatted** (object) - Formatted string representation of `totalVolume`. - **totalTraders** (number) - The total number of traders in the specified timeframe. - **generatedAt** (number) - Unix timestamp when the leaderboard was generated. ### Request Example ```json { "timeframe": "7d", "sortBy": "volume", "limit": 10 } ``` ### Response Example ```json { "timeframe": "7d", "entries": [ { "rank": 1, "address": "0x...", "totalVolume": 100000000000000000000, "tradesCount": 50, "marketsTraded": 5, "formatted": { "totalVolume": "100 Volume" } } ], "totalTraders": 1000, "generatedAt": 1700000000 } ``` ``` -------------------------------- ### GET /transactionDetails Source: https://github.com/rain1-labs/rain-sdk/blob/main/AGENTS.md Retrieves detailed information for a specific transaction using its hash. ```APIDOC ## GET /transactionDetails ### Description Decodes and retrieves detailed information for a single transaction identified by its hash. ### Method GET ### Endpoint /transactionDetails ### Parameters #### Query Parameters - **transactionHash** (string) - Required - The hash of the transaction to decode. ### Response #### Success Response (200) - **transactionHash** (string) - The hash of the transaction. - **blockNumber** (bigint) - The block number in which the transaction was included. - **timestamp** (bigint) - The Unix timestamp of the transaction. - **from** (string) - The sender's address. - **to** (string) - The receiver's address. - **status** (string) - The status of the transaction ('success' or 'failed'). - **gasUsed** (bigint) - The amount of gas used by the transaction. - **effectiveGasPrice** (bigint) - The effective gas price of the transaction. - **events** (array) - An array of events associated with the transaction. Each event has the same structure as a transaction object in `getTransactions`. ### Request Example ```json { "transactionHash": "0x..." } ``` ### Response Example ```json { "transactionHash": "0xabc", "blockNumber": 123456, "timestamp": 1700000000, "from": "0x...", "to": "0x...", "status": "success", "gasUsed": 21000, "effectiveGasPrice": 100000000000000000, "events": [ { "type": "buy", "id": "event1", "marketAddress": "0x...", "transactionHash": "0xabc", "blockNumber": 123456, "timestamp": 1700000000, "wallet": "0x..." } ] } ``` ``` -------------------------------- ### GET /transactions Source: https://github.com/rain1-labs/rain-sdk/blob/main/AGENTS.md Retrieves a paginated list of wallet transactions across all markets. ```APIDOC ## GET /transactions ### Description Fetches a history of wallet transactions across all markets. Supports filtering by various parameters. ### Method GET ### Endpoint /transactions ### Parameters #### Query Parameters - **address** (string) - Required - The wallet address to fetch transactions for. - **first** (number) - Optional - The number of transactions to return per page. Defaults to 20. - **skip** (number) - Optional - The number of transactions to skip. Defaults to 0. - **orderDirection** (string) - Optional - The direction to order transactions ('asc' or 'desc'). Defaults to 'desc'. - **marketAddress** (string) - Optional - Filter transactions by a specific market address. - **types** (array of strings) - Optional - Filter transactions by type. Possible values: 'buy', 'limit_buy_placed', 'limit_sell_placed', 'limit_buy_filled', 'limit_sell_filled', 'cancel_buy', 'cancel_sell', 'add_liquidity', 'claim'. - **fromTimestamp** (bigint) - Optional - Filter transactions from a specific Unix timestamp (inclusive). - **toTimestamp** (bigint) - Optional - Filter transactions up to a specific Unix timestamp (inclusive). ### Response #### Success Response (200) - **address** (string) - The requested wallet address. - **transactions** (array) - An array of transaction objects. - **type** (string) - The type of transaction. - **id** (string) - The unique ID of the transaction. - **marketAddress** (string) - The address of the market where the transaction occurred. - **transactionHash** (string) - The hash of the blockchain transaction. - **blockNumber** (bigint) - The block number of the transaction. - **timestamp** (bigint) - The Unix timestamp of the transaction. - **wallet** (string) - The wallet address associated with the transaction. - **option** (number) - Optional - The option index for certain transaction types. - **baseAmount** (bigint) - Optional - The amount of base token involved. - **optionAmount** (bigint) - Optional - The amount of option token involved. - **price** (bigint) - Optional - The price at which the transaction occurred. - **orderId** (number) - Optional - The ID of the order associated with the transaction. - **maker** (string) - Optional - The maker's address for the trade. - **taker** (string) - Optional - The taker's address for the trade. - **winnerOption** (number) - Optional - The winning option index for certain transaction types. - **reward** (bigint) - Optional - Reward amount. - **liquidityReward** (bigint) - Optional - Liquidity reward amount. - **totalReward** (bigint) - Optional - Total reward amount. - **total** (number) - The total number of transactions available for the given filters. ### Request Example ```json { "address": "0x...", "first": 20, "skip": 0, "orderDirection": "desc", "marketAddress": "0x...", "types": ["buy", "limit_buy_placed"], "fromTimestamp": 1700000000, "toTimestamp": 1710000000 } ``` ### Response Example ```json { "address": "0x...", "transactions": [ { "type": "buy", "id": "tx123", "marketAddress": "0x...", "transactionHash": "0xabc", "blockNumber": 123456, "timestamp": 1700000000, "wallet": "0x...", "option": 0, "baseAmount": 1000000000000000000, "optionAmount": 500000000000000000, "price": 2000000000000000000, "orderId": 1, "maker": "0x...", "taker": "0x...", "winnerOption": 0, "reward": 100000000000000000, "liquidityReward": 50000000000000000, "totalReward": 150000000000000000 } ], "total": 100 } ``` ``` -------------------------------- ### GET /getPublicMarkets Source: https://github.com/rain1-labs/rain-sdk/blob/main/AGENTS.md Retrieves a list of public markets with optional filtering and pagination. ```APIDOC ## GET /getPublicMarkets ### Description Browse and filter available markets on the Rain protocol. ### Method GET ### Parameters #### Query Parameters - **limit** (number) - Optional - Number of results to return - **offset** (number) - Optional - Pagination offset - **sortBy** (string) - Optional - Sorting criteria: 'Liquidity', 'Volumn', or 'latest' - **status** (string) - Optional - Market status filter: 'Live', 'New', 'WaitingForResult', 'UnderDispute', 'UnderAppeal', 'ClosingSoon', 'InReview', 'InEvaluation', 'Closed', 'Trading' - **creator** (string) - Optional - Filter by creator address ### Response #### Success Response (200) - **Market[]** (array) - List of market objects #### Response Example [ { "id": "698c8f116e985bbfacc7fc01", "title": "Market Title", "totalVolume": "1000", "status": "Live", "poolOwnerWalletAddress": "0x...", "contractAddress": "0x..." } ] ``` -------------------------------- ### Rain Constructor and Configuration Source: https://github.com/rain1-labs/rain-sdk/blob/main/AGENTS.md Initialize the Rain client with optional configuration settings. ```ts const rain = new Rain(config?: RainCoreConfig); ``` ```ts interface RainCoreConfig { environment?: 'development' | 'stage' | 'production'; // default: 'production' rpcUrl?: string; // defaults to public Arbitrum RPCs apiUrl?: string; // auto-set from environment subgraphUrl?: string; // required for tx history, price history, analytics subgraphApiKey?: string; // TheGraph API key wsRpcUrl?: string; // required for WebSocket subscriptions wsReconnect?: boolean | { attempts?: number; delay?: number }; } ``` -------------------------------- ### getEOAFromSmartAccount Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/api-reference/Rain.md Reverse lookup: get the EOA (regular account) that created a smart account. ```APIDOC ## getEOAFromSmartAccount ### Description Retrieves the Externally Owned Account (EOA) that was used to create a given smart account. ### Method `getEOAFromSmartAccount` ### Parameters #### Path Parameters - **smartAccountAddress** (`0x${string}`) - Required - The address of the smart account. #### Returns Ethereum address (`0x${string}`) of the EOA that created the smart account. ### Usage Example ```typescript const eoa = await rain.getEOAFromSmartAccount('0x...smartAccount'); ``` ``` -------------------------------- ### GET /pnl Source: https://github.com/rain1-labs/rain-sdk/blob/main/AGENTS.md Retrieves realized and unrealized Profit and Loss (PnL) data for a user. ```APIDOC ## GET /pnl ### Description Fetches realized and unrealized Profit and Loss (PnL) data for a specific user, optionally filtered by market. This endpoint requires access to the subgraph. ### Method GET ### Endpoint /pnl ### Parameters #### Query Parameters - **address** (string) - Required - The user's wallet address. - **marketAddress** (string) - Optional - The address of the market to filter PnL data. If omitted, aggregate PnL across all markets is returned. ### Response #### Success Response (200) - **address** (string) - The user's wallet address. - **markets** (array) - An array of market PnL objects. - **marketId** (string) - The ID of the market. - **title** (string) - The title of the market. - **status** (string) - The status of the market. - **contractAddress** (string) - The contract address of the market. - **baseTokenDecimals** (number) - The number of decimals for the base token. - **options** (array) - An array of option PnL objects for the market. - **choiceIndex** (number) - The index of the option. - **optionName** (string) - The name of the option. - **buyShares** (bigint) - Shares bought. - **buyCost** (bigint) - Cost of shares bought. - **sellShares** (bigint) - Shares sold. - **sellProceeds** (bigint) - Proceeds from shares sold. - **currentShares** (bigint) - Current shares held. - **currentValue** (bigint) - Current value of held shares. - **costBasis** (bigint) - Cost basis of held shares. - **realizedPnL** (bigint) - Realized PnL for the option. - **unrealizedPnL** (bigint) - Unrealized PnL for the option. - **formatted** (object) - Formatted string representations of PnL fields. - **claimed** (boolean) - Whether rewards have been claimed. - **claimReward** (bigint) - The amount of reward available to claim. - **liquidityCost** (bigint) - Cost associated with liquidity provision. - **liquidityReward** (bigint) - Reward from liquidity provision. - **totalCostBasis** (bigint) - Total cost basis for the market. - **totalCurrentValue** (bigint) - Total current value for the market. - **realizedPnL** (bigint) - Total realized PnL for the market. - **unrealizedPnL** (bigint) - Total unrealized PnL for the market. - **totalPnL** (bigint) - Total PnL for the market. - **formatted** (object) - Formatted string representations of PnL fields. - **totalRealizedPnL** (bigint) - Aggregate realized PnL across all markets. - **totalUnrealizedPnL** (bigint) - Aggregate unrealized PnL across all markets. - **totalPnL** (bigint) - Aggregate total PnL across all markets. - **formatted** (object) - Formatted string representations of aggregate PnL fields. ### Request Example ```json { "address": "0x...", "marketAddress": "0x..." } ``` ### Response Example ```json { "address": "0x...", "markets": [ { "marketId": "market1", "title": "Market Title", "status": "active", "contractAddress": "0x...", "baseTokenDecimals": 18, "options": [ { "choiceIndex": 0, "optionName": "Option A", "buyShares": 100, "buyCost": 1000000000000000000, "sellShares": 0, "sellProceeds": 0, "currentShares": 100, "currentValue": 1200000000000000000, "costBasis": 1000000000000000000, "realizedPnL": 50000000000000000, "unrealizedPnL": 200000000000000000, "formatted": {} } ], "claimed": false, "claimReward": 0, "liquidityCost": 0, "liquidityReward": 0, "totalCostBasis": 1000000000000000000, "totalCurrentValue": 1200000000000000000, "realizedPnL": 50000000000000000, "unrealizedPnL": 200000000000000000, "totalPnL": 250000000000000000, "formatted": {} } ], "totalRealizedPnL": 50000000000000000, "totalUnrealizedPnL": 200000000000000000, "totalPnL": 250000000000000000, "formatted": { "totalRealizedPnL": "50 PNL", "totalUnrealizedPnL": "200 PNL", "totalPnL": "250 PNL" } } ``` ``` -------------------------------- ### GET /tradeHistory Source: https://github.com/rain1-labs/rain-sdk/blob/main/AGENTS.md Retrieves a specific user's trade history on a particular market. ```APIDOC ## GET /tradeHistory ### Description Fetches the trade history for a given user address on a specific market. ### Method GET ### Endpoint /tradeHistory ### Parameters #### Query Parameters - **address** (string) - Required - The user's wallet address. - **marketAddress** (string) - Required - The address of the market. ### Response #### Success Response (200) - **address** (string) - The user's wallet address. - **marketAddress** (string) - The market address. - **history** (array) - An array of trade objects for the user on the specified market. Each trade object contains details like `type`, `id`, `marketAddress`, `transactionHash`, `blockNumber`, `timestamp`, `wallet`, `option`, `baseAmount`, `optionAmount`, `price`, `orderId`, `maker`, `taker`, `winnerOption`, `reward`, `liquidityReward`, `totalReward`. ### Request Example ```json { "address": "0x...", "marketAddress": "0x..." } ``` ### Response Example ```json { "address": "0x...", "marketAddress": "0x...", "history": [ { "type": "buy", "id": "trade1", "marketAddress": "0x...", "transactionHash": "0xabc", "blockNumber": 123456, "timestamp": 1700000000, "wallet": "0x...", "baseAmount": 1000000000000000000, "optionAmount": 500000000000000000, "price": 2000000000000000000 } ] } ``` ``` -------------------------------- ### Initialize RainAA (Smart Account) Source: https://github.com/rain1-labs/rain-sdk/blob/main/skills/rain-trade/SKILL.md Initialize the RainAA SDK for gas-sponsored transactions. Requires a wallet client, Alchemy API key, paymaster policy ID, and the chain. ```typescript import { RainAA } from '@buidlrrr/rain-sdk'; const rainAA = new RainAA({ walletClient, alchemyApiKey: '...', paymasterPolicyId: '...', chain: arbitrum, }); const smartAddr = await rainAA.connect(); ``` -------------------------------- ### Get Position by Market Source: https://github.com/rain1-labs/rain-sdk/blob/main/AGENTS.md Fetches the position details for a specific wallet on a particular market. ```typescript const pos = await rain.getPositionByMarket('0x...' as `0x${string}`, '698c8f116e985bbfacc7fc01'); ``` -------------------------------- ### Initialize Rain and RainAA with Environment Variables Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/configuration.md Demonstrates how to use environment variables for SDK configuration, specifically for subgraph API keys, Alchemy API keys, and paymaster policy IDs. ```typescript // Usage const rain = new Rain({ environment: 'production', subgraphApiKey: process.env.GRAPH_API_KEY }); const rainAA = new RainAA({ alchemyApiKey: process.env.ALCHEMY_API_KEY, paymasterPolicyId: process.env.PAYMASTER_POLICY_ID, // ... other config }); ``` -------------------------------- ### Get Positions for a Wallet Source: https://github.com/rain1-labs/rain-sdk/blob/main/AGENTS.md Retrieves all positions across all markets for a given wallet address. ```typescript const positions = await rain.getPositions('0x...' as `0x${string}`); ``` -------------------------------- ### Build Close and Choose Winner Transactions (Step-by-Step) Source: https://github.com/rain1-labs/rain-sdk/blob/main/skills/rain-create-market/SKILL.md Alternatively, close a market and choose the winner using separate transactions: `buildCloseMarketTx` and `buildChooseWinnerTx`. Remember that `winningOption` is 1-indexed. ```typescript const closeTx = await rain.buildCloseMarketTx({ marketId: '...' }); const winnerTx = await rain.buildChooseWinnerTx({ marketId: '...', winningOption: 1 }); ``` -------------------------------- ### Get Market Address Source: https://github.com/rain1-labs/rain-sdk/blob/main/AGENTS.md Looks up the on-chain contract address for a given market ID. ```typescript const address = await rain.getMarketAddress('698c8f116e985bbfacc7fc01'); ``` -------------------------------- ### getMarketLiquidity Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/api-reference/Rain.md Get AMM liquidity pools and order book depths per option for a given market. ```APIDOC ## GET /markets/{marketId}/liquidity ### Description Get AMM liquidity pools and order book depths per option for a given market. ### Method GET ### Endpoint /markets/{marketId}/liquidity ### Parameters #### Path Parameters - **marketId** (string) - Required - The ID of the market to fetch liquidity for. ### Returns `MarketLiquidity` — MarketLiquidity with totalLiquidity and optionLiquidity array including bid/ask prices. ### Usage ```typescript const liq = await rain.getMarketLiquidity('698c8f116e985bbfacc7fc01'); liq.optionLiquidity.forEach(opt => { console.log(`${opt.optionName}: buy @ ${opt.firstBuyOrderPrice}, sell @ ${opt.firstSellOrderPrice}`); }); ``` ``` -------------------------------- ### Constructor Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/api-reference/Rain.md Initializes the Rain SDK. It can be configured with environment-specific settings for RPC, API, and WebSocket endpoints. ```APIDOC ## Constructor Rain ### Description Initializes the Rain SDK. It can be configured with environment-specific settings for RPC, API, and WebSocket endpoints. ### Signature ```typescript constructor(config?: RainCoreConfig): Rain ``` ### Parameters #### Constructor Parameters - **environment** (string) - Optional - Environment to connect to. Defaults to 'development'. - **rpcUrl** (string) - Optional - RPC endpoint for on-chain reads (Arbitrum One). Defaults to auto-selected public RPC. - **apiUrl** (string) - Optional - Rain backend API endpoint. Defaults to environment-specific. - **subgraphUrl** (string) - Optional - The Graph subgraph endpoint (required for history/analytics). Defaults to environment-specific. - **subgraphApiKey** (string) - Optional - The Graph API key for authentication. - **wsRpcUrl** (string) - Optional - WebSocket RPC for live event subscriptions. - **wsReconnect** (boolean | { attempts?: number; delay?: number }) - Optional - Auto-reconnect config for WebSocket. ### Usage ```typescript import { Rain } from '@buidlrrr/rain-sdk'; const rain = new Rain({ environment: 'production', rpcUrl: 'https://arb1.arbitrum.io/rpc', wsRpcUrl: 'wss://arbitrum-one-rpc.publicnode.com' }); ``` ``` -------------------------------- ### Handle Missing Configuration Errors Source: https://github.com/rain1-labs/rain-sdk/blob/main/_autodocs/configuration.md Illustrates how the SDK throws errors for missing required configuration and how to fix them by providing the necessary parameters in the constructor or method calls. ```typescript const rain = new Rain(); // Error: subgraphUrl is required — pass it in the Rain constructor config or in the method params await rain.getTransactions({ address: '0x...' }); // Fix: provide subgraphUrl const rain2 = new Rain({ environment: 'production', subgraphUrl: 'https://...' }); await rain2.getTransactions({ address: '0x...' }); // Or: await rain.getTransactions({ address: '0x...', subgraphUrl: 'https://...' }); ``` -------------------------------- ### Get Protocol Statistics Source: https://github.com/rain1-labs/rain-sdk/blob/main/README.md Retrieves overall protocol metrics. Use this to monitor the health and scale of the platform. ```typescript const stats = await rain.getProtocolStats(); // Returns: ProtocolStats // { tvl, totalVolume, activeMarkets, totalMarkets, uniqueTraders } ```