@roochnetwork/rooch-sdk
Version:
141 lines (114 loc) • 3.71 kB
text/typescript
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0
// import { PACKAGE_VERSION, TARGETED_RPC_VERSION } from '../version.js'
import { JsonRpcError, RoochHTTPStatusError } from './error.js'
import { SSEClient } from './sseTransport.js'
import {
RoochSSETransportSubscribeOptions,
RoochTransport,
RoochTransportRequestOptions,
RoochTransportSubscribeOptions,
} from './transportInterface.js'
import { WebsocketClient, WebsocketClientOptions } from './wsTransport.js'
export type HttpHeaders = { [header: string]: string }
export interface RoochHTTPTransportOptions {
fetch?: typeof fetch
WebSocketConstructor?: typeof WebSocket
url: string
rpc?: {
headers?: HttpHeaders
url?: string
}
websocket?: WebsocketClientOptions & {
url?: string
}
}
export class RoochHTTPTransport implements RoochTransport {
constructor(options: RoochHTTPTransportOptions) {
this.
}
if (!this.
this.
}
return this.
}
if (!this.
const WebSocketConstructor = this.
if (!WebSocketConstructor) {
throw new Error(
'The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.',
)
}
this.
this.
{
WebSocketConstructor,
...this.
},
)
}
return this.
}
fetch(input: RequestInfo, init?: RequestInit): Promise<Response> {
const fetchFn = this.
if (!fetchFn) {
throw new Error(
'The current environment does not support fetch, you can provide a fetch implementation in the options for RoochHTTPTransport.',
)
}
return fetchFn(input, init)
}
async request<T>(input: RoochTransportRequestOptions): Promise<T> {
this.
const res = await this.fetch(this.
method: 'POST',
headers: {
'Content-Type': 'application/json',
...this.
},
body: JSON.stringify({
jsonrpc: '2.0',
id: this.
method: input.method,
params: input.params,
}),
})
if (!res.ok) {
throw new RoochHTTPStatusError(
`Unexpected status code: ${res.status}`,
res.status,
res.statusText,
)
}
const data = await res.json()
if ('error' in data && data.error != null) {
throw new JsonRpcError(data.error.message, data.error.code)
}
return data.result
}
async subscribeWithSSE<T>(
input: RoochSSETransportSubscribeOptions<T>,
): Promise<() => Promise<boolean>> {
const unsubscribe = await this.
return async () => !!(await unsubscribe())
}
async subscribe<T>(input: RoochTransportSubscribeOptions<T>): Promise<() => Promise<boolean>> {
const unsubscribe = await this.
if (input.signal) {
input.signal.throwIfAborted()
input.signal.addEventListener('abort', () => {
unsubscribe()
})
}
return async () => !!(await unsubscribe())
}
destroy(): void {
// HTTP is stateless, no cleanup needed
}
}