diff --git a/packages/indexer/src/indexer.gen.ts b/packages/indexer/src/indexer.gen.ts new file mode 100644 index 000000000..e9104a103 --- /dev/null +++ b/packages/indexer/src/indexer.gen.ts @@ -0,0 +1,2658 @@ +/* eslint-disable */ +// sequence-indexer v0.4.0 6950eb4778c44c2e495457ea489e1e08ce2067c0 +// -- +// Code generated by webrpc-gen@v0.25.3 with typescript generator. DO NOT EDIT. +// +// 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.25.3;gen-typescript@v0.17.0;sequence-indexer@v0.4.0' + +// WebRPC description and code-gen version +export const WebRPCVersion = 'v1' + +// Schema version of your RIDL schema +export const WebRPCSchemaVersion = 'v0.4.0' + +// Schema hash generated from your RIDL schema +export const WebRPCSchemaHash = '6950eb4778c44c2e495457ea489e1e08ce2067c0' + +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 ?? '' + } +} + +// +// Types +// + +export interface Asset { + id: number + collectionId: number + tokenId?: string + url?: string + metadataField: string + name?: string + filesize?: number + mimeType?: string + width?: number + height?: number + updatedAt?: string +} + +export interface BloomStats { + hitRatio: string + falsePositivesPercent: string + hitCount: number + missCount: number + falsePositives: number +} + +export interface BloomStatus { + enabled: boolean + initialized: boolean + bloomInitElapsedTime: string + stats: BloomStats +} + +export interface Bond { + pebble: PebbleMetrics + estimatedDiskUsagePerTable: any + estimatedDiskUsageTotal: string +} + +export interface ChainInfo { + chainId: number + chainName: string +} + +export interface ContractInfo { + chainId: number + address: string + source: string + name: string + type: string + symbol: string + decimals?: number + logoURI: string + deployed: boolean + bytecodeHash: string + extensions: ContractInfoExtensions + updatedAt: string + queuedAt?: string + status: ResourceStatus +} + +export interface 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 enum ContractType { + UNKNOWN = 'UNKNOWN', + NATIVE = 'NATIVE', + ERC20 = 'ERC20', + ERC721 = 'ERC721', + ERC1155 = 'ERC1155', + SEQUENCE_WALLET = 'SEQUENCE_WALLET', + ERC20_BRIDGE = 'ERC20_BRIDGE', + ERC721_BRIDGE = 'ERC721_BRIDGE', + ERC1155_BRIDGE = 'ERC1155_BRIDGE', + SEQ_MARKETPLACE = 'SEQ_MARKETPLACE', + ERC6909 = 'ERC6909' +} + +export enum ContractVerificationStatus { + VERIFIED = 'VERIFIED', + UNVERIFIED = 'UNVERIFIED', + ALL = 'ALL' +} + +export interface DiskUsage { + humanReadable: string + used: number + size: number + percent: number + dirs: { [key: string]: string } +} + +export interface EtherBalance { + accountAddress: string + balanceWei: string +} + +export interface EventDecoded { + topicHash: string + eventSig: string + types: Array + names: Array + values: Array +} + +export interface EventFilter { + events?: Array + contractAddresses?: Array + accounts?: Array + tokenIDs?: Array +} + +export interface EventLog { + id: number + uid: string + type: EventLogType + blockNumber: number + blockHash: string + parentBlockHash: string + contractAddress: string + contractType: ContractType + txnHash: string + txnIndex: number + txnLogIndex: number + logDataType: EventLogDataType + ts: string + txnInfo?: TxnInfo + rawLog?: { [key: string]: any } + event?: EventDecoded +} + +export enum EventLogDataType { + EVENT = 'EVENT', + TOKEN_TRANSFER = 'TOKEN_TRANSFER', + NATIVE_TOKEN_TRANSFER = 'NATIVE_TOKEN_TRANSFER', + SEQUENCE_TXN = 'SEQUENCE_TXN' +} + +export enum EventLogType { + UNKNOWN = 'UNKNOWN', + BLOCK_ADDED = 'BLOCK_ADDED', + BLOCK_REMOVED = 'BLOCK_REMOVED' +} + +export interface GatewayBackendResponseTime { + percentiles: { [key: string]: number } + average: number +} + +export interface GatewayBackendRuntimeStatus { + name: string + chainId: number + responseTime: GatewayBackendResponseTime +} + +export interface GatewayEtherBalance { + chainId: number + errorReason?: string + result: EtherBalance +} + +export interface GatewayNativeTokenBalance { + chainId: number + errorReason?: string + result: NativeTokenBalance +} + +export interface GatewayNativeTokenBalances { + chainId: number + errorReason?: string + results: Array +} + +export interface GatewayRuntimeStatus { + healthOK: boolean + startTime: string + uptime: number + ver: string + branch: string + commitHash: string + backends: Array +} + +export interface GatewayTokenBalance { + chainId: number + errorReason?: string + results: Array +} + +export interface GatewayTransaction { + chainId: number + errorReason?: string + results: Array +} + +export interface IndexState { + chainId: string + lastBlockNum: number + lastBlockHash: string +} + +export interface IndexedBlock { + blockNumber: number + blockShortHash: string +} + +export interface IndexerMetrics { + blocksPerSecond: number + eventsPerSecond: number +} + +export interface MarketplaceOrder { + orderId: string + tokenContract: string + tokenId: string + isListing: boolean + quantity: string + quantityRemaining: string + currencyAddress: string + pricePerToken: string + expiry: string + orderStatus: OrderStatus + createdBy: string + blockNumber: number + orderbookContractAddress: string + createdAt: number +} + +export interface MarketplaceOrderFilter { + isListing?: boolean + userAddresses?: Array + currencyAddresses: Array + orderIds: Array + tokenIds: Array + excludeUserAddresses?: Array + blockNumberGt: number + createdAtAfter: number + orderStatuses: Array + returnExpired: boolean +} + +export interface MarketplaceTopOrdersFilter { + currencyAddresses: Array + tokenIds: Array + isListing: boolean + priceSort: SortOrder + excludeUser?: string +} + +export interface MetadataOptions { + verifiedOnly?: boolean + unverifiedOnly?: boolean + includeContracts?: Array +} + +export interface NativeTokenBalance { + accountAddress: string + chainId: number + balance: string + balanceUSD: string + priceUSD: string + error: string +} + +export enum NetworkType { + MAINNETS = 'MAINNETS', + TESTNETS = 'TESTNETS', + ALL = 'ALL' +} + +export enum OrderStatus { + OPEN = 'OPEN', + CLOSED = 'CLOSED', + CANCELLED = 'CANCELLED' +} + +export interface Page { + page?: number + column?: string + before?: any + after?: any + sort?: Array + pageSize?: number + more?: boolean +} + +export interface PebbleMetrics { + compactionCount: number + compactionEstimatedDebt: number + compactionInProgressBytes: number + compactionNumInProgress: number + compactionMarkedFiles: number +} + +export interface Price { + contractAddress: string + tokenID?: string + priceUSD: string +} + +export enum ResourceStatus { + NOT_AVAILABLE = 'NOT_AVAILABLE', + REFRESHING = 'REFRESHING', + AVAILABLE = 'AVAILABLE' +} + +export interface RuntimeChecks { + running: boolean + runnables: any + cgoEnabled: boolean + quotaControlEnabled: boolean + syncMode: string + percentIndexed: number + lastBlockNum: number + lastBlockNumWithState: number + bloomStatus: BloomStatus + bond: Bond + diskUsage: DiskUsage + metrics: IndexerMetrics +} + +export interface RuntimeStatus { + healthOK: boolean + indexerEnabled: boolean + startTime: string + uptime: number + ver: string + branch: string + commitHash: string + chainID: number + checks: RuntimeChecks +} + +export interface SortBy { + column: string + order: SortOrder +} + +export enum SortOrder { + DESC = 'DESC', + ASC = 'ASC' +} + +export interface TokenBalance { + contractType: ContractType + contractAddress: string + accountAddress: string + tokenID?: string + balance: string + balanceUSD: string + priceUSD: string + blockHash: string + blockNumber: number + chainId: number + uniqueCollectibles: string + isSummary: boolean + contractInfo?: ContractInfo + tokenMetadata?: TokenMetadata +} + +export interface TokenBalanceFilter { + contractAddress: string + sinceBlockNumber: number +} + +export interface TokenBalancesByContractFilter { + contractAddresses: Array + accountAddresses?: Array + contractStatus?: ContractVerificationStatus +} + +export interface TokenBalancesFilter { + accountAddresses: Array + contractStatus?: ContractVerificationStatus + contractWhitelist?: Array + contractBlacklist?: Array + omitNativeBalances: boolean + omitPrices?: boolean +} + +export interface TokenHistory { + blockNumber: number + blockHash: string + contractAddress: string + contractType: ContractType + fromAddress: string + toAddress: string + txnHash: string + txnIndex: number + txnLogIndex: number + tokenIDs: string + amounts: string + ts: string +} + +export interface TokenIDRange { + start: string + end: string +} + +export interface TokenMetadata { + 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 TokenSupply { + tokenID: string + supply: string + chainId: number + contractInfo?: ContractInfo + tokenMetadata?: TokenMetadata +} + +export interface Transaction { + txnHash: string + blockNumber: number + blockHash: string + chainId: number + metaTxnID?: string + transfers?: Array + timestamp: string +} + +export interface TransactionFilter { + txnHash?: string + from?: string + to?: string + contractAddress?: string + event?: string +} + +export interface TransactionHistoryFilter { + accountAddress?: string + contractAddress?: string + accountAddresses?: Array + contractAddresses?: Array + transactionHashes?: Array + metaTransactionIDs?: Array + fromBlock?: number + toBlock?: number + tokenID?: string + omitPrices?: boolean +} + +export interface TransactionLog { + contractAddress: string + topics: Array + data: string + index: number +} + +export interface TransactionReceipt { + txnHash: string + txnStatus: TransactionStatus + txnIndex: number + txnType: TransactionType + blockHash: string + blockNumber: number + gasUsed: number + effectiveGasPrice: string + from: string + to: string + logs: Array + final: boolean + reorged: boolean +} + +export enum TransactionStatus { + FAILED = 'FAILED', + SUCCESSFUL = 'SUCCESSFUL' +} + +export enum TransactionType { + LegacyTxnType = 'LegacyTxnType', + AccessListTxnType = 'AccessListTxnType', + DynamicFeeTxnType = 'DynamicFeeTxnType' +} + +export interface TxnInfo { + from: string + to: string + value: string +} + +export interface TxnTransfer { + transferType: TxnTransferType + contractAddress: string + contractType: ContractType + from: string + to: string + tokenIds?: Array + amounts: Array + logIndex: number + amountsUSD?: Array + pricesUSD?: Array + contractInfo?: ContractInfo + tokenMetadata?: { [key: string]: TokenMetadata } +} + +export enum TxnTransferType { + UNKNOWN = 'UNKNOWN', + SEND = 'SEND', + RECEIVE = 'RECEIVE' +} + +export interface Version { + webrpcVersion: string + schemaVersion: string + schemaHash: string + appVersion: string +} + +export interface WALWriterRuntimeStatus { + healthOK: boolean + startTime: string + uptime: number + ver: string + branch: string + commitHash: string + chainID: number + percentWALWritten: number +} + +export interface WebhookListener { + id: number + projectID: number + url: string + filters: EventFilter + name: string + updatedAt: string + active: boolean +} + +export interface Indexer { + addWebhookListener(args: AddWebhookListenerArgs, headers?: object, signal?: AbortSignal): Promise + /** + * Fetches a single receipt and then will stop the subscription + */ + fetchTransactionReceipt( + args: FetchTransactionReceiptArgs, + headers?: object, + signal?: AbortSignal + ): Promise + /** + * Fetches a single receipt with filter and then will stop the subscription + */ + fetchTransactionReceiptWithFilter( + args: FetchTransactionReceiptWithFilterArgs, + headers?: object, + signal?: AbortSignal + ): Promise + /** + * Webhooks + */ + getAllWebhookListeners( + args: GetAllWebhookListenersArgs, + 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(args: GetBalanceUpdatesArgs, 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(args: GetEtherBalanceArgs, 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( + args: GetMarketplaceOrdersArgs, + 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( + args: GetMarketplaceTopOrdersArgs, + 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( + args: GetNativeTokenBalanceArgs, + headers?: object, + signal?: AbortSignal + ): Promise + getPrices(args: GetPricesArgs, 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(args: GetTokenBalancesArgs, 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( + args: GetTokenBalancesByContractArgs, + 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( + args: GetTokenBalancesDetailsArgs, + 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( + args: GetTokenBalancesSummaryArgs, + 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(args: GetTokenIDRangesArgs, 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(args: GetTokenIDsArgs, 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(args: GetTokenSuppliesArgs, 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(args: GetTokenSuppliesMapArgs, 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( + args: GetTransactionHistoryArgs, + headers?: object, + signal?: AbortSignal + ): Promise + getWebhookListener(args: GetWebhookListenerArgs, headers?: object, signal?: AbortSignal): Promise + pauseAllWebhookListeners( + args: PauseAllWebhookListenersArgs, + headers?: object, + signal?: AbortSignal + ): Promise + /** + * Ping the indexer + */ + ping(headers?: object, signal?: AbortSignal): Promise + removeAllWebhookListeners( + args: RemoveAllWebhookListenersArgs, + headers?: object, + signal?: AbortSignal + ): Promise + removeWebhookListener( + args: RemoveWebhookListenerArgs, + headers?: object, + signal?: AbortSignal + ): Promise + resumeAllWebhookListeners( + args: ResumeAllWebhookListenersArgs, + 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( + args: SubscribeBalanceUpdatesArgs, + 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(args: SubscribeEventsArgs, options: WebrpcStreamOptions): WebrpcStreamController + /** + * Listen to transaction receipts on-chain based on the filter criteria + */ + subscribeReceipts(args: SubscribeReceiptsArgs, 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(args: SyncBalanceArgs, headers?: object, signal?: AbortSignal): Promise + toggleWebhookListener( + args: ToggleWebhookListenerArgs, + headers?: object, + signal?: AbortSignal + ): Promise + updateWebhookListener( + args: UpdateWebhookListenerArgs, + headers?: object, + signal?: AbortSignal + ): Promise + /** + * Get the current version of the indexer + */ + version(headers?: object, signal?: AbortSignal): Promise +} + +export interface AddWebhookListenerArgs { + url: string + filters: EventFilter + projectId?: number +} + +export interface AddWebhookListenerReturn { + status: boolean + listener: WebhookListener +} +export interface FetchTransactionReceiptArgs { + txnHash: string + maxBlockWait?: number +} + +export interface FetchTransactionReceiptReturn { + receipt: TransactionReceipt +} +export interface FetchTransactionReceiptWithFilterArgs { + filter: TransactionFilter + maxBlockWait?: number +} + +export interface FetchTransactionReceiptWithFilterReturn { + receipt: TransactionReceipt +} +export interface GetAllWebhookListenersArgs { + projectId?: number +} + +export interface GetAllWebhookListenersReturn { + listeners: Array +} +export interface GetBalanceUpdatesArgs { + contractAddress: string + lastBlockNumber: number + lastBlockHash?: string + page?: Page +} + +export interface GetBalanceUpdatesReturn { + page: Page + balances: Array +} +export interface GetChainIDArgs {} + +export interface GetChainIDReturn { + chainID: number +} +export interface GetEtherBalanceArgs { + accountAddress?: string +} + +export interface GetEtherBalanceReturn { + balance: EtherBalance +} +export interface GetMarketplaceOrdersArgs { + marketplaceContractAddress: string + collectionAddress: string + filter?: MarketplaceOrderFilter + page?: Page +} + +export interface GetMarketplaceOrdersReturn { + page?: Page + orders: Array +} +export interface GetMarketplaceTopOrdersArgs { + marketplaceContractAddress: string + collectionAddress: string + filter: MarketplaceTopOrdersFilter +} + +export interface GetMarketplaceTopOrdersReturn { + orders: Array +} +export interface GetNativeTokenBalanceArgs { + accountAddress?: string + omitPrices?: boolean +} + +export interface GetNativeTokenBalanceReturn { + balance: NativeTokenBalance +} +export interface GetPricesArgs { + page?: Page +} + +export interface GetPricesReturn { + page: Page + prices: Array +} +export interface GetTokenBalancesArgs { + accountAddress?: string + contractAddress?: string + tokenID?: string + includeMetadata?: boolean + metadataOptions?: MetadataOptions + includeCollectionTokens?: boolean + page?: Page +} + +export interface GetTokenBalancesReturn { + page: Page + balances: Array +} +export interface GetTokenBalancesByContractArgs { + filter: TokenBalancesByContractFilter + omitMetadata?: boolean + page?: Page +} + +export interface GetTokenBalancesByContractReturn { + page: Page + balances: Array +} +export interface GetTokenBalancesDetailsArgs { + filter: TokenBalancesFilter + omitMetadata?: boolean + page?: Page +} + +export interface GetTokenBalancesDetailsReturn { + page: Page + nativeBalances: Array + balances: Array +} +export interface GetTokenBalancesSummaryArgs { + filter: TokenBalancesFilter + omitMetadata?: boolean + page?: Page +} + +export interface GetTokenBalancesSummaryReturn { + page: Page + nativeBalances: Array + balances: Array +} +export interface GetTokenIDRangesArgs { + contractAddress: string + lastTokenID?: string +} + +export interface GetTokenIDRangesReturn { + contractType: ContractType + tokenIDRanges: Array + moreRanges: boolean +} +export interface GetTokenIDsArgs { + contractAddress: string + page?: Page +} + +export interface GetTokenIDsReturn { + page: Page + contractType: ContractType + tokenIDs: Array +} +export interface GetTokenSuppliesArgs { + contractAddress: string + includeMetadata?: boolean + metadataOptions?: MetadataOptions + page?: Page +} + +export interface GetTokenSuppliesReturn { + page: Page + contractType: ContractType + tokenIDs: Array +} +export interface GetTokenSuppliesMapArgs { + tokenMap: { [key: string]: Array } + includeMetadata?: boolean + metadataOptions?: MetadataOptions +} + +export interface GetTokenSuppliesMapReturn { + supplies: { [key: string]: Array } +} +export interface GetTransactionHistoryArgs { + filter: TransactionHistoryFilter + page?: Page + includeMetadata?: boolean + metadataOptions?: MetadataOptions +} + +export interface GetTransactionHistoryReturn { + page: Page + transactions: Array +} +export interface GetWebhookListenerArgs { + id: number + projectId?: number +} + +export interface GetWebhookListenerReturn { + listener: WebhookListener +} +export interface PauseAllWebhookListenersArgs { + projectId?: number +} + +export interface PauseAllWebhookListenersReturn { + status: boolean +} +export interface PingArgs {} + +export interface PingReturn { + status: boolean +} +export interface RemoveAllWebhookListenersArgs { + projectId?: number +} + +export interface RemoveAllWebhookListenersReturn { + status: boolean +} +export interface RemoveWebhookListenerArgs { + id: number + projectId?: number +} + +export interface RemoveWebhookListenerReturn { + status: boolean +} +export interface ResumeAllWebhookListenersArgs { + projectId?: number +} + +export interface ResumeAllWebhookListenersReturn { + status: boolean +} +export interface RuntimeStatusArgs {} + +export interface RuntimeStatusReturn { + status: RuntimeStatus +} +export interface SubscribeBalanceUpdatesArgs { + contractAddress: string +} + +export interface SubscribeBalanceUpdatesReturn { + balance: TokenBalance +} +export interface SubscribeEventsArgs { + filter: EventFilter +} + +export interface SubscribeEventsReturn { + log: EventLog +} +export interface SubscribeReceiptsArgs { + filter: TransactionFilter +} + +export interface SubscribeReceiptsReturn { + receipt: TransactionReceipt +} +export interface SyncBalanceArgs { + accountAddress: string + contractAddress: string + tokenID?: string +} + +export interface SyncBalanceReturn {} +export interface ToggleWebhookListenerArgs { + id: number + projectId?: number +} + +export interface ToggleWebhookListenerReturn { + webhookListener: WebhookListener +} +export interface UpdateWebhookListenerArgs { + listener: WebhookListener + projectId?: number +} + +export interface UpdateWebhookListenerReturn { + status: boolean +} +export interface VersionArgs {} + +export interface VersionReturn { + version: Version +} + +// +// Client +// +export class Indexer implements Indexer { + protected hostname: string + protected fetch: Fetch + protected path = '/rpc/Indexer/' + + constructor(hostname: string, fetch: Fetch) { + this.hostname = hostname.replace(/\/*$/, '') + this.fetch = (input: RequestInfo, init?: RequestInit) => fetch(input, init) + } + + private url(name: string): string { + return this.hostname + this.path + name + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + getMarketplaceOrders = ( + args: GetMarketplaceOrdersArgs, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetMarketplaceOrders'), 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 || ''}` }) + } + ) + } + + getMarketplaceTopOrders = ( + args: GetMarketplaceTopOrdersArgs, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch(this.url('GetMarketplaceTopOrders'), createHTTPRequest(args, headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return { + orders: >_data.orders + } + }) + }, + 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 || ''}` }) + } + ) + } + + getPrices = (args: GetPricesArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetPrices'), createHTTPRequest(args, headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return { + page: _data.page, + prices: >_data.prices + } + }) + }, + 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 || ''}` }) + } + ) + } + + 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 = ( + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + subscribeBalanceUpdates = ( + args: SubscribeBalanceUpdatesArgs, + 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(args, 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 = (args: SubscribeEventsArgs, 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(args, 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 = ( + args: SubscribeReceiptsArgs, + 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(args, options.headers, abortSignal)).then( + async res => { + await sseResponse(res, options, _fetch) + }, + error => { + options.onError(error, _fetch) + } + ) + + const resp = _fetch() + return { + abort: abortController.abort.bind(abortController), + closed: resp + } + } + syncBalance = (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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } +} + +const sseResponse = async (res: Response, options: WebrpcStreamOptions, retryFetch: () => Promise) => { + const { onMessage, onOpen, onClose, onError } = options + + if (!res.ok) { + try { + await buildResponse(res) + } catch (error) { + // @ts-ignore + onError(error, retryFetch) + } + return + } + + if (!res.body) { + onError( + WebrpcBadResponseError.new({ + status: res.status, + cause: 'Invalid response, missing body' + }), + retryFetch + ) + return + } + + onOpen && onOpen() + + const reader = res.body.getReader() + const decoder = new TextDecoder() + let buffer = '' + let lastReadTime = Date.now() + const timeout = (10 + 1) * 1000 + let timeoutError = false + const intervalId = setInterval(() => { + if (Date.now() - lastReadTime > timeout) { + timeoutError = true + clearInterval(intervalId) + reader.releaseLock() + } + }, timeout) + + while (true) { + let value + let done + try { + ;({ value, done } = await reader.read()) + if (timeoutError) throw new Error('Timeout, no data or heartbeat received') + lastReadTime = Date.now() + buffer += decoder.decode(value, { stream: true }) + } catch (error) { + let message = '' + if (error instanceof Error) { + message = error.message + } + + if (error instanceof DOMException && error.name === 'AbortError') { + onError( + WebrpcRequestFailedError.new({ + message: 'AbortError', + cause: `AbortError: ${message}` + }), + () => { + throw new Error('Abort signal cannot be used to reconnect') + } + ) + } else { + onError( + WebrpcStreamLostError.new({ + cause: `reader.read(): ${message}` + }), + retryFetch + ) + } + 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 + } + } catch (error) { + if (error instanceof Error && error.message === 'Abort signal cannot be used to reconnect') { + throw error + } + onError( + WebrpcBadResponseError.new({ + status: res.status, + // @ts-ignore + cause: `JSON.parse(): ${error.message}` + }), + retryFetch + ) + } + onMessage(data) + } + + if (!done) { + buffer = lines[lines.length - 1] + continue + } + + 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 buildResponse = (res: Response): Promise => { + return res.text().then(text => { + let data + try { + data = JSON.parse(text) + } catch (error) { + let message = '' + if (error instanceof Error) { + message = error.message + } + throw WebrpcBadResponseError.new({ + status: res.status, + cause: `JSON.parse(): ${message}: response text: ${text}` + }) + } + if (!res.ok) { + const code: number = typeof data.code === 'number' ? data.code : 0 + throw (webrpcErrorByCode[code] || WebrpcError).new(data) + } + return data + }) +} + +// +// Errors +// + +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 + 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) + } +} + +// 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) + 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) + 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) + 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) + 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) + 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) + 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) + 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) + 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 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) + 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) + Object.setPrototypeOf(this, WebrpcStreamFinishedError.prototype) + } +} + +// Schema errors + +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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 enum errors { + WebrpcEndpoint = 'WebrpcEndpoint', + WebrpcRequestFailed = 'WebrpcRequestFailed', + WebrpcBadRoute = 'WebrpcBadRoute', + WebrpcBadMethod = 'WebrpcBadMethod', + WebrpcBadRequest = 'WebrpcBadRequest', + WebrpcBadResponse = 'WebrpcBadResponse', + WebrpcServerPanic = 'WebrpcServerPanic', + WebrpcInternalError = 'WebrpcInternalError', + WebrpcClientDisconnected = 'WebrpcClientDisconnected', + WebrpcStreamLost = 'WebrpcStreamLost', + WebrpcStreamFinished = 'WebrpcStreamFinished', + Aborted = 'Aborted', + AccessKeyMismatch = 'AccessKeyMismatch', + AccessKeyNotFound = 'AccessKeyNotFound', + AtLeastOneKey = 'AtLeastOneKey', + Geoblocked = 'Geoblocked', + InvalidArgument = 'InvalidArgument', + InvalidOrigin = 'InvalidOrigin', + InvalidService = 'InvalidService', + MaxAccessKeys = 'MaxAccessKeys', + MetadataCallFailed = 'MetadataCallFailed', + MethodNotFound = 'MethodNotFound', + NoDefaultKey = 'NoDefaultKey', + NotFound = 'NotFound', + PermissionDenied = 'PermissionDenied', + ProjectNotFound = 'ProjectNotFound', + QueryFailed = 'QueryFailed', + QuotaExceeded = 'QuotaExceeded', + RateLimit = 'RateLimit', + RateLimited = 'RateLimited', + RequestConflict = 'RequestConflict', + ResourceExhausted = 'ResourceExhausted', + SessionExpired = 'SessionExpired', + Timeout = 'Timeout', + Unauthorized = 'Unauthorized', + UnauthorizedUser = 'UnauthorizedUser', + Unavailable = 'Unavailable' +} + +export enum WebrpcErrorCodes { + WebrpcEndpoint = 0, + WebrpcRequestFailed = -1, + WebrpcBadRoute = -2, + WebrpcBadMethod = -3, + WebrpcBadRequest = -4, + WebrpcBadResponse = -5, + WebrpcServerPanic = -6, + WebrpcInternalError = -7, + WebrpcClientDisconnected = -8, + WebrpcStreamLost = -9, + WebrpcStreamFinished = -10, + Aborted = 1005, + AccessKeyMismatch = 1102, + AccessKeyNotFound = 1101, + AtLeastOneKey = 1302, + Geoblocked = 1006, + InvalidArgument = 2001, + InvalidOrigin = 1103, + InvalidService = 1104, + MaxAccessKeys = 1301, + MetadataCallFailed = 3003, + MethodNotFound = 1003, + NoDefaultKey = 1300, + NotFound = 3000, + PermissionDenied = 1001, + ProjectNotFound = 1100, + QueryFailed = 2003, + QuotaExceeded = 1200, + RateLimit = 1201, + RateLimited = 1007, + RequestConflict = 1004, + ResourceExhausted = 2004, + SessionExpired = 1002, + Timeout = 1900, + Unauthorized = 1000, + UnauthorizedUser = 1105, + Unavailable = 2002 +} + +export const webrpcErrorByCode: { [code: number]: any } = { + [0]: WebrpcEndpointError, + [-1]: WebrpcRequestFailedError, + [-2]: WebrpcBadRouteError, + [-3]: WebrpcBadMethodError, + [-4]: WebrpcBadRequestError, + [-5]: WebrpcBadResponseError, + [-6]: WebrpcServerPanicError, + [-7]: WebrpcInternalErrorError, + [-8]: WebrpcClientDisconnectedError, + [-9]: WebrpcStreamLostError, + [-10]: WebrpcStreamFinishedError, + [1005]: AbortedError, + [1102]: AccessKeyMismatchError, + [1101]: AccessKeyNotFoundError, + [1302]: AtLeastOneKeyError, + [1006]: GeoblockedError, + [2001]: InvalidArgumentError, + [1103]: InvalidOriginError, + [1104]: InvalidServiceError, + [1301]: MaxAccessKeysError, + [3003]: MetadataCallFailedError, + [1003]: MethodNotFoundError, + [1300]: NoDefaultKeyError, + [3000]: NotFoundError, + [1001]: PermissionDeniedError, + [1100]: ProjectNotFoundError, + [2003]: QueryFailedError, + [1200]: QuotaExceededError, + [1201]: RateLimitError, + [1007]: RateLimitedError, + [1004]: RequestConflictError, + [2004]: ResourceExhaustedError, + [1002]: SessionExpiredError, + [1900]: TimeoutError, + [1000]: UnauthorizedError, + [1105]: UnauthorizedUserError, + [2002]: UnavailableError +} + +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 +} diff --git a/packages/indexer/src/indexergw.gen.ts b/packages/indexer/src/indexergw.gen.ts new file mode 100644 index 000000000..a23eb87a6 --- /dev/null +++ b/packages/indexer/src/indexergw.gen.ts @@ -0,0 +1,1715 @@ +/* eslint-disable */ +// sequence-indexer v0.4.0 9424146daac757c1b912723a9a212b419dfea11e +// -- +// Code generated by webrpc-gen@v0.25.3 with typescript generator. DO NOT EDIT. +// +// 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.25.3;gen-typescript@v0.17.0;sequence-indexer@v0.4.0' + +// WebRPC description and code-gen version +export const WebRPCVersion = 'v1' + +// Schema version of your RIDL schema +export const WebRPCSchemaVersion = 'v0.4.0' + +// Schema hash generated from your RIDL schema +export const WebRPCSchemaHash = '9424146daac757c1b912723a9a212b419dfea11e' + +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 ?? '' + } +} + +// +// Types +// + +export interface Asset { + id: number + collectionId: number + tokenId?: string + url?: string + metadataField: string + name?: string + filesize?: number + mimeType?: string + width?: number + height?: number + updatedAt?: string +} + +export interface BloomStats { + hitRatio: string + falsePositivesPercent: string + hitCount: number + missCount: number + falsePositives: number +} + +export interface BloomStatus { + enabled: boolean + initialized: boolean + bloomInitElapsedTime: string + stats: BloomStats +} + +export interface Bond { + pebble: PebbleMetrics + estimatedDiskUsagePerTable: any + estimatedDiskUsageTotal: string +} + +export interface ChainInfo { + chainId: number + chainName: string +} + +export interface ContractInfo { + chainId: number + address: string + source: string + name: string + type: string + symbol: string + decimals?: number + logoURI: string + deployed: boolean + bytecodeHash: string + extensions: ContractInfoExtensions + updatedAt: string + queuedAt?: string + status: ResourceStatus +} + +export interface 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 enum ContractType { + UNKNOWN = 'UNKNOWN', + NATIVE = 'NATIVE', + ERC20 = 'ERC20', + ERC721 = 'ERC721', + ERC1155 = 'ERC1155', + SEQUENCE_WALLET = 'SEQUENCE_WALLET', + ERC20_BRIDGE = 'ERC20_BRIDGE', + ERC721_BRIDGE = 'ERC721_BRIDGE', + ERC1155_BRIDGE = 'ERC1155_BRIDGE', + SEQ_MARKETPLACE = 'SEQ_MARKETPLACE', + ERC6909 = 'ERC6909' +} + +export enum ContractVerificationStatus { + VERIFIED = 'VERIFIED', + UNVERIFIED = 'UNVERIFIED', + ALL = 'ALL' +} + +export interface DiskUsage { + humanReadable: string + used: number + size: number + percent: number + dirs: { [key: string]: string } +} + +export interface EtherBalance { + accountAddress: string + balanceWei: string +} + +export interface EventDecoded { + topicHash: string + eventSig: string + types: Array + names: Array + values: Array +} + +export interface EventFilter { + events?: Array + contractAddresses?: Array + accounts?: Array + tokenIDs?: Array +} + +export interface EventLog { + id: number + uid: string + type: EventLogType + blockNumber: number + blockHash: string + parentBlockHash: string + contractAddress: string + contractType: ContractType + txnHash: string + txnIndex: number + txnLogIndex: number + logDataType: EventLogDataType + ts: string + txnInfo?: TxnInfo + rawLog?: { [key: string]: any } + event?: EventDecoded +} + +export enum EventLogDataType { + EVENT = 'EVENT', + TOKEN_TRANSFER = 'TOKEN_TRANSFER', + NATIVE_TOKEN_TRANSFER = 'NATIVE_TOKEN_TRANSFER', + SEQUENCE_TXN = 'SEQUENCE_TXN' +} + +export enum EventLogType { + UNKNOWN = 'UNKNOWN', + BLOCK_ADDED = 'BLOCK_ADDED', + BLOCK_REMOVED = 'BLOCK_REMOVED' +} + +export interface GatewayBackendResponseTime { + percentiles: { [key: string]: number } + average: number +} + +export interface GatewayBackendRuntimeStatus { + name: string + chainId: number + responseTime: GatewayBackendResponseTime +} + +export interface GatewayEtherBalance { + chainId: number + errorReason?: string + result: EtherBalance +} + +export interface GatewayNativeTokenBalance { + chainId: number + errorReason?: string + result: NativeTokenBalance +} + +export interface GatewayNativeTokenBalances { + chainId: number + errorReason?: string + results: Array +} + +export interface GatewayRuntimeStatus { + healthOK: boolean + startTime: string + uptime: number + ver: string + branch: string + commitHash: string + backends: Array +} + +export interface GatewayTokenBalance { + chainId: number + errorReason?: string + results: Array +} + +export interface GatewayTransaction { + chainId: number + errorReason?: string + results: Array +} + +export interface IndexState { + chainId: string + lastBlockNum: number + lastBlockHash: string +} + +export interface IndexedBlock { + blockNumber: number + blockShortHash: string +} + +export interface IndexerMetrics { + blocksPerSecond: number + eventsPerSecond: number +} + +export interface MarketplaceOrder { + orderId: string + tokenContract: string + tokenId: string + isListing: boolean + quantity: string + quantityRemaining: string + currencyAddress: string + pricePerToken: string + expiry: string + orderStatus: OrderStatus + createdBy: string + blockNumber: number + orderbookContractAddress: string + createdAt: number +} + +export interface MarketplaceOrderFilter { + isListing?: boolean + userAddresses?: Array + currencyAddresses: Array + orderIds: Array + tokenIds: Array + excludeUserAddresses?: Array + blockNumberGt: number + createdAtAfter: number + orderStatuses: Array + returnExpired: boolean +} + +export interface MarketplaceTopOrdersFilter { + currencyAddresses: Array + tokenIds: Array + isListing: boolean + priceSort: SortOrder + excludeUser?: string +} + +export interface MetadataOptions { + verifiedOnly?: boolean + unverifiedOnly?: boolean + includeContracts?: Array +} + +export interface NativeTokenBalance { + accountAddress: string + chainId: number + balance: string + balanceUSD: string + priceUSD: string + error: string +} + +export enum NetworkType { + MAINNETS = 'MAINNETS', + TESTNETS = 'TESTNETS', + ALL = 'ALL' +} + +export enum OrderStatus { + OPEN = 'OPEN', + CLOSED = 'CLOSED', + CANCELLED = 'CANCELLED' +} + +export interface Page { + page?: number + column?: string + before?: any + after?: any + sort?: Array + pageSize?: number + more?: boolean +} + +export interface PebbleMetrics { + compactionCount: number + compactionEstimatedDebt: number + compactionInProgressBytes: number + compactionNumInProgress: number + compactionMarkedFiles: number +} + +export interface Price { + contractAddress: string + tokenID?: string + priceUSD: string +} + +export enum ResourceStatus { + NOT_AVAILABLE = 'NOT_AVAILABLE', + REFRESHING = 'REFRESHING', + AVAILABLE = 'AVAILABLE' +} + +export interface RuntimeChecks { + running: boolean + runnables: any + cgoEnabled: boolean + quotaControlEnabled: boolean + syncMode: string + percentIndexed: number + lastBlockNum: number + lastBlockNumWithState: number + bloomStatus: BloomStatus + bond: Bond + diskUsage: DiskUsage + metrics: IndexerMetrics +} + +export interface RuntimeStatus { + healthOK: boolean + indexerEnabled: boolean + startTime: string + uptime: number + ver: string + branch: string + commitHash: string + chainID: number + checks: RuntimeChecks +} + +export interface SortBy { + column: string + order: SortOrder +} + +export enum SortOrder { + DESC = 'DESC', + ASC = 'ASC' +} + +export interface TokenBalance { + contractType: ContractType + contractAddress: string + accountAddress: string + tokenID?: string + balance: string + balanceUSD: string + priceUSD: string + blockHash: string + blockNumber: number + chainId: number + uniqueCollectibles: string + isSummary: boolean + contractInfo?: ContractInfo + tokenMetadata?: TokenMetadata +} + +export interface TokenBalanceFilter { + contractAddress: string + sinceBlockNumber: number +} + +export interface TokenBalancesByContractFilter { + contractAddresses: Array + accountAddresses?: Array + contractStatus?: ContractVerificationStatus +} + +export interface TokenBalancesFilter { + accountAddresses: Array + contractStatus?: ContractVerificationStatus + contractWhitelist?: Array + contractBlacklist?: Array + omitNativeBalances: boolean + omitPrices?: boolean +} + +export interface TokenHistory { + blockNumber: number + blockHash: string + contractAddress: string + contractType: ContractType + fromAddress: string + toAddress: string + txnHash: string + txnIndex: number + txnLogIndex: number + tokenIDs: string + amounts: string + ts: string +} + +export interface TokenIDRange { + start: string + end: string +} + +export interface TokenMetadata { + 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 TokenSupply { + tokenID: string + supply: string + chainId: number + contractInfo?: ContractInfo + tokenMetadata?: TokenMetadata +} + +export interface Transaction { + txnHash: string + blockNumber: number + blockHash: string + chainId: number + metaTxnID?: string + transfers?: Array + timestamp: string +} + +export interface TransactionFilter { + txnHash?: string + from?: string + to?: string + contractAddress?: string + event?: string +} + +export interface TransactionHistoryFilter { + accountAddress?: string + contractAddress?: string + accountAddresses?: Array + contractAddresses?: Array + transactionHashes?: Array + metaTransactionIDs?: Array + fromBlock?: number + toBlock?: number + tokenID?: string + omitPrices?: boolean +} + +export interface TransactionLog { + contractAddress: string + topics: Array + data: string + index: number +} + +export interface TransactionReceipt { + txnHash: string + txnStatus: TransactionStatus + txnIndex: number + txnType: TransactionType + blockHash: string + blockNumber: number + gasUsed: number + effectiveGasPrice: string + from: string + to: string + logs: Array + final: boolean + reorged: boolean +} + +export enum TransactionStatus { + FAILED = 'FAILED', + SUCCESSFUL = 'SUCCESSFUL' +} + +export enum TransactionType { + LegacyTxnType = 'LegacyTxnType', + AccessListTxnType = 'AccessListTxnType', + DynamicFeeTxnType = 'DynamicFeeTxnType' +} + +export interface TxnInfo { + from: string + to: string + value: string +} + +export interface TxnTransfer { + transferType: TxnTransferType + contractAddress: string + contractType: ContractType + from: string + to: string + tokenIds?: Array + amounts: Array + logIndex: number + amountsUSD?: Array + pricesUSD?: Array + contractInfo?: ContractInfo + tokenMetadata?: { [key: string]: TokenMetadata } +} + +export enum TxnTransferType { + UNKNOWN = 'UNKNOWN', + SEND = 'SEND', + RECEIVE = 'RECEIVE' +} + +export interface Version { + webrpcVersion: string + schemaVersion: string + schemaHash: string + appVersion: string +} + +export interface WALWriterRuntimeStatus { + healthOK: boolean + startTime: string + uptime: number + ver: string + branch: string + commitHash: string + chainID: number + percentWALWritten: number +} + +export interface WebhookListener { + id: number + projectID: number + url: string + filters: EventFilter + name: string + updatedAt: string + active: boolean +} + +export interface IndexerGateway { + /** + * 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(args: GetBalanceUpdatesArgs, headers?: object, signal?: AbortSignal): Promise + /** + * GetChains returns a list of chains with their ID and name + */ + getChains(args: GetChainsArgs, headers?: object, signal?: AbortSignal): Promise + /** + * GetNativeTokenBalance queries indexer nodes for the latest native token + * account balance. + */ + getNativeTokenBalance( + args: GetNativeTokenBalanceArgs, + 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(args: GetTokenBalancesArgs, 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( + args: GetTokenBalancesByContractArgs, + 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( + args: GetTokenBalancesDetailsArgs, + 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( + args: GetTokenBalancesSummaryArgs, + 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( + args: GetTransactionHistoryArgs, + 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 interface GetBalanceUpdatesArgs { + chainIds?: Array + networks?: Array + networkType?: NetworkType + contractAddress: string + lastBlockNumber: number + lastBlockHash?: string + page?: Page +} + +export interface GetBalanceUpdatesReturn { + page: Page + balances: Array +} +export interface GetChainsArgs { + networkType?: NetworkType +} + +export interface GetChainsReturn { + chains: Array +} +export interface GetNativeTokenBalanceArgs { + chainIds?: Array + networks?: Array + networkType?: NetworkType + accountAddress?: string + omitPrices?: boolean +} + +export interface GetNativeTokenBalanceReturn { + balances: Array +} +export interface GetTokenBalancesArgs { + chainIds?: Array + networks?: Array + networkType?: NetworkType + accountAddress?: string + contractAddress?: string + tokenID?: string + includeMetadata?: boolean + metadataOptions?: MetadataOptions + includeCollectionTokens?: boolean + page?: Page +} + +export interface GetTokenBalancesReturn { + page: Page + balances: Array +} +export interface GetTokenBalancesByContractArgs { + chainIds?: Array + networks?: Array + networkType?: NetworkType + filter: TokenBalancesByContractFilter + omitMetadata?: boolean + page?: Page +} + +export interface GetTokenBalancesByContractReturn { + page: Page + balances: Array +} +export interface GetTokenBalancesDetailsArgs { + chainIds?: Array + networks?: Array + networkType?: NetworkType + filter: TokenBalancesFilter + omitMetadata?: boolean + page?: Page +} + +export interface GetTokenBalancesDetailsReturn { + page: Page + nativeBalances: Array + balances: Array +} +export interface GetTokenBalancesSummaryArgs { + chainIds?: Array + networks?: Array + networkType?: NetworkType + filter: TokenBalancesFilter + omitMetadata?: boolean + page?: Page +} + +export interface GetTokenBalancesSummaryReturn { + page: Page + nativeBalances: Array + balances: Array +} +export interface GetTransactionHistoryArgs { + chainIds?: Array + networks?: Array + networkType?: NetworkType + filter: TransactionHistoryFilter + includeMetadata?: boolean + metadataOptions?: MetadataOptions + page?: Page +} + +export interface GetTransactionHistoryReturn { + page: Page + transactions: Array +} +export interface PingArgs {} + +export interface PingReturn { + status: boolean +} +export interface RuntimeStatusArgs {} + +export interface RuntimeStatusReturn { + status: GatewayRuntimeStatus +} +export interface VersionArgs {} + +export interface VersionReturn { + version: Version +} + +// +// Client +// +export class IndexerGateway implements IndexerGateway { + protected hostname: string + protected fetch: Fetch + protected path = '/rpc/IndexerGateway/' + + constructor(hostname: string, fetch: Fetch) { + this.hostname = hostname.replace(/\/*$/, '') + this.fetch = (input: RequestInfo, init?: RequestInit) => fetch(input, init) + } + + private url(name: string): string { + return this.hostname + this.path + name + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 = ( + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } + + 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 || ''}` }) + } + ) + } +} + +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 buildResponse = (res: Response): Promise => { + return res.text().then(text => { + let data + try { + data = JSON.parse(text) + } catch (error) { + let message = '' + if (error instanceof Error) { + message = error.message + } + throw WebrpcBadResponseError.new({ + status: res.status, + cause: `JSON.parse(): ${message}: response text: ${text}` + }) + } + if (!res.ok) { + const code: number = typeof data.code === 'number' ? data.code : 0 + throw (webrpcErrorByCode[code] || WebrpcError).new(data) + } + return data + }) +} + +// +// Errors +// + +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 + 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) + } +} + +// 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) + 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) + 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) + 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) + 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) + 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) + 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) + 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) + 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 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) + 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) + Object.setPrototypeOf(this, WebrpcStreamFinishedError.prototype) + } +} + +// Schema errors + +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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 enum errors { + WebrpcEndpoint = 'WebrpcEndpoint', + WebrpcRequestFailed = 'WebrpcRequestFailed', + WebrpcBadRoute = 'WebrpcBadRoute', + WebrpcBadMethod = 'WebrpcBadMethod', + WebrpcBadRequest = 'WebrpcBadRequest', + WebrpcBadResponse = 'WebrpcBadResponse', + WebrpcServerPanic = 'WebrpcServerPanic', + WebrpcInternalError = 'WebrpcInternalError', + WebrpcClientDisconnected = 'WebrpcClientDisconnected', + WebrpcStreamLost = 'WebrpcStreamLost', + WebrpcStreamFinished = 'WebrpcStreamFinished', + Aborted = 'Aborted', + AccessKeyMismatch = 'AccessKeyMismatch', + AccessKeyNotFound = 'AccessKeyNotFound', + AtLeastOneKey = 'AtLeastOneKey', + Geoblocked = 'Geoblocked', + InvalidArgument = 'InvalidArgument', + InvalidOrigin = 'InvalidOrigin', + InvalidService = 'InvalidService', + MaxAccessKeys = 'MaxAccessKeys', + MetadataCallFailed = 'MetadataCallFailed', + MethodNotFound = 'MethodNotFound', + NoDefaultKey = 'NoDefaultKey', + NotFound = 'NotFound', + PermissionDenied = 'PermissionDenied', + ProjectNotFound = 'ProjectNotFound', + QueryFailed = 'QueryFailed', + QuotaExceeded = 'QuotaExceeded', + RateLimit = 'RateLimit', + RateLimited = 'RateLimited', + RequestConflict = 'RequestConflict', + ResourceExhausted = 'ResourceExhausted', + SessionExpired = 'SessionExpired', + Timeout = 'Timeout', + Unauthorized = 'Unauthorized', + UnauthorizedUser = 'UnauthorizedUser', + Unavailable = 'Unavailable' +} + +export enum WebrpcErrorCodes { + WebrpcEndpoint = 0, + WebrpcRequestFailed = -1, + WebrpcBadRoute = -2, + WebrpcBadMethod = -3, + WebrpcBadRequest = -4, + WebrpcBadResponse = -5, + WebrpcServerPanic = -6, + WebrpcInternalError = -7, + WebrpcClientDisconnected = -8, + WebrpcStreamLost = -9, + WebrpcStreamFinished = -10, + Aborted = 1005, + AccessKeyMismatch = 1102, + AccessKeyNotFound = 1101, + AtLeastOneKey = 1302, + Geoblocked = 1006, + InvalidArgument = 2001, + InvalidOrigin = 1103, + InvalidService = 1104, + MaxAccessKeys = 1301, + MetadataCallFailed = 3003, + MethodNotFound = 1003, + NoDefaultKey = 1300, + NotFound = 3000, + PermissionDenied = 1001, + ProjectNotFound = 1100, + QueryFailed = 2003, + QuotaExceeded = 1200, + RateLimit = 1201, + RateLimited = 1007, + RequestConflict = 1004, + ResourceExhausted = 2004, + SessionExpired = 1002, + Timeout = 1900, + Unauthorized = 1000, + UnauthorizedUser = 1105, + Unavailable = 2002 +} + +export const webrpcErrorByCode: { [code: number]: any } = { + [0]: WebrpcEndpointError, + [-1]: WebrpcRequestFailedError, + [-2]: WebrpcBadRouteError, + [-3]: WebrpcBadMethodError, + [-4]: WebrpcBadRequestError, + [-5]: WebrpcBadResponseError, + [-6]: WebrpcServerPanicError, + [-7]: WebrpcInternalErrorError, + [-8]: WebrpcClientDisconnectedError, + [-9]: WebrpcStreamLostError, + [-10]: WebrpcStreamFinishedError, + [1005]: AbortedError, + [1102]: AccessKeyMismatchError, + [1101]: AccessKeyNotFoundError, + [1302]: AtLeastOneKeyError, + [1006]: GeoblockedError, + [2001]: InvalidArgumentError, + [1103]: InvalidOriginError, + [1104]: InvalidServiceError, + [1301]: MaxAccessKeysError, + [3003]: MetadataCallFailedError, + [1003]: MethodNotFoundError, + [1300]: NoDefaultKeyError, + [3000]: NotFoundError, + [1001]: PermissionDeniedError, + [1100]: ProjectNotFoundError, + [2003]: QueryFailedError, + [1200]: QuotaExceededError, + [1201]: RateLimitError, + [1007]: RateLimitedError, + [1004]: RequestConflictError, + [2004]: ResourceExhaustedError, + [1002]: SessionExpiredError, + [1900]: TimeoutError, + [1000]: UnauthorizedError, + [1105]: UnauthorizedUserError, + [2002]: UnavailableError +} + +export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise