From d20dd050b44bb3fe2e59bcf356fa5601ead59f07 Mon Sep 17 00:00:00 2001 From: marino39 <722509+marino39@users.noreply.github.com> Date: Fri, 17 Oct 2025 13:54:22 +0000 Subject: [PATCH 1/8] [AUTOMATED] Update: proto/clients/indexer*.gen.ts --- packages/indexer/src/indexer.gen.ts | 2658 +++++++++++++++++++++++++ packages/indexer/src/indexergw.gen.ts | 1715 ++++++++++++++++ 2 files changed, 4373 insertions(+) create mode 100644 packages/indexer/src/indexer.gen.ts create mode 100644 packages/indexer/src/indexergw.gen.ts 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 From b920e59c5432099104e5e30586ae8fe084655865 Mon Sep 17 00:00:00 2001 From: marino39 <722509+marino39@users.noreply.github.com> Date: Tue, 18 Nov 2025 09:04:16 +0000 Subject: [PATCH 2/8] [AUTOMATED] Update: proto/clients/indexer*.gen.ts --- packages/indexer/src/indexer.gen.ts | 2662 +++++++++++++------------ packages/indexer/src/indexergw.gen.ts | 1155 +++++------ 2 files changed, 1970 insertions(+), 1847 deletions(-) diff --git a/packages/indexer/src/indexer.gen.ts b/packages/indexer/src/indexer.gen.ts index e9104a103..08004d443 100644 --- a/packages/indexer/src/indexer.gen.ts +++ b/packages/indexer/src/indexer.gen.ts @@ -1,299 +1,570 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 6950eb4778c44c2e495457ea489e1e08ce2067c0 +// sequence-indexer v0.4.0 42b746c7de262224143cc5c55403e7619c514ec4 // -- -// Code generated by webrpc-gen@v0.25.3 with typescript generator. DO NOT EDIT. +// Code generated by Webrpc-gen@v0.31.0 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' +// Webrpc description and code-gen version +export const WebrpcVersion = 'v1' // Schema version of your RIDL schema -export const WebRPCSchemaVersion = 'v0.4.0' +export const WebrpcSchemaVersion = 'v0.4.0' // Schema hash generated from your RIDL schema -export const WebRPCSchemaHash = '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 ?? '' - } -} +export const WebrpcSchemaHash = '42b746c7de262224143cc5c55403e7619c514ec4' // -// Types +// Client interface // -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 IndexerClient { + addWebhookListener(req: AddWebhookListenerRequest, headers?: object, signal?: AbortSignal): Promise -export interface BloomStatus { - enabled: boolean - initialized: boolean - bloomInitElapsedTime: string - stats: BloomStats -} + /** + * Fetches a single receipt and then will stop the subscription + */ + fetchTransactionReceipt( + req: FetchTransactionReceiptRequest, + headers?: object, + signal?: AbortSignal + ): Promise -export interface Bond { - pebble: PebbleMetrics - estimatedDiskUsagePerTable: any - estimatedDiskUsageTotal: string -} + /** + * Fetches a single receipt with filter and then will stop the subscription + */ + fetchTransactionReceiptWithFilter( + req: FetchTransactionReceiptWithFilterRequest, + headers?: object, + signal?: AbortSignal + ): Promise -export interface ChainInfo { - chainId: number - chainName: string -} + /** + * Webhooks + */ + getAllWebhookListeners( + req: GetAllWebhookListenersRequest, + headers?: object, + signal?: AbortSignal + ): Promise -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 -} + /** + * Get balance update aggregate values -- useful for syncing balance details of a contract, ie. from Skyweaver. + * Also consider using SubscribeBalanceUpdates or SubscribeEvents as other alternatives. + */ + getBalanceUpdates(req: GetBalanceUpdatesRequest, headers?: object, signal?: AbortSignal): Promise -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 -} + /** + * Get the chain ID of the indexer + */ + getChainID(headers?: object, signal?: AbortSignal): Promise -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' -} + /** + * Queries an ethereum node for the latest and confirm ETH balances + * DEPRECATED: use GetNativeTokenBalance instead + * + * @deprecated GetNativeTokenBalance + */ + getEtherBalance(req: GetEtherBalanceRequest, headers?: object, signal?: AbortSignal): Promise -export enum ContractVerificationStatus { - VERIFIED = 'VERIFIED', - UNVERIFIED = 'UNVERIFIED', - ALL = 'ALL' -} + /** + * GetMarketplaceOrders queries marketplace orders with filtering and pagination. + * + * Retrieves buy orders (offers) and sell orders (listings) from a specific marketplace + * and collection with comprehensive filtering options. + * + * Parameters: + * marketplaceContractAddress: Target marketplace contract (required) + * collectionAddress: NFT collection contract (required) + * filter: MarketplaceOrderFilter with options: + * - isListing: true=listings, false=offers, omit=both + * - userAddresses: Include specific users + * - currencyAddresses: Filter by currencies (empty=all) + * - orderIds: Filter by specific order ids (empty=all) + * - tokenIds: Filter by specific tokens (empty=all) + * - excludeUserAddresses: Exclude specific users + * - blockNumberGt: Orders greater than block number + * - createdAtAfter: Orders after timestamp + * - orderStatuses: Filter by status (OPEN, CLOSED, CANCELLED) + * - returnExpired: Include expired orders + * page: Pagination control (optional) + * + * Returns: Updated pagination info and array of matching orders + */ + getMarketplaceOrders( + req: GetMarketplaceOrdersRequest, + headers?: object, + signal?: AbortSignal + ): Promise -export interface DiskUsage { - humanReadable: string - used: number - size: number - percent: number - dirs: { [key: string]: string } -} + /** + * GetMarketplaceTopOrders finds the most competitive orders for specific tokens. + * + * Optimized for price discovery, returns the best available orders for each token. + * Useful for displaying current market prices and finding trading opportunities. + * + * Parameters: + * marketplaceContractAddress: Target marketplace contract (required) + * collectionAddress: NFT collection contract (required) + * filter: MarketplaceTopOrdersFilter with options: + * - currencyAddresses: Consider specific currencies (empty=all) + * - tokenIds: Target token IDs (required, non-empty) + * - isListing: true=listings/sell orders, false=offers/buy orders + * - priceSort: ASC=lowest first, DESC=highest first + * - excludeUser: Hide orders from specific user + * + * Returns: Array of top-priced active orders, sorted by priceSort preference + */ + getMarketplaceTopOrders( + req: GetMarketplaceTopOrdersRequest, + headers?: object, + signal?: AbortSignal + ): Promise -export interface EtherBalance { - accountAddress: string - balanceWei: string -} + /** + * GetNativeTokenBalance queries an ethereum node for the latest native token account balance. + * The native token is the token of the chain the indexer is connected to, for example, ETH on Ethereum + * and POL on Polygon. + */ + getNativeTokenBalance( + req: GetNativeTokenBalanceRequest, + headers?: object, + signal?: AbortSignal + ): Promise -export interface EventDecoded { - topicHash: string - eventSig: string - types: Array - names: Array - values: Array -} + getPrices(req: GetPricesRequest, headers?: object, signal?: AbortSignal): Promise -export interface EventFilter { - events?: Array - contractAddresses?: Array - accounts?: Array - tokenIDs?: Array -} + /** + * GetTokenBalances returns a balance summary/details for a specific account. By default + * if accountAddress is left empty, it will use the account from the jwt session. + * + * Also, if contractAddress is undefined, then it will list all current user coins/collectibles. + * But, if contractAddress is provided, then it will return the token balances for the contract, this is + * only useful for 1155, but for other tokens, it can act as a filter for the single balance. + * + * DEPRECATED: use GetTokenBalancesSummary / GetTokenBalancesDetails + * + * @deprecated GetTokenBalancesSummary + */ + getTokenBalances(req: GetTokenBalancesRequest, headers?: object, signal?: AbortSignal): Promise -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 -} + /** + * GetTokenBalancesByContract returns a balances for a specific accounts and + * contracts. The collection ERC721 & ERC1155 tokens are represented as + * individual balances. + * + * If `filter` is not provided, it will error out as it requires at least + * contract address. + * + * If `filter.contractStatus` is not provided, it will include verified only + * tokens. + */ + getTokenBalancesByContract( + req: GetTokenBalancesByContractRequest, + headers?: object, + signal?: AbortSignal + ): Promise -export enum EventLogDataType { - EVENT = 'EVENT', - TOKEN_TRANSFER = 'TOKEN_TRANSFER', - NATIVE_TOKEN_TRANSFER = 'NATIVE_TOKEN_TRANSFER', - SEQUENCE_TXN = 'SEQUENCE_TXN' -} + /** + * GetTokenBalancesDetails returns a detailed balance summary for a specific + * accounts. The collection ERC721 & ERC1155 tokens are represented as + * individual balances. + * + * If `filter` is not provided, it will use the filter with account from the + * jwt session. + * + * If `filter.contractStatus` is not provided, it will include verified only + * tokens. + */ + getTokenBalancesDetails( + req: GetTokenBalancesDetailsRequest, + headers?: object, + signal?: AbortSignal + ): Promise -export enum EventLogType { - UNKNOWN = 'UNKNOWN', - BLOCK_ADDED = 'BLOCK_ADDED', - BLOCK_REMOVED = 'BLOCK_REMOVED' -} + /** + * GetTokenBalancesSummary returns a summary of token balances for a specific + * accounts. The collection ERC721 & ERC1155 tokens are represented as a + * single aggregated balance. + * + * If `filter` is not provided, it will use the filter with account from the + * jwt session. + * + * If `filter.contractStatus` is not provided, it will include verified only + * tokens. + */ + getTokenBalancesSummary( + req: GetTokenBalancesSummaryRequest, + headers?: object, + signal?: AbortSignal + ): Promise -export interface GatewayBackendResponseTime { - percentiles: { [key: string]: number } - average: number -} + /** + * GetTokenIDRanges returns the range of tokenIDs for a token collection contract. + * This is useful for ERC-721 and ERC-1155 contracts to get the range of valid tokenIDs. It is similar to + * GetTokenIDs, but returns the range of tokenIDs instead of the list of tokenIDs, which is more efficient + * for large collections and very easy to the caller to expand the range into a list of tokenIDs. + * + * NOTE: this method will only return up to 15,000 ranges, if there are more ranges, it will return + * a boolean to indicate there are more ranges beyond the first 15,000. Therefore, if `moreRanges` is + * false then you have all the ranges, but if true, you need to make a follow up call to fetch the next + * page of ranges. + * + * As an example, if a NFT collection of 100,000 tokens uses ids from 1,2,3,...,100_000 then this endpoint + * will return just a single range from [1,100_000], but if there are gaps between the sequence, then + * those will be broken into separate range entries. + */ + getTokenIDRanges(req: GetTokenIDRangesRequest, headers?: object, signal?: AbortSignal): Promise -export interface GatewayBackendRuntimeStatus { - name: string - chainId: number - responseTime: GatewayBackendResponseTime -} + /** + * GetTokenIDs returns the list of each individual token id for a token collection contract. + * This is useful for ERC-721 and ERC-1155 contracts to get the list of valid tokenIDs. + */ + getTokenIDs(req: GetTokenIDsRequest, headers?: object, signal?: AbortSignal): Promise -export interface GatewayEtherBalance { - chainId: number - errorReason?: string - result: EtherBalance -} + /** + * GetTokenSupplies returns the set of tokenIDs used by a contract address, supporting ERC-20, ERC-721, and ERC-1155 + * contracts, and their respective supply as well. + */ + getTokenSupplies(req: GetTokenSuppliesRequest, headers?: object, signal?: AbortSignal): Promise -export interface GatewayNativeTokenBalance { - chainId: number - errorReason?: string - result: NativeTokenBalance -} + /** + * GetTokenSuppliesMap returns the token supplies of ERC-20 and ERC-1155 tokens as requested in the `tokenMap` + * represented as a map of contractAddress :: []tokenIDs. + * + * For an ERC-20 specify tokenIDs as an empty array or [0], for example, { '0xdef': [] } or { '0xdef': [0] } + * For ERC-1155 pass the array of tokens are strings, ie. { '0xabc': ['1', '2', '3'] } + */ + getTokenSuppliesMap( + req: GetTokenSuppliesMapRequest, + headers?: object, + signal?: AbortSignal + ): Promise -export interface GatewayNativeTokenBalances { - chainId: number - errorReason?: string - results: Array -} + /** + * History of mined transactions for the account which includes a list of token transfers (sent/recieved) + * and sent transactions from a Sequence wallet + */ + getTransactionHistory( + req: GetTransactionHistoryRequest, + headers?: object, + signal?: AbortSignal + ): Promise -export interface GatewayRuntimeStatus { - healthOK: boolean - startTime: string - uptime: number - ver: string - branch: string - commitHash: string - backends: Array + getWebhookListener(req: GetWebhookListenerRequest, headers?: object, signal?: AbortSignal): Promise + + pauseAllWebhookListeners( + req: PauseAllWebhookListenersRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * Ping the indexer + */ + ping(headers?: object, signal?: AbortSignal): Promise + + removeAllWebhookListeners( + req: RemoveAllWebhookListenersRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + removeWebhookListener( + req: RemoveWebhookListenerRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + resumeAllWebhookListeners( + req: ResumeAllWebhookListenersRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * Get the current runtime health status of the indexer + */ + runtimeStatus(headers?: object, signal?: AbortSignal): Promise + + /** + * SubscribeBalanceUpdates listens to balance updates for a specific contract address + */ + subscribeBalanceUpdates( + req: SubscribeBalanceUpdatesRequest, + options: WebrpcStreamOptions + ): WebrpcStreamController + + /** + * SubscribeEvents listens to events on-chain based on the filter criteria + * + * TODO: some additional options can be passed such as block, reorg true, etc. + * or stay behind, etc. + */ + subscribeEvents(req: SubscribeEventsRequest, options: WebrpcStreamOptions): WebrpcStreamController + + /** + * Listen to transaction receipts on-chain based on the filter criteria + */ + subscribeReceipts( + req: SubscribeReceiptsRequest, + options: WebrpcStreamOptions + ): WebrpcStreamController + + /** + * Re-sync an incorrect token balance with the correct on-chain balance + * NOTE: this method is almost never used, but we've marked it internal in case + * we ever want to use it again. This method was written a very long time ago in + * scenarios when the indexer had little bugs, but now its solid. + */ + syncBalance(req: SyncBalanceRequest, headers?: object, signal?: AbortSignal): Promise + + toggleWebhookListener( + req: ToggleWebhookListenerRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + updateWebhookListener( + req: UpdateWebhookListenerRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * Get the current version of the indexer + */ + version(headers?: object, signal?: AbortSignal): Promise } -export interface GatewayTokenBalance { - chainId: number - errorReason?: string - results: Array +// +// Schema types +// + +export interface Asset { + id: number + collectionId: number + tokenId?: string + url?: string + metadataField: string + name?: string + filesize?: number + mimeType?: string + width?: number + height?: number + updatedAt?: string } -export interface GatewayTransaction { - chainId: number - errorReason?: string - results: Array +export interface BloomStats { + hitRatio: string + falsePositivesPercent: string + hitCount: number + missCount: number + falsePositives: number } -export interface IndexState { - chainId: string - lastBlockNum: number - lastBlockHash: string +export interface BloomStatus { + enabled: boolean + initialized: boolean + bloomInitElapsedTime: string + stats: BloomStats } -export interface IndexedBlock { - blockNumber: number - blockShortHash: string +export interface Bond { + pebble: PebbleMetrics + estimatedDiskUsagePerTable: any + estimatedDiskUsageTotal: string } -export interface IndexerMetrics { - blocksPerSecond: number - eventsPerSecond: number +export interface ChainInfo { + chainId: number + chainName: string } -export interface MarketplaceOrder { - orderId: string - tokenContract: string - tokenId: string - isListing: boolean +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 @@ -336,10 +607,12 @@ export interface MetadataOptions { export interface NativeTokenBalance { accountAddress: string chainId: number + name: string + symbol: string balance: string balanceUSD: string priceUSD: string - error: string + errorReason?: string } export enum NetworkType { @@ -452,6 +725,7 @@ export interface TokenBalancesByContractFilter { export interface TokenBalancesFilter { accountAddresses: Array contractStatus?: ContractVerificationStatus + contractTypes?: Array contractWhitelist?: Array contractBlacklist?: Array omitNativeBalances: boolean @@ -537,470 +811,202 @@ export interface TransactionHistoryFilter { 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 + 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 AddWebhookListenerArgs { +export interface WebhookListener { + id: number + projectID: number + url: string + filters: EventFilter + name: string + updatedAt: string + active: boolean +} + +export interface AddWebhookListenerRequest { url: string filters: EventFilter projectId?: number } -export interface AddWebhookListenerReturn { +export interface AddWebhookListenerResponse { status: boolean listener: WebhookListener } -export interface FetchTransactionReceiptArgs { + +export interface FetchTransactionReceiptRequest { txnHash: string maxBlockWait?: number } -export interface FetchTransactionReceiptReturn { +export interface FetchTransactionReceiptResponse { receipt: TransactionReceipt } -export interface FetchTransactionReceiptWithFilterArgs { + +export interface FetchTransactionReceiptWithFilterRequest { filter: TransactionFilter maxBlockWait?: number } -export interface FetchTransactionReceiptWithFilterReturn { +export interface FetchTransactionReceiptWithFilterResponse { receipt: TransactionReceipt } -export interface GetAllWebhookListenersArgs { + +export interface GetAllWebhookListenersRequest { projectId?: number } -export interface GetAllWebhookListenersReturn { +export interface GetAllWebhookListenersResponse { listeners: Array } -export interface GetBalanceUpdatesArgs { + +export interface GetBalanceUpdatesRequest { contractAddress: string lastBlockNumber: number lastBlockHash?: string page?: Page } -export interface GetBalanceUpdatesReturn { +export interface GetBalanceUpdatesResponse { page: Page balances: Array } -export interface GetChainIDArgs {} -export interface GetChainIDReturn { +export interface GetChainIDRequest {} + +export interface GetChainIDResponse { chainID: number } -export interface GetEtherBalanceArgs { + +export interface GetEtherBalanceRequest { accountAddress?: string } -export interface GetEtherBalanceReturn { +export interface GetEtherBalanceResponse { balance: EtherBalance } -export interface GetMarketplaceOrdersArgs { + +export interface GetMarketplaceOrdersRequest { marketplaceContractAddress: string collectionAddress: string filter?: MarketplaceOrderFilter page?: Page } -export interface GetMarketplaceOrdersReturn { +export interface GetMarketplaceOrdersResponse { page?: Page orders: Array } -export interface GetMarketplaceTopOrdersArgs { + +export interface GetMarketplaceTopOrdersRequest { marketplaceContractAddress: string collectionAddress: string filter: MarketplaceTopOrdersFilter } -export interface GetMarketplaceTopOrdersReturn { +export interface GetMarketplaceTopOrdersResponse { orders: Array } -export interface GetNativeTokenBalanceArgs { + +export interface GetNativeTokenBalanceRequest { accountAddress?: string omitPrices?: boolean } -export interface GetNativeTokenBalanceReturn { +export interface GetNativeTokenBalanceResponse { balance: NativeTokenBalance } -export interface GetPricesArgs { + +export interface GetPricesRequest { page?: Page } -export interface GetPricesReturn { +export interface GetPricesResponse { page: Page prices: Array } -export interface GetTokenBalancesArgs { + +export interface GetTokenBalancesRequest { accountAddress?: string contractAddress?: string tokenID?: string @@ -1010,195 +1016,218 @@ export interface GetTokenBalancesArgs { page?: Page } -export interface GetTokenBalancesReturn { +export interface GetTokenBalancesResponse { page: Page balances: Array } -export interface GetTokenBalancesByContractArgs { + +export interface GetTokenBalancesByContractRequest { filter: TokenBalancesByContractFilter omitMetadata?: boolean page?: Page } -export interface GetTokenBalancesByContractReturn { +export interface GetTokenBalancesByContractResponse { page: Page balances: Array } -export interface GetTokenBalancesDetailsArgs { + +export interface GetTokenBalancesDetailsRequest { filter: TokenBalancesFilter omitMetadata?: boolean page?: Page } -export interface GetTokenBalancesDetailsReturn { +export interface GetTokenBalancesDetailsResponse { page: Page nativeBalances: Array balances: Array } -export interface GetTokenBalancesSummaryArgs { + +export interface GetTokenBalancesSummaryRequest { filter: TokenBalancesFilter omitMetadata?: boolean page?: Page } -export interface GetTokenBalancesSummaryReturn { +export interface GetTokenBalancesSummaryResponse { page: Page nativeBalances: Array balances: Array } -export interface GetTokenIDRangesArgs { + +export interface GetTokenIDRangesRequest { contractAddress: string lastTokenID?: string } -export interface GetTokenIDRangesReturn { +export interface GetTokenIDRangesResponse { contractType: ContractType tokenIDRanges: Array moreRanges: boolean } -export interface GetTokenIDsArgs { + +export interface GetTokenIDsRequest { contractAddress: string page?: Page } -export interface GetTokenIDsReturn { +export interface GetTokenIDsResponse { page: Page contractType: ContractType tokenIDs: Array } -export interface GetTokenSuppliesArgs { + +export interface GetTokenSuppliesRequest { contractAddress: string includeMetadata?: boolean metadataOptions?: MetadataOptions page?: Page } -export interface GetTokenSuppliesReturn { +export interface GetTokenSuppliesResponse { page: Page contractType: ContractType tokenIDs: Array } -export interface GetTokenSuppliesMapArgs { + +export interface GetTokenSuppliesMapRequest { tokenMap: { [key: string]: Array } includeMetadata?: boolean metadataOptions?: MetadataOptions } -export interface GetTokenSuppliesMapReturn { +export interface GetTokenSuppliesMapResponse { supplies: { [key: string]: Array } } -export interface GetTransactionHistoryArgs { + +export interface GetTransactionHistoryRequest { filter: TransactionHistoryFilter page?: Page includeMetadata?: boolean metadataOptions?: MetadataOptions } -export interface GetTransactionHistoryReturn { +export interface GetTransactionHistoryResponse { page: Page transactions: Array } -export interface GetWebhookListenerArgs { + +export interface GetWebhookListenerRequest { id: number projectId?: number } -export interface GetWebhookListenerReturn { +export interface GetWebhookListenerResponse { listener: WebhookListener } -export interface PauseAllWebhookListenersArgs { + +export interface PauseAllWebhookListenersRequest { projectId?: number } -export interface PauseAllWebhookListenersReturn { +export interface PauseAllWebhookListenersResponse { status: boolean } -export interface PingArgs {} -export interface PingReturn { +export interface PingRequest {} + +export interface PingResponse { status: boolean } -export interface RemoveAllWebhookListenersArgs { + +export interface RemoveAllWebhookListenersRequest { projectId?: number } -export interface RemoveAllWebhookListenersReturn { +export interface RemoveAllWebhookListenersResponse { status: boolean } -export interface RemoveWebhookListenerArgs { + +export interface RemoveWebhookListenerRequest { id: number projectId?: number } -export interface RemoveWebhookListenerReturn { +export interface RemoveWebhookListenerResponse { status: boolean } -export interface ResumeAllWebhookListenersArgs { + +export interface ResumeAllWebhookListenersRequest { projectId?: number } -export interface ResumeAllWebhookListenersReturn { +export interface ResumeAllWebhookListenersResponse { status: boolean } -export interface RuntimeStatusArgs {} -export interface RuntimeStatusReturn { +export interface RuntimeStatusRequest {} + +export interface RuntimeStatusResponse { status: RuntimeStatus } -export interface SubscribeBalanceUpdatesArgs { + +export interface SubscribeBalanceUpdatesRequest { contractAddress: string } -export interface SubscribeBalanceUpdatesReturn { +export interface SubscribeBalanceUpdatesResponse { balance: TokenBalance } -export interface SubscribeEventsArgs { + +export interface SubscribeEventsRequest { filter: EventFilter } -export interface SubscribeEventsReturn { +export interface SubscribeEventsResponse { log: EventLog } -export interface SubscribeReceiptsArgs { + +export interface SubscribeReceiptsRequest { filter: TransactionFilter } -export interface SubscribeReceiptsReturn { +export interface SubscribeReceiptsResponse { receipt: TransactionReceipt } -export interface SyncBalanceArgs { + +export interface SyncBalanceRequest { accountAddress: string contractAddress: string tokenID?: string } -export interface SyncBalanceReturn {} -export interface ToggleWebhookListenerArgs { +export interface SyncBalanceResponse {} + +export interface ToggleWebhookListenerRequest { id: number projectId?: number } -export interface ToggleWebhookListenerReturn { +export interface ToggleWebhookListenerResponse { webhookListener: WebhookListener } -export interface UpdateWebhookListenerArgs { + +export interface UpdateWebhookListenerRequest { listener: WebhookListener projectId?: number } -export interface UpdateWebhookListenerReturn { +export interface UpdateWebhookListenerResponse { status: boolean } -export interface VersionArgs {} -export interface VersionReturn { +export interface VersionRequest {} + +export interface VersionResponse { version: Version } // // Client // -export class Indexer implements Indexer { + +export class Indexer implements IndexerClient { protected hostname: string protected fetch: Fetch protected path = '/rpc/Indexer/' @@ -1212,499 +1241,549 @@ export class Indexer implements Indexer { return this.hostname + this.path + name } + queryKey = { + addWebhookListener: (req: AddWebhookListenerRequest) => ['Indexer', 'addWebhookListener', req] as const, + fetchTransactionReceipt: (req: FetchTransactionReceiptRequest) => ['Indexer', 'fetchTransactionReceipt', req] as const, + fetchTransactionReceiptWithFilter: (req: FetchTransactionReceiptWithFilterRequest) => + ['Indexer', 'fetchTransactionReceiptWithFilter', req] as const, + getAllWebhookListeners: (req: GetAllWebhookListenersRequest) => ['Indexer', 'getAllWebhookListeners', req] as const, + getBalanceUpdates: (req: GetBalanceUpdatesRequest) => ['Indexer', 'getBalanceUpdates', req] as const, + getChainID: () => ['Indexer', 'getChainID'] as const, + getEtherBalance: (req: GetEtherBalanceRequest) => ['Indexer', 'getEtherBalance', req] as const, + getMarketplaceOrders: (req: GetMarketplaceOrdersRequest) => ['Indexer', 'getMarketplaceOrders', req] as const, + getMarketplaceTopOrders: (req: GetMarketplaceTopOrdersRequest) => ['Indexer', 'getMarketplaceTopOrders', req] as const, + getNativeTokenBalance: (req: GetNativeTokenBalanceRequest) => ['Indexer', 'getNativeTokenBalance', req] as const, + getPrices: (req: GetPricesRequest) => ['Indexer', 'getPrices', req] as const, + getTokenBalances: (req: GetTokenBalancesRequest) => ['Indexer', 'getTokenBalances', req] as const, + getTokenBalancesByContract: (req: GetTokenBalancesByContractRequest) => + ['Indexer', 'getTokenBalancesByContract', req] as const, + getTokenBalancesDetails: (req: GetTokenBalancesDetailsRequest) => ['Indexer', 'getTokenBalancesDetails', req] as const, + getTokenBalancesSummary: (req: GetTokenBalancesSummaryRequest) => ['Indexer', 'getTokenBalancesSummary', req] as const, + getTokenIDRanges: (req: GetTokenIDRangesRequest) => ['Indexer', 'getTokenIDRanges', req] as const, + getTokenIDs: (req: GetTokenIDsRequest) => ['Indexer', 'getTokenIDs', req] as const, + getTokenSupplies: (req: GetTokenSuppliesRequest) => ['Indexer', 'getTokenSupplies', req] as const, + getTokenSuppliesMap: (req: GetTokenSuppliesMapRequest) => ['Indexer', 'getTokenSuppliesMap', req] as const, + getTransactionHistory: (req: GetTransactionHistoryRequest) => ['Indexer', 'getTransactionHistory', req] as const, + getWebhookListener: (req: GetWebhookListenerRequest) => ['Indexer', 'getWebhookListener', req] as const, + pauseAllWebhookListeners: (req: PauseAllWebhookListenersRequest) => ['Indexer', 'pauseAllWebhookListeners', req] as const, + ping: () => ['Indexer', 'ping'] as const, + removeAllWebhookListeners: (req: RemoveAllWebhookListenersRequest) => ['Indexer', 'removeAllWebhookListeners', req] as const, + removeWebhookListener: (req: RemoveWebhookListenerRequest) => ['Indexer', 'removeWebhookListener', req] as const, + resumeAllWebhookListeners: (req: ResumeAllWebhookListenersRequest) => ['Indexer', 'resumeAllWebhookListeners', req] as const, + runtimeStatus: () => ['Indexer', 'runtimeStatus'] as const, + subscribeBalanceUpdates: (req: SubscribeBalanceUpdatesRequest) => ['Indexer', 'subscribeBalanceUpdates', req] as const, + subscribeEvents: (req: SubscribeEventsRequest) => ['Indexer', 'subscribeEvents', req] as const, + subscribeReceipts: (req: SubscribeReceiptsRequest) => ['Indexer', 'subscribeReceipts', req] as const, + syncBalance: (req: SyncBalanceRequest) => ['Indexer', 'syncBalance', req] as const, + toggleWebhookListener: (req: ToggleWebhookListenerRequest) => ['Indexer', 'toggleWebhookListener', req] as const, + updateWebhookListener: (req: UpdateWebhookListenerRequest) => ['Indexer', 'updateWebhookListener', req] as const, + version: () => ['Indexer', 'version'] as const + } + addWebhookListener = ( - args: AddWebhookListenerArgs, + req: AddWebhookListenerRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('AddWebhookListener'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('AddWebhookListener'), + createHttpRequest(JsonEncode(req, 'AddWebhookListenerRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - status: _data.status, - listener: _data.listener - } + return JsonDecode(_data, 'AddWebhookListenerResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } fetchTransactionReceipt = ( - args: FetchTransactionReceiptArgs, + req: FetchTransactionReceiptRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('FetchTransactionReceipt'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('FetchTransactionReceipt'), + createHttpRequest(JsonEncode(req, 'FetchTransactionReceiptRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - receipt: _data.receipt - } + return JsonDecode(_data, 'FetchTransactionReceiptResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } fetchTransactionReceiptWithFilter = ( - args: FetchTransactionReceiptWithFilterArgs, + req: FetchTransactionReceiptWithFilterRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('FetchTransactionReceiptWithFilter'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('FetchTransactionReceiptWithFilter'), + createHttpRequest(JsonEncode(req, 'FetchTransactionReceiptWithFilterRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - receipt: _data.receipt - } + return JsonDecode(_data, 'FetchTransactionReceiptWithFilterResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getAllWebhookListeners = ( - args: GetAllWebhookListenersArgs, + req: GetAllWebhookListenersRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetAllWebhookListeners'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetAllWebhookListeners'), + createHttpRequest(JsonEncode(req, 'GetAllWebhookListenersRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - listeners: >_data.listeners - } + return JsonDecode(_data, 'GetAllWebhookListenersResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - getBalanceUpdates = (args: GetBalanceUpdatesArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetBalanceUpdates'), createHTTPRequest(args, headers, signal)).then( + getBalanceUpdates = ( + req: GetBalanceUpdatesRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch( + this.url('GetBalanceUpdates'), + createHttpRequest(JsonEncode(req, 'GetBalanceUpdatesRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - balances: >_data.balances - } + return JsonDecode(_data, 'GetBalanceUpdatesResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - getChainID = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetChainID'), createHTTPRequest({}, headers, signal)).then( + 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 - } + return JsonDecode(_data, 'GetChainIDResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - getEtherBalance = (args: GetEtherBalanceArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetEtherBalance'), createHTTPRequest(args, headers, signal)).then( + getEtherBalance = (req: GetEtherBalanceRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('GetEtherBalance'), + createHttpRequest(JsonEncode(req, 'GetEtherBalanceRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - balance: _data.balance - } + return JsonDecode(_data, 'GetEtherBalanceResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getMarketplaceOrders = ( - args: GetMarketplaceOrdersArgs, + req: GetMarketplaceOrdersRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetMarketplaceOrders'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetMarketplaceOrders'), + createHttpRequest(JsonEncode(req, 'GetMarketplaceOrdersRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - orders: >_data.orders - } + return JsonDecode(_data, 'GetMarketplaceOrdersResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getMarketplaceTopOrders = ( - args: GetMarketplaceTopOrdersArgs, + req: GetMarketplaceTopOrdersRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetMarketplaceTopOrders'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetMarketplaceTopOrders'), + createHttpRequest(JsonEncode(req, 'GetMarketplaceTopOrdersRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - orders: >_data.orders - } + return JsonDecode(_data, 'GetMarketplaceTopOrdersResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getNativeTokenBalance = ( - args: GetNativeTokenBalanceArgs, + req: GetNativeTokenBalanceRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetNativeTokenBalance'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetNativeTokenBalance'), + createHttpRequest(JsonEncode(req, 'GetNativeTokenBalanceRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - balance: _data.balance - } + return JsonDecode(_data, 'GetNativeTokenBalanceResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - getPrices = (args: GetPricesArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetPrices'), createHTTPRequest(args, headers, signal)).then( + getPrices = (req: GetPricesRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetPrices'), createHttpRequest(JsonEncode(req, 'GetPricesRequest'), headers, signal)).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - prices: >_data.prices - } + return JsonDecode(_data, 'GetPricesResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - getTokenBalances = (args: GetTokenBalancesArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenBalances'), createHTTPRequest(args, headers, signal)).then( + getTokenBalances = ( + req: GetTokenBalancesRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch( + this.url('GetTokenBalances'), + createHttpRequest(JsonEncode(req, 'GetTokenBalancesRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - balances: >_data.balances - } + return JsonDecode(_data, 'GetTokenBalancesResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getTokenBalancesByContract = ( - args: GetTokenBalancesByContractArgs, + req: GetTokenBalancesByContractRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalancesByContract'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetTokenBalancesByContract'), + createHttpRequest(JsonEncode(req, 'GetTokenBalancesByContractRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - balances: >_data.balances - } + return JsonDecode(_data, 'GetTokenBalancesByContractResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getTokenBalancesDetails = ( - args: GetTokenBalancesDetailsArgs, + req: GetTokenBalancesDetailsRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalancesDetails'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetTokenBalancesDetails'), + createHttpRequest(JsonEncode(req, 'GetTokenBalancesDetailsRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - nativeBalances: >_data.nativeBalances, - balances: >_data.balances - } + return JsonDecode(_data, 'GetTokenBalancesDetailsResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getTokenBalancesSummary = ( - args: GetTokenBalancesSummaryArgs, + req: GetTokenBalancesSummaryRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalancesSummary'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetTokenBalancesSummary'), + createHttpRequest(JsonEncode(req, 'GetTokenBalancesSummaryRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - nativeBalances: >_data.nativeBalances, - balances: >_data.balances - } + return JsonDecode(_data, 'GetTokenBalancesSummaryResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - getTokenIDRanges = (args: GetTokenIDRangesArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenIDRanges'), createHTTPRequest(args, headers, signal)).then( + getTokenIDRanges = ( + req: GetTokenIDRangesRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch( + this.url('GetTokenIDRanges'), + createHttpRequest(JsonEncode(req, 'GetTokenIDRangesRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - contractType: _data.contractType, - tokenIDRanges: >_data.tokenIDRanges, - moreRanges: _data.moreRanges - } + return JsonDecode(_data, 'GetTokenIDRangesResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - getTokenIDs = (args: GetTokenIDsArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenIDs'), createHTTPRequest(args, headers, signal)).then( + getTokenIDs = (req: GetTokenIDsRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetTokenIDs'), createHttpRequest(JsonEncode(req, 'GetTokenIDsRequest'), headers, signal)).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - contractType: _data.contractType, - tokenIDs: >_data.tokenIDs - } + return JsonDecode(_data, 'GetTokenIDsResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - getTokenSupplies = (args: GetTokenSuppliesArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenSupplies'), createHTTPRequest(args, headers, signal)).then( + getTokenSupplies = ( + req: GetTokenSuppliesRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch( + this.url('GetTokenSupplies'), + createHttpRequest(JsonEncode(req, 'GetTokenSuppliesRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - contractType: _data.contractType, - tokenIDs: >_data.tokenIDs - } + return JsonDecode(_data, 'GetTokenSuppliesResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getTokenSuppliesMap = ( - args: GetTokenSuppliesMapArgs, + req: GetTokenSuppliesMapRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenSuppliesMap'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetTokenSuppliesMap'), + createHttpRequest(JsonEncode(req, 'GetTokenSuppliesMapRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - supplies: <{ [key: string]: Array }>_data.supplies - } + return JsonDecode(_data, 'GetTokenSuppliesMapResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getTransactionHistory = ( - args: GetTransactionHistoryArgs, + req: GetTransactionHistoryRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTransactionHistory'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetTransactionHistory'), + createHttpRequest(JsonEncode(req, 'GetTransactionHistoryRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - transactions: >_data.transactions - } + return JsonDecode(_data, 'GetTransactionHistoryResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getWebhookListener = ( - args: GetWebhookListenerArgs, + req: GetWebhookListenerRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetWebhookListener'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetWebhookListener'), + createHttpRequest(JsonEncode(req, 'GetWebhookListenerRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - listener: _data.listener - } + return JsonDecode(_data, 'GetWebhookListenerResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } pauseAllWebhookListeners = ( - args: PauseAllWebhookListenersArgs, + req: PauseAllWebhookListenersRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('PauseAllWebhookListeners'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('PauseAllWebhookListeners'), + createHttpRequest(JsonEncode(req, 'PauseAllWebhookListenersRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - status: _data.status - } + return JsonDecode(_data, 'PauseAllWebhookListenersResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - ping = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Ping'), createHTTPRequest({}, headers, signal)).then( + 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 - } + return JsonDecode(_data, 'PingResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } removeAllWebhookListeners = ( - args: RemoveAllWebhookListenersArgs, + req: RemoveAllWebhookListenersRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('RemoveAllWebhookListeners'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('RemoveAllWebhookListeners'), + createHttpRequest(JsonEncode(req, 'RemoveAllWebhookListenersRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - status: _data.status - } + return JsonDecode(_data, 'RemoveAllWebhookListenersResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } removeWebhookListener = ( - args: RemoveWebhookListenerArgs, + req: RemoveWebhookListenerRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('RemoveWebhookListener'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('RemoveWebhookListener'), + createHttpRequest(JsonEncode(req, 'RemoveWebhookListenerRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - status: _data.status - } + return JsonDecode(_data, 'RemoveWebhookListenerResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } resumeAllWebhookListeners = ( - args: ResumeAllWebhookListenersArgs, + req: ResumeAllWebhookListenersRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('ResumeAllWebhookListeners'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('ResumeAllWebhookListeners'), + createHttpRequest(JsonEncode(req, 'ResumeAllWebhookListenersRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - status: _data.status - } + return JsonDecode(_data, 'ResumeAllWebhookListenersResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - runtimeStatus = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('RuntimeStatus'), createHTTPRequest({}, headers, signal)).then( + 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 - } + return JsonDecode(_data, 'RuntimeStatusResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } subscribeBalanceUpdates = ( - args: SubscribeBalanceUpdatesArgs, - options: WebrpcStreamOptions + req: SubscribeBalanceUpdatesRequest, + options: WebrpcStreamOptions ): WebrpcStreamController => { const abortController = new AbortController() const abortSignal = abortController.signal @@ -1716,7 +1795,10 @@ export class Indexer implements Indexer { } const _fetch = () => - this.fetch(this.url('SubscribeBalanceUpdates'), createHTTPRequest(args, options.headers, abortSignal)).then( + this.fetch( + this.url('SubscribeBalanceUpdates'), + createHttpRequest(JsonEncode(req, 'SubscribeBalanceUpdatesRequest'), options.headers, abortSignal) + ).then( async res => { await sseResponse(res, options, _fetch) }, @@ -1731,7 +1813,10 @@ export class Indexer implements Indexer { closed: resp } } - subscribeEvents = (args: SubscribeEventsArgs, options: WebrpcStreamOptions): WebrpcStreamController => { + subscribeEvents = ( + req: SubscribeEventsRequest, + options: WebrpcStreamOptions + ): WebrpcStreamController => { const abortController = new AbortController() const abortSignal = abortController.signal @@ -1742,7 +1827,10 @@ export class Indexer implements Indexer { } const _fetch = () => - this.fetch(this.url('SubscribeEvents'), createHTTPRequest(args, options.headers, abortSignal)).then( + this.fetch( + this.url('SubscribeEvents'), + createHttpRequest(JsonEncode(req, 'SubscribeEventsRequest'), options.headers, abortSignal) + ).then( async res => { await sseResponse(res, options, _fetch) }, @@ -1758,8 +1846,8 @@ export class Indexer implements Indexer { } } subscribeReceipts = ( - args: SubscribeReceiptsArgs, - options: WebrpcStreamOptions + req: SubscribeReceiptsRequest, + options: WebrpcStreamOptions ): WebrpcStreamController => { const abortController = new AbortController() const abortSignal = abortController.signal @@ -1771,7 +1859,10 @@ export class Indexer implements Indexer { } const _fetch = () => - this.fetch(this.url('SubscribeReceipts'), createHTTPRequest(args, options.headers, abortSignal)).then( + this.fetch( + this.url('SubscribeReceipts'), + createHttpRequest(JsonEncode(req, 'SubscribeReceiptsRequest'), options.headers, abortSignal) + ).then( async res => { await sseResponse(res, options, _fetch) }, @@ -1786,68 +1877,68 @@ export class Indexer implements Indexer { closed: resp } } - syncBalance = (args: SyncBalanceArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('SyncBalance'), createHTTPRequest(args, headers, signal)).then( + syncBalance = (req: SyncBalanceRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('SyncBalance'), createHttpRequest(JsonEncode(req, 'SyncBalanceRequest'), headers, signal)).then( res => { return buildResponse(res).then(_data => { - return {} + return JsonDecode(_data, 'SyncBalanceResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } toggleWebhookListener = ( - args: ToggleWebhookListenerArgs, + req: ToggleWebhookListenerRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('ToggleWebhookListener'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('ToggleWebhookListener'), + createHttpRequest(JsonEncode(req, 'ToggleWebhookListenerRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - webhookListener: _data.webhookListener - } + return JsonDecode(_data, 'ToggleWebhookListenerResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } updateWebhookListener = ( - args: UpdateWebhookListenerArgs, + req: UpdateWebhookListenerRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('UpdateWebhookListener'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('UpdateWebhookListener'), + createHttpRequest(JsonEncode(req, 'UpdateWebhookListenerRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - status: _data.status - } + return JsonDecode(_data, 'UpdateWebhookListenerResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - version = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Version'), createHTTPRequest({}, headers, signal)).then( + 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 - } + return JsonDecode(_data, 'VersionResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } @@ -1902,16 +1993,11 @@ const sseResponse = async (res: Response, options: WebrpcStreamOptions, ret lastReadTime = Date.now() buffer += decoder.decode(value, { stream: true }) } catch (error) { - let message = '' - if (error instanceof Error) { - message = error.message - } - if (error instanceof DOMException && error.name === 'AbortError') { onError( - WebrpcRequestFailedError.new({ + WebrpcClientAbortedError.new({ message: 'AbortError', - cause: `AbortError: ${message}` + cause: `AbortError: ${error instanceof Error ? error.message : String(error)}` }), () => { throw new Error('Abort signal cannot be used to reconnect') @@ -1920,7 +2006,7 @@ const sseResponse = async (res: Response, options: WebrpcStreamOptions, ret } else { onError( WebrpcStreamLostError.new({ - cause: `reader.read(): ${message}` + cause: `reader.read(): ${error instanceof Error ? error.message : String(error)}` }), retryFetch ) @@ -1930,12 +2016,13 @@ const sseResponse = async (res: Response, options: WebrpcStreamOptions, ret let lines = buffer.split('\n') for (let i = 0; i < lines.length - 1; i++) { - if (lines[i].length == 0) { + const line = lines[i] + if (line?.length === 0) { continue } let data: any try { - data = JSON.parse(lines[i]) + data = JSON.parse(line) if (data.hasOwnProperty('webrpcError')) { const error = data.webrpcError const code: number = typeof error.code === 'number' ? error.code : 0 @@ -1949,8 +2036,7 @@ const sseResponse = async (res: Response, options: WebrpcStreamOptions, ret onError( WebrpcBadResponseError.new({ status: res.status, - // @ts-ignore - cause: `JSON.parse(): ${error.message}` + cause: `JSON.parse(): ${error instanceof Error ? error.message : String(error)}` }), retryFetch ) @@ -1959,7 +2045,8 @@ const sseResponse = async (res: Response, options: WebrpcStreamOptions, ret } if (!done) { - buffer = lines[lines.length - 1] + const lastLine = lines[lines.length - 1] + buffer = lastLine || '' continue } @@ -1968,16 +2055,13 @@ const sseResponse = async (res: Response, options: WebrpcStreamOptions, ret } } -const createHTTPRequest = (body: object = {}, headers: object = {}, signal: AbortSignal | null = null): object => { - const reqHeaders: { [key: string]: string } = { ...headers, 'Content-Type': 'application/json' } - reqHeaders[WebrpcHeader] = WebrpcHeaderValue - - return { - method: 'POST', - headers: reqHeaders, - body: JSON.stringify(body || {}), - signal +const createHttpRequest = (body: string = '{}', headers: object = {}, signal: AbortSignal | null = null): object => { + const reqHeaders: { [key: string]: string } = { + ...headers, + 'Content-Type': 'application/json', + [WebrpcHeader]: WebrpcHeaderValue } + return { method: 'POST', headers: reqHeaders, body, signal } } const buildResponse = (res: Response): Promise => { @@ -1986,13 +2070,9 @@ const buildResponse = (res: Response): Promise => { try { data = JSON.parse(text) } catch (error) { - let message = '' - if (error instanceof Error) { - message = error.message - } throw WebrpcBadResponseError.new({ status: res.status, - cause: `JSON.parse(): ${message}: response text: ${text}` + cause: `JSON.parse(): ${error instanceof Error ? error.message : String(error)}: response text: ${text}` }) } if (!res.ok) { @@ -2003,517 +2083,510 @@ const buildResponse = (res: Response): Promise => { }) } +export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise + +export interface WebrpcStreamOptions extends WebrpcOptions { + onMessage: (message: T) => void + onError: (error: WebrpcError, reconnect: () => void) => void + onOpen?: () => void + onClose?: () => void +} + +export interface WebrpcOptions { + headers?: HeadersInit + signal?: AbortSignal +} + +export interface WebrpcStreamController { + abort: (reason?: any) => void + closed: Promise +} + +export const JsonEncode = (obj: T, _typ: string = ''): string => { + return JSON.stringify(obj) +} + +export const JsonDecode = (data: string | any, _typ: string = ''): T => { + let parsed: any = data + if (typeof data === 'string') { + try { + parsed = JSON.parse(data) + } catch (err) { + throw WebrpcBadResponseError.new({ cause: `JsonDecode: JSON.parse failed: ${(err as Error).message}` }) + } + } + return parsed as T +} + // // Errors // +type WebrpcErrorParams = { name?: string; code?: number; message?: string; status?: number; cause?: string } + export class WebrpcError extends Error { - name: string code: number - message: string status: number - cause?: string - - /** @deprecated Use message instead of msg. Deprecated in webrpc v0.11.0. */ - msg: string - - constructor(name: string, code: number, message: string, status: number, cause?: string) { - super(message) - this.name = name || 'WebrpcError' - this.code = typeof code === 'number' ? code : 0 - this.message = message || `endpoint error ${this.code}` - this.msg = this.message - this.status = typeof status === 'number' ? status : 0 - this.cause = cause + + constructor(error: WebrpcErrorParams = {}) { + super(error.message) + this.name = error.name || 'WebrpcEndpointError' + this.code = typeof error.code === 'number' ? error.code : 0 + this.message = error.message || `endpoint error` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcError.prototype) } static new(payload: any): WebrpcError { - return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause) + return new this({ message: payload.message, code: payload.code, status: payload.status, cause: payload.cause }) } } -// Webrpc errors - export class WebrpcEndpointError extends WebrpcError { - constructor( - name: string = 'WebrpcEndpoint', - code: number = 0, - message: string = `endpoint error`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcEndpoint' + this.code = typeof error.code === 'number' ? error.code : 0 + this.message = error.message || `endpoint error` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcEndpointError.prototype) } } export class WebrpcRequestFailedError extends WebrpcError { - constructor( - name: string = 'WebrpcRequestFailed', - code: number = -1, - message: string = `request failed`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcRequestFailed' + this.code = typeof error.code === 'number' ? error.code : -1 + this.message = error.message || `request failed` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcRequestFailedError.prototype) } } export class WebrpcBadRouteError extends WebrpcError { - constructor( - name: string = 'WebrpcBadRoute', - code: number = -2, - message: string = `bad route`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadRoute' + this.code = typeof error.code === 'number' ? error.code : -2 + this.message = error.message || `bad route` + this.status = typeof error.status === 'number' ? error.status : 404 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadRouteError.prototype) } } export class WebrpcBadMethodError extends WebrpcError { - constructor( - name: string = 'WebrpcBadMethod', - code: number = -3, - message: string = `bad method`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadMethod' + this.code = typeof error.code === 'number' ? error.code : -3 + this.message = error.message || `bad method` + this.status = typeof error.status === 'number' ? error.status : 405 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadMethodError.prototype) } } export class WebrpcBadRequestError extends WebrpcError { - constructor( - name: string = 'WebrpcBadRequest', - code: number = -4, - message: string = `bad request`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadRequest' + this.code = typeof error.code === 'number' ? error.code : -4 + this.message = error.message || `bad request` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadRequestError.prototype) } } export class WebrpcBadResponseError extends WebrpcError { - constructor( - name: string = 'WebrpcBadResponse', - code: number = -5, - message: string = `bad response`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadResponse' + this.code = typeof error.code === 'number' ? error.code : -5 + this.message = error.message || `bad response` + this.status = typeof error.status === 'number' ? error.status : 500 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadResponseError.prototype) } } export class WebrpcServerPanicError extends WebrpcError { - constructor( - name: string = 'WebrpcServerPanic', - code: number = -6, - message: string = `server panic`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcServerPanic' + this.code = typeof error.code === 'number' ? error.code : -6 + this.message = error.message || `server panic` + this.status = typeof error.status === 'number' ? error.status : 500 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcServerPanicError.prototype) } } export class WebrpcInternalErrorError extends WebrpcError { - constructor( - name: string = 'WebrpcInternalError', - code: number = -7, - message: string = `internal error`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcInternalError' + this.code = typeof error.code === 'number' ? error.code : -7 + this.message = error.message || `internal error` + this.status = typeof error.status === 'number' ? error.status : 500 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcInternalErrorError.prototype) } } -export class WebrpcClientDisconnectedError extends WebrpcError { - constructor( - name: string = 'WebrpcClientDisconnected', - code: number = -8, - message: string = `client disconnected`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, WebrpcClientDisconnectedError.prototype) +export class WebrpcClientAbortedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcClientAborted' + this.code = typeof error.code === 'number' ? error.code : -8 + this.message = error.message || `request aborted by client` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, WebrpcClientAbortedError.prototype) } } export class WebrpcStreamLostError extends WebrpcError { - constructor( - name: string = 'WebrpcStreamLost', - code: number = -9, - message: string = `stream lost`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcStreamLost' + this.code = typeof error.code === 'number' ? error.code : -9 + this.message = error.message || `stream lost` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcStreamLostError.prototype) } } export class WebrpcStreamFinishedError extends WebrpcError { - constructor( - name: string = 'WebrpcStreamFinished', - code: number = -10, - message: string = `stream finished`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcStreamFinished' + this.code = typeof error.code === 'number' ? error.code : -10 + this.message = error.message || `stream finished` + this.status = typeof error.status === 'number' ? error.status : 200 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcStreamFinishedError.prototype) } } +// // Schema errors +// export class 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) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Aborted' + this.code = typeof error.code === 'number' ? error.code : 1005 + this.message = error.message || `Request aborted` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, AbortedError.prototype) } } export class AccessKeyMismatchError extends WebrpcError { - constructor( - name: string = 'AccessKeyMismatch', - code: number = 1102, - message: string = `Access key mismatch`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'AccessKeyMismatch' + this.code = typeof error.code === 'number' ? error.code : 1102 + this.message = error.message || `Access key mismatch` + this.status = typeof error.status === 'number' ? error.status : 409 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, AccessKeyMismatchError.prototype) } } export class AccessKeyNotFoundError extends WebrpcError { - constructor( - name: string = 'AccessKeyNotFound', - code: number = 1101, - message: string = `Access key not found`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'AccessKeyNotFound' + this.code = typeof error.code === 'number' ? error.code : 1101 + this.message = error.message || `Access key not found` + this.status = typeof error.status === 'number' ? error.status : 401 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, AccessKeyNotFoundError.prototype) } } export class AtLeastOneKeyError extends WebrpcError { - constructor( - 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) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'AtLeastOneKey' + this.code = typeof error.code === 'number' ? error.code : 1302 + this.message = error.message || `You need at least one Access Key` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, AtLeastOneKeyError.prototype) } } export class GeoblockedError extends WebrpcError { - constructor( - name: string = 'Geoblocked', - code: number = 1006, - message: string = `Geoblocked region`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Geoblocked' + this.code = typeof error.code === 'number' ? error.code : 1006 + this.message = error.message || `Geoblocked region` + this.status = typeof error.status === 'number' ? error.status : 451 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, GeoblockedError.prototype) } } export class InvalidArgumentError extends WebrpcError { - constructor( - name: string = 'InvalidArgument', - code: number = 2001, - message: string = `Invalid argument`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'InvalidArgument' + this.code = typeof error.code === 'number' ? error.code : 2001 + this.message = error.message || `Invalid argument` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, InvalidArgumentError.prototype) } } export class InvalidOriginError extends WebrpcError { - constructor( - name: string = 'InvalidOrigin', - code: number = 1103, - message: string = `Invalid origin for Access Key`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'InvalidOrigin' + this.code = typeof error.code === 'number' ? error.code : 1103 + this.message = error.message || `Invalid origin for Access Key` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, InvalidOriginError.prototype) } } export class InvalidServiceError extends WebrpcError { - constructor( - 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) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'InvalidService' + this.code = typeof error.code === 'number' ? error.code : 1104 + this.message = error.message || `Service not enabled for Access key` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, InvalidServiceError.prototype) } } export class MaxAccessKeysError extends WebrpcError { - constructor( - name: string = 'MaxAccessKeys', - code: number = 1301, - message: string = `Access keys limit reached`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'MaxAccessKeys' + this.code = typeof error.code === 'number' ? error.code : 1301 + this.message = error.message || `Access keys limit reached` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, MaxAccessKeysError.prototype) } } export class MetadataCallFailedError extends WebrpcError { - constructor( - name: string = 'MetadataCallFailed', - code: number = 3003, - message: string = `Metadata service call failed`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'MetadataCallFailed' + this.code = typeof error.code === 'number' ? error.code : 3003 + this.message = error.message || `Metadata service call failed` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, MetadataCallFailedError.prototype) } } export class MethodNotFoundError extends WebrpcError { - constructor( - name: string = 'MethodNotFound', - code: number = 1003, - message: string = `Method not found`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'MethodNotFound' + this.code = typeof error.code === 'number' ? error.code : 1003 + this.message = error.message || `Method not found` + this.status = typeof error.status === 'number' ? error.status : 404 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, MethodNotFoundError.prototype) } } export class NoDefaultKeyError extends WebrpcError { - constructor( - name: string = 'NoDefaultKey', - code: number = 1300, - message: string = `No default access key found`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'NoDefaultKey' + this.code = typeof error.code === 'number' ? error.code : 1300 + this.message = error.message || `No default access key found` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, NoDefaultKeyError.prototype) } } export class NotFoundError extends WebrpcError { - constructor( - name: string = 'NotFound', - code: number = 3000, - message: string = `Resource not found`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'NotFound' + this.code = typeof error.code === 'number' ? error.code : 3000 + this.message = error.message || `Resource not found` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, NotFoundError.prototype) } } export class PermissionDeniedError extends WebrpcError { - constructor( - name: string = 'PermissionDenied', - code: number = 1001, - message: string = `Permission denied`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'PermissionDenied' + this.code = typeof error.code === 'number' ? error.code : 1001 + this.message = error.message || `Permission denied` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, PermissionDeniedError.prototype) } } export class ProjectNotFoundError extends WebrpcError { - constructor( - name: string = 'ProjectNotFound', - code: number = 1100, - message: string = `Project not found`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'ProjectNotFound' + this.code = typeof error.code === 'number' ? error.code : 1100 + this.message = error.message || `Project not found` + this.status = typeof error.status === 'number' ? error.status : 401 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, ProjectNotFoundError.prototype) } } export class QueryFailedError extends WebrpcError { - constructor( - name: string = 'QueryFailed', - code: number = 2003, - message: string = `Query failed`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'QueryFailed' + this.code = typeof error.code === 'number' ? error.code : 2003 + this.message = error.message || `Query failed` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, QueryFailedError.prototype) } } export class QuotaExceededError extends WebrpcError { - constructor( - name: string = 'QuotaExceeded', - code: number = 1200, - message: string = `Quota exceeded`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'QuotaExceeded' + this.code = typeof error.code === 'number' ? error.code : 1200 + this.message = error.message || `Quota exceeded` + this.status = typeof error.status === 'number' ? error.status : 429 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, QuotaExceededError.prototype) } } export class RateLimitError extends WebrpcError { - constructor( - name: string = 'RateLimit', - code: number = 1201, - message: string = `Rate limit exceeded`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'RateLimit' + this.code = typeof error.code === 'number' ? error.code : 1201 + this.message = error.message || `Rate limit exceeded` + this.status = typeof error.status === 'number' ? error.status : 429 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, RateLimitError.prototype) } } export class RateLimitedError extends WebrpcError { - constructor( - name: string = 'RateLimited', - code: number = 1007, - message: string = `Rate-limited. Please slow down.`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'RateLimited' + this.code = typeof error.code === 'number' ? error.code : 1007 + this.message = error.message || `Rate-limited. Please slow down.` + this.status = typeof error.status === 'number' ? error.status : 429 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, RateLimitedError.prototype) } } export class RequestConflictError extends WebrpcError { - constructor( - name: string = 'RequestConflict', - code: number = 1004, - message: string = `Conflict with target resource`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'RequestConflict' + this.code = typeof error.code === 'number' ? error.code : 1004 + this.message = error.message || `Conflict with target resource` + this.status = typeof error.status === 'number' ? error.status : 409 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, RequestConflictError.prototype) } } export class ResourceExhaustedError extends WebrpcError { - constructor( - name: string = 'ResourceExhausted', - code: number = 2004, - message: string = `Resource exhausted`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'ResourceExhausted' + this.code = typeof error.code === 'number' ? error.code : 2004 + this.message = error.message || `Resource exhausted` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, ResourceExhaustedError.prototype) } } export class SessionExpiredError extends WebrpcError { - constructor( - name: string = 'SessionExpired', - code: number = 1002, - message: string = `Session expired`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'SessionExpired' + this.code = typeof error.code === 'number' ? error.code : 1002 + this.message = error.message || `Session expired` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, SessionExpiredError.prototype) } } export class TimeoutError extends WebrpcError { - constructor( - name: string = 'Timeout', - code: number = 1900, - message: string = `Request timed out`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Timeout' + this.code = typeof error.code === 'number' ? error.code : 1900 + this.message = error.message || `Request timed out` + this.status = typeof error.status === 'number' ? error.status : 408 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, TimeoutError.prototype) } } export class UnauthorizedError extends WebrpcError { - constructor( - name: string = 'Unauthorized', - code: number = 1000, - message: string = `Unauthorized access`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Unauthorized' + this.code = typeof error.code === 'number' ? error.code : 1000 + this.message = error.message || `Unauthorized access` + this.status = typeof error.status === 'number' ? error.status : 401 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, UnauthorizedError.prototype) } } export class UnauthorizedUserError extends WebrpcError { - constructor( - name: string = 'UnauthorizedUser', - code: number = 1105, - message: string = `Unauthorized user`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'UnauthorizedUser' + this.code = typeof error.code === 'number' ? error.code : 1105 + this.message = error.message || `Unauthorized user` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, UnauthorizedUserError.prototype) } } export class UnavailableError extends WebrpcError { - constructor( - name: string = 'Unavailable', - code: number = 2002, - message: string = `Unavailable resource`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Unavailable' + this.code = typeof error.code === 'number' ? error.code : 2002 + this.message = error.message || `Unavailable resource` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, UnavailableError.prototype) } } @@ -2527,7 +2600,7 @@ export enum errors { WebrpcBadResponse = 'WebrpcBadResponse', WebrpcServerPanic = 'WebrpcServerPanic', WebrpcInternalError = 'WebrpcInternalError', - WebrpcClientDisconnected = 'WebrpcClientDisconnected', + WebrpcClientAborted = 'WebrpcClientAborted', WebrpcStreamLost = 'WebrpcStreamLost', WebrpcStreamFinished = 'WebrpcStreamFinished', Aborted = 'Aborted', @@ -2567,7 +2640,7 @@ export enum WebrpcErrorCodes { WebrpcBadResponse = -5, WebrpcServerPanic = -6, WebrpcInternalError = -7, - WebrpcClientDisconnected = -8, + WebrpcClientAborted = -8, WebrpcStreamLost = -9, WebrpcStreamFinished = -10, Aborted = 1005, @@ -2607,7 +2680,7 @@ export const webrpcErrorByCode: { [code: number]: any } = { [-5]: WebrpcBadResponseError, [-6]: WebrpcServerPanicError, [-7]: WebrpcInternalErrorError, - [-8]: WebrpcClientDisconnectedError, + [-8]: WebrpcClientAbortedError, [-9]: WebrpcStreamLostError, [-10]: WebrpcStreamFinishedError, [1005]: AbortedError, @@ -2638,21 +2711,58 @@ export const webrpcErrorByCode: { [code: number]: any } = { [2002]: UnavailableError } -export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise +// +// Webrpc +// -export interface WebrpcStreamOptions extends WebrpcOptions { - onMessage: (message: T) => void - onError: (error: WebrpcError, reconnect: () => void) => void - onOpen?: () => void - onClose?: () => void +export const WebrpcHeader = 'Webrpc' + +export const WebrpcHeaderValue = 'webrpc@v0.31.0;gen-typescript@v0.22.5;sequence-indexer@v0.4.0' + +type WebrpcGenVersions = { + WebrpcGenVersion: string + codeGenName: string + codeGenVersion: string + schemaName: string + schemaVersion: string } -export interface WebrpcOptions { - headers?: HeadersInit - signal?: AbortSignal +export function VersionFromHeader(headers: Headers): WebrpcGenVersions { + const headerValue = headers.get(WebrpcHeader) + if (!headerValue) { + return { + WebrpcGenVersion: '', + codeGenName: '', + codeGenVersion: '', + schemaName: '', + schemaVersion: '' + } + } + + return parseWebrpcGenVersions(headerValue) } -export interface WebrpcStreamController { - abort: (reason?: any) => void - closed: Promise +function parseWebrpcGenVersions(header: string): WebrpcGenVersions { + const versions = header.split(';') + if (versions.length < 3) { + return { + WebrpcGenVersion: '', + codeGenName: '', + codeGenVersion: '', + schemaName: '', + schemaVersion: '' + } + } + + const [_, WebrpcGenVersion] = versions[0]!.split('@') + const [codeGenName, codeGenVersion] = versions[1]!.split('@') + const [schemaName, schemaVersion] = versions[2]!.split('@') + + return { + WebrpcGenVersion: WebrpcGenVersion ?? '', + codeGenName: codeGenName ?? '', + codeGenVersion: codeGenVersion ?? '', + schemaName: schemaName ?? '', + schemaVersion: schemaVersion ?? '' + } } diff --git a/packages/indexer/src/indexergw.gen.ts b/packages/indexer/src/indexergw.gen.ts index a23eb87a6..31d484100 100644 --- a/packages/indexer/src/indexergw.gen.ts +++ b/packages/indexer/src/indexergw.gen.ts @@ -1,73 +1,117 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 9424146daac757c1b912723a9a212b419dfea11e +// sequence-indexer v0.4.0 f957af073daf1c3c88b0dc45ba70695f982181e7 // -- -// Code generated by webrpc-gen@v0.25.3 with typescript generator. DO NOT EDIT. +// Code generated by Webrpc-gen@v0.31.0 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' +// Webrpc description and code-gen version +export const WebrpcVersion = 'v1' // Schema version of your RIDL schema -export const WebRPCSchemaVersion = 'v0.4.0' +export const WebrpcSchemaVersion = 'v0.4.0' // Schema hash generated from your RIDL schema -export const WebRPCSchemaHash = '9424146daac757c1b912723a9a212b419dfea11e' +export const WebrpcSchemaHash = 'f957af073daf1c3c88b0dc45ba70695f982181e7' -type WebrpcGenVersions = { - webrpcGenVersion: string - codeGenName: string - codeGenVersion: string - schemaName: string - schemaVersion: string -} +// +// Client interface +// -export function VersionFromHeader(headers: Headers): WebrpcGenVersions { - const headerValue = headers.get(WebrpcHeader) - if (!headerValue) { - return { - webrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '' - } - } +export interface IndexerGatewayClient { + /** + * GetTokenBalances returns a balance summary/details for an specific account + * on all indexer nodes. By default if accountAddress is left empty, it will + * use the account from the jwt session. + */ + getBalanceUpdates(req: GetBalanceUpdatesRequest, headers?: object, signal?: AbortSignal): Promise - return parseWebrpcGenVersions(headerValue) -} + /** + * GetChains returns a list of chains with their ID and name + */ + getChains(req: GetChainsRequest, headers?: object, signal?: AbortSignal): Promise -function parseWebrpcGenVersions(header: string): WebrpcGenVersions { - const versions = header.split(';') - if (versions.length < 3) { - return { - webrpcGenVersion: '', - codeGenName: '', - codeGenVersion: '', - schemaName: '', - schemaVersion: '' - } - } + /** + * GetNativeTokenBalance queries indexer nodes for the latest native token + * account balance. + */ + getNativeTokenBalance( + req: GetNativeTokenBalanceRequest, + headers?: object, + signal?: AbortSignal + ): Promise - const [_, webrpcGenVersion] = versions[0]!.split('@') - const [codeGenName, codeGenVersion] = versions[1]!.split('@') - const [schemaName, schemaVersion] = versions[2]!.split('@') + /** + * GetTokenBalances returns a balance summary/details for a specific account + * on all indexer nodes. By default if accountAddress is left empty, it will + * use the account from the jwt session. + * + * @deprecated Use GetTokenBalancesSummary or GetTokenBalancesDetails instead. + */ + getTokenBalances(req: GetTokenBalancesRequest, headers?: object, signal?: AbortSignal): Promise - return { - webrpcGenVersion: webrpcGenVersion ?? '', - codeGenName: codeGenName ?? '', - codeGenVersion: codeGenVersion ?? '', - schemaName: schemaName ?? '', - schemaVersion: schemaVersion ?? '' - } + /** + * GetTokenBalancesByContract returns a balances for specific accounts and + * contracts on all indexer nodes. The collection ERC721 & ERC1155 tokens are + * represented as individual balances. + */ + getTokenBalancesByContract( + req: GetTokenBalancesByContractRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * GetTokenBalancesDetails returns a detailed balance summary for the given + * accounts on all indexer nodes. The collection ERC721 & ERC1155 tokens are + * represented as individual balances. + */ + getTokenBalancesDetails( + req: GetTokenBalancesDetailsRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * GetTokenBalancesSummary returns a summary of token balances for the given + * accounts on all indexer nodes. The collection ERC721 & ERC1155 tokens are + * represented as a single aggregated balance. + */ + getTokenBalancesSummary( + req: GetTokenBalancesSummaryRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * GetTransactionHistory returns the history of mined transactions for the + * given account on all indexer nodes, which includes a list of token transfer + * (sent/received) , and sent transactions from a Sequence wallet. + */ + getTransactionHistory( + req: GetTransactionHistoryRequest, + headers?: object, + signal?: AbortSignal + ): Promise + + /** + * Ping the indexer + */ + ping(headers?: object, signal?: AbortSignal): Promise + + /** + * Get the current runtime health status of the indexer gatewya + */ + runtimeStatus(headers?: object, signal?: AbortSignal): Promise + + /** + * Get the current version of the indexer + */ + version(headers?: object, signal?: AbortSignal): Promise } // -// Types +// Schema types // export interface Asset { @@ -336,10 +380,12 @@ export interface MetadataOptions { export interface NativeTokenBalance { accountAddress: string chainId: number + name: string + symbol: string balance: string balanceUSD: string priceUSD: string - error: string + errorReason?: string } export enum NetworkType { @@ -452,6 +498,7 @@ export interface TokenBalancesByContractFilter { export interface TokenBalancesFilter { accountAddresses: Array contractStatus?: ContractVerificationStatus + contractTypes?: Array contractWhitelist?: Array contractBlacklist?: Array omitNativeBalances: boolean @@ -629,89 +676,7 @@ export interface WebhookListener { 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 { +export interface GetBalanceUpdatesRequest { chainIds?: Array networks?: Array networkType?: NetworkType @@ -721,18 +686,20 @@ export interface GetBalanceUpdatesArgs { page?: Page } -export interface GetBalanceUpdatesReturn { +export interface GetBalanceUpdatesResponse { page: Page balances: Array } -export interface GetChainsArgs { + +export interface GetChainsRequest { networkType?: NetworkType } -export interface GetChainsReturn { +export interface GetChainsResponse { chains: Array } -export interface GetNativeTokenBalanceArgs { + +export interface GetNativeTokenBalanceRequest { chainIds?: Array networks?: Array networkType?: NetworkType @@ -740,10 +707,11 @@ export interface GetNativeTokenBalanceArgs { omitPrices?: boolean } -export interface GetNativeTokenBalanceReturn { +export interface GetNativeTokenBalanceResponse { balances: Array } -export interface GetTokenBalancesArgs { + +export interface GetTokenBalancesRequest { chainIds?: Array networks?: Array networkType?: NetworkType @@ -756,11 +724,12 @@ export interface GetTokenBalancesArgs { page?: Page } -export interface GetTokenBalancesReturn { +export interface GetTokenBalancesResponse { page: Page balances: Array } -export interface GetTokenBalancesByContractArgs { + +export interface GetTokenBalancesByContractRequest { chainIds?: Array networks?: Array networkType?: NetworkType @@ -769,11 +738,12 @@ export interface GetTokenBalancesByContractArgs { page?: Page } -export interface GetTokenBalancesByContractReturn { +export interface GetTokenBalancesByContractResponse { page: Page balances: Array } -export interface GetTokenBalancesDetailsArgs { + +export interface GetTokenBalancesDetailsRequest { chainIds?: Array networks?: Array networkType?: NetworkType @@ -782,12 +752,13 @@ export interface GetTokenBalancesDetailsArgs { page?: Page } -export interface GetTokenBalancesDetailsReturn { +export interface GetTokenBalancesDetailsResponse { page: Page nativeBalances: Array balances: Array } -export interface GetTokenBalancesSummaryArgs { + +export interface GetTokenBalancesSummaryRequest { chainIds?: Array networks?: Array networkType?: NetworkType @@ -796,12 +767,13 @@ export interface GetTokenBalancesSummaryArgs { page?: Page } -export interface GetTokenBalancesSummaryReturn { +export interface GetTokenBalancesSummaryResponse { page: Page nativeBalances: Array balances: Array } -export interface GetTransactionHistoryArgs { + +export interface GetTransactionHistoryRequest { chainIds?: Array networks?: Array networkType?: NetworkType @@ -811,30 +783,34 @@ export interface GetTransactionHistoryArgs { page?: Page } -export interface GetTransactionHistoryReturn { +export interface GetTransactionHistoryResponse { page: Page transactions: Array } -export interface PingArgs {} -export interface PingReturn { +export interface PingRequest {} + +export interface PingResponse { status: boolean } -export interface RuntimeStatusArgs {} -export interface RuntimeStatusReturn { +export interface RuntimeStatusRequest {} + +export interface RuntimeStatusResponse { status: GatewayRuntimeStatus } -export interface VersionArgs {} -export interface VersionReturn { +export interface VersionRequest {} + +export interface VersionResponse { version: Version } // // Client // -export class IndexerGateway implements IndexerGateway { + +export class IndexerGateway implements IndexerGatewayClient { protected hostname: string protected fetch: Fetch protected path = '/rpc/IndexerGateway/' @@ -848,210 +824,221 @@ export class IndexerGateway implements IndexerGateway { 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( + queryKey = { + getBalanceUpdates: (req: GetBalanceUpdatesRequest) => ['IndexerGateway', 'getBalanceUpdates', req] as const, + getChains: (req: GetChainsRequest) => ['IndexerGateway', 'getChains', req] as const, + getNativeTokenBalance: (req: GetNativeTokenBalanceRequest) => ['IndexerGateway', 'getNativeTokenBalance', req] as const, + getTokenBalances: (req: GetTokenBalancesRequest) => ['IndexerGateway', 'getTokenBalances', req] as const, + getTokenBalancesByContract: (req: GetTokenBalancesByContractRequest) => + ['IndexerGateway', 'getTokenBalancesByContract', req] as const, + getTokenBalancesDetails: (req: GetTokenBalancesDetailsRequest) => ['IndexerGateway', 'getTokenBalancesDetails', req] as const, + getTokenBalancesSummary: (req: GetTokenBalancesSummaryRequest) => ['IndexerGateway', 'getTokenBalancesSummary', req] as const, + getTransactionHistory: (req: GetTransactionHistoryRequest) => ['IndexerGateway', 'getTransactionHistory', req] as const, + ping: () => ['IndexerGateway', 'ping'] as const, + runtimeStatus: () => ['IndexerGateway', 'runtimeStatus'] as const, + version: () => ['IndexerGateway', 'version'] as const + } + + getBalanceUpdates = ( + req: GetBalanceUpdatesRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch( + this.url('GetBalanceUpdates'), + createHttpRequest(JsonEncode(req, 'GetBalanceUpdatesRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - balances: >_data.balances - } + return JsonDecode(_data, 'GetBalanceUpdatesResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - getChains = (args: GetChainsArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetChains'), createHTTPRequest(args, headers, signal)).then( + getChains = (req: GetChainsRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetChains'), createHttpRequest(JsonEncode(req, 'GetChainsRequest'), headers, signal)).then( res => { return buildResponse(res).then(_data => { - return { - chains: >_data.chains - } + return JsonDecode(_data, 'GetChainsResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getNativeTokenBalance = ( - args: GetNativeTokenBalanceArgs, + req: GetNativeTokenBalanceRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetNativeTokenBalance'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetNativeTokenBalance'), + createHttpRequest(JsonEncode(req, 'GetNativeTokenBalanceRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - balances: >_data.balances - } + return JsonDecode(_data, 'GetNativeTokenBalanceResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - getTokenBalances = (args: GetTokenBalancesArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenBalances'), createHTTPRequest(args, headers, signal)).then( + getTokenBalances = ( + req: GetTokenBalancesRequest, + headers?: object, + signal?: AbortSignal + ): Promise => { + return this.fetch( + this.url('GetTokenBalances'), + createHttpRequest(JsonEncode(req, 'GetTokenBalancesRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - balances: >_data.balances - } + return JsonDecode(_data, 'GetTokenBalancesResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getTokenBalancesByContract = ( - args: GetTokenBalancesByContractArgs, + req: GetTokenBalancesByContractRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalancesByContract'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetTokenBalancesByContract'), + createHttpRequest(JsonEncode(req, 'GetTokenBalancesByContractRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - balances: >_data.balances - } + return JsonDecode(_data, 'GetTokenBalancesByContractResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getTokenBalancesDetails = ( - args: GetTokenBalancesDetailsArgs, + req: GetTokenBalancesDetailsRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalancesDetails'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetTokenBalancesDetails'), + createHttpRequest(JsonEncode(req, 'GetTokenBalancesDetailsRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - nativeBalances: >_data.nativeBalances, - balances: >_data.balances - } + return JsonDecode(_data, 'GetTokenBalancesDetailsResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getTokenBalancesSummary = ( - args: GetTokenBalancesSummaryArgs, + req: GetTokenBalancesSummaryRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalancesSummary'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetTokenBalancesSummary'), + createHttpRequest(JsonEncode(req, 'GetTokenBalancesSummaryRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - nativeBalances: >_data.nativeBalances, - balances: >_data.balances - } + return JsonDecode(_data, 'GetTokenBalancesSummaryResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } getTransactionHistory = ( - args: GetTransactionHistoryArgs, + req: GetTransactionHistoryRequest, headers?: object, signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTransactionHistory'), createHTTPRequest(args, headers, signal)).then( + ): Promise => { + return this.fetch( + this.url('GetTransactionHistory'), + createHttpRequest(JsonEncode(req, 'GetTransactionHistoryRequest'), headers, signal) + ).then( res => { return buildResponse(res).then(_data => { - return { - page: _data.page, - transactions: >_data.transactions - } + return JsonDecode(_data, 'GetTransactionHistoryResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - ping = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Ping'), createHTTPRequest({}, headers, signal)).then( + 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 - } + return JsonDecode(_data, 'PingResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - runtimeStatus = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('RuntimeStatus'), createHTTPRequest({}, headers, signal)).then( + 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 - } + return JsonDecode(_data, 'RuntimeStatusResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } - version = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Version'), createHTTPRequest({}, headers, signal)).then( + 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 - } + return JsonDecode(_data, 'VersionResponse') }) }, error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) } ) } } -const createHTTPRequest = (body: object = {}, headers: object = {}, signal: AbortSignal | null = null): object => { - const reqHeaders: { [key: string]: string } = { ...headers, 'Content-Type': 'application/json' } - reqHeaders[WebrpcHeader] = WebrpcHeaderValue - - return { - method: 'POST', - headers: reqHeaders, - body: JSON.stringify(body || {}), - signal +const createHttpRequest = (body: string = '{}', headers: object = {}, signal: AbortSignal | null = null): object => { + const reqHeaders: { [key: string]: string } = { + ...headers, + 'Content-Type': 'application/json', + [WebrpcHeader]: WebrpcHeaderValue } + return { method: 'POST', headers: reqHeaders, body, signal } } const buildResponse = (res: Response): Promise => { @@ -1060,13 +1047,9 @@ const buildResponse = (res: Response): Promise => { try { data = JSON.parse(text) } catch (error) { - let message = '' - if (error instanceof Error) { - message = error.message - } throw WebrpcBadResponseError.new({ status: res.status, - cause: `JSON.parse(): ${message}: response text: ${text}` + cause: `JSON.parse(): ${error instanceof Error ? error.message : String(error)}: response text: ${text}` }) } if (!res.ok) { @@ -1077,517 +1060,493 @@ const buildResponse = (res: Response): Promise => { }) } +export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise + +export const JsonEncode = (obj: T, _typ: string = ''): string => { + return JSON.stringify(obj) +} + +export const JsonDecode = (data: string | any, _typ: string = ''): T => { + let parsed: any = data + if (typeof data === 'string') { + try { + parsed = JSON.parse(data) + } catch (err) { + throw WebrpcBadResponseError.new({ cause: `JsonDecode: JSON.parse failed: ${(err as Error).message}` }) + } + } + return parsed as T +} + // // Errors // +type WebrpcErrorParams = { name?: string; code?: number; message?: string; status?: number; cause?: string } + export class WebrpcError extends Error { - name: string code: number - message: string status: number - cause?: string - - /** @deprecated Use message instead of msg. Deprecated in webrpc v0.11.0. */ - msg: string - - constructor(name: string, code: number, message: string, status: number, cause?: string) { - super(message) - this.name = name || 'WebrpcError' - this.code = typeof code === 'number' ? code : 0 - this.message = message || `endpoint error ${this.code}` - this.msg = this.message - this.status = typeof status === 'number' ? status : 0 - this.cause = cause + + constructor(error: WebrpcErrorParams = {}) { + super(error.message) + this.name = error.name || 'WebrpcEndpointError' + this.code = typeof error.code === 'number' ? error.code : 0 + this.message = error.message || `endpoint error` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcError.prototype) } static new(payload: any): WebrpcError { - return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause) + return new this({ message: payload.message, code: payload.code, status: payload.status, cause: payload.cause }) } } -// Webrpc errors - export class WebrpcEndpointError extends WebrpcError { - constructor( - name: string = 'WebrpcEndpoint', - code: number = 0, - message: string = `endpoint error`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcEndpoint' + this.code = typeof error.code === 'number' ? error.code : 0 + this.message = error.message || `endpoint error` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcEndpointError.prototype) } } export class WebrpcRequestFailedError extends WebrpcError { - constructor( - name: string = 'WebrpcRequestFailed', - code: number = -1, - message: string = `request failed`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcRequestFailed' + this.code = typeof error.code === 'number' ? error.code : -1 + this.message = error.message || `request failed` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcRequestFailedError.prototype) } } export class WebrpcBadRouteError extends WebrpcError { - constructor( - name: string = 'WebrpcBadRoute', - code: number = -2, - message: string = `bad route`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadRoute' + this.code = typeof error.code === 'number' ? error.code : -2 + this.message = error.message || `bad route` + this.status = typeof error.status === 'number' ? error.status : 404 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadRouteError.prototype) } } export class WebrpcBadMethodError extends WebrpcError { - constructor( - name: string = 'WebrpcBadMethod', - code: number = -3, - message: string = `bad method`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadMethod' + this.code = typeof error.code === 'number' ? error.code : -3 + this.message = error.message || `bad method` + this.status = typeof error.status === 'number' ? error.status : 405 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadMethodError.prototype) } } export class WebrpcBadRequestError extends WebrpcError { - constructor( - name: string = 'WebrpcBadRequest', - code: number = -4, - message: string = `bad request`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadRequest' + this.code = typeof error.code === 'number' ? error.code : -4 + this.message = error.message || `bad request` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadRequestError.prototype) } } export class WebrpcBadResponseError extends WebrpcError { - constructor( - name: string = 'WebrpcBadResponse', - code: number = -5, - message: string = `bad response`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcBadResponse' + this.code = typeof error.code === 'number' ? error.code : -5 + this.message = error.message || `bad response` + this.status = typeof error.status === 'number' ? error.status : 500 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcBadResponseError.prototype) } } export class WebrpcServerPanicError extends WebrpcError { - constructor( - name: string = 'WebrpcServerPanic', - code: number = -6, - message: string = `server panic`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcServerPanic' + this.code = typeof error.code === 'number' ? error.code : -6 + this.message = error.message || `server panic` + this.status = typeof error.status === 'number' ? error.status : 500 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcServerPanicError.prototype) } } export class WebrpcInternalErrorError extends WebrpcError { - constructor( - name: string = 'WebrpcInternalError', - code: number = -7, - message: string = `internal error`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcInternalError' + this.code = typeof error.code === 'number' ? error.code : -7 + this.message = error.message || `internal error` + this.status = typeof error.status === 'number' ? error.status : 500 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcInternalErrorError.prototype) } } -export class WebrpcClientDisconnectedError extends WebrpcError { - constructor( - name: string = 'WebrpcClientDisconnected', - code: number = -8, - message: string = `client disconnected`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, WebrpcClientDisconnectedError.prototype) +export class WebrpcClientAbortedError extends WebrpcError { + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcClientAborted' + this.code = typeof error.code === 'number' ? error.code : -8 + this.message = error.message || `request aborted by client` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause + Object.setPrototypeOf(this, WebrpcClientAbortedError.prototype) } } export class WebrpcStreamLostError extends WebrpcError { - constructor( - name: string = 'WebrpcStreamLost', - code: number = -9, - message: string = `stream lost`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcStreamLost' + this.code = typeof error.code === 'number' ? error.code : -9 + this.message = error.message || `stream lost` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcStreamLostError.prototype) } } export class WebrpcStreamFinishedError extends WebrpcError { - constructor( - name: string = 'WebrpcStreamFinished', - code: number = -10, - message: string = `stream finished`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'WebrpcStreamFinished' + this.code = typeof error.code === 'number' ? error.code : -10 + this.message = error.message || `stream finished` + this.status = typeof error.status === 'number' ? error.status : 200 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, WebrpcStreamFinishedError.prototype) } } +// // Schema errors +// export class 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) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Aborted' + this.code = typeof error.code === 'number' ? error.code : 1005 + this.message = error.message || `Request aborted` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, AbortedError.prototype) } } export class AccessKeyMismatchError extends WebrpcError { - constructor( - name: string = 'AccessKeyMismatch', - code: number = 1102, - message: string = `Access key mismatch`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'AccessKeyMismatch' + this.code = typeof error.code === 'number' ? error.code : 1102 + this.message = error.message || `Access key mismatch` + this.status = typeof error.status === 'number' ? error.status : 409 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, AccessKeyMismatchError.prototype) } } export class AccessKeyNotFoundError extends WebrpcError { - constructor( - name: string = 'AccessKeyNotFound', - code: number = 1101, - message: string = `Access key not found`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'AccessKeyNotFound' + this.code = typeof error.code === 'number' ? error.code : 1101 + this.message = error.message || `Access key not found` + this.status = typeof error.status === 'number' ? error.status : 401 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, AccessKeyNotFoundError.prototype) } } export class AtLeastOneKeyError extends WebrpcError { - constructor( - 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) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'AtLeastOneKey' + this.code = typeof error.code === 'number' ? error.code : 1302 + this.message = error.message || `You need at least one Access Key` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, AtLeastOneKeyError.prototype) } } export class GeoblockedError extends WebrpcError { - constructor( - name: string = 'Geoblocked', - code: number = 1006, - message: string = `Geoblocked region`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Geoblocked' + this.code = typeof error.code === 'number' ? error.code : 1006 + this.message = error.message || `Geoblocked region` + this.status = typeof error.status === 'number' ? error.status : 451 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, GeoblockedError.prototype) } } export class InvalidArgumentError extends WebrpcError { - constructor( - name: string = 'InvalidArgument', - code: number = 2001, - message: string = `Invalid argument`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'InvalidArgument' + this.code = typeof error.code === 'number' ? error.code : 2001 + this.message = error.message || `Invalid argument` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, InvalidArgumentError.prototype) } } export class InvalidOriginError extends WebrpcError { - constructor( - name: string = 'InvalidOrigin', - code: number = 1103, - message: string = `Invalid origin for Access Key`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'InvalidOrigin' + this.code = typeof error.code === 'number' ? error.code : 1103 + this.message = error.message || `Invalid origin for Access Key` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, InvalidOriginError.prototype) } } export class InvalidServiceError extends WebrpcError { - constructor( - 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) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'InvalidService' + this.code = typeof error.code === 'number' ? error.code : 1104 + this.message = error.message || `Service not enabled for Access key` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, InvalidServiceError.prototype) } } export class MaxAccessKeysError extends WebrpcError { - constructor( - name: string = 'MaxAccessKeys', - code: number = 1301, - message: string = `Access keys limit reached`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'MaxAccessKeys' + this.code = typeof error.code === 'number' ? error.code : 1301 + this.message = error.message || `Access keys limit reached` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, MaxAccessKeysError.prototype) } } export class MetadataCallFailedError extends WebrpcError { - constructor( - name: string = 'MetadataCallFailed', - code: number = 3003, - message: string = `Metadata service call failed`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'MetadataCallFailed' + this.code = typeof error.code === 'number' ? error.code : 3003 + this.message = error.message || `Metadata service call failed` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, MetadataCallFailedError.prototype) } } export class MethodNotFoundError extends WebrpcError { - constructor( - name: string = 'MethodNotFound', - code: number = 1003, - message: string = `Method not found`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'MethodNotFound' + this.code = typeof error.code === 'number' ? error.code : 1003 + this.message = error.message || `Method not found` + this.status = typeof error.status === 'number' ? error.status : 404 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, MethodNotFoundError.prototype) } } export class NoDefaultKeyError extends WebrpcError { - constructor( - name: string = 'NoDefaultKey', - code: number = 1300, - message: string = `No default access key found`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'NoDefaultKey' + this.code = typeof error.code === 'number' ? error.code : 1300 + this.message = error.message || `No default access key found` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, NoDefaultKeyError.prototype) } } export class NotFoundError extends WebrpcError { - constructor( - name: string = 'NotFound', - code: number = 3000, - message: string = `Resource not found`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'NotFound' + this.code = typeof error.code === 'number' ? error.code : 3000 + this.message = error.message || `Resource not found` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, NotFoundError.prototype) } } export class PermissionDeniedError extends WebrpcError { - constructor( - name: string = 'PermissionDenied', - code: number = 1001, - message: string = `Permission denied`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'PermissionDenied' + this.code = typeof error.code === 'number' ? error.code : 1001 + this.message = error.message || `Permission denied` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, PermissionDeniedError.prototype) } } export class ProjectNotFoundError extends WebrpcError { - constructor( - name: string = 'ProjectNotFound', - code: number = 1100, - message: string = `Project not found`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'ProjectNotFound' + this.code = typeof error.code === 'number' ? error.code : 1100 + this.message = error.message || `Project not found` + this.status = typeof error.status === 'number' ? error.status : 401 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, ProjectNotFoundError.prototype) } } export class QueryFailedError extends WebrpcError { - constructor( - name: string = 'QueryFailed', - code: number = 2003, - message: string = `Query failed`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'QueryFailed' + this.code = typeof error.code === 'number' ? error.code : 2003 + this.message = error.message || `Query failed` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, QueryFailedError.prototype) } } export class QuotaExceededError extends WebrpcError { - constructor( - name: string = 'QuotaExceeded', - code: number = 1200, - message: string = `Quota exceeded`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'QuotaExceeded' + this.code = typeof error.code === 'number' ? error.code : 1200 + this.message = error.message || `Quota exceeded` + this.status = typeof error.status === 'number' ? error.status : 429 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, QuotaExceededError.prototype) } } export class RateLimitError extends WebrpcError { - constructor( - name: string = 'RateLimit', - code: number = 1201, - message: string = `Rate limit exceeded`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'RateLimit' + this.code = typeof error.code === 'number' ? error.code : 1201 + this.message = error.message || `Rate limit exceeded` + this.status = typeof error.status === 'number' ? error.status : 429 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, RateLimitError.prototype) } } export class RateLimitedError extends WebrpcError { - constructor( - name: string = 'RateLimited', - code: number = 1007, - message: string = `Rate-limited. Please slow down.`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'RateLimited' + this.code = typeof error.code === 'number' ? error.code : 1007 + this.message = error.message || `Rate-limited. Please slow down.` + this.status = typeof error.status === 'number' ? error.status : 429 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, RateLimitedError.prototype) } } export class RequestConflictError extends WebrpcError { - constructor( - name: string = 'RequestConflict', - code: number = 1004, - message: string = `Conflict with target resource`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'RequestConflict' + this.code = typeof error.code === 'number' ? error.code : 1004 + this.message = error.message || `Conflict with target resource` + this.status = typeof error.status === 'number' ? error.status : 409 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, RequestConflictError.prototype) } } export class ResourceExhaustedError extends WebrpcError { - constructor( - name: string = 'ResourceExhausted', - code: number = 2004, - message: string = `Resource exhausted`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'ResourceExhausted' + this.code = typeof error.code === 'number' ? error.code : 2004 + this.message = error.message || `Resource exhausted` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, ResourceExhaustedError.prototype) } } export class SessionExpiredError extends WebrpcError { - constructor( - name: string = 'SessionExpired', - code: number = 1002, - message: string = `Session expired`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'SessionExpired' + this.code = typeof error.code === 'number' ? error.code : 1002 + this.message = error.message || `Session expired` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, SessionExpiredError.prototype) } } export class TimeoutError extends WebrpcError { - constructor( - name: string = 'Timeout', - code: number = 1900, - message: string = `Request timed out`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Timeout' + this.code = typeof error.code === 'number' ? error.code : 1900 + this.message = error.message || `Request timed out` + this.status = typeof error.status === 'number' ? error.status : 408 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, TimeoutError.prototype) } } export class UnauthorizedError extends WebrpcError { - constructor( - name: string = 'Unauthorized', - code: number = 1000, - message: string = `Unauthorized access`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Unauthorized' + this.code = typeof error.code === 'number' ? error.code : 1000 + this.message = error.message || `Unauthorized access` + this.status = typeof error.status === 'number' ? error.status : 401 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, UnauthorizedError.prototype) } } export class UnauthorizedUserError extends WebrpcError { - constructor( - name: string = 'UnauthorizedUser', - code: number = 1105, - message: string = `Unauthorized user`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'UnauthorizedUser' + this.code = typeof error.code === 'number' ? error.code : 1105 + this.message = error.message || `Unauthorized user` + this.status = typeof error.status === 'number' ? error.status : 403 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, UnauthorizedUserError.prototype) } } export class UnavailableError extends WebrpcError { - constructor( - name: string = 'Unavailable', - code: number = 2002, - message: string = `Unavailable resource`, - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) + constructor(error: WebrpcErrorParams = {}) { + super(error) + this.name = error.name || 'Unavailable' + this.code = typeof error.code === 'number' ? error.code : 2002 + this.message = error.message || `Unavailable resource` + this.status = typeof error.status === 'number' ? error.status : 400 + if (error.cause !== undefined) this.cause = error.cause Object.setPrototypeOf(this, UnavailableError.prototype) } } @@ -1601,7 +1560,7 @@ export enum errors { WebrpcBadResponse = 'WebrpcBadResponse', WebrpcServerPanic = 'WebrpcServerPanic', WebrpcInternalError = 'WebrpcInternalError', - WebrpcClientDisconnected = 'WebrpcClientDisconnected', + WebrpcClientAborted = 'WebrpcClientAborted', WebrpcStreamLost = 'WebrpcStreamLost', WebrpcStreamFinished = 'WebrpcStreamFinished', Aborted = 'Aborted', @@ -1641,7 +1600,7 @@ export enum WebrpcErrorCodes { WebrpcBadResponse = -5, WebrpcServerPanic = -6, WebrpcInternalError = -7, - WebrpcClientDisconnected = -8, + WebrpcClientAborted = -8, WebrpcStreamLost = -9, WebrpcStreamFinished = -10, Aborted = 1005, @@ -1681,7 +1640,7 @@ export const webrpcErrorByCode: { [code: number]: any } = { [-5]: WebrpcBadResponseError, [-6]: WebrpcServerPanicError, [-7]: WebrpcInternalErrorError, - [-8]: WebrpcClientDisconnectedError, + [-8]: WebrpcClientAbortedError, [-9]: WebrpcStreamLostError, [-10]: WebrpcStreamFinishedError, [1005]: AbortedError, @@ -1712,4 +1671,58 @@ export const webrpcErrorByCode: { [code: number]: any } = { [2002]: UnavailableError } -export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise +// +// Webrpc +// + +export const WebrpcHeader = 'Webrpc' + +export const WebrpcHeaderValue = 'webrpc@v0.31.0;gen-typescript@v0.22.5;sequence-indexer@v0.4.0' + +type WebrpcGenVersions = { + WebrpcGenVersion: string + codeGenName: string + codeGenVersion: string + schemaName: string + schemaVersion: string +} + +export function VersionFromHeader(headers: Headers): WebrpcGenVersions { + const headerValue = headers.get(WebrpcHeader) + if (!headerValue) { + return { + WebrpcGenVersion: '', + codeGenName: '', + codeGenVersion: '', + schemaName: '', + schemaVersion: '' + } + } + + return parseWebrpcGenVersions(headerValue) +} + +function parseWebrpcGenVersions(header: string): WebrpcGenVersions { + const versions = header.split(';') + if (versions.length < 3) { + return { + WebrpcGenVersion: '', + codeGenName: '', + codeGenVersion: '', + schemaName: '', + schemaVersion: '' + } + } + + const [_, WebrpcGenVersion] = versions[0]!.split('@') + const [codeGenName, codeGenVersion] = versions[1]!.split('@') + const [schemaName, schemaVersion] = versions[2]!.split('@') + + return { + WebrpcGenVersion: WebrpcGenVersion ?? '', + codeGenName: codeGenName ?? '', + codeGenVersion: codeGenVersion ?? '', + schemaName: schemaName ?? '', + schemaVersion: schemaVersion ?? '' + } +} From d19f601a930479799e56aa4c52f9b3c316872bd6 Mon Sep 17 00:00:00 2001 From: pkieltyka <18831+pkieltyka@users.noreply.github.com> Date: Mon, 24 Nov 2025 14:33:09 +0000 Subject: [PATCH 3/8] [AUTOMATED] Update: proto/clients/indexer*.gen.ts --- packages/indexer/src/indexer.gen.ts | 147 ++++++-------------------- packages/indexer/src/indexergw.gen.ts | 43 ++------ 2 files changed, 44 insertions(+), 146 deletions(-) diff --git a/packages/indexer/src/indexer.gen.ts b/packages/indexer/src/indexer.gen.ts index 08004d443..c2db84f68 100644 --- a/packages/indexer/src/indexer.gen.ts +++ b/packages/indexer/src/indexer.gen.ts @@ -1,7 +1,7 @@ /* eslint-disable */ // sequence-indexer v0.4.0 42b746c7de262224143cc5c55403e7619c514ec4 // -- -// Code generated by Webrpc-gen@v0.31.0 with typescript generator. DO NOT EDIT. +// Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. // // webrpc-gen -schema=merged.gen.json -service=Indexer -target=typescript -client -out=./clients/indexer.gen.ts @@ -1285,10 +1285,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('AddWebhookListener'), - createHttpRequest(JsonEncode(req, 'AddWebhookListenerRequest'), headers, signal) - ).then( + return this.fetch(this.url('AddWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'AddWebhookListenerResponse') @@ -1305,10 +1302,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('FetchTransactionReceipt'), - createHttpRequest(JsonEncode(req, 'FetchTransactionReceiptRequest'), headers, signal) - ).then( + return this.fetch(this.url('FetchTransactionReceipt'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'FetchTransactionReceiptResponse') @@ -1325,10 +1319,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('FetchTransactionReceiptWithFilter'), - createHttpRequest(JsonEncode(req, 'FetchTransactionReceiptWithFilterRequest'), headers, signal) - ).then( + return this.fetch(this.url('FetchTransactionReceiptWithFilter'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'FetchTransactionReceiptWithFilterResponse') @@ -1345,10 +1336,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetAllWebhookListeners'), - createHttpRequest(JsonEncode(req, 'GetAllWebhookListenersRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetAllWebhookListeners'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetAllWebhookListenersResponse') @@ -1365,10 +1353,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetBalanceUpdates'), - createHttpRequest(JsonEncode(req, 'GetBalanceUpdatesRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetBalanceUpdates'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetBalanceUpdatesResponse') @@ -1394,10 +1379,7 @@ export class Indexer implements IndexerClient { } getEtherBalance = (req: GetEtherBalanceRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch( - this.url('GetEtherBalance'), - createHttpRequest(JsonEncode(req, 'GetEtherBalanceRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetEtherBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetEtherBalanceResponse') @@ -1414,10 +1396,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetMarketplaceOrders'), - createHttpRequest(JsonEncode(req, 'GetMarketplaceOrdersRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetMarketplaceOrders'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetMarketplaceOrdersResponse') @@ -1434,10 +1413,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetMarketplaceTopOrders'), - createHttpRequest(JsonEncode(req, 'GetMarketplaceTopOrdersRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetMarketplaceTopOrders'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetMarketplaceTopOrdersResponse') @@ -1454,10 +1430,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetNativeTokenBalance'), - createHttpRequest(JsonEncode(req, 'GetNativeTokenBalanceRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetNativeTokenBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetNativeTokenBalanceResponse') @@ -1470,7 +1443,7 @@ export class Indexer implements IndexerClient { } getPrices = (req: GetPricesRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetPrices'), createHttpRequest(JsonEncode(req, 'GetPricesRequest'), headers, signal)).then( + return this.fetch(this.url('GetPrices'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetPricesResponse') @@ -1487,10 +1460,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetTokenBalances'), - createHttpRequest(JsonEncode(req, 'GetTokenBalancesRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetTokenBalances'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTokenBalancesResponse') @@ -1507,10 +1477,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetTokenBalancesByContract'), - createHttpRequest(JsonEncode(req, 'GetTokenBalancesByContractRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetTokenBalancesByContract'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTokenBalancesByContractResponse') @@ -1527,10 +1494,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetTokenBalancesDetails'), - createHttpRequest(JsonEncode(req, 'GetTokenBalancesDetailsRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetTokenBalancesDetails'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTokenBalancesDetailsResponse') @@ -1547,10 +1511,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetTokenBalancesSummary'), - createHttpRequest(JsonEncode(req, 'GetTokenBalancesSummaryRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetTokenBalancesSummary'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTokenBalancesSummaryResponse') @@ -1567,10 +1528,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetTokenIDRanges'), - createHttpRequest(JsonEncode(req, 'GetTokenIDRangesRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetTokenIDRanges'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTokenIDRangesResponse') @@ -1583,7 +1541,7 @@ export class Indexer implements IndexerClient { } getTokenIDs = (req: GetTokenIDsRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenIDs'), createHttpRequest(JsonEncode(req, 'GetTokenIDsRequest'), headers, signal)).then( + return this.fetch(this.url('GetTokenIDs'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTokenIDsResponse') @@ -1600,10 +1558,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetTokenSupplies'), - createHttpRequest(JsonEncode(req, 'GetTokenSuppliesRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetTokenSupplies'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTokenSuppliesResponse') @@ -1620,10 +1575,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetTokenSuppliesMap'), - createHttpRequest(JsonEncode(req, 'GetTokenSuppliesMapRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetTokenSuppliesMap'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTokenSuppliesMapResponse') @@ -1640,10 +1592,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetTransactionHistory'), - createHttpRequest(JsonEncode(req, 'GetTransactionHistoryRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetTransactionHistory'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTransactionHistoryResponse') @@ -1660,10 +1609,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetWebhookListener'), - createHttpRequest(JsonEncode(req, 'GetWebhookListenerRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetWebhookListenerResponse') @@ -1680,10 +1626,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('PauseAllWebhookListeners'), - createHttpRequest(JsonEncode(req, 'PauseAllWebhookListenersRequest'), headers, signal) - ).then( + return this.fetch(this.url('PauseAllWebhookListeners'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'PauseAllWebhookListenersResponse') @@ -1713,10 +1656,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('RemoveAllWebhookListeners'), - createHttpRequest(JsonEncode(req, 'RemoveAllWebhookListenersRequest'), headers, signal) - ).then( + return this.fetch(this.url('RemoveAllWebhookListeners'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'RemoveAllWebhookListenersResponse') @@ -1733,10 +1673,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('RemoveWebhookListener'), - createHttpRequest(JsonEncode(req, 'RemoveWebhookListenerRequest'), headers, signal) - ).then( + return this.fetch(this.url('RemoveWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'RemoveWebhookListenerResponse') @@ -1753,10 +1690,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('ResumeAllWebhookListeners'), - createHttpRequest(JsonEncode(req, 'ResumeAllWebhookListenersRequest'), headers, signal) - ).then( + return this.fetch(this.url('ResumeAllWebhookListeners'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'ResumeAllWebhookListenersResponse') @@ -1795,10 +1729,7 @@ export class Indexer implements IndexerClient { } const _fetch = () => - this.fetch( - this.url('SubscribeBalanceUpdates'), - createHttpRequest(JsonEncode(req, 'SubscribeBalanceUpdatesRequest'), options.headers, abortSignal) - ).then( + this.fetch(this.url('SubscribeBalanceUpdates'), createHttpRequest(JsonEncode(req), options.headers, abortSignal)).then( async res => { await sseResponse(res, options, _fetch) }, @@ -1827,10 +1758,7 @@ export class Indexer implements IndexerClient { } const _fetch = () => - this.fetch( - this.url('SubscribeEvents'), - createHttpRequest(JsonEncode(req, 'SubscribeEventsRequest'), options.headers, abortSignal) - ).then( + this.fetch(this.url('SubscribeEvents'), createHttpRequest(JsonEncode(req), options.headers, abortSignal)).then( async res => { await sseResponse(res, options, _fetch) }, @@ -1859,10 +1787,7 @@ export class Indexer implements IndexerClient { } const _fetch = () => - this.fetch( - this.url('SubscribeReceipts'), - createHttpRequest(JsonEncode(req, 'SubscribeReceiptsRequest'), options.headers, abortSignal) - ).then( + this.fetch(this.url('SubscribeReceipts'), createHttpRequest(JsonEncode(req), options.headers, abortSignal)).then( async res => { await sseResponse(res, options, _fetch) }, @@ -1878,7 +1803,7 @@ export class Indexer implements IndexerClient { } } syncBalance = (req: SyncBalanceRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('SyncBalance'), createHttpRequest(JsonEncode(req, 'SyncBalanceRequest'), headers, signal)).then( + return this.fetch(this.url('SyncBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'SyncBalanceResponse') @@ -1895,10 +1820,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('ToggleWebhookListener'), - createHttpRequest(JsonEncode(req, 'ToggleWebhookListenerRequest'), headers, signal) - ).then( + return this.fetch(this.url('ToggleWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'ToggleWebhookListenerResponse') @@ -1915,10 +1837,7 @@ export class Indexer implements IndexerClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('UpdateWebhookListener'), - createHttpRequest(JsonEncode(req, 'UpdateWebhookListenerRequest'), headers, signal) - ).then( + return this.fetch(this.url('UpdateWebhookListener'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'UpdateWebhookListenerResponse') @@ -2102,7 +2021,7 @@ export interface WebrpcStreamController { closed: Promise } -export const JsonEncode = (obj: T, _typ: string = ''): string => { +export const JsonEncode = (obj: T): string => { return JSON.stringify(obj) } @@ -2717,7 +2636,7 @@ export const webrpcErrorByCode: { [code: number]: any } = { export const WebrpcHeader = 'Webrpc' -export const WebrpcHeaderValue = 'webrpc@v0.31.0;gen-typescript@v0.22.5;sequence-indexer@v0.4.0' +export const WebrpcHeaderValue = 'webrpc@v0.31.2;gen-typescript@v0.23.1;sequence-indexer@v0.4.0' type WebrpcGenVersions = { WebrpcGenVersion: string diff --git a/packages/indexer/src/indexergw.gen.ts b/packages/indexer/src/indexergw.gen.ts index 31d484100..0b64769c8 100644 --- a/packages/indexer/src/indexergw.gen.ts +++ b/packages/indexer/src/indexergw.gen.ts @@ -1,7 +1,7 @@ /* eslint-disable */ // sequence-indexer v0.4.0 f957af073daf1c3c88b0dc45ba70695f982181e7 // -- -// Code generated by Webrpc-gen@v0.31.0 with typescript generator. DO NOT EDIT. +// Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. // // webrpc-gen -schema=merged.gen.json -service=IndexerGateway -target=typescript -client -out=./clients/indexergw.gen.ts @@ -844,10 +844,7 @@ export class IndexerGateway implements IndexerGatewayClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetBalanceUpdates'), - createHttpRequest(JsonEncode(req, 'GetBalanceUpdatesRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetBalanceUpdates'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetBalanceUpdatesResponse') @@ -860,7 +857,7 @@ export class IndexerGateway implements IndexerGatewayClient { } getChains = (req: GetChainsRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetChains'), createHttpRequest(JsonEncode(req, 'GetChainsRequest'), headers, signal)).then( + return this.fetch(this.url('GetChains'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetChainsResponse') @@ -877,10 +874,7 @@ export class IndexerGateway implements IndexerGatewayClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetNativeTokenBalance'), - createHttpRequest(JsonEncode(req, 'GetNativeTokenBalanceRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetNativeTokenBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetNativeTokenBalanceResponse') @@ -897,10 +891,7 @@ export class IndexerGateway implements IndexerGatewayClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetTokenBalances'), - createHttpRequest(JsonEncode(req, 'GetTokenBalancesRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetTokenBalances'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTokenBalancesResponse') @@ -917,10 +908,7 @@ export class IndexerGateway implements IndexerGatewayClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetTokenBalancesByContract'), - createHttpRequest(JsonEncode(req, 'GetTokenBalancesByContractRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetTokenBalancesByContract'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTokenBalancesByContractResponse') @@ -937,10 +925,7 @@ export class IndexerGateway implements IndexerGatewayClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetTokenBalancesDetails'), - createHttpRequest(JsonEncode(req, 'GetTokenBalancesDetailsRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetTokenBalancesDetails'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTokenBalancesDetailsResponse') @@ -957,10 +942,7 @@ export class IndexerGateway implements IndexerGatewayClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetTokenBalancesSummary'), - createHttpRequest(JsonEncode(req, 'GetTokenBalancesSummaryRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetTokenBalancesSummary'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTokenBalancesSummaryResponse') @@ -977,10 +959,7 @@ export class IndexerGateway implements IndexerGatewayClient { headers?: object, signal?: AbortSignal ): Promise => { - return this.fetch( - this.url('GetTransactionHistory'), - createHttpRequest(JsonEncode(req, 'GetTransactionHistoryRequest'), headers, signal) - ).then( + return this.fetch(this.url('GetTransactionHistory'), createHttpRequest(JsonEncode(req), headers, signal)).then( res => { return buildResponse(res).then(_data => { return JsonDecode(_data, 'GetTransactionHistoryResponse') @@ -1062,7 +1041,7 @@ const buildResponse = (res: Response): Promise => { export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise -export const JsonEncode = (obj: T, _typ: string = ''): string => { +export const JsonEncode = (obj: T): string => { return JSON.stringify(obj) } @@ -1677,7 +1656,7 @@ export const webrpcErrorByCode: { [code: number]: any } = { export const WebrpcHeader = 'Webrpc' -export const WebrpcHeaderValue = 'webrpc@v0.31.0;gen-typescript@v0.22.5;sequence-indexer@v0.4.0' +export const WebrpcHeaderValue = 'webrpc@v0.31.2;gen-typescript@v0.23.1;sequence-indexer@v0.4.0' type WebrpcGenVersions = { WebrpcGenVersion: string From ac25c7f1ec86560ad162b42feb4366b5ae59b9d6 Mon Sep 17 00:00:00 2001 From: marino39 <722509+marino39@users.noreply.github.com> Date: Tue, 25 Nov 2025 12:07:53 +0000 Subject: [PATCH 4/8] [AUTOMATED] Update: proto/clients/indexer*.gen.ts --- packages/indexer/src/indexer.gen.ts | 39 +++++++++++++++++---------- packages/indexer/src/indexergw.gen.ts | 39 +++++++++++++++++---------- 2 files changed, 50 insertions(+), 28 deletions(-) diff --git a/packages/indexer/src/indexer.gen.ts b/packages/indexer/src/indexer.gen.ts index c2db84f68..855e656eb 100644 --- a/packages/indexer/src/indexer.gen.ts +++ b/packages/indexer/src/indexer.gen.ts @@ -1,5 +1,5 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 42b746c7de262224143cc5c55403e7619c514ec4 +// sequence-indexer v0.4.0 1532960ee7a152a172fcfb97cdc150b16c7dc297 // -- // Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. // @@ -12,7 +12,7 @@ export const WebrpcVersion = 'v1' export const WebrpcSchemaVersion = 'v0.4.0' // Schema hash generated from your RIDL schema -export const WebrpcSchemaHash = '42b746c7de262224143cc5c55403e7619c514ec4' +export const WebrpcSchemaHash = '1532960ee7a152a172fcfb97cdc150b16c7dc297' // // Client interface @@ -398,19 +398,29 @@ export interface ContractInfo { status: ResourceStatus } +export interface ContractInfoExtensionBridgeInfo { + tokenAddress: string +} + +export interface ContractInfoExtensionIndexingInfo { + useOnChainBalance: boolean +} + 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 + link?: string + description?: string + categories?: Array + bridgeInfo?: { [key: string]: ContractInfoExtensionBridgeInfo } + indexingInfo?: ContractInfoExtensionIndexingInfo + ogImage?: string + ogName?: string + originChainId?: number + originAddress?: string + blacklist?: boolean + verified?: boolean + verifiedBy?: string + featured?: boolean + featureIndex?: number } export enum ContractType { @@ -753,6 +763,7 @@ export interface TokenIDRange { } export interface TokenMetadata { + chainId?: number contractAddress?: string tokenId: string source: string diff --git a/packages/indexer/src/indexergw.gen.ts b/packages/indexer/src/indexergw.gen.ts index 0b64769c8..037b6a76e 100644 --- a/packages/indexer/src/indexergw.gen.ts +++ b/packages/indexer/src/indexergw.gen.ts @@ -1,5 +1,5 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 f957af073daf1c3c88b0dc45ba70695f982181e7 +// sequence-indexer v0.4.0 7a9b9e18649eaeedb05601c567192f27cb831ee4 // -- // Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. // @@ -12,7 +12,7 @@ export const WebrpcVersion = 'v1' export const WebrpcSchemaVersion = 'v0.4.0' // Schema hash generated from your RIDL schema -export const WebrpcSchemaHash = 'f957af073daf1c3c88b0dc45ba70695f982181e7' +export const WebrpcSchemaHash = '7a9b9e18649eaeedb05601c567192f27cb831ee4' // // Client interface @@ -171,19 +171,29 @@ export interface ContractInfo { status: ResourceStatus } +export interface ContractInfoExtensionBridgeInfo { + tokenAddress: string +} + +export interface ContractInfoExtensionIndexingInfo { + useOnChainBalance: boolean +} + 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 + link?: string + description?: string + categories?: Array + bridgeInfo?: { [key: string]: ContractInfoExtensionBridgeInfo } + indexingInfo?: ContractInfoExtensionIndexingInfo + ogImage?: string + ogName?: string + originChainId?: number + originAddress?: string + blacklist?: boolean + verified?: boolean + verifiedBy?: string + featured?: boolean + featureIndex?: number } export enum ContractType { @@ -526,6 +536,7 @@ export interface TokenIDRange { } export interface TokenMetadata { + chainId?: number contractAddress?: string tokenId: string source: string From 03a67db0612dd2934fcb0ffeda4798125696d46d Mon Sep 17 00:00:00 2001 From: xiam <385670+xiam@users.noreply.github.com> Date: Tue, 25 Nov 2025 17:16:15 +0000 Subject: [PATCH 5/8] [AUTOMATED] Update: proto/clients/indexer*.gen.ts --- packages/indexer/src/indexer.gen.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/indexer/src/indexer.gen.ts b/packages/indexer/src/indexer.gen.ts index 855e656eb..c9d092274 100644 --- a/packages/indexer/src/indexer.gen.ts +++ b/packages/indexer/src/indexer.gen.ts @@ -1,5 +1,5 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 1532960ee7a152a172fcfb97cdc150b16c7dc297 +// sequence-indexer v0.4.0 745836d4b69c5544f7de1f7f83a6fa0b30e35769 // -- // Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. // @@ -12,7 +12,7 @@ export const WebrpcVersion = 'v1' export const WebrpcSchemaVersion = 'v0.4.0' // Schema hash generated from your RIDL schema -export const WebrpcSchemaHash = '1532960ee7a152a172fcfb97cdc150b16c7dc297' +export const WebrpcSchemaHash = '745836d4b69c5544f7de1f7f83a6fa0b30e35769' // // Client interface @@ -1092,7 +1092,6 @@ export interface GetTokenIDsResponse { export interface GetTokenSuppliesRequest { contractAddress: string includeMetadata?: boolean - metadataOptions?: MetadataOptions page?: Page } @@ -1105,7 +1104,6 @@ export interface GetTokenSuppliesResponse { export interface GetTokenSuppliesMapRequest { tokenMap: { [key: string]: Array } includeMetadata?: boolean - metadataOptions?: MetadataOptions } export interface GetTokenSuppliesMapResponse { From afcffbdd8a6bd4235f8b709f2a204d85081b082d Mon Sep 17 00:00:00 2001 From: marino39 <722509+marino39@users.noreply.github.com> Date: Thu, 27 Nov 2025 10:43:49 +0000 Subject: [PATCH 6/8] [AUTOMATED] Update: proto/clients/indexer*.gen.ts --- packages/indexer/src/indexer.gen.ts | 118 ++++++++++++++++++++------ packages/indexer/src/indexergw.gen.ts | 68 ++++++++++++++- 2 files changed, 157 insertions(+), 29 deletions(-) diff --git a/packages/indexer/src/indexer.gen.ts b/packages/indexer/src/indexer.gen.ts index c9d092274..4a6f47bd2 100644 --- a/packages/indexer/src/indexer.gen.ts +++ b/packages/indexer/src/indexer.gen.ts @@ -1,5 +1,5 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 745836d4b69c5544f7de1f7f83a6fa0b30e35769 +// sequence-indexer v0.4.0 e954f2ab6a7aac1d14fe89ba64a5e228aaeef7cc // -- // Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. // @@ -12,7 +12,7 @@ export const WebrpcVersion = 'v1' export const WebrpcSchemaVersion = 'v0.4.0' // Schema hash generated from your RIDL schema -export const WebrpcSchemaHash = '745836d4b69c5544f7de1f7f83a6fa0b30e35769' +export const WebrpcSchemaHash = 'e954f2ab6a7aac1d14fe89ba64a5e228aaeef7cc' // // Client interface @@ -132,8 +132,6 @@ export interface IndexerClient { signal?: AbortSignal ): Promise - getPrices(req: GetPricesRequest, 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. @@ -222,6 +220,10 @@ export interface IndexerClient { */ getTokenIDs(req: GetTokenIDsRequest, headers?: object, signal?: AbortSignal): Promise + getTokenPrice(req: GetTokenPriceRequest, headers?: object, signal?: AbortSignal): Promise + + getTokenPrices(req: GetTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise + /** * GetTokenSupplies returns the set of tokenIDs used by a contract address, supporting ERC-20, ERC-721, and ERC-1155 * contracts, and their respective supply as well. @@ -253,6 +255,8 @@ export interface IndexerClient { getWebhookListener(req: GetWebhookListenerRequest, headers?: object, signal?: AbortSignal): Promise + listTokenPrices(req: ListTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise + pauseAllWebhookListeners( req: PauseAllWebhookListenersRequest, headers?: object, @@ -532,6 +536,12 @@ export interface GatewayNativeTokenBalances { results: Array } +export interface GatewayPrice { + chainID: number + errorReason?: string + results: Array +} + export interface GatewayRuntimeStatus { healthOK: boolean startTime: string @@ -548,6 +558,11 @@ export interface GatewayTokenBalance { results: Array } +export interface GatewayTokenPriceQuery { + chainID: number + queries: Array +} + export interface GatewayTransaction { chainId: number errorReason?: string @@ -786,6 +801,11 @@ export interface TokenMetadata { lastFetched?: string } +export interface TokenPriceQuery { + contractAddress: string + tokenID?: string +} + export interface TokenSupply { tokenID: string supply: string @@ -1008,15 +1028,6 @@ export interface GetNativeTokenBalanceResponse { balance: NativeTokenBalance } -export interface GetPricesRequest { - page?: Page -} - -export interface GetPricesResponse { - page: Page - prices: Array -} - export interface GetTokenBalancesRequest { accountAddress?: string contractAddress?: string @@ -1089,6 +1100,22 @@ export interface GetTokenIDsResponse { tokenIDs: Array } +export interface GetTokenPriceRequest { + q: TokenPriceQuery +} + +export interface GetTokenPriceResponse { + price: Price +} + +export interface GetTokenPricesRequest { + q: Array +} + +export interface GetTokenPricesResponse { + prices: Array +} + export interface GetTokenSuppliesRequest { contractAddress: string includeMetadata?: boolean @@ -1131,6 +1158,15 @@ export interface GetWebhookListenerResponse { listener: WebhookListener } +export interface ListTokenPricesRequest { + page?: Page +} + +export interface ListTokenPricesResponse { + page: Page + prices: Array +} + export interface PauseAllWebhookListenersRequest { projectId?: number } @@ -1262,7 +1298,6 @@ export class Indexer implements IndexerClient { getMarketplaceOrders: (req: GetMarketplaceOrdersRequest) => ['Indexer', 'getMarketplaceOrders', req] as const, getMarketplaceTopOrders: (req: GetMarketplaceTopOrdersRequest) => ['Indexer', 'getMarketplaceTopOrders', req] as const, getNativeTokenBalance: (req: GetNativeTokenBalanceRequest) => ['Indexer', 'getNativeTokenBalance', req] as const, - getPrices: (req: GetPricesRequest) => ['Indexer', 'getPrices', req] as const, getTokenBalances: (req: GetTokenBalancesRequest) => ['Indexer', 'getTokenBalances', req] as const, getTokenBalancesByContract: (req: GetTokenBalancesByContractRequest) => ['Indexer', 'getTokenBalancesByContract', req] as const, @@ -1270,10 +1305,13 @@ export class Indexer implements IndexerClient { getTokenBalancesSummary: (req: GetTokenBalancesSummaryRequest) => ['Indexer', 'getTokenBalancesSummary', req] as const, getTokenIDRanges: (req: GetTokenIDRangesRequest) => ['Indexer', 'getTokenIDRanges', req] as const, getTokenIDs: (req: GetTokenIDsRequest) => ['Indexer', 'getTokenIDs', req] as const, + getTokenPrice: (req: GetTokenPriceRequest) => ['Indexer', 'getTokenPrice', req] as const, + getTokenPrices: (req: GetTokenPricesRequest) => ['Indexer', 'getTokenPrices', req] as const, getTokenSupplies: (req: GetTokenSuppliesRequest) => ['Indexer', 'getTokenSupplies', req] as const, getTokenSuppliesMap: (req: GetTokenSuppliesMapRequest) => ['Indexer', 'getTokenSuppliesMap', req] as const, getTransactionHistory: (req: GetTransactionHistoryRequest) => ['Indexer', 'getTransactionHistory', req] as const, getWebhookListener: (req: GetWebhookListenerRequest) => ['Indexer', 'getWebhookListener', req] as const, + listTokenPrices: (req: ListTokenPricesRequest) => ['Indexer', 'listTokenPrices', req] as const, pauseAllWebhookListeners: (req: PauseAllWebhookListenersRequest) => ['Indexer', 'pauseAllWebhookListeners', req] as const, ping: () => ['Indexer', 'ping'] as const, removeAllWebhookListeners: (req: RemoveAllWebhookListenersRequest) => ['Indexer', 'removeAllWebhookListeners', req] as const, @@ -1451,19 +1489,6 @@ export class Indexer implements IndexerClient { ) } - getPrices = (req: GetPricesRequest, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetPrices'), createHttpRequest(JsonEncode(req), headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return JsonDecode(_data, 'GetPricesResponse') - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) - } - ) - } - getTokenBalances = ( req: GetTokenBalancesRequest, headers?: object, @@ -1562,6 +1587,32 @@ export class Indexer implements IndexerClient { ) } + getTokenPrice = (req: GetTokenPriceRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetTokenPrice'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenPriceResponse') + }) + }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } + ) + } + + getTokenPrices = (req: GetTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetTokenPrices'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenPricesResponse') + }) + }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } + ) + } + getTokenSupplies = ( req: GetTokenSuppliesRequest, headers?: object, @@ -1630,6 +1681,19 @@ export class Indexer implements IndexerClient { ) } + listTokenPrices = (req: ListTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('ListTokenPrices'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'ListTokenPricesResponse') + }) + }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } + ) + } + pauseAllWebhookListeners = ( req: PauseAllWebhookListenersRequest, headers?: object, diff --git a/packages/indexer/src/indexergw.gen.ts b/packages/indexer/src/indexergw.gen.ts index 037b6a76e..6c76b73a8 100644 --- a/packages/indexer/src/indexergw.gen.ts +++ b/packages/indexer/src/indexergw.gen.ts @@ -1,5 +1,5 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 7a9b9e18649eaeedb05601c567192f27cb831ee4 +// sequence-indexer v0.4.0 55682a7b898c05eb9201eef2e0043f6ca381d383 // -- // Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. // @@ -12,7 +12,7 @@ export const WebrpcVersion = 'v1' export const WebrpcSchemaVersion = 'v0.4.0' // Schema hash generated from your RIDL schema -export const WebrpcSchemaHash = '7a9b9e18649eaeedb05601c567192f27cb831ee4' +export const WebrpcSchemaHash = '55682a7b898c05eb9201eef2e0043f6ca381d383' // // Client interface @@ -83,6 +83,10 @@ export interface IndexerGatewayClient { signal?: AbortSignal ): Promise + getTokenPrice(req: GetTokenPriceRequest, headers?: object, signal?: AbortSignal): Promise + + getTokenPrices(req: GetTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise + /** * GetTransactionHistory returns the history of mined transactions for the * given account on all indexer nodes, which includes a list of token transfer @@ -305,6 +309,12 @@ export interface GatewayNativeTokenBalances { results: Array } +export interface GatewayPrice { + chainID: number + errorReason?: string + results: Array +} + export interface GatewayRuntimeStatus { healthOK: boolean startTime: string @@ -321,6 +331,11 @@ export interface GatewayTokenBalance { results: Array } +export interface GatewayTokenPriceQuery { + chainID: number + queries: Array +} + export interface GatewayTransaction { chainId: number errorReason?: string @@ -559,6 +574,11 @@ export interface TokenMetadata { lastFetched?: string } +export interface TokenPriceQuery { + contractAddress: string + tokenID?: string +} + export interface TokenSupply { tokenID: string supply: string @@ -784,6 +804,22 @@ export interface GetTokenBalancesSummaryResponse { balances: Array } +export interface GetTokenPriceRequest { + q: GatewayTokenPriceQuery +} + +export interface GetTokenPriceResponse { + price: GatewayPrice +} + +export interface GetTokenPricesRequest { + q: Array +} + +export interface GetTokenPricesResponse { + prices: Array +} + export interface GetTransactionHistoryRequest { chainIds?: Array networks?: Array @@ -844,6 +880,8 @@ export class IndexerGateway implements IndexerGatewayClient { ['IndexerGateway', 'getTokenBalancesByContract', req] as const, getTokenBalancesDetails: (req: GetTokenBalancesDetailsRequest) => ['IndexerGateway', 'getTokenBalancesDetails', req] as const, getTokenBalancesSummary: (req: GetTokenBalancesSummaryRequest) => ['IndexerGateway', 'getTokenBalancesSummary', req] as const, + getTokenPrice: (req: GetTokenPriceRequest) => ['IndexerGateway', 'getTokenPrice', req] as const, + getTokenPrices: (req: GetTokenPricesRequest) => ['IndexerGateway', 'getTokenPrices', req] as const, getTransactionHistory: (req: GetTransactionHistoryRequest) => ['IndexerGateway', 'getTransactionHistory', req] as const, ping: () => ['IndexerGateway', 'ping'] as const, runtimeStatus: () => ['IndexerGateway', 'runtimeStatus'] as const, @@ -965,6 +1003,32 @@ export class IndexerGateway implements IndexerGatewayClient { ) } + getTokenPrice = (req: GetTokenPriceRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetTokenPrice'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenPriceResponse') + }) + }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } + ) + } + + getTokenPrices = (req: GetTokenPricesRequest, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch(this.url('GetTokenPrices'), createHttpRequest(JsonEncode(req), headers, signal)).then( + res => { + return buildResponse(res).then(_data => { + return JsonDecode(_data, 'GetTokenPricesResponse') + }) + }, + error => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error instanceof Error ? error.message : String(error)}` }) + } + ) + } + getTransactionHistory = ( req: GetTransactionHistoryRequest, headers?: object, From a8c0df28dd75af84d80796192a993e217fb5620d Mon Sep 17 00:00:00 2001 From: marino39 <722509+marino39@users.noreply.github.com> Date: Thu, 27 Nov 2025 15:18:49 +0000 Subject: [PATCH 7/8] [AUTOMATED] Update: proto/clients/indexer*.gen.ts --- packages/indexer/src/indexer.gen.ts | 4 ++-- packages/indexer/src/indexergw.gen.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/indexer/src/indexer.gen.ts b/packages/indexer/src/indexer.gen.ts index 4a6f47bd2..01f66645a 100644 --- a/packages/indexer/src/indexer.gen.ts +++ b/packages/indexer/src/indexer.gen.ts @@ -1,5 +1,5 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 e954f2ab6a7aac1d14fe89ba64a5e228aaeef7cc +// sequence-indexer v0.4.0 42364084a9e85e579205500b8748d9630b380cbb // -- // Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. // @@ -12,7 +12,7 @@ export const WebrpcVersion = 'v1' export const WebrpcSchemaVersion = 'v0.4.0' // Schema hash generated from your RIDL schema -export const WebrpcSchemaHash = 'e954f2ab6a7aac1d14fe89ba64a5e228aaeef7cc' +export const WebrpcSchemaHash = '42364084a9e85e579205500b8748d9630b380cbb' // // Client interface diff --git a/packages/indexer/src/indexergw.gen.ts b/packages/indexer/src/indexergw.gen.ts index 6c76b73a8..ef867b3fd 100644 --- a/packages/indexer/src/indexergw.gen.ts +++ b/packages/indexer/src/indexergw.gen.ts @@ -1,5 +1,5 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 55682a7b898c05eb9201eef2e0043f6ca381d383 +// sequence-indexer v0.4.0 ec2391094a2acda7ad674fb9006b56cf5984919d // -- // Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. // @@ -12,7 +12,7 @@ export const WebrpcVersion = 'v1' export const WebrpcSchemaVersion = 'v0.4.0' // Schema hash generated from your RIDL schema -export const WebrpcSchemaHash = '55682a7b898c05eb9201eef2e0043f6ca381d383' +export const WebrpcSchemaHash = 'ec2391094a2acda7ad674fb9006b56cf5984919d' // // Client interface From e9161c2f2981d371d40ea1f85a2c22f26fca3c93 Mon Sep 17 00:00:00 2001 From: marino39 <722509+marino39@users.noreply.github.com> Date: Mon, 1 Dec 2025 11:30:55 +0000 Subject: [PATCH 8/8] [AUTOMATED] Update: proto/clients/indexer*.gen.ts --- packages/indexer/src/indexer.gen.ts | 7 +++++-- packages/indexer/src/indexergw.gen.ts | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/indexer/src/indexer.gen.ts b/packages/indexer/src/indexer.gen.ts index 01f66645a..0fc4a52a1 100644 --- a/packages/indexer/src/indexer.gen.ts +++ b/packages/indexer/src/indexer.gen.ts @@ -1,5 +1,5 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 42364084a9e85e579205500b8748d9630b380cbb +// sequence-indexer v0.4.0 cfbb0160fed6f7e2208a73cad454f3cddace9c7a // -- // Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. // @@ -12,7 +12,7 @@ export const WebrpcVersion = 'v1' export const WebrpcSchemaVersion = 'v0.4.0' // Schema hash generated from your RIDL schema -export const WebrpcSchemaHash = '42364084a9e85e579205500b8748d9630b380cbb' +export const WebrpcSchemaHash = 'cfbb0160fed6f7e2208a73cad454f3cddace9c7a' // // Client interface @@ -637,6 +637,7 @@ export interface NativeTokenBalance { balance: string balanceUSD: string priceUSD: string + priceUpdatedAt?: string errorReason?: string } @@ -674,6 +675,7 @@ export interface Price { contractAddress: string tokenID?: string priceUSD: string + updatedAt?: string } export enum ResourceStatus { @@ -727,6 +729,7 @@ export interface TokenBalance { balance: string balanceUSD: string priceUSD: string + priceUpdatedAt?: string blockHash: string blockNumber: number chainId: number diff --git a/packages/indexer/src/indexergw.gen.ts b/packages/indexer/src/indexergw.gen.ts index ef867b3fd..ce59f412a 100644 --- a/packages/indexer/src/indexergw.gen.ts +++ b/packages/indexer/src/indexergw.gen.ts @@ -1,5 +1,5 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 ec2391094a2acda7ad674fb9006b56cf5984919d +// sequence-indexer v0.4.0 3309c3d48de1790b7d12c5769c1e6bc59eb9831c // -- // Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT. // @@ -12,7 +12,7 @@ export const WebrpcVersion = 'v1' export const WebrpcSchemaVersion = 'v0.4.0' // Schema hash generated from your RIDL schema -export const WebrpcSchemaHash = 'ec2391094a2acda7ad674fb9006b56cf5984919d' +export const WebrpcSchemaHash = '3309c3d48de1790b7d12c5769c1e6bc59eb9831c' // // Client interface @@ -410,6 +410,7 @@ export interface NativeTokenBalance { balance: string balanceUSD: string priceUSD: string + priceUpdatedAt?: string errorReason?: string } @@ -447,6 +448,7 @@ export interface Price { contractAddress: string tokenID?: string priceUSD: string + updatedAt?: string } export enum ResourceStatus { @@ -500,6 +502,7 @@ export interface TokenBalance { balance: string balanceUSD: string priceUSD: string + priceUpdatedAt?: string blockHash: string blockNumber: number chainId: number