From 3eb23f786706376ae5599f0628016ab631a0695c Mon Sep 17 00:00:00 2001 From: Alexander Kolberg Date: Mon, 23 Feb 2026 14:36:42 +0200 Subject: [PATCH 1/2] Move indexer clients to packages/services/indexer and remove old packages/indexer --- packages/indexer/src/indexer.gen.ts | 2765 -------------- packages/indexer/src/indexergw.gen.ts | 1787 --------- packages/services/indexer/src/indexer.gen.ts | 3386 +++++++++-------- .../services/indexer/src/indexergw.gen.ts | 2156 ++++++----- 4 files changed, 3109 insertions(+), 6985 deletions(-) delete mode 100644 packages/indexer/src/indexer.gen.ts delete mode 100644 packages/indexer/src/indexergw.gen.ts diff --git a/packages/indexer/src/indexer.gen.ts b/packages/indexer/src/indexer.gen.ts deleted file mode 100644 index 97d3d2472..000000000 --- a/packages/indexer/src/indexer.gen.ts +++ /dev/null @@ -1,2765 +0,0 @@ -/* eslint-disable */ -// sequence-indexer v0.4.0 caf5c4c3677ac2dce41858dce7cd727a7810845f -// -- -// Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. -// -// webrpc-gen -schema=merged.gen.json -service=Indexer -target=typescript -client -out=./clients/indexer.gen.ts - -// Webrpc description and code-gen version -export const WebrpcVersion = 'v1' - -// Schema version of your RIDL schema -export const WebrpcSchemaVersion = 'v0.4.0' - -// Schema hash generated from your RIDL schema -export const WebrpcSchemaHash = 'caf5c4c3677ac2dce41858dce7cd727a7810845f' - -// -// Client interface -// - -export interface IndexerClient { - addWebhookListener(req: AddWebhookListenerRequest, headers?: object, signal?: AbortSignal): Promise - - /** - * Fetches a single receipt and then will stop the subscription - */ - fetchTransactionReceipt( - req: FetchTransactionReceiptRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * Fetches a single receipt with filter and then will stop the subscription - */ - fetchTransactionReceiptWithFilter( - req: FetchTransactionReceiptWithFilterRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * Webhooks - */ - getAllWebhookListeners( - req: GetAllWebhookListenersRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * Get balance update aggregate values -- useful for syncing balance details of a contract, ie. from Skyweaver. - * Also consider using SubscribeBalanceUpdates or SubscribeEvents as other alternatives. - */ - getBalanceUpdates(req: GetBalanceUpdatesRequest, headers?: object, signal?: AbortSignal): Promise - - /** - * Get the chain ID of the indexer - */ - getChainID(headers?: object, signal?: AbortSignal): Promise - - /** - * Queries an ethereum node for the latest and confirm ETH balances - * DEPRECATED: use GetNativeTokenBalance instead - * - * @deprecated GetNativeTokenBalance - */ - getEtherBalance(req: GetEtherBalanceRequest, headers?: object, signal?: AbortSignal): Promise - - /** - * GetMarketplaceOrders queries marketplace orders with filtering and pagination. - * - * Retrieves buy orders (offers) and sell orders (listings) from a specific marketplace - * and collection with comprehensive filtering options. - * - * Parameters: - * marketplaceContractAddress: Target marketplace contract (required) - * collectionAddress: NFT collection contract (required) - * filter: MarketplaceOrderFilter with options: - * - isListing: true=listings, false=offers, omit=both - * - userAddresses: Include specific users - * - currencyAddresses: Filter by currencies (empty=all) - * - orderIds: Filter by specific order ids (empty=all) - * - tokenIds: Filter by specific tokens (empty=all) - * - excludeUserAddresses: Exclude specific users - * - blockNumberGt: Orders greater than block number - * - createdAtAfter: Orders after timestamp - * - orderStatuses: Filter by status (OPEN, CLOSED, CANCELLED) - * - returnExpired: Include expired orders - * page: Pagination control (optional) - * - * Returns: Updated pagination info and array of matching orders - */ - getMarketplaceOrders( - req: GetMarketplaceOrdersRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * GetMarketplaceTopOrders finds the most competitive orders for specific tokens. - * - * Optimized for price discovery, returns the best available orders for each token. - * Useful for displaying current market prices and finding trading opportunities. - * - * Parameters: - * marketplaceContractAddress: Target marketplace contract (required) - * collectionAddress: NFT collection contract (required) - * filter: MarketplaceTopOrdersFilter with options: - * - currencyAddresses: Consider specific currencies (empty=all) - * - tokenIds: Target token IDs (required, non-empty) - * - isListing: true=listings/sell orders, false=offers/buy orders - * - priceSort: ASC=lowest first, DESC=highest first - * - excludeUser: Hide orders from specific user - * - * Returns: Array of top-priced active orders, sorted by priceSort preference - */ - getMarketplaceTopOrders( - req: GetMarketplaceTopOrdersRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * GetNativeTokenBalance queries an ethereum node for the latest native token account balance. - * The native token is the token of the chain the indexer is connected to, for example, ETH on Ethereum - * and POL on Polygon. - */ - getNativeTokenBalance( - req: GetNativeTokenBalanceRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * GetTokenBalances returns a balance summary/details for a specific account. By default - * if accountAddress is left empty, it will use the account from the jwt session. - * - * Also, if contractAddress is undefined, then it will list all current user coins/collectibles. - * But, if contractAddress is provided, then it will return the token balances for the contract, this is - * only useful for 1155, but for other tokens, it can act as a filter for the single balance. - * - * DEPRECATED: use GetTokenBalancesSummary / GetTokenBalancesDetails - * - * @deprecated GetTokenBalancesSummary - */ - getTokenBalances(req: GetTokenBalancesRequest, headers?: object, signal?: AbortSignal): Promise - - /** - * GetTokenBalancesByContract returns a balances for a specific accounts and - * contracts. The collection ERC721 & ERC1155 tokens are represented as - * individual balances. - * - * If `filter` is not provided, it will error out as it requires at least - * contract address. - * - * If `filter.contractStatus` is not provided, it will include verified only - * tokens. - */ - getTokenBalancesByContract( - req: GetTokenBalancesByContractRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * GetTokenBalancesDetails returns a detailed balance summary for a specific - * accounts. The collection ERC721 & ERC1155 tokens are represented as - * individual balances. - * - * If `filter` is not provided, it will use the filter with account from the - * jwt session. - * - * If `filter.contractStatus` is not provided, it will include verified only - * tokens. - */ - getTokenBalancesDetails( - req: GetTokenBalancesDetailsRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * GetTokenBalancesSummary returns a summary of token balances for a specific - * accounts. The collection ERC721 & ERC1155 tokens are represented as a - * single aggregated balance. - * - * If `filter` is not provided, it will use the filter with account from the - * jwt session. - * - * If `filter.contractStatus` is not provided, it will include verified only - * tokens. - */ - getTokenBalancesSummary( - req: GetTokenBalancesSummaryRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * GetTokenIDRanges returns the range of tokenIDs for a token collection contract. - * This is useful for ERC-721 and ERC-1155 contracts to get the range of valid tokenIDs. It is similar to - * GetTokenIDs, but returns the range of tokenIDs instead of the list of tokenIDs, which is more efficient - * for large collections and very easy to the caller to expand the range into a list of tokenIDs. - * - * NOTE: this method will only return up to 15,000 ranges, if there are more ranges, it will return - * a boolean to indicate there are more ranges beyond the first 15,000. Therefore, if `moreRanges` is - * false then you have all the ranges, but if true, you need to make a follow up call to fetch the next - * page of ranges. - * - * As an example, if a NFT collection of 100,000 tokens uses ids from 1,2,3,...,100_000 then this endpoint - * will return just a single range from [1,100_000], but if there are gaps between the sequence, then - * those will be broken into separate range entries. - */ - getTokenIDRanges(req: GetTokenIDRangesRequest, headers?: object, signal?: AbortSignal): Promise - - /** - * GetTokenIDs returns the list of each individual token id for a token collection contract. - * This is useful for ERC-721 and ERC-1155 contracts to get the list of valid tokenIDs. - */ - getTokenIDs(req: GetTokenIDsRequest, headers?: object, signal?: AbortSignal): Promise - - getTokenPrice(req: GetTokenPriceRequest, headers?: object, signal?: AbortSignal): Promise - - getTokenPrices(req: GetTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise - - /** - * GetTokenSupplies returns the set of tokenIDs used by a contract address, supporting ERC-20, ERC-721, and ERC-1155 - * contracts, and their respective supply as well. - */ - getTokenSupplies(req: GetTokenSuppliesRequest, headers?: object, signal?: AbortSignal): Promise - - /** - * GetTokenSuppliesMap returns the token supplies of ERC-20 and ERC-1155 tokens as requested in the `tokenMap` - * represented as a map of contractAddress :: []tokenIDs. - * - * For an ERC-20 specify tokenIDs as an empty array or [0], for example, { '0xdef': [] } or { '0xdef': [0] } - * For ERC-1155 pass the array of tokens are strings, ie. { '0xabc': ['1', '2', '3'] } - */ - getTokenSuppliesMap( - req: GetTokenSuppliesMapRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * History of mined transactions for the account which includes a list of token transfers (sent/recieved) - * and sent transactions from a Sequence wallet - */ - getTransactionHistory( - req: GetTransactionHistoryRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - getWebhookListener(req: GetWebhookListenerRequest, headers?: object, signal?: AbortSignal): Promise - - listTokenPrices(req: ListTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise - - pauseAllWebhookListeners( - req: PauseAllWebhookListenersRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * Ping the indexer - */ - ping(headers?: object, signal?: AbortSignal): Promise - - removeAllWebhookListeners( - req: RemoveAllWebhookListenersRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - removeWebhookListener( - req: RemoveWebhookListenerRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - resumeAllWebhookListeners( - req: ResumeAllWebhookListenersRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * Get the current runtime health status of the indexer - */ - runtimeStatus(headers?: object, signal?: AbortSignal): Promise - - /** - * SubscribeBalanceUpdates listens to balance updates for a specific contract address - */ - subscribeBalanceUpdates( - req: SubscribeBalanceUpdatesRequest, - options: WebrpcStreamOptions - ): WebrpcStreamController - - /** - * SubscribeEvents listens to events on-chain based on the filter criteria - * - * TODO: some additional options can be passed such as block, reorg true, etc. - * or stay behind, etc. - */ - subscribeEvents(req: SubscribeEventsRequest, options: WebrpcStreamOptions): WebrpcStreamController - - /** - * Listen to transaction receipts on-chain based on the filter criteria - */ - subscribeReceipts( - req: SubscribeReceiptsRequest, - options: WebrpcStreamOptions - ): WebrpcStreamController - - /** - * Re-sync an incorrect token balance with the correct on-chain balance - * NOTE: this method is almost never used, but we've marked it internal in case - * we ever want to use it again. This method was written a very long time ago in - * scenarios when the indexer had little bugs, but now its solid. - */ - syncBalance(req: SyncBalanceRequest, headers?: object, signal?: AbortSignal): Promise - - toggleWebhookListener( - req: ToggleWebhookListenerRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - updateWebhookListener( - req: UpdateWebhookListenerRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * Get the current version of the indexer - */ - version(headers?: object, signal?: AbortSignal): Promise -} - -// -// Schema types -// - -export interface Asset { - id: number - collectionId: number - tokenId?: string - url?: string - metadataField: string - name?: string - filesize?: number - mimeType?: string - width?: number - height?: number - updatedAt?: string -} - -export interface BloomStats { - hitRatio: string - falsePositivesPercent: string - hitCount: number - missCount: number - falsePositives: number -} - -export interface BloomStatus { - enabled: boolean - initialized: boolean - bloomInitElapsedTime: string - stats: BloomStats -} - -export interface Bond { - pebble: PebbleMetrics - estimatedDiskUsagePerTable: any - estimatedDiskUsageTotal: string -} - -export interface ChainInfo { - chainId: number - chainName: string -} - -export interface ContractInfo { - chainId: number - address: string - source: string - name: string - type: string - symbol: string - decimals?: number - logoURI: string - deployed: boolean - bytecodeHash: string - extensions: ContractInfoExtensions - updatedAt: string - queuedAt?: string - status: ResourceStatus -} - -export interface ContractInfoExtensionBridgeInfo { - tokenAddress: string -} - -export interface ContractInfoExtensionIndexingInfo { - useOnChainBalance: boolean -} - -export interface ContractInfoExtensions { - link?: string - description?: string - categories?: Array - bridgeInfo?: { [key: string]: ContractInfoExtensionBridgeInfo } - indexingInfo?: ContractInfoExtensionIndexingInfo - ogImage?: string - ogName?: string - originChainId?: number - originAddress?: string - blacklist?: boolean - verified?: boolean - verifiedBy?: string - featured?: boolean - featureIndex?: number -} - -export enum ContractType { - UNKNOWN = 'UNKNOWN', - NATIVE = 'NATIVE', - ERC20 = 'ERC20', - ERC721 = 'ERC721', - ERC1155 = 'ERC1155', - SEQUENCE_WALLET = 'SEQUENCE_WALLET', - ERC20_BRIDGE = 'ERC20_BRIDGE', - ERC721_BRIDGE = 'ERC721_BRIDGE', - ERC1155_BRIDGE = 'ERC1155_BRIDGE', - SEQ_MARKETPLACE = 'SEQ_MARKETPLACE', - ERC6909 = 'ERC6909' -} - -export enum ContractVerificationStatus { - VERIFIED = 'VERIFIED', - UNVERIFIED = 'UNVERIFIED', - ALL = 'ALL' -} - -export interface DiskUsage { - humanReadable: string - used: number - size: number - percent: number - dirs: { [key: string]: string } -} - -export interface EtherBalance { - accountAddress: string - balanceWei: string -} - -export interface EventDecoded { - topicHash: string - eventSig: string - types: Array - names: Array - values: Array -} - -export interface EventFilter { - events?: Array - contractAddresses?: Array - accounts?: Array - tokenIDs?: Array -} - -export interface EventLog { - id: number - uid: string - type: EventLogType - blockNumber: number - blockHash: string - parentBlockHash: string - contractAddress: string - contractType: ContractType - txnHash: string - txnIndex: number - txnLogIndex: number - logDataType: EventLogDataType - ts: string - txnInfo?: TxnInfo - rawLog?: { [key: string]: any } - event?: EventDecoded -} - -export enum EventLogDataType { - EVENT = 'EVENT', - TOKEN_TRANSFER = 'TOKEN_TRANSFER', - NATIVE_TOKEN_TRANSFER = 'NATIVE_TOKEN_TRANSFER', - SEQUENCE_TXN = 'SEQUENCE_TXN' -} - -export enum EventLogType { - UNKNOWN = 'UNKNOWN', - BLOCK_ADDED = 'BLOCK_ADDED', - BLOCK_REMOVED = 'BLOCK_REMOVED' -} - -export interface GatewayBackendResponseTime { - percentiles: { [key: string]: number } - average: number -} - -export interface GatewayBackendRuntimeStatus { - name: string - chainId: number - responseTime: GatewayBackendResponseTime -} - -export interface GatewayEtherBalance { - chainId: number - errorReason?: string - result: EtherBalance -} - -export interface GatewayNativeTokenBalance { - chainId: number - errorReason?: string - result: NativeTokenBalance -} - -export interface GatewayNativeTokenBalances { - chainId: number - errorReason?: string - results: Array -} - -export interface GatewayPrice { - chainID: number - errorReason?: string - results: Array -} - -export interface GatewayRuntimeStatus { - healthOK: boolean - startTime: string - uptime: number - ver: string - branch: string - commitHash: string - backends: Array -} - -export interface GatewayTokenBalance { - chainId: number - errorReason?: string - results: Array -} - -export interface GatewayTokenPriceQuery { - chainID: number - queries: Array -} - -export interface GatewayTransaction { - chainId: number - errorReason?: string - results: Array -} - -export interface IndexState { - chainId: string - lastBlockNum: number - lastBlockHash: string -} - -export interface IndexedBlock { - blockNumber: number - blockShortHash: string -} - -export interface IndexerMetrics { - blocksPerSecond: number - eventsPerSecond: number -} - -export interface MarketplaceOrder { - orderId: string - tokenContract: string - tokenId: string - isListing: boolean - quantity: string - quantityRemaining: string - currencyAddress: string - pricePerToken: string - expiry: string - orderStatus: OrderStatus - createdBy: string - blockNumber: number - orderbookContractAddress: string - createdAt: number -} - -export interface MarketplaceOrderFilter { - isListing?: boolean - userAddresses?: Array - currencyAddresses: Array - orderIds: Array - tokenIds: Array - excludeUserAddresses?: Array - blockNumberGt: number - createdAtAfter: number - orderStatuses: Array - returnExpired: boolean -} - -export interface MarketplaceTopOrdersFilter { - currencyAddresses: Array - tokenIds: Array - isListing: boolean - priceSort: SortOrder - excludeUser?: string -} - -export interface MetadataOptions { - verifiedOnly?: boolean - unverifiedOnly?: boolean - includeContracts?: Array -} - -export interface NativeTokenBalance { - accountAddress: string - chainId: number - name: string - symbol: string - balance: string - balanceUSD: string - priceUSD: string - priceUpdatedAt?: string - errorReason?: string -} - -export enum NetworkType { - MAINNETS = 'MAINNETS', - TESTNETS = 'TESTNETS', - ALL = 'ALL' -} - -export enum OrderStatus { - OPEN = 'OPEN', - CLOSED = 'CLOSED', - CANCELLED = 'CANCELLED' -} - -export interface Page { - page?: number - column?: string - before?: any - after?: any - sort?: Array - pageSize?: number - more?: boolean -} - -export interface PebbleMetrics { - compactionCount: number - compactionEstimatedDebt: number - compactionInProgressBytes: number - compactionNumInProgress: number - compactionMarkedFiles: number -} - -export interface Price { - contractAddress: string - tokenID?: string - priceUSD: string - updatedAt?: string -} - -export enum ResourceStatus { - NOT_AVAILABLE = 'NOT_AVAILABLE', - REFRESHING = 'REFRESHING', - AVAILABLE = 'AVAILABLE' -} - -export interface RuntimeChecks { - running: boolean - runnables: any - cgoEnabled: boolean - quotaControlEnabled: boolean - syncMode: string - percentIndexed: number - lastBlockNum: number - lastBlockNumWithState: number - bloomStatus: BloomStatus - bond: Bond - diskUsage: DiskUsage - metrics: IndexerMetrics -} - -export interface RuntimeStatus { - healthOK: boolean - indexerEnabled: boolean - startTime: string - uptime: number - ver: string - branch: string - commitHash: string - chainID: number - checks: RuntimeChecks -} - -export interface SortBy { - column: string - order: SortOrder -} - -export enum SortOrder { - DESC = 'DESC', - ASC = 'ASC' -} - -export interface TokenBalance { - contractType: ContractType - contractAddress: string - accountAddress: string - tokenID?: string - balance: string - balanceUSD: string - priceUSD: string - priceUpdatedAt?: string - blockHash: string - blockNumber: number - chainId: number - uniqueCollectibles: string - isSummary: boolean - contractInfo?: ContractInfo - tokenMetadata?: TokenMetadata -} - -export interface TokenBalanceFilter { - contractAddress: string - sinceBlockNumber: number -} - -export interface TokenBalancesByContractFilter { - contractAddresses: Array - accountAddresses?: Array - contractStatus?: ContractVerificationStatus - tokenIDs?: Array -} - -export interface TokenBalancesFilter { - accountAddresses: Array - contractStatus?: ContractVerificationStatus - contractTypes?: Array - contractWhitelist?: Array - contractBlacklist?: Array - omitNativeBalances: boolean - omitPrices?: boolean - tokenIDs?: Array -} - -export interface TokenHistory { - blockNumber: number - blockHash: string - contractAddress: string - contractType: ContractType - fromAddress: string - toAddress: string - txnHash: string - txnIndex: number - txnLogIndex: number - tokenIDs: string - amounts: string - ts: string -} - -export interface TokenIDRange { - start: string - end: string -} - -export interface TokenMetadata { - chainId?: number - contractAddress?: string - tokenId: string - source: string - name: string - description?: string - image?: string - video?: string - audio?: string - properties?: { [key: string]: any } - attributes: Array<{ [key: string]: any }> - image_data?: string - external_url?: string - background_color?: string - animation_url?: string - decimals?: number - updatedAt?: string - assets?: Array - status: ResourceStatus - queuedAt?: string - lastFetched?: string -} - -export interface TokenPriceQuery { - contractAddress: string - tokenID?: string -} - -export interface TokenSupply { - tokenID: string - supply: string - chainId: number - contractInfo?: ContractInfo - tokenMetadata?: TokenMetadata -} - -export interface Transaction { - txnHash: string - blockNumber: number - blockHash: string - chainId: number - metaTxnID?: string - transfers?: Array - timestamp: string -} - -export interface TransactionFilter { - txnHash?: string - from?: string - to?: string - contractAddress?: string - event?: string -} - -export interface TransactionHistoryFilter { - accountAddress?: string - contractAddress?: string - accountAddresses?: Array - contractAddresses?: Array - transactionHashes?: Array - metaTransactionIDs?: Array - fromBlock?: number - toBlock?: number - tokenID?: string - omitPrices?: boolean -} - -export interface TransactionLog { - contractAddress: string - topics: Array - data: string - index: number -} - -export interface TransactionReceipt { - txnHash: string - txnStatus: TransactionStatus - txnIndex: number - txnType: TransactionType - blockHash: string - blockNumber: number - gasUsed: number - effectiveGasPrice: string - from: string - to: string - logs: Array - final: boolean - reorged: boolean -} - -export enum TransactionStatus { - FAILED = 'FAILED', - SUCCESSFUL = 'SUCCESSFUL' -} - -export enum TransactionType { - LegacyTxnType = 'LegacyTxnType', - AccessListTxnType = 'AccessListTxnType', - DynamicFeeTxnType = 'DynamicFeeTxnType' -} - -export interface TxnInfo { - from: string - to: string - value: string -} - -export interface TxnTransfer { - transferType: TxnTransferType - contractAddress: string - contractType: ContractType - from: string - to: string - tokenIds?: Array - amounts: Array - logIndex: number - amountsUSD?: Array - pricesUSD?: Array - contractInfo?: ContractInfo - tokenMetadata?: { [key: string]: TokenMetadata } -} - -export enum TxnTransferType { - UNKNOWN = 'UNKNOWN', - SEND = 'SEND', - RECEIVE = 'RECEIVE' -} - -export interface Version { - webrpcVersion: string - schemaVersion: string - schemaHash: string - appVersion: string -} - -export interface WALWriterRuntimeStatus { - healthOK: boolean - startTime: string - uptime: number - ver: string - branch: string - commitHash: string - chainID: number - percentWALWritten: number -} - -export interface WebhookListener { - id: number - projectID: number - url: string - filters: EventFilter - name: string - updatedAt: string - active: boolean -} - -export interface AddWebhookListenerRequest { - url: string - filters: EventFilter - projectId?: number -} - -export interface AddWebhookListenerResponse { - status: boolean - listener: WebhookListener -} - -export interface FetchTransactionReceiptRequest { - txnHash: string - maxBlockWait?: number -} - -export interface FetchTransactionReceiptResponse { - receipt: TransactionReceipt -} - -export interface FetchTransactionReceiptWithFilterRequest { - filter: TransactionFilter - maxBlockWait?: number -} - -export interface FetchTransactionReceiptWithFilterResponse { - receipt: TransactionReceipt -} - -export interface GetAllWebhookListenersRequest { - projectId?: number -} - -export interface GetAllWebhookListenersResponse { - listeners: Array -} - -export interface GetBalanceUpdatesRequest { - contractAddress: string - lastBlockNumber: number - lastBlockHash?: string - page?: Page -} - -export interface GetBalanceUpdatesResponse { - page: Page - balances: Array -} - -export interface GetChainIDRequest {} - -export interface GetChainIDResponse { - chainID: number -} - -export interface GetEtherBalanceRequest { - accountAddress?: string -} - -export interface GetEtherBalanceResponse { - balance: EtherBalance -} - -export interface GetMarketplaceOrdersRequest { - marketplaceContractAddress: string - collectionAddress: string - filter?: MarketplaceOrderFilter - page?: Page -} - -export interface GetMarketplaceOrdersResponse { - page?: Page - orders: Array -} - -export interface GetMarketplaceTopOrdersRequest { - marketplaceContractAddress: string - collectionAddress: string - filter: MarketplaceTopOrdersFilter -} - -export interface GetMarketplaceTopOrdersResponse { - orders: Array -} - -export interface GetNativeTokenBalanceRequest { - accountAddress?: string - omitPrices?: boolean -} - -export interface GetNativeTokenBalanceResponse { - balance: NativeTokenBalance -} - -export interface GetTokenBalancesRequest { - accountAddress?: string - contractAddress?: string - tokenID?: string - includeMetadata?: boolean - metadataOptions?: MetadataOptions - includeCollectionTokens?: boolean - page?: Page -} - -export interface GetTokenBalancesResponse { - page: Page - balances: Array -} - -export interface GetTokenBalancesByContractRequest { - filter: TokenBalancesByContractFilter - omitMetadata?: boolean - page?: Page -} - -export interface GetTokenBalancesByContractResponse { - page: Page - balances: Array -} - -export interface GetTokenBalancesDetailsRequest { - filter: TokenBalancesFilter - omitMetadata?: boolean - page?: Page -} - -export interface GetTokenBalancesDetailsResponse { - page: Page - nativeBalances: Array - balances: Array -} - -export interface GetTokenBalancesSummaryRequest { - filter: TokenBalancesFilter - omitMetadata?: boolean - page?: Page -} - -export interface GetTokenBalancesSummaryResponse { - page: Page - nativeBalances: Array - balances: Array -} - -export interface GetTokenIDRangesRequest { - contractAddress: string - lastTokenID?: string -} - -export interface GetTokenIDRangesResponse { - contractType: ContractType - tokenIDRanges: Array - moreRanges: boolean -} - -export interface GetTokenIDsRequest { - contractAddress: string - page?: Page -} - -export interface GetTokenIDsResponse { - page: Page - contractType: ContractType - tokenIDs: Array -} - -export interface GetTokenPriceRequest { - q: TokenPriceQuery -} - -export interface GetTokenPriceResponse { - price: Price -} - -export interface GetTokenPricesRequest { - q: Array -} - -export interface GetTokenPricesResponse { - prices: Array -} - -export interface GetTokenSuppliesRequest { - contractAddress: string - includeMetadata?: boolean - page?: Page -} - -export interface GetTokenSuppliesResponse { - page: Page - contractType: ContractType - tokenIDs: Array -} - -export interface GetTokenSuppliesMapRequest { - tokenMap: { [key: string]: Array } - includeMetadata?: boolean -} - -export interface GetTokenSuppliesMapResponse { - supplies: { [key: string]: Array } -} - -export interface GetTransactionHistoryRequest { - filter: TransactionHistoryFilter - page?: Page - includeMetadata?: boolean - metadataOptions?: MetadataOptions -} - -export interface GetTransactionHistoryResponse { - page: Page - transactions: Array -} - -export interface GetWebhookListenerRequest { - id: number - projectId?: number -} - -export interface GetWebhookListenerResponse { - listener: WebhookListener -} - -export interface ListTokenPricesRequest { - page?: Page -} - -export interface ListTokenPricesResponse { - page: Page - prices: Array -} - -export interface PauseAllWebhookListenersRequest { - projectId?: number -} - -export interface PauseAllWebhookListenersResponse { - status: boolean -} - -export interface PingRequest {} - -export interface PingResponse { - status: boolean -} - -export interface RemoveAllWebhookListenersRequest { - projectId?: number -} - -export interface RemoveAllWebhookListenersResponse { - status: boolean -} - -export interface RemoveWebhookListenerRequest { - id: number - projectId?: number -} - -export interface RemoveWebhookListenerResponse { - status: boolean -} - -export interface ResumeAllWebhookListenersRequest { - projectId?: number -} - -export interface ResumeAllWebhookListenersResponse { - status: boolean -} - -export interface RuntimeStatusRequest {} - -export interface RuntimeStatusResponse { - status: RuntimeStatus -} - -export interface SubscribeBalanceUpdatesRequest { - contractAddress: string -} - -export interface SubscribeBalanceUpdatesResponse { - balance: TokenBalance -} - -export interface SubscribeEventsRequest { - filter: EventFilter -} - -export interface SubscribeEventsResponse { - log: EventLog -} - -export interface SubscribeReceiptsRequest { - filter: TransactionFilter -} - -export interface SubscribeReceiptsResponse { - receipt: TransactionReceipt -} - -export interface SyncBalanceRequest { - accountAddress: string - contractAddress: string - tokenID?: string -} - -export interface SyncBalanceResponse {} - -export interface ToggleWebhookListenerRequest { - id: number - projectId?: number -} - -export interface ToggleWebhookListenerResponse { - webhookListener: WebhookListener -} - -export interface UpdateWebhookListenerRequest { - listener: WebhookListener - projectId?: number -} - -export interface UpdateWebhookListenerResponse { - status: boolean -} - -export interface VersionRequest {} - -export interface VersionResponse { - version: Version -} - -// -// Client -// - -export class Indexer implements IndexerClient { - protected hostname: string - protected fetch: Fetch - protected path = '/rpc/Indexer/' - - constructor(hostname: string, fetch: Fetch) { - this.hostname = hostname.replace(/\/*$/, '') - this.fetch = (input: RequestInfo, init?: RequestInit) => fetch(input, init) - } - - private url(name: string): string { - return this.hostname + this.path + name - } - - queryKey = { - addWebhookListener: (req: AddWebhookListenerRequest) => ['Indexer', 'addWebhookListener', req] as const, - fetchTransactionReceipt: (req: FetchTransactionReceiptRequest) => ['Indexer', 'fetchTransactionReceipt', req] as const, - fetchTransactionReceiptWithFilter: (req: FetchTransactionReceiptWithFilterRequest) => - ['Indexer', 'fetchTransactionReceiptWithFilter', req] as const, - getAllWebhookListeners: (req: GetAllWebhookListenersRequest) => ['Indexer', 'getAllWebhookListeners', req] as const, - getBalanceUpdates: (req: GetBalanceUpdatesRequest) => ['Indexer', 'getBalanceUpdates', req] as const, - getChainID: () => ['Indexer', 'getChainID'] as const, - getEtherBalance: (req: GetEtherBalanceRequest) => ['Indexer', 'getEtherBalance', req] as const, - getMarketplaceOrders: (req: GetMarketplaceOrdersRequest) => ['Indexer', 'getMarketplaceOrders', req] as const, - getMarketplaceTopOrders: (req: GetMarketplaceTopOrdersRequest) => ['Indexer', 'getMarketplaceTopOrders', req] as const, - getNativeTokenBalance: (req: GetNativeTokenBalanceRequest) => ['Indexer', 'getNativeTokenBalance', req] as const, - getTokenBalances: (req: GetTokenBalancesRequest) => ['Indexer', 'getTokenBalances', req] as const, - getTokenBalancesByContract: (req: GetTokenBalancesByContractRequest) => - ['Indexer', 'getTokenBalancesByContract', req] as const, - getTokenBalancesDetails: (req: GetTokenBalancesDetailsRequest) => ['Indexer', 'getTokenBalancesDetails', req] as const, - getTokenBalancesSummary: (req: GetTokenBalancesSummaryRequest) => ['Indexer', 'getTokenBalancesSummary', req] as const, - getTokenIDRanges: (req: GetTokenIDRangesRequest) => ['Indexer', 'getTokenIDRanges', req] as const, - getTokenIDs: (req: GetTokenIDsRequest) => ['Indexer', 'getTokenIDs', req] as const, - getTokenPrice: (req: GetTokenPriceRequest) => ['Indexer', 'getTokenPrice', req] as const, - getTokenPrices: (req: GetTokenPricesRequest) => ['Indexer', 'getTokenPrices', req] as const, - getTokenSupplies: (req: GetTokenSuppliesRequest) => ['Indexer', 'getTokenSupplies', req] as const, - getTokenSuppliesMap: (req: GetTokenSuppliesMapRequest) => ['Indexer', 'getTokenSuppliesMap', req] as const, - getTransactionHistory: (req: GetTransactionHistoryRequest) => ['Indexer', 'getTransactionHistory', req] as const, - getWebhookListener: (req: GetWebhookListenerRequest) => ['Indexer', 'getWebhookListener', req] as const, - listTokenPrices: (req: ListTokenPricesRequest) => ['Indexer', 'listTokenPrices', req] as const, - pauseAllWebhookListeners: (req: PauseAllWebhookListenersRequest) => ['Indexer', 'pauseAllWebhookListeners', req] as const, - ping: () => ['Indexer', 'ping'] as const, - removeAllWebhookListeners: (req: RemoveAllWebhookListenersRequest) => ['Indexer', 'removeAllWebhookListeners', req] as const, - removeWebhookListener: (req: RemoveWebhookListenerRequest) => ['Indexer', 'removeWebhookListener', req] as const, - resumeAllWebhookListeners: (req: ResumeAllWebhookListenersRequest) => ['Indexer', 'resumeAllWebhookListeners', req] as const, - runtimeStatus: () => ['Indexer', 'runtimeStatus'] as const, - subscribeBalanceUpdates: (req: SubscribeBalanceUpdatesRequest) => ['Indexer', 'subscribeBalanceUpdates', req] as const, - subscribeEvents: (req: SubscribeEventsRequest) => ['Indexer', 'subscribeEvents', req] as const, - subscribeReceipts: (req: SubscribeReceiptsRequest) => ['Indexer', 'subscribeReceipts', req] as const, - syncBalance: (req: SyncBalanceRequest) => ['Indexer', 'syncBalance', req] as const, - toggleWebhookListener: (req: ToggleWebhookListenerRequest) => ['Indexer', 'toggleWebhookListener', req] as const, - updateWebhookListener: (req: UpdateWebhookListenerRequest) => ['Indexer', 'updateWebhookListener', req] as const, - version: () => ['Indexer', 'version'] as const - } - - addWebhookListener = ( - req: AddWebhookListenerRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('AddWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'AddWebhookListenerResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - fetchTransactionReceipt = ( - req: FetchTransactionReceiptRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('FetchTransactionReceipt'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'FetchTransactionReceiptResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - fetchTransactionReceiptWithFilter = ( - req: FetchTransactionReceiptWithFilterRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('FetchTransactionReceiptWithFilter'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'FetchTransactionReceiptWithFilterResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getAllWebhookListeners = ( - req: GetAllWebhookListenersRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetAllWebhookListeners'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetAllWebhookListenersResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getBalanceUpdates = ( - req: GetBalanceUpdatesRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetBalanceUpdates'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetBalanceUpdatesResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getChainID = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetChainID'), createHttpRequest('{}', headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetChainIDResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getEtherBalance = (req: GetEtherBalanceRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetEtherBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetEtherBalanceResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getMarketplaceOrders = ( - req: GetMarketplaceOrdersRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetMarketplaceOrders'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetMarketplaceOrdersResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getMarketplaceTopOrders = ( - req: GetMarketplaceTopOrdersRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetMarketplaceTopOrders'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetMarketplaceTopOrdersResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getNativeTokenBalance = ( - req: GetNativeTokenBalanceRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetNativeTokenBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetNativeTokenBalanceResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenBalances = ( - req: GetTokenBalancesRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalances'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenBalancesResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenBalancesByContract = ( - req: GetTokenBalancesByContractRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalancesByContract'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenBalancesByContractResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenBalancesDetails = ( - req: GetTokenBalancesDetailsRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalancesDetails'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenBalancesDetailsResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenBalancesSummary = ( - req: GetTokenBalancesSummaryRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalancesSummary'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenBalancesSummaryResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenIDRanges = ( - req: GetTokenIDRangesRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenIDRanges'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenIDRangesResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenIDs = (req: GetTokenIDsRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenIDs'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenIDsResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenPrice = (req: GetTokenPriceRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenPrice'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenPriceResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenPrices = (req: GetTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenPrices'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenPricesResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenSupplies = ( - req: GetTokenSuppliesRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenSupplies'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenSuppliesResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenSuppliesMap = ( - req: GetTokenSuppliesMapRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenSuppliesMap'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenSuppliesMapResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTransactionHistory = ( - req: GetTransactionHistoryRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTransactionHistory'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTransactionHistoryResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getWebhookListener = ( - req: GetWebhookListenerRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetWebhookListenerResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - listTokenPrices = (req: ListTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('ListTokenPrices'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'ListTokenPricesResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - pauseAllWebhookListeners = ( - req: PauseAllWebhookListenersRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('PauseAllWebhookListeners'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'PauseAllWebhookListenersResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - ping = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Ping'), createHttpRequest('{}', headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'PingResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - removeAllWebhookListeners = ( - req: RemoveAllWebhookListenersRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('RemoveAllWebhookListeners'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'RemoveAllWebhookListenersResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - removeWebhookListener = ( - req: RemoveWebhookListenerRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('RemoveWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'RemoveWebhookListenerResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - resumeAllWebhookListeners = ( - req: ResumeAllWebhookListenersRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('ResumeAllWebhookListeners'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'ResumeAllWebhookListenersResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - runtimeStatus = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('RuntimeStatus'), createHttpRequest('{}', headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'RuntimeStatusResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - subscribeBalanceUpdates = ( - req: SubscribeBalanceUpdatesRequest, - options: WebrpcStreamOptions - ): WebrpcStreamController => { - const abortController = new AbortController() - const abortSignal = abortController.signal - - if (options.signal) { - abortSignal.addEventListener('abort', () => abortController.abort(options.signal?.reason), { - signal: options.signal - }) - } - - const _fetch = () => - this.fetch(this.url('SubscribeBalanceUpdates'), createHttpRequest(JsonEncode(req), options.headers, abortSignal)).then( - async res => { - await sseResponse(res, options, _fetch) - }, - error => { - options.onError(error, _fetch) - } - ) - - const resp = _fetch() - return { - abort: abortController.abort.bind(abortController), - closed: resp - } - } - subscribeEvents = ( - req: SubscribeEventsRequest, - options: WebrpcStreamOptions - ): WebrpcStreamController => { - const abortController = new AbortController() - const abortSignal = abortController.signal - - if (options.signal) { - abortSignal.addEventListener('abort', () => abortController.abort(options.signal?.reason), { - signal: options.signal - }) - } - - const _fetch = () => - this.fetch(this.url('SubscribeEvents'), createHttpRequest(JsonEncode(req), options.headers, abortSignal)).then( - async res => { - await sseResponse(res, options, _fetch) - }, - error => { - options.onError(error, _fetch) - } - ) - - const resp = _fetch() - return { - abort: abortController.abort.bind(abortController), - closed: resp - } - } - subscribeReceipts = ( - req: SubscribeReceiptsRequest, - options: WebrpcStreamOptions - ): WebrpcStreamController => { - const abortController = new AbortController() - const abortSignal = abortController.signal - - if (options.signal) { - abortSignal.addEventListener('abort', () => abortController.abort(options.signal?.reason), { - signal: options.signal - }) - } - - const _fetch = () => - this.fetch(this.url('SubscribeReceipts'), createHttpRequest(JsonEncode(req), options.headers, abortSignal)).then( - async res => { - await sseResponse(res, options, _fetch) - }, - error => { - options.onError(error, _fetch) - } - ) - - const resp = _fetch() - return { - abort: abortController.abort.bind(abortController), - closed: resp - } - } - syncBalance = (req: SyncBalanceRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('SyncBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'SyncBalanceResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - toggleWebhookListener = ( - req: ToggleWebhookListenerRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('ToggleWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'ToggleWebhookListenerResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - updateWebhookListener = ( - req: UpdateWebhookListenerRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('UpdateWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'UpdateWebhookListenerResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - version = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Version'), createHttpRequest('{}', headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'VersionResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } -} - -const sseResponse = async (res: Response, options: WebrpcStreamOptions, retryFetch: () => Promise) => { - const { onMessage, onOpen, onClose, onError } = options - - if (!res.ok) { - try { - await buildResponse(res) - } catch (error) { - // @ts-ignore - onError(error, retryFetch) - } - return - } - - if (!res.body) { - onError( - WebrpcBadResponseError.new({ - status: res.status, - cause: 'Invalid response, missing body' - }), - retryFetch - ) - return - } - - onOpen && onOpen() - - const reader = res.body.getReader() - const decoder = new TextDecoder() - let buffer = '' - let lastReadTime = Date.now() - const timeout = (10 + 1) * 1000 - let timeoutError = false - const intervalId = setInterval(() => { - if (Date.now() - lastReadTime > timeout) { - timeoutError = true - clearInterval(intervalId) - reader.releaseLock() - } - }, timeout) - - while (true) { - let value - let done - try { - ;({ value, done } = await reader.read()) - if (timeoutError) throw new Error('Timeout, no data or heartbeat received') - lastReadTime = Date.now() - buffer += decoder.decode(value, { stream: true }) - } catch (error) { - if (error instanceof DOMException && error.name === 'AbortError') { - onError( - WebrpcClientAbortedError.new({ - message: 'AbortError', - cause: `AbortError: ${error instanceof Error ? error.message : String(error)}` - }), - () => { - throw new Error('Abort signal cannot be used to reconnect') - } - ) - } else { - onError( - WebrpcStreamLostError.new({ - cause: `reader.read(): ${error instanceof Error ? error.message : String(error)}` - }), - retryFetch - ) - } - return - } - - let lines = buffer.split('\n') - for (let i = 0; i < lines.length - 1; i++) { - const line = lines[i] - if (line?.length === 0) { - continue - } - let data: any - try { - data = JSON.parse(line) - if (data.hasOwnProperty('webrpcError')) { - const error = data.webrpcError - const code: number = typeof error.code === 'number' ? error.code : 0 - onError((webrpcErrorByCode[code] || WebrpcError).new(error), retryFetch) - return - } - } catch (error) { - if (error instanceof Error && error.message === 'Abort signal cannot be used to reconnect') { - throw error - } - onError( - WebrpcBadResponseError.new({ - status: res.status, - cause: `JSON.parse(): ${error instanceof Error ? error.message : String(error)}` - }), - retryFetch - ) - } - onMessage(data) - } - - if (!done) { - const lastLine = lines[lines.length - 1] - buffer = lastLine || '' - continue - } - - onClose && onClose() - return - } -} - -const createHttpRequest = (body: string = '{}', headers: object = {}, signal: AbortSignal | null = null): object => { - const reqHeaders: { [key: string]: string } = { - ...headers, - 'Content-Type': 'application/json', - [WebrpcHeader]: WebrpcHeaderValue - } - return { method: 'POST', headers: reqHeaders, body, signal } -} - -const buildResponse = (res: Response): Promise => { - return res.text().then(text => { - let data - try { - data = JSON.parse(text) - } catch (error) { - throw WebrpcBadResponseError.new({ - status: res.status, - cause: `JSON.parse(): ${error instanceof Error ? error.message : String(error)}: response text: ${text}` - }) - } - if (!res.ok) { - const code: number = typeof data.code === 'number' ? data.code : 0 - throw (webrpcErrorByCode[code] || WebrpcError).new(data) - } - return data - }) -} - -export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise - -export interface WebrpcStreamOptions extends WebrpcOptions { - onMessage: (message: T) => void - onError: (error: WebrpcError, reconnect: () => void) => void - onOpen?: () => void - onClose?: () => void -} - -export interface WebrpcOptions { - headers?: HeadersInit - signal?: AbortSignal -} - -export interface WebrpcStreamController { - abort: (reason?: any) => void - closed: Promise -} - -export const JsonEncode = (obj: T): string => { - return JSON.stringify(obj) -} - -export const JsonDecode = (data: string | any, _typ: string = ''): T => { - let parsed: any = data - if (typeof data === 'string') { - try { - parsed = JSON.parse(data) - } catch (err) { - throw WebrpcBadResponseError.new({ cause: `JsonDecode: JSON.parse failed: ${(err as Error).message}` }) - } - } - return parsed as T -} - -// -// Errors -// - -type WebrpcErrorParams = { name?: string; code?: number; message?: string; status?: number; cause?: string } - -export class WebrpcError extends Error { - code: number - status: number - - constructor(error: WebrpcErrorParams = {}) { - super(error.message) - this.name = error.name || 'WebrpcEndpointError' - this.code = typeof error.code === 'number' ? error.code : 0 - this.message = error.message || `endpoint error` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcError.prototype) - } - - static new(payload: any): WebrpcError { - return new this({ message: payload.message, code: payload.code, status: payload.status, cause: payload.cause }) - } -} - -export class WebrpcEndpointError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcEndpoint' - this.code = typeof error.code === 'number' ? error.code : 0 - this.message = error.message || `endpoint error` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcEndpointError.prototype) - } -} - -export class WebrpcRequestFailedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcRequestFailed' - this.code = typeof error.code === 'number' ? error.code : -1 - this.message = error.message || `request failed` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcRequestFailedError.prototype) - } -} - -export class WebrpcBadRouteError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcBadRoute' - this.code = typeof error.code === 'number' ? error.code : -2 - this.message = error.message || `bad route` - this.status = typeof error.status === 'number' ? error.status : 404 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcBadRouteError.prototype) - } -} - -export class WebrpcBadMethodError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcBadMethod' - this.code = typeof error.code === 'number' ? error.code : -3 - this.message = error.message || `bad method` - this.status = typeof error.status === 'number' ? error.status : 405 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcBadMethodError.prototype) - } -} - -export class WebrpcBadRequestError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcBadRequest' - this.code = typeof error.code === 'number' ? error.code : -4 - this.message = error.message || `bad request` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcBadRequestError.prototype) - } -} - -export class WebrpcBadResponseError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcBadResponse' - this.code = typeof error.code === 'number' ? error.code : -5 - this.message = error.message || `bad response` - this.status = typeof error.status === 'number' ? error.status : 500 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcBadResponseError.prototype) - } -} - -export class WebrpcServerPanicError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcServerPanic' - this.code = typeof error.code === 'number' ? error.code : -6 - this.message = error.message || `server panic` - this.status = typeof error.status === 'number' ? error.status : 500 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcServerPanicError.prototype) - } -} - -export class WebrpcInternalErrorError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcInternalError' - this.code = typeof error.code === 'number' ? error.code : -7 - this.message = error.message || `internal error` - this.status = typeof error.status === 'number' ? error.status : 500 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcInternalErrorError.prototype) - } -} - -export class WebrpcClientAbortedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcClientAborted' - this.code = typeof error.code === 'number' ? error.code : -8 - this.message = error.message || `request aborted by client` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcClientAbortedError.prototype) - } -} - -export class WebrpcStreamLostError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcStreamLost' - this.code = typeof error.code === 'number' ? error.code : -9 - this.message = error.message || `stream lost` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcStreamLostError.prototype) - } -} - -export class WebrpcStreamFinishedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcStreamFinished' - this.code = typeof error.code === 'number' ? error.code : -10 - this.message = error.message || `stream finished` - this.status = typeof error.status === 'number' ? error.status : 200 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcStreamFinishedError.prototype) - } -} - -// -// Schema errors -// - -export class AbortedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'Aborted' - this.code = typeof error.code === 'number' ? error.code : 1005 - this.message = error.message || `Request aborted` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, AbortedError.prototype) - } -} - -export class AccessKeyMismatchError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'AccessKeyMismatch' - this.code = typeof error.code === 'number' ? error.code : 1102 - this.message = error.message || `Access key mismatch` - this.status = typeof error.status === 'number' ? error.status : 409 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, AccessKeyMismatchError.prototype) - } -} - -export class AccessKeyNotFoundError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'AccessKeyNotFound' - this.code = typeof error.code === 'number' ? error.code : 1101 - this.message = error.message || `Access key not found` - this.status = typeof error.status === 'number' ? error.status : 401 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, AccessKeyNotFoundError.prototype) - } -} - -export class AtLeastOneKeyError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'AtLeastOneKey' - this.code = typeof error.code === 'number' ? error.code : 1302 - this.message = error.message || `You need at least one Access Key` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, AtLeastOneKeyError.prototype) - } -} - -export class GeoblockedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'Geoblocked' - this.code = typeof error.code === 'number' ? error.code : 1006 - this.message = error.message || `Geoblocked region` - this.status = typeof error.status === 'number' ? error.status : 451 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, GeoblockedError.prototype) - } -} - -export class InvalidArgumentError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'InvalidArgument' - this.code = typeof error.code === 'number' ? error.code : 2001 - this.message = error.message || `Invalid argument` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, InvalidArgumentError.prototype) - } -} - -export class InvalidOriginError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'InvalidOrigin' - this.code = typeof error.code === 'number' ? error.code : 1103 - this.message = error.message || `Invalid origin for Access Key` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, InvalidOriginError.prototype) - } -} - -export class InvalidServiceError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'InvalidService' - this.code = typeof error.code === 'number' ? error.code : 1104 - this.message = error.message || `Service not enabled for Access key` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, InvalidServiceError.prototype) - } -} - -export class MaxAccessKeysError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'MaxAccessKeys' - this.code = typeof error.code === 'number' ? error.code : 1301 - this.message = error.message || `Access keys limit reached` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, MaxAccessKeysError.prototype) - } -} - -export class MetadataCallFailedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'MetadataCallFailed' - this.code = typeof error.code === 'number' ? error.code : 3003 - this.message = error.message || `Metadata service call failed` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, MetadataCallFailedError.prototype) - } -} - -export class MethodNotFoundError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'MethodNotFound' - this.code = typeof error.code === 'number' ? error.code : 1003 - this.message = error.message || `Method not found` - this.status = typeof error.status === 'number' ? error.status : 404 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, MethodNotFoundError.prototype) - } -} - -export class NoDefaultKeyError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'NoDefaultKey' - this.code = typeof error.code === 'number' ? error.code : 1300 - this.message = error.message || `No default access key found` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, NoDefaultKeyError.prototype) - } -} - -export class NotFoundError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'NotFound' - this.code = typeof error.code === 'number' ? error.code : 3000 - this.message = error.message || `Resource not found` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, NotFoundError.prototype) - } -} - -export class PermissionDeniedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'PermissionDenied' - this.code = typeof error.code === 'number' ? error.code : 1001 - this.message = error.message || `Permission denied` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, PermissionDeniedError.prototype) - } -} - -export class ProjectNotFoundError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'ProjectNotFound' - this.code = typeof error.code === 'number' ? error.code : 1100 - this.message = error.message || `Project not found` - this.status = typeof error.status === 'number' ? error.status : 401 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, ProjectNotFoundError.prototype) - } -} - -export class QueryFailedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'QueryFailed' - this.code = typeof error.code === 'number' ? error.code : 2003 - this.message = error.message || `Query failed` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, QueryFailedError.prototype) - } -} - -export class QuotaExceededError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'QuotaExceeded' - this.code = typeof error.code === 'number' ? error.code : 1200 - this.message = error.message || `Quota exceeded` - this.status = typeof error.status === 'number' ? error.status : 429 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, QuotaExceededError.prototype) - } -} - -export class RateLimitError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'RateLimit' - this.code = typeof error.code === 'number' ? error.code : 1201 - this.message = error.message || `Rate limit exceeded` - this.status = typeof error.status === 'number' ? error.status : 429 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, RateLimitError.prototype) - } -} - -export class RateLimitedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'RateLimited' - this.code = typeof error.code === 'number' ? error.code : 1007 - this.message = error.message || `Rate-limited. Please slow down.` - this.status = typeof error.status === 'number' ? error.status : 429 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, RateLimitedError.prototype) - } -} - -export class RequestConflictError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'RequestConflict' - this.code = typeof error.code === 'number' ? error.code : 1004 - this.message = error.message || `Conflict with target resource` - this.status = typeof error.status === 'number' ? error.status : 409 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, RequestConflictError.prototype) - } -} - -export class ResourceExhaustedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'ResourceExhausted' - this.code = typeof error.code === 'number' ? error.code : 2004 - this.message = error.message || `Resource exhausted` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, ResourceExhaustedError.prototype) - } -} - -export class SessionExpiredError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'SessionExpired' - this.code = typeof error.code === 'number' ? error.code : 1002 - this.message = error.message || `Session expired` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, SessionExpiredError.prototype) - } -} - -export class TimeoutError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'Timeout' - this.code = typeof error.code === 'number' ? error.code : 1900 - this.message = error.message || `Request timed out` - this.status = typeof error.status === 'number' ? error.status : 408 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, TimeoutError.prototype) - } -} - -export class UnauthorizedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'Unauthorized' - this.code = typeof error.code === 'number' ? error.code : 1000 - this.message = error.message || `Unauthorized access` - this.status = typeof error.status === 'number' ? error.status : 401 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, UnauthorizedError.prototype) - } -} - -export class UnauthorizedUserError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'UnauthorizedUser' - this.code = typeof error.code === 'number' ? error.code : 1105 - this.message = error.message || `Unauthorized user` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, UnauthorizedUserError.prototype) - } -} - -export class UnavailableError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'Unavailable' - this.code = typeof error.code === 'number' ? error.code : 2002 - this.message = error.message || `Unavailable resource` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, UnavailableError.prototype) - } -} - -export enum errors { - WebrpcEndpoint = 'WebrpcEndpoint', - WebrpcRequestFailed = 'WebrpcRequestFailed', - WebrpcBadRoute = 'WebrpcBadRoute', - WebrpcBadMethod = 'WebrpcBadMethod', - WebrpcBadRequest = 'WebrpcBadRequest', - WebrpcBadResponse = 'WebrpcBadResponse', - WebrpcServerPanic = 'WebrpcServerPanic', - WebrpcInternalError = 'WebrpcInternalError', - WebrpcClientAborted = 'WebrpcClientAborted', - WebrpcStreamLost = 'WebrpcStreamLost', - WebrpcStreamFinished = 'WebrpcStreamFinished', - Aborted = 'Aborted', - AccessKeyMismatch = 'AccessKeyMismatch', - AccessKeyNotFound = 'AccessKeyNotFound', - AtLeastOneKey = 'AtLeastOneKey', - Geoblocked = 'Geoblocked', - InvalidArgument = 'InvalidArgument', - InvalidOrigin = 'InvalidOrigin', - InvalidService = 'InvalidService', - MaxAccessKeys = 'MaxAccessKeys', - MetadataCallFailed = 'MetadataCallFailed', - MethodNotFound = 'MethodNotFound', - NoDefaultKey = 'NoDefaultKey', - NotFound = 'NotFound', - PermissionDenied = 'PermissionDenied', - ProjectNotFound = 'ProjectNotFound', - QueryFailed = 'QueryFailed', - QuotaExceeded = 'QuotaExceeded', - RateLimit = 'RateLimit', - RateLimited = 'RateLimited', - RequestConflict = 'RequestConflict', - ResourceExhausted = 'ResourceExhausted', - SessionExpired = 'SessionExpired', - Timeout = 'Timeout', - Unauthorized = 'Unauthorized', - UnauthorizedUser = 'UnauthorizedUser', - Unavailable = 'Unavailable' -} - -export enum WebrpcErrorCodes { - WebrpcEndpoint = 0, - WebrpcRequestFailed = -1, - WebrpcBadRoute = -2, - WebrpcBadMethod = -3, - WebrpcBadRequest = -4, - WebrpcBadResponse = -5, - WebrpcServerPanic = -6, - WebrpcInternalError = -7, - WebrpcClientAborted = -8, - WebrpcStreamLost = -9, - WebrpcStreamFinished = -10, - Aborted = 1005, - AccessKeyMismatch = 1102, - AccessKeyNotFound = 1101, - AtLeastOneKey = 1302, - Geoblocked = 1006, - InvalidArgument = 2001, - InvalidOrigin = 1103, - InvalidService = 1104, - MaxAccessKeys = 1301, - MetadataCallFailed = 3003, - MethodNotFound = 1003, - NoDefaultKey = 1300, - NotFound = 3000, - PermissionDenied = 1001, - ProjectNotFound = 1100, - QueryFailed = 2003, - QuotaExceeded = 1200, - RateLimit = 1201, - RateLimited = 1007, - RequestConflict = 1004, - ResourceExhausted = 2004, - SessionExpired = 1002, - Timeout = 1900, - Unauthorized = 1000, - UnauthorizedUser = 1105, - Unavailable = 2002 -} - -export const webrpcErrorByCode: { [code: number]: any } = { - [0]: WebrpcEndpointError, - [-1]: WebrpcRequestFailedError, - [-2]: WebrpcBadRouteError, - [-3]: WebrpcBadMethodError, - [-4]: WebrpcBadRequestError, - [-5]: WebrpcBadResponseError, - [-6]: WebrpcServerPanicError, - [-7]: WebrpcInternalErrorError, - [-8]: WebrpcClientAbortedError, - [-9]: WebrpcStreamLostError, - [-10]: WebrpcStreamFinishedError, - [1005]: AbortedError, - [1102]: AccessKeyMismatchError, - [1101]: AccessKeyNotFoundError, - [1302]: AtLeastOneKeyError, - [1006]: GeoblockedError, - [2001]: InvalidArgumentError, - [1103]: InvalidOriginError, - [1104]: InvalidServiceError, - [1301]: MaxAccessKeysError, - [3003]: MetadataCallFailedError, - [1003]: MethodNotFoundError, - [1300]: NoDefaultKeyError, - [3000]: NotFoundError, - [1001]: PermissionDeniedError, - [1100]: ProjectNotFoundError, - [2003]: QueryFailedError, - [1200]: QuotaExceededError, - [1201]: RateLimitError, - [1007]: RateLimitedError, - [1004]: RequestConflictError, - [2004]: ResourceExhaustedError, - [1002]: SessionExpiredError, - [1900]: TimeoutError, - [1000]: UnauthorizedError, - [1105]: UnauthorizedUserError, - [2002]: UnavailableError -} - -// -// Webrpc -// - -export const WebrpcHeader = 'Webrpc' - -export const WebrpcHeaderValue = 'webrpc@v0.31.2;gen-typescript@v0.23.1;sequence-indexer@v0.4.0' - -type WebrpcGenVersions = { - WebrpcGenVersion: string - codeGenName: string - codeGenVersion: string - schemaName: string - schemaVersion: string -} - -export function VersionFromHeader(headers: Headers): WebrpcGenVersions { - const headerValue = headers.get(WebrpcHeader) - if (!headerValue) { - return { - WebrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '' - } - } - - return parseWebrpcGenVersions(headerValue) -} - -function parseWebrpcGenVersions(header: string): WebrpcGenVersions { - const versions = header.split(';') - if (versions.length < 3) { - return { - WebrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '' - } - } - - const [_, WebrpcGenVersion] = versions[0]!.split('@') - const [codeGenName, codeGenVersion] = versions[1]!.split('@') - const [schemaName, schemaVersion] = versions[2]!.split('@') - - return { - WebrpcGenVersion: WebrpcGenVersion ?? '', - codeGenName: codeGenName ?? '', - codeGenVersion: codeGenVersion ?? '', - schemaName: schemaName ?? '', - schemaVersion: schemaVersion ?? '' - } -} diff --git a/packages/indexer/src/indexergw.gen.ts b/packages/indexer/src/indexergw.gen.ts deleted file mode 100644 index 729d04cdc..000000000 --- a/packages/indexer/src/indexergw.gen.ts +++ /dev/null @@ -1,1787 +0,0 @@ -/* eslint-disable */ -// sequence-indexer v0.4.0 b978d153702d614d5f1b9c98ff7f2e5857cccfd6 -// -- -// Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. -// -// webrpc-gen -schema=merged.gen.json -service=IndexerGateway -target=typescript -client -out=./clients/indexergw.gen.ts - -// Webrpc description and code-gen version -export const WebrpcVersion = 'v1' - -// Schema version of your RIDL schema -export const WebrpcSchemaVersion = 'v0.4.0' - -// Schema hash generated from your RIDL schema -export const WebrpcSchemaHash = 'b978d153702d614d5f1b9c98ff7f2e5857cccfd6' - -// -// Client interface -// - -export interface IndexerGatewayClient { - /** - * GetTokenBalances returns a balance summary/details for an specific account - * on all indexer nodes. By default if accountAddress is left empty, it will - * use the account from the jwt session. - */ - getBalanceUpdates(req: GetBalanceUpdatesRequest, headers?: object, signal?: AbortSignal): Promise - - /** - * GetChains returns a list of chains with their ID and name - */ - getChains(req: GetChainsRequest, headers?: object, signal?: AbortSignal): Promise - - /** - * GetNativeTokenBalance queries indexer nodes for the latest native token - * account balance. - */ - getNativeTokenBalance( - req: GetNativeTokenBalanceRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * GetTokenBalances returns a balance summary/details for a specific account - * on all indexer nodes. By default if accountAddress is left empty, it will - * use the account from the jwt session. - * - * @deprecated Use GetTokenBalancesSummary or GetTokenBalancesDetails instead. - */ - getTokenBalances(req: GetTokenBalancesRequest, headers?: object, signal?: AbortSignal): Promise - - /** - * GetTokenBalancesByContract returns a balances for specific accounts and - * contracts on all indexer nodes. The collection ERC721 & ERC1155 tokens are - * represented as individual balances. - */ - getTokenBalancesByContract( - req: GetTokenBalancesByContractRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * GetTokenBalancesDetails returns a detailed balance summary for the given - * accounts on all indexer nodes. The collection ERC721 & ERC1155 tokens are - * represented as individual balances. - */ - getTokenBalancesDetails( - req: GetTokenBalancesDetailsRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * GetTokenBalancesSummary returns a summary of token balances for the given - * accounts on all indexer nodes. The collection ERC721 & ERC1155 tokens are - * represented as a single aggregated balance. - */ - getTokenBalancesSummary( - req: GetTokenBalancesSummaryRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - getTokenPrice(req: GetTokenPriceRequest, headers?: object, signal?: AbortSignal): Promise - - getTokenPrices(req: GetTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise - - /** - * GetTransactionHistory returns the history of mined transactions for the - * given account on all indexer nodes, which includes a list of token transfer - * (sent/received) , and sent transactions from a Sequence wallet. - */ - getTransactionHistory( - req: GetTransactionHistoryRequest, - headers?: object, - signal?: AbortSignal - ): Promise - - /** - * Ping the indexer - */ - ping(headers?: object, signal?: AbortSignal): Promise - - /** - * Get the current runtime health status of the indexer gatewya - */ - runtimeStatus(headers?: object, signal?: AbortSignal): Promise - - /** - * Get the current version of the indexer - */ - version(headers?: object, signal?: AbortSignal): Promise -} - -// -// Schema types -// - -export interface Asset { - id: number - collectionId: number - tokenId?: string - url?: string - metadataField: string - name?: string - filesize?: number - mimeType?: string - width?: number - height?: number - updatedAt?: string -} - -export interface BloomStats { - hitRatio: string - falsePositivesPercent: string - hitCount: number - missCount: number - falsePositives: number -} - -export interface BloomStatus { - enabled: boolean - initialized: boolean - bloomInitElapsedTime: string - stats: BloomStats -} - -export interface Bond { - pebble: PebbleMetrics - estimatedDiskUsagePerTable: any - estimatedDiskUsageTotal: string -} - -export interface ChainInfo { - chainId: number - chainName: string -} - -export interface ContractInfo { - chainId: number - address: string - source: string - name: string - type: string - symbol: string - decimals?: number - logoURI: string - deployed: boolean - bytecodeHash: string - extensions: ContractInfoExtensions - updatedAt: string - queuedAt?: string - status: ResourceStatus -} - -export interface ContractInfoExtensionBridgeInfo { - tokenAddress: string -} - -export interface ContractInfoExtensionIndexingInfo { - useOnChainBalance: boolean -} - -export interface ContractInfoExtensions { - link?: string - description?: string - categories?: Array - bridgeInfo?: { [key: string]: ContractInfoExtensionBridgeInfo } - indexingInfo?: ContractInfoExtensionIndexingInfo - ogImage?: string - ogName?: string - originChainId?: number - originAddress?: string - blacklist?: boolean - verified?: boolean - verifiedBy?: string - featured?: boolean - featureIndex?: number -} - -export enum ContractType { - UNKNOWN = 'UNKNOWN', - NATIVE = 'NATIVE', - ERC20 = 'ERC20', - ERC721 = 'ERC721', - ERC1155 = 'ERC1155', - SEQUENCE_WALLET = 'SEQUENCE_WALLET', - ERC20_BRIDGE = 'ERC20_BRIDGE', - ERC721_BRIDGE = 'ERC721_BRIDGE', - ERC1155_BRIDGE = 'ERC1155_BRIDGE', - SEQ_MARKETPLACE = 'SEQ_MARKETPLACE', - ERC6909 = 'ERC6909' -} - -export enum ContractVerificationStatus { - VERIFIED = 'VERIFIED', - UNVERIFIED = 'UNVERIFIED', - ALL = 'ALL' -} - -export interface DiskUsage { - humanReadable: string - used: number - size: number - percent: number - dirs: { [key: string]: string } -} - -export interface EtherBalance { - accountAddress: string - balanceWei: string -} - -export interface EventDecoded { - topicHash: string - eventSig: string - types: Array - names: Array - values: Array -} - -export interface EventFilter { - events?: Array - contractAddresses?: Array - accounts?: Array - tokenIDs?: Array -} - -export interface EventLog { - id: number - uid: string - type: EventLogType - blockNumber: number - blockHash: string - parentBlockHash: string - contractAddress: string - contractType: ContractType - txnHash: string - txnIndex: number - txnLogIndex: number - logDataType: EventLogDataType - ts: string - txnInfo?: TxnInfo - rawLog?: { [key: string]: any } - event?: EventDecoded -} - -export enum EventLogDataType { - EVENT = 'EVENT', - TOKEN_TRANSFER = 'TOKEN_TRANSFER', - NATIVE_TOKEN_TRANSFER = 'NATIVE_TOKEN_TRANSFER', - SEQUENCE_TXN = 'SEQUENCE_TXN' -} - -export enum EventLogType { - UNKNOWN = 'UNKNOWN', - BLOCK_ADDED = 'BLOCK_ADDED', - BLOCK_REMOVED = 'BLOCK_REMOVED' -} - -export interface GatewayBackendResponseTime { - percentiles: { [key: string]: number } - average: number -} - -export interface GatewayBackendRuntimeStatus { - name: string - chainId: number - responseTime: GatewayBackendResponseTime -} - -export interface GatewayEtherBalance { - chainId: number - errorReason?: string - result: EtherBalance -} - -export interface GatewayNativeTokenBalance { - chainId: number - errorReason?: string - result: NativeTokenBalance -} - -export interface GatewayNativeTokenBalances { - chainId: number - errorReason?: string - results: Array -} - -export interface GatewayPrice { - chainID: number - errorReason?: string - results: Array -} - -export interface GatewayRuntimeStatus { - healthOK: boolean - startTime: string - uptime: number - ver: string - branch: string - commitHash: string - backends: Array -} - -export interface GatewayTokenBalance { - chainId: number - errorReason?: string - results: Array -} - -export interface GatewayTokenPriceQuery { - chainID: number - queries: Array -} - -export interface GatewayTransaction { - chainId: number - errorReason?: string - results: Array -} - -export interface IndexState { - chainId: string - lastBlockNum: number - lastBlockHash: string -} - -export interface IndexedBlock { - blockNumber: number - blockShortHash: string -} - -export interface IndexerMetrics { - blocksPerSecond: number - eventsPerSecond: number -} - -export interface MarketplaceOrder { - orderId: string - tokenContract: string - tokenId: string - isListing: boolean - quantity: string - quantityRemaining: string - currencyAddress: string - pricePerToken: string - expiry: string - orderStatus: OrderStatus - createdBy: string - blockNumber: number - orderbookContractAddress: string - createdAt: number -} - -export interface MarketplaceOrderFilter { - isListing?: boolean - userAddresses?: Array - currencyAddresses: Array - orderIds: Array - tokenIds: Array - excludeUserAddresses?: Array - blockNumberGt: number - createdAtAfter: number - orderStatuses: Array - returnExpired: boolean -} - -export interface MarketplaceTopOrdersFilter { - currencyAddresses: Array - tokenIds: Array - isListing: boolean - priceSort: SortOrder - excludeUser?: string -} - -export interface MetadataOptions { - verifiedOnly?: boolean - unverifiedOnly?: boolean - includeContracts?: Array -} - -export interface NativeTokenBalance { - accountAddress: string - chainId: number - name: string - symbol: string - balance: string - balanceUSD: string - priceUSD: string - priceUpdatedAt?: string - errorReason?: string -} - -export enum NetworkType { - MAINNETS = 'MAINNETS', - TESTNETS = 'TESTNETS', - ALL = 'ALL' -} - -export enum OrderStatus { - OPEN = 'OPEN', - CLOSED = 'CLOSED', - CANCELLED = 'CANCELLED' -} - -export interface Page { - page?: number - column?: string - before?: any - after?: any - sort?: Array - pageSize?: number - more?: boolean -} - -export interface PebbleMetrics { - compactionCount: number - compactionEstimatedDebt: number - compactionInProgressBytes: number - compactionNumInProgress: number - compactionMarkedFiles: number -} - -export interface Price { - contractAddress: string - tokenID?: string - priceUSD: string - updatedAt?: string -} - -export enum ResourceStatus { - NOT_AVAILABLE = 'NOT_AVAILABLE', - REFRESHING = 'REFRESHING', - AVAILABLE = 'AVAILABLE' -} - -export interface RuntimeChecks { - running: boolean - runnables: any - cgoEnabled: boolean - quotaControlEnabled: boolean - syncMode: string - percentIndexed: number - lastBlockNum: number - lastBlockNumWithState: number - bloomStatus: BloomStatus - bond: Bond - diskUsage: DiskUsage - metrics: IndexerMetrics -} - -export interface RuntimeStatus { - healthOK: boolean - indexerEnabled: boolean - startTime: string - uptime: number - ver: string - branch: string - commitHash: string - chainID: number - checks: RuntimeChecks -} - -export interface SortBy { - column: string - order: SortOrder -} - -export enum SortOrder { - DESC = 'DESC', - ASC = 'ASC' -} - -export interface TokenBalance { - contractType: ContractType - contractAddress: string - accountAddress: string - tokenID?: string - balance: string - balanceUSD: string - priceUSD: string - priceUpdatedAt?: string - blockHash: string - blockNumber: number - chainId: number - uniqueCollectibles: string - isSummary: boolean - contractInfo?: ContractInfo - tokenMetadata?: TokenMetadata -} - -export interface TokenBalanceFilter { - contractAddress: string - sinceBlockNumber: number -} - -export interface TokenBalancesByContractFilter { - contractAddresses: Array - accountAddresses?: Array - contractStatus?: ContractVerificationStatus - tokenIDs?: Array -} - -export interface TokenBalancesFilter { - accountAddresses: Array - contractStatus?: ContractVerificationStatus - contractTypes?: Array - contractWhitelist?: Array - contractBlacklist?: Array - omitNativeBalances: boolean - omitPrices?: boolean - tokenIDs?: Array -} - -export interface TokenHistory { - blockNumber: number - blockHash: string - contractAddress: string - contractType: ContractType - fromAddress: string - toAddress: string - txnHash: string - txnIndex: number - txnLogIndex: number - tokenIDs: string - amounts: string - ts: string -} - -export interface TokenIDRange { - start: string - end: string -} - -export interface TokenMetadata { - chainId?: number - contractAddress?: string - tokenId: string - source: string - name: string - description?: string - image?: string - video?: string - audio?: string - properties?: { [key: string]: any } - attributes: Array<{ [key: string]: any }> - image_data?: string - external_url?: string - background_color?: string - animation_url?: string - decimals?: number - updatedAt?: string - assets?: Array - status: ResourceStatus - queuedAt?: string - lastFetched?: string -} - -export interface TokenPriceQuery { - contractAddress: string - tokenID?: string -} - -export interface TokenSupply { - tokenID: string - supply: string - chainId: number - contractInfo?: ContractInfo - tokenMetadata?: TokenMetadata -} - -export interface Transaction { - txnHash: string - blockNumber: number - blockHash: string - chainId: number - metaTxnID?: string - transfers?: Array - timestamp: string -} - -export interface TransactionFilter { - txnHash?: string - from?: string - to?: string - contractAddress?: string - event?: string -} - -export interface TransactionHistoryFilter { - accountAddress?: string - contractAddress?: string - accountAddresses?: Array - contractAddresses?: Array - transactionHashes?: Array - metaTransactionIDs?: Array - fromBlock?: number - toBlock?: number - tokenID?: string - omitPrices?: boolean -} - -export interface TransactionLog { - contractAddress: string - topics: Array - data: string - index: number -} - -export interface TransactionReceipt { - txnHash: string - txnStatus: TransactionStatus - txnIndex: number - txnType: TransactionType - blockHash: string - blockNumber: number - gasUsed: number - effectiveGasPrice: string - from: string - to: string - logs: Array - final: boolean - reorged: boolean -} - -export enum TransactionStatus { - FAILED = 'FAILED', - SUCCESSFUL = 'SUCCESSFUL' -} - -export enum TransactionType { - LegacyTxnType = 'LegacyTxnType', - AccessListTxnType = 'AccessListTxnType', - DynamicFeeTxnType = 'DynamicFeeTxnType' -} - -export interface TxnInfo { - from: string - to: string - value: string -} - -export interface TxnTransfer { - transferType: TxnTransferType - contractAddress: string - contractType: ContractType - from: string - to: string - tokenIds?: Array - amounts: Array - logIndex: number - amountsUSD?: Array - pricesUSD?: Array - contractInfo?: ContractInfo - tokenMetadata?: { [key: string]: TokenMetadata } -} - -export enum TxnTransferType { - UNKNOWN = 'UNKNOWN', - SEND = 'SEND', - RECEIVE = 'RECEIVE' -} - -export interface Version { - webrpcVersion: string - schemaVersion: string - schemaHash: string - appVersion: string -} - -export interface WALWriterRuntimeStatus { - healthOK: boolean - startTime: string - uptime: number - ver: string - branch: string - commitHash: string - chainID: number - percentWALWritten: number -} - -export interface WebhookListener { - id: number - projectID: number - url: string - filters: EventFilter - name: string - updatedAt: string - active: boolean -} - -export interface GetBalanceUpdatesRequest { - chainIds?: Array - networks?: Array - networkType?: NetworkType - contractAddress: string - lastBlockNumber: number - lastBlockHash?: string - page?: Page -} - -export interface GetBalanceUpdatesResponse { - page: Page - balances: Array -} - -export interface GetChainsRequest { - networkType?: NetworkType -} - -export interface GetChainsResponse { - chains: Array -} - -export interface GetNativeTokenBalanceRequest { - chainIds?: Array - networks?: Array - networkType?: NetworkType - accountAddress?: string - omitPrices?: boolean -} - -export interface GetNativeTokenBalanceResponse { - balances: Array -} - -export interface GetTokenBalancesRequest { - chainIds?: Array - networks?: Array - networkType?: NetworkType - accountAddress?: string - contractAddress?: string - tokenID?: string - includeMetadata?: boolean - metadataOptions?: MetadataOptions - includeCollectionTokens?: boolean - page?: Page -} - -export interface GetTokenBalancesResponse { - page: Page - balances: Array -} - -export interface GetTokenBalancesByContractRequest { - chainIds?: Array - networks?: Array - networkType?: NetworkType - filter: TokenBalancesByContractFilter - omitMetadata?: boolean - page?: Page -} - -export interface GetTokenBalancesByContractResponse { - page: Page - balances: Array -} - -export interface GetTokenBalancesDetailsRequest { - chainIds?: Array - networks?: Array - networkType?: NetworkType - filter: TokenBalancesFilter - omitMetadata?: boolean - page?: Page -} - -export interface GetTokenBalancesDetailsResponse { - page: Page - nativeBalances: Array - balances: Array -} - -export interface GetTokenBalancesSummaryRequest { - chainIds?: Array - networks?: Array - networkType?: NetworkType - filter: TokenBalancesFilter - omitMetadata?: boolean - page?: Page -} - -export interface GetTokenBalancesSummaryResponse { - page: Page - nativeBalances: Array - balances: Array -} - -export interface GetTokenPriceRequest { - q: GatewayTokenPriceQuery -} - -export interface GetTokenPriceResponse { - price: GatewayPrice -} - -export interface GetTokenPricesRequest { - q: Array -} - -export interface GetTokenPricesResponse { - prices: Array -} - -export interface GetTransactionHistoryRequest { - chainIds?: Array - networks?: Array - networkType?: NetworkType - filter: TransactionHistoryFilter - includeMetadata?: boolean - metadataOptions?: MetadataOptions - page?: Page -} - -export interface GetTransactionHistoryResponse { - page: Page - transactions: Array -} - -export interface PingRequest {} - -export interface PingResponse { - status: boolean -} - -export interface RuntimeStatusRequest {} - -export interface RuntimeStatusResponse { - status: GatewayRuntimeStatus -} - -export interface VersionRequest {} - -export interface VersionResponse { - version: Version -} - -// -// Client -// - -export class IndexerGateway implements IndexerGatewayClient { - protected hostname: string - protected fetch: Fetch - protected path = '/rpc/IndexerGateway/' - - constructor(hostname: string, fetch: Fetch) { - this.hostname = hostname.replace(/\/*$/, '') - this.fetch = (input: RequestInfo, init?: RequestInit) => fetch(input, init) - } - - private url(name: string): string { - return this.hostname + this.path + name - } - - queryKey = { - getBalanceUpdates: (req: GetBalanceUpdatesRequest) => ['IndexerGateway', 'getBalanceUpdates', req] as const, - getChains: (req: GetChainsRequest) => ['IndexerGateway', 'getChains', req] as const, - getNativeTokenBalance: (req: GetNativeTokenBalanceRequest) => ['IndexerGateway', 'getNativeTokenBalance', req] as const, - getTokenBalances: (req: GetTokenBalancesRequest) => ['IndexerGateway', 'getTokenBalances', req] as const, - getTokenBalancesByContract: (req: GetTokenBalancesByContractRequest) => - ['IndexerGateway', 'getTokenBalancesByContract', req] as const, - getTokenBalancesDetails: (req: GetTokenBalancesDetailsRequest) => ['IndexerGateway', 'getTokenBalancesDetails', req] as const, - getTokenBalancesSummary: (req: GetTokenBalancesSummaryRequest) => ['IndexerGateway', 'getTokenBalancesSummary', req] as const, - getTokenPrice: (req: GetTokenPriceRequest) => ['IndexerGateway', 'getTokenPrice', req] as const, - getTokenPrices: (req: GetTokenPricesRequest) => ['IndexerGateway', 'getTokenPrices', req] as const, - getTransactionHistory: (req: GetTransactionHistoryRequest) => ['IndexerGateway', 'getTransactionHistory', req] as const, - ping: () => ['IndexerGateway', 'ping'] as const, - runtimeStatus: () => ['IndexerGateway', 'runtimeStatus'] as const, - version: () => ['IndexerGateway', 'version'] as const - } - - getBalanceUpdates = ( - req: GetBalanceUpdatesRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetBalanceUpdates'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetBalanceUpdatesResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getChains = (req: GetChainsRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetChains'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetChainsResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getNativeTokenBalance = ( - req: GetNativeTokenBalanceRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetNativeTokenBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetNativeTokenBalanceResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenBalances = ( - req: GetTokenBalancesRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalances'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenBalancesResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenBalancesByContract = ( - req: GetTokenBalancesByContractRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalancesByContract'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenBalancesByContractResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenBalancesDetails = ( - req: GetTokenBalancesDetailsRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalancesDetails'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenBalancesDetailsResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenBalancesSummary = ( - req: GetTokenBalancesSummaryRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalancesSummary'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenBalancesSummaryResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenPrice = (req: GetTokenPriceRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenPrice'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenPriceResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTokenPrices = (req: GetTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenPrices'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTokenPricesResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - getTransactionHistory = ( - req: GetTransactionHistoryRequest, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTransactionHistory'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetTransactionHistoryResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - ping = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Ping'), createHttpRequest('{}', headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'PingResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - runtimeStatus = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('RuntimeStatus'), createHttpRequest('{}', headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'RuntimeStatusResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - - version = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Version'), createHttpRequest('{}', headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'VersionResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } -} - -const createHttpRequest = (body: string = '{}', headers: object = {}, signal: AbortSignal | null = null): object => { - const reqHeaders: { [key: string]: string } = { - ...headers, - 'Content-Type': 'application/json', - [WebrpcHeader]: WebrpcHeaderValue - } - return { method: 'POST', headers: reqHeaders, body, signal } -} - -const buildResponse = (res: Response): Promise => { - return res.text().then(text => { - let data - try { - data = JSON.parse(text) - } catch (error) { - throw WebrpcBadResponseError.new({ - status: res.status, - cause: `JSON.parse(): ${error instanceof Error ? error.message : String(error)}: response text: ${text}` - }) - } - if (!res.ok) { - const code: number = typeof data.code === 'number' ? data.code : 0 - throw (webrpcErrorByCode[code] || WebrpcError).new(data) - } - return data - }) -} - -export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise - -export const JsonEncode = (obj: T): string => { - return JSON.stringify(obj) -} - -export const JsonDecode = (data: string | any, _typ: string = ''): T => { - let parsed: any = data - if (typeof data === 'string') { - try { - parsed = JSON.parse(data) - } catch (err) { - throw WebrpcBadResponseError.new({ cause: `JsonDecode: JSON.parse failed: ${(err as Error).message}` }) - } - } - return parsed as T -} - -// -// Errors -// - -type WebrpcErrorParams = { name?: string; code?: number; message?: string; status?: number; cause?: string } - -export class WebrpcError extends Error { - code: number - status: number - - constructor(error: WebrpcErrorParams = {}) { - super(error.message) - this.name = error.name || 'WebrpcEndpointError' - this.code = typeof error.code === 'number' ? error.code : 0 - this.message = error.message || `endpoint error` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcError.prototype) - } - - static new(payload: any): WebrpcError { - return new this({ message: payload.message, code: payload.code, status: payload.status, cause: payload.cause }) - } -} - -export class WebrpcEndpointError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcEndpoint' - this.code = typeof error.code === 'number' ? error.code : 0 - this.message = error.message || `endpoint error` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcEndpointError.prototype) - } -} - -export class WebrpcRequestFailedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcRequestFailed' - this.code = typeof error.code === 'number' ? error.code : -1 - this.message = error.message || `request failed` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcRequestFailedError.prototype) - } -} - -export class WebrpcBadRouteError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcBadRoute' - this.code = typeof error.code === 'number' ? error.code : -2 - this.message = error.message || `bad route` - this.status = typeof error.status === 'number' ? error.status : 404 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcBadRouteError.prototype) - } -} - -export class WebrpcBadMethodError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcBadMethod' - this.code = typeof error.code === 'number' ? error.code : -3 - this.message = error.message || `bad method` - this.status = typeof error.status === 'number' ? error.status : 405 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcBadMethodError.prototype) - } -} - -export class WebrpcBadRequestError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcBadRequest' - this.code = typeof error.code === 'number' ? error.code : -4 - this.message = error.message || `bad request` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcBadRequestError.prototype) - } -} - -export class WebrpcBadResponseError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcBadResponse' - this.code = typeof error.code === 'number' ? error.code : -5 - this.message = error.message || `bad response` - this.status = typeof error.status === 'number' ? error.status : 500 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcBadResponseError.prototype) - } -} - -export class WebrpcServerPanicError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcServerPanic' - this.code = typeof error.code === 'number' ? error.code : -6 - this.message = error.message || `server panic` - this.status = typeof error.status === 'number' ? error.status : 500 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcServerPanicError.prototype) - } -} - -export class WebrpcInternalErrorError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcInternalError' - this.code = typeof error.code === 'number' ? error.code : -7 - this.message = error.message || `internal error` - this.status = typeof error.status === 'number' ? error.status : 500 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcInternalErrorError.prototype) - } -} - -export class WebrpcClientAbortedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcClientAborted' - this.code = typeof error.code === 'number' ? error.code : -8 - this.message = error.message || `request aborted by client` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcClientAbortedError.prototype) - } -} - -export class WebrpcStreamLostError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcStreamLost' - this.code = typeof error.code === 'number' ? error.code : -9 - this.message = error.message || `stream lost` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcStreamLostError.prototype) - } -} - -export class WebrpcStreamFinishedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'WebrpcStreamFinished' - this.code = typeof error.code === 'number' ? error.code : -10 - this.message = error.message || `stream finished` - this.status = typeof error.status === 'number' ? error.status : 200 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, WebrpcStreamFinishedError.prototype) - } -} - -// -// Schema errors -// - -export class AbortedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'Aborted' - this.code = typeof error.code === 'number' ? error.code : 1005 - this.message = error.message || `Request aborted` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, AbortedError.prototype) - } -} - -export class AccessKeyMismatchError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'AccessKeyMismatch' - this.code = typeof error.code === 'number' ? error.code : 1102 - this.message = error.message || `Access key mismatch` - this.status = typeof error.status === 'number' ? error.status : 409 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, AccessKeyMismatchError.prototype) - } -} - -export class AccessKeyNotFoundError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'AccessKeyNotFound' - this.code = typeof error.code === 'number' ? error.code : 1101 - this.message = error.message || `Access key not found` - this.status = typeof error.status === 'number' ? error.status : 401 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, AccessKeyNotFoundError.prototype) - } -} - -export class AtLeastOneKeyError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'AtLeastOneKey' - this.code = typeof error.code === 'number' ? error.code : 1302 - this.message = error.message || `You need at least one Access Key` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, AtLeastOneKeyError.prototype) - } -} - -export class GeoblockedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'Geoblocked' - this.code = typeof error.code === 'number' ? error.code : 1006 - this.message = error.message || `Geoblocked region` - this.status = typeof error.status === 'number' ? error.status : 451 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, GeoblockedError.prototype) - } -} - -export class InvalidArgumentError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'InvalidArgument' - this.code = typeof error.code === 'number' ? error.code : 2001 - this.message = error.message || `Invalid argument` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, InvalidArgumentError.prototype) - } -} - -export class InvalidOriginError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'InvalidOrigin' - this.code = typeof error.code === 'number' ? error.code : 1103 - this.message = error.message || `Invalid origin for Access Key` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, InvalidOriginError.prototype) - } -} - -export class InvalidServiceError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'InvalidService' - this.code = typeof error.code === 'number' ? error.code : 1104 - this.message = error.message || `Service not enabled for Access key` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, InvalidServiceError.prototype) - } -} - -export class MaxAccessKeysError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'MaxAccessKeys' - this.code = typeof error.code === 'number' ? error.code : 1301 - this.message = error.message || `Access keys limit reached` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, MaxAccessKeysError.prototype) - } -} - -export class MetadataCallFailedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'MetadataCallFailed' - this.code = typeof error.code === 'number' ? error.code : 3003 - this.message = error.message || `Metadata service call failed` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, MetadataCallFailedError.prototype) - } -} - -export class MethodNotFoundError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'MethodNotFound' - this.code = typeof error.code === 'number' ? error.code : 1003 - this.message = error.message || `Method not found` - this.status = typeof error.status === 'number' ? error.status : 404 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, MethodNotFoundError.prototype) - } -} - -export class NoDefaultKeyError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'NoDefaultKey' - this.code = typeof error.code === 'number' ? error.code : 1300 - this.message = error.message || `No default access key found` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, NoDefaultKeyError.prototype) - } -} - -export class NotFoundError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'NotFound' - this.code = typeof error.code === 'number' ? error.code : 3000 - this.message = error.message || `Resource not found` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, NotFoundError.prototype) - } -} - -export class PermissionDeniedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'PermissionDenied' - this.code = typeof error.code === 'number' ? error.code : 1001 - this.message = error.message || `Permission denied` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, PermissionDeniedError.prototype) - } -} - -export class ProjectNotFoundError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'ProjectNotFound' - this.code = typeof error.code === 'number' ? error.code : 1100 - this.message = error.message || `Project not found` - this.status = typeof error.status === 'number' ? error.status : 401 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, ProjectNotFoundError.prototype) - } -} - -export class QueryFailedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'QueryFailed' - this.code = typeof error.code === 'number' ? error.code : 2003 - this.message = error.message || `Query failed` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, QueryFailedError.prototype) - } -} - -export class QuotaExceededError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'QuotaExceeded' - this.code = typeof error.code === 'number' ? error.code : 1200 - this.message = error.message || `Quota exceeded` - this.status = typeof error.status === 'number' ? error.status : 429 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, QuotaExceededError.prototype) - } -} - -export class RateLimitError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'RateLimit' - this.code = typeof error.code === 'number' ? error.code : 1201 - this.message = error.message || `Rate limit exceeded` - this.status = typeof error.status === 'number' ? error.status : 429 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, RateLimitError.prototype) - } -} - -export class RateLimitedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'RateLimited' - this.code = typeof error.code === 'number' ? error.code : 1007 - this.message = error.message || `Rate-limited. Please slow down.` - this.status = typeof error.status === 'number' ? error.status : 429 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, RateLimitedError.prototype) - } -} - -export class RequestConflictError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'RequestConflict' - this.code = typeof error.code === 'number' ? error.code : 1004 - this.message = error.message || `Conflict with target resource` - this.status = typeof error.status === 'number' ? error.status : 409 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, RequestConflictError.prototype) - } -} - -export class ResourceExhaustedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'ResourceExhausted' - this.code = typeof error.code === 'number' ? error.code : 2004 - this.message = error.message || `Resource exhausted` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, ResourceExhaustedError.prototype) - } -} - -export class SessionExpiredError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'SessionExpired' - this.code = typeof error.code === 'number' ? error.code : 1002 - this.message = error.message || `Session expired` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, SessionExpiredError.prototype) - } -} - -export class TimeoutError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'Timeout' - this.code = typeof error.code === 'number' ? error.code : 1900 - this.message = error.message || `Request timed out` - this.status = typeof error.status === 'number' ? error.status : 408 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, TimeoutError.prototype) - } -} - -export class UnauthorizedError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'Unauthorized' - this.code = typeof error.code === 'number' ? error.code : 1000 - this.message = error.message || `Unauthorized access` - this.status = typeof error.status === 'number' ? error.status : 401 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, UnauthorizedError.prototype) - } -} - -export class UnauthorizedUserError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'UnauthorizedUser' - this.code = typeof error.code === 'number' ? error.code : 1105 - this.message = error.message || `Unauthorized user` - this.status = typeof error.status === 'number' ? error.status : 403 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, UnauthorizedUserError.prototype) - } -} - -export class UnavailableError extends WebrpcError { - constructor(error: WebrpcErrorParams = {}) { - super(error) - this.name = error.name || 'Unavailable' - this.code = typeof error.code === 'number' ? error.code : 2002 - this.message = error.message || `Unavailable resource` - this.status = typeof error.status === 'number' ? error.status : 400 - if (error.cause !== undefined) this.cause = error.cause - Object.setPrototypeOf(this, UnavailableError.prototype) - } -} - -export enum errors { - WebrpcEndpoint = 'WebrpcEndpoint', - WebrpcRequestFailed = 'WebrpcRequestFailed', - WebrpcBadRoute = 'WebrpcBadRoute', - WebrpcBadMethod = 'WebrpcBadMethod', - WebrpcBadRequest = 'WebrpcBadRequest', - WebrpcBadResponse = 'WebrpcBadResponse', - WebrpcServerPanic = 'WebrpcServerPanic', - WebrpcInternalError = 'WebrpcInternalError', - WebrpcClientAborted = 'WebrpcClientAborted', - WebrpcStreamLost = 'WebrpcStreamLost', - WebrpcStreamFinished = 'WebrpcStreamFinished', - Aborted = 'Aborted', - AccessKeyMismatch = 'AccessKeyMismatch', - AccessKeyNotFound = 'AccessKeyNotFound', - AtLeastOneKey = 'AtLeastOneKey', - Geoblocked = 'Geoblocked', - InvalidArgument = 'InvalidArgument', - InvalidOrigin = 'InvalidOrigin', - InvalidService = 'InvalidService', - MaxAccessKeys = 'MaxAccessKeys', - MetadataCallFailed = 'MetadataCallFailed', - MethodNotFound = 'MethodNotFound', - NoDefaultKey = 'NoDefaultKey', - NotFound = 'NotFound', - PermissionDenied = 'PermissionDenied', - ProjectNotFound = 'ProjectNotFound', - QueryFailed = 'QueryFailed', - QuotaExceeded = 'QuotaExceeded', - RateLimit = 'RateLimit', - RateLimited = 'RateLimited', - RequestConflict = 'RequestConflict', - ResourceExhausted = 'ResourceExhausted', - SessionExpired = 'SessionExpired', - Timeout = 'Timeout', - Unauthorized = 'Unauthorized', - UnauthorizedUser = 'UnauthorizedUser', - Unavailable = 'Unavailable' -} - -export enum WebrpcErrorCodes { - WebrpcEndpoint = 0, - WebrpcRequestFailed = -1, - WebrpcBadRoute = -2, - WebrpcBadMethod = -3, - WebrpcBadRequest = -4, - WebrpcBadResponse = -5, - WebrpcServerPanic = -6, - WebrpcInternalError = -7, - WebrpcClientAborted = -8, - WebrpcStreamLost = -9, - WebrpcStreamFinished = -10, - Aborted = 1005, - AccessKeyMismatch = 1102, - AccessKeyNotFound = 1101, - AtLeastOneKey = 1302, - Geoblocked = 1006, - InvalidArgument = 2001, - InvalidOrigin = 1103, - InvalidService = 1104, - MaxAccessKeys = 1301, - MetadataCallFailed = 3003, - MethodNotFound = 1003, - NoDefaultKey = 1300, - NotFound = 3000, - PermissionDenied = 1001, - ProjectNotFound = 1100, - QueryFailed = 2003, - QuotaExceeded = 1200, - RateLimit = 1201, - RateLimited = 1007, - RequestConflict = 1004, - ResourceExhausted = 2004, - SessionExpired = 1002, - Timeout = 1900, - Unauthorized = 1000, - UnauthorizedUser = 1105, - Unavailable = 2002 -} - -export const webrpcErrorByCode: { [code: number]: any } = { - [0]: WebrpcEndpointError, - [-1]: WebrpcRequestFailedError, - [-2]: WebrpcBadRouteError, - [-3]: WebrpcBadMethodError, - [-4]: WebrpcBadRequestError, - [-5]: WebrpcBadResponseError, - [-6]: WebrpcServerPanicError, - [-7]: WebrpcInternalErrorError, - [-8]: WebrpcClientAbortedError, - [-9]: WebrpcStreamLostError, - [-10]: WebrpcStreamFinishedError, - [1005]: AbortedError, - [1102]: AccessKeyMismatchError, - [1101]: AccessKeyNotFoundError, - [1302]: AtLeastOneKeyError, - [1006]: GeoblockedError, - [2001]: InvalidArgumentError, - [1103]: InvalidOriginError, - [1104]: InvalidServiceError, - [1301]: MaxAccessKeysError, - [3003]: MetadataCallFailedError, - [1003]: MethodNotFoundError, - [1300]: NoDefaultKeyError, - [3000]: NotFoundError, - [1001]: PermissionDeniedError, - [1100]: ProjectNotFoundError, - [2003]: QueryFailedError, - [1200]: QuotaExceededError, - [1201]: RateLimitError, - [1007]: RateLimitedError, - [1004]: RequestConflictError, - [2004]: ResourceExhaustedError, - [1002]: SessionExpiredError, - [1900]: TimeoutError, - [1000]: UnauthorizedError, - [1105]: UnauthorizedUserError, - [2002]: UnavailableError -} - -// -// Webrpc -// - -export const WebrpcHeader = 'Webrpc' - -export const WebrpcHeaderValue = 'webrpc@v0.31.2;gen-typescript@v0.23.1;sequence-indexer@v0.4.0' - -type WebrpcGenVersions = { - WebrpcGenVersion: string - codeGenName: string - codeGenVersion: string - schemaName: string - schemaVersion: string -} - -export function VersionFromHeader(headers: Headers): WebrpcGenVersions { - const headerValue = headers.get(WebrpcHeader) - if (!headerValue) { - return { - WebrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '' - } - } - - return parseWebrpcGenVersions(headerValue) -} - -function parseWebrpcGenVersions(header: string): WebrpcGenVersions { - const versions = header.split(';') - if (versions.length < 3) { - return { - WebrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '' - } - } - - const [_, WebrpcGenVersion] = versions[0]!.split('@') - const [codeGenName, codeGenVersion] = versions[1]!.split('@') - const [schemaName, schemaVersion] = versions[2]!.split('@') - - return { - WebrpcGenVersion: WebrpcGenVersion ?? '', - codeGenName: codeGenName ?? '', - codeGenVersion: codeGenVersion ?? '', - schemaName: schemaName ?? '', - schemaVersion: schemaVersion ?? '' - } -} diff --git a/packages/services/indexer/src/indexer.gen.ts b/packages/services/indexer/src/indexer.gen.ts index 89de72566..97d3d2472 100644 --- a/packages/services/indexer/src/indexer.gen.ts +++ b/packages/services/indexer/src/indexer.gen.ts @@ -1,79 +1,388 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 546b527de7002f409ffa602ad35b5a3abe979088 +// sequence-indexer v0.4.0 caf5c4c3677ac2dce41858dce7cd727a7810845f // -- -// Code generated by webrpc-gen@v0.21.1 with typescript generator. DO NOT EDIT. +// Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. // -// webrpc-gen -schema=indexer.ridl -service=Indexer -target=typescript -client -out=./clients/indexer.gen.ts +// webrpc-gen -schema=merged.gen.json -service=Indexer -target=typescript -client -out=./clients/indexer.gen.ts -export const WebrpcHeader = 'Webrpc' - -export const WebrpcHeaderValue = 'webrpc@v0.21.1;gen-typescript@v0.15.1;sequence-indexer@v0.4.0' - -// WebRPC description and code-gen version -export const WebRPCVersion = 'v1' +// Webrpc description and code-gen version +export const WebrpcVersion = 'v1' // Schema version of your RIDL schema -export const WebRPCSchemaVersion = 'v0.4.0' +export const WebrpcSchemaVersion = 'v0.4.0' // Schema hash generated from your RIDL schema -export const WebRPCSchemaHash = '546b527de7002f409ffa602ad35b5a3abe979088' +export const WebrpcSchemaHash = 'caf5c4c3677ac2dce41858dce7cd727a7810845f' -type WebrpcGenVersions = { - webrpcGenVersion: string - codeGenName: string - codeGenVersion: string - schemaName: string - schemaVersion: string -} +// +// Client interface +// -export function VersionFromHeader(headers: Headers): WebrpcGenVersions { - const headerValue = headers.get(WebrpcHeader) - if (!headerValue) { - return { - webrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '', - } - } +export interface IndexerClient { + addWebhookListener(req: AddWebhookListenerRequest, headers?: object, signal?: AbortSignal): Promise - return parseWebrpcGenVersions(headerValue) -} + /** + * Fetches a single receipt and then will stop the subscription + */ + fetchTransactionReceipt( + req: FetchTransactionReceiptRequest, + headers?: object, + signal?: AbortSignal + ): Promise -function parseWebrpcGenVersions(header: string): WebrpcGenVersions { - const versions = header.split(';') - if (versions.length < 3) { - return { - webrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '', - } - } + /** + * Fetches a single receipt with filter and then will stop the subscription + */ + fetchTransactionReceiptWithFilter( + req: FetchTransactionReceiptWithFilterRequest, + headers?: object, + signal?: AbortSignal + ): Promise - const [_, webrpcGenVersion] = versions[0]!.split('@') - const [codeGenName, codeGenVersion] = versions[1]!.split('@') - const [schemaName, schemaVersion] = versions[2]!.split('@') + /** + * Webhooks + */ + getAllWebhookListeners( + req: GetAllWebhookListenersRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * Get balance update aggregate values -- useful for syncing balance details of a contract, ie. from Skyweaver. + * Also consider using SubscribeBalanceUpdates or SubscribeEvents as other alternatives. + */ + getBalanceUpdates(req: GetBalanceUpdatesRequest, headers?: object, signal?: AbortSignal): Promise + + /** + * Get the chain ID of the indexer + */ + getChainID(headers?: object, signal?: AbortSignal): Promise + + /** + * Queries an ethereum node for the latest and confirm ETH balances + * DEPRECATED: use GetNativeTokenBalance instead + * + * @deprecated GetNativeTokenBalance + */ + getEtherBalance(req: GetEtherBalanceRequest, headers?: object, signal?: AbortSignal): Promise + + /** + * GetMarketplaceOrders queries marketplace orders with filtering and pagination. + * + * Retrieves buy orders (offers) and sell orders (listings) from a specific marketplace + * and collection with comprehensive filtering options. + * + * Parameters: + * marketplaceContractAddress: Target marketplace contract (required) + * collectionAddress: NFT collection contract (required) + * filter: MarketplaceOrderFilter with options: + * - isListing: true=listings, false=offers, omit=both + * - userAddresses: Include specific users + * - currencyAddresses: Filter by currencies (empty=all) + * - orderIds: Filter by specific order ids (empty=all) + * - tokenIds: Filter by specific tokens (empty=all) + * - excludeUserAddresses: Exclude specific users + * - blockNumberGt: Orders greater than block number + * - createdAtAfter: Orders after timestamp + * - orderStatuses: Filter by status (OPEN, CLOSED, CANCELLED) + * - returnExpired: Include expired orders + * page: Pagination control (optional) + * + * Returns: Updated pagination info and array of matching orders + */ + getMarketplaceOrders( + req: GetMarketplaceOrdersRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * GetMarketplaceTopOrders finds the most competitive orders for specific tokens. + * + * Optimized for price discovery, returns the best available orders for each token. + * Useful for displaying current market prices and finding trading opportunities. + * + * Parameters: + * marketplaceContractAddress: Target marketplace contract (required) + * collectionAddress: NFT collection contract (required) + * filter: MarketplaceTopOrdersFilter with options: + * - currencyAddresses: Consider specific currencies (empty=all) + * - tokenIds: Target token IDs (required, non-empty) + * - isListing: true=listings/sell orders, false=offers/buy orders + * - priceSort: ASC=lowest first, DESC=highest first + * - excludeUser: Hide orders from specific user + * + * Returns: Array of top-priced active orders, sorted by priceSort preference + */ + getMarketplaceTopOrders( + req: GetMarketplaceTopOrdersRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * GetNativeTokenBalance queries an ethereum node for the latest native token account balance. + * The native token is the token of the chain the indexer is connected to, for example, ETH on Ethereum + * and POL on Polygon. + */ + getNativeTokenBalance( + req: GetNativeTokenBalanceRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * GetTokenBalances returns a balance summary/details for a specific account. By default + * if accountAddress is left empty, it will use the account from the jwt session. + * + * Also, if contractAddress is undefined, then it will list all current user coins/collectibles. + * But, if contractAddress is provided, then it will return the token balances for the contract, this is + * only useful for 1155, but for other tokens, it can act as a filter for the single balance. + * + * DEPRECATED: use GetTokenBalancesSummary / GetTokenBalancesDetails + * + * @deprecated GetTokenBalancesSummary + */ + getTokenBalances(req: GetTokenBalancesRequest, headers?: object, signal?: AbortSignal): Promise + + /** + * GetTokenBalancesByContract returns a balances for a specific accounts and + * contracts. The collection ERC721 & ERC1155 tokens are represented as + * individual balances. + * + * If `filter` is not provided, it will error out as it requires at least + * contract address. + * + * If `filter.contractStatus` is not provided, it will include verified only + * tokens. + */ + getTokenBalancesByContract( + req: GetTokenBalancesByContractRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * GetTokenBalancesDetails returns a detailed balance summary for a specific + * accounts. The collection ERC721 & ERC1155 tokens are represented as + * individual balances. + * + * If `filter` is not provided, it will use the filter with account from the + * jwt session. + * + * If `filter.contractStatus` is not provided, it will include verified only + * tokens. + */ + getTokenBalancesDetails( + req: GetTokenBalancesDetailsRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * GetTokenBalancesSummary returns a summary of token balances for a specific + * accounts. The collection ERC721 & ERC1155 tokens are represented as a + * single aggregated balance. + * + * If `filter` is not provided, it will use the filter with account from the + * jwt session. + * + * If `filter.contractStatus` is not provided, it will include verified only + * tokens. + */ + getTokenBalancesSummary( + req: GetTokenBalancesSummaryRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * GetTokenIDRanges returns the range of tokenIDs for a token collection contract. + * This is useful for ERC-721 and ERC-1155 contracts to get the range of valid tokenIDs. It is similar to + * GetTokenIDs, but returns the range of tokenIDs instead of the list of tokenIDs, which is more efficient + * for large collections and very easy to the caller to expand the range into a list of tokenIDs. + * + * NOTE: this method will only return up to 15,000 ranges, if there are more ranges, it will return + * a boolean to indicate there are more ranges beyond the first 15,000. Therefore, if `moreRanges` is + * false then you have all the ranges, but if true, you need to make a follow up call to fetch the next + * page of ranges. + * + * As an example, if a NFT collection of 100,000 tokens uses ids from 1,2,3,...,100_000 then this endpoint + * will return just a single range from [1,100_000], but if there are gaps between the sequence, then + * those will be broken into separate range entries. + */ + getTokenIDRanges(req: GetTokenIDRangesRequest, headers?: object, signal?: AbortSignal): Promise + + /** + * GetTokenIDs returns the list of each individual token id for a token collection contract. + * This is useful for ERC-721 and ERC-1155 contracts to get the list of valid tokenIDs. + */ + getTokenIDs(req: GetTokenIDsRequest, headers?: object, signal?: AbortSignal): Promise + + getTokenPrice(req: GetTokenPriceRequest, headers?: object, signal?: AbortSignal): Promise + + getTokenPrices(req: GetTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise + + /** + * GetTokenSupplies returns the set of tokenIDs used by a contract address, supporting ERC-20, ERC-721, and ERC-1155 + * contracts, and their respective supply as well. + */ + getTokenSupplies(req: GetTokenSuppliesRequest, headers?: object, signal?: AbortSignal): Promise + + /** + * GetTokenSuppliesMap returns the token supplies of ERC-20 and ERC-1155 tokens as requested in the `tokenMap` + * represented as a map of contractAddress :: []tokenIDs. + * + * For an ERC-20 specify tokenIDs as an empty array or [0], for example, { '0xdef': [] } or { '0xdef': [0] } + * For ERC-1155 pass the array of tokens are strings, ie. { '0xabc': ['1', '2', '3'] } + */ + getTokenSuppliesMap( + req: GetTokenSuppliesMapRequest, + headers?: object, + signal?: AbortSignal + ): Promise - return { - webrpcGenVersion: webrpcGenVersion!, - codeGenName: codeGenName!, - codeGenVersion: codeGenVersion!, - schemaName: schemaName!, - schemaVersion: schemaVersion!, - } + /** + * History of mined transactions for the account which includes a list of token transfers (sent/recieved) + * and sent transactions from a Sequence wallet + */ + getTransactionHistory( + req: GetTransactionHistoryRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + getWebhookListener(req: GetWebhookListenerRequest, headers?: object, signal?: AbortSignal): Promise + + listTokenPrices(req: ListTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise + + pauseAllWebhookListeners( + req: PauseAllWebhookListenersRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * Ping the indexer + */ + ping(headers?: object, signal?: AbortSignal): Promise + + removeAllWebhookListeners( + req: RemoveAllWebhookListenersRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + removeWebhookListener( + req: RemoveWebhookListenerRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + resumeAllWebhookListeners( + req: ResumeAllWebhookListenersRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * Get the current runtime health status of the indexer + */ + runtimeStatus(headers?: object, signal?: AbortSignal): Promise + + /** + * SubscribeBalanceUpdates listens to balance updates for a specific contract address + */ + subscribeBalanceUpdates( + req: SubscribeBalanceUpdatesRequest, + options: WebrpcStreamOptions + ): WebrpcStreamController + + /** + * SubscribeEvents listens to events on-chain based on the filter criteria + * + * TODO: some additional options can be passed such as block, reorg true, etc. + * or stay behind, etc. + */ + subscribeEvents(req: SubscribeEventsRequest, options: WebrpcStreamOptions): WebrpcStreamController + + /** + * Listen to transaction receipts on-chain based on the filter criteria + */ + subscribeReceipts( + req: SubscribeReceiptsRequest, + options: WebrpcStreamOptions + ): WebrpcStreamController + + /** + * Re-sync an incorrect token balance with the correct on-chain balance + * NOTE: this method is almost never used, but we've marked it internal in case + * we ever want to use it again. This method was written a very long time ago in + * scenarios when the indexer had little bugs, but now its solid. + */ + syncBalance(req: SyncBalanceRequest, headers?: object, signal?: AbortSignal): Promise + + toggleWebhookListener( + req: ToggleWebhookListenerRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + updateWebhookListener( + req: UpdateWebhookListenerRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * Get the current version of the indexer + */ + version(headers?: object, signal?: AbortSignal): Promise } // -// Types +// Schema types // -export enum ResourceStatus { - NOT_AVAILABLE = 'NOT_AVAILABLE', - REFRESHING = 'REFRESHING', - AVAILABLE = 'AVAILABLE', +export interface Asset { + id: number + collectionId: number + tokenId?: string + url?: string + metadataField: string + name?: string + filesize?: number + mimeType?: string + width?: number + height?: number + updatedAt?: string +} + +export interface BloomStats { + hitRatio: string + falsePositivesPercent: string + hitCount: number + missCount: number + falsePositives: number +} + +export interface BloomStatus { + enabled: boolean + initialized: boolean + bloomInitElapsedTime: string + stats: BloomStats +} + +export interface Bond { + pebble: PebbleMetrics + estimatedDiskUsagePerTable: any + estimatedDiskUsageTotal: string +} + +export interface ChainInfo { + chainId: number + chainName: string } export interface ContractInfo { @@ -93,56 +402,29 @@ export interface ContractInfo { status: ResourceStatus } -export interface ContractInfoExtensions { - link: string - description: string - categories: Array - ogImage: string - ogName: string - originChainId: number - originAddress: string - blacklist: boolean - verified: boolean - verifiedBy: string - featured: boolean - featureIndex: number +export interface ContractInfoExtensionBridgeInfo { + tokenAddress: string } -export interface TokenMetadata { - contractAddress?: string - tokenId: string - source: string - name: string - description?: string - image?: string - video?: string - audio?: string - properties?: { [key: string]: any } - attributes: Array<{ [key: string]: any }> - image_data?: string - external_url?: string - background_color?: string - animation_url?: string - decimals?: number - updatedAt?: string - assets?: Array - status: ResourceStatus - queuedAt?: string - lastFetched?: string +export interface ContractInfoExtensionIndexingInfo { + useOnChainBalance: boolean } -export interface Asset { - id: number - collectionId: number - tokenId?: string - url?: string - metadataField: string - name?: string - filesize?: number - mimeType?: string - width?: number - height?: number - updatedAt?: string +export interface ContractInfoExtensions { + link?: string + description?: string + categories?: Array + bridgeInfo?: { [key: string]: ContractInfoExtensionBridgeInfo } + indexingInfo?: ContractInfoExtensionIndexingInfo + ogImage?: string + ogName?: string + originChainId?: number + originAddress?: string + blacklist?: boolean + verified?: boolean + verifiedBy?: string + featured?: boolean + featureIndex?: number } export enum ContractType { @@ -156,72 +438,73 @@ export enum ContractType { ERC721_BRIDGE = 'ERC721_BRIDGE', ERC1155_BRIDGE = 'ERC1155_BRIDGE', SEQ_MARKETPLACE = 'SEQ_MARKETPLACE', + ERC6909 = 'ERC6909' } -export enum EventLogType { - UNKNOWN = 'UNKNOWN', - BLOCK_ADDED = 'BLOCK_ADDED', - BLOCK_REMOVED = 'BLOCK_REMOVED', -} - -export enum EventLogDataType { - EVENT = 'EVENT', - TOKEN_TRANSFER = 'TOKEN_TRANSFER', - NATIVE_TOKEN_TRANSFER = 'NATIVE_TOKEN_TRANSFER', - SEQUENCE_TXN = 'SEQUENCE_TXN', -} - -export enum OrderStatus { - OPEN = 'OPEN', - CLOSED = 'CLOSED', - CANCELLED = 'CANCELLED', +export enum ContractVerificationStatus { + VERIFIED = 'VERIFIED', + UNVERIFIED = 'UNVERIFIED', + ALL = 'ALL' } -export enum TxnTransferType { - UNKNOWN = 'UNKNOWN', - SEND = 'SEND', - RECEIVE = 'RECEIVE', +export interface DiskUsage { + humanReadable: string + used: number + size: number + percent: number + dirs: { [key: string]: string } } -export enum TransactionStatus { - FAILED = 'FAILED', - SUCCESSFUL = 'SUCCESSFUL', +export interface EtherBalance { + accountAddress: string + balanceWei: string } -export enum TransactionType { - LegacyTxnType = 'LegacyTxnType', - AccessListTxnType = 'AccessListTxnType', - DynamicFeeTxnType = 'DynamicFeeTxnType', +export interface EventDecoded { + topicHash: string + eventSig: string + types: Array + names: Array + values: Array } -export enum SortOrder { - DESC = 'DESC', - ASC = 'ASC', +export interface EventFilter { + events?: Array + contractAddresses?: Array + accounts?: Array + tokenIDs?: Array } -export enum ContractVerificationStatus { - VERIFIED = 'VERIFIED', - UNVERIFIED = 'UNVERIFIED', - ALL = 'ALL', +export interface EventLog { + id: number + uid: string + type: EventLogType + blockNumber: number + blockHash: string + parentBlockHash: string + contractAddress: string + contractType: ContractType + txnHash: string + txnIndex: number + txnLogIndex: number + logDataType: EventLogDataType + ts: string + txnInfo?: TxnInfo + rawLog?: { [key: string]: any } + event?: EventDecoded } -export interface Version { - webrpcVersion: string - schemaVersion: string - schemaHash: string - appVersion: string +export enum EventLogDataType { + EVENT = 'EVENT', + TOKEN_TRANSFER = 'TOKEN_TRANSFER', + NATIVE_TOKEN_TRANSFER = 'NATIVE_TOKEN_TRANSFER', + SEQUENCE_TXN = 'SEQUENCE_TXN' } -export interface RuntimeStatus { - healthOK: boolean - indexerEnabled: boolean - startTime: string - uptime: number - ver: string - branch: string - commitHash: string - chainID: number - checks: RuntimeChecks +export enum EventLogType { + UNKNOWN = 'UNKNOWN', + BLOCK_ADDED = 'BLOCK_ADDED', + BLOCK_REMOVED = 'BLOCK_REMOVED' } export interface GatewayBackendResponseTime { @@ -235,6 +518,30 @@ export interface GatewayBackendRuntimeStatus { responseTime: GatewayBackendResponseTime } +export interface GatewayEtherBalance { + chainId: number + errorReason?: string + result: EtherBalance +} + +export interface GatewayNativeTokenBalance { + chainId: number + errorReason?: string + result: NativeTokenBalance +} + +export interface GatewayNativeTokenBalances { + chainId: number + errorReason?: string + results: Array +} + +export interface GatewayPrice { + chainID: number + errorReason?: string + results: Array +} + export interface GatewayRuntimeStatus { healthOK: boolean startTime: string @@ -245,43 +552,115 @@ export interface GatewayRuntimeStatus { backends: Array } -export interface WALWriterRuntimeStatus { - healthOK: boolean - startTime: string - uptime: number - ver: string - branch: string - commitHash: string +export interface GatewayTokenBalance { + chainId: number + errorReason?: string + results: Array +} + +export interface GatewayTokenPriceQuery { chainID: number - percentWALWritten: number + queries: Array +} + +export interface GatewayTransaction { + chainId: number + errorReason?: string + results: Array +} + +export interface IndexState { + chainId: string + lastBlockNum: number + lastBlockHash: string +} + +export interface IndexedBlock { + blockNumber: number + blockShortHash: string +} + +export interface IndexerMetrics { + blocksPerSecond: number + eventsPerSecond: number +} + +export interface MarketplaceOrder { + orderId: string + tokenContract: string + tokenId: string + isListing: boolean + quantity: string + quantityRemaining: string + currencyAddress: string + pricePerToken: string + expiry: string + orderStatus: OrderStatus + createdBy: string + blockNumber: number + orderbookContractAddress: string + createdAt: number +} + +export interface MarketplaceOrderFilter { + isListing?: boolean + userAddresses?: Array + currencyAddresses: Array + orderIds: Array + tokenIds: Array + excludeUserAddresses?: Array + blockNumberGt: number + createdAtAfter: number + orderStatuses: Array + returnExpired: boolean +} + +export interface MarketplaceTopOrdersFilter { + currencyAddresses: Array + tokenIds: Array + isListing: boolean + priceSort: SortOrder + excludeUser?: string } -export interface RuntimeChecks { - running: boolean - runnables: any - cgoEnabled: boolean - quotaControlEnabled: boolean - syncMode: string - percentIndexed: number - lastBlockNum: number - lastBlockNumWithState: number - bloomStatus: BloomStatus - bond: Bond - diskUsage: DiskUsage +export interface MetadataOptions { + verifiedOnly?: boolean + unverifiedOnly?: boolean + includeContracts?: Array } -export interface DiskUsage { - humanReadable: string - used: number - size: number - percent: number - dirs: { [key: string]: string } +export interface NativeTokenBalance { + accountAddress: string + chainId: number + name: string + symbol: string + balance: string + balanceUSD: string + priceUSD: string + priceUpdatedAt?: string + errorReason?: string } -export interface Bond { - pebble: PebbleMetrics - estimatedDiskUsagePerTable: any - estimatedDiskUsageTotal: string +export enum NetworkType { + MAINNETS = 'MAINNETS', + TESTNETS = 'TESTNETS', + ALL = 'ALL' +} + +export enum OrderStatus { + OPEN = 'OPEN', + CLOSED = 'CLOSED', + CANCELLED = 'CANCELLED' +} + +export interface Page { + page?: number + column?: string + before?: any + after?: any + sort?: Array + pageSize?: number + more?: boolean } export interface PebbleMetrics { @@ -292,66 +671,54 @@ export interface PebbleMetrics { compactionMarkedFiles: number } -export interface BloomStatus { - enabled: boolean - initialized: boolean - bloomInitElapsedTime: string -} - -export interface EtherBalance { - accountAddress: string - balanceWei: string +export interface Price { + contractAddress: string + tokenID?: string + priceUSD: string + updatedAt?: string } -export interface NativeTokenBalance { - accountAddress: string - chainId: number - balance: string - error: string +export enum ResourceStatus { + NOT_AVAILABLE = 'NOT_AVAILABLE', + REFRESHING = 'REFRESHING', + AVAILABLE = 'AVAILABLE' } -export interface IndexState { - chainId: string +export interface RuntimeChecks { + running: boolean + runnables: any + cgoEnabled: boolean + quotaControlEnabled: boolean + syncMode: string + percentIndexed: number lastBlockNum: number - lastBlockHash: string -} - -export interface IndexedBlock { - blockNumber: number - blockShortHash: string + lastBlockNumWithState: number + bloomStatus: BloomStatus + bond: Bond + diskUsage: DiskUsage + metrics: IndexerMetrics } -export interface TxnInfo { - from: string - to: string - value: string +export interface RuntimeStatus { + healthOK: boolean + indexerEnabled: boolean + startTime: string + uptime: number + ver: string + branch: string + commitHash: string + chainID: number + checks: RuntimeChecks } -export interface EventLog { - id: number - uid: string - type: EventLogType - blockNumber: number - blockHash: string - parentBlockHash: string - contractAddress: string - contractType: ContractType - txnHash: string - txnIndex: number - txnLogIndex: number - logDataType: EventLogDataType - ts: string - txnInfo?: TxnInfo - rawLog?: { [key: string]: any } - event?: EventDecoded +export interface SortBy { + column: string + order: SortOrder } -export interface EventDecoded { - topicHash: string - eventSig: string - types: Array - names: Array - values: Array +export enum SortOrder { + DESC = 'DESC', + ASC = 'ASC' } export interface TokenBalance { @@ -360,6 +727,9 @@ export interface TokenBalance { accountAddress: string tokenID?: string balance: string + balanceUSD: string + priceUSD: string + priceUpdatedAt?: string blockHash: string blockNumber: number chainId: number @@ -369,39 +739,32 @@ export interface TokenBalance { tokenMetadata?: TokenMetadata } -export interface OrderbookOrder { - orderId: string - tokenContract: string - tokenId: string - isListing: boolean - quantity: string - quantityRemaining: string - currencyAddress: string - pricePerToken: string - expiry: string - orderStatus: OrderStatus - createdBy: string - blockNumber: number - orderbookContractAddress: string - createdAt: number +export interface TokenBalanceFilter { + contractAddress: string + sinceBlockNumber: number } -export interface OrderbookOrderFilter { - isListing?: boolean - userAddresses?: Array - tokenIds: Array - excludeUserAddresses?: Array - afterBlockNumber: number - afterCreatedAt: number - beforeExpiry: number - userAddress?: string - excludeUserAddress?: string +export interface TokenBalancesByContractFilter { + contractAddresses: Array + accountAddresses?: Array + contractStatus?: ContractVerificationStatus + tokenIDs?: Array +} + +export interface TokenBalancesFilter { + accountAddresses: Array + contractStatus?: ContractVerificationStatus + contractTypes?: Array + contractWhitelist?: Array + contractBlacklist?: Array + omitNativeBalances: boolean + omitPrices?: boolean + tokenIDs?: Array } export interface TokenHistory { blockNumber: number blockHash: string - accountAddress: string contractAddress: string contractType: ContractType fromAddress: string @@ -409,12 +772,45 @@ export interface TokenHistory { txnHash: string txnIndex: number txnLogIndex: number - logData: string tokenIDs: string - Amounts: string + amounts: string ts: string } +export interface TokenIDRange { + start: string + end: string +} + +export interface TokenMetadata { + chainId?: number + contractAddress?: string + tokenId: string + source: string + name: string + description?: string + image?: string + video?: string + audio?: string + properties?: { [key: string]: any } + attributes: Array<{ [key: string]: any }> + image_data?: string + external_url?: string + background_color?: string + animation_url?: string + decimals?: number + updatedAt?: string + assets?: Array + status: ResourceStatus + queuedAt?: string + lastFetched?: string +} + +export interface TokenPriceQuery { + contractAddress: string + tokenID?: string +} + export interface TokenSupply { tokenID: string supply: string @@ -433,17 +829,12 @@ export interface Transaction { timestamp: string } -export interface TxnTransfer { - transferType: TxnTransferType - contractAddress: string - contractType: ContractType - from: string - to: string - tokenIds?: Array - amounts: Array - logIndex: number - contractInfo?: ContractInfo - tokenMetadata?: { [key: string]: TokenMetadata } +export interface TransactionFilter { + txnHash?: string + from?: string + to?: string + contractAddress?: string + event?: string } export interface TransactionHistoryFilter { @@ -456,14 +847,14 @@ export interface TransactionHistoryFilter { fromBlock?: number toBlock?: number tokenID?: string + omitPrices?: boolean } -export interface TransactionFilter { - txnHash?: string - from?: string - to?: string - contractAddress?: string - event?: string +export interface TransactionLog { + contractAddress: string + topics: Array + data: string + index: number } export interface TransactionReceipt { @@ -482,31 +873,60 @@ export interface TransactionReceipt { reorged: boolean } -export interface TransactionLog { - contractAddress: string - topics: Array - data: string - index: number +export enum TransactionStatus { + FAILED = 'FAILED', + SUCCESSFUL = 'SUCCESSFUL' } -export interface TokenIDRange { - start: string - end: string +export enum TransactionType { + LegacyTxnType = 'LegacyTxnType', + AccessListTxnType = 'AccessListTxnType', + DynamicFeeTxnType = 'DynamicFeeTxnType' +} + +export interface TxnInfo { + from: string + to: string + value: string +} + +export interface TxnTransfer { + transferType: TxnTransferType + contractAddress: string + contractType: ContractType + from: string + to: string + tokenIds?: Array + amounts: Array + logIndex: number + amountsUSD?: Array + pricesUSD?: Array + contractInfo?: ContractInfo + tokenMetadata?: { [key: string]: TokenMetadata } } -export interface Page { - page?: number - column?: string - before?: any - after?: any - sort?: Array - pageSize?: number - more?: boolean +export enum TxnTransferType { + UNKNOWN = 'UNKNOWN', + SEND = 'SEND', + RECEIVE = 'RECEIVE' } -export interface SortBy { - column: string - order: SortOrder +export interface Version { + webrpcVersion: string + schemaVersion: string + schemaHash: string + appVersion: string +} + +export interface WALWriterRuntimeStatus { + healthOK: boolean + startTime: string + uptime: number + ver: string + branch: string + commitHash: string + chainID: number + percentWALWritten: number } export interface WebhookListener { @@ -519,469 +939,345 @@ export interface WebhookListener { active: boolean } -export interface EventFilter { - events?: Array - contractAddresses?: Array - accounts?: Array - tokenIDs?: Array +export interface AddWebhookListenerRequest { + url: string + filters: EventFilter + projectId?: number } -export interface TokenBalanceFilter { - contractAddress: string - sinceBlockNumber: number +export interface AddWebhookListenerResponse { + status: boolean + listener: WebhookListener } -export interface MetadataOptions { - verifiedOnly?: boolean - unverifiedOnly?: boolean - includeContracts?: Array +export interface FetchTransactionReceiptRequest { + txnHash: string + maxBlockWait?: number } -export interface TokenBalancesFilter { - accountAddresses: Array - contractStatus?: ContractVerificationStatus - contractTypes?: Array - contractWhitelist?: Array - contractBlacklist?: Array - omitNativeBalances: boolean +export interface FetchTransactionReceiptResponse { + receipt: TransactionReceipt } -export interface TokenBalancesByContractFilter { - contractAddresses: Array - accountAddresses?: Array - contractStatus?: ContractVerificationStatus +export interface FetchTransactionReceiptWithFilterRequest { + filter: TransactionFilter + maxBlockWait?: number } -export interface GatewayEtherBalance { - chainId: number - error: string - result: EtherBalance +export interface FetchTransactionReceiptWithFilterResponse { + receipt: TransactionReceipt } -export interface GatewayNativeTokenBalance { - chainId: number - error: string - result: NativeTokenBalance +export interface GetAllWebhookListenersRequest { + projectId?: number } -export interface GatewayNativeTokenBalances { - chainId: number - error: string - results: Array +export interface GetAllWebhookListenersResponse { + listeners: Array } -export interface GatewayTokenBalance { - chainId: number - error: string - results: Array +export interface GetBalanceUpdatesRequest { + contractAddress: string + lastBlockNumber: number + lastBlockHash?: string + page?: Page } -export interface Indexer { - ping(headers?: object, signal?: AbortSignal): Promise - version(headers?: object, signal?: AbortSignal): Promise - runtimeStatus(headers?: object, signal?: AbortSignal): Promise - getChainID(headers?: object, signal?: AbortSignal): Promise - getEtherBalance(args: GetEtherBalanceArgs, headers?: object, signal?: AbortSignal): Promise - getNativeTokenBalance( - args: GetNativeTokenBalanceArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - getTokenBalancesSummary( - args: GetTokenBalancesSummaryArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - getTokenBalancesDetails( - args: GetTokenBalancesDetailsArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - getTokenBalancesByContract( - args: GetTokenBalancesByContractArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - getTokenBalances(args: GetTokenBalancesArgs, headers?: object, signal?: AbortSignal): Promise - getTokenSupplies(args: GetTokenSuppliesArgs, headers?: object, signal?: AbortSignal): Promise - getTokenSuppliesMap( - args: GetTokenSuppliesMapArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - getTokenIDs(args: GetTokenIDsArgs, headers?: object, signal?: AbortSignal): Promise - getTokenIDRanges(args: GetTokenIDRangesArgs, headers?: object, signal?: AbortSignal): Promise - getBalanceUpdates( - args: GetBalanceUpdatesArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - getTransactionHistory( - args: GetTransactionHistoryArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - fetchTransactionReceipt( - args: FetchTransactionReceiptArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - fetchTransactionReceiptWithFilter( - args: FetchTransactionReceiptWithFilterArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - subscribeReceipts(args: SubscribeReceiptsArgs, options: WebrpcStreamOptions): Promise - subscribeEvents(args: SubscribeEventsArgs, options: WebrpcStreamOptions): Promise - subscribeBalanceUpdates( - args: SubscribeBalanceUpdatesArgs, - options: WebrpcStreamOptions, - ): Promise - syncBalance(args: SyncBalanceArgs, headers?: object, signal?: AbortSignal): Promise - getAllWebhookListeners( - args: GetAllWebhookListenersArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - getWebhookListener( - args: GetWebhookListenerArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - addWebhookListener( - args: AddWebhookListenerArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - updateWebhookListener( - args: UpdateWebhookListenerArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - removeWebhookListener( - args: RemoveWebhookListenerArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - removeAllWebhookListeners( - args: RemoveAllWebhookListenersArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - toggleWebhookListener( - args: ToggleWebhookListenerArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - pauseAllWebhookListeners( - args: PauseAllWebhookListenersArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - resumeAllWebhookListeners( - args: ResumeAllWebhookListenersArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - getOrderbookOrders( - args: GetOrderbookOrdersArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - getTopOrders(args: GetTopOrdersArgs, headers?: object, signal?: AbortSignal): Promise +export interface GetBalanceUpdatesResponse { + page: Page + balances: Array } -export interface PingArgs {} +export interface GetChainIDRequest {} -export interface PingReturn { - status: boolean +export interface GetChainIDResponse { + chainID: number } -export interface VersionArgs {} -export interface VersionReturn { - version: Version +export interface GetEtherBalanceRequest { + accountAddress?: string } -export interface RuntimeStatusArgs {} -export interface RuntimeStatusReturn { - status: RuntimeStatus +export interface GetEtherBalanceResponse { + balance: EtherBalance } -export interface GetChainIDArgs {} -export interface GetChainIDReturn { - chainID: number +export interface GetMarketplaceOrdersRequest { + marketplaceContractAddress: string + collectionAddress: string + filter?: MarketplaceOrderFilter + page?: Page } -export interface GetEtherBalanceArgs { - accountAddress?: string + +export interface GetMarketplaceOrdersResponse { + page?: Page + orders: Array } -export interface GetEtherBalanceReturn { - balance: EtherBalance +export interface GetMarketplaceTopOrdersRequest { + marketplaceContractAddress: string + collectionAddress: string + filter: MarketplaceTopOrdersFilter +} + +export interface GetMarketplaceTopOrdersResponse { + orders: Array } -export interface GetNativeTokenBalanceArgs { + +export interface GetNativeTokenBalanceRequest { accountAddress?: string + omitPrices?: boolean } -export interface GetNativeTokenBalanceReturn { +export interface GetNativeTokenBalanceResponse { balance: NativeTokenBalance } -export interface GetTokenBalancesSummaryArgs { - filter: TokenBalancesFilter - omitMetadata?: boolean + +export interface GetTokenBalancesRequest { + accountAddress?: string + contractAddress?: string + tokenID?: string + includeMetadata?: boolean + metadataOptions?: MetadataOptions + includeCollectionTokens?: boolean page?: Page } -export interface GetTokenBalancesSummaryReturn { +export interface GetTokenBalancesResponse { page: Page - nativeBalances: Array balances: Array } -export interface GetTokenBalancesDetailsArgs { - filter: TokenBalancesFilter + +export interface GetTokenBalancesByContractRequest { + filter: TokenBalancesByContractFilter omitMetadata?: boolean page?: Page } -export interface GetTokenBalancesDetailsReturn { +export interface GetTokenBalancesByContractResponse { page: Page - nativeBalances: Array balances: Array } -export interface GetTokenBalancesByContractArgs { - filter: TokenBalancesByContractFilter + +export interface GetTokenBalancesDetailsRequest { + filter: TokenBalancesFilter omitMetadata?: boolean page?: Page } -export interface GetTokenBalancesByContractReturn { +export interface GetTokenBalancesDetailsResponse { page: Page + nativeBalances: Array balances: Array } -export interface GetTokenBalancesArgs { - accountAddress?: string - contractAddress?: string - tokenID?: string - includeMetadata?: boolean - metadataOptions?: MetadataOptions - includeCollectionTokens?: boolean + +export interface GetTokenBalancesSummaryRequest { + filter: TokenBalancesFilter + omitMetadata?: boolean page?: Page } -export interface GetTokenBalancesReturn { +export interface GetTokenBalancesSummaryResponse { page: Page + nativeBalances: Array balances: Array } -export interface GetTokenSuppliesArgs { + +export interface GetTokenIDRangesRequest { contractAddress: string - includeMetadata?: boolean - metadataOptions?: MetadataOptions - page?: Page + lastTokenID?: string } -export interface GetTokenSuppliesReturn { - page: Page +export interface GetTokenIDRangesResponse { contractType: ContractType - tokenIDs: Array -} -export interface GetTokenSuppliesMapArgs { - tokenMap: { [key: string]: Array } - includeMetadata?: boolean - metadataOptions?: MetadataOptions + tokenIDRanges: Array + moreRanges: boolean } -export interface GetTokenSuppliesMapReturn { - supplies: { [key: string]: Array } -} -export interface GetTokenIDsArgs { +export interface GetTokenIDsRequest { contractAddress: string page?: Page } -export interface GetTokenIDsReturn { +export interface GetTokenIDsResponse { page: Page contractType: ContractType tokenIDs: Array } -export interface GetTokenIDRangesArgs { - contractAddress: string + +export interface GetTokenPriceRequest { + q: TokenPriceQuery } -export interface GetTokenIDRangesReturn { - contractType: ContractType - tokenIDRanges: Array - moreRanges: boolean +export interface GetTokenPriceResponse { + price: Price +} + +export interface GetTokenPricesRequest { + q: Array +} + +export interface GetTokenPricesResponse { + prices: Array } -export interface GetBalanceUpdatesArgs { + +export interface GetTokenSuppliesRequest { contractAddress: string - lastBlockNumber: number - lastBlockHash?: string + includeMetadata?: boolean page?: Page } -export interface GetBalanceUpdatesReturn { +export interface GetTokenSuppliesResponse { page: Page - balances: Array + contractType: ContractType + tokenIDs: Array +} + +export interface GetTokenSuppliesMapRequest { + tokenMap: { [key: string]: Array } + includeMetadata?: boolean +} + +export interface GetTokenSuppliesMapResponse { + supplies: { [key: string]: Array } } -export interface GetTransactionHistoryArgs { + +export interface GetTransactionHistoryRequest { filter: TransactionHistoryFilter page?: Page includeMetadata?: boolean metadataOptions?: MetadataOptions } -export interface GetTransactionHistoryReturn { +export interface GetTransactionHistoryResponse { page: Page transactions: Array } -export interface FetchTransactionReceiptArgs { - txnHash: string - maxBlockWait?: number -} -export interface FetchTransactionReceiptReturn { - receipt: TransactionReceipt -} -export interface FetchTransactionReceiptWithFilterArgs { - filter: TransactionFilter - maxBlockWait?: number +export interface GetWebhookListenerRequest { + id: number + projectId?: number } -export interface FetchTransactionReceiptWithFilterReturn { - receipt: TransactionReceipt -} -export interface SubscribeReceiptsArgs { - filter: TransactionFilter +export interface GetWebhookListenerResponse { + listener: WebhookListener } -export interface SubscribeReceiptsReturn { - receipt: TransactionReceipt -} -export interface SubscribeEventsArgs { - filter: EventFilter +export interface ListTokenPricesRequest { + page?: Page } -export interface SubscribeEventsReturn { - log: EventLog +export interface ListTokenPricesResponse { + page: Page + prices: Array } -export interface SubscribeBalanceUpdatesArgs { - contractAddress: string + +export interface PauseAllWebhookListenersRequest { + projectId?: number } -export interface SubscribeBalanceUpdatesReturn { - balance: TokenBalance +export interface PauseAllWebhookListenersResponse { + status: boolean } -export interface SyncBalanceArgs { - accountAddress: string - contractAddress: string - tokenID?: string + +export interface PingRequest {} + +export interface PingResponse { + status: boolean } -export interface SyncBalanceReturn {} -export interface GetAllWebhookListenersArgs { +export interface RemoveAllWebhookListenersRequest { projectId?: number } -export interface GetAllWebhookListenersReturn { - listeners: Array +export interface RemoveAllWebhookListenersResponse { + status: boolean } -export interface GetWebhookListenerArgs { + +export interface RemoveWebhookListenerRequest { id: number projectId?: number } -export interface GetWebhookListenerReturn { - listener: WebhookListener +export interface RemoveWebhookListenerResponse { + status: boolean } -export interface AddWebhookListenerArgs { - url: string - filters: EventFilter + +export interface ResumeAllWebhookListenersRequest { projectId?: number } -export interface AddWebhookListenerReturn { +export interface ResumeAllWebhookListenersResponse { status: boolean - listener: WebhookListener } -export interface UpdateWebhookListenerArgs { - listener: WebhookListener - projectId?: number + +export interface RuntimeStatusRequest {} + +export interface RuntimeStatusResponse { + status: RuntimeStatus } -export interface UpdateWebhookListenerReturn { - status: boolean +export interface SubscribeBalanceUpdatesRequest { + contractAddress: string } -export interface RemoveWebhookListenerArgs { - id: number - projectId?: number + +export interface SubscribeBalanceUpdatesResponse { + balance: TokenBalance +} + +export interface SubscribeEventsRequest { + filter: EventFilter +} + +export interface SubscribeEventsResponse { + log: EventLog } -export interface RemoveWebhookListenerReturn { - status: boolean +export interface SubscribeReceiptsRequest { + filter: TransactionFilter } -export interface RemoveAllWebhookListenersArgs { - projectId?: number + +export interface SubscribeReceiptsResponse { + receipt: TransactionReceipt } -export interface RemoveAllWebhookListenersReturn { - status: boolean +export interface SyncBalanceRequest { + accountAddress: string + contractAddress: string + tokenID?: string } -export interface ToggleWebhookListenerArgs { + +export interface SyncBalanceResponse {} + +export interface ToggleWebhookListenerRequest { id: number projectId?: number } -export interface ToggleWebhookListenerReturn { +export interface ToggleWebhookListenerResponse { webhookListener: WebhookListener } -export interface PauseAllWebhookListenersArgs { - projectId?: number -} -export interface PauseAllWebhookListenersReturn { - status: boolean -} -export interface ResumeAllWebhookListenersArgs { +export interface UpdateWebhookListenerRequest { + listener: WebhookListener projectId?: number } -export interface ResumeAllWebhookListenersReturn { +export interface UpdateWebhookListenerResponse { status: boolean } -export interface GetOrderbookOrdersArgs { - page?: Page - orderbookContractAddress: string - collectionAddress: string - currencyAddresses: Array - filter: OrderbookOrderFilter - orderStatuses: Array - filters: Array - beforeExpiryTimestamp: number - blockNumberAfter: number - createdAtAfter: number -} -export interface GetOrderbookOrdersReturn { - page?: Page - orders: Array -} -export interface GetTopOrdersArgs { - orderbookContractAddress: string - collectionAddress: string - currencyAddresses: Array - tokenIDs: Array - isListing: boolean - priceSort: SortOrder - excludeUser?: string -} +export interface VersionRequest {} -export interface GetTopOrdersReturn { - orders: Array +export interface VersionResponse { + version: Version } // // Client // -export class Indexer implements Indexer { + +export class Indexer implements IndexerClient { protected hostname: string protected fetch: Fetch protected path = '/rpc/Indexer/' @@ -995,601 +1291,652 @@ export class Indexer implements Indexer { return this.hostname + this.path + name } - ping = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Ping'), createHTTPRequest({}, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - status: _data.status, - } + queryKey = { + addWebhookListener: (req: AddWebhookListenerRequest) => ['Indexer', 'addWebhookListener', req] as const, + fetchTransactionReceipt: (req: FetchTransactionReceiptRequest) => ['Indexer', 'fetchTransactionReceipt', req] as const, + fetchTransactionReceiptWithFilter: (req: FetchTransactionReceiptWithFilterRequest) => + ['Indexer', 'fetchTransactionReceiptWithFilter', req] as const, + getAllWebhookListeners: (req: GetAllWebhookListenersRequest) => ['Indexer', 'getAllWebhookListeners', req] as const, + getBalanceUpdates: (req: GetBalanceUpdatesRequest) => ['Indexer', 'getBalanceUpdates', req] as const, + getChainID: () => ['Indexer', 'getChainID'] as const, + getEtherBalance: (req: GetEtherBalanceRequest) => ['Indexer', 'getEtherBalance', req] as const, + getMarketplaceOrders: (req: GetMarketplaceOrdersRequest) => ['Indexer', 'getMarketplaceOrders', req] as const, + getMarketplaceTopOrders: (req: GetMarketplaceTopOrdersRequest) => ['Indexer', 'getMarketplaceTopOrders', req] as const, + getNativeTokenBalance: (req: GetNativeTokenBalanceRequest) => ['Indexer', 'getNativeTokenBalance', req] as const, + getTokenBalances: (req: GetTokenBalancesRequest) => ['Indexer', 'getTokenBalances', req] as const, + getTokenBalancesByContract: (req: GetTokenBalancesByContractRequest) => + ['Indexer', 'getTokenBalancesByContract', req] as const, + getTokenBalancesDetails: (req: GetTokenBalancesDetailsRequest) => ['Indexer', 'getTokenBalancesDetails', req] as const, + getTokenBalancesSummary: (req: GetTokenBalancesSummaryRequest) => ['Indexer', 'getTokenBalancesSummary', req] as const, + getTokenIDRanges: (req: GetTokenIDRangesRequest) => ['Indexer', 'getTokenIDRanges', req] as const, + getTokenIDs: (req: GetTokenIDsRequest) => ['Indexer', 'getTokenIDs', req] as const, + getTokenPrice: (req: GetTokenPriceRequest) => ['Indexer', 'getTokenPrice', req] as const, + getTokenPrices: (req: GetTokenPricesRequest) => ['Indexer', 'getTokenPrices', req] as const, + getTokenSupplies: (req: GetTokenSuppliesRequest) => ['Indexer', 'getTokenSupplies', req] as const, + getTokenSuppliesMap: (req: GetTokenSuppliesMapRequest) => ['Indexer', 'getTokenSuppliesMap', req] as const, + getTransactionHistory: (req: GetTransactionHistoryRequest) => ['Indexer', 'getTransactionHistory', req] as const, + getWebhookListener: (req: GetWebhookListenerRequest) => ['Indexer', 'getWebhookListener', req] as const, + listTokenPrices: (req: ListTokenPricesRequest) => ['Indexer', 'listTokenPrices', req] as const, + pauseAllWebhookListeners: (req: PauseAllWebhookListenersRequest) => ['Indexer', 'pauseAllWebhookListeners', req] as const, + ping: () => ['Indexer', 'ping'] as const, + removeAllWebhookListeners: (req: RemoveAllWebhookListenersRequest) => ['Indexer', 'removeAllWebhookListeners', req] as const, + removeWebhookListener: (req: RemoveWebhookListenerRequest) => ['Indexer', 'removeWebhookListener', req] as const, + resumeAllWebhookListeners: (req: ResumeAllWebhookListenersRequest) => ['Indexer', 'resumeAllWebhookListeners', req] as const, + runtimeStatus: () => ['Indexer', 'runtimeStatus'] as const, + subscribeBalanceUpdates: (req: SubscribeBalanceUpdatesRequest) => ['Indexer', 'subscribeBalanceUpdates', req] as const, + subscribeEvents: (req: SubscribeEventsRequest) => ['Indexer', 'subscribeEvents', req] as const, + subscribeReceipts: (req: SubscribeReceiptsRequest) => ['Indexer', 'subscribeReceipts', req] as const, + syncBalance: (req: SyncBalanceRequest) => ['Indexer', 'syncBalance', req] as const, + toggleWebhookListener: (req: ToggleWebhookListenerRequest) => ['Indexer', 'toggleWebhookListener', req] as const, + updateWebhookListener: (req: UpdateWebhookListenerRequest) => ['Indexer', 'updateWebhookListener', req] as const, + version: () => ['Indexer', 'version'] as const + } + + addWebhookListener = ( + req: AddWebhookListenerRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('AddWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'AddWebhookListenerResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - version = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Version'), createHTTPRequest({}, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - version: _data.version, - } + fetchTransactionReceipt = ( + req: FetchTransactionReceiptRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('FetchTransactionReceipt'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'FetchTransactionReceiptResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - runtimeStatus = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('RuntimeStatus'), createHTTPRequest({}, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - status: _data.status, - } + fetchTransactionReceiptWithFilter = ( + req: FetchTransactionReceiptWithFilterRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('FetchTransactionReceiptWithFilter'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'FetchTransactionReceiptWithFilterResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getChainID = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetChainID'), createHTTPRequest({}, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - chainID: _data.chainID, - } + getAllWebhookListeners = ( + req: GetAllWebhookListenersRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetAllWebhookListeners'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetAllWebhookListenersResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getEtherBalance = ( - args: GetEtherBalanceArgs, + getBalanceUpdates = ( + req: GetBalanceUpdatesRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetEtherBalance'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - balance: _data.balance, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetBalanceUpdates'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetBalanceUpdatesResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getNativeTokenBalance = ( - args: GetNativeTokenBalanceArgs, - headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetNativeTokenBalance'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - balance: _data.balance, - } + getChainID = (headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetChainID'), createHttpRequest('{}', headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetChainIDResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } + ) + } + + getEtherBalance = (req: GetEtherBalanceRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetEtherBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetEtherBalanceResponse') + }) }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getTokenBalancesSummary = ( - args: GetTokenBalancesSummaryArgs, + getMarketplaceOrders = ( + req: GetMarketplaceOrdersRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetTokenBalancesSummary'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - nativeBalances: >_data.nativeBalances, - balances: >_data.balances, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetMarketplaceOrders'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetMarketplaceOrdersResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getTokenBalancesDetails = ( - args: GetTokenBalancesDetailsArgs, + getMarketplaceTopOrders = ( + req: GetMarketplaceTopOrdersRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetTokenBalancesDetails'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - nativeBalances: >_data.nativeBalances, - balances: >_data.balances, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetMarketplaceTopOrders'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetMarketplaceTopOrdersResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getTokenBalancesByContract = ( - args: GetTokenBalancesByContractArgs, + getNativeTokenBalance = ( + req: GetNativeTokenBalanceRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetTokenBalancesByContract'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - balances: >_data.balances, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetNativeTokenBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetNativeTokenBalanceResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } getTokenBalances = ( - args: GetTokenBalancesArgs, + req: GetTokenBalancesRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetTokenBalances'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - balances: >_data.balances, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetTokenBalances'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenBalancesResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getTokenSupplies = ( - args: GetTokenSuppliesArgs, + getTokenBalancesByContract = ( + req: GetTokenBalancesByContractRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetTokenSupplies'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - contractType: _data.contractType, - tokenIDs: >_data.tokenIDs, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetTokenBalancesByContract'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenBalancesByContractResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getTokenSuppliesMap = ( - args: GetTokenSuppliesMapArgs, + getTokenBalancesDetails = ( + req: GetTokenBalancesDetailsRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetTokenSuppliesMap'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - supplies: <{ [key: string]: Array }>_data.supplies, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetTokenBalancesDetails'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenBalancesDetailsResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getTokenIDs = (args: GetTokenIDsArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenIDs'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - contractType: _data.contractType, - tokenIDs: >_data.tokenIDs, - } + getTokenBalancesSummary = ( + req: GetTokenBalancesSummaryRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetTokenBalancesSummary'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenBalancesSummaryResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } getTokenIDRanges = ( - args: GetTokenIDRangesArgs, + req: GetTokenIDRangesRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetTokenIDRanges'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - contractType: _data.contractType, - tokenIDRanges: >_data.tokenIDRanges, - moreRanges: _data.moreRanges, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetTokenIDRanges'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenIDRangesResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getBalanceUpdates = ( - args: GetBalanceUpdatesArgs, - headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetBalanceUpdates'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - balances: >_data.balances, - } + getTokenIDs = (req: GetTokenIDsRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetTokenIDs'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenIDsResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getTransactionHistory = ( - args: GetTransactionHistoryArgs, - headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetTransactionHistory'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - transactions: >_data.transactions, - } + getTokenPrice = (req: GetTokenPriceRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetTokenPrice'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenPriceResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - fetchTransactionReceipt = ( - args: FetchTransactionReceiptArgs, - headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('FetchTransactionReceipt'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - receipt: _data.receipt, - } + getTokenPrices = (req: GetTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetTokenPrices'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenPricesResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - fetchTransactionReceiptWithFilter = ( - args: FetchTransactionReceiptWithFilterArgs, + getTokenSupplies = ( + req: GetTokenSuppliesRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('FetchTransactionReceiptWithFilter'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - receipt: _data.receipt, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetTokenSupplies'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenSuppliesResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - subscribeReceipts = ( - args: SubscribeReceiptsArgs, - options: WebrpcStreamOptions, - ): Promise => { - const _fetch = () => - this.fetch(this.url('SubscribeReceipts'), createHTTPRequest(args, options.headers, options.signal)).then( - async (res) => { - await sseResponse(res, options, _fetch) - }, - (error) => { - options.onError(error, _fetch) - }, - ) - return _fetch() - } - subscribeEvents = (args: SubscribeEventsArgs, options: WebrpcStreamOptions): Promise => { - const _fetch = () => - this.fetch(this.url('SubscribeEvents'), createHTTPRequest(args, options.headers, options.signal)).then( - async (res) => { - await sseResponse(res, options, _fetch) - }, - (error) => { - options.onError(error, _fetch) - }, - ) - return _fetch() - } - subscribeBalanceUpdates = ( - args: SubscribeBalanceUpdatesArgs, - options: WebrpcStreamOptions, - ): Promise => { - const _fetch = () => - this.fetch(this.url('SubscribeBalanceUpdates'), createHTTPRequest(args, options.headers, options.signal)).then( - async (res) => { - await sseResponse(res, options, _fetch) - }, - (error) => { - options.onError(error, _fetch) - }, - ) - return _fetch() - } - syncBalance = (args: SyncBalanceArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('SyncBalance'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return {} + getTokenSuppliesMap = ( + req: GetTokenSuppliesMapRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetTokenSuppliesMap'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenSuppliesMapResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getAllWebhookListeners = ( - args: GetAllWebhookListenersArgs, + getTransactionHistory = ( + req: GetTransactionHistoryRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetAllWebhookListeners'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - listeners: >_data.listeners, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetTransactionHistory'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTransactionHistoryResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } getWebhookListener = ( - args: GetWebhookListenerArgs, + req: GetWebhookListenerRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetWebhookListener'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - listener: _data.listener, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetWebhookListenerResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } + ) + } + + listTokenPrices = (req: ListTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('ListTokenPrices'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'ListTokenPricesResponse') + }) }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - addWebhookListener = ( - args: AddWebhookListenerArgs, + pauseAllWebhookListeners = ( + req: PauseAllWebhookListenersRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('AddWebhookListener'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - status: _data.status, - listener: _data.listener, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('PauseAllWebhookListeners'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'PauseAllWebhookListenersResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } + ) + } + + ping = (headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('Ping'), createHttpRequest('{}', headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'PingResponse') + }) }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - updateWebhookListener = ( - args: UpdateWebhookListenerArgs, + removeAllWebhookListeners = ( + req: RemoveAllWebhookListenersRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('UpdateWebhookListener'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - status: _data.status, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('RemoveAllWebhookListeners'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'RemoveAllWebhookListenersResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } removeWebhookListener = ( - args: RemoveWebhookListenerArgs, + req: RemoveWebhookListenerRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('RemoveWebhookListener'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - status: _data.status, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('RemoveWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'RemoveWebhookListenerResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - removeAllWebhookListeners = ( - args: RemoveAllWebhookListenersArgs, + resumeAllWebhookListeners = ( + req: ResumeAllWebhookListenersRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('RemoveAllWebhookListeners'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - status: _data.status, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('ResumeAllWebhookListeners'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'ResumeAllWebhookListenersResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - toggleWebhookListener = ( - args: ToggleWebhookListenerArgs, - headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('ToggleWebhookListener'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - webhookListener: _data.webhookListener, - } + runtimeStatus = (headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('RuntimeStatus'), createHttpRequest('{}', headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'RuntimeStatusResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - pauseAllWebhookListeners = ( - args: PauseAllWebhookListenersArgs, - headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('PauseAllWebhookListeners'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - status: _data.status, - } + subscribeBalanceUpdates = ( + req: SubscribeBalanceUpdatesRequest, + options: WebrpcStreamOptions + ): WebrpcStreamController => { + const abortController = new AbortController() + const abortSignal = abortController.signal + + if (options.signal) { + abortSignal.addEventListener('abort', () => abortController.abort(options.signal?.reason), { + signal: options.signal + }) + } + + const _fetch = () => + this.fetch(this.url('SubscribeBalanceUpdates'), createHttpRequest(JsonEncode(req), options.headers, abortSignal)).then( + async res => { + await sseResponse(res, options, _fetch) + }, + error => { + options.onError(error, _fetch) + } + ) + + const resp = _fetch() + return { + abort: abortController.abort.bind(abortController), + closed: resp + } + } + subscribeEvents = ( + req: SubscribeEventsRequest, + options: WebrpcStreamOptions + ): WebrpcStreamController => { + const abortController = new AbortController() + const abortSignal = abortController.signal + + if (options.signal) { + abortSignal.addEventListener('abort', () => abortController.abort(options.signal?.reason), { + signal: options.signal + }) + } + + const _fetch = () => + this.fetch(this.url('SubscribeEvents'), createHttpRequest(JsonEncode(req), options.headers, abortSignal)).then( + async res => { + await sseResponse(res, options, _fetch) + }, + error => { + options.onError(error, _fetch) + } + ) + + const resp = _fetch() + return { + abort: abortController.abort.bind(abortController), + closed: resp + } + } + subscribeReceipts = ( + req: SubscribeReceiptsRequest, + options: WebrpcStreamOptions + ): WebrpcStreamController => { + const abortController = new AbortController() + const abortSignal = abortController.signal + + if (options.signal) { + abortSignal.addEventListener('abort', () => abortController.abort(options.signal?.reason), { + signal: options.signal + }) + } + + const _fetch = () => + this.fetch(this.url('SubscribeReceipts'), createHttpRequest(JsonEncode(req), options.headers, abortSignal)).then( + async res => { + await sseResponse(res, options, _fetch) + }, + error => { + options.onError(error, _fetch) + } + ) + + const resp = _fetch() + return { + abort: abortController.abort.bind(abortController), + closed: resp + } + } + syncBalance = (req: SyncBalanceRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('SyncBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'SyncBalanceResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - resumeAllWebhookListeners = ( - args: ResumeAllWebhookListenersArgs, + toggleWebhookListener = ( + req: ToggleWebhookListenerRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('ResumeAllWebhookListeners'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - status: _data.status, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('ToggleWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'ToggleWebhookListenerResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getOrderbookOrders = ( - args: GetOrderbookOrdersArgs, + updateWebhookListener = ( + req: UpdateWebhookListenerRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetOrderbookOrders'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - orders: >_data.orders, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('UpdateWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'UpdateWebhookListenerResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getTopOrders = (args: GetTopOrdersArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTopOrders'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - orders: >_data.orders, - } + version = (headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('Version'), createHttpRequest('{}', headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'VersionResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } } @@ -1611,9 +1958,9 @@ const sseResponse = async (res: Response, options: WebrpcStreamOptions, ret onError( WebrpcBadResponseError.new({ status: res.status, - cause: 'Invalid response, missing body', + cause: 'Invalid response, missing body' }), - retryFetch, + retryFetch ) return } @@ -1643,27 +1990,22 @@ const sseResponse = async (res: Response, options: WebrpcStreamOptions, ret lastReadTime = Date.now() buffer += decoder.decode(value, { stream: true }) } catch (error) { - let message = '' - if (error instanceof Error) { - message = error.message - } - if (error instanceof DOMException && error.name === 'AbortError') { onError( - WebrpcRequestFailedError.new({ + WebrpcClientAbortedError.new({ message: 'AbortError', - cause: `AbortError: ${message}`, + cause: `AbortError: ${error instanceof Error ? error.message : String(error)}` }), () => { throw new Error('Abort signal cannot be used to reconnect') - }, + } ) } else { onError( WebrpcStreamLostError.new({ - cause: `reader.read(): ${message}`, + cause: `reader.read(): ${error instanceof Error ? error.message : String(error)}` }), - retryFetch, + retryFetch ) } return @@ -1671,12 +2013,13 @@ const sseResponse = async (res: Response, options: WebrpcStreamOptions, ret let lines = buffer.split('\n') for (let i = 0; i < lines.length - 1; i++) { - if (lines[i]!.length == 0) { + const line = lines[i] + if (line?.length === 0) { continue } let data: any try { - data = JSON.parse(lines[i]!) + data = JSON.parse(line) if (data.hasOwnProperty('webrpcError')) { const error = data.webrpcError const code: number = typeof error.code === 'number' ? error.code : 0 @@ -1690,17 +2033,17 @@ const sseResponse = async (res: Response, options: WebrpcStreamOptions, ret onError( WebrpcBadResponseError.new({ status: res.status, - // @ts-ignore - cause: `JSON.parse(): ${error.message}`, + cause: `JSON.parse(): ${error instanceof Error ? error.message : String(error)}` }), - retryFetch, + retryFetch ) } onMessage(data) } if (!done) { - buffer = lines[lines.length - 1]! + const lastLine = lines[lines.length - 1] + buffer = lastLine || '' continue } @@ -1709,31 +2052,24 @@ const sseResponse = async (res: Response, options: WebrpcStreamOptions, ret } } -const createHTTPRequest = (body: object = {}, headers: object = {}, signal: AbortSignal | null = null): object => { - const reqHeaders: { [key: string]: string } = { ...headers, 'Content-Type': 'application/json' } - reqHeaders[WebrpcHeader] = WebrpcHeaderValue - - return { - method: 'POST', - headers: reqHeaders, - body: JSON.stringify(body || {}), - signal, +const createHttpRequest = (body: string = '{}', headers: object = {}, signal: AbortSignal | null = null): object => { + const reqHeaders: { [key: string]: string } = { + ...headers, + 'Content-Type': 'application/json', + [WebrpcHeader]: WebrpcHeaderValue } + return { method: 'POST', headers: reqHeaders, body, signal } } const buildResponse = (res: Response): Promise => { - return res.text().then((text) => { + return res.text().then(text => { let data try { data = JSON.parse(text) } catch (error) { - let message = '' - if (error instanceof Error) { - message = error.message - } throw WebrpcBadResponseError.new({ status: res.status, - cause: `JSON.parse(): ${message}: response text: ${text}`, + cause: `JSON.parse(): ${error instanceof Error ? error.message : String(error)}: response text: ${text}` }) } if (!res.ok) { @@ -1744,518 +2080,511 @@ const buildResponse = (res: Response): Promise => { }) } +export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise + +export interface WebrpcStreamOptions extends WebrpcOptions { + onMessage: (message: T) => void + onError: (error: WebrpcError, reconnect: () => void) => void + onOpen?: () => void + onClose?: () => void +} + +export interface WebrpcOptions { + headers?: HeadersInit + signal?: AbortSignal +} + +export interface WebrpcStreamController { + abort: (reason?: any) => void + closed: Promise +} + +export const JsonEncode = (obj: T): string => { + return JSON.stringify(obj) +} + +export const JsonDecode = (data: string | any, _typ: string = ''): T => { + let parsed: any = data + if (typeof data === 'string') { + try { + parsed = JSON.parse(data) + } catch (err) { + throw WebrpcBadResponseError.new({ cause: `JsonDecode: JSON.parse failed: ${(err as Error).message}` }) + } + } + return parsed as T +} + // // Errors // +type WebrpcErrorParams = { name?: string; code?: number; message?: string; status?: number; cause?: string } + export class WebrpcError extends Error { - name: string code: number - message: string status: number - cause?: string - - /** @deprecated Use message instead of msg. Deprecated in webrpc v0.11.0. */ - msg: string - - constructor(name: string, code: number, message: string, status: number, cause?: string) { - super(message) - this.name = name || 'WebrpcError' - this.code = typeof code === 'number' ? code : 0 - this.message = message || `endpoint error ${this.code}` - this.msg = this.message - this.status = typeof status === 'number' ? status : 0 - this.cause = cause + + constructor(error: WebrpcErrorParams = {}) { + super(error.message) + this.name = error.name || 'WebrpcEndpointError' + this.code = typeof error.code === 'number' ? error.code : 0 + this.message = error.message || `endpoint error` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcError.prototype) } static new(payload: any): WebrpcError { - return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause) + return new this({ message: payload.message, code: payload.code, status: payload.status, cause: payload.cause }) } } -// Webrpc errors - export class WebrpcEndpointError extends WebrpcError { - constructor( - name: string = 'WebrpcEndpoint', - code: number = 0, - message: string = 'endpoint error', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcEndpoint' + this.code = typeof error.code === 'number' ? error.code : 0 + this.message = error.message || `endpoint error` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcEndpointError.prototype) } } export class WebrpcRequestFailedError extends WebrpcError { - constructor( - name: string = 'WebrpcRequestFailed', - code: number = -1, - message: string = 'request failed', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcRequestFailed' + this.code = typeof error.code === 'number' ? error.code : -1 + this.message = error.message || `request failed` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcRequestFailedError.prototype) } } export class WebrpcBadRouteError extends WebrpcError { - constructor( - name: string = 'WebrpcBadRoute', - code: number = -2, - message: string = 'bad route', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadRoute' + this.code = typeof error.code === 'number' ? error.code : -2 + this.message = error.message || `bad route` + this.status = typeof error.status === 'number' ? error.status : 404 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadRouteError.prototype) } } export class WebrpcBadMethodError extends WebrpcError { - constructor( - name: string = 'WebrpcBadMethod', - code: number = -3, - message: string = 'bad method', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadMethod' + this.code = typeof error.code === 'number' ? error.code : -3 + this.message = error.message || `bad method` + this.status = typeof error.status === 'number' ? error.status : 405 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadMethodError.prototype) } } export class WebrpcBadRequestError extends WebrpcError { - constructor( - name: string = 'WebrpcBadRequest', - code: number = -4, - message: string = 'bad request', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadRequest' + this.code = typeof error.code === 'number' ? error.code : -4 + this.message = error.message || `bad request` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadRequestError.prototype) } } export class WebrpcBadResponseError extends WebrpcError { - constructor( - name: string = 'WebrpcBadResponse', - code: number = -5, - message: string = 'bad response', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadResponse' + this.code = typeof error.code === 'number' ? error.code : -5 + this.message = error.message || `bad response` + this.status = typeof error.status === 'number' ? error.status : 500 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadResponseError.prototype) } } export class WebrpcServerPanicError extends WebrpcError { - constructor( - name: string = 'WebrpcServerPanic', - code: number = -6, - message: string = 'server panic', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcServerPanic' + this.code = typeof error.code === 'number' ? error.code : -6 + this.message = error.message || `server panic` + this.status = typeof error.status === 'number' ? error.status : 500 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcServerPanicError.prototype) } } export class WebrpcInternalErrorError extends WebrpcError { - constructor( - name: string = 'WebrpcInternalError', - code: number = -7, - message: string = 'internal error', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcInternalError' + this.code = typeof error.code === 'number' ? error.code : -7 + this.message = error.message || `internal error` + this.status = typeof error.status === 'number' ? error.status : 500 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcInternalErrorError.prototype) } } -export class WebrpcClientDisconnectedError extends WebrpcError { - constructor( - name: string = 'WebrpcClientDisconnected', - code: number = -8, - message: string = 'client disconnected', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, WebrpcClientDisconnectedError.prototype) +export class WebrpcClientAbortedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcClientAborted' + this.code = typeof error.code === 'number' ? error.code : -8 + this.message = error.message || `request aborted by client` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, WebrpcClientAbortedError.prototype) } } export class WebrpcStreamLostError extends WebrpcError { - constructor( - name: string = 'WebrpcStreamLost', - code: number = -9, - message: string = 'stream lost', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcStreamLost' + this.code = typeof error.code === 'number' ? error.code : -9 + this.message = error.message || `stream lost` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcStreamLostError.prototype) } } export class WebrpcStreamFinishedError extends WebrpcError { - constructor( - name: string = 'WebrpcStreamFinished', - code: number = -10, - message: string = 'stream finished', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcStreamFinished' + this.code = typeof error.code === 'number' ? error.code : -10 + this.message = error.message || `stream finished` + this.status = typeof error.status === 'number' ? error.status : 200 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcStreamFinishedError.prototype) } } +// // Schema errors +// -export class UnauthorizedError extends WebrpcError { - constructor( - name: string = 'Unauthorized', - code: number = 1000, - message: string = 'Unauthorized access', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, UnauthorizedError.prototype) +export class AbortedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Aborted' + this.code = typeof error.code === 'number' ? error.code : 1005 + this.message = error.message || `Request aborted` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, AbortedError.prototype) } } -export class PermissionDeniedError extends WebrpcError { - constructor( - name: string = 'PermissionDenied', - code: number = 1001, - message: string = 'Permission denied', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, PermissionDeniedError.prototype) +export class AccessKeyMismatchError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'AccessKeyMismatch' + this.code = typeof error.code === 'number' ? error.code : 1102 + this.message = error.message || `Access key mismatch` + this.status = typeof error.status === 'number' ? error.status : 409 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, AccessKeyMismatchError.prototype) } } -export class SessionExpiredError extends WebrpcError { - constructor( - name: string = 'SessionExpired', - code: number = 1002, - message: string = 'Session expired', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, SessionExpiredError.prototype) +export class AccessKeyNotFoundError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'AccessKeyNotFound' + this.code = typeof error.code === 'number' ? error.code : 1101 + this.message = error.message || `Access key not found` + this.status = typeof error.status === 'number' ? error.status : 401 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, AccessKeyNotFoundError.prototype) } } -export class MethodNotFoundError extends WebrpcError { - constructor( - name: string = 'MethodNotFound', - code: number = 1003, - message: string = 'Method not found', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, MethodNotFoundError.prototype) +export class AtLeastOneKeyError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'AtLeastOneKey' + this.code = typeof error.code === 'number' ? error.code : 1302 + this.message = error.message || `You need at least one Access Key` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, AtLeastOneKeyError.prototype) } } -export class RequestConflictError extends WebrpcError { - constructor( - name: string = 'RequestConflict', - code: number = 1004, - message: string = 'Conflict with target resource', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, RequestConflictError.prototype) +export class GeoblockedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Geoblocked' + this.code = typeof error.code === 'number' ? error.code : 1006 + this.message = error.message || `Geoblocked region` + this.status = typeof error.status === 'number' ? error.status : 451 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, GeoblockedError.prototype) } } -export class AbortedError extends WebrpcError { - constructor( - name: string = 'Aborted', - code: number = 1005, - message: string = 'Request aborted', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, AbortedError.prototype) +export class InvalidArgumentError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'InvalidArgument' + this.code = typeof error.code === 'number' ? error.code : 2001 + this.message = error.message || `Invalid argument` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, InvalidArgumentError.prototype) } } -export class GeoblockedError extends WebrpcError { - constructor( - name: string = 'Geoblocked', - code: number = 1006, - message: string = 'Geoblocked region', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, GeoblockedError.prototype) +export class InvalidOriginError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'InvalidOrigin' + this.code = typeof error.code === 'number' ? error.code : 1103 + this.message = error.message || `Invalid origin for Access Key` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, InvalidOriginError.prototype) } } -export class RateLimitedError extends WebrpcError { - constructor( - name: string = 'RateLimited', - code: number = 1007, - message: string = 'Rate-limited. Please slow down.', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, RateLimitedError.prototype) +export class InvalidServiceError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'InvalidService' + this.code = typeof error.code === 'number' ? error.code : 1104 + this.message = error.message || `Service not enabled for Access key` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, InvalidServiceError.prototype) } } -export class ProjectNotFoundError extends WebrpcError { - constructor( - name: string = 'ProjectNotFound', - code: number = 1100, - message: string = 'Project not found', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, ProjectNotFoundError.prototype) +export class MaxAccessKeysError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'MaxAccessKeys' + this.code = typeof error.code === 'number' ? error.code : 1301 + this.message = error.message || `Access keys limit reached` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, MaxAccessKeysError.prototype) } } -export class AccessKeyNotFoundError extends WebrpcError { - constructor( - name: string = 'AccessKeyNotFound', - code: number = 1101, - message: string = 'Access key not found', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, AccessKeyNotFoundError.prototype) +export class MetadataCallFailedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'MetadataCallFailed' + this.code = typeof error.code === 'number' ? error.code : 3003 + this.message = error.message || `Metadata service call failed` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, MetadataCallFailedError.prototype) } } -export class AccessKeyMismatchError extends WebrpcError { - constructor( - name: string = 'AccessKeyMismatch', - code: number = 1102, - message: string = 'Access key mismatch', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, AccessKeyMismatchError.prototype) +export class MethodNotFoundError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'MethodNotFound' + this.code = typeof error.code === 'number' ? error.code : 1003 + this.message = error.message || `Method not found` + this.status = typeof error.status === 'number' ? error.status : 404 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, MethodNotFoundError.prototype) } } -export class InvalidOriginError extends WebrpcError { - constructor( - name: string = 'InvalidOrigin', - code: number = 1103, - message: string = 'Invalid origin for Access Key', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, InvalidOriginError.prototype) +export class NoDefaultKeyError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'NoDefaultKey' + this.code = typeof error.code === 'number' ? error.code : 1300 + this.message = error.message || `No default access key found` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, NoDefaultKeyError.prototype) } } -export class InvalidServiceError extends WebrpcError { - constructor( - name: string = 'InvalidService', - code: number = 1104, - message: string = 'Service not enabled for Access key', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, InvalidServiceError.prototype) +export class NotFoundError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'NotFound' + this.code = typeof error.code === 'number' ? error.code : 3000 + this.message = error.message || `Resource not found` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, NotFoundError.prototype) } } -export class UnauthorizedUserError extends WebrpcError { - constructor( - name: string = 'UnauthorizedUser', - code: number = 1105, - message: string = 'Unauthorized user', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, UnauthorizedUserError.prototype) +export class PermissionDeniedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'PermissionDenied' + this.code = typeof error.code === 'number' ? error.code : 1001 + this.message = error.message || `Permission denied` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, PermissionDeniedError.prototype) } } -export class QuotaExceededError extends WebrpcError { - constructor( - name: string = 'QuotaExceeded', - code: number = 1200, - message: string = 'Quota exceeded', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, QuotaExceededError.prototype) +export class ProjectNotFoundError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'ProjectNotFound' + this.code = typeof error.code === 'number' ? error.code : 1100 + this.message = error.message || `Project not found` + this.status = typeof error.status === 'number' ? error.status : 401 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, ProjectNotFoundError.prototype) } } -export class RateLimitError extends WebrpcError { - constructor( - name: string = 'RateLimit', - code: number = 1201, - message: string = 'Rate limit exceeded', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, RateLimitError.prototype) +export class QueryFailedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'QueryFailed' + this.code = typeof error.code === 'number' ? error.code : 2003 + this.message = error.message || `Query failed` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, QueryFailedError.prototype) } } -export class NoDefaultKeyError extends WebrpcError { - constructor( - name: string = 'NoDefaultKey', - code: number = 1300, - message: string = 'No default access key found', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, NoDefaultKeyError.prototype) +export class QuotaExceededError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'QuotaExceeded' + this.code = typeof error.code === 'number' ? error.code : 1200 + this.message = error.message || `Quota exceeded` + this.status = typeof error.status === 'number' ? error.status : 429 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, QuotaExceededError.prototype) } } -export class MaxAccessKeysError extends WebrpcError { - constructor( - name: string = 'MaxAccessKeys', - code: number = 1301, - message: string = 'Access keys limit reached', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, MaxAccessKeysError.prototype) +export class RateLimitError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'RateLimit' + this.code = typeof error.code === 'number' ? error.code : 1201 + this.message = error.message || `Rate limit exceeded` + this.status = typeof error.status === 'number' ? error.status : 429 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, RateLimitError.prototype) } } -export class AtLeastOneKeyError extends WebrpcError { - constructor( - name: string = 'AtLeastOneKey', - code: number = 1302, - message: string = 'You need at least one Access Key', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, AtLeastOneKeyError.prototype) +export class RateLimitedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'RateLimited' + this.code = typeof error.code === 'number' ? error.code : 1007 + this.message = error.message || `Rate-limited. Please slow down.` + this.status = typeof error.status === 'number' ? error.status : 429 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, RateLimitedError.prototype) } } -export class TimeoutError extends WebrpcError { - constructor( - name: string = 'Timeout', - code: number = 1900, - message: string = 'Request timed out', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, TimeoutError.prototype) +export class RequestConflictError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'RequestConflict' + this.code = typeof error.code === 'number' ? error.code : 1004 + this.message = error.message || `Conflict with target resource` + this.status = typeof error.status === 'number' ? error.status : 409 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, RequestConflictError.prototype) } } -export class InvalidArgumentError extends WebrpcError { - constructor( - name: string = 'InvalidArgument', - code: number = 2001, - message: string = 'Invalid argument', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, InvalidArgumentError.prototype) +export class ResourceExhaustedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'ResourceExhausted' + this.code = typeof error.code === 'number' ? error.code : 2004 + this.message = error.message || `Resource exhausted` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, ResourceExhaustedError.prototype) } } -export class UnavailableError extends WebrpcError { - constructor( - name: string = 'Unavailable', - code: number = 2002, - message: string = 'Unavailable resource', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, UnavailableError.prototype) +export class SessionExpiredError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'SessionExpired' + this.code = typeof error.code === 'number' ? error.code : 1002 + this.message = error.message || `Session expired` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, SessionExpiredError.prototype) } } -export class QueryFailedError extends WebrpcError { - constructor( - name: string = 'QueryFailed', - code: number = 2003, - message: string = 'Query failed', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, QueryFailedError.prototype) +export class TimeoutError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Timeout' + this.code = typeof error.code === 'number' ? error.code : 1900 + this.message = error.message || `Request timed out` + this.status = typeof error.status === 'number' ? error.status : 408 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, TimeoutError.prototype) } } -export class ResourceExhaustedError extends WebrpcError { - constructor( - name: string = 'ResourceExhausted', - code: number = 2004, - message: string = 'Resource exhausted', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, ResourceExhaustedError.prototype) +export class UnauthorizedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Unauthorized' + this.code = typeof error.code === 'number' ? error.code : 1000 + this.message = error.message || `Unauthorized access` + this.status = typeof error.status === 'number' ? error.status : 401 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, UnauthorizedError.prototype) } } -export class NotFoundError extends WebrpcError { - constructor( - name: string = 'NotFound', - code: number = 3000, - message: string = 'Resource not found', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, NotFoundError.prototype) +export class UnauthorizedUserError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'UnauthorizedUser' + this.code = typeof error.code === 'number' ? error.code : 1105 + this.message = error.message || `Unauthorized user` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, UnauthorizedUserError.prototype) } } -export class MetadataCallFailedError extends WebrpcError { - constructor( - name: string = 'MetadataCallFailed', - code: number = 3003, - message: string = 'Metadata service call failed', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, MetadataCallFailedError.prototype) +export class UnavailableError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Unavailable' + this.code = typeof error.code === 'number' ? error.code : 2002 + this.message = error.message || `Unavailable resource` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, UnavailableError.prototype) } } @@ -2268,38 +2597,78 @@ export enum errors { WebrpcBadResponse = 'WebrpcBadResponse', WebrpcServerPanic = 'WebrpcServerPanic', WebrpcInternalError = 'WebrpcInternalError', - WebrpcClientDisconnected = 'WebrpcClientDisconnected', + WebrpcClientAborted = 'WebrpcClientAborted', WebrpcStreamLost = 'WebrpcStreamLost', WebrpcStreamFinished = 'WebrpcStreamFinished', - Unauthorized = 'Unauthorized', - PermissionDenied = 'PermissionDenied', - SessionExpired = 'SessionExpired', - MethodNotFound = 'MethodNotFound', - RequestConflict = 'RequestConflict', Aborted = 'Aborted', - Geoblocked = 'Geoblocked', - RateLimited = 'RateLimited', - ProjectNotFound = 'ProjectNotFound', - AccessKeyNotFound = 'AccessKeyNotFound', AccessKeyMismatch = 'AccessKeyMismatch', + AccessKeyNotFound = 'AccessKeyNotFound', + AtLeastOneKey = 'AtLeastOneKey', + Geoblocked = 'Geoblocked', + InvalidArgument = 'InvalidArgument', InvalidOrigin = 'InvalidOrigin', InvalidService = 'InvalidService', - UnauthorizedUser = 'UnauthorizedUser', - QuotaExceeded = 'QuotaExceeded', - RateLimit = 'RateLimit', - NoDefaultKey = 'NoDefaultKey', MaxAccessKeys = 'MaxAccessKeys', - AtLeastOneKey = 'AtLeastOneKey', - Timeout = 'Timeout', - InvalidArgument = 'InvalidArgument', - Unavailable = 'Unavailable', + MetadataCallFailed = 'MetadataCallFailed', + MethodNotFound = 'MethodNotFound', + NoDefaultKey = 'NoDefaultKey', + NotFound = 'NotFound', + PermissionDenied = 'PermissionDenied', + ProjectNotFound = 'ProjectNotFound', QueryFailed = 'QueryFailed', + QuotaExceeded = 'QuotaExceeded', + RateLimit = 'RateLimit', + RateLimited = 'RateLimited', + RequestConflict = 'RequestConflict', ResourceExhausted = 'ResourceExhausted', - NotFound = 'NotFound', - MetadataCallFailed = 'MetadataCallFailed', -} - -const webrpcErrorByCode: { [code: number]: any } = { + SessionExpired = 'SessionExpired', + Timeout = 'Timeout', + Unauthorized = 'Unauthorized', + UnauthorizedUser = 'UnauthorizedUser', + Unavailable = 'Unavailable' +} + +export enum WebrpcErrorCodes { + WebrpcEndpoint = 0, + WebrpcRequestFailed = -1, + WebrpcBadRoute = -2, + WebrpcBadMethod = -3, + WebrpcBadRequest = -4, + WebrpcBadResponse = -5, + WebrpcServerPanic = -6, + WebrpcInternalError = -7, + WebrpcClientAborted = -8, + WebrpcStreamLost = -9, + WebrpcStreamFinished = -10, + Aborted = 1005, + AccessKeyMismatch = 1102, + AccessKeyNotFound = 1101, + AtLeastOneKey = 1302, + Geoblocked = 1006, + InvalidArgument = 2001, + InvalidOrigin = 1103, + InvalidService = 1104, + MaxAccessKeys = 1301, + MetadataCallFailed = 3003, + MethodNotFound = 1003, + NoDefaultKey = 1300, + NotFound = 3000, + PermissionDenied = 1001, + ProjectNotFound = 1100, + QueryFailed = 2003, + QuotaExceeded = 1200, + RateLimit = 1201, + RateLimited = 1007, + RequestConflict = 1004, + ResourceExhausted = 2004, + SessionExpired = 1002, + Timeout = 1900, + Unauthorized = 1000, + UnauthorizedUser = 1105, + Unavailable = 2002 +} + +export const webrpcErrorByCode: { [code: number]: any } = { [0]: WebrpcEndpointError, [-1]: WebrpcRequestFailedError, [-2]: WebrpcBadRouteError, @@ -2308,46 +2677,89 @@ const webrpcErrorByCode: { [code: number]: any } = { [-5]: WebrpcBadResponseError, [-6]: WebrpcServerPanicError, [-7]: WebrpcInternalErrorError, - [-8]: WebrpcClientDisconnectedError, + [-8]: WebrpcClientAbortedError, [-9]: WebrpcStreamLostError, [-10]: WebrpcStreamFinishedError, - [1000]: UnauthorizedError, - [1001]: PermissionDeniedError, - [1002]: SessionExpiredError, - [1003]: MethodNotFoundError, - [1004]: RequestConflictError, [1005]: AbortedError, - [1006]: GeoblockedError, - [1007]: RateLimitedError, - [1100]: ProjectNotFoundError, - [1101]: AccessKeyNotFoundError, [1102]: AccessKeyMismatchError, + [1101]: AccessKeyNotFoundError, + [1302]: AtLeastOneKeyError, + [1006]: GeoblockedError, + [2001]: InvalidArgumentError, [1103]: InvalidOriginError, [1104]: InvalidServiceError, - [1105]: UnauthorizedUserError, - [1200]: QuotaExceededError, - [1201]: RateLimitError, - [1300]: NoDefaultKeyError, [1301]: MaxAccessKeysError, - [1302]: AtLeastOneKeyError, - [1900]: TimeoutError, - [2001]: InvalidArgumentError, - [2002]: UnavailableError, + [3003]: MetadataCallFailedError, + [1003]: MethodNotFoundError, + [1300]: NoDefaultKeyError, + [3000]: NotFoundError, + [1001]: PermissionDeniedError, + [1100]: ProjectNotFoundError, [2003]: QueryFailedError, + [1200]: QuotaExceededError, + [1201]: RateLimitError, + [1007]: RateLimitedError, + [1004]: RequestConflictError, [2004]: ResourceExhaustedError, - [3000]: NotFoundError, - [3003]: MetadataCallFailedError, + [1002]: SessionExpiredError, + [1900]: TimeoutError, + [1000]: UnauthorizedError, + [1105]: UnauthorizedUserError, + [2002]: UnavailableError } -export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise +// +// Webrpc +// -export interface WebrpcStreamOptions extends WebrpcOptions { - onMessage: (message: T) => void - onError: (error: WebrpcError, reconnect: () => void) => void - onOpen?: () => void - onClose?: () => void +export const WebrpcHeader = 'Webrpc' + +export const WebrpcHeaderValue = 'webrpc@v0.31.2;gen-typescript@v0.23.1;sequence-indexer@v0.4.0' + +type WebrpcGenVersions = { + WebrpcGenVersion: string + codeGenName: string + codeGenVersion: string + schemaName: string + schemaVersion: string } -export interface WebrpcOptions { - headers?: HeadersInit - signal?: AbortSignal + +export function VersionFromHeader(headers: Headers): WebrpcGenVersions { + const headerValue = headers.get(WebrpcHeader) + if (!headerValue) { + return { + WebrpcGenVersion: '', + codeGenName: '', + codeGenVersion: '', + schemaName: '', + schemaVersion: '' + } + } + + return parseWebrpcGenVersions(headerValue) +} + +function parseWebrpcGenVersions(header: string): WebrpcGenVersions { + const versions = header.split(';') + if (versions.length < 3) { + return { + WebrpcGenVersion: '', + codeGenName: '', + codeGenVersion: '', + schemaName: '', + schemaVersion: '' + } + } + + const [_, WebrpcGenVersion] = versions[0]!.split('@') + const [codeGenName, codeGenVersion] = versions[1]!.split('@') + const [schemaName, schemaVersion] = versions[2]!.split('@') + + return { + WebrpcGenVersion: WebrpcGenVersion ?? '', + codeGenName: codeGenName ?? '', + codeGenVersion: codeGenVersion ?? '', + schemaName: schemaName ?? '', + schemaVersion: schemaVersion ?? '' + } } diff --git a/packages/services/indexer/src/indexergw.gen.ts b/packages/services/indexer/src/indexergw.gen.ts index 92f85b2c8..729d04cdc 100644 --- a/packages/services/indexer/src/indexergw.gen.ts +++ b/packages/services/indexer/src/indexergw.gen.ts @@ -1,79 +1,161 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 5be4a3e78d9c7e0cc378c675ec01c518e83772e3 +// sequence-indexer v0.4.0 b978d153702d614d5f1b9c98ff7f2e5857cccfd6 // -- -// Code generated by webrpc-gen@v0.21.1 with typescript generator. DO NOT EDIT. +// Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. // -// webrpc-gen -schema=indexer.ridl -service=IndexerGateway -target=typescript -client -out=./clients/indexergw.gen.ts +// webrpc-gen -schema=merged.gen.json -service=IndexerGateway -target=typescript -client -out=./clients/indexergw.gen.ts -export const WebrpcHeader = 'Webrpc' - -export const WebrpcHeaderValue = 'webrpc@v0.21.1;gen-typescript@v0.15.1;sequence-indexer@v0.4.0' - -// WebRPC description and code-gen version -export const WebRPCVersion = 'v1' +// Webrpc description and code-gen version +export const WebrpcVersion = 'v1' // Schema version of your RIDL schema -export const WebRPCSchemaVersion = 'v0.4.0' +export const WebrpcSchemaVersion = 'v0.4.0' // Schema hash generated from your RIDL schema -export const WebRPCSchemaHash = '5be4a3e78d9c7e0cc378c675ec01c518e83772e3' +export const WebrpcSchemaHash = 'b978d153702d614d5f1b9c98ff7f2e5857cccfd6' -type WebrpcGenVersions = { - webrpcGenVersion: string - codeGenName: string - codeGenVersion: string - schemaName: string - schemaVersion: string -} +// +// Client interface +// -export function VersionFromHeader(headers: Headers): WebrpcGenVersions { - const headerValue = headers.get(WebrpcHeader) - if (!headerValue) { - return { - webrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '', - } - } +export interface IndexerGatewayClient { + /** + * GetTokenBalances returns a balance summary/details for an specific account + * on all indexer nodes. By default if accountAddress is left empty, it will + * use the account from the jwt session. + */ + getBalanceUpdates(req: GetBalanceUpdatesRequest, headers?: object, signal?: AbortSignal): Promise + + /** + * GetChains returns a list of chains with their ID and name + */ + getChains(req: GetChainsRequest, headers?: object, signal?: AbortSignal): Promise + + /** + * GetNativeTokenBalance queries indexer nodes for the latest native token + * account balance. + */ + getNativeTokenBalance( + req: GetNativeTokenBalanceRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * GetTokenBalances returns a balance summary/details for a specific account + * on all indexer nodes. By default if accountAddress is left empty, it will + * use the account from the jwt session. + * + * @deprecated Use GetTokenBalancesSummary or GetTokenBalancesDetails instead. + */ + getTokenBalances(req: GetTokenBalancesRequest, headers?: object, signal?: AbortSignal): Promise + + /** + * GetTokenBalancesByContract returns a balances for specific accounts and + * contracts on all indexer nodes. The collection ERC721 & ERC1155 tokens are + * represented as individual balances. + */ + getTokenBalancesByContract( + req: GetTokenBalancesByContractRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * GetTokenBalancesDetails returns a detailed balance summary for the given + * accounts on all indexer nodes. The collection ERC721 & ERC1155 tokens are + * represented as individual balances. + */ + getTokenBalancesDetails( + req: GetTokenBalancesDetailsRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * GetTokenBalancesSummary returns a summary of token balances for the given + * accounts on all indexer nodes. The collection ERC721 & ERC1155 tokens are + * represented as a single aggregated balance. + */ + getTokenBalancesSummary( + req: GetTokenBalancesSummaryRequest, + headers?: object, + signal?: AbortSignal + ): Promise - return parseWebrpcGenVersions(headerValue) -} + getTokenPrice(req: GetTokenPriceRequest, headers?: object, signal?: AbortSignal): Promise -function parseWebrpcGenVersions(header: string): WebrpcGenVersions { - const versions = header.split(';') - if (versions.length < 3) { - return { - webrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '', - } - } + getTokenPrices(req: GetTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise - const [_, webrpcGenVersion] = versions[0]!.split('@') - const [codeGenName, codeGenVersion] = versions[1]!.split('@') - const [schemaName, schemaVersion] = versions[2]!.split('@') + /** + * GetTransactionHistory returns the history of mined transactions for the + * given account on all indexer nodes, which includes a list of token transfer + * (sent/received) , and sent transactions from a Sequence wallet. + */ + getTransactionHistory( + req: GetTransactionHistoryRequest, + headers?: object, + signal?: AbortSignal + ): Promise - return { - webrpcGenVersion: webrpcGenVersion!, - codeGenName: codeGenName!, - codeGenVersion: codeGenVersion!, - schemaName: schemaName!, - schemaVersion: schemaVersion!, - } + /** + * Ping the indexer + */ + ping(headers?: object, signal?: AbortSignal): Promise + + /** + * Get the current runtime health status of the indexer gatewya + */ + runtimeStatus(headers?: object, signal?: AbortSignal): Promise + + /** + * Get the current version of the indexer + */ + version(headers?: object, signal?: AbortSignal): Promise } // -// Types +// Schema types // -export enum ResourceStatus { - NOT_AVAILABLE = 'NOT_AVAILABLE', - REFRESHING = 'REFRESHING', - AVAILABLE = 'AVAILABLE', +export interface Asset { + id: number + collectionId: number + tokenId?: string + url?: string + metadataField: string + name?: string + filesize?: number + mimeType?: string + width?: number + height?: number + updatedAt?: string +} + +export interface BloomStats { + hitRatio: string + falsePositivesPercent: string + hitCount: number + missCount: number + falsePositives: number +} + +export interface BloomStatus { + enabled: boolean + initialized: boolean + bloomInitElapsedTime: string + stats: BloomStats +} + +export interface Bond { + pebble: PebbleMetrics + estimatedDiskUsagePerTable: any + estimatedDiskUsageTotal: string +} + +export interface ChainInfo { + chainId: number + chainName: string } export interface ContractInfo { @@ -93,56 +175,29 @@ export interface ContractInfo { status: ResourceStatus } -export interface ContractInfoExtensions { - link: string - description: string - categories: Array - ogImage: string - ogName: string - originChainId: number - originAddress: string - blacklist: boolean - verified: boolean - verifiedBy: string - featured: boolean - featureIndex: number +export interface ContractInfoExtensionBridgeInfo { + tokenAddress: string } -export interface TokenMetadata { - contractAddress?: string - tokenId: string - source: string - name: string - description?: string - image?: string - video?: string - audio?: string - properties?: { [key: string]: any } - attributes: Array<{ [key: string]: any }> - image_data?: string - external_url?: string - background_color?: string - animation_url?: string - decimals?: number - updatedAt?: string - assets?: Array - status: ResourceStatus - queuedAt?: string - lastFetched?: string +export interface ContractInfoExtensionIndexingInfo { + useOnChainBalance: boolean } -export interface Asset { - id: number - collectionId: number - tokenId?: string - url?: string - metadataField: string - name?: string - filesize?: number - mimeType?: string - width?: number - height?: number - updatedAt?: string +export interface ContractInfoExtensions { + link?: string + description?: string + categories?: Array + bridgeInfo?: { [key: string]: ContractInfoExtensionBridgeInfo } + indexingInfo?: ContractInfoExtensionIndexingInfo + ogImage?: string + ogName?: string + originChainId?: number + originAddress?: string + blacklist?: boolean + verified?: boolean + verifiedBy?: string + featured?: boolean + featureIndex?: number } export enum ContractType { @@ -156,72 +211,73 @@ export enum ContractType { ERC721_BRIDGE = 'ERC721_BRIDGE', ERC1155_BRIDGE = 'ERC1155_BRIDGE', SEQ_MARKETPLACE = 'SEQ_MARKETPLACE', + ERC6909 = 'ERC6909' } -export enum EventLogType { - UNKNOWN = 'UNKNOWN', - BLOCK_ADDED = 'BLOCK_ADDED', - BLOCK_REMOVED = 'BLOCK_REMOVED', -} - -export enum EventLogDataType { - EVENT = 'EVENT', - TOKEN_TRANSFER = 'TOKEN_TRANSFER', - NATIVE_TOKEN_TRANSFER = 'NATIVE_TOKEN_TRANSFER', - SEQUENCE_TXN = 'SEQUENCE_TXN', -} - -export enum OrderStatus { - OPEN = 'OPEN', - CLOSED = 'CLOSED', - CANCELLED = 'CANCELLED', +export enum ContractVerificationStatus { + VERIFIED = 'VERIFIED', + UNVERIFIED = 'UNVERIFIED', + ALL = 'ALL' } -export enum TxnTransferType { - UNKNOWN = 'UNKNOWN', - SEND = 'SEND', - RECEIVE = 'RECEIVE', +export interface DiskUsage { + humanReadable: string + used: number + size: number + percent: number + dirs: { [key: string]: string } } -export enum TransactionStatus { - FAILED = 'FAILED', - SUCCESSFUL = 'SUCCESSFUL', +export interface EtherBalance { + accountAddress: string + balanceWei: string } -export enum TransactionType { - LegacyTxnType = 'LegacyTxnType', - AccessListTxnType = 'AccessListTxnType', - DynamicFeeTxnType = 'DynamicFeeTxnType', +export interface EventDecoded { + topicHash: string + eventSig: string + types: Array + names: Array + values: Array } -export enum SortOrder { - DESC = 'DESC', - ASC = 'ASC', +export interface EventFilter { + events?: Array + contractAddresses?: Array + accounts?: Array + tokenIDs?: Array } -export enum ContractVerificationStatus { - VERIFIED = 'VERIFIED', - UNVERIFIED = 'UNVERIFIED', - ALL = 'ALL', +export interface EventLog { + id: number + uid: string + type: EventLogType + blockNumber: number + blockHash: string + parentBlockHash: string + contractAddress: string + contractType: ContractType + txnHash: string + txnIndex: number + txnLogIndex: number + logDataType: EventLogDataType + ts: string + txnInfo?: TxnInfo + rawLog?: { [key: string]: any } + event?: EventDecoded } -export interface Version { - webrpcVersion: string - schemaVersion: string - schemaHash: string - appVersion: string +export enum EventLogDataType { + EVENT = 'EVENT', + TOKEN_TRANSFER = 'TOKEN_TRANSFER', + NATIVE_TOKEN_TRANSFER = 'NATIVE_TOKEN_TRANSFER', + SEQUENCE_TXN = 'SEQUENCE_TXN' } -export interface RuntimeStatus { - healthOK: boolean - indexerEnabled: boolean - startTime: string - uptime: number - ver: string - branch: string - commitHash: string - chainID: number - checks: RuntimeChecks +export enum EventLogType { + UNKNOWN = 'UNKNOWN', + BLOCK_ADDED = 'BLOCK_ADDED', + BLOCK_REMOVED = 'BLOCK_REMOVED' } export interface GatewayBackendResponseTime { @@ -235,6 +291,30 @@ export interface GatewayBackendRuntimeStatus { responseTime: GatewayBackendResponseTime } +export interface GatewayEtherBalance { + chainId: number + errorReason?: string + result: EtherBalance +} + +export interface GatewayNativeTokenBalance { + chainId: number + errorReason?: string + result: NativeTokenBalance +} + +export interface GatewayNativeTokenBalances { + chainId: number + errorReason?: string + results: Array +} + +export interface GatewayPrice { + chainID: number + errorReason?: string + results: Array +} + export interface GatewayRuntimeStatus { healthOK: boolean startTime: string @@ -245,113 +325,173 @@ export interface GatewayRuntimeStatus { backends: Array } -export interface WALWriterRuntimeStatus { - healthOK: boolean - startTime: string - uptime: number - ver: string - branch: string - commitHash: string +export interface GatewayTokenBalance { + chainId: number + errorReason?: string + results: Array +} + +export interface GatewayTokenPriceQuery { chainID: number - percentWALWritten: number + queries: Array } -export interface RuntimeChecks { - running: boolean - runnables: any - cgoEnabled: boolean - quotaControlEnabled: boolean - syncMode: string - percentIndexed: number +export interface GatewayTransaction { + chainId: number + errorReason?: string + results: Array +} + +export interface IndexState { + chainId: string lastBlockNum: number - lastBlockNumWithState: number - bloomStatus: BloomStatus - bond: Bond - diskUsage: DiskUsage + lastBlockHash: string } -export interface DiskUsage { - humanReadable: string - used: number - size: number - percent: number - dirs: { [key: string]: string } +export interface IndexedBlock { + blockNumber: number + blockShortHash: string } -export interface Bond { - pebble: PebbleMetrics - estimatedDiskUsagePerTable: any - estimatedDiskUsageTotal: string +export interface IndexerMetrics { + blocksPerSecond: number + eventsPerSecond: number } -export interface PebbleMetrics { - compactionCount: number - compactionEstimatedDebt: number - compactionInProgressBytes: number - compactionNumInProgress: number - compactionMarkedFiles: number +export interface MarketplaceOrder { + orderId: string + tokenContract: string + tokenId: string + isListing: boolean + quantity: string + quantityRemaining: string + currencyAddress: string + pricePerToken: string + expiry: string + orderStatus: OrderStatus + createdBy: string + blockNumber: number + orderbookContractAddress: string + createdAt: number } -export interface BloomStatus { - enabled: boolean - initialized: boolean - bloomInitElapsedTime: string +export interface MarketplaceOrderFilter { + isListing?: boolean + userAddresses?: Array + currencyAddresses: Array + orderIds: Array + tokenIds: Array + excludeUserAddresses?: Array + blockNumberGt: number + createdAtAfter: number + orderStatuses: Array + returnExpired: boolean } -export interface EtherBalance { - accountAddress: string - balanceWei: string +export interface MarketplaceTopOrdersFilter { + currencyAddresses: Array + tokenIds: Array + isListing: boolean + priceSort: SortOrder + excludeUser?: string +} + +export interface MetadataOptions { + verifiedOnly?: boolean + unverifiedOnly?: boolean + includeContracts?: Array } export interface NativeTokenBalance { accountAddress: string chainId: number + name: string + symbol: string balance: string - error: string + balanceUSD: string + priceUSD: string + priceUpdatedAt?: string + errorReason?: string } -export interface IndexState { - chainId: string - lastBlockNum: number - lastBlockHash: string +export enum NetworkType { + MAINNETS = 'MAINNETS', + TESTNETS = 'TESTNETS', + ALL = 'ALL' } -export interface IndexedBlock { - blockNumber: number - blockShortHash: string +export enum OrderStatus { + OPEN = 'OPEN', + CLOSED = 'CLOSED', + CANCELLED = 'CANCELLED' } -export interface TxnInfo { - from: string - to: string - value: string +export interface Page { + page?: number + column?: string + before?: any + after?: any + sort?: Array + pageSize?: number + more?: boolean } -export interface EventLog { - id: number - uid: string - type: EventLogType - blockNumber: number - blockHash: string - parentBlockHash: string +export interface PebbleMetrics { + compactionCount: number + compactionEstimatedDebt: number + compactionInProgressBytes: number + compactionNumInProgress: number + compactionMarkedFiles: number +} + +export interface Price { contractAddress: string - contractType: ContractType - txnHash: string - txnIndex: number - txnLogIndex: number - logDataType: EventLogDataType - ts: string - txnInfo?: TxnInfo - rawLog?: { [key: string]: any } - event?: EventDecoded + tokenID?: string + priceUSD: string + updatedAt?: string } -export interface EventDecoded { - topicHash: string - eventSig: string - types: Array - names: Array - values: Array +export enum ResourceStatus { + NOT_AVAILABLE = 'NOT_AVAILABLE', + REFRESHING = 'REFRESHING', + AVAILABLE = 'AVAILABLE' +} + +export interface RuntimeChecks { + running: boolean + runnables: any + cgoEnabled: boolean + quotaControlEnabled: boolean + syncMode: string + percentIndexed: number + lastBlockNum: number + lastBlockNumWithState: number + bloomStatus: BloomStatus + bond: Bond + diskUsage: DiskUsage + metrics: IndexerMetrics +} + +export interface RuntimeStatus { + healthOK: boolean + indexerEnabled: boolean + startTime: string + uptime: number + ver: string + branch: string + commitHash: string + chainID: number + checks: RuntimeChecks +} + +export interface SortBy { + column: string + order: SortOrder +} + +export enum SortOrder { + DESC = 'DESC', + ASC = 'ASC' } export interface TokenBalance { @@ -360,6 +500,9 @@ export interface TokenBalance { accountAddress: string tokenID?: string balance: string + balanceUSD: string + priceUSD: string + priceUpdatedAt?: string blockHash: string blockNumber: number chainId: number @@ -369,39 +512,32 @@ export interface TokenBalance { tokenMetadata?: TokenMetadata } -export interface OrderbookOrder { - orderId: string - tokenContract: string - tokenId: string - isListing: boolean - quantity: string - quantityRemaining: string - currencyAddress: string - pricePerToken: string - expiry: string - orderStatus: OrderStatus - createdBy: string - blockNumber: number - orderbookContractAddress: string - createdAt: number +export interface TokenBalanceFilter { + contractAddress: string + sinceBlockNumber: number } -export interface OrderbookOrderFilter { - isListing?: boolean - userAddresses?: Array - tokenIds: Array - excludeUserAddresses?: Array - afterBlockNumber: number - afterCreatedAt: number - beforeExpiry: number - userAddress?: string - excludeUserAddress?: string +export interface TokenBalancesByContractFilter { + contractAddresses: Array + accountAddresses?: Array + contractStatus?: ContractVerificationStatus + tokenIDs?: Array +} + +export interface TokenBalancesFilter { + accountAddresses: Array + contractStatus?: ContractVerificationStatus + contractTypes?: Array + contractWhitelist?: Array + contractBlacklist?: Array + omitNativeBalances: boolean + omitPrices?: boolean + tokenIDs?: Array } export interface TokenHistory { blockNumber: number blockHash: string - accountAddress: string contractAddress: string contractType: ContractType fromAddress: string @@ -409,12 +545,45 @@ export interface TokenHistory { txnHash: string txnIndex: number txnLogIndex: number - logData: string tokenIDs: string - Amounts: string + amounts: string ts: string } +export interface TokenIDRange { + start: string + end: string +} + +export interface TokenMetadata { + chainId?: number + contractAddress?: string + tokenId: string + source: string + name: string + description?: string + image?: string + video?: string + audio?: string + properties?: { [key: string]: any } + attributes: Array<{ [key: string]: any }> + image_data?: string + external_url?: string + background_color?: string + animation_url?: string + decimals?: number + updatedAt?: string + assets?: Array + status: ResourceStatus + queuedAt?: string + lastFetched?: string +} + +export interface TokenPriceQuery { + contractAddress: string + tokenID?: string +} + export interface TokenSupply { tokenID: string supply: string @@ -433,17 +602,12 @@ export interface Transaction { timestamp: string } -export interface TxnTransfer { - transferType: TxnTransferType - contractAddress: string - contractType: ContractType - from: string - to: string - tokenIds?: Array - amounts: Array - logIndex: number - contractInfo?: ContractInfo - tokenMetadata?: { [key: string]: TokenMetadata } +export interface TransactionFilter { + txnHash?: string + from?: string + to?: string + contractAddress?: string + event?: string } export interface TransactionHistoryFilter { @@ -456,14 +620,14 @@ export interface TransactionHistoryFilter { fromBlock?: number toBlock?: number tokenID?: string + omitPrices?: boolean } -export interface TransactionFilter { - txnHash?: string - from?: string - to?: string - contractAddress?: string - event?: string +export interface TransactionLog { + contractAddress: string + topics: Array + data: string + index: number } export interface TransactionReceipt { @@ -482,31 +646,60 @@ export interface TransactionReceipt { reorged: boolean } -export interface TransactionLog { +export enum TransactionStatus { + FAILED = 'FAILED', + SUCCESSFUL = 'SUCCESSFUL' +} + +export enum TransactionType { + LegacyTxnType = 'LegacyTxnType', + AccessListTxnType = 'AccessListTxnType', + DynamicFeeTxnType = 'DynamicFeeTxnType' +} + +export interface TxnInfo { + from: string + to: string + value: string +} + +export interface TxnTransfer { + transferType: TxnTransferType contractAddress: string - topics: Array - data: string - index: number + contractType: ContractType + from: string + to: string + tokenIds?: Array + amounts: Array + logIndex: number + amountsUSD?: Array + pricesUSD?: Array + contractInfo?: ContractInfo + tokenMetadata?: { [key: string]: TokenMetadata } } -export interface TokenIDRange { - start: string - end: string +export enum TxnTransferType { + UNKNOWN = 'UNKNOWN', + SEND = 'SEND', + RECEIVE = 'RECEIVE' } -export interface Page { - page?: number - column?: string - before?: any - after?: any - sort?: Array - pageSize?: number - more?: boolean +export interface Version { + webrpcVersion: string + schemaVersion: string + schemaHash: string + appVersion: string } -export interface SortBy { - column: string - order: SortOrder +export interface WALWriterRuntimeStatus { + healthOK: boolean + startTime: string + uptime: number + ver: string + branch: string + commitHash: string + chainID: number + percentWALWritten: number } export interface WebhookListener { @@ -519,109 +712,45 @@ export interface WebhookListener { active: boolean } -export interface EventFilter { - events?: Array - contractAddresses?: Array - accounts?: Array - tokenIDs?: Array -} - -export interface TokenBalanceFilter { +export interface GetBalanceUpdatesRequest { + chainIds?: Array + networks?: Array + networkType?: NetworkType contractAddress: string - sinceBlockNumber: number -} - -export interface MetadataOptions { - verifiedOnly?: boolean - unverifiedOnly?: boolean - includeContracts?: Array -} - -export interface TokenBalancesFilter { - accountAddresses: Array - contractStatus?: ContractVerificationStatus - contractTypes?: Array - contractWhitelist?: Array - contractBlacklist?: Array - omitNativeBalances: boolean -} - -export interface TokenBalancesByContractFilter { - contractAddresses: Array - accountAddresses?: Array - contractStatus?: ContractVerificationStatus -} - -export interface GatewayEtherBalance { - chainId: number - error: string - result: EtherBalance -} - -export interface GatewayNativeTokenBalance { - chainId: number - error: string - result: NativeTokenBalance + lastBlockNumber: number + lastBlockHash?: string + page?: Page } -export interface GatewayNativeTokenBalances { - chainId: number - error: string - results: Array +export interface GetBalanceUpdatesResponse { + page: Page + balances: Array } -export interface GatewayTokenBalance { - chainId: number - error: string - results: Array +export interface GetChainsRequest { + networkType?: NetworkType } -export interface IndexerGateway { - getNativeTokenBalance( - args: GetNativeTokenBalanceArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - getTokenBalances(args: GetTokenBalancesArgs, headers?: object, signal?: AbortSignal): Promise - getTokenBalancesSummary( - args: GetTokenBalancesSummaryArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - getTokenBalancesDetails( - args: GetTokenBalancesDetailsArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - getTokenBalancesByContract( - args: GetTokenBalancesByContractArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - getBalanceUpdates( - args: GetBalanceUpdatesArgs, - headers?: object, - signal?: AbortSignal, - ): Promise - ping(headers?: object, signal?: AbortSignal): Promise - version(headers?: object, signal?: AbortSignal): Promise - runtimeStatus(headers?: object, signal?: AbortSignal): Promise +export interface GetChainsResponse { + chains: Array } -export interface GetNativeTokenBalanceArgs { +export interface GetNativeTokenBalanceRequest { chainIds?: Array networks?: Array - testnets?: boolean + networkType?: NetworkType accountAddress?: string + omitPrices?: boolean } -export interface GetNativeTokenBalanceReturn { +export interface GetNativeTokenBalanceResponse { balances: Array } -export interface GetTokenBalancesArgs { + +export interface GetTokenBalancesRequest { chainIds?: Array networks?: Array - testnets?: boolean + networkType?: NetworkType accountAddress?: string contractAddress?: string tokenID?: string @@ -631,85 +760,109 @@ export interface GetTokenBalancesArgs { page?: Page } -export interface GetTokenBalancesReturn { +export interface GetTokenBalancesResponse { page: Page balances: Array } -export interface GetTokenBalancesSummaryArgs { + +export interface GetTokenBalancesByContractRequest { chainIds?: Array networks?: Array - testnets?: boolean - filter: TokenBalancesFilter + networkType?: NetworkType + filter: TokenBalancesByContractFilter omitMetadata?: boolean page?: Page } -export interface GetTokenBalancesSummaryReturn { +export interface GetTokenBalancesByContractResponse { page: Page - nativeBalances: Array balances: Array } -export interface GetTokenBalancesDetailsArgs { + +export interface GetTokenBalancesDetailsRequest { chainIds?: Array networks?: Array - testnets?: boolean + networkType?: NetworkType filter: TokenBalancesFilter omitMetadata?: boolean page?: Page } -export interface GetTokenBalancesDetailsReturn { +export interface GetTokenBalancesDetailsResponse { page: Page nativeBalances: Array balances: Array } -export interface GetTokenBalancesByContractArgs { + +export interface GetTokenBalancesSummaryRequest { chainIds?: Array networks?: Array - testnets?: boolean - filter: TokenBalancesByContractFilter + networkType?: NetworkType + filter: TokenBalancesFilter omitMetadata?: boolean page?: Page } -export interface GetTokenBalancesByContractReturn { +export interface GetTokenBalancesSummaryResponse { page: Page + nativeBalances: Array balances: Array } -export interface GetBalanceUpdatesArgs { + +export interface GetTokenPriceRequest { + q: GatewayTokenPriceQuery +} + +export interface GetTokenPriceResponse { + price: GatewayPrice +} + +export interface GetTokenPricesRequest { + q: Array +} + +export interface GetTokenPricesResponse { + prices: Array +} + +export interface GetTransactionHistoryRequest { chainIds?: Array networks?: Array - testnets?: boolean - contractAddress: string - lastBlockNumber: number - lastBlockHash?: string + networkType?: NetworkType + filter: TransactionHistoryFilter + includeMetadata?: boolean + metadataOptions?: MetadataOptions page?: Page } -export interface GetBalanceUpdatesReturn { +export interface GetTransactionHistoryResponse { page: Page - balances: Array + transactions: Array } -export interface PingArgs {} -export interface PingReturn { +export interface PingRequest {} + +export interface PingResponse { status: boolean } -export interface VersionArgs {} -export interface VersionReturn { - version: Version -} -export interface RuntimeStatusArgs {} +export interface RuntimeStatusRequest {} -export interface RuntimeStatusReturn { +export interface RuntimeStatusResponse { status: GatewayRuntimeStatus } +export interface VersionRequest {} + +export interface VersionResponse { + version: Version +} + // // Client // -export class IndexerGateway implements IndexerGateway { + +export class IndexerGateway implements IndexerGatewayClient { protected hostname: string protected fetch: Fetch protected path = '/rpc/IndexerGateway/' @@ -723,198 +876,239 @@ export class IndexerGateway implements IndexerGateway { return this.hostname + this.path + name } - getNativeTokenBalance = ( - args: GetNativeTokenBalanceArgs, + queryKey = { + getBalanceUpdates: (req: GetBalanceUpdatesRequest) => ['IndexerGateway', 'getBalanceUpdates', req] as const, + getChains: (req: GetChainsRequest) => ['IndexerGateway', 'getChains', req] as const, + getNativeTokenBalance: (req: GetNativeTokenBalanceRequest) => ['IndexerGateway', 'getNativeTokenBalance', req] as const, + getTokenBalances: (req: GetTokenBalancesRequest) => ['IndexerGateway', 'getTokenBalances', req] as const, + getTokenBalancesByContract: (req: GetTokenBalancesByContractRequest) => + ['IndexerGateway', 'getTokenBalancesByContract', req] as const, + getTokenBalancesDetails: (req: GetTokenBalancesDetailsRequest) => ['IndexerGateway', 'getTokenBalancesDetails', req] as const, + getTokenBalancesSummary: (req: GetTokenBalancesSummaryRequest) => ['IndexerGateway', 'getTokenBalancesSummary', req] as const, + getTokenPrice: (req: GetTokenPriceRequest) => ['IndexerGateway', 'getTokenPrice', req] as const, + getTokenPrices: (req: GetTokenPricesRequest) => ['IndexerGateway', 'getTokenPrices', req] as const, + getTransactionHistory: (req: GetTransactionHistoryRequest) => ['IndexerGateway', 'getTransactionHistory', req] as const, + ping: () => ['IndexerGateway', 'ping'] as const, + runtimeStatus: () => ['IndexerGateway', 'runtimeStatus'] as const, + version: () => ['IndexerGateway', 'version'] as const + } + + getBalanceUpdates = ( + req: GetBalanceUpdatesRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetNativeTokenBalance'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - balances: >_data.balances, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetBalanceUpdates'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetBalanceUpdatesResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } + ) + } + + getChains = (req: GetChainsRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetChains'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetChainsResponse') + }) + }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } + ) + } + + getNativeTokenBalance = ( + req: GetNativeTokenBalanceRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetNativeTokenBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetNativeTokenBalanceResponse') + }) }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } getTokenBalances = ( - args: GetTokenBalancesArgs, + req: GetTokenBalancesRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetTokenBalances'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenBalancesResponse') + }) + }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } + ) + } + + getTokenBalancesByContract = ( + req: GetTokenBalancesByContractRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetTokenBalances'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - balances: >_data.balances, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetTokenBalancesByContract'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenBalancesByContractResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } + ) + } + + getTokenBalancesDetails = ( + req: GetTokenBalancesDetailsRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetTokenBalancesDetails'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenBalancesDetailsResponse') + }) }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } getTokenBalancesSummary = ( - args: GetTokenBalancesSummaryArgs, + req: GetTokenBalancesSummaryRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetTokenBalancesSummary'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - nativeBalances: >_data.nativeBalances, - balances: >_data.balances, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetTokenBalancesSummary'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenBalancesSummaryResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getTokenBalancesDetails = ( - args: GetTokenBalancesDetailsArgs, - headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetTokenBalancesDetails'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - nativeBalances: >_data.nativeBalances, - balances: >_data.balances, - } + getTokenPrice = (req: GetTokenPriceRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetTokenPrice'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenPriceResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getTokenBalancesByContract = ( - args: GetTokenBalancesByContractArgs, - headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetTokenBalancesByContract'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - balances: >_data.balances, - } + getTokenPrices = (req: GetTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetTokenPrices'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenPricesResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - getBalanceUpdates = ( - args: GetBalanceUpdatesArgs, + getTransactionHistory = ( + req: GetTransactionHistoryRequest, headers?: object, - signal?: AbortSignal, - ): Promise => { - return this.fetch(this.url('GetBalanceUpdates'), createHTTPRequest(args, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - page: _data.page, - balances: >_data.balances, - } + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetTransactionHistory'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTransactionHistoryResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - ping = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Ping'), createHTTPRequest({}, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - status: _data.status, - } + ping = (headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('Ping'), createHttpRequest('{}', headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'PingResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - version = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Version'), createHTTPRequest({}, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - version: _data.version, - } + runtimeStatus = (headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('RuntimeStatus'), createHttpRequest('{}', headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'RuntimeStatusResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } - runtimeStatus = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('RuntimeStatus'), createHTTPRequest({}, headers, signal)).then( - (res) => { - return buildResponse(res).then((_data) => { - return { - status: _data.status, - } + version = (headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('Version'), createHttpRequest('{}', headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'VersionResponse') }) }, - (error) => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } ) } } -const createHTTPRequest = (body: object = {}, headers: object = {}, signal: AbortSignal | null = null): object => { - const reqHeaders: { [key: string]: string } = { ...headers, 'Content-Type': 'application/json' } - reqHeaders[WebrpcHeader] = WebrpcHeaderValue - - return { - method: 'POST', - headers: reqHeaders, - body: JSON.stringify(body || {}), - signal, +const createHttpRequest = (body: string = '{}', headers: object = {}, signal: AbortSignal | null = null): object => { + const reqHeaders: { [key: string]: string } = { + ...headers, + 'Content-Type': 'application/json', + [WebrpcHeader]: WebrpcHeaderValue } + return { method: 'POST', headers: reqHeaders, body, signal } } const buildResponse = (res: Response): Promise => { - return res.text().then((text) => { + return res.text().then(text => { let data try { data = JSON.parse(text) } catch (error) { - let message = '' - if (error instanceof Error) { - message = error.message - } throw WebrpcBadResponseError.new({ status: res.status, - cause: `JSON.parse(): ${message}: response text: ${text}`, + cause: `JSON.parse(): ${error instanceof Error ? error.message : String(error)}: response text: ${text}` }) } if (!res.ok) { @@ -925,518 +1119,494 @@ const buildResponse = (res: Response): Promise => { }) } +export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise + +export const JsonEncode = (obj: T): string => { + return JSON.stringify(obj) +} + +export const JsonDecode = (data: string | any, _typ: string = ''): T => { + let parsed: any = data + if (typeof data === 'string') { + try { + parsed = JSON.parse(data) + } catch (err) { + throw WebrpcBadResponseError.new({ cause: `JsonDecode: JSON.parse failed: ${(err as Error).message}` }) + } + } + return parsed as T +} + // // Errors // +type WebrpcErrorParams = { name?: string; code?: number; message?: string; status?: number; cause?: string } + export class WebrpcError extends Error { - name: string code: number - message: string status: number - cause?: string - - /** @deprecated Use message instead of msg. Deprecated in webrpc v0.11.0. */ - msg: string - - constructor(name: string, code: number, message: string, status: number, cause?: string) { - super(message) - this.name = name || 'WebrpcError' - this.code = typeof code === 'number' ? code : 0 - this.message = message || `endpoint error ${this.code}` - this.msg = this.message - this.status = typeof status === 'number' ? status : 0 - this.cause = cause + + constructor(error: WebrpcErrorParams = {}) { + super(error.message) + this.name = error.name || 'WebrpcEndpointError' + this.code = typeof error.code === 'number' ? error.code : 0 + this.message = error.message || `endpoint error` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcError.prototype) } static new(payload: any): WebrpcError { - return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause) + return new this({ message: payload.message, code: payload.code, status: payload.status, cause: payload.cause }) } } -// Webrpc errors - export class WebrpcEndpointError extends WebrpcError { - constructor( - name: string = 'WebrpcEndpoint', - code: number = 0, - message: string = 'endpoint error', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcEndpoint' + this.code = typeof error.code === 'number' ? error.code : 0 + this.message = error.message || `endpoint error` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcEndpointError.prototype) } } export class WebrpcRequestFailedError extends WebrpcError { - constructor( - name: string = 'WebrpcRequestFailed', - code: number = -1, - message: string = 'request failed', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcRequestFailed' + this.code = typeof error.code === 'number' ? error.code : -1 + this.message = error.message || `request failed` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcRequestFailedError.prototype) } } export class WebrpcBadRouteError extends WebrpcError { - constructor( - name: string = 'WebrpcBadRoute', - code: number = -2, - message: string = 'bad route', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadRoute' + this.code = typeof error.code === 'number' ? error.code : -2 + this.message = error.message || `bad route` + this.status = typeof error.status === 'number' ? error.status : 404 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadRouteError.prototype) } } export class WebrpcBadMethodError extends WebrpcError { - constructor( - name: string = 'WebrpcBadMethod', - code: number = -3, - message: string = 'bad method', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadMethod' + this.code = typeof error.code === 'number' ? error.code : -3 + this.message = error.message || `bad method` + this.status = typeof error.status === 'number' ? error.status : 405 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadMethodError.prototype) } } export class WebrpcBadRequestError extends WebrpcError { - constructor( - name: string = 'WebrpcBadRequest', - code: number = -4, - message: string = 'bad request', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadRequest' + this.code = typeof error.code === 'number' ? error.code : -4 + this.message = error.message || `bad request` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadRequestError.prototype) } } export class WebrpcBadResponseError extends WebrpcError { - constructor( - name: string = 'WebrpcBadResponse', - code: number = -5, - message: string = 'bad response', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadResponse' + this.code = typeof error.code === 'number' ? error.code : -5 + this.message = error.message || `bad response` + this.status = typeof error.status === 'number' ? error.status : 500 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadResponseError.prototype) } } export class WebrpcServerPanicError extends WebrpcError { - constructor( - name: string = 'WebrpcServerPanic', - code: number = -6, - message: string = 'server panic', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcServerPanic' + this.code = typeof error.code === 'number' ? error.code : -6 + this.message = error.message || `server panic` + this.status = typeof error.status === 'number' ? error.status : 500 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcServerPanicError.prototype) } } export class WebrpcInternalErrorError extends WebrpcError { - constructor( - name: string = 'WebrpcInternalError', - code: number = -7, - message: string = 'internal error', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcInternalError' + this.code = typeof error.code === 'number' ? error.code : -7 + this.message = error.message || `internal error` + this.status = typeof error.status === 'number' ? error.status : 500 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcInternalErrorError.prototype) } } -export class WebrpcClientDisconnectedError extends WebrpcError { - constructor( - name: string = 'WebrpcClientDisconnected', - code: number = -8, - message: string = 'client disconnected', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, WebrpcClientDisconnectedError.prototype) +export class WebrpcClientAbortedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcClientAborted' + this.code = typeof error.code === 'number' ? error.code : -8 + this.message = error.message || `request aborted by client` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, WebrpcClientAbortedError.prototype) } } export class WebrpcStreamLostError extends WebrpcError { - constructor( - name: string = 'WebrpcStreamLost', - code: number = -9, - message: string = 'stream lost', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcStreamLost' + this.code = typeof error.code === 'number' ? error.code : -9 + this.message = error.message || `stream lost` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcStreamLostError.prototype) } } export class WebrpcStreamFinishedError extends WebrpcError { - constructor( - name: string = 'WebrpcStreamFinished', - code: number = -10, - message: string = 'stream finished', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcStreamFinished' + this.code = typeof error.code === 'number' ? error.code : -10 + this.message = error.message || `stream finished` + this.status = typeof error.status === 'number' ? error.status : 200 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcStreamFinishedError.prototype) } } +// // Schema errors +// -export class UnauthorizedError extends WebrpcError { - constructor( - name: string = 'Unauthorized', - code: number = 1000, - message: string = 'Unauthorized access', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, UnauthorizedError.prototype) +export class AbortedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Aborted' + this.code = typeof error.code === 'number' ? error.code : 1005 + this.message = error.message || `Request aborted` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, AbortedError.prototype) } } -export class PermissionDeniedError extends WebrpcError { - constructor( - name: string = 'PermissionDenied', - code: number = 1001, - message: string = 'Permission denied', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, PermissionDeniedError.prototype) +export class AccessKeyMismatchError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'AccessKeyMismatch' + this.code = typeof error.code === 'number' ? error.code : 1102 + this.message = error.message || `Access key mismatch` + this.status = typeof error.status === 'number' ? error.status : 409 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, AccessKeyMismatchError.prototype) } } -export class SessionExpiredError extends WebrpcError { - constructor( - name: string = 'SessionExpired', - code: number = 1002, - message: string = 'Session expired', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, SessionExpiredError.prototype) +export class AccessKeyNotFoundError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'AccessKeyNotFound' + this.code = typeof error.code === 'number' ? error.code : 1101 + this.message = error.message || `Access key not found` + this.status = typeof error.status === 'number' ? error.status : 401 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, AccessKeyNotFoundError.prototype) } } -export class MethodNotFoundError extends WebrpcError { - constructor( - name: string = 'MethodNotFound', - code: number = 1003, - message: string = 'Method not found', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, MethodNotFoundError.prototype) +export class AtLeastOneKeyError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'AtLeastOneKey' + this.code = typeof error.code === 'number' ? error.code : 1302 + this.message = error.message || `You need at least one Access Key` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, AtLeastOneKeyError.prototype) } } -export class RequestConflictError extends WebrpcError { - constructor( - name: string = 'RequestConflict', - code: number = 1004, - message: string = 'Conflict with target resource', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, RequestConflictError.prototype) +export class GeoblockedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Geoblocked' + this.code = typeof error.code === 'number' ? error.code : 1006 + this.message = error.message || `Geoblocked region` + this.status = typeof error.status === 'number' ? error.status : 451 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, GeoblockedError.prototype) } } -export class AbortedError extends WebrpcError { - constructor( - name: string = 'Aborted', - code: number = 1005, - message: string = 'Request aborted', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, AbortedError.prototype) +export class InvalidArgumentError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'InvalidArgument' + this.code = typeof error.code === 'number' ? error.code : 2001 + this.message = error.message || `Invalid argument` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, InvalidArgumentError.prototype) } } -export class GeoblockedError extends WebrpcError { - constructor( - name: string = 'Geoblocked', - code: number = 1006, - message: string = 'Geoblocked region', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, GeoblockedError.prototype) +export class InvalidOriginError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'InvalidOrigin' + this.code = typeof error.code === 'number' ? error.code : 1103 + this.message = error.message || `Invalid origin for Access Key` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, InvalidOriginError.prototype) } } -export class RateLimitedError extends WebrpcError { - constructor( - name: string = 'RateLimited', - code: number = 1007, - message: string = 'Rate-limited. Please slow down.', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, RateLimitedError.prototype) +export class InvalidServiceError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'InvalidService' + this.code = typeof error.code === 'number' ? error.code : 1104 + this.message = error.message || `Service not enabled for Access key` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, InvalidServiceError.prototype) } } -export class ProjectNotFoundError extends WebrpcError { - constructor( - name: string = 'ProjectNotFound', - code: number = 1100, - message: string = 'Project not found', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, ProjectNotFoundError.prototype) +export class MaxAccessKeysError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'MaxAccessKeys' + this.code = typeof error.code === 'number' ? error.code : 1301 + this.message = error.message || `Access keys limit reached` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, MaxAccessKeysError.prototype) } } -export class AccessKeyNotFoundError extends WebrpcError { - constructor( - name: string = 'AccessKeyNotFound', - code: number = 1101, - message: string = 'Access key not found', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, AccessKeyNotFoundError.prototype) +export class MetadataCallFailedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'MetadataCallFailed' + this.code = typeof error.code === 'number' ? error.code : 3003 + this.message = error.message || `Metadata service call failed` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, MetadataCallFailedError.prototype) } } -export class AccessKeyMismatchError extends WebrpcError { - constructor( - name: string = 'AccessKeyMismatch', - code: number = 1102, - message: string = 'Access key mismatch', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, AccessKeyMismatchError.prototype) +export class MethodNotFoundError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'MethodNotFound' + this.code = typeof error.code === 'number' ? error.code : 1003 + this.message = error.message || `Method not found` + this.status = typeof error.status === 'number' ? error.status : 404 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, MethodNotFoundError.prototype) } } -export class InvalidOriginError extends WebrpcError { - constructor( - name: string = 'InvalidOrigin', - code: number = 1103, - message: string = 'Invalid origin for Access Key', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, InvalidOriginError.prototype) +export class NoDefaultKeyError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'NoDefaultKey' + this.code = typeof error.code === 'number' ? error.code : 1300 + this.message = error.message || `No default access key found` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, NoDefaultKeyError.prototype) } } -export class InvalidServiceError extends WebrpcError { - constructor( - name: string = 'InvalidService', - code: number = 1104, - message: string = 'Service not enabled for Access key', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, InvalidServiceError.prototype) +export class NotFoundError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'NotFound' + this.code = typeof error.code === 'number' ? error.code : 3000 + this.message = error.message || `Resource not found` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, NotFoundError.prototype) } } -export class UnauthorizedUserError extends WebrpcError { - constructor( - name: string = 'UnauthorizedUser', - code: number = 1105, - message: string = 'Unauthorized user', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, UnauthorizedUserError.prototype) +export class PermissionDeniedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'PermissionDenied' + this.code = typeof error.code === 'number' ? error.code : 1001 + this.message = error.message || `Permission denied` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, PermissionDeniedError.prototype) } } -export class QuotaExceededError extends WebrpcError { - constructor( - name: string = 'QuotaExceeded', - code: number = 1200, - message: string = 'Quota exceeded', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, QuotaExceededError.prototype) +export class ProjectNotFoundError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'ProjectNotFound' + this.code = typeof error.code === 'number' ? error.code : 1100 + this.message = error.message || `Project not found` + this.status = typeof error.status === 'number' ? error.status : 401 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, ProjectNotFoundError.prototype) } } -export class RateLimitError extends WebrpcError { - constructor( - name: string = 'RateLimit', - code: number = 1201, - message: string = 'Rate limit exceeded', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, RateLimitError.prototype) +export class QueryFailedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'QueryFailed' + this.code = typeof error.code === 'number' ? error.code : 2003 + this.message = error.message || `Query failed` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, QueryFailedError.prototype) } } -export class NoDefaultKeyError extends WebrpcError { - constructor( - name: string = 'NoDefaultKey', - code: number = 1300, - message: string = 'No default access key found', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, NoDefaultKeyError.prototype) +export class QuotaExceededError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'QuotaExceeded' + this.code = typeof error.code === 'number' ? error.code : 1200 + this.message = error.message || `Quota exceeded` + this.status = typeof error.status === 'number' ? error.status : 429 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, QuotaExceededError.prototype) } } -export class MaxAccessKeysError extends WebrpcError { - constructor( - name: string = 'MaxAccessKeys', - code: number = 1301, - message: string = 'Access keys limit reached', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, MaxAccessKeysError.prototype) +export class RateLimitError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'RateLimit' + this.code = typeof error.code === 'number' ? error.code : 1201 + this.message = error.message || `Rate limit exceeded` + this.status = typeof error.status === 'number' ? error.status : 429 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, RateLimitError.prototype) } } -export class AtLeastOneKeyError extends WebrpcError { - constructor( - name: string = 'AtLeastOneKey', - code: number = 1302, - message: string = 'You need at least one Access Key', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, AtLeastOneKeyError.prototype) +export class RateLimitedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'RateLimited' + this.code = typeof error.code === 'number' ? error.code : 1007 + this.message = error.message || `Rate-limited. Please slow down.` + this.status = typeof error.status === 'number' ? error.status : 429 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, RateLimitedError.prototype) } } -export class TimeoutError extends WebrpcError { - constructor( - name: string = 'Timeout', - code: number = 1900, - message: string = 'Request timed out', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, TimeoutError.prototype) +export class RequestConflictError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'RequestConflict' + this.code = typeof error.code === 'number' ? error.code : 1004 + this.message = error.message || `Conflict with target resource` + this.status = typeof error.status === 'number' ? error.status : 409 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, RequestConflictError.prototype) } } -export class InvalidArgumentError extends WebrpcError { - constructor( - name: string = 'InvalidArgument', - code: number = 2001, - message: string = 'Invalid argument', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, InvalidArgumentError.prototype) +export class ResourceExhaustedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'ResourceExhausted' + this.code = typeof error.code === 'number' ? error.code : 2004 + this.message = error.message || `Resource exhausted` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, ResourceExhaustedError.prototype) } } -export class UnavailableError extends WebrpcError { - constructor( - name: string = 'Unavailable', - code: number = 2002, - message: string = 'Unavailable resource', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, UnavailableError.prototype) +export class SessionExpiredError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'SessionExpired' + this.code = typeof error.code === 'number' ? error.code : 1002 + this.message = error.message || `Session expired` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, SessionExpiredError.prototype) } } -export class QueryFailedError extends WebrpcError { - constructor( - name: string = 'QueryFailed', - code: number = 2003, - message: string = 'Query failed', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, QueryFailedError.prototype) +export class TimeoutError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Timeout' + this.code = typeof error.code === 'number' ? error.code : 1900 + this.message = error.message || `Request timed out` + this.status = typeof error.status === 'number' ? error.status : 408 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, TimeoutError.prototype) } } -export class ResourceExhaustedError extends WebrpcError { - constructor( - name: string = 'ResourceExhausted', - code: number = 2004, - message: string = 'Resource exhausted', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, ResourceExhaustedError.prototype) +export class UnauthorizedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Unauthorized' + this.code = typeof error.code === 'number' ? error.code : 1000 + this.message = error.message || `Unauthorized access` + this.status = typeof error.status === 'number' ? error.status : 401 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, UnauthorizedError.prototype) } } -export class NotFoundError extends WebrpcError { - constructor( - name: string = 'NotFound', - code: number = 3000, - message: string = 'Resource not found', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, NotFoundError.prototype) +export class UnauthorizedUserError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'UnauthorizedUser' + this.code = typeof error.code === 'number' ? error.code : 1105 + this.message = error.message || `Unauthorized user` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, UnauthorizedUserError.prototype) } } -export class MetadataCallFailedError extends WebrpcError { - constructor( - name: string = 'MetadataCallFailed', - code: number = 3003, - message: string = 'Metadata service call failed', - status: number = 0, - cause?: string, - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, MetadataCallFailedError.prototype) +export class UnavailableError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Unavailable' + this.code = typeof error.code === 'number' ? error.code : 2002 + this.message = error.message || `Unavailable resource` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, UnavailableError.prototype) } } @@ -1449,38 +1619,78 @@ export enum errors { WebrpcBadResponse = 'WebrpcBadResponse', WebrpcServerPanic = 'WebrpcServerPanic', WebrpcInternalError = 'WebrpcInternalError', - WebrpcClientDisconnected = 'WebrpcClientDisconnected', + WebrpcClientAborted = 'WebrpcClientAborted', WebrpcStreamLost = 'WebrpcStreamLost', WebrpcStreamFinished = 'WebrpcStreamFinished', - Unauthorized = 'Unauthorized', - PermissionDenied = 'PermissionDenied', - SessionExpired = 'SessionExpired', - MethodNotFound = 'MethodNotFound', - RequestConflict = 'RequestConflict', Aborted = 'Aborted', - Geoblocked = 'Geoblocked', - RateLimited = 'RateLimited', - ProjectNotFound = 'ProjectNotFound', - AccessKeyNotFound = 'AccessKeyNotFound', AccessKeyMismatch = 'AccessKeyMismatch', + AccessKeyNotFound = 'AccessKeyNotFound', + AtLeastOneKey = 'AtLeastOneKey', + Geoblocked = 'Geoblocked', + InvalidArgument = 'InvalidArgument', InvalidOrigin = 'InvalidOrigin', InvalidService = 'InvalidService', - UnauthorizedUser = 'UnauthorizedUser', - QuotaExceeded = 'QuotaExceeded', - RateLimit = 'RateLimit', - NoDefaultKey = 'NoDefaultKey', MaxAccessKeys = 'MaxAccessKeys', - AtLeastOneKey = 'AtLeastOneKey', - Timeout = 'Timeout', - InvalidArgument = 'InvalidArgument', - Unavailable = 'Unavailable', + MetadataCallFailed = 'MetadataCallFailed', + MethodNotFound = 'MethodNotFound', + NoDefaultKey = 'NoDefaultKey', + NotFound = 'NotFound', + PermissionDenied = 'PermissionDenied', + ProjectNotFound = 'ProjectNotFound', QueryFailed = 'QueryFailed', + QuotaExceeded = 'QuotaExceeded', + RateLimit = 'RateLimit', + RateLimited = 'RateLimited', + RequestConflict = 'RequestConflict', ResourceExhausted = 'ResourceExhausted', - NotFound = 'NotFound', - MetadataCallFailed = 'MetadataCallFailed', -} - -const webrpcErrorByCode: { [code: number]: any } = { + SessionExpired = 'SessionExpired', + Timeout = 'Timeout', + Unauthorized = 'Unauthorized', + UnauthorizedUser = 'UnauthorizedUser', + Unavailable = 'Unavailable' +} + +export enum WebrpcErrorCodes { + WebrpcEndpoint = 0, + WebrpcRequestFailed = -1, + WebrpcBadRoute = -2, + WebrpcBadMethod = -3, + WebrpcBadRequest = -4, + WebrpcBadResponse = -5, + WebrpcServerPanic = -6, + WebrpcInternalError = -7, + WebrpcClientAborted = -8, + WebrpcStreamLost = -9, + WebrpcStreamFinished = -10, + Aborted = 1005, + AccessKeyMismatch = 1102, + AccessKeyNotFound = 1101, + AtLeastOneKey = 1302, + Geoblocked = 1006, + InvalidArgument = 2001, + InvalidOrigin = 1103, + InvalidService = 1104, + MaxAccessKeys = 1301, + MetadataCallFailed = 3003, + MethodNotFound = 1003, + NoDefaultKey = 1300, + NotFound = 3000, + PermissionDenied = 1001, + ProjectNotFound = 1100, + QueryFailed = 2003, + QuotaExceeded = 1200, + RateLimit = 1201, + RateLimited = 1007, + RequestConflict = 1004, + ResourceExhausted = 2004, + SessionExpired = 1002, + Timeout = 1900, + Unauthorized = 1000, + UnauthorizedUser = 1105, + Unavailable = 2002 +} + +export const webrpcErrorByCode: { [code: number]: any } = { [0]: WebrpcEndpointError, [-1]: WebrpcRequestFailedError, [-2]: WebrpcBadRouteError, @@ -1489,35 +1699,89 @@ const webrpcErrorByCode: { [code: number]: any } = { [-5]: WebrpcBadResponseError, [-6]: WebrpcServerPanicError, [-7]: WebrpcInternalErrorError, - [-8]: WebrpcClientDisconnectedError, + [-8]: WebrpcClientAbortedError, [-9]: WebrpcStreamLostError, [-10]: WebrpcStreamFinishedError, - [1000]: UnauthorizedError, - [1001]: PermissionDeniedError, - [1002]: SessionExpiredError, - [1003]: MethodNotFoundError, - [1004]: RequestConflictError, [1005]: AbortedError, - [1006]: GeoblockedError, - [1007]: RateLimitedError, - [1100]: ProjectNotFoundError, - [1101]: AccessKeyNotFoundError, [1102]: AccessKeyMismatchError, + [1101]: AccessKeyNotFoundError, + [1302]: AtLeastOneKeyError, + [1006]: GeoblockedError, + [2001]: InvalidArgumentError, [1103]: InvalidOriginError, [1104]: InvalidServiceError, - [1105]: UnauthorizedUserError, - [1200]: QuotaExceededError, - [1201]: RateLimitError, - [1300]: NoDefaultKeyError, [1301]: MaxAccessKeysError, - [1302]: AtLeastOneKeyError, - [1900]: TimeoutError, - [2001]: InvalidArgumentError, - [2002]: UnavailableError, + [3003]: MetadataCallFailedError, + [1003]: MethodNotFoundError, + [1300]: NoDefaultKeyError, + [3000]: NotFoundError, + [1001]: PermissionDeniedError, + [1100]: ProjectNotFoundError, [2003]: QueryFailedError, + [1200]: QuotaExceededError, + [1201]: RateLimitError, + [1007]: RateLimitedError, + [1004]: RequestConflictError, [2004]: ResourceExhaustedError, - [3000]: NotFoundError, - [3003]: MetadataCallFailedError, + [1002]: SessionExpiredError, + [1900]: TimeoutError, + [1000]: UnauthorizedError, + [1105]: UnauthorizedUserError, + [2002]: UnavailableError } -export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise +// +// Webrpc +// + +export const WebrpcHeader = 'Webrpc' + +export const WebrpcHeaderValue = 'webrpc@v0.31.2;gen-typescript@v0.23.1;sequence-indexer@v0.4.0' + +type WebrpcGenVersions = { + WebrpcGenVersion: string + codeGenName: string + codeGenVersion: string + schemaName: string + schemaVersion: string +} + +export function VersionFromHeader(headers: Headers): WebrpcGenVersions { + const headerValue = headers.get(WebrpcHeader) + if (!headerValue) { + return { + WebrpcGenVersion: '', + codeGenName: '', + codeGenVersion: '', + schemaName: '', + schemaVersion: '' + } + } + + return parseWebrpcGenVersions(headerValue) +} + +function parseWebrpcGenVersions(header: string): WebrpcGenVersions { + const versions = header.split(';') + if (versions.length < 3) { + return { + WebrpcGenVersion: '', + codeGenName: '', + codeGenVersion: '', + schemaName: '', + schemaVersion: '' + } + } + + const [_, WebrpcGenVersion] = versions[0]!.split('@') + const [codeGenName, codeGenVersion] = versions[1]!.split('@') + const [schemaName, schemaVersion] = versions[2]!.split('@') + + return { + WebrpcGenVersion: WebrpcGenVersion ?? '', + codeGenName: codeGenName ?? '', + codeGenVersion: codeGenVersion ?? '', + schemaName: schemaName ?? '', + schemaVersion: schemaVersion ?? '' + } +} From e9262faa186c060112b58bf857e40a152ebbcc24 Mon Sep 17 00:00:00 2001 From: Alexander Kolberg Date: Mon, 23 Feb 2026 14:46:36 +0200 Subject: [PATCH 2/2] Disable noUncheckedIndexedAccess for indexer package --- packages/services/indexer/tsconfig.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/services/indexer/tsconfig.json b/packages/services/indexer/tsconfig.json index fed9c77b4..8623be1c0 100644 --- a/packages/services/indexer/tsconfig.json +++ b/packages/services/indexer/tsconfig.json @@ -3,7 +3,9 @@ "compilerOptions": { "rootDir": "src", "outDir": "dist", - "types": ["node"] + "types": ["node"], + // TODO: enable when webrpc codegen handles noUncheckedIndexedAccess + "noUncheckedIndexedAccess": false }, "include": ["src"], "exclude": ["node_modules", "dist"]