### Complete Trading Flow Integration (TypeScript) Source: https://context7.com/0xprobable/clob-examples/llms.txt Orchestrates a complete trading flow, starting from wallet setup, token approvals, balance checks, API key creation, order management, and finally placing a new order. This script imports and calls various step functions to achieve the full workflow. ```typescript import { account } from './setup/clients'; import { step1_createProxyWallet } from './steps/step1-create-proxy'; import { step2_approveTokens } from './steps/step2-approve-tokens'; import { step3_checkUSDTBalance } from './steps/step3-check-balance'; import { step4_createOrLoadApiKey } from './steps/step4-api-key'; import { step5_getOpenOrders } from './steps/step5-get-orders'; import { step6_cancelOrders } from './steps/step6-cancel-orders'; import { step7_placeOrder } from './steps/step7-place-order'; async function main(): Promise { console.log('EOA Address:', account.address); console.log('Network: BSC Mainnet'); // Step 1: Create or get existing proxy wallet const proxyAddress = await step1_createProxyWallet(); console.log('Proxy Address:', proxyAddress); // Step 2: Approve USDT and CTF tokens for trading await step2_approveTokens(proxyAddress); // Step 3: Verify USDT balance in proxy wallet await step3_checkUSDTBalance(proxyAddress); // Step 4: Create or load API key for authentication const apiKey = await step4_createOrLoadApiKey(proxyAddress); // Step 5: Get all open orders const orders = await step5_getOpenOrders(proxyAddress, apiKey); // Step 6: Cancel any existing open orders await step6_cancelOrders(proxyAddress, orders); // Step 7: Place a new buy order (requires CTF_TOKEN_ID in .env) await step7_placeOrder(proxyAddress); console.log('All steps completed successfully!'); } // Run with: bun run index.ts main().catch(console.error); ``` -------------------------------- ### GET /public/api/v1/orders/:chainId/open Source: https://context7.com/0xprobable/clob-examples/llms.txt Retrieves all open orders for the authenticated user from the Probable Markets API. ```APIDOC ## GET /public/api/v1/orders/:chainId/open ### Description Retrieves all open orders for the authenticated user from the Probable Markets API. ### Method GET ### Endpoint `/public/api/v1/orders/:chainId/open` ### Parameters #### Path Parameters - **chainId** (number) - Required - The chain ID of the network. #### Query Parameters - **page** (number) - Optional - The page number for pagination. - **limit** (number) - Optional - The number of orders per page. #### Request Body None ### Request Example ```http GET /public/api/v1/orders/56/open?page=1&limit=20 HTTP/1.1 Host: api.probable.markets prob_address: 0x... prob_signature: ... prob_timestamp: 1678886400 prob_api_key: ... prob_passphrase: ... ``` ### Response #### Success Response (200) - **orders** (array) - An array of open order objects. - **orderId** (number) - The ID of the order. - **clientOrderId** (string) - The client-provided order ID. - **symbol** (string) - The trading symbol. - **side** (string) - The side of the order ('BUY' or 'SELL'). - **price** (string) - The order price. - **origQty** (string) - The original quantity of the order. - **executedQty** (string) - The executed quantity of the order. - **status** (string) - The status of the order. - **tokenId** (string) - The ID of the token. - **ctfTokenId** (string) - The CTF token ID. #### Response Example ```json { "orders": [ { "orderId": 123, "clientOrderId": "...", "symbol": "...", "side": "BUY", "price": "0.10", "origQty": "10", "executedQty": "0", "status": "OPEN", "tokenId": "...", "ctfTokenId": "..." } ] } ``` ``` -------------------------------- ### Execute Safe Transaction using Safe Protocol Kit (TypeScript) Source: https://context7.com/0xprobable/clob-examples/llms.txt Executes batched transactions through a Gnosis Safe proxy wallet using the Safe Protocol Kit. It initializes the ProtocolKit with provider, signer, and safe address, then creates and executes a safe transaction. ```typescript import Safe from '@safe-global/protocol-kit'; import type { MetaTransactionData } from '@safe-global/types-kit'; async function executeSafeTransaction( safeAddress: `0x${string}`, transactions: MetaTransactionData[] ): Promise<`0x${string}`> { const protocolKit = await Safe.init({ provider: 'https://bscrpc.pancakeswap.finance', signer: privateKey, safeAddress: safeAddress, }); const safeTransaction = await protocolKit.createTransaction({ transactions }); const executeTxResponse = await protocolKit.executeTransaction(safeTransaction); return executeTxResponse.hash as `0x${string}`; } // Usage: Batch multiple token approvals const transactions: MetaTransactionData[] = [ { to: '0x55d398326f99059fF775485246999027B3197955', // USDT data: encodeFunctionData({ abi: ERC20_ABI, functionName: 'approve', args: [spender, maxUint256] }), value: '0', }, { to: '0x364d05055614B506e2b9A287E4ac34167204cA83', // CTF Token data: encodeFunctionData({ abi: ERC1155_ABI, functionName: 'setApprovalForAll', args: [operator, true] }), value: '0', }, ]; const txHash = await executeSafeTransaction(proxyAddress, transactions); // Output: 0xabc123... (transaction hash) ``` -------------------------------- ### Create Proxy Wallet with EIP-712 Signature (TypeScript) Source: https://context7.com/0xprobable/clob-examples/llms.txt Generates a Gnosis Safe proxy wallet address for a user and creates it on the blockchain if it doesn't exist. It uses EIP-712 signatures for transaction authorization, handling payment details and signature parsing for the `createProxy` function. ```typescript import { getContract } from 'viem'; import { PROXY_FACTORY_ADDRESS, PROXY_FACTORY_ABI } from './config'; async function createProxyWallet(userAddress: `0x${string}`): Promise<`0x${string}`> { const proxyFactory = getContract({ address: PROXY_FACTORY_ADDRESS, abi: PROXY_FACTORY_ABI, client: { public: publicClient, wallet: walletClient }, }); // Check if proxy already exists const proxyAddress = await proxyFactory.read.computeProxyAddress([userAddress]); const code = await publicClient.getBytecode({ address: proxyAddress }); if (code && code !== '0x') { console.log('Proxy already exists:', proxyAddress); return proxyAddress; } // Generate EIP-712 signature for proxy creation const paymentToken = '0x0000000000000000000000000000000000000000' as `0x${string}`; const payment = 0n; const paymentReceiver = '0x0000000000000000000000000000000000000000' as `0x${string}`; const domain = { name: 'Probable Contract Proxy Factory', chainId: 56, verifyingContract: PROXY_FACTORY_ADDRESS, }; const types = { CreateProxy: [ { name: 'paymentToken', type: 'address' }, { name: 'payment', type: 'uint256' }, { name: 'paymentReceiver', type: 'address' }, ], }; const signature = await walletClient.signTypedData({ account, domain, types, primaryType: 'CreateProxy', message: { paymentToken, payment, paymentReceiver }, }); // Parse signature into v, r, s components const r = `0x${signature.slice(2, 66)}` as `0x${string}`; const s = `0x${signature.slice(66, 130)}` as `0x${string}`; let v = parseInt(signature.slice(130, 132), 16); if (v < 27) v += 27; // Create the proxy wallet const hash = await proxyFactory.write.createProxy([ paymentToken, payment, paymentReceiver, { v, r, s } ]); await publicClient.waitForTransactionReceipt({ hash }); return proxyAddress; } // Usage const proxyAddress = await createProxyWallet(account.address); // Output: 0x1234...abcd (proxy wallet address) ``` -------------------------------- ### POST /public/api/v1/order/:chainId Source: https://context7.com/0xprobable/clob-examples/llms.txt Creates a signed order and submits it to the Probable Markets exchange with HMAC authentication. ```APIDOC ## POST /public/api/v1/order/:chainId ### Description Creates a signed order and submits it to the Probable Markets exchange with HMAC authentication. ### Method POST ### Endpoint `/public/api/v1/order/:chainId` ### Parameters #### Path Parameters - **chainId** (number) - Required - The chain ID of the network. #### Query Parameters None #### Request Body - **deferExec** (boolean) - Required - Whether to defer execution. - **order** (object) - Required - The order details. - **side** (string) - Required - The side of the order ('BUY' or 'SELL'). - **signature** (string) - Required - The EIP-712 signature of the order. - **owner** (string) - Required - The address of the order owner. - **orderType** (string) - Required - The type of order (e.g., 'GTC'). ### Request Example ```json { "deferExec": true, "order": { "salt": "...", "maker": "0x...", "signer": "0x...", "taker": "0x0000000000000000000000000000000000000000", "tokenId": "123", "makerAmount": "10000000000000000000", "takerAmount": "1000000000000000000", "expiration": "0", "nonce": "0", "feeRateBps": "0", "side": "BUY", "signatureType": 2, "signature": "0x..." }, "owner": "0x...", "orderType": "GTC" } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the submitted order. - **status** (string) - The status of the order (e.g., 'OPEN'). #### Response Example ```json { "id": "order-789", "status": "OPEN", "..." } ``` ``` -------------------------------- ### Initialize Blockchain Clients with Viem (TypeScript) Source: https://context7.com/0xprobable/clob-examples/llms.txt Sets up blockchain clients for interacting with Binance Smart Chain (BSC) using Viem. Requires private key and optional RPC URL from environment variables. Configures network details including chain ID, proxy factory, token addresses, and API endpoint. ```typescript import { createWalletClient, createPublicClient, http } from 'viem'; import { privateKeyToAccount } from 'viem/accounts'; import { bsc } from 'viem/chains'; // Environment variables required: // PRIVATE_KEY=0x... (64-character hex string) // RPC_URL=https://bsc-dataseed1.binance.org/ (optional) // CTF_TOKEN_ID=... (required for trading) const privateKey = process.env.PRIVATE_KEY as `0x${string}`; const account = privateKeyToAccount(privateKey); const publicClient = createPublicClient({ chain: bsc, transport: http(process.env.RPC_URL), }); const walletClient = createWalletClient({ account, chain: bsc, transport: http('https://bscrpc.pancakeswap.finance'), }); // Network configuration const NETWORK_CONFIG = { chainId: 56, name: 'BSC Mainnet', proxyFactoryAddress: '0xB99159aBF0bF59a512970586F38292f8b9029924', usdtAddress: '0x55d398326f99059fF775485246999027B3197955', ctfTokenAddress: '0x364d05055614B506e2b9A287E4ac34167204cA83', ctfExchangeAddress: '0xF99F5367ce708c66F0860B77B4331301A5597c86', entryService: 'https://api.probable.markets', }; ``` -------------------------------- ### Fetch Available Markets (Bash) Source: https://context7.com/0xprobable/clob-examples/llms.txt Fetches active prediction market events and their token IDs from the Probable Markets API using a simple curl command. The response is a JSON object containing a list of events, each with its title and associated markets. ```bash # Get all active events curl "https://market-api.probable.markets/public/api/v1/events?active=true" # Response structure: # { # "events": [{ # "id": "event-123", # "title": "Will BTC reach $100k?", # "markets": [{ # "id": "market-456", # "tokens": [ # { "token_id": "94480968951305741611959068661572376473445324604113916072487458356172146839804", "outcome": "Yes" }, # { "token_id": "1234567890123456789012345678901234567890123456789012345678901234567", "outcome": "No" } # ] # }] # }] # } ``` -------------------------------- ### Get Open Orders with HMAC Auth (TypeScript) Source: https://context7.com/0xprobable/clob-examples/llms.txt Retrieves all open orders for the authenticated user from the Probable Markets API using HMAC authentication. It requires API credentials and optionally an account type. The function returns an array of ApiOrder objects. ```typescript interface ApiOrder { orderId: number; clientOrderId: string; symbol: string; side: 'BUY' | 'SELL'; price: string; origQty: string; executedQty: string; status: string; tokenId: string; ctfTokenId: string; } async function getOpenOrders(apiKey: ApiKeyCreds, accountType?: 'eoa'): Promise { const timestamp = Math.floor(Date.now() / 1000); const path = '/public/api/v1/orders/56/open?page=1&limit=20'; // HMAC signature for GET request (no body) const hmacMessage = `${timestamp}GET${path}`; const hmac = crypto.createHmac('sha256', Buffer.from(apiKey.secret, 'base64')); const signature = hmac.update(hmacMessage).digest('base64') .replace(/\+/g, '-').replace(/\//g, '_'); const headers: Record = { prob_address: account.address, prob_signature: signature, prob_timestamp: timestamp.toString(), prob_api_key: apiKey.key, prob_passphrase: apiKey.passphrase, }; // Add account type header for EOA accounts if (accountType === 'eoa') { headers['PROB_ACCOUNT_TYPE'] = 'eoa'; } const response = await axios.get(`https://api.probable.markets${path}`, { headers }); return response.data.orders || []; } // Usage const orders = await getOpenOrders(apiKey); // Output: [{ orderId: 123, side: "BUY", price: "0.10", status: "OPEN", ... }] ``` -------------------------------- ### Create API Key with EIP-712 Signature (TypeScript) Source: https://context7.com/0xprobable/clob-examples/llms.txt Creates an API key for authenticated access to the Probable Markets trading API. It uses EIP-712 signed authentication by constructing a typed message and signing it with the provided wallet client. Dependencies include axios. ```typescript import axios from 'axios'; interface ApiKeyCreds { key: string; secret: string; passphrase: string; } async function createApiKey(wallet: WalletClient): Promise { const timestamp = Math.floor(Date.now() / 1000); const nonce = 0; const chainId = 56; // Build EIP-712 signature for authentication const domain = { name: 'ClobAuthDomain', version: '1', chainId }; const types = { ClobAuth: [ { name: 'address', type: 'address' }, { name: 'timestamp', type: 'string' }, { name: 'nonce', type: 'uint256' }, { name: 'message', type: 'string' }, ], }; const message = { address: wallet.account.address, timestamp: `${timestamp}`, nonce, message: 'This message attests that I control the given wallet', }; const signature = await wallet.signTypedData({ domain, types, primaryType: 'ClobAuth', message }); const headers = { PROB_ADDRESS: wallet.account.address, PROB_SIGNATURE: signature, PROB_TIMESTAMP: `${timestamp}`, PROB_NONCE: `${nonce}`, }; const response = await axios.post( `https://api.probable.markets/public/api/v1/auth/api-key/${chainId}`, {}, { headers } ); return { key: response.data.apiKey, secret: response.data.secret, passphrase: response.data.passphrase, }; } // Usage const apiKey = await createApiKey(walletClient); // Output: { key: "abc123...", secret: "xyz789...", passphrase: "pass..." } ``` -------------------------------- ### Create and Submit Order with HMAC Auth (TypeScript) Source: https://context7.com/0xprobable/clob-examples/llms.txt Creates a signed order using EIP-712 and submits it to the Probable Markets exchange. It utilizes HMAC authentication for API requests, requiring wallet client, API credentials, and order details. The function returns void upon successful submission. ```typescript import * as crypto from 'crypto'; enum Side { BUY = 0, SELL = 1 } enum SignatureType { EOA = 0, PROB_GNOSIS_SAFE = 2 } interface UserOrder { tokenID: string; price: number; size: number; side: Side; feeRateBps?: number; nonce?: number; } async function createAndSubmitOrder( wallet: WalletClient, makerAddress: `0x${string}`, apiKey: ApiKeyCreds, tokenID: string, side: Side, price: number, size: number ): Promise { // Calculate order amounts const makerAmount = (side === Side.BUY ? size * price : size) * 1e18; const takerAmount = (side === Side.BUY ? size : size * price) * 1e18; // Build order data const orderData = { salt: BigInt(Math.floor(Math.random() * 1e18)).toString(), maker: makerAddress, signer: wallet.account.address, taker: '0x0000000000000000000000000000000000000000', tokenId: tokenID, makerAmount: makerAmount.toString(), takerAmount: takerAmount.toString(), expiration: '0', nonce: '0', feeRateBps: '0', side: side, signatureType: SignatureType.PROB_GNOSIS_SAFE, }; // Sign order with EIP-712 const orderSignature = await wallet.signTypedData({ domain: { name: 'Probable CTF Exchange', version: '1', chainId: 56, verifyingContract: CTF_EXCHANGE_ADDRESS, }, types: { Order: [ { name: 'salt', type: 'uint256' }, { name: 'maker', type: 'address' }, { name: 'signer', type: 'address' }, { name: 'taker', type: 'address' }, { name: 'tokenId', type: 'uint256' }, { name: 'makerAmount', type: 'uint256' }, { name: 'takerAmount', type: 'uint256' }, { name: 'expiration', type: 'uint256' }, { name: 'nonce', type: 'uint256' }, { name: 'feeRateBps', type: 'uint256' }, { name: 'side', type: 'uint8' }, { name: 'signatureType', type: 'uint8' }, ], }, primaryType: 'Order', message: orderData, }); // Create HMAC signature for API authentication const timestamp = Math.floor(Date.now() / 1000); const path = '/public/api/v1/order/56'; const requestBody = { deferExec: true, order: { ...orderData, side: side === 0 ? 'BUY' : 'SELL', signature: orderSignature }, owner: wallet.account.address, orderType: 'GTC', }; const bodyString = JSON.stringify(requestBody); const hmacMessage = `${timestamp}POST${path}${bodyString}`; const hmac = crypto.createHmac('sha256', Buffer.from(apiKey.secret, 'base64')); const signature = hmac.update(hmacMessage).digest('base64') .replace(/\+/g, '-').replace(/\//g, '_'); const headers = { prob_address: wallet.account.address, prob_signature: signature, prob_timestamp: timestamp.toString(), prob_api_key: apiKey.key, prob_passphrase: apiKey.passphrase, 'Content-Type': 'application/json', }; const response = await axios.post(`https://api.probable.markets${path}`, requestBody, { headers }); console.log('Order submitted:', response.data); } // Usage: Place a BUY order at $0.10 for 10 shares await createAndSubmitOrder(walletClient, proxyAddress, apiKey, CTF_TOKEN_ID, Side.BUY, 0.10, 10); // Output: Order submitted: { id: "order-789", status: "OPEN", ... } ``` -------------------------------- ### Approve ERC20 and ERC1155 Tokens for Trading with Safe (TypeScript) Source: https://context7.com/0xprobable/clob-examples/llms.txt Approves USDT (ERC-20) and CTF tokens (ERC-1155) for trading on the exchange. It first checks existing approvals using multicall and then creates a batched Safe transaction to grant necessary permissions. Dependencies include viem and Safe SDK. ```typescript import { encodeFunctionData, maxUint256 } from 'viem'; import Safe from '@safe-global/protocol-kit'; import type { MetaTransactionData } from '@safe-global/types-kit'; const ERC20_ABI = [ 'function allowance(address owner, address spender) view returns (uint256)', 'function approve(address spender, uint256 amount) returns (bool)', ]; const ERC1155_ABI = [ 'function isApprovedForAll(address account, address operator) view returns (bool)', 'function setApprovalForAll(address operator, bool approved)', ]; async function approveTokens(proxyAddress: `0x${string}`): Promise { // Check existing approvals using multicall const results = await publicClient.multicall({ contracts: [ { address: USDT_ADDRESS, abi: ERC20_ABI, functionName: 'allowance', args: [proxyAddress, CTF_TOKEN_ADDRESS] }, { address: USDT_ADDRESS, abi: ERC20_ABI, functionName: 'allowance', args: [proxyAddress, CTF_EXCHANGE_ADDRESS] }, { address: CTF_TOKEN_ADDRESS, abi: ERC1155_ABI, functionName: 'isApprovedForAll', args: [proxyAddress, CTF_EXCHANGE_ADDRESS] }, ], }); const transactions: MetaTransactionData[] = []; // Add USDT approval for CTF token if needed if (results[0].result < maxUint256) { transactions.push({ to: USDT_ADDRESS, data: encodeFunctionData({ abi: ERC20_ABI, functionName: 'approve', args: [CTF_TOKEN_ADDRESS, maxUint256] }), value: '0', }); } // Add USDT approval for exchange if needed if (results[1].result < maxUint256) { transactions.push({ to: USDT_ADDRESS, data: encodeFunctionData({ abi: ERC20_ABI, functionName: 'approve', args: [CTF_EXCHANGE_ADDRESS, maxUint256] }), value: '0', }); } // Add CTF token approval for exchange if needed if (!results[2].result) { transactions.push({ to: CTF_TOKEN_ADDRESS, data: encodeFunctionData({ abi: ERC1155_ABI, functionName: 'setApprovalForAll', args: [CTF_EXCHANGE_ADDRESS, true] }), value: '0', }); } if (transactions.length === 0) return; // Execute batch transaction via Safe SDK const protocolKit = await Safe.init({ provider: 'https://bscrpc.pancakeswap.finance', signer: privateKey, safeAddress: proxyAddress, }); const safeTransaction = await protocolKit.createTransaction({ transactions }); const result = await protocolKit.executeTransaction(safeTransaction); await publicClient.waitForTransactionReceipt({ hash: result.hash }); } ``` -------------------------------- ### Cancel Order using Probable Markets API (TypeScript) Source: https://context7.com/0xprobable/clob-examples/llms.txt Cancels an open order by its ID using the Probable Markets API. It requires API credentials, the order ID, and a token ID. The function generates an HMAC signature for authentication and uses axios to send a DELETE request. ```typescript async function cancelOrder(apiKey: ApiKeyCreds, orderId: number, tokenId: string): Promise { const timestamp = Math.floor(Date.now() / 1000); const path = `/public/api/v1/order/56/${orderId}?tokenId=${tokenId}`; // HMAC signature for DELETE request const hmacMessage = `${timestamp}DELETE${path}`; const hmac = crypto.createHmac('sha256', Buffer.from(apiKey.secret, 'base64')); const signature = hmac.update(hmacMessage).digest('base64') .replace(/\+/g, '-').replace(/\//g, '_'); const headers = { prob_address: account.address, prob_signature: signature, prob_timestamp: timestamp.toString(), prob_api_key: apiKey.key, prob_passphrase: apiKey.passphrase, }; await axios.delete(`https://api.probable.markets${path}`, { headers }); console.log(`Order ${orderId} cancelled successfully`); } // Usage await cancelOrder(apiKey, 123, '94480968951305741611959068661572376473445324604113916072487458356172146839804'); // Output: Order 123 cancelled successfully ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.