From 0794b5d0e8a1fe551cb91e4a1afb931d2a5fd1f3 Mon Sep 17 00:00:00 2001 From: Taylan Pince Date: Mon, 16 Feb 2026 15:32:12 +0100 Subject: [PATCH] Add latest indexer gen files --- packages/indexer/src/indexer.gen.ts | 3688 +++++++++++++------------ packages/indexer/src/indexergw.gen.ts | 2177 ++++++++------- 2 files changed, 3157 insertions(+), 2708 deletions(-) diff --git a/packages/indexer/src/indexer.gen.ts b/packages/indexer/src/indexer.gen.ts index de6d45d2c..6aa58ba63 100644 --- a/packages/indexer/src/indexer.gen.ts +++ b/packages/indexer/src/indexer.gen.ts @@ -1,79 +1,315 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 f9220b18008af826218980db21a68ec39989fb80 +// 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 = 'f9220b18008af826218980db21a68ec39989fb80' +export const WebrpcSchemaHash = "caf5c4c3677ac2dce41858dce7cd727a7810845f" -type WebrpcGenVersions = { - webrpcGenVersion: string - codeGenName: string - codeGenVersion: string - schemaName: string - schemaVersion: string +// +// 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 } -export function VersionFromHeader(headers: Headers): WebrpcGenVersions { - const headerValue = headers.get(WebrpcHeader) - if (!headerValue) { - return { - webrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '' - } - } - return parseWebrpcGenVersions(headerValue) -} +// +// Schema types +// -function parseWebrpcGenVersions(header: string): WebrpcGenVersions { - const versions = header.split(';') - if (versions.length < 3) { - return { - webrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '' - } - } +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 +} - const [_, webrpcGenVersion] = versions[0].split('@') - const [codeGenName, codeGenVersion] = versions[1].split('@') - const [schemaName, schemaVersion] = versions[2].split('@') +export interface BloomStats { + hitRatio: string + falsePositivesPercent: string + hitCount: number + missCount: number + falsePositives: number +} - return { - webrpcGenVersion, - codeGenName, - codeGenVersion, - schemaName, - schemaVersion - } +export interface BloomStatus { + enabled: boolean + initialized: boolean + bloomInitElapsedTime: string + stats: BloomStats } -// -// Types -// +export interface Bond { + pebble: PebbleMetrics + estimatedDiskUsagePerTable: any + estimatedDiskUsageTotal: string +} -export enum ResourceStatus { - NOT_AVAILABLE = 'NOT_AVAILABLE', - REFRESHING = 'REFRESHING', - AVAILABLE = 'AVAILABLE' +export interface ChainInfo { + chainId: number + chainName: string } export interface ContractInfo { @@ -93,56 +329,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 { @@ -155,90 +364,109 @@ export enum ContractType { ERC20_BRIDGE = 'ERC20_BRIDGE', ERC721_BRIDGE = 'ERC721_BRIDGE', ERC1155_BRIDGE = 'ERC1155_BRIDGE', - SEQ_MARKETPLACE = 'SEQ_MARKETPLACE' + SEQ_MARKETPLACE = 'SEQ_MARKETPLACE', + ERC6909 = 'ERC6909' } -export enum EventLogType { - UNKNOWN = 'UNKNOWN', - BLOCK_ADDED = 'BLOCK_ADDED', - BLOCK_REMOVED = 'BLOCK_REMOVED' +export enum ContractVerificationStatus { + VERIFIED = 'VERIFIED', + UNVERIFIED = 'UNVERIFIED', + ALL = 'ALL' } -export enum EventLogDataType { - EVENT = 'EVENT', - TOKEN_TRANSFER = 'TOKEN_TRANSFER', - NATIVE_TOKEN_TRANSFER = 'NATIVE_TOKEN_TRANSFER', - SEQUENCE_TXN = 'SEQUENCE_TXN' +export interface DiskUsage { + humanReadable: string + used: number + size: number + percent: number + dirs: {[key: string]: string} } -export enum OrderStatus { - OPEN = 'OPEN', - CLOSED = 'CLOSED', - CANCELLED = 'CANCELLED' +export interface EtherBalance { + accountAddress: string + balanceWei: string } -export enum TxnTransferType { - UNKNOWN = 'UNKNOWN', - SEND = 'SEND', - RECEIVE = 'RECEIVE' +export interface EventDecoded { + topicHash: string + eventSig: string + types: Array + names: Array + values: Array } -export enum TransactionStatus { - FAILED = 'FAILED', - SUCCESSFUL = 'SUCCESSFUL' +export interface EventFilter { + events?: Array + contractAddresses?: Array + accounts?: Array + tokenIDs?: Array } -export enum TransactionType { - LegacyTxnType = 'LegacyTxnType', - AccessListTxnType = 'AccessListTxnType', - DynamicFeeTxnType = 'DynamicFeeTxnType' +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 SortOrder { - DESC = 'DESC', - ASC = 'ASC' +export enum EventLogDataType { + EVENT = 'EVENT', + TOKEN_TRANSFER = 'TOKEN_TRANSFER', + NATIVE_TOKEN_TRANSFER = 'NATIVE_TOKEN_TRANSFER', + SEQUENCE_TXN = 'SEQUENCE_TXN' } -export enum ContractVerificationStatus { - VERIFIED = 'VERIFIED', - UNVERIFIED = 'UNVERIFIED', - ALL = 'ALL' +export enum EventLogType { + UNKNOWN = 'UNKNOWN', + BLOCK_ADDED = 'BLOCK_ADDED', + BLOCK_REMOVED = 'BLOCK_REMOVED' } -export enum NetworkType { - MAINNETS = 'MAINNETS', - TESTNETS = 'TESTNETS', - ALL = 'ALL' +export interface GatewayBackendResponseTime { + percentiles: {[key: string]: number} + average: number } -export interface Version { - webrpcVersion: string - schemaVersion: string - schemaHash: string - appVersion: string +export interface GatewayBackendRuntimeStatus { + name: string + chainId: number + responseTime: GatewayBackendResponseTime } -export interface RuntimeStatus { - healthOK: boolean - indexerEnabled: boolean - startTime: string - uptime: number - ver: string - branch: string - commitHash: string - chainID: number - checks: RuntimeChecks +export interface GatewayEtherBalance { + chainId: number + errorReason?: string + result: EtherBalance } -export interface GatewayBackendResponseTime { - percentiles: { [key: string]: number } - average: number +export interface GatewayNativeTokenBalance { + chainId: number + errorReason?: string + result: NativeTokenBalance } -export interface GatewayBackendRuntimeStatus { - name: string +export interface GatewayNativeTokenBalances { chainId: number - responseTime: GatewayBackendResponseTime + errorReason?: string + results: Array +} + +export interface GatewayPrice { + chainID: number + errorReason?: string + results: Array } export interface GatewayRuntimeStatus { @@ -251,113 +479,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 + 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 { @@ -366,48 +654,44 @@ export interface TokenBalance { 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 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 + blockNumber: number + chainId: number + uniqueCollectibles: string + isSummary: boolean + contractInfo?: ContractInfo + tokenMetadata?: TokenMetadata } -export interface OrderbookOrderFilter { - isListing?: boolean - userAddresses?: Array - tokenIds: Array - excludeUserAddresses?: Array - afterBlockNumber: number - afterCreatedAt: number - beforeExpiry: number - userAddress?: string - excludeUserAddress?: string +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 - accountAddress: string contractAddress: string contractType: ContractType fromAddress: string @@ -415,12 +699,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 @@ -439,17 +756,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 { @@ -462,14 +774,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 { @@ -488,31 +800,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 { @@ -525,454 +866,352 @@ 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 - errorReason?: string - result: EtherBalance +export interface FetchTransactionReceiptWithFilterResponse { + receipt: TransactionReceipt } -export interface GatewayNativeTokenBalance { - chainId: number - errorReason?: string - result: NativeTokenBalance +export interface GetAllWebhookListenersRequest { + projectId?: number } -export interface GatewayNativeTokenBalances { - chainId: number - errorReason?: string - results: Array +export interface GetAllWebhookListenersResponse { + listeners: Array } -export interface GatewayTokenBalance { - chainId: number - errorReason?: string - results: Array +export interface GetBalanceUpdatesRequest { + contractAddress: string + lastBlockNumber: number + lastBlockHash?: string + page?: Page } -export interface ChainInfo { - chainId: number - chainName: string +export interface GetBalanceUpdatesResponse { + page: Page + balances: Array } -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 PingArgs {} - -export interface PingReturn { - status: boolean +export interface GetChainIDRequest { } -export interface VersionArgs {} -export interface VersionReturn { - version: Version +export interface GetChainIDResponse { + chainID: number } -export interface RuntimeStatusArgs {} -export interface RuntimeStatusReturn { - status: RuntimeStatus +export interface GetEtherBalanceRequest { + accountAddress?: string } -export interface GetChainIDArgs {} -export interface GetChainIDReturn { - chainID: number +export interface GetEtherBalanceResponse { + balance: EtherBalance } -export interface GetEtherBalanceArgs { - accountAddress?: string + +export interface GetMarketplaceOrdersRequest { + marketplaceContractAddress: string + collectionAddress: string + filter?: MarketplaceOrderFilter + page?: Page } -export interface GetEtherBalanceReturn { - balance: EtherBalance +export interface GetMarketplaceOrdersResponse { + page?: Page + orders: Array } -export interface GetNativeTokenBalanceArgs { - accountAddress?: string + +export interface GetMarketplaceTopOrdersRequest { + marketplaceContractAddress: string + collectionAddress: string + filter: MarketplaceTopOrdersFilter } -export interface GetNativeTokenBalanceReturn { - balance: NativeTokenBalance +export interface GetMarketplaceTopOrdersResponse { + orders: Array } -export interface GetTokenBalancesSummaryArgs { - filter: TokenBalancesFilter - omitMetadata?: boolean - page?: Page + +export interface GetNativeTokenBalanceRequest { + accountAddress?: string + omitPrices?: boolean } -export interface GetTokenBalancesSummaryReturn { - page: Page - nativeBalances: Array - balances: Array +export interface GetNativeTokenBalanceResponse { + balance: NativeTokenBalance } -export interface GetTokenBalancesDetailsArgs { - filter: TokenBalancesFilter - omitMetadata?: boolean + +export interface GetTokenBalancesRequest { + accountAddress?: string + contractAddress?: string + tokenID?: string + includeMetadata?: boolean + metadataOptions?: MetadataOptions + includeCollectionTokens?: boolean page?: Page } -export interface GetTokenBalancesDetailsReturn { +export interface GetTokenBalancesResponse { page: Page - nativeBalances: Array balances: Array } -export interface GetTokenBalancesByContractArgs { + +export interface GetTokenBalancesByContractRequest { filter: TokenBalancesByContractFilter omitMetadata?: boolean page?: Page } -export interface GetTokenBalancesByContractReturn { +export interface GetTokenBalancesByContractResponse { page: Page balances: Array } -export interface GetTokenBalancesArgs { - accountAddress?: string - contractAddress?: string - tokenID?: string - includeMetadata?: boolean - metadataOptions?: MetadataOptions - includeCollectionTokens?: boolean + +export interface GetTokenBalancesDetailsRequest { + filter: TokenBalancesFilter + omitMetadata?: boolean page?: Page } -export interface GetTokenBalancesReturn { +export interface GetTokenBalancesDetailsResponse { page: Page + nativeBalances: Array balances: Array } -export interface GetTokenSuppliesArgs { - contractAddress: string - includeMetadata?: boolean - metadataOptions?: MetadataOptions + +export interface GetTokenBalancesSummaryRequest { + filter: TokenBalancesFilter + omitMetadata?: boolean page?: Page } -export interface GetTokenSuppliesReturn { +export interface GetTokenBalancesSummaryResponse { page: Page - contractType: ContractType - tokenIDs: Array + nativeBalances: Array + balances: Array } -export interface GetTokenSuppliesMapArgs { - tokenMap: { [key: string]: Array } - includeMetadata?: boolean - metadataOptions?: MetadataOptions + +export interface GetTokenIDRangesRequest { + contractAddress: string + lastTokenID?: string } -export interface GetTokenSuppliesMapReturn { - supplies: { [key: string]: Array } +export interface GetTokenIDRangesResponse { + contractType: ContractType + tokenIDRanges: Array + moreRanges: boolean } -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 ListTokenPricesRequest { + page?: Page } -export interface SubscribeEventsArgs { - filter: EventFilter + +export interface ListTokenPricesResponse { + page: Page + prices: Array } -export interface SubscribeEventsReturn { - log: EventLog +export interface PauseAllWebhookListenersRequest { + projectId?: number } -export interface SubscribeBalanceUpdatesArgs { - contractAddress: string + +export interface PauseAllWebhookListenersResponse { + status: boolean } -export interface SubscribeBalanceUpdatesReturn { - balance: TokenBalance +export interface PingRequest { } -export interface SyncBalanceArgs { - accountAddress: string - contractAddress: string - tokenID?: string + +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 UpdateWebhookListenerReturn { - status: boolean +export interface RuntimeStatusResponse { + status: RuntimeStatus } -export interface RemoveWebhookListenerArgs { - id: number - projectId?: number + +export interface SubscribeBalanceUpdatesRequest { + contractAddress: string } -export interface RemoveWebhookListenerReturn { - status: boolean +export interface SubscribeBalanceUpdatesResponse { + balance: TokenBalance } -export interface RemoveAllWebhookListenersArgs { - projectId?: number + +export interface SubscribeEventsRequest { + filter: EventFilter } -export interface RemoveAllWebhookListenersReturn { - status: boolean +export interface SubscribeEventsResponse { + log: EventLog } -export interface ToggleWebhookListenerArgs { - id: number - projectId?: number + +export interface SubscribeReceiptsRequest { + filter: TransactionFilter } -export interface ToggleWebhookListenerReturn { - webhookListener: WebhookListener +export interface SubscribeReceiptsResponse { + receipt: TransactionReceipt } -export interface PauseAllWebhookListenersArgs { - projectId?: number + +export interface SyncBalanceRequest { + accountAddress: string + contractAddress: string + tokenID?: string } -export interface PauseAllWebhookListenersReturn { - status: boolean +export interface SyncBalanceResponse { } -export interface ResumeAllWebhookListenersArgs { + +export interface ToggleWebhookListenerRequest { + id: number projectId?: number } -export interface ResumeAllWebhookListenersReturn { - status: boolean +export interface ToggleWebhookListenerResponse { + webhookListener: WebhookListener } -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 UpdateWebhookListenerRequest { + listener: WebhookListener + projectId?: number } -export interface GetOrderbookOrdersReturn { - page?: Page - orders: Array +export interface UpdateWebhookListenerResponse { + status: boolean } -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/' @@ -985,708 +1224,643 @@ export class Indexer implements Indexer { 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)}` }) + }) + } - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - getEtherBalance = (args: GetEtherBalanceArgs, 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - getTokenBalancesSummary = ( - args: GetTokenBalancesSummaryArgs, - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - getTokenBalances = (args: GetTokenBalancesArgs, 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - getTokenSupplies = (args: GetTokenSuppliesArgs, 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - getTokenSuppliesMap = ( - args: GetTokenSuppliesMapArgs, - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - getTokenIDRanges = (args: GetTokenIDRangesArgs, 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - fetchTransactionReceiptWithFilter = ( - args: FetchTransactionReceiptWithFilterArgs, - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 {} - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - getAllWebhookListeners = ( - args: GetAllWebhookListenersArgs, - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - getWebhookListener = ( - args: GetWebhookListenerArgs, - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - addWebhookListener = ( - args: AddWebhookListenerArgs, - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - updateWebhookListener = ( - args: UpdateWebhookListenerArgs, - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - removeWebhookListener = ( - args: RemoveWebhookListenerArgs, - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - removeAllWebhookListeners = ( - args: RemoveAllWebhookListenersArgs, - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - resumeAllWebhookListeners = ( - args: ResumeAllWebhookListenersArgs, - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - getOrderbookOrders = ( - args: GetOrderbookOrdersArgs, - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } -} - -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) + 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 } - return + } + 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)}` }) + }) } - 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() + 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; } - }, 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) { - let message = '' - if (error instanceof Error) { - message = error.message - } - - if (error instanceof DOMException && error.name === 'AbortError') { + if (!res.body) { onError( - WebrpcRequestFailedError.new({ - message: 'AbortError', - cause: `AbortError: ${message}` - }), - () => { - throw new Error('Abort signal cannot be used to reconnect') - } + WebrpcBadResponseError.new({ + status: res.status, + cause: "Invalid response, missing body", + }), + retryFetch ) - } else { - onError( - WebrpcStreamLostError.new({ - cause: `reader.read(): ${message}` - }), - retryFetch - ) - } - return + return; } - let lines = buffer.split('\n') - for (let i = 0; i < lines.length - 1; i++) { - if (lines[i].length == 0) { - continue - } - let data: any - try { - data = JSON.parse(lines[i]) - 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 + 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() } - } catch (error) { - if (error instanceof Error && error.message === 'Abort signal cannot be used to reconnect') { - throw error + }, 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) } - onError( - WebrpcBadResponseError.new({ - status: res.status, - // @ts-ignore - cause: `JSON.parse(): ${error.message}` - }), - retryFetch - ) - } - onMessage(data) - } - if (!done) { - buffer = lines[lines.length - 1] - continue + if (!done) { + const lastLine = lines[lines.length - 1]; + buffer = lastLine || ""; + continue; + } + + onClose && onClose() + return; } +}; - onClose && onClose() - return - } -} -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 => { @@ -1694,539 +1868,535 @@ const buildResponse = (res: Response): Promise => { let data try { data = JSON.parse(text) - } catch (error) { - let message = '' - if (error instanceof Error) { - message = error.message - } + } catch(error) { 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) { - const code: number = typeof data.code === 'number' ? data.code : 0 + 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 { - 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) } } + export enum errors { WebrpcEndpoint = 'WebrpcEndpoint', WebrpcRequestFailed = 'WebrpcRequestFailed', @@ -2236,38 +2406,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', + MaxAccessKeys = 'MaxAccessKeys', + MetadataCallFailed = 'MetadataCallFailed', + MethodNotFound = 'MethodNotFound', + NoDefaultKey = 'NoDefaultKey', + NotFound = 'NotFound', + PermissionDenied = 'PermissionDenied', + ProjectNotFound = 'ProjectNotFound', + QueryFailed = 'QueryFailed', QuotaExceeded = 'QuotaExceeded', RateLimit = 'RateLimit', - NoDefaultKey = 'NoDefaultKey', - MaxAccessKeys = 'MaxAccessKeys', - AtLeastOneKey = 'AtLeastOneKey', + RateLimited = 'RateLimited', + RequestConflict = 'RequestConflict', + ResourceExhausted = 'ResourceExhausted', + SessionExpired = 'SessionExpired', Timeout = 'Timeout', - InvalidArgument = 'InvalidArgument', + Unauthorized = 'Unauthorized', + UnauthorizedUser = 'UnauthorizedUser', Unavailable = 'Unavailable', - QueryFailed = 'QueryFailed', - ResourceExhausted = 'ResourceExhausted', - NotFound = 'NotFound', - MetadataCallFailed = 'MetadataCallFailed' } -const webrpcErrorByCode: { [code: number]: any } = { +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, @@ -2276,46 +2486,92 @@ 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, + [1301]: MaxAccessKeysError, + [3003]: MetadataCallFailedError, + [1003]: MethodNotFoundError, + [1300]: NoDefaultKeyError, + [3000]: NotFoundError, + [1001]: PermissionDeniedError, + [1100]: ProjectNotFoundError, + [2003]: QueryFailedError, [1200]: QuotaExceededError, [1201]: RateLimitError, - [1300]: NoDefaultKeyError, - [1301]: MaxAccessKeysError, - [1302]: AtLeastOneKeyError, + [1007]: RateLimitedError, + [1004]: RequestConflictError, + [2004]: ResourceExhaustedError, + [1002]: SessionExpiredError, [1900]: TimeoutError, - [2001]: InvalidArgumentError, + [1000]: UnauthorizedError, + [1105]: UnauthorizedUserError, [2002]: UnavailableError, - [2003]: QueryFailedError, - [2004]: ResourceExhaustedError, - [3000]: NotFoundError, - [3003]: MetadataCallFailedError } -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 + +// +// 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) } -export interface WebrpcOptions { - headers?: HeadersInit - signal?: AbortSignal + +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 index 3849f2246..562250c80 100644 --- a/packages/indexer/src/indexergw.gen.ts +++ b/packages/indexer/src/indexergw.gen.ts @@ -1,79 +1,142 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 399517e791d272fddd35b036260f7bbbe6cea0e5 +// 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 = '399517e791d272fddd35b036260f7bbbe6cea0e5' +export const WebrpcSchemaHash = "b978d153702d614d5f1b9c98ff7f2e5857cccfd6" -type WebrpcGenVersions = { - webrpcGenVersion: string - codeGenName: string - codeGenVersion: string - schemaName: string - schemaVersion: string +// +// 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 } -export function VersionFromHeader(headers: Headers): WebrpcGenVersions { - const headerValue = headers.get(WebrpcHeader) - if (!headerValue) { - return { - webrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '' - } - } - return parseWebrpcGenVersions(headerValue) -} +// +// Schema types +// -function parseWebrpcGenVersions(header: string): WebrpcGenVersions { - const versions = header.split(';') - if (versions.length < 3) { - return { - webrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '' - } - } +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 +} - const [_, webrpcGenVersion] = versions[0].split('@') - const [codeGenName, codeGenVersion] = versions[1].split('@') - const [schemaName, schemaVersion] = versions[2].split('@') +export interface BloomStats { + hitRatio: string + falsePositivesPercent: string + hitCount: number + missCount: number + falsePositives: number +} - return { - webrpcGenVersion, - codeGenName, - codeGenVersion, - schemaName, - schemaVersion - } +export interface BloomStatus { + enabled: boolean + initialized: boolean + bloomInitElapsedTime: string + stats: BloomStats } -// -// Types -// +export interface Bond { + pebble: PebbleMetrics + estimatedDiskUsagePerTable: any + estimatedDiskUsageTotal: string +} -export enum ResourceStatus { - NOT_AVAILABLE = 'NOT_AVAILABLE', - REFRESHING = 'REFRESHING', - AVAILABLE = 'AVAILABLE' +export interface ChainInfo { + chainId: number + chainName: string } export interface ContractInfo { @@ -93,56 +156,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 { @@ -155,90 +191,109 @@ export enum ContractType { ERC20_BRIDGE = 'ERC20_BRIDGE', ERC721_BRIDGE = 'ERC721_BRIDGE', ERC1155_BRIDGE = 'ERC1155_BRIDGE', - SEQ_MARKETPLACE = 'SEQ_MARKETPLACE' + SEQ_MARKETPLACE = 'SEQ_MARKETPLACE', + ERC6909 = 'ERC6909' } -export enum EventLogType { - UNKNOWN = 'UNKNOWN', - BLOCK_ADDED = 'BLOCK_ADDED', - BLOCK_REMOVED = 'BLOCK_REMOVED' +export enum ContractVerificationStatus { + VERIFIED = 'VERIFIED', + UNVERIFIED = 'UNVERIFIED', + ALL = 'ALL' } -export enum EventLogDataType { - EVENT = 'EVENT', - TOKEN_TRANSFER = 'TOKEN_TRANSFER', - NATIVE_TOKEN_TRANSFER = 'NATIVE_TOKEN_TRANSFER', - SEQUENCE_TXN = 'SEQUENCE_TXN' +export interface DiskUsage { + humanReadable: string + used: number + size: number + percent: number + dirs: {[key: string]: string} } -export enum OrderStatus { - OPEN = 'OPEN', - CLOSED = 'CLOSED', - CANCELLED = 'CANCELLED' +export interface EtherBalance { + accountAddress: string + balanceWei: string } -export enum TxnTransferType { - UNKNOWN = 'UNKNOWN', - SEND = 'SEND', - RECEIVE = 'RECEIVE' +export interface EventDecoded { + topicHash: string + eventSig: string + types: Array + names: Array + values: Array } -export enum TransactionStatus { - FAILED = 'FAILED', - SUCCESSFUL = 'SUCCESSFUL' +export interface EventFilter { + events?: Array + contractAddresses?: Array + accounts?: Array + tokenIDs?: Array } -export enum TransactionType { - LegacyTxnType = 'LegacyTxnType', - AccessListTxnType = 'AccessListTxnType', - DynamicFeeTxnType = 'DynamicFeeTxnType' +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 SortOrder { - DESC = 'DESC', - ASC = 'ASC' +export enum EventLogDataType { + EVENT = 'EVENT', + TOKEN_TRANSFER = 'TOKEN_TRANSFER', + NATIVE_TOKEN_TRANSFER = 'NATIVE_TOKEN_TRANSFER', + SEQUENCE_TXN = 'SEQUENCE_TXN' } -export enum ContractVerificationStatus { - VERIFIED = 'VERIFIED', - UNVERIFIED = 'UNVERIFIED', - ALL = 'ALL' +export enum EventLogType { + UNKNOWN = 'UNKNOWN', + BLOCK_ADDED = 'BLOCK_ADDED', + BLOCK_REMOVED = 'BLOCK_REMOVED' } -export enum NetworkType { - MAINNETS = 'MAINNETS', - TESTNETS = 'TESTNETS', - ALL = 'ALL' +export interface GatewayBackendResponseTime { + percentiles: {[key: string]: number} + average: number } -export interface Version { - webrpcVersion: string - schemaVersion: string - schemaHash: string - appVersion: string +export interface GatewayBackendRuntimeStatus { + name: string + chainId: number + responseTime: GatewayBackendResponseTime } -export interface RuntimeStatus { - healthOK: boolean - indexerEnabled: boolean - startTime: string - uptime: number - ver: string - branch: string - commitHash: string - chainID: number - checks: RuntimeChecks +export interface GatewayEtherBalance { + chainId: number + errorReason?: string + result: EtherBalance } -export interface GatewayBackendResponseTime { - percentiles: { [key: string]: number } - average: number +export interface GatewayNativeTokenBalance { + chainId: number + errorReason?: string + result: NativeTokenBalance } -export interface GatewayBackendRuntimeStatus { - name: string +export interface GatewayNativeTokenBalances { chainId: number - responseTime: GatewayBackendResponseTime + errorReason?: string + results: Array +} + +export interface GatewayPrice { + chainID: number + errorReason?: string + results: Array } export interface GatewayRuntimeStatus { @@ -251,113 +306,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 + 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 { @@ -366,6 +481,9 @@ export interface TokenBalance { accountAddress: string tokenID?: string balance: string + balanceUSD: string + priceUSD: string + priceUpdatedAt?: string blockHash: string blockNumber: number chainId: number @@ -375,39 +493,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 @@ -415,12 +526,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 @@ -439,17 +583,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 { @@ -462,14 +601,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 { @@ -488,31 +627,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 { @@ -525,108 +693,42 @@ 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 - errorReason?: string - result: EtherBalance -} - -export interface GatewayNativeTokenBalance { - chainId: number - errorReason?: string - result: NativeTokenBalance + lastBlockNumber: number + lastBlockHash?: string + page?: Page } -export interface GatewayNativeTokenBalances { - chainId: number - errorReason?: string - results: Array +export interface GetBalanceUpdatesResponse { + page: Page + balances: Array } -export interface GatewayTokenBalance { - chainId: number - errorReason?: string - results: Array +export interface GetChainsRequest { + networkType?: NetworkType } -export interface ChainInfo { - chainId: number - chainName: string +export interface GetChainsResponse { + chains: Array } -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 - getChains(args: GetChainsArgs, 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 GetNativeTokenBalanceArgs { +export interface GetNativeTokenBalanceRequest { chainIds?: Array networks?: Array networkType?: NetworkType accountAddress?: string + omitPrices?: boolean } -export interface GetNativeTokenBalanceReturn { +export interface GetNativeTokenBalanceResponse { balances: Array } -export interface GetTokenBalancesArgs { + +export interface GetTokenBalancesRequest { chainIds?: Array networks?: Array networkType?: NetworkType @@ -639,25 +741,26 @@ 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 networkType?: NetworkType - filter: TokenBalancesFilter + 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 networkType?: NetworkType @@ -666,65 +769,86 @@ export interface GetTokenBalancesDetailsArgs { page?: Page } -export interface GetTokenBalancesDetailsReturn { +export interface GetTokenBalancesDetailsResponse { page: Page nativeBalances: Array balances: Array } -export interface GetTokenBalancesByContractArgs { + +export interface GetTokenBalancesSummaryRequest { chainIds?: Array networks?: Array networkType?: NetworkType - filter: TokenBalancesByContractFilter + 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 networkType?: NetworkType - contractAddress: string - lastBlockNumber: number - lastBlockHash?: string + filter: TransactionHistoryFilter + includeMetadata?: boolean + metadataOptions?: MetadataOptions page?: Page } -export interface GetBalanceUpdatesReturn { - page: Page - balances: Array +export interface GetTransactionHistoryResponse { + page: Page + transactions: Array +} + +export interface PingRequest { +} + +export interface PingResponse { + status: boolean } -export interface GetChainsArgs { - networkType?: NetworkType + +export interface RuntimeStatusRequest { } -export interface GetChainsReturn { - chains: Array +export interface RuntimeStatusResponse { + status: GatewayRuntimeStatus } -export interface PingArgs {} -export interface PingReturn { - status: boolean +export interface VersionRequest { } -export interface VersionArgs {} -export interface VersionReturn { +export interface VersionResponse { version: Version } -export interface RuntimeStatusArgs {} -export interface RuntimeStatusReturn { - status: GatewayRuntimeStatus -} + // // Client // -export class IndexerGateway implements IndexerGateway { + +export class IndexerGateway implements IndexerGatewayClient { protected hostname: string protected fetch: Fetch protected path = '/rpc/IndexerGateway/' @@ -737,191 +861,184 @@ export class IndexerGateway implements IndexerGateway { 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)}` }) + }) + } - 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 { - balances: >_data.balances - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + 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)}` }) + }) } - getTokenBalances = (args: GetTokenBalancesArgs, 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + 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)}` }) + }) } - getTokenBalancesSummary = ( - args: GetTokenBalancesSummaryArgs, - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + 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)}` }) + }) } - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + 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)}` }) + }) } - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + 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)}` }) + }) } - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + 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)}` }) + }) } - getChains = (args: GetChainsArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetChains'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - chains: >_data.chains - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + 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)}` }) + }) } - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + 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)}` }) + }) } - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + 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)}` }) + }) } - 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 - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + 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)}` }) + }) } -} -const createHTTPRequest = (body: object = {}, headers: object = {}, signal: AbortSignal | null = null): object => { - const reqHeaders: { [key: string]: string } = { ...headers, 'Content-Type': 'application/json' } - reqHeaders[WebrpcHeader] = WebrpcHeaderValue + 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)}` }) + }) + } - return { - method: 'POST', - headers: reqHeaders, - body: JSON.stringify(body || {}), - signal + 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 => { @@ -929,539 +1046,518 @@ const buildResponse = (res: Response): Promise => { let data try { data = JSON.parse(text) - } catch (error) { - let message = '' - if (error instanceof Error) { - message = error.message - } + } catch(error) { 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) { - const code: number = typeof data.code === 'number' ? data.code : 0 + 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 { - 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) } } + export enum errors { WebrpcEndpoint = 'WebrpcEndpoint', WebrpcRequestFailed = 'WebrpcRequestFailed', @@ -1471,38 +1567,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', + MaxAccessKeys = 'MaxAccessKeys', + MetadataCallFailed = 'MetadataCallFailed', + MethodNotFound = 'MethodNotFound', + NoDefaultKey = 'NoDefaultKey', + NotFound = 'NotFound', + PermissionDenied = 'PermissionDenied', + ProjectNotFound = 'ProjectNotFound', + QueryFailed = 'QueryFailed', QuotaExceeded = 'QuotaExceeded', RateLimit = 'RateLimit', - NoDefaultKey = 'NoDefaultKey', - MaxAccessKeys = 'MaxAccessKeys', - AtLeastOneKey = 'AtLeastOneKey', + RateLimited = 'RateLimited', + RequestConflict = 'RequestConflict', + ResourceExhausted = 'ResourceExhausted', + SessionExpired = 'SessionExpired', Timeout = 'Timeout', - InvalidArgument = 'InvalidArgument', + Unauthorized = 'Unauthorized', + UnauthorizedUser = 'UnauthorizedUser', Unavailable = 'Unavailable', - QueryFailed = 'QueryFailed', - ResourceExhausted = 'ResourceExhausted', - NotFound = 'NotFound', - MetadataCallFailed = 'MetadataCallFailed' } -const webrpcErrorByCode: { [code: number]: any } = { +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, @@ -1511,35 +1647,92 @@ 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, + [1301]: MaxAccessKeysError, + [3003]: MetadataCallFailedError, + [1003]: MethodNotFoundError, + [1300]: NoDefaultKeyError, + [3000]: NotFoundError, + [1001]: PermissionDeniedError, + [1100]: ProjectNotFoundError, + [2003]: QueryFailedError, [1200]: QuotaExceededError, [1201]: RateLimitError, - [1300]: NoDefaultKeyError, - [1301]: MaxAccessKeysError, - [1302]: AtLeastOneKeyError, + [1007]: RateLimitedError, + [1004]: RequestConflictError, + [2004]: ResourceExhaustedError, + [1002]: SessionExpiredError, [1900]: TimeoutError, - [2001]: InvalidArgumentError, + [1000]: UnauthorizedError, + [1105]: UnauthorizedUserError, [2002]: UnavailableError, - [2003]: QueryFailedError, - [2004]: ResourceExhaustedError, - [3000]: NotFoundError, - [3003]: MetadataCallFailedError } -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 ?? "", + }; +} +