### Install TxLINE dependencies Source: https://txline.txodds.com/documentation/worldcup Install the required Solana and utility packages via npm. ```bash npm install @coral-xyz/anchor @solana/web3.js @solana/spl-token axios tweetnacl ``` -------------------------------- ### Install dependencies Source: https://txline.txodds.com/documentation/examples/devnet-examples Install project dependencies from the repository root using yarn. ```bash yarn install ``` -------------------------------- ### GET /api/fixtures/snapshot Source: https://txline.txodds.com/documentation/examples/fetching-snapshots Retrieves a snapshot of fixtures. Can be filtered by competition ID or return all fixtures. ```APIDOC ## GET /api/fixtures/snapshot ### Description Retrieves a list of fixtures. Optionally filter by competition. ### Method GET ### Endpoint /api/fixtures/snapshot ### Parameters #### Query Parameters - **competitionId** (number) - Optional - The ID of the competition to filter fixtures by. ``` -------------------------------- ### GET /api/scores/historical/{fixtureId} Source: https://txline.txodds.com/documentation/examples/streaming-data Fetches the complete sequence of score updates for a fixture that started between two weeks and six hours ago. ```APIDOC ## GET /api/scores/historical/{fixtureId} ### Description Fetch the complete sequence of score updates for a fixture that started between two weeks and six hours ago. ### Method GET ### Endpoint /api/scores/historical/{fixtureId} ### Parameters #### Path Parameters - **fixtureId** (integer) - Required - The unique identifier of the fixture. ### Request Example GET /api/scores/historical/17952170 ### Response #### Success Response (200) - **data** (array) - A list of score update objects containing sequence, timestamp, and game state information. ``` -------------------------------- ### GET /api/odds/snapshot/{fixtureId} Source: https://txline.txodds.com/documentation/examples/fetching-snapshots Retrieves odds data for a specific fixture. ```APIDOC ## GET /api/odds/snapshot/{fixtureId} ### Description Retrieves odds data for a specific fixture. ### Method GET ### Endpoint /api/odds/snapshot/{fixtureId} ### Parameters #### Path Parameters - **fixtureId** (number) - Required - The unique identifier of the fixture. ``` -------------------------------- ### GET /api/scores/snapshot/{fixtureId} Source: https://txline.txodds.com/documentation/examples/fetching-snapshots Retrieves a scores snapshot for a specific fixture. ```APIDOC ## GET /api/scores/snapshot/{fixtureId} ### Description Retrieves a scores snapshot for a specific fixture. ### Method GET ### Endpoint /api/scores/snapshot/{fixtureId} ### Parameters #### Path Parameters - **fixtureId** (number) - Required - The unique identifier of the fixture. ``` -------------------------------- ### GET /api/odds/updates/{epochDay}/{hourOfDay}/{interval} Source: https://txline.txodds.com/documentation/examples/fetching-snapshots Retrieves odds updates for a specific time period. ```APIDOC ## GET /api/odds/updates/{epochDay}/{hourOfDay}/{interval} ### Description Retrieves odds updates for a specific time period defined by epoch day, hour, and interval. ### Method GET ### Endpoint /api/odds/updates/{epochDay}/{hourOfDay}/{interval} ### Parameters #### Path Parameters - **epochDay** (number) - Required - The epoch day. - **hourOfDay** (number) - Required - The hour of the day. - **interval** (number) - Required - The time interval. ``` -------------------------------- ### GET /api/scores/stream Source: https://txline.txodds.com/documentation/examples/onchain-validation Establishes a Server-Sent Events (SSE) connection to receive real-time score updates. ```APIDOC ## GET /api/scores/stream ### Description Subscribes to a stream of real-time score updates using Server-Sent Events (SSE). ### Method GET ### Endpoint https://txline.txodds.com/api/scores/stream ### Headers - **Authorization** (string) - Required - Bearer token for authentication. - **X-Api-Token** (string) - Required - API token for service access. - **Accept** (string) - Required - Must be set to "text/event-stream". - **Cache-Control** (string) - Required - Should be set to "no-cache". ``` -------------------------------- ### GET /api/scores/updates/{fixtureId} Source: https://txline.txodds.com/documentation/examples/fetching-snapshots Retrieves live scores updates for a specific fixture. ```APIDOC ## GET /api/scores/updates/{fixtureId} ### Description Retrieves live scores updates for a specific fixture. ### Method GET ### Endpoint /api/scores/updates/{fixtureId} ### Parameters #### Path Parameters - **fixtureId** (number) - Required - The unique identifier of the fixture. ``` -------------------------------- ### GET /scores/stat-validation (V2) Source: https://txline.txodds.com/documentation/examples/devnet-examples Validates multiple statistics using indexed predicates and multi-leg strategies. ```APIDOC ## GET /scores/stat-validation ### Description Performs multi-stat validation with indexed predicates and multi-leg strategies. The order of `statKeys` is critical as it maps to the proof contract positions. ### Method GET ### Endpoint /scores/stat-validation ### Parameters #### Query Parameters - **fixtureId** (string) - Required - The unique identifier for the fixture. - **seq** (string) - Required - The sequence number for the score update. - **statKeys** (string) - Required - A comma-separated list of statistic keys to validate. ``` -------------------------------- ### GET /scores/stat-validation (Legacy) Source: https://txline.txodds.com/documentation/examples/devnet-examples Validates single-stat or legacy two-stat records using a specific statKey. ```APIDOC ## GET /scores/stat-validation ### Description Validates single-stat or legacy two-stat examples using `statKey` and optional `statKey2`. ### Method GET ### Endpoint /scores/stat-validation ### Parameters #### Query Parameters - **fixtureId** (string) - Required - The unique identifier for the fixture. - **seq** (string) - Required - The sequence number for the score update. - **statKey** (string) - Required - The key identifying the statistic to validate. ``` -------------------------------- ### POST /auth/guest/start Source: https://txline.txodds.com/documentation/programs/addresses Initializes a guest session to obtain a JWT for API access. ```APIDOC ## POST /auth/guest/start ### Description Initiates a guest session to receive a JWT required for subsequent API requests. ### Method POST ### Endpoint https://txline.txodds.com/auth/guest/start (Mainnet) or https://txline-dev.txodds.com/auth/guest/start (Devnet) ``` -------------------------------- ### Initialize TxLine Solana Program Source: https://txline.txodds.com/documentation/quickstart Sets up the Anchor provider and program instance using network-specific configuration constants. Ensure the wallet variable is defined before execution. ```typescript import * as anchor from "@coral-xyz/anchor"; import type { Txoracle } from "./types/txoracle"; // Use the matching mainnet/devnet type import txoracleIdl from "./idl/txoracle.json"; // Use the matching mainnet/devnet IDL import { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, getAssociatedTokenAddressSync, } from "@solana/spl-token"; import { Connection, PublicKey, SystemProgram } from "@solana/web3.js"; import axios from "axios"; import nacl from "tweetnacl"; const NETWORK: "mainnet" | "devnet" = "mainnet"; const CONFIG = { mainnet: { rpcUrl: "https://api.mainnet-beta.solana.com", apiOrigin: "https://txline.txodds.com", programId: new PublicKey("9ExbZjAapQww1vfcisDmrngPinHTEfpjYRWMunJgcKaA"), txlTokenMint: new PublicKey("Zhw9TVKp68a1QrftncMSd6ELXKDtpVMNuMGr1jNwdeL"), }, devnet: { rpcUrl: "https://api.devnet.solana.com", apiOrigin: "https://txline-dev.txodds.com", programId: new PublicKey("6pW64gN1s2uqjHkn1unFeEjAwJkPGHoppGvS715wyP2J"), txlTokenMint: new PublicKey("4Zao8ocPhmMgq7PdsYWyxvqySMGx7xb9cMftPMkEokRG"), }, } as const; const { rpcUrl, apiOrigin, programId, txlTokenMint } = CONFIG[NETWORK]; const apiBaseUrl = `${apiOrigin}/api`; const connection = new Connection(rpcUrl, "confirmed"); const provider = new anchor.AnchorProvider(connection, wallet, { commitment: "confirmed", }); anchor.setProvider(provider); const program = new anchor.Program( txoracleIdl as Txoracle, provider ); if (!program.programId.equals(programId)) { throw new Error( `Loaded IDL program ${program.programId.toBase58()} does not match ${NETWORK} program ${programId.toBase58()}` ); } ``` -------------------------------- ### GET /api/scores/stat-validation Source: https://txline.txodds.com/documentation/examples/onchain-validation Validates a specific score sequence for a fixture. ```APIDOC ## GET /api/scores/stat-validation ### Description Requests a validation proof for a specific score sequence observed in a score record. ### Method GET ### Endpoint /api/scores/stat-validation ### Parameters #### Query Parameters - **fixtureId** (number) - Required - The unique identifier for the fixture. - **seq** (number) - Required - The sequence number of the score record (must be >= 1). - **statKey** (number) - Required - The statistical key to validate. ``` -------------------------------- ### POST /auth/guest/start Source: https://txline.txodds.com/documentation/programs/devnet Initiates a guest session to obtain a JWT for subsequent API requests. ```APIDOC ## POST /auth/guest/start ### Description Starts a guest authentication session to retrieve a JWT required for API access. ### Method POST ### Endpoint https://txline-dev.txodds.com/auth/guest/start ``` -------------------------------- ### Initialize TxLINE client configuration Source: https://txline.txodds.com/documentation/worldcup Configure the Anchor provider and program instance using the appropriate network settings. ```typescript import * as anchor from "@coral-xyz/anchor"; import type { Txoracle } from "./types/txoracle"; // Use the matching mainnet/devnet type import txoracleIdl from "./idl/txoracle.json"; // Use the matching mainnet/devnet IDL import { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, getAssociatedTokenAddressSync, } from "@solana/spl-token"; import { Connection, PublicKey, SystemProgram } from "@solana/web3.js"; import axios from "axios"; import nacl from "tweetnacl"; const NETWORK: "mainnet" | "devnet" = "devnet"; const CONFIG = { mainnet: { rpcUrl: "https://api.mainnet-beta.solana.com", apiOrigin: "https://txline.txodds.com", programId: new PublicKey("9ExbZjAapQww1vfcisDmrngPinHTEfpjYRWMunJgcKaA"), txlTokenMint: new PublicKey("Zhw9TVKp68a1QrftncMSd6ELXKDtpVMNuMGr1jNwdeL"), }, devnet: { rpcUrl: "https://api.devnet.solana.com", apiOrigin: "https://txline-dev.txodds.com", programId: new PublicKey("6pW64gN1s2uqjHkn1unFeEjAwJkPGHoppGvS715wyP2J"), txlTokenMint: new PublicKey("4Zao8ocPhmMgq7PdsYWyxvqySMGx7xb9cMftPMkEokRG"), }, } as const; const { rpcUrl, apiOrigin, programId, txlTokenMint } = CONFIG[NETWORK]; const apiBaseUrl = `${apiOrigin}/api`; const connection = new Connection(rpcUrl, "confirmed"); const provider = new anchor.AnchorProvider(connection, wallet, { commitment: "confirmed", }); anchor.setProvider(provider); const program = new anchor.Program( txoracleIdl as Txoracle, provider ); if (!program.programId.equals(programId)) { throw new Error( `Loaded IDL program ${program.programId.toBase58()} does not match ${NETWORK} program ${programId.toBase58()}` ); } ``` -------------------------------- ### Initialize Txoracle Client and Helpers Source: https://txline.txodds.com/documentation/examples/onchain-validation Sets up the Anchor provider, authenticated HTTP client, and utility functions for converting proof data into the required 32-byte format. ```typescript import * as anchor from "@coral-xyz/anchor"; import { PublicKey, ComputeBudgetProgram } from "@solana/web3.js"; import { BN } from "@coral-xyz/anchor"; import axios from "axios"; const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); const program = anchor.workspace.Txoracle as anchor.Program; // Create HTTP client with authentication const httpClient = axios.create({ timeout: 30000, headers: { "Content-Type": "application/json", "Authorization": `Bearer ${jwt}`, "X-Api-Token": apiToken }, baseURL: "https://txline.txodds.com", }); // For devnet, use baseURL: "https://txline-dev.txodds.com". function toBytes32(value: string | number[] | Uint8Array): number[] { const bytes = Array.isArray(value) ? Uint8Array.from(value) : value instanceof Uint8Array ? value : value.startsWith("0x") ? Buffer.from(value.slice(2), "hex") : Buffer.from(value, "base64"); if (bytes.length !== 32) { throw new Error(`Expected 32 bytes, received ${bytes.length}`); } return Array.from(bytes); } function toProofNodes(nodes: Array<{ hash: string | number[] | Uint8Array; isRightSibling: boolean }>) { return nodes.map((node) => ({ hash: toBytes32(node.hash), isRightSibling: node.isRightSibling, })); } ``` -------------------------------- ### Run devnet subscription script Source: https://txline.txodds.com/documentation/examples/devnet-examples Execute the subscription free tier script with the required environment variables for devnet connectivity. ```bash TOKEN_MINT_ADDRESS=4Zao8ocPhmMgq7PdsYWyxvqySMGx7xb9cMftPMkEokRG \ ANCHOR_PROVIDER_URL="https://api.devnet.solana.com" \ ANCHOR_WALLET="./_keys/testuser-wallet-1.json" \ yarn ts-node examples/devnet/scripts/subscription_free_tier.ts ``` -------------------------------- ### Verify Subscription Pricing on-chain with TypeScript Source: https://txline.txodds.com/documentation/subscription-tiers Fetches the pricing matrix account from the program to inspect service levels and token costs. Requires an initialized Anchor program instance. ```typescript const [pricingMatrixPda] = anchor.web3.PublicKey.findProgramAddressSync( [Buffer.from("pricing_matrix")], program.programId ); const matrix = await program.account.pricingMatrix.fetch(pricingMatrixPda); matrix.rows.forEach((row) => { console.log({ serviceLevel: row.rowId, tokensPerWeek: row.pricePerWeekToken, samplingInterval: row.samplingIntervalSec, leagueBundle: row.leagueBundleId, marketBundle: row.marketBundleId }); }); ``` -------------------------------- ### Subscribe to Free Tier On-Chain Source: https://txline.txodds.com/documentation/worldcup Configures subscription parameters and executes the on-chain transaction to register the wallet for data access. ```typescript // Free tier configuration - choose one: const SERVICE_LEVEL_ID = 1; // Devnet: samplingIntervalSec = 0; mainnet: 60 seconds // const SERVICE_LEVEL_ID = 12; // Mainnet real-time World Cup & Int Friendlies const DURATION_WEEKS = 4; // Subscribe for 4 weeks at a time const SELECTED_LEAGUES: number[] = []; // Empty for standard bundle const [tokenTreasuryPda] = PublicKey.findProgramAddressSync( [Buffer.from("token_treasury_v2")], program.programId ); const tokenTreasuryVault = getAssociatedTokenAddressSync( txlTokenMint, tokenTreasuryPda, true, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID ); const [pricingMatrixPda] = PublicKey.findProgramAddressSync( [Buffer.from("pricing_matrix")], program.programId ); const userTokenAccount = getAssociatedTokenAddressSync( txlTokenMint, provider.wallet.publicKey, false, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID ); // Subscribe on-chain const txSig = await program.methods .subscribe(SERVICE_LEVEL_ID, DURATION_WEEKS) .accounts({ user: provider.wallet.publicKey, pricingMatrix: pricingMatrixPda, tokenMint: txlTokenMint, userTokenAccount, tokenTreasuryVault, tokenTreasuryPda, tokenProgram: TOKEN_2022_PROGRAM_ID, associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, systemProgram: SystemProgram.programId, }) .rpc(); console.log("Subscription transaction:", txSig); ``` -------------------------------- ### Execute On-Chain Subscription Source: https://txline.txodds.com/documentation/quickstart Initiate a subscription transaction for either standard bundles or custom league selections. ```typescript const SERVICE_LEVEL_ID = 1; const DURATION_WEEKS = 4; const SELECTED_LEAGUES: number[] = []; // Standard bundle const txSig = await program.methods .subscribe(SERVICE_LEVEL_ID, DURATION_WEEKS) .accounts({ user: provider.wallet.publicKey, pricingMatrix: pricingMatrixPda, tokenMint: txlTokenMint, userTokenAccount, tokenTreasuryVault, tokenTreasuryPda, tokenProgram: TOKEN_2022_PROGRAM_ID, associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, systemProgram: SystemProgram.programId, }) .rpc(); ``` ```typescript const SERVICE_LEVEL_ID = 3; const DURATION_WEEKS = 4; const SELECTED_LEAGUES = [500001]; // Your league IDs const txSig = await program.methods .subscribe(SERVICE_LEVEL_ID, DURATION_WEEKS) .accounts({ user: provider.wallet.publicKey, pricingMatrix: pricingMatrixPda, tokenMint: txlTokenMint, userTokenAccount, tokenTreasuryVault, tokenTreasuryPda, tokenProgram: TOKEN_2022_PROGRAM_ID, associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, systemProgram: SystemProgram.programId, }) .rpc(); ``` -------------------------------- ### Activation Message Format for Free Bundle Source: https://txline.txodds.com/documentation/quickstart The expected message format when no specific leagues are selected. ```text ${txSig}::${jwt} ``` -------------------------------- ### GET /api/scores/updates/{epochDay}/{hourOfDay}/{interval} Source: https://txline.txodds.com/documentation/examples/fetching-snapshots Retrieves historical scores updates for a specific time period. ```APIDOC ## GET /api/scores/updates/{epochDay}/{hourOfDay}/{interval} ### Description Retrieves historical scores updates for a specific time period. ### Method GET ### Endpoint /api/scores/updates/{epochDay}/{hourOfDay}/{interval} ### Parameters #### Path Parameters - **epochDay** (number) - Required - The epoch day. - **hourOfDay** (number) - Required - The hour of the day. - **interval** (number) - Required - The time interval. ``` -------------------------------- ### Activate API Access with TypeScript Source: https://txline.txodds.com/documentation/quickstart Signs the activation message using the wallet and calls the activation endpoint to retrieve the API token. ```typescript // Get guest JWT const authResponse = await axios.post(`${apiOrigin}/auth/guest/start`); const jwt = authResponse.data.token; // Sign the subscription transaction const messageString = `${txSig}:${SELECTED_LEAGUES.join(",")}:${jwt}`; const message = new TextEncoder().encode(messageString); // For SELECTED_LEAGUES = [], this signs `${txSig}::${jwt}`. async function signActivationMessage(message: Uint8Array): Promise { if ("signMessage" in wallet && wallet.signMessage) { return wallet.signMessage(message); } const localPayer = (provider.wallet as anchor.Wallet & { payer?: anchor.web3.Keypair; }).payer; if (localPayer) { return nacl.sign.detached(message, localPayer.secretKey); } throw new Error("Wallet must support signMessage, or run with a local Anchor payer."); } const signatureBytes = await signActivationMessage(message); const walletSignature = Buffer.from(signatureBytes).toString("base64"); // Activate API access const activationResponse = await axios.post( `${apiBaseUrl}/token/activate`, { txSig, walletSignature, leagues: SELECTED_LEAGUES, }, { headers: { Authorization: `Bearer ${jwt}` } } ); const apiToken = activationResponse.data.token || activationResponse.data; ``` -------------------------------- ### Verify and Sign Transaction Source: https://txline.txodds.com/documentation/quickstart Deserialize the transaction from the quote, sign it locally, and broadcast it to the Solana network. ```typescript // Deserialize the transaction from the quote const txBuffer = Buffer.from(quoteData.transactionBase64, "base64"); const transaction = anchor.web3.Transaction.from(txBuffer); // Verify transaction safety locally (recommended) // This ensures the transaction matches what you requested // Sign the transaction with either a local Keypair or a wallet adapter const signedTransaction = "secretKey" in wallet ? (transaction.partialSign(wallet), transaction) : await wallet.signTransaction(transaction); // Broadcast to Solana const txSignature = await connection.sendRawTransaction(signedTransaction.serialize(), { skipPreflight: false, preflightCommitment: "confirmed" }); // Confirm transaction await connection.confirmTransaction(txSignature, "confirmed"); console.log("Purchase successful:", txSignature); ``` -------------------------------- ### GET /scores/stat-validation Source: https://txline.txodds.com/documentation/programs/devnet Validates score statistics using either legacy single-stat or multi-stat validation methods. ```APIDOC ## GET /scores/stat-validation ### Description Validates score statistics for a given fixture. Supports legacy single-stat validation via `statKey` or multi-stat validation via `statKeys`. ### Method GET ### Endpoint /scores/stat-validation ### Parameters #### Query Parameters - **fixtureId** (string) - Required - The unique identifier for the fixture. - **seq** (string) - Required - A real sequence value from an observed score record. - **statKey** (string) - Optional - The key for single-stat validation. - **statKeys** (string) - Optional - A comma-separated list of keys for multi-stat validation (e.g., 1,2,3). ``` -------------------------------- ### Fetch Fixtures Snapshot with TypeScript Source: https://txline.txodds.com/documentation/examples/fetching-snapshots Configures an Axios client with required authentication headers and retrieves fixture data for a specific competition or the entire set. ```typescript import axios from "axios"; const httpClient = axios.create({ timeout: 30000, headers: { "Content-Type": "application/json", "Authorization": `Bearer ${jwt}`, "X-Api-Token": apiToken }, baseURL: "https://txline.txodds.com", }); // Get fixtures for specific competition const fixturesResponse = await httpClient.get("/api/fixtures/snapshot", { params: { competitionId: 500005, // NCAA Division I FBS }, }); const fixtures = fixturesResponse.data; console.log(`Retrieved ${fixtures.length} fixtures`); fixtures.slice(0, 3).forEach((fixture, index) => { const homeTeam = fixture.Participant1IsHome ? fixture.Participant1 : fixture.Participant2; const awayTeam = fixture.Participant1IsHome ? fixture.Participant2 : fixture.Participant1; console.log(`${index + 1}. ${homeTeam} vs ${awayTeam}`); console.log(` ID: ${fixture.FixtureId}, Start: ${new Date(fixture.StartTime).toISOString()}`); console.log(` GameState: ${fixture.GameState ?? fixture.gameState}`); }); // Get all fixtures const allFixturesResponse = await httpClient.get("/api/fixtures/snapshot"); const allFixtures = allFixturesResponse.data; console.log(`Retrieved ${allFixtures.length} total fixtures`); ``` -------------------------------- ### GET /scores/stat-validation Source: https://txline.txodds.com/documentation/programs/mainnet Validates score statistics against on-chain records using either single-stat or multi-stat validation methods. ```APIDOC ## GET /scores/stat-validation ### Description Validates score statistics for a given fixture. Supports legacy single-stat validation and multi-stat validation with indexed strategies. ### Method GET ### Endpoint /scores/stat-validation ### Parameters #### Query Parameters - **fixtureId** (string) - Required - The unique identifier for the fixture. - **seq** (string) - Required - A real sequence value from an observed score record. - **statKey** (string) - Optional - The key for single-stat validation. - **statKeys** (string) - Optional - A comma-separated list of keys for multi-stat validation. ``` -------------------------------- ### Activate API Access Source: https://txline.txodds.com/documentation/worldcup Authenticates the user by signing a message containing the subscription transaction signature and a guest JWT. ```typescript // Get guest authentication token const authResponse = await axios.post(`${apiOrigin}/auth/guest/start`); const jwt = authResponse.data.token; // Create message to sign const messageString = `${txSig}:${SELECTED_LEAGUES.join(",")}:${jwt}`; const message = new TextEncoder().encode(messageString); // For SELECTED_LEAGUES = [], this signs `${txSig}::${jwt}`. async function signActivationMessage(message: Uint8Array): Promise { if ("signMessage" in wallet && wallet.signMessage) { return wallet.signMessage(message); } const localPayer = (provider.wallet as anchor.Wallet & { payer?: anchor.web3.Keypair; }).payer; if (localPayer) { return nacl.sign.detached(message, localPayer.secretKey); } throw new Error("Wallet must support signMessage, or run with a local Anchor payer."); } const signatureBytes = await signActivationMessage(message); const walletSignature = Buffer.from(signatureBytes).toString("base64"); // Activate your API access const activationResponse = await axios.post( `${apiBaseUrl}/token/activate`, { txSig, walletSignature, leagues: SELECTED_LEAGUES, }, { headers: { Authorization: `Bearer ${jwt}` } } ); // Save your API token const apiToken = activationResponse.data.token || activationResponse.data; console.log("API Token activated successfully!"); ``` -------------------------------- ### POST /api/token/activate Source: https://txline.txodds.com/documentation/programs/devnet Activates an API token after a subscription transaction has been confirmed on the Solana devnet. ```APIDOC ## POST /api/token/activate ### Description Activates the API token by providing a wallet signature and the guest JWT obtained from the authentication endpoint. ### Method POST ### Endpoint https://txline-dev.txodds.com/api/token/activate ### Request Body - **walletSignature** (string) - Required - The detached wallet signature as base64. The message to sign is `${txSig}:${selectedLeagues.join(",")}:${jwt}`. ### Headers - **Authorization** (string) - Required - Bearer (The guest JWT from the devnet host). ``` -------------------------------- ### Request Purchase Quote Source: https://txline.txodds.com/documentation/quickstart Obtain a guest JWT and request a purchase quote for a specific amount of TxL tokens. ```typescript // Get guest JWT const authResponse = await axios.post(`${apiOrigin}/auth/guest/start`); const jwt = authResponse.data.token; // Request purchase quote const txlineAmount = 50; // Amount of TxL tokens to purchase const quoteResponse = await fetch(`${apiBaseUrl}/guest/purchase/quote`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${jwt}` }, body: JSON.stringify({ buyerPubkey: wallet.publicKey.toBase58(), txlineAmount: txlineAmount }) }); const quoteData = await quoteResponse.json(); console.log(`Base Cost: ${quoteData.baseUsdtCost} USDT`); console.log(`Premium Fee: ${quoteData.feeUsdtAmount} USDT`); console.log(`Total: ${quoteData.totalUsdtCharged} USDT`); ``` -------------------------------- ### POST /api/token/activate Source: https://txline.txodds.com/documentation/programs/addresses Activates the API token after a successful on-chain subscription transaction. ```APIDOC ## POST /api/token/activate ### Description Activates the API token by providing a wallet signature after the on-chain subscribe transaction is confirmed. ### Method POST ### Endpoint https://txline.txodds.com/api/token/activate (Mainnet) or https://txline-dev.txodds.com/api/token/activate (Devnet) ### Parameters #### Request Body - **walletSignature** (string) - Required - The detached wallet signature as base64. ### Request Headers - **Authorization** (string) - Required - Bearer ``` -------------------------------- ### POST /api/token/activate Source: https://txline.txodds.com/documentation/programs/mainnet Activates an API token after a subscription transaction has been confirmed on the Solana blockchain. ```APIDOC ## POST /api/token/activate ### Description Activates the API token by providing a wallet signature and the guest JWT obtained from the authentication service. ### Method POST ### Endpoint https://txline.txodds.com/api/token/activate ### Request Body - **walletSignature** (string) - Required - The base64 encoded detached wallet signature of the activation message. - **Authorization** (header) - Required - Bearer token containing the guest JWT. ### Activation Message Format The message to be signed by the wallet is constructed as follows: - Standard: `${txSig}:${selectedLeagues.join(",")}:${jwt}` - Free Bundle: `${txSig}::${jwt}` ``` -------------------------------- ### Configure Exact Match Predicate in TypeScript Source: https://txline.txodds.com/documentation/examples/troubleshooting Sets up an initial sanity check predicate to verify the returned stat value matches the expected threshold. ```typescript const predicate = { threshold: validation.statToProve.value, comparison: { equalTo: {} }, }; ``` -------------------------------- ### deriveTenDailyFixturesPda Source: https://txline.txodds.com/documentation/programs/mainnet Derives the PDA for ten daily fixtures roots based on the fixture proof timestamp. ```APIDOC ## deriveTenDailyFixturesPda(fixtureProofTimestampMs) ### Description Derives the Program Derived Address (PDA) for ten daily fixtures roots by aligning the epoch day to a 10-day window. ### Parameters - **fixtureProofTimestampMs** (number) - Required - The fixture timestamp in milliseconds extracted from the proof response. ### Returns - **PublicKey** - The derived Solana account address. ``` -------------------------------- ### Subscribe to Real-Time Scores via SSE Source: https://txline.txodds.com/documentation/examples/onchain-validation Establishes a connection to the score streaming endpoint using Bearer authentication and an API token. Requires helper functions for reading and parsing SSE messages. ```typescript const streamUrl = "https://txline.txodds.com/api/scores/stream"; const streamResponse = await fetch(streamUrl, { headers: { Authorization: `Bearer ${jwt}`, "X-Api-Token": apiToken, Accept: "text/event-stream", "Cache-Control": "no-cache", }, }); if (!streamResponse.ok) { throw new Error(`Stream failed: ${streamResponse.status}`); } // Reuse the readSseMessages and parseSseData helpers from the Streaming Data guide. for await (const message of readSseMessages(streamResponse)) { console.log(message.event ?? "message", parseSseData(message.data)); } ``` -------------------------------- ### Activation Message Format Source: https://txline.txodds.com/documentation/programs/addresses The message format required for API token activation after a subscription transaction. ```text ${txSig}:${selectedLeagues.join(",")}:${jwt} ``` ```text ${txSig}::${jwt} ``` -------------------------------- ### Fetch Odds Snapshot with TypeScript Source: https://txline.txodds.com/documentation/examples/fetching-snapshots Retrieves odds data for a specific fixture ID or historical updates based on epoch day, hour, and interval. ```typescript const fixtureId = 17271370; // Get odds for specific fixture const fixtureOddsResponse = await httpClient.get( `/api/odds/snapshot/${fixtureId}` ); const fixtureOdds = fixtureOddsResponse.data; console.log(`Retrieved ${fixtureOdds.length} odds entries`); // Get odds for time period const epochDay = 20085; const hourOfDay = 15; const interval = 0; const updatesResponse = await httpClient.get( `/api/odds/updates/${epochDay}/${hourOfDay}/${interval}` ); const updates = updatesResponse.data; console.log(`Retrieved ${updates.length} odds updates`); ``` -------------------------------- ### Fetch Scores Snapshot with TypeScript Source: https://txline.txodds.com/documentation/examples/fetching-snapshots Retrieves score snapshots for a specific fixture, live updates for a fixture, or historical score updates for a specific time period. ```typescript const fixtureId = 17271370; // Get scores snapshot for fixture const snapshotScoresResponse = await httpClient.get( `/api/scores/snapshot/${fixtureId}` ); const snapshotScores = snapshotScoresResponse.data; console.log(`Retrieved ${snapshotScores.length} snapshot scores entries`); // Get live scores updates const liveScoresResponse = await httpClient.get( `/api/scores/updates/${fixtureId}` ); const liveScores = liveScoresResponse.data; console.log(`Retrieved ${liveScores.length} live scores updates`); // Get scores for time period const epochDay = 20085; const hourOfDay = 15; const interval = 0; const historicalUpdatesResponse = await httpClient.get( `/api/scores/updates/${epochDay}/${hourOfDay}/${interval}` ); const historicalUpdates = historicalUpdatesResponse.data; console.log(`Retrieved ${historicalUpdates.length} historical scores updates`); ``` -------------------------------- ### Derive Shared Accounts for TxLINE Source: https://txline.txodds.com/documentation/quickstart Derive the necessary PDAs and associated token accounts before initiating a subscription. ```typescript const [tokenTreasuryPda] = PublicKey.findProgramAddressSync( [Buffer.from("token_treasury_v2")], program.programId ); const tokenTreasuryVault = getAssociatedTokenAddressSync( txlTokenMint, tokenTreasuryPda, true, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID ); const [pricingMatrixPda] = PublicKey.findProgramAddressSync( [Buffer.from("pricing_matrix")], program.programId ); const userTokenAccount = getAssociatedTokenAddressSync( txlTokenMint, provider.wallet.publicKey, false, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID ); ```