### Install Azuro Protocol Toolkit Source: https://github.com/azuro-protocol/toolkit/blob/main/README.md Install the toolkit package using npm. Ensure peer dependencies are met. ```bash npm i --save @azuro-org/toolkit ``` -------------------------------- ### Get Games and Markets with Azuro Toolkit Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/00-START-HERE.md Retrieve game and market data using filters. This example shows how to get prematch games and then fetch the associated conditions (markets) and outcomes for the first game. ```typescript import { getGamesByFilters, getConditionsByGameIds, GameState } from '@azuro-org/toolkit' // Get prematch games const games = await getGamesByFilters({ chainId: 137, state: GameState.Prematch, page: 1, perPage: 50, }) // Get markets for first game const conditions = await getConditionsByGameIds({ chainId: 137, gameIds: [games.games[0].id], }) // Show outcomes conditions.forEach(condition => { condition.outcomes.forEach(outcome => { console.log(`${outcome.selection.name}: ${outcome.odds}`) }) }) ``` -------------------------------- ### Install Azuro Toolkit Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/README.md Install the @azuro-org/toolkit package using npm. Ensure your Node.js version is 22.11.0 or higher. ```bash npm install @azuro-org/toolkit ``` -------------------------------- ### Setup Custom Contracts with `setupContracts` Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/configuration.md Use `setupContracts` to create custom contract configurations by providing specific contract addresses. The `cashout` address is optional. ```typescript import { setupContracts } from '@azuro-org/toolkit' const contracts = setupContracts({ lp: '0x0FA7FB5407eA971694652E6E16C12A52625DE1b8', core: '0xF9548Be470A4e130c90ceA8b179FCD66D2972AC7', relayer: '0x8dA05c0021e6b35865FDC959c54dCeF3A4AbBa9d', azuroBet: '0x7A1c3FEf712753374C4DCe34254B96faF2B7265B', vault: '0x1a0612FE7D0Def35559a1f71Ff155e344Ae69d2C', paymaster: '0xeD5760fC2d2f6d363d73e576173e5e8Ca6A877e1', cashout: '0x4a2BB4211cCF9b9eA6eF01D0a61448154ED19095', // optional }) ``` -------------------------------- ### Utilities & Helpers Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/REFERENCE-INDEX.md Utility functions for calculations, data organization, and contract setup. ```APIDOC ## calcMinOdds() ### Description Calculate minimum odds with slippage. ### Purpose Determines the minimum acceptable odds considering a slippage tolerance. ### Location [utility-functions.md](api-reference/utility-functions.md#calcminodds) ``` ```APIDOC ## groupConditionsByMarket() ### Description Organize conditions by market type. ### Purpose Groups various conditions based on their associated market type. ### Location [utility-functions.md](api-reference/utility-functions.md#groupconditionsbymarket) ``` ```APIDOC ## getIsPendingResolution() ### Description Check if a game is pending settlement. ### Purpose Verifies whether a game is currently awaiting resolution or settlement. ### Location [utility-functions.md](api-reference/utility-functions.md#getispendingresolution) ``` ```APIDOC ## getProviderFromId() ### Description Get Viem Chain object from an ID. ### Purpose Retrieves a Viem Chain object based on a provided identifier. ### Location [utility-functions.md](api-reference/utility-functions.md#getproviderid) ``` ```APIDOC ## setupContracts() ### Description Create contract configuration. ### Purpose Sets up the necessary configuration for smart contracts. ### Location [utility-functions.md](api-reference/utility-functions.md#setupcontracts) ``` ```APIDOC ## formatToFixed() ### Description Format decimals to a fixed precision. ### Purpose Formats decimal numbers to a specified fixed number of decimal places. ### Location [utility-functions.md](api-reference/utility-functions.md#formattofixed) ``` -------------------------------- ### Setup Azuro Protocol Contracts Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/utility-functions.md Creates contract configuration objects with ABIs for all Azuro Protocol contracts. Provide contract addresses as parameters to generate the configuration. ```typescript import { setupContracts } from '@azuro-org/toolkit' const contracts = setupContracts({ lp: '0x0FA7FB5407eA971694652E6E16C12A52625DE1b8', core: '0xF9548Be470A4e130c90ceA8b179FCD66D2972AC7', relayer: '0x8dA05c0021e6b35865FDC959c54dCeF3A4AbBa9d', azuroBet: '0x7A1c3FEf712753374C4DCe34254B96faF2B7265B', vault: '0x1a0612FE7D0Def35559a1f71Ff155e344Ae69d2C', paymaster: '0xeD5760fC2d2f6d363d73e576173e5e8Ca6A877e1', cashout: '0x4a2BB4211cCF9b9eA6eF01D0a61448154ED19095', }) console.log(contracts.core.address) // Use contracts.core.abi with viem's contract methods ``` -------------------------------- ### Utility Functions Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/INDEX.md A collection of helper functions for calculations, data formatting, and contract setup. ```APIDOC ## Utility Functions ### Description Provides essential helper functions for common tasks such as odds calculation, data formatting, and contract initialization. ### Functions - `calcMinOdds()`: Calculates the minimum odds required for a bet. - `groupConditionsByMarket()`: Organizes betting conditions by their respective markets. - `getIsPendingResolution()`: Checks if a bet is pending resolution. - `getProviderFromId()`: Retrieves a chain provider object based on its ID. - `setupContracts()`: Configures and sets up smart contracts. - `formatToFixed()`: Formats a number to a fixed number of decimal places. ``` -------------------------------- ### Use a Freebet Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/README.md This example shows how to use an available freebet for placing a new bet. It involves fetching available freebets, checking their restrictions, and then including the freebet ID during bet creation. ```typescript import { getBonuses, BonusStatus, createBet } from '@azuro-org/toolkit' // Get available freebets const freebets = await getBonuses({ chainId: 137, account: userAddress, affiliate: affiliateAddress, bonusStatus: BonusStatus.Available, }) if (!freebets || freebets.length === 0) { console.log('No freebets available') return } // Check freebet restrictions const freebet = freebets[0] console.log(`Min odds: ${freebet.settings.betRestriction.minOdds}`) console.log(`Bet type: ${freebet.settings.betRestriction.type}`) // Use freebet in bet creation const result = await createBet({ account: userAddress, clientData, bet: { /* ... */ }, signature, bonusId: freebet.id, // Include freebet ID }) ``` -------------------------------- ### Example Usage of getUserFavorites Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/user-favorites.md Demonstrates how to import and use the `getUserFavorites` function with sample user and affiliate IDs. It logs the names of favorite countries and leagues to the console. ```typescript import { getUserFavorites } from '@azuro-org/toolkit' const { favorites } = await getUserFavorites({ userId: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', affiliateId: '0x123...', chainId: 137, }) console.log('Favorite countries:', favorites.countries.map(c => c.countryRef.name)) console.log('Favorite leagues:', favorites.leagues.map(l => l.leagueRef.name)) ``` -------------------------------- ### Example Usage of getBetStatus Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/bet-operations.md Demonstrates how to use the getBetStatus function with sample game, order, and graph statuses to determine the bet's current status. It shows how to import necessary types and check the returned status. ```typescript import { getBetStatus, BetStatus, GameState, BetOrderState } from '@azuro-org/toolkit' const status = getBetStatus({ games: [{ state: GameState.Live, startsAt: '1234567890' }], orderState: BetOrderState.Accepted, graphStatus: GraphBetStatus.Accepted, }) if (status === BetStatus.Live) { console.log('Bet is currently live') } ``` -------------------------------- ### Place a Single Bet with Azuro Toolkit Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/00-START-HERE.md Use this workflow to place a single bet. It involves getting fees, generating typed data for signing, signing with a wallet, and finally submitting the bet. ```typescript import { createBet, getBetTypedData, getBetFee } from '@azuro-org/toolkit' import { signTypedData } from 'viem/actions' // 1. Get current fees const fee = await getBetFee(137) // Polygon // 2. Generate typed data const typedData = getBetTypedData({ account: userAddress, clientData: { // ... fee and metadata }, bet: { conditionId: '123', outcomeId: '1', minOdds: '1500000000000', amount: '1000000', nonce: '1', }, }) // 3. Sign with wallet const signature = await signTypedData(walletClient, typedData) // 4. Submit const result = await createBet({ account: userAddress, clientData: { /* ... */ }, bet: { /* ... */ }, signature, }) console.log('Bet ID:', result.id) ``` -------------------------------- ### Get Available Games and Markets Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/README.md Retrieve prematch games and their associated markets (conditions and outcomes). This snippet demonstrates filtering games by state and then fetching conditions for specific game IDs. ```typescript import { getGamesByFilters, getConditionsByGameIds, GameState } from '@azuro-org/toolkit' // Get prematch games const response = await getGamesByFilters({ chainId: 137, state: GameState.Prematch, page: 1, perPage: 50, }) // Get markets for first game const conditions = await getConditionsByGameIds({ chainId: 137, gameIds: [response.games[0].id], }) // Display conditions conditions.forEach(condition => { console.log(`Market ${condition.conditionId}`) condition.outcomes.forEach(outcome => { console.log(` ${outcome.selection.name}: ${outcome.odds}`) }) }) ``` -------------------------------- ### Get Wave Leaderboard Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/wave-operations.md Fetches the leaderboard of top performers in a wave. Supports pagination and filtering by wave ID and chain ID. ```typescript function getWaveLeaderBoard(params?: { waveId?: WaveId; chainId?: ChainId; limit?: number; offset?: number; }): Promise; ``` ```typescript import { getWaveLeaderBoard } from '@azuro-org/toolkit' const leaderboard = await getWaveLeaderBoard({ waveId: 'active', limit: 50, }) leaderboard.forEach(item => { console.log(`${item.rank}. ${item.address}: ${item.points} points (${item.level})`) }) ``` -------------------------------- ### Cash Out a Bet Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/README.md This snippet guides through cashing out a bet. It includes calculating the potential cashout amount, signing the cashout request, and submitting it for acceptance. ```typescript import { getCalculatedCashout, getCashoutTypedData, createCashout, CashoutState, } from '@azuro-org/toolkit' import { signTypedData } from 'viem/actions' // Calculate cashout amount const cashout = await getCalculatedCashout({ chainId: 137, betId: '12345', }) console.log('You will receive:', cashout.payoutAmount) // Sign cashout const typedData = getCashoutTypedData({ chainId: 137, calculationId: cashout.calculationId, betId: '12345', minOdds: '1000000000000', }) const signature = await signTypedData(walletClient, typedData) // Submit cashout const result = await createCashout({ chainId: 137, calculationId: cashout.calculationId, attention: 'I agree to cashout', signature, }) if (result.state === CashoutState.Accepted) { console.log('Cashout successful!') } ``` -------------------------------- ### Get Available Games and Markets Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/README.md Retrieves a list of available games and their associated markets (conditions and outcomes). This is useful for displaying betting options to users. ```APIDOC ## Get Available Games and Markets ### Description Fetches available games and their markets (conditions and outcomes) based on specified filters. ### Method Asynchronous function calls using `@azuro-org/toolkit`. ### Parameters - `getGamesByFilters`: Retrieves games based on chain ID, state, and pagination. - `getConditionsByGameIds`: Retrieves markets for a given list of game IDs. ### Request Example ```typescript import { getGamesByFilters, getConditionsByGameIds, GameState } from '@azuro-org/toolkit' // Get prematch games const response = await getGamesByFilters({ chainId: 137, state: GameState.Prematch, page: 1, perPage: 50, }) // Get markets for first game const conditions = await getConditionsByGameIds({ chainId: 137, gameIds: [response.games[0].id], }) // Display conditions conditions.forEach(condition => { console.log(`Market ${condition.conditionId}`) condition.outcomes.forEach(outcome => { console.log(` ${outcome.selection.name}: ${outcome.odds}`) }) }) ``` ``` -------------------------------- ### Get Wave Periods Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/wave-operations.md Fetches the time periods and schedule for a wave. Defaults to the active wave and chain ID 137 (Polygon). The response includes start and end dates, duration, and details about seasons within the wave. ```typescript function getWavePeriods(params?: { waveId?: WaveId; chainId?: ChainId; }): Promise; ``` ```typescript import { getWavePeriods } from '@azuro-org/toolkit' const periods = await getWavePeriods() console.log(`Wave runs from ${periods.startDate} to ${periods.endDate}`) periods.seasons.forEach(season => { console.log(`Season ${season.name}: ${season.startDate}`) }) ``` -------------------------------- ### setupContracts Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/utility-functions.md Creates contract configuration objects with ABIs for all Azuro Protocol contracts. It takes contract addresses as input and returns a Contracts object containing addresses and ABIs for each contract. ```APIDOC ## setupContracts ### Description Creates contract configuration objects with ABIs for all Azuro Protocol contracts. ### Method Signature ```typescript function setupContracts(params: ContractAddresses): Contracts; ``` ### Parameters #### Path Parameters * **lp** (Address) - Required - Liquidity Pool contract address * **core** (Address) - Required - Core betting contract address * **relayer** (Address) - Required - Relayer contract address * **azuroBet** (Address) - Required - AzuroBet NFT contract address * **vault** (Address) - Required - Vault contract address * **paymaster** (Address) - Required - Paymaster contract address * **cashout** (Address) - Optional - Cashout contract address ### Returns **Contracts** object with all contract configurations: #### Success Response - **lp** (ContractConfig) - LP contract with address and ABI - **core** (ContractConfig) - Core contract with address and ABI - **relayer** (ContractConfig) - Relayer contract with address and ABI - **azuroBet** (ContractConfig) - AzuroBet NFT with address and ABI - **vault** (ContractConfig) - Vault contract with address and ABI - **paymaster** (ContractConfig) - Paymaster contract with address and ABI - **cashout** (ContractConfig | undefined) - Cashout contract (if provided) ### Example ```typescript import { setupContracts } from '@azuro-org/toolkit' const contracts = setupContracts({ lp: '0x0FA7FB5407eA971694652E6E16C12A52625DE1b8', core: '0xF9548Be470A4e130c90ceA8b179FCD66D2972AC7', relayer: '0x8dA05c0021e6b35865FDC959c54dCeF3A4AbBa9d', azuroBet: '0x7A1c3FEf712753374C4DCe34254B96faF2B7265B', vault: '0x1a0612FE7D0Def35559a1f71Ff155e344Ae69d2C', paymaster: '0xeD5760fC2d2f6d363d73e576173e5e8Ca6A877e1', cashout: '0x4a2BB4211cCF9b9eA6eF01D0a61448154ED19095', }) console.log(contracts.core.address) // Use contracts.core.abi with viem's contract methods ``` ``` -------------------------------- ### Get Wave Statistics Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/wave-operations.md Retrieves aggregated statistics for a wave campaign. You can specify a waveId or use 'active' to get stats for the current active wave. Defaults to chain ID 137 (Polygon). ```typescript function getWaveStats(params?: { waveId?: WaveId; chainId?: ChainId; }): Promise; ``` ```typescript import { getWaveStats } from '@azuro-org/toolkit' const stats = await getWaveStats({ waveId: 'active' }) console.log(`Total volume: ${stats.totalVolume}`) console.log(`Participants: ${stats.totalParticipants}`) ``` -------------------------------- ### Get API Endpoints by Chain ID Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/configuration.md Use helper functions to get specific API endpoints (REST, GraphQL, WebSocket) based on the provided chain ID. Supports production and development endpoints. ```typescript import { getFeedGraphqlEndpoint, getBetsGraphqlEndpoint, getApiEndpoint, getSocketEndpoint, } from '@azuro-org/toolkit' // Get REST API endpoint const api = getApiEndpoint(137) // Polygon // Returns: 'https://api.onchainfeed.org/api/v1/public' // Get bets GraphQL endpoint const betsGql = getBetsGraphqlEndpoint(137) // Returns: 'https://thegraph.onchainfeed.org/subgraphs/name/azuro-protocol/azuro-api-polygon-v3' // Get WebSocket endpoint for real-time updates const socket = getSocketEndpoint(137) // Returns: 'wss://streams.onchainfeed.org/v1/streams' // Get legacy feed endpoint (deprecated for v2 feed) const legacyGql = getFeedGraphqlEndpoint(137) // Returns: 'https://thegraph-1.onchainfeed.org/subgraphs/name/azuro-protocol/azuro-data-feed-polygon' ``` -------------------------------- ### Import Azuro Toolkit Components Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/REFERENCE-INDEX.md Demonstrates how to import all components or specific functions, types, and configuration constants from the '@azuro-org/toolkit' package. ```typescript // Import everything import * as Toolkit from '@azuro-org/toolkit' // Import specific items import { // Functions createBet, getBet, getGamesByFilters, // Types type BetClientData, type GameData, GameState, BetStatus, // Configuration polygonData, baseData, ODDS_DECIMALS, // ABIs coreAbi, } from '@azuro-org/toolkit' ``` -------------------------------- ### Get WebSocket Endpoint Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/configuration.md Retrieves the WebSocket endpoint for real-time updates on a given chain ID. ```APIDOC ## Get WebSocket Endpoint ### Description Retrieves the WebSocket endpoint for real-time updates on a given chain ID. ### Method GET (for WebSocket endpoint URL retrieval) ### Endpoint `/v1/streams` (This is a base path, the full URL is constructed by the toolkit function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { getSocketEndpoint } from '@azuro-org/toolkit' const socket = getSocketEndpoint(137) ``` ### Response #### Success Response (200) - **url** (string) - The URL of the WebSocket endpoint. #### Response Example ```json { "url": "wss://streams.onchainfeed.org/v1/streams" } ``` ``` -------------------------------- ### Import All Exports from Azuro Toolkit Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/README.md This snippet shows how to import all available exports from the main '@azuro-org/toolkit' package. It includes configuration, constants, bet operations, feed operations, cashout, bonuses, authentication, user, wave, utilities, endpoints, ABIs, and types. ```typescript import { // Configuration & chain data environments, Environment, polygonData, baseData, chainsData, chainsDataByEnv, // Constants ODDS_DECIMALS, ODDS_COMBO_FEE_MODIFIER, // Bet operations getBetStatus, BetStatus, getBetFee, getBetTypedData, getComboBetTypedData, createBet, createComboBet, getBet, getBetCalculation, getBetsByBettor, // Feed operations getConditionsByGameIds, getConditionsState, getPredefinedCombo, getGamesByFilters, getGamesByIds, getNavigation, getSports, searchGames, GameOrderBy, GameState, ConditionState, // Cashout getPrecalculatedCashouts, getCalculatedCashout, getCashoutTypedData, createCashout, CashoutState, getCashout, // Bonus getBonuses, BonusStatus, getAvailableFreebets, // Auth getSiweNonce, verifySiwe, buildSiweMessage, // User getUserFavorites, createUserFavorite, deleteUserFavorite, // Wave getWaveLevels, WaveLevelName, getWaveStats, getWavePeriods, getWaveLeaderBoard, activateWave, // Utilities setupContracts, calcMinOdds, getIsPendingResolution, groupConditionsByMarket, getProviderFromId, // Endpoints getFeedGraphqlEndpoint, getBetsGraphqlEndpoint, getApiEndpoint, getSocketEndpoint, // ABIs lpAbi, coreAbi, azuroBetAbi, relayerAbi, cashoutAbi, vaultAbi, paymasterAbi, // Types type CreateBetResponse, type BetClientData, type BetOrderState, type GameData, type PaginatedGamesResponse, // ... and many more type exports } from '@azuro-org/toolkit' ``` -------------------------------- ### Get Bets GraphQL Endpoint Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/configuration.md Retrieves the production GraphQL endpoint for bets on a given chain ID. ```APIDOC ## Get Bets GraphQL Endpoint ### Description Retrieves the production GraphQL endpoint for bets on a given chain ID. ### Method GET (for GraphQL endpoint URL retrieval) ### Endpoint `/subgraphs/name/azuro-protocol/azuro-api-polygon-v3` (This is a base path, the full URL is constructed by the toolkit function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { getBetsGraphqlEndpoint } from '@azuro-org/toolkit' const betsGql = getBetsGraphqlEndpoint(137) ``` ### Response #### Success Response (200) - **url** (string) - The URL of the Bets GraphQL endpoint. #### Response Example ```json { "url": "https://thegraph.onchainfeed.org/subgraphs/name/azuro-protocol/azuro-api-polygon-v3" } ``` ``` -------------------------------- ### Get REST API Endpoint Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/configuration.md Retrieves the production REST API endpoint for a given chain ID. ```APIDOC ## Get REST API Endpoint ### Description Retrieves the production REST API endpoint for a given chain ID. ### Method GET ### Endpoint `/api/v1/public` (This is a base path, the full URL is constructed by the toolkit function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { getApiEndpoint } from '@azuro-org/toolkit' const api = getApiEndpoint(137) // Polygon ``` ### Response #### Success Response (200) - **url** (string) - The URL of the REST API endpoint. #### Response Example ```json { "url": "https://api.onchainfeed.org/api/v1/public" } ``` ``` -------------------------------- ### Get Bet Status Function Signature Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/bet-operations.md Defines the signature for the getBetStatus function, outlining its parameters and return type. ```typescript function getBetStatus(props: { games: Array<{ state: GameState; startsAt: string }>; orderState: BetOrderState | null; graphStatus: BetStatus | null; }): BetStatus; ``` -------------------------------- ### getConditionsByGameIds Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/feed-operations.md Retrieves all betting conditions/markets for specific games. This function is useful for getting all available betting options for a given set of games. ```APIDOC ## getConditionsByGameIds ### Description Retrieves all betting conditions/markets for specific games. ### Parameters #### Query Parameters - **chainId** (ChainId) - Required - Chain ID to query - **gameIds** (string[]) - Required - Array of game IDs ### Returns **ConditionDetailedData[]** array, each containing: - **conditionId** (string) - Unique condition/market ID - **game** (GameInfo) - Minimal game info reference - **outcomes** (OutcomeData[]) - Array of possible outcomes - **outcomes[].outcomeId** (string) - Outcome ID (selection) - **outcomes[].odds** (string) - Decimal odds (scaled by 10^12) - **outcomes[].selection** (SelectionInfo) - Name and ID of selection ### Example ```typescript import { getConditionsByGameIds } from '@azuro-org/toolkit' const conditions = await getConditionsByGameIds({ chainId: 137, gameIds: ['123'], }) conditions.forEach(condition => { console.log(`Market: ${condition.conditionId}`) condition.outcomes.forEach(outcome => { console.log(` ${outcome.selection.name}: ${outcome.odds}`) }) }) ``` ``` -------------------------------- ### buildSiweMessage Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/bonus-and-auth.md Constructs an EIP-4361 (Sign In With Ethereum) message string for wallet signing. ```APIDOC ## buildSiweMessage Constructs an EIP-4361 (Sign In With Ethereum) message string for wallet signing. ### Function Signature ```typescript function buildSiweMessage(params: BuildSiweMessageParams): string; ``` ### Parameters #### Parameters - **domain** (string) - Required - Domain name (e.g., 'app.example.com') - **address** (Address) - Required - User's wallet address (EIP-55 checksummed) - **uri** (string) - Required - Full URI of signing origin - **chainId** (number) - Required - Chain ID (e.g., 137 for Polygon) - **nonce** (string) - Required - Nonce from getSiweNonce - **issuedAt** (number) - Required - Issued timestamp (unix milliseconds) - **expiresAt** (number) - Optional - Expiration timestamp (unix milliseconds) - **statement** (string) - Optional - Optional statement/disclaimer - **version** (string) - Optional - SIWE protocol version (default: '1') ### Returns **string** — EIP-4361 formatted message ready for signMessage(). ### Example ```typescript import { buildSiweMessage, getSiweNonce } from '@azuro-org/toolkit' import { signMessage } from 'viem/actions' const { nonce } = await getSiweNonce({ chainId: 137, affiliateId: '0x123...' }) const message = buildSiweMessage({ domain: 'app.example.com', address: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', uri: 'https://app.example.com', chainId: 137, nonce, issuedAt: Date.now(), expiresAt: Date.now() + 3600000, statement: 'Sign in to place bets on Azuro', }) const signature = await signMessage(walletClient, { message }) ``` ``` -------------------------------- ### Accessing Chain Configuration Data Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/configuration.md Demonstrates how to import and access chain configuration data using environment constants, environment enums, or chain IDs. Ensure necessary imports from '@azuro-org/toolkit'. ```typescript import { polygonData, baseData, chainsData, chainsDataByEnv } from '@azuro-org/toolkit' // By environment constant const config = polygonData // By environment enum import { Environment, chainsDataByEnv } from '@azuro-org/toolkit' const config = chainsDataByEnv[Environment.PolygonUSDT] // By chain ID const config = chainsData[137] // Polygon const config = chainsData[8453] // Base ``` -------------------------------- ### Project File Structure Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/GENERATION-SUMMARY.md This tree displays the organization of the Azuro Protocol Toolkit project, including documentation files, API reference directories, and source code locations. ```tree output/ ├── README.md # Start here - package overview ├── REFERENCE-INDEX.md # Complete function/type index ├── configuration.md # Chain setup and constants ├── types.md # All type definitions ├── errors.md # Error codes and handling ├── GENERATION-SUMMARY.md # This file └── api-reference/ ├── bet-operations.md # Betting functions ├── feed-operations.md # Game/market functions ├── cashout-operations.md # Cashout functions ├── bonus-and-auth.md # Bonus and auth functions ├── user-favorites.md # User preference functions ├── utility-functions.md # Helper functions └── wave-operations.md # Wave campaign functions ``` -------------------------------- ### getIsPendingResolution Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/utility-functions.md Determines if a game is awaiting settlement of its bets. It checks the game's state and start time to ascertain if resolution is pending. ```APIDOC ## getIsPendingResolution ### Description Determines if a game is awaiting settlement of its bets. ### Parameters #### Path Parameters - **game** (object) - Required - Game object with state and start time - **game.state** (GameState) - Required - Current game state - **game.startsAt** (string) - Required - Unix timestamp in seconds as string ### Returns **boolean** — True if game has finished and is awaiting bet resolution/settlement. ### Example ```typescript import { getIsPendingResolution, GameState } from '@azuro-org/toolkit' const game = { state: GameState.Finished, startsAt: '1234567890', } if (getIsPendingResolution(game)) { console.log('Waiting for this game to be settled') } ``` ``` -------------------------------- ### Get Legacy Feed GraphQL Endpoint Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/configuration.md Retrieves the legacy GraphQL endpoint for the feed (deprecated for v2 feed) on a given chain ID. ```APIDOC ## Get Legacy Feed GraphQL Endpoint ### Description Retrieves the legacy GraphQL endpoint for the feed (deprecated for v2 feed) on a given chain ID. ### Method GET (for GraphQL endpoint URL retrieval) ### Endpoint `/subgraphs/name/azuro-protocol/azuro-data-feed-polygon` (This is a base path, the full URL is constructed by the toolkit function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { getFeedGraphqlEndpoint } from '@azuro-org/toolkit' const legacyGql = getFeedGraphqlEndpoint(137) ``` ### Response #### Success Response (200) - **url** (string) - The URL of the legacy GraphQL endpoint. #### Response Example ```json { "url": "https://thegraph-1.onchainfeed.org/subgraphs/name/azuro-protocol/azuro-data-feed-polygon" } ``` ``` -------------------------------- ### Azuro Protocol Toolkit Module Organization Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/README.md Illustrates the directory structure and key files within the Azuro Protocol Toolkit's source code. ```tree src/ ├── config.ts # Chain data and constants ├── envs.ts # Environment enum ├── global.ts # Global types and enums ├── abis/ # Smart contract ABIs ├── utils/ │ ├── bet/ # Bet operations │ ├── feed/ # Game/condition queries │ ├── cashout/ # Cashout operations │ ├── bonus/ # Freebet operations │ ├── auth/ # SIWE authentication │ ├── user/ # User favorites │ ├── wave/ # Wave campaigns │ ├── helpers/ # Utility helpers │ └── ... └── index.ts # Main entry point (all exports) ``` -------------------------------- ### Authenticate User with SIWE using Azuro Toolkit Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/00-START-HERE.md Authenticate users using the Sign-In with Ethereum (SIWE) flow. This process includes obtaining a nonce, building the SIWE message, signing it with the user's wallet, and verifying the signature. ```typescript import { getSiweNonce, buildSiweMessage, verifySiwe } from '@azuro-org/toolkit' import { signMessage } from 'viem/actions' // Get nonce const { nonce } = await getSiweNonce({ chainId: 137, affiliateId: '0x123...', }) // Build message const message = buildSiweMessage({ domain: 'app.example.com', address: userAddress, uri: 'https://app.example.com', chainId: 137, nonce, issuedAt: Date.now(), }) // Sign const signature = await signMessage(walletClient, { message }) // Verify const result = await verifySiwe({ chainId: 137, message, signature, affiliateId: '0x123...', }) if (result.valid) { console.log('User authenticated:', result.address) } ``` -------------------------------- ### GameOrderBy Enum Definition Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/types.md An enum specifying the fields that can be used for sorting game results. Currently supports sorting by start time and turnover. ```typescript enum GameOrderBy { StartsAt = 'startsAt', Turnover = 'turnover' } ``` -------------------------------- ### Cash Out a Bet with Azuro Toolkit Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/00-START-HERE.md Initiate a cashout for a bet. This involves calculating the potential cashout amount, generating typed data for signing, signing with a wallet, and submitting the cashout request. ```typescript import { getCalculatedCashout, createCashout, CashoutState } from '@azuro-org/toolkit' import { signTypedData } from 'viem/actions' // Calculate cashout const cashout = await getCalculatedCashout({ chainId: 137, betId: '12345', }) // Sign it const typedData = getCashoutTypedData({ chainId: 137, calculationId: cashout.calculationId, betId: '12345', minOdds: '1000000000000', }) const signature = await signTypedData(walletClient, typedData) // Submit const result = await createCashout({ chainId: 137, calculationId: cashout.calculationId, attention: 'I agree', signature, }) if (result.state === CashoutState.Accepted) { console.log('Cashout complete!') } ``` -------------------------------- ### Place a Bet Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/README.md Use this snippet to place a bet. It involves fetching fee information, preparing client data, obtaining typed data for signing, signing with a wallet, and finally submitting the bet. ```typescript import { getBetFee, getBetTypedData, createBet, BetClientData } from '@azuro-org/toolkit' import { signTypedData } from 'viem/actions' // Get fee information const fee = await getBetFee(137) // Prepare client data const clientData: BetClientData = { attention: 'I agree to place this bet', affiliate: '0x...', core: '0x...', expiresAt: Date.now() + 3600000, chainId: 137, relayerFeeAmount: fee.relayerFeeAmount, isBetSponsored: false, isFeeSponsored: false, isSponsoredBetReturnable: false, } // Get typed data for signing const typedData = getBetTypedData({ account: userAddress, clientData, bet: { conditionId: '123', outcomeId: '1', minOdds: '1500000000000', amount: '1000000', nonce: '1', }, }) // Sign with wallet const signature = await signTypedData(walletClient, typedData) // Submit bet const result = await createBet({ account: userAddress, clientData, bet: { /* ... */ }, signature, }) console.log('Bet ID:', result.id) ``` -------------------------------- ### Get Viem Chain Provider from Chain ID Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/utility-functions.md Maps a chain ID to its corresponding Viem Chain object. This is useful for network configuration in Viem. ```typescript import { getProviderFromId } from '@azuro-org/toolkit' const chain = getProviderFromId(137) console.log(chain.name) // 'Polygon' console.log(chain.rpcUrls) // RPC endpoint URLs ``` -------------------------------- ### Get User Favorites Function Signature Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/user-favorites.md Defines the function signature for retrieving user favorites. It takes `GetUserFavoritesParams` and returns a `Promise` resolving to `GetUserFavoritesResult`. ```typescript function getUserFavorites(params: GetUserFavoritesParams): Promise; ``` -------------------------------- ### Azuro Protocol Toolkit Peer Dependencies Source: https://github.com/azuro-protocol/toolkit/blob/main/README.md List of required peer dependencies for the Azuro Protocol Toolkit. ```bash @azuro-org/dictionaries@^3.0.28 graphql-tag@^2.12.6 viem@^2.37.4 ``` -------------------------------- ### Get Cashout Status with TypeScript Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/cashout-operations.md Retrieves the status of a previously submitted cashout using its ID and chain ID. Ensure you have the necessary imports from '@azuro-org/toolkit'. ```typescript import { getCashout, CashoutState } from '@azuro-org/toolkit' const cashout = await getCashout({ chainId: 137, cashoutId: 'cashout_123', }) console.log('Status:', cashout.state) console.log('Payout:', cashout.payoutAmount) ``` -------------------------------- ### Create a Bet with Azuro Toolkit Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/bet-operations.md Submits a signed single bet to the Azuro relayer for on-chain placement. Ensure you have the necessary parameters like account, clientData, bet details, and a valid EIP-712 signature. ```typescript import { createBet } from '@azuro-org/toolkit' const result = await createBet({ account: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', clientData: { /* from getBetFee or similar */ }, bet: { conditionId: '123', outcomeId: '1', minOdds: '1500000000000', amount: '1000000', nonce: '1', }, signature: '0xabc123...', }) console.log('Bet ID:', result.id) console.log('State:', result.state) ``` -------------------------------- ### Handle getWaveLevels 404 Not Found Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/errors.md Use `getWaveLevels` to retrieve wave data. It returns `null` for a 404 status, allowing for graceful handling, while other errors are thrown. ```typescript // Returns null instead of throwing on 404 const levels = await getWaveLevels({ waveId: 'active' }) if (!levels) { console.log('Wave not found') } // Throws on other errors try { const levels = await getWaveLevels({ waveId: 999 }) } catch (error) { console.error(`Status ${error.message}`) } ``` -------------------------------- ### Fetch Conditions State Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/feed-operations.md Use this function to get the current on-chain state of specific conditions or markets. Requires chain ID and an array of condition IDs. ```typescript import { getConditionsState } from '@azuro-org/toolkit' const states = await getConditionsState({ chainId: 137, conditionIds: ['123', '124'], }) states.forEach(state => { console.log(`Condition ${state.conditionId}: ${state.state}`) if (state.outcome !== null) { console.log(` Winner: ${state.outcome}`) } }) ``` -------------------------------- ### Check if Game is Pending Resolution Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/utility-functions.md Use this function to determine if a game has finished and is awaiting bet resolution. It requires a game object with its state and start time. ```typescript import { getIsPendingResolution, GameState } from '@azuro-org/toolkit' const game = { state: GameState.Finished, startsAt: '1234567890', } if (getIsPendingResolution(game)) { console.log('Waiting for this game to be settled') } ``` -------------------------------- ### getPredefinedCombo Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/feed-operations.md Fetches pre-built combination bet suggestions for specific games. ```APIDOC ## getPredefinedCombo ### Description Fetches pre-built combination bet suggestions for specific games. ### Method ```typescript function getPredefinedCombo(params: GetPredefinedComboParams): Promise; ``` ### Parameters #### Path Parameters - **chainId** (ChainId) - Required - Chain ID to query - **gameIds** (string[]) - Required - Array of game IDs for combo ### Returns **PredefinedComboResult** containing pre-selected combo options: #### Success Response - **combos** (PredefinedComboData[]) - Array of combo suggestions - **combos[].name** (string) - Combo name/description - **combos[].conditions** (PredefinedComboConditionData[]) - Pre-selected conditions in combo ### Example ```typescript import { getPredefinedCombo } from '@azuro-org/toolkit' const combos = await getPredefinedCombo({ chainId: 137, gameIds: ['123', '124'], }) combos.combos.forEach(combo => { console.log(`${combo.name}:`, combo.conditions.length, 'conditions') }) ``` ``` -------------------------------- ### Bonus and Authentication Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/INDEX.md Functions related to user bonuses, freebets, and authentication using Sign-In with Ethereum (SIWE). ```APIDOC ## Bonus and Authentication ### Description Manages user bonuses, available freebets, and implements authentication flows using the Sign-In with Ethereum (SIWE) standard. ### Functions - `getBonuses()`: Retrieves information about available bonuses. - `getAvailableFreebets()`: Lists the user's available freebets. - `getSiweNonce()`: Requests a nonce for SIWE authentication. - `buildSiweMessage()`: Constructs an EIP-4361 compliant SIWE message. - `verifySiwe()`: Verifies the signature of a SIWE message. ``` -------------------------------- ### Get Bet Fee Information Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/bet-operations.md Retrieves current relayer fee details, including gas price and bet token exchange rate. Use this to estimate transaction costs. ```typescript function getBetFee(chainId: ChainId): Promise; ``` ```typescript import { getBetFee } from '@azuro-org/toolkit' const feeInfo = await getBetFee(137) // Polygon console.log('Relayer fee:', feeInfo.beautyRelayerFeeAmount, feeInfo.symbol) console.log('Gas limit:', feeInfo.gasLimit) ``` -------------------------------- ### Fetch Predefined Combinations Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/api-reference/feed-operations.md Retrieve pre-built combination bet suggestions for specified games. Requires chain ID and an array of game IDs. ```typescript import { getPredefinedCombo } from '@azuro-org/toolkit' const combos = await getPredefinedCombo({ chainId: 137, gameIds: ['123', '124'], }) combos.combos.forEach(combo => { console.log(`${combo.name}:`, combo.conditions.length, 'conditions') }) ``` -------------------------------- ### Azuro Protocol Toolkit Betting Data Flow Source: https://github.com/azuro-protocol/toolkit/blob/main/_autodocs/README.md Outlines the sequence of operations for placing a bet using the Azuro Protocol Toolkit. ```text getBetFee → getBetTypedData → signTypedData → createBet → getBet ```