import type { AttestEnclaveResponse, BridgeEnclaveResponse, ClockResponse, FeedRequest, FetchQuoteResponse, FetchSignaturesConsensusResponse, HealthyOraclesResponse, PingResponse, RandomnessRevealResponse } from './types/gateway.js'; import { CrossbarClient } from './crossbar-client.js'; export { GatewayRequestError, summarizeGatewayRequestError, } from './gateway-request-error.js'; export * from './types/gateway.js'; /** * Gateway - Interface to Switchboard Oracle Network * * The Gateway class provides methods to interact with Switchboard's oracle network, * allowing you to fetch signatures, quotes, and randomness from oracle operators. * * ## Variable Overrides * * Many methods support `variableOverrides`, which replace matching `${NAME}` * placeholders in string-valued task fields for one execution request. Overrides * can supply credentials, endpoints, or other request-scoped values without changing * the stored oracle job definition. * * ### Trust Model * * Override values are execution inputs selected by the requester. The feed identity * commits to the stored job definition, and oracle signatures commit to that identity * and the resulting value, but neither commits to the override map itself. * * Semantic overrides, such as URLs, symbols, paths, or calculation parameters, are * appropriate when the update path is controlled and feed consumers intentionally * trust the requester to select those values. For permissionlessly updated feeds, * keep data sources, data selection, and calculations fixed in the job definition. * Credentials are the usual override because they grant access without intentionally * changing the feed's declared semantics. * * ### How Variable Overrides Work * * When you provide variableOverrides, the gateway will: * 1. Parse the oracle job definitions * 2. Replace any matching variable references with your provided values * 3. Execute the jobs with the overridden values * 4. Return signed oracle responses * * Overrides are substitution-based. Override names are not automatically routed * to a service. A task must contain a matching `${NAME}` reference unless its * documentation explicitly defines a reserved override. * * ### API Key Behavior * * For new jobs, API-key overrides follow the same pattern across services: * put a `${NAME}` placeholder in the task's API-key field and provide the * matching `NAME` value in `variableOverrides`. * * | Task | Preferred task setting | Request setting | * | --- | --- | --- | * | `JupiterSwapTask` | `apiKey: "${NAME}"` | Matching `NAME` | * | Pyth Hermes (`pythAddress`) | `pythConfigs.apiKey: "${NAME}"` | Matching `NAME` | * * For Jupiter, `JUPITER_API_KEY` is a naming convention rather than a reserved * override. Supplying it without a matching `apiKey: "${JUPITER_API_KEY}"` * placeholder does not change the task's authentication. A non-empty literal * `apiKey` is also accepted. Each Jupiter task resolves its own field, so one * job may mix different keys and tasks that use the built-in compatibility key. * Missing or literal blank fields use that built-in key. An unresolved * placeholder, or a placeholder whose effective cache/override value is blank, * fails before Jupiter is contacted. A preceding `CacheTask` value takes normal * substitution precedence over a request override with the same name. * * For Pyth Hermes, `PYTH_API_KEY` is also a reserved compatibility fallback * for jobs that omit or leave `pythConfigs.apiKey` empty. The fallback is * request-wide: every `pythAddress` task in that execution without its own * non-empty `apiKey` receives the same key. A non-empty task field wins, so * separate Pyth tasks can use different placeholders and keys. `pythPushFeedId` * reads an on-chain account and does not use a Hermes API key. * * ### Example Usage * * \`\`\`typescript * const apiKey = process.env.API_KEY; * if (!apiKey) throw new Error('API_KEY is required'); * * // `oracleJob` contains an ${API_KEY} placeholder in an authentication field. * const overrides = { * API_KEY: apiKey, * }; * * const response = await gateway.fetchSignaturesConsensus({ * feedConfigs: [ * { * jobs: [oracleJob], * maxVariance: 1, * minResponses: 1, * }, * ], * numSignatures: 3, * variableOverrides: overrides, * }); * \`\`\` * * ### Best Practices * * 1. **Security**: Prefer overrides when credentials should be supplied per request * 2. **Environment Management**: Use overrides to switch between dev/staging/prod * 3. **Flexibility**: Design jobs with variables for maximum reusability * 4. **Validation**: Ensure all required variables are provided in overrides * 5. **Documentation**: Document expected variables in your job definitions * * @class Gateway */ export declare class Gateway { readonly gatewayUrl: string; /** * Constructs a Gateway instance * * @param {string | Gateway} gatewayUrlOrInstance - The URL of the switchboard gateway, or another Gateway instance to clone * * @example * ```typescript * // Create from URL string * const gateway1 = new Gateway("https://gateway.switchboard.xyz"); * * // Clone from another Gateway instance * const gateway2 = new Gateway(gateway1); * ``` */ constructor(gatewayUrlOrInstance: string | Gateway); ping(): Promise; /** * * Fetches signatures from the gateway. * REST API endpoint: /api/v1/gateway_attest_enclave * @param timestamp The timestamp of the attestation * @param quote The quote of the attestation * @param oracle_pubkey The oracle's public key * @param oracle_reward_wallet The oracle's reward wallet * @param oracle_ed25519_enclave_signer The oracle's ed25519 enclave signer * @param oracle_secp256k1_enclave_signer The oracle's secp256k1 enclave signer * @param recentHash The chain metadata to sign with. Blockhash or slothash. * @returns A promise that resolves to the attestation response. * @throws if the request fails. */ fetchAttestation(params: { timestamp: number; quote: string; oracle_pubkey: string; oracle_reward_wallet: string; oracle_ed25519_enclave_signer: string; oracle_secp256k1_enclave_signer: string; recentHash: string; }): Promise; /** * Fetches an attestation quote from the gateway. * * REST API endpoint: /api/v1/gateway_fetch_quote * * * @param blockhash The blockhash to fetch the quote for. * @param get_for_oracle Whether to fetch the quote for the oracle. * @param get_for_guardian Whether to fetch the quote for the guardian. * @returns A promise that resolves to the quote response. * @throws if the request fails. */ fetchAttestationQuote(params: { blockhash: string; get_for_oracle: boolean; get_for_guardian: boolean; }): Promise; /** * Fetches signatures using consensus mechanism * REST API endpoint: /api/v1/fetch_signatures_consensus * * @param feedConfigs Array of feed configurations to fetch signatures for. * V1 feed config `maxVariance` is a human percent (1 = 1%) and is scaled by 1e9 here. * Use `maxVarianceScaled` instead when forwarding an exact 1e9-scaled integer, * such as a value read from an on-chain account. Do not provide both fields. * V2 feed config `feed.maxJobRangePct` must already be a raw scaled integer (1_000_000_000 = 1%). * @param useTimestamp Whether to use the timestamp in the response & to encode update signature. * @param numSignatures The number of oracles to fetch signatures from. * @param useEd25519 Whether to use Ed25519 signatures instead of secp256k1. * @param variableOverrides Optional variable overrides for task execution (e.g., {"API_KEY": "custom-key"}) * @returns A promise that resolves to the consensus response. * @throws if the request fails. */ fetchSignaturesConsensus(params: { feedConfigs: FeedRequest[]; useTimestamp?: boolean; numSignatures?: number; useEd25519?: boolean; variableOverrides?: Record; }): Promise; /** * Fetches oracle quote data from the gateway * * This method retrieves signed price quotes from oracle operators through * the gateway interface. It's the primary method for fetching oracle data * using the modern quote terminology. * * ## Protocol Details * - Uses Ed25519 signature scheme for efficient verification * - Supports both protobuf and legacy job specifications * - Implements consensus mechanism across multiple oracles * - Returns structured response with oracle metadata * * ## Response Structure * The returned response contains: * - `oracle_responses`: Array of signed oracle data * - `recent_hash`: Recent Solana block hash for replay protection * - `slot`: Recent slot number for temporal validation * * @param {CrossbarClient} crossbar - Crossbar client for data routing and feed resolution * @param {string[]} feedHashes - Array of feed hashes to fetch (hex strings, max 16) * @param {number} numSignatures - Number of oracle signatures required (default: 1, max based on queue config) * @returns {Promise} Oracle quote response with signatures * * @throws {Error} When gateway is unreachable or returns error * @throws {Error} When crossbar cannot resolve feed hashes * @throws {Error} When insufficient oracles are available * * @since 2.14.0 * @see {@link fetchUpdateBundle} - Deprecated equivalent method * @see {@link Queue.fetchQuoteIx} - High-level method that uses this internally * * @example * ```typescript * import { CrossbarClient } from '@switchboard-xyz/common'; * * // Initialize crossbar client * const crossbar = CrossbarClient.default(); * * // Single feed quote * const btcQuote = await gateway.fetchQuote( * crossbar, * ['0xef0d8b6fcd0104e3e75096912fc8e1e432893da4f18faedaacca7e5875da620f'], // BTC/USD * 1 // Single signature for fast updates * ); * * // Multi-feed quote for DeFi protocol * const defiAssets = [ * '0xef0d8b6fcd0104e3e75096912fc8e1e432893da4f18faedaacca7e5875da620f', // BTC/USD * '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef', // ETH/USD * '0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890', // SOL/USD * '0x9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba' // USDC/USD * ]; * * const portfolioQuote = await gateway.fetchQuote( * crossbar, * defiAssets, * 5 // Higher consensus for financial operations * ); * * // Access oracle responses * console.log('Oracle responses:', portfolioQuote.oracle_responses.length); * console.log('Recent slot:', portfolioQuote.slot); * * // Process individual feed responses * portfolioQuote.oracle_responses.forEach((oracle, index) => { * oracle.feed_responses.forEach((feed, feedIndex) => { * console.log(`Oracle ${index}, Feed ${feedIndex}:`, { * feedHash: feed.feed_hash, * value: feed.success_value, * confidence: feed.min_oracle_samples * }); * }); * }); * ``` */ fetchQuote(crossbar: CrossbarClient, feedHashes: string[], numSignatures?: number, variableOverrides?: Record): Promise; /** * Sends a request to the gateway bridge enclave. * * REST API endpoint: /api/v1/gateway_bridge_enclave * * @param chainHash The chain hash to include in the request. * @param oraclePubkey The public key of the oracle. * @param queuePubkey The public key of the queue. * @returns A promise that resolves to the response. * @throws if the request fails. */ fetchBridgingMessage(params: { chainHash: string; oraclePubkey: string; queuePubkey: string; }): Promise; /** * Fetches the randomness reveal from the gateway. * @param params The parameters for the randomness reveal. * @returns The randomness reveal response. */ fetchRandomnessReveal(params: { randomnessAccount: { toBuffer(): Buffer; }; slothash: string; slot: number; rpc?: string; } | { randomnessId: string; timestamp: number; minStalenessSeconds: number; }): Promise; /** * Fetches a list of healthy oracles with their current health metrics * * This method queries the gateway for all available oracles that are currently * healthy and operational. The response includes comprehensive health metrics * for each oracle including active connections, subscriptions, feed counts, * and WebSocket connection status. * * REST API endpoint: GET /gateway/api/v1/healthy_oracles * * @returns A promise that resolves to the healthy oracles response containing * a list of oracles and their health metrics * @throws if the request fails * * @example * ```typescript * const gateway = new Gateway("https://gateway.switchboard.xyz"); * const response = await gateway.fetchHealthyOracles(); * * console.log(`Found ${response.count} healthy oracles`); * response.oracles.forEach(oracle => { * console.log(`Oracle: ${oracle.oracle_url}`); * console.log(`Active connections: ${oracle.active_connections}`); * console.log(`Total feeds: ${oracle.total_feeds}`); * }); * ``` */ fetchHealthyOracles(): Promise; /** * Fetches the current server time from the Binance clock proxy * * This method queries the gateway's Binance time proxy endpoint which returns * the current server time in milliseconds. This is useful for clock synchronization * and ensuring timestamps are accurate for trading operations. * * REST API endpoint: GET /api/v3/time * Proxies: https://api.binance.com/api/v3/time * * @returns A promise that resolves to the clock response containing server time * @throws if the request fails * * @example * ```typescript * const gateway = new Gateway("https://gateway.switchboard.xyz"); * const response = await gateway.fetchClock(); * * console.log(`Server time: ${response.serverTime}`); * console.log(`Server date: ${new Date(response.serverTime)}`); * * // Calculate clock offset * const localTime = Date.now(); * const offset = response.serverTime - localTime; * console.log(`Clock offset: ${offset}ms`); * ``` */ fetchClock(): Promise; endpoint(): string; toString(): string; [Symbol.toPrimitive](hint: string): string | null; } //# sourceMappingURL=gateway.d.ts.map