Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
private timeout(error?: Error) {
if (!this.connection || !this.connection.isPending) {
this.connection = future()
}
const timeoutError = error || new Error('Connection timeout')
this.responseCallbacks.forEach($ => $.reject(timeoutError))
this.responseCallbacks.clear()
// reset all requests and callbacks
if (!this.isDisposed) {
this.connect()
}
}
private connect() {
if (this.connection && !this.connection.isPending) {
// tslint:disable-next-line
this.connection.then($ => $.close())
}
if (!this.connection || !this.connection.isPending) {
this.connection = future()
}
this.lastChunk = ''
let ctor = this.options.WebSocketConstructor || (typeof WebSocket !== 'undefined' ? WebSocket : void 0)
if (!ctor) {
throw new Error('Please provide a WebSocketConstructor')
}
const connection = new ctor(this.url, this.options.protocol)
connection.onopen = () => {
this.connection.resolve(connection)
}
if (
typeof (message as any) !== 'object' ||
typeof (message.id as any) !== 'number' ||
typeof (message.method as any) !== 'string' ||
(message.jsonrpc as any) !== '2.0'
) {
throw new Error('Invalid JSON-RPC message')
}
if (!isWhitelistedRPC(message)) {
throw new Error(`The Ethereum method "${message.method}" is blacklisted on Decentraland Provider`)
}
lastSentId += 1
const theFuture = future()
const originalId = message.id
message.id = lastSentId
messageMap.set(message.id, theFuture)
// TODO: Sanitize and filter messages
requestManager.provider.sendAsync(message, (error: Error, res: { id: number }) => {
if (error) {
theFuture.reject(error)
} else {
res.id = originalId
theFuture.resolve(res)
}
injectValidation(callback: (result) => Promise) {
const defer = future()
this.validations.push({ callback, defer })
return defer
}
payload.forEach((payload, ix) => {
const defer = future()
defer
.then(r => {
pollsData[ix].callback(null, r)
})
.catch(e => {
pollsData[ix].callback(e, void 0)
})
defer.finally(() => this.requestManager.requests.delete(payload.id))
this.requestManager.requests.set(payload.id, defer)
})
payload.map($ => {
const defer = future()
try {
const message = toRPC($)
toSend.push(message)
this.responseCallbacks.set(message.id, defer)
} catch (e) {
defer.reject(e)
}
return defer
})
)
return (key: string, ...args: Parameters): Promise => {
const timeout = timeouts[key]
if (timeout) {
clearTimeout(timeout)
}
if (!futures[key]) {
futures[key] = future()
}
timeouts[key] = setTimeout(async () => {
const promise = futures[key]
if (promise) {
try {
await fn(...args)
promise.resolve()
} catch (e) {
promise.reject(e.message)
}
delete futures[key]
}
}, ms)
return futures[key]
}
}