diff --git a/packages/indexer/src/indexer.gen.ts b/packages/indexer/src/indexer.gen.ts index 98908ed78..b31634e95 100644 --- a/packages/indexer/src/indexer.gen.ts +++ b/packages/indexer/src/indexer.gen.ts @@ -1,23 +1,76 @@ /* eslint-disable */ -// sequence-indexer v0.4.0 cae735346d8e5c3dce48dce9f85116989b6beffd +// sequence-indexer v0.4.0 c1a1d68bd53788a27c6954562b24debe49bd029a // -- -// Code generated by webrpc-gen@v0.20.3 with typescript generator. DO NOT EDIT. +// Code generated by webrpc-gen@v0.21.1 with typescript generator. DO NOT EDIT. // -// webrpc-gen -schema=indexer.ridl -target=typescript -client -out=./clients/indexer.gen.ts +// webrpc-gen -schema=indexer.ridl -service=Indexer -target=typescript -client -out=./clients/indexer.gen.ts + +export const WebrpcHeader = "Webrpc" + +export const WebrpcHeaderValue = "webrpc@v0.21.1;gen-typescript@v0.15.1;sequence-indexer@v0.4.0" // WebRPC description and code-gen version -export const WebRPCVersion = 'v1' +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 = 'cae735346d8e5c3dce48dce9f85116989b6beffd' +export const WebRPCSchemaHash = "c1a1d68bd53788a27c6954562b24debe49bd029a" + +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, + codeGenName, + codeGenVersion, + schemaName, + schemaVersion, + }; +} // // Types // + export interface ContractInfo { chainId: number address: string @@ -51,8 +104,8 @@ export interface TokenMetadata { image?: string video?: string audio?: string - properties?: { [key: string]: any } - attributes: Array<{ [key: string]: any }> + properties?: {[key: string]: any} + attributes: Array<{[key: string]: any}> image_data?: string external_url?: string background_color?: string @@ -151,7 +204,7 @@ export interface RuntimeStatus { ver: string branch: string commitHash: string - chainID: number + chainId: number checks: RuntimeChecks } @@ -162,7 +215,7 @@ export interface WALWriterRuntimeStatus { ver: string branch: string commitHash: string - chainID: number + chainId: number percentWALWritten: number } @@ -185,7 +238,7 @@ export interface DiskUsage { used: number size: number percent: number - dirs: { [key: string]: string } + dirs: {[key: string]: string} } export interface Bond { @@ -250,7 +303,7 @@ export interface EventLog { logDataType: EventLogDataType ts: string txnInfo?: TxnInfo - rawLog?: { [key: string]: any } + rawLog?: {[key: string]: any} event?: EventDecoded } @@ -351,7 +404,7 @@ export interface TxnTransfer { amounts: Array logIndex: number contractInfo?: ContractInfo - tokenMetadata?: { [key: string]: TokenMetadata } + tokenMetadata?: {[key: string]: TokenMetadata} } export interface TransactionHistoryFilter { @@ -397,6 +450,11 @@ export interface TransactionLog { index: number } +export interface TokenIDRange { + start: string + end: string +} + export interface Page { page?: number column?: string @@ -442,15 +500,33 @@ export interface MetadataOptions { export interface TokenBalancesFilter { accountAddresses: Array - contractStatus: ContractVerificationStatus - contractWhitelist: Array - contractBlacklist: Array + contractStatus?: ContractVerificationStatus + contractWhitelist?: Array + contractBlacklist?: Array } export interface TokenBalancesByContractFilter { contractAddresses: Array - accountAddresses: Array - contractStatus: ContractVerificationStatus + accountAddresses?: Array + contractStatus?: ContractVerificationStatus +} + +export interface GatewayEtherBalance { + chainId: number + error: string + result: EtherBalance +} + +export interface GatewayNativeTokenBalance { + chainId: number + error: string + result: NativeTokenBalance +} + +export interface GatewayTokenBalance { + chainId: number + error: string + results: Array } export interface Indexer { @@ -459,121 +535,72 @@ export interface Indexer { runtimeStatus(headers?: object, signal?: AbortSignal): Promise getChainID(headers?: object, signal?: AbortSignal): Promise getEtherBalance(args: GetEtherBalanceArgs, headers?: object, signal?: AbortSignal): Promise - getNativeTokenBalance( - args: GetNativeTokenBalanceArgs, - headers?: object, - signal?: AbortSignal - ): Promise - getTokenBalancesSummary( - args: GetTokenBalancesSummaryArgs, - headers?: object, - signal?: AbortSignal - ): Promise - getTokenBalancesDetails( - args: GetTokenBalancesDetailsArgs, - headers?: object, - signal?: AbortSignal - ): Promise - getTokenBalancesByContract( - args: GetTokenBalancesByContractArgs, - headers?: object, - signal?: AbortSignal - ): Promise + getNativeTokenBalance(args: GetNativeTokenBalanceArgs, headers?: object, signal?: AbortSignal): Promise + getTokenBalancesSummary(args: GetTokenBalancesSummaryArgs, headers?: object, signal?: AbortSignal): Promise + getTokenBalancesDetails(args: GetTokenBalancesDetailsArgs, headers?: object, signal?: AbortSignal): Promise + getTokenBalancesByContract(args: GetTokenBalancesByContractArgs, headers?: object, signal?: AbortSignal): Promise getTokenBalances(args: GetTokenBalancesArgs, headers?: object, signal?: AbortSignal): Promise getTokenSupplies(args: GetTokenSuppliesArgs, headers?: object, signal?: AbortSignal): Promise getTokenSuppliesMap(args: GetTokenSuppliesMapArgs, headers?: object, signal?: AbortSignal): Promise + getTokenIDs(args: GetTokenIDsArgs, headers?: object, signal?: AbortSignal): Promise + getTokenIDRanges(args: GetTokenIDRangesArgs, headers?: object, signal?: AbortSignal): Promise getBalanceUpdates(args: GetBalanceUpdatesArgs, headers?: object, signal?: AbortSignal): Promise - getTransactionHistory( - args: GetTransactionHistoryArgs, - headers?: object, - signal?: AbortSignal - ): Promise + getTransactionHistory(args: GetTransactionHistoryArgs, headers?: object, signal?: AbortSignal): Promise + fetchTransactionReceipt(args: FetchTransactionReceiptArgs, headers?: object, signal?: AbortSignal): Promise + fetchTransactionReceiptWithFilter(args: FetchTransactionReceiptWithFilterArgs, headers?: object, signal?: AbortSignal): Promise + subscribeReceipts(args: SubscribeReceiptsArgs, options: WebrpcStreamOptions): Promise + subscribeEvents(args: SubscribeEventsArgs, options: WebrpcStreamOptions): Promise + subscribeBalanceUpdates(args: SubscribeBalanceUpdatesArgs, options: WebrpcStreamOptions): Promise syncBalance(args: SyncBalanceArgs, headers?: object, signal?: AbortSignal): Promise - fetchTransactionReceipt( - args: FetchTransactionReceiptArgs, - headers?: object, - signal?: AbortSignal - ): Promise - getOrderbookOrders(args: GetOrderbookOrdersArgs, headers?: object, signal?: AbortSignal): Promise - getTopOrders(args: GetTopOrdersArgs, headers?: object, signal?: AbortSignal): Promise - fetchTransactionReceiptWithFilter( - args: FetchTransactionReceiptWithFilterArgs, - headers?: object, - signal?: AbortSignal - ): Promise - getAllWebhookListeners( - args: GetAllWebhookListenersArgs, - headers?: object, - signal?: AbortSignal - ): Promise + getAllWebhookListeners(args: GetAllWebhookListenersArgs, headers?: object, signal?: AbortSignal): Promise getWebhookListener(args: GetWebhookListenerArgs, headers?: object, signal?: AbortSignal): Promise addWebhookListener(args: AddWebhookListenerArgs, headers?: object, signal?: AbortSignal): Promise - updateWebhookListener( - args: UpdateWebhookListenerArgs, - headers?: object, - signal?: AbortSignal - ): Promise - removeWebhookListener( - args: RemoveWebhookListenerArgs, - headers?: object, - signal?: AbortSignal - ): Promise - toggleWebhookListener( - args: ToggleWebhookListenerArgs, - headers?: object, - signal?: AbortSignal - ): Promise - pauseAllWebhookListeners( - args: PauseAllWebhookListenersArgs, - headers?: object, - signal?: AbortSignal - ): Promise - resumeAllWebhookListeners( - args: ResumeAllWebhookListenersArgs, - headers?: object, - signal?: AbortSignal - ): Promise - subscribeReceipts(args: SubscribeReceiptsArgs, options: WebrpcStreamOptions): Promise - subscribeEvents(args: SubscribeEventsArgs, options: WebrpcStreamOptions): Promise - subscribeBalanceUpdates( - args: SubscribeBalanceUpdatesArgs, - options: WebrpcStreamOptions - ): Promise + updateWebhookListener(args: UpdateWebhookListenerArgs, headers?: object, signal?: AbortSignal): Promise + removeWebhookListener(args: RemoveWebhookListenerArgs, headers?: object, signal?: AbortSignal): Promise + toggleWebhookListener(args: ToggleWebhookListenerArgs, headers?: object, signal?: AbortSignal): Promise + pauseAllWebhookListeners(args: PauseAllWebhookListenersArgs, headers?: object, signal?: AbortSignal): Promise + resumeAllWebhookListeners(args: ResumeAllWebhookListenersArgs, headers?: object, signal?: AbortSignal): Promise + getOrderbookOrders(args: GetOrderbookOrdersArgs, headers?: object, signal?: AbortSignal): Promise + getTopOrders(args: GetTopOrdersArgs, headers?: object, signal?: AbortSignal): Promise } -export interface PingArgs {} +export interface PingArgs { +} export interface PingReturn { - status: boolean + status: boolean +} +export interface VersionArgs { } -export interface VersionArgs {} export interface VersionReturn { - version: Version + version: Version +} +export interface RuntimeStatusArgs { } -export interface RuntimeStatusArgs {} export interface RuntimeStatusReturn { - status: RuntimeStatus + status: RuntimeStatus +} +export interface GetChainIDArgs { } -export interface GetChainIDArgs {} export interface GetChainIDReturn { - chainID: number + chainId: number } export interface GetEtherBalanceArgs { accountAddress?: string } export interface GetEtherBalanceReturn { - balance: EtherBalance + balance: EtherBalance } export interface GetNativeTokenBalanceArgs { accountAddress?: string } export interface GetNativeTokenBalanceReturn { - balance: NativeTokenBalance + balance: NativeTokenBalance } export interface GetTokenBalancesSummaryArgs { filter: TokenBalancesFilter @@ -583,7 +610,7 @@ export interface GetTokenBalancesSummaryArgs { export interface GetTokenBalancesSummaryReturn { page: Page - balances: Array + balances: Array } export interface GetTokenBalancesDetailsArgs { filter: TokenBalancesFilter @@ -593,7 +620,7 @@ export interface GetTokenBalancesDetailsArgs { export interface GetTokenBalancesDetailsReturn { page: Page - balances: Array + balances: Array } export interface GetTokenBalancesByContractArgs { filter: TokenBalancesByContractFilter @@ -603,7 +630,7 @@ export interface GetTokenBalancesByContractArgs { export interface GetTokenBalancesByContractReturn { page: Page - balances: Array + balances: Array } export interface GetTokenBalancesArgs { accountAddress?: string @@ -617,7 +644,7 @@ export interface GetTokenBalancesArgs { export interface GetTokenBalancesReturn { page: Page - balances: Array + balances: Array } export interface GetTokenSuppliesArgs { contractAddress: string @@ -629,16 +656,35 @@ export interface GetTokenSuppliesArgs { export interface GetTokenSuppliesReturn { page: Page contractType: ContractType - tokenIDs: Array + tokenIDs: Array } export interface GetTokenSuppliesMapArgs { - tokenMap: { [key: string]: Array } + tokenMap: {[key: string]: Array} includeMetadata?: boolean metadataOptions?: MetadataOptions } export interface GetTokenSuppliesMapReturn { - supplies: { [key: string]: Array } + supplies: {[key: string]: Array} +} +export interface GetTokenIDsArgs { + contractAddress: string + page?: Page +} + +export interface GetTokenIDsReturn { + page: Page + contractType: ContractType + tokenIDs: Array +} +export interface GetTokenIDRangesArgs { + contractAddress: string +} + +export interface GetTokenIDRangesReturn { + contractType: ContractType + tokenIDRanges: Array + moreRanges: boolean } export interface GetBalanceUpdatesArgs { contractAddress: string @@ -649,7 +695,7 @@ export interface GetBalanceUpdatesArgs { export interface GetBalanceUpdatesReturn { page: Page - balances: Array + balances: Array } export interface GetTransactionHistoryArgs { filter: TransactionHistoryFilter @@ -660,67 +706,59 @@ export interface GetTransactionHistoryArgs { export interface GetTransactionHistoryReturn { page: Page - transactions: Array -} -export interface SyncBalanceArgs { - accountAddress: string - contractAddress: string - tokenID?: string + transactions: Array } - -export interface SyncBalanceReturn {} export interface FetchTransactionReceiptArgs { txnHash: string maxBlockWait?: number } export interface FetchTransactionReceiptReturn { - receipt: TransactionReceipt + receipt: TransactionReceipt } -export interface GetOrderbookOrdersArgs { - page?: Page - orderbookContractAddress: string - collectionAddress: string - currencyAddresses: Array - filter: OrderbookOrderFilter - orderStatuses: Array - filters: Array - beforeExpiryTimestamp: number - blockNumberAfter: number - createdAtAfter: number +export interface FetchTransactionReceiptWithFilterArgs { + filter: TransactionFilter + maxBlockWait?: number } -export interface GetOrderbookOrdersReturn { - page?: Page - orders: Array +export interface FetchTransactionReceiptWithFilterReturn { + receipt: TransactionReceipt } -export interface GetTopOrdersArgs { - orderbookContractAddress: string - collectionAddress: string - currencyAddresses: Array - tokenIDs: Array - isListing: boolean - priceSort: SortOrder - excludeUser?: string +export interface SubscribeReceiptsArgs { + filter: TransactionFilter } -export interface GetTopOrdersReturn { - orders: Array +export interface SubscribeReceiptsReturn { + receipt: TransactionReceipt } -export interface FetchTransactionReceiptWithFilterArgs { - filter: TransactionFilter - maxBlockWait?: number +export interface SubscribeEventsArgs { + filter: EventFilter } -export interface FetchTransactionReceiptWithFilterReturn { - receipt: TransactionReceipt +export interface SubscribeEventsReturn { + log: EventLog +} +export interface SubscribeBalanceUpdatesArgs { + contractAddress: string +} + +export interface SubscribeBalanceUpdatesReturn { + balance: TokenBalance +} +export interface SyncBalanceArgs { + accountAddress: string + contractAddress: string + tokenID?: string +} + +export interface SyncBalanceReturn { } export interface GetAllWebhookListenersArgs { projectId?: number } export interface GetAllWebhookListenersReturn { - listeners: Array + listeners: Array } export interface GetWebhookListenerArgs { id: number @@ -728,7 +766,7 @@ export interface GetWebhookListenerArgs { } export interface GetWebhookListenerReturn { - listener: WebhookListener + listener: WebhookListener } export interface AddWebhookListenerArgs { url: string @@ -738,7 +776,7 @@ export interface AddWebhookListenerArgs { export interface AddWebhookListenerReturn { status: boolean - listener: WebhookListener + listener: WebhookListener } export interface UpdateWebhookListenerArgs { listener: WebhookListener @@ -746,7 +784,7 @@ export interface UpdateWebhookListenerArgs { } export interface UpdateWebhookListenerReturn { - status: boolean + status: boolean } export interface RemoveWebhookListenerArgs { id: number @@ -754,7 +792,7 @@ export interface RemoveWebhookListenerArgs { } export interface RemoveWebhookListenerReturn { - status: boolean + status: boolean } export interface ToggleWebhookListenerArgs { id: number @@ -762,44 +800,55 @@ export interface ToggleWebhookListenerArgs { } export interface ToggleWebhookListenerReturn { - webhookListener: WebhookListener + webhookListener: WebhookListener } export interface PauseAllWebhookListenersArgs { projectId?: number } export interface PauseAllWebhookListenersReturn { - status: boolean + status: boolean } export interface ResumeAllWebhookListenersArgs { projectId?: number } export interface ResumeAllWebhookListenersReturn { - status: boolean + status: boolean } -export interface SubscribeReceiptsArgs { - filter: TransactionFilter +export interface GetOrderbookOrdersArgs { + page?: Page + orderbookContractAddress: string + collectionAddress: string + currencyAddresses: Array + filter: OrderbookOrderFilter + orderStatuses: Array + filters: Array + beforeExpiryTimestamp: number + blockNumberAfter: number + createdAtAfter: number } -export interface SubscribeReceiptsReturn { - receipt: TransactionReceipt +export interface GetOrderbookOrdersReturn { + page?: Page + orders: Array } -export interface SubscribeEventsArgs { - filter: EventFilter +export interface GetTopOrdersArgs { + orderbookContractAddress: string + collectionAddress: string + currencyAddresses: Array + tokenIDs: Array + isListing: boolean + priceSort: SortOrder + excludeUser?: string } -export interface SubscribeEventsReturn { - log: EventLog -} -export interface SubscribeBalanceUpdatesArgs { - contractAddress: string +export interface GetTopOrdersReturn { + orders: Array } -export interface SubscribeBalanceUpdatesReturn { - balance: TokenBalance -} + // // Client // @@ -816,648 +865,593 @@ export class Indexer implements Indexer { private url(name: string): string { return this.hostname + this.path + name } - + ping = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Ping'), createHTTPRequest({}, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - status: _data.status - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + return this.fetch( + this.url('Ping'), + createHTTPRequest({}, headers, signal) + ).then((res) => { + return buildResponse(res).then(_data => { + return { + status: (_data.status), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) } - + version = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('Version'), createHTTPRequest({}, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - version: _data.version - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + return this.fetch( + this.url('Version'), + createHTTPRequest({}, headers, signal) + ).then((res) => { + return buildResponse(res).then(_data => { + return { + version: (_data.version), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) } - + runtimeStatus = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('RuntimeStatus'), createHTTPRequest({}, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - status: _data.status - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + return this.fetch( + this.url('RuntimeStatus'), + createHTTPRequest({}, headers, signal) + ).then((res) => { + return buildResponse(res).then(_data => { + return { + status: (_data.status), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) } - + getChainID = (headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetChainID'), createHTTPRequest({}, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - chainID: _data.chainID - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + return this.fetch( + this.url('GetChainID'), + createHTTPRequest({}, headers, signal) + ).then((res) => { + return buildResponse(res).then(_data => { + return { + chainId: (_data.chainId), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) } - + getEtherBalance = (args: GetEtherBalanceArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetEtherBalance'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - balance: _data.balance - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - getNativeTokenBalance = ( - args: GetNativeTokenBalanceArgs, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetNativeTokenBalance'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - balance: _data.balance - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - getTokenBalancesSummary = ( - args: GetTokenBalancesSummaryArgs, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenBalancesSummary'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - page: _data.page, - 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, - 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 || ''}` }) - } - ) + return this.fetch( + this.url('GetEtherBalance'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + balance: (_data.balance), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) } - + + getNativeTokenBalance = (args: GetNativeTokenBalanceArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('GetNativeTokenBalance'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + balance: (_data.balance), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + + getTokenBalancesSummary = (args: GetTokenBalancesSummaryArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('GetTokenBalancesSummary'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + page: (_data.page), + 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), + balances: >(_data.balances), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + + getTokenBalancesByContract = (args: GetTokenBalancesByContractArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('GetTokenBalancesByContract'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + page: (_data.page), + balances: >(_data.balances), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + getTokenBalances = (args: GetTokenBalancesArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenBalances'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - page: _data.page, - balances: >_data.balances - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + return this.fetch( + this.url('GetTokenBalances'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + page: (_data.page), + balances: >(_data.balances), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) } - + getTokenSupplies = (args: GetTokenSuppliesArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTokenSupplies'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - page: _data.page, - contractType: _data.contractType, - tokenIDs: >_data.tokenIDs - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - getTokenSuppliesMap = ( - args: GetTokenSuppliesMapArgs, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTokenSuppliesMap'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - supplies: <{ [key: string]: Array }>_data.supplies - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + return this.fetch( + this.url('GetTokenSupplies'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + page: (_data.page), + contractType: (_data.contractType), + tokenIDs: >(_data.tokenIDs), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) } - + + getTokenSuppliesMap = (args: GetTokenSuppliesMapArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('GetTokenSuppliesMap'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + supplies: <{[key: string]: Array}>(_data.supplies), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + + getTokenIDs = (args: GetTokenIDsArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('GetTokenIDs'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + page: (_data.page), + contractType: (_data.contractType), + tokenIDs: >(_data.tokenIDs), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + + getTokenIDRanges = (args: GetTokenIDRangesArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('GetTokenIDRanges'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + contractType: (_data.contractType), + tokenIDRanges: >(_data.tokenIDRanges), + moreRanges: (_data.moreRanges), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + getBalanceUpdates = (args: GetBalanceUpdatesArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetBalanceUpdates'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - page: _data.page, - balances: >_data.balances - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - getTransactionHistory = ( - args: GetTransactionHistoryArgs, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetTransactionHistory'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - page: _data.page, - transactions: >_data.transactions - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + 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 || ''}` }) + }) } - - 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 || ''}` }) - } - ) - } - - 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 || ''}` }) - } - ) - } - - getOrderbookOrders = ( - args: GetOrderbookOrdersArgs, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetOrderbookOrders'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - page: _data.page, - orders: >_data.orders - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + + 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 || ''}` }) + }) } - - getTopOrders = (args: GetTopOrdersArgs, headers?: object, signal?: AbortSignal): Promise => { - return this.fetch(this.url('GetTopOrders'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - orders: >_data.orders - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - 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 || ''}` }) - } - ) - } - - getWebhookListener = ( - args: GetWebhookListenerArgs, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('GetWebhookListener'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - listener: _data.listener - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - addWebhookListener = ( - args: AddWebhookListenerArgs, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('AddWebhookListener'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - status: _data.status, - listener: _data.listener - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - updateWebhookListener = ( - args: UpdateWebhookListenerArgs, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('UpdateWebhookListener'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - status: _data.status - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - removeWebhookListener = ( - args: RemoveWebhookListenerArgs, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('RemoveWebhookListener'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - status: _data.status - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - toggleWebhookListener = ( - args: ToggleWebhookListenerArgs, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('ToggleWebhookListener'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - webhookListener: _data.webhookListener - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - pauseAllWebhookListeners = ( - args: PauseAllWebhookListenersArgs, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('PauseAllWebhookListeners'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - status: _data.status - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) - } - - resumeAllWebhookListeners = ( - args: ResumeAllWebhookListenersArgs, - headers?: object, - signal?: AbortSignal - ): Promise => { - return this.fetch(this.url('ResumeAllWebhookListeners'), createHTTPRequest(args, headers, signal)).then( - res => { - return buildResponse(res).then(_data => { - return { - status: _data.status - } - }) - }, - error => { - throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) - } - ) + + 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 || ''}` }) + }) } - - subscribeReceipts = (args: SubscribeReceiptsArgs, options: WebrpcStreamOptions): Promise => { - const _fetch = () => - this.fetch(this.url('SubscribeReceipts'), createHTTPRequest(args, options.headers, options.signal)).then( - async res => { - await sseResponse(res, options, _fetch) - }, - error => { - options.onError(error, _fetch) + + 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), } - ) - return _fetch() + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + + subscribeReceipts = (args: SubscribeReceiptsArgs, options: WebrpcStreamOptions): Promise => { + const _fetch = () => this.fetch(this.url('SubscribeReceipts'),createHTTPRequest(args, options.headers, options.signal) + ).then(async (res) => { + await sseResponse(res, options, _fetch); + }, (error) => { + options.onError(error, _fetch); + }); + return _fetch(); } subscribeEvents = (args: SubscribeEventsArgs, options: WebrpcStreamOptions): Promise => { - const _fetch = () => - this.fetch(this.url('SubscribeEvents'), createHTTPRequest(args, options.headers, options.signal)).then( - async res => { - await sseResponse(res, options, _fetch) - }, - error => { - options.onError(error, _fetch) + const _fetch = () => this.fetch(this.url('SubscribeEvents'),createHTTPRequest(args, options.headers, options.signal) + ).then(async (res) => { + await sseResponse(res, options, _fetch); + }, (error) => { + options.onError(error, _fetch); + }); + return _fetch(); + } + subscribeBalanceUpdates = (args: SubscribeBalanceUpdatesArgs, options: WebrpcStreamOptions): Promise => { + const _fetch = () => this.fetch(this.url('SubscribeBalanceUpdates'),createHTTPRequest(args, options.headers, options.signal) + ).then(async (res) => { + await sseResponse(res, options, _fetch); + }, (error) => { + options.onError(error, _fetch); + }); + return _fetch(); + } + syncBalance = (args: SyncBalanceArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('SyncBalance'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return {} + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + + getAllWebhookListeners = (args: GetAllWebhookListenersArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('GetAllWebhookListeners'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + listeners: >(_data.listeners), } - ) - return _fetch() - } - subscribeBalanceUpdates = ( - args: SubscribeBalanceUpdatesArgs, - options: WebrpcStreamOptions - ): Promise => { - const _fetch = () => - this.fetch(this.url('SubscribeBalanceUpdates'), createHTTPRequest(args, options.headers, options.signal)).then( - async res => { - await sseResponse(res, options, _fetch) - }, - error => { - options.onError(error, _fetch) + }) + }, (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), } - ) - return _fetch() + }) + }, (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 + + addWebhookListener = (args: AddWebhookListenerArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('AddWebhookListener'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + status: (_data.status), + listener: (_data.listener), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + + updateWebhookListener = (args: UpdateWebhookListenerArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('UpdateWebhookListener'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + status: (_data.status), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + + removeWebhookListener = (args: RemoveWebhookListenerArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('RemoveWebhookListener'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + status: (_data.status), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + + toggleWebhookListener = (args: ToggleWebhookListenerArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('ToggleWebhookListener'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + webhookListener: (_data.webhookListener), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + + pauseAllWebhookListeners = (args: PauseAllWebhookListenersArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('PauseAllWebhookListeners'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + status: (_data.status), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + + resumeAllWebhookListeners = (args: ResumeAllWebhookListenersArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('ResumeAllWebhookListeners'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + status: (_data.status), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + + getOrderbookOrders = (args: GetOrderbookOrdersArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('GetOrderbookOrders'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + page: (_data.page), + orders: >(_data.orders), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) } + + getTopOrders = (args: GetTopOrdersArgs, headers?: object, signal?: AbortSignal): Promise => { + return this.fetch( + this.url('GetTopOrders'), + createHTTPRequest(args, headers, signal)).then((res) => { + return buildResponse(res).then(_data => { + return { + orders: >(_data.orders), + } + }) + }, (error) => { + throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` }) + }) + } + +} + +const sseResponse = async ( + res: Response, + options: WebrpcStreamOptions, + retryFetch: () => Promise +) => { + const {onMessage, onOpen, onClose, onError} = options; - if (!res.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() + if (!res.ok) { + try { + await buildResponse(res); + } catch (error) { + // @ts-ignore + onError(error, retryFetch); + } + return; } - }, timeout) - while (true) { - let value - let done - try { - ;({ value, done } = await reader.read()) - if (timeoutError) throw new Error('Timeout, no data or heartbeat received') - lastReadTime = Date.now() - buffer += decoder.decode(value, { stream: true }) - } catch (error) { - let message = '' - if (error instanceof Error) { - message = error.message - } - - if (error instanceof DOMException && error.name === 'AbortError') { + if (!res.body) { onError( - WebrpcRequestFailedError.new({ - message: 'AbortError', - cause: `AbortError: ${message}` - }), - () => { - throw new Error('Abort signal cannot be used to reconnect') - } - ) - } else { - onError( - WebrpcStreamLostError.new({ - cause: `reader.read(): ${message}` - }), - retryFetch - ) - } - return + WebrpcBadResponseError.new({ + status: res.status, + cause: "Invalid response, missing body", + }), + 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 + onOpen && onOpen(); + + const reader = res.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; + let lastReadTime = Date.now(); + const timeout = (10 + 1) * 1000; + let timeoutError = false + const intervalId = setInterval(() => { + if (Date.now() - lastReadTime > timeout) { + timeoutError = true + clearInterval(intervalId) + reader.releaseLock() } - } catch (error) { - if (error instanceof Error && error.message === 'Abort signal cannot be used to reconnect') { - throw error + }, timeout); + + while (true) { + let value; + let done; + try { + ({value, done} = await reader.read()); + if (timeoutError) throw new Error("Timeout, no data or heartbeat received") + lastReadTime = Date.now(); + buffer += decoder.decode(value, {stream: true}); + } catch (error) { + 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; } - 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; } +}; - onClose && onClose() - return - } -} -const createHTTPRequest = (body: object = {}, headers: object = {}, signal: AbortSignal | null = null): object => { + + 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: { ...headers, 'Content-Type': 'application/json' }, + headers: reqHeaders, body: JSON.stringify(body || {}), signal } @@ -1468,18 +1462,18 @@ const buildResponse = (res: Response): Promise => { let data try { data = JSON.parse(text) - } catch (error) { + } catch(error) { let message = '' - if (error instanceof Error) { + if (error instanceof Error) { message = error.message } throw WebrpcBadResponseError.new({ status: res.status, - cause: `JSON.parse(): ${message}: response text: ${text}` - }) + cause: `JSON.parse(): ${message}: response text: ${text}`}, + ) } if (!res.ok) { - const code: number = typeof data.code === 'number' ? data.code : 0 + const code: number = (typeof data.code === 'number') ? data.code : 0 throw (webrpcErrorByCode[code] || WebrpcError).new(data) } return data @@ -1661,6 +1655,7 @@ export class WebrpcStreamFinishedError extends WebrpcError { } } + // Schema errors export class UnauthorizedError extends WebrpcError { @@ -1741,10 +1736,179 @@ export class AbortedError extends WebrpcError { } } +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 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 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 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 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 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 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 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 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 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 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 TimeoutError extends WebrpcError { constructor( name: string = 'Timeout', - code: number = 2000, + code: number = 1900, message: string = 'Request timed out', status: number = 0, cause?: string @@ -1819,19 +1983,6 @@ export class NotFoundError extends WebrpcError { } } -export class ProjectNotFoundError extends WebrpcError { - constructor( - name: string = 'ProjectNotFound', - code: number = 3002, - message: string = 'Project not found', - status: number = 0, - cause?: string - ) { - super(name, code, message, status, cause) - Object.setPrototypeOf(this, ProjectNotFoundError.prototype) - } -} - export class MetadataCallFailedError extends WebrpcError { constructor( name: string = 'MetadataCallFailed', @@ -1845,6 +1996,7 @@ export class MetadataCallFailedError extends WebrpcError { } } + export enum errors { WebrpcEndpoint = 'WebrpcEndpoint', WebrpcRequestFailed = 'WebrpcRequestFailed', @@ -1863,14 +2015,26 @@ export enum errors { MethodNotFound = 'MethodNotFound', RequestConflict = 'RequestConflict', Aborted = 'Aborted', + Geoblocked = 'Geoblocked', + RateLimited = 'RateLimited', + ProjectNotFound = 'ProjectNotFound', + AccessKeyNotFound = 'AccessKeyNotFound', + AccessKeyMismatch = 'AccessKeyMismatch', + InvalidOrigin = 'InvalidOrigin', + InvalidService = 'InvalidService', + UnauthorizedUser = 'UnauthorizedUser', + QuotaExceeded = 'QuotaExceeded', + RateLimit = 'RateLimit', + NoDefaultKey = 'NoDefaultKey', + MaxAccessKeys = 'MaxAccessKeys', + AtLeastOneKey = 'AtLeastOneKey', Timeout = 'Timeout', InvalidArgument = 'InvalidArgument', Unavailable = 'Unavailable', QueryFailed = 'QueryFailed', ResourceExhausted = 'ResourceExhausted', NotFound = 'NotFound', - ProjectNotFound = 'ProjectNotFound', - MetadataCallFailed = 'MetadataCallFailed' + MetadataCallFailed = 'MetadataCallFailed', } const webrpcErrorByCode: { [code: number]: any } = { @@ -1891,25 +2055,38 @@ const webrpcErrorByCode: { [code: number]: any } = { [1003]: MethodNotFoundError, [1004]: RequestConflictError, [1005]: AbortedError, - [2000]: TimeoutError, + [1006]: GeoblockedError, + [1007]: RateLimitedError, + [1100]: ProjectNotFoundError, + [1101]: AccessKeyNotFoundError, + [1102]: AccessKeyMismatchError, + [1103]: InvalidOriginError, + [1104]: InvalidServiceError, + [1105]: UnauthorizedUserError, + [1200]: QuotaExceededError, + [1201]: RateLimitError, + [1300]: NoDefaultKeyError, + [1301]: MaxAccessKeysError, + [1302]: AtLeastOneKeyError, + [1900]: TimeoutError, [2001]: InvalidArgumentError, [2002]: UnavailableError, [2003]: QueryFailedError, [2004]: ResourceExhaustedError, [3000]: NotFoundError, - [3002]: ProjectNotFoundError, - [3003]: MetadataCallFailedError + [3003]: MetadataCallFailedError, } export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise export interface WebrpcStreamOptions extends WebrpcOptions { - onMessage: (message: T) => void - onError: (error: WebrpcError, reconnect: () => void) => void - onOpen?: () => void - onClose?: () => void + onMessage: (message: T) => void; + onError: (error: WebrpcError, reconnect: () => void) => void; + onOpen?: () => void; + onClose?: () => void; } export interface WebrpcOptions { - headers?: HeadersInit - signal?: AbortSignal + headers?: HeadersInit; + signal?: AbortSignal; } +