Socket
Socket
Sign inDemoInstall

@0xsequence/network

Package Overview
Dependencies
Maintainers
6
Versions
464
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@0xsequence/network - npm Package Compare versions

Comparing version 0.0.0-20240613131211 to 0.0.0-20240613194955

dist/declarations/src/json-rpc/handler.d.ts

533

dist/0xsequence-network.cjs.dev.js

@@ -6,4 +6,4 @@ 'use strict';

var constants_dist_0xsequenceNetworkConstants = require('../constants/dist/0xsequence-network-constants.cjs.dev.js');
var utils = require('@0xsequence/utils');
var ethers = require('ethers');
var utils = require('@0xsequence/utils');

@@ -35,3 +35,3 @@ function _extends() {

}
return ethers.ethers.BigNumber.from(chainId).toNumber();
return Number(BigInt(chainId));
};

@@ -143,3 +143,3 @@ const maybeChainId = chainId => {

if (chainId.startsWith('0x')) {
const id = ethers.ethers.BigNumber.from(chainId).toNumber();
const id = Number(BigInt(chainId));
return networks.find(n => n.chainId === id);

@@ -153,4 +153,4 @@ } else {

return networks.find(n => n.chainId === chainId.chainId);
} else if (ethers.ethers.BigNumber.isBigNumber(chainId)) {
const id = chainId.toNumber();
} else if (typeof chainId === 'bigint') {
const id = Number(chainId);
return networks.find(n => n.chainId === id);

@@ -224,9 +224,9 @@ } else {

function toChainIdNumber(chainIdLike) {
if (ethers.ethers.BigNumber.isBigNumber(chainIdLike)) {
if (typeof chainIdLike === 'bigint') {
return chainIdLike;
}
if (utils.isBigNumberish(chainIdLike)) {
return ethers.ethers.BigNumber.from(chainIdLike);
return BigInt(chainIdLike);
}
return ethers.ethers.BigNumber.from(chainIdLike.chainId);
return BigInt(chainIdLike.chainId);
}

@@ -273,6 +273,2 @@ const genUrls = network => {

const JsonRpcVersion = '2.0';
// EIP-1193 function signature
class JsonRpcRouter {

@@ -288,10 +284,6 @@ constructor(middlewares, sender) {

setMiddleware(middlewares) {
this.handler = createJsonRpcMiddlewareStack(middlewares, this.sender.sendAsync);
this.handler = createJsonRpcMiddlewareStack(middlewares, this.sender);
}
sendAsync(request, callback, chainId) {
try {
this.handler(request, callback, chainId);
} catch (err) {
callback(err, undefined);
}
request(request) {
return this.handler.request(request);
}

@@ -302,4 +294,4 @@ }

const toMiddleware = v => {
if (v.sendAsyncMiddleware) {
return v.sendAsyncMiddleware;
if (v.requestHandler) {
return v.requestHandler;
} else {

@@ -310,80 +302,49 @@ return v;

let chain;
chain = toMiddleware(middlewares[middlewares.length - 1])(handler);
chain = toMiddleware(middlewares[middlewares.length - 1])(handler.request);
for (let i = middlewares.length - 2; i >= 0; i--) {
chain = toMiddleware(middlewares[i])(chain);
}
return chain;
return {
request: chain
};
};
// TODOXXX: review..
function isJsonRpcProvider(cand) {
return cand !== undefined && cand.send !== undefined && cand.constructor.defaultUrl !== undefined && cand.detectNetwork !== undefined && cand.getSigner !== undefined && cand.perform !== undefined;
}
function isJsonRpcHandler(cand) {
return cand !== undefined && cand.sendAsync !== undefined;
function isJsonRpcSender(cand) {
return cand !== undefined && cand.send !== undefined;
}
let _nextId = 0;
class JsonRpcSender {
class JsonRpcHandler {
constructor(provider, defaultChainId) {
this.send = void 0;
this.request = void 0;
this.provider = void 0;
this.defaultChainId = void 0;
this.sendAsync = (request, callback, chainId) => {
this.send(request.method, request.params, chainId || this.defaultChainId).then(r => {
callback(undefined, {
jsonrpc: '2.0',
id: request.id,
result: r
});
}).catch(e => {
callback(e, undefined);
});
};
this.defaultChainId = defaultChainId;
if (isJsonRpcProvider(provider)) {
// we can ignore defaultChainId for JsonRpcProviders as they are already chain-bound
this.send = provider.send.bind(provider);
} else if (isJsonRpcHandler(provider)) {
this.send = (method, params, chainId) => {
return new Promise((resolve, reject) => {
provider.sendAsync({
// TODO: really shouldn't have to set these here?
jsonrpc: JsonRpcVersion,
id: ++_nextId,
method,
params
}, (error, response) => {
if (error) {
reject(error);
} else if (response) {
resolve(response.result);
} else {
resolve(undefined);
}
}, chainId || this.defaultChainId);
});
if (isJsonRpcSender(provider)) {
this.provider = request => {
return provider.send(request.method, request.params, request.chainId);
};
} else if (isJsonRpcProvider(provider)) {
this.provider = request => {
return provider.send(request.method, request.params || []);
};
} else {
this.send = provider;
this.provider = provider;
}
this.request = (request, chainId) => {
return this.send(request.method, request.params, chainId);
};
this.defaultChainId = defaultChainId;
}
}
class JsonRpcExternalProvider {
constructor(provider) {
this.provider = provider;
this.sendAsync = (request, callback) => {
this.provider.send(request.method, request.params).then(r => {
callback(undefined, {
jsonrpc: '2.0',
id: request.id,
result: r
});
}).catch(e => {
callback(e, undefined);
});
request(request) {
if (!request.chainId) {
request.chainId = this.defaultChainId;
}
return this.provider(request);
}
send(method, params, chainId) {
const request = {
method,
params,
chainId
};
this.send = this.sendAsync;
return this.request(request);
}

@@ -394,3 +355,3 @@ }

constructor(isAllowedFunc) {
this.sendAsyncMiddleware = void 0;
this.requestHandler = void 0;
this.isAllowedFunc = void 0;

@@ -402,11 +363,11 @@ if (isAllowedFunc) {

}
this.sendAsyncMiddleware = allowProviderMiddleware(this.isAllowedFunc);
this.requestHandler = allowProviderMiddleware(this.isAllowedFunc);
}
setIsAllowedFunc(fn) {
this.isAllowedFunc = fn;
this.sendAsyncMiddleware = allowProviderMiddleware(this.isAllowedFunc);
this.requestHandler = allowProviderMiddleware(this.isAllowedFunc);
}
}
const allowProviderMiddleware = isAllowed => next => {
return (request, callback, chainId) => {
return request => {
// ensure precondition is met or do not allow the request to continue

@@ -418,3 +379,3 @@ if (!isAllowed(request)) {

// request is allowed. keep going..
next(request, callback, chainId);
return next(request);
};

@@ -425,2 +386,3 @@ };

constructor(options) {
var _this = this;
// cachableJsonRpcMethods which can be permanently cached for lifetime

@@ -444,15 +406,13 @@ // of the provider.

this.defaultChainId = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback, chainId) => {
this.requestHandler = next => {
return async function (request) {
// Respond early with cached result
if (this.cachableJsonRpcMethods.includes(request.method) || this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
const key = this.cacheKey(request.method, request.params, chainId || this.defaultChainId);
const result = this.getCacheValue(key);
if (result && result !== '') {
callback(undefined, {
jsonrpc: '2.0',
if (_this.cachableJsonRpcMethods.includes(request.method) || _this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
const key = _this.cacheKey(request.method, request.params, request.chainId || _this.defaultChainId);
const _result = _this.getCacheValue(key);
if (_result && _result !== '') {
return {
id: request.id,
result: result
});
return;
result: _result
};
}

@@ -462,19 +422,17 @@ }

// Continue down the handler chain
next(request, (error, response, chainId) => {
// Store result in cache and continue
if (this.cachableJsonRpcMethods.includes(request.method) || this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
if (response && response.result && this.shouldCacheResponse(request, response)) {
// cache the value
const key = this.cacheKey(request.method, request.params, chainId || this.defaultChainId);
if (this.cachableJsonRpcMethods.includes(request.method)) {
this.setCacheValue(key, response.result);
} else {
this.setCacheByBlockValue(key, response.result);
}
const result = await next(request);
// Store result in cache and continue
if (_this.cachableJsonRpcMethods.includes(request.method) || _this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
if (result && _this.shouldCacheResponse(request, result)) {
// cache the value
const key = _this.cacheKey(request.method, request.params, request.chainId || _this.defaultChainId);
if (_this.cachableJsonRpcMethods.includes(request.method)) {
_this.setCacheValue(key, result);
} else {
_this.setCacheByBlockValue(key, result);
}
}
// Exec next handler
callback(error, response);
}, chainId || this.defaultChainId);
}
return result;
};

@@ -528,5 +486,5 @@ };

};
this.shouldCacheResponse = (request, response) => {
this.shouldCacheResponse = (request, result) => {
// skip if we do not have response result
if (!response || !response.result) {
if (!result) {
return false;

@@ -536,3 +494,3 @@ }

// skip caching eth_getCode where resposne value is '0x' or empty
if (request.method === 'eth_getCode' && response.result.length <= 2) {
if (request.method === 'eth_getCode' && result.length <= 2) {
return false;

@@ -569,52 +527,29 @@ }

constructor(options) {
var _this = this;
this.options = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback, chainId) => {
const {
id,
method
} = request;
switch (method) {
this.requestHandler = next => {
return async function (request) {
switch (request.method) {
case 'net_version':
if (this.options.chainId) {
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: `${this.options.chainId}`
});
return;
if (_this.options.chainId) {
return `${_this.options.chainId}`;
}
break;
case 'eth_chainId':
if (this.options.chainId) {
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: ethers.ethers.utils.hexlify(this.options.chainId)
});
return;
if (_this.options.chainId) {
return ethers.ethers.toBeHex(_this.options.chainId);
}
break;
case 'eth_accounts':
if (this.options.accountAddress) {
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: [ethers.ethers.utils.getAddress(this.options.accountAddress)]
});
return;
if (_this.options.accountAddress) {
return [ethers.ethers.getAddress(_this.options.accountAddress)];
}
break;
case 'sequence_getWalletContext':
if (this.options.walletContext) {
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: this.options.walletContext
});
return;
if (_this.options.walletContext) {
return _this.options.walletContext;
}
break;
}
next(request, callback, chainId);
return next(request);
};

@@ -627,13 +562,12 @@ };

const exceptionProviderMiddleware = next => {
return (request, callback, chainId) => {
next(request, (error, response) => {
if (!error && response && response.error) {
if (typeof response.error === 'string') {
throw new Error(response.error);
} else {
throw new Error(response.error.message);
}
return async request => {
try {
return await next(request);
} catch (error) {
if (typeof error === 'string') {
throw new Error(error);
} else {
throw new Error(error.message);
}
callback(error, response);
}, chainId);
}
};

@@ -644,13 +578,12 @@ };

const loggingProviderMiddleware = next => {
return (request, callback, chainId) => {
const chainIdLabel = chainId ? ` chainId:${chainId}` : '';
return async request => {
const chainIdLabel = request.chainId ? ` chainId:${request.chainId}` : '';
utils.logger.info(`[provider request]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params);
next(request, (error, response) => {
if (error) {
utils.logger.warn(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `error:`, error);
} else {
utils.logger.info(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `response:`, response);
}
callback(error, response);
}, chainId);
try {
const result = await next(request);
utils.logger.info(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `result:`, result);
return result;
} catch (error) {
utils.logger.warn(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `error:`, error);
}
};

@@ -660,27 +593,17 @@ };

const networkProviderMiddleware = getChainId => next => {
return (request, callback, chainId) => {
return async request => {
const networkChainId = getChainId(request);
const {
id,
method
} = request;
switch (method) {
switch (request.method) {
case 'net_version':
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: `${networkChainId}`
});
return;
{
return `${networkChainId}`;
}
case 'eth_chainId':
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: ethers.ethers.utils.hexlify(networkChainId)
});
return;
{
return ethers.ethers.toBeHex(networkChainId);
}
}
// request is allowed. keep going..
next(request, callback, chainId);
return next(request);
};

@@ -698,12 +621,11 @@ };

this.provider = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback, chainId) => {
this.requestHandler = next => {
return request => {
// Forward signing requests to the signing provider
if (SignerJsonRpcMethods.includes(request.method)) {
this.provider.sendAsync(request, callback, chainId);
return;
return this.provider.request(request);
}
// Continue to next handler
next(request, callback, chainId);
return next(request);
};

@@ -720,14 +642,7 @@ };

this.rpcUrl = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback) => {
this.requestHandler = next => {
return request => {
// When provider is configured, send non-private methods to our local public provider
if (this.provider && !this.privateJsonRpcMethods.includes(request.method)) {
this.provider.send(request.method, request.params).then(r => {
callback(undefined, {
jsonrpc: '2.0',
id: request.id,
result: r
});
}).catch(e => callback(e));
return;
return this.provider.send(request.method, request.params || []);
}

@@ -737,3 +652,3 @@

utils.logger.debug('[public-provider] sending request to signer window', request.method);
next(request, callback);
return next(request);
};

@@ -756,3 +671,3 @@ };

// which supports better caching.
this.provider = new ethers.providers.JsonRpcProvider(rpcUrl);
this.provider = new ethers.ethers.JsonRpcProvider(rpcUrl);
}

@@ -764,47 +679,48 @@ }

constructor() {
var _this = this;
this.singleflightJsonRpcMethods = ['eth_chainId', 'net_version', 'eth_call', 'eth_getCode', 'eth_blockNumber', 'eth_getBalance', 'eth_getStorageAt', 'eth_getTransactionCount', 'eth_getBlockTransactionCountByHash', 'eth_getBlockTransactionCountByNumber', 'eth_getUncleCountByBlockHash', 'eth_getUncleCountByBlockNumber', 'eth_getBlockByHash', 'eth_getBlockByNumber', 'eth_getTransactionByHash', 'eth_getTransactionByBlockHashAndIndex', 'eth_getTransactionByBlockNumberAndIndex', 'eth_getTransactionReceipt', 'eth_getUncleByBlockHashAndIndex', 'eth_getUncleByBlockNumberAndIndex', 'eth_getLogs'];
this.inflight = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback, chainId) => {
this.requestHandler = next => {
return async function (request) {
// continue to next handler if method isn't part of methods list
if (!this.singleflightJsonRpcMethods.includes(request.method)) {
next(request, callback, chainId);
return;
if (!_this.singleflightJsonRpcMethods.includes(request.method)) {
return next(request);
}
const key = this.requestKey(request.method, request.params || [], chainId);
if (!this.inflight[key]) {
const key = _this.requestKey(request.method, request.params || [], request.chainId);
if (!_this.inflight[key]) {
// first request -- init the empty list
this.inflight[key] = [];
_this.inflight[key] = [];
} else {
// already in-flight, add the callback to the list and return
this.inflight[key].push({
id: request.id,
callback
return new Promise((resolve, reject) => {
_this.inflight[key].push({
id: request.id,
callback: (error, response) => {
if (error) {
reject(error);
} else {
resolve(response);
}
}
});
});
return;
}
// Continue down the handler chain
next(request, (error, response, chainId) => {
// callback the original request
callback(error, response);
// callback all other requests of the same kind in queue, with the
// same response result as from the first response.
for (let i = 0; i < this.inflight[key].length; i++) {
const sub = this.inflight[key][i];
if (error) {
sub.callback(error, response);
} else if (response) {
sub.callback(undefined, {
jsonrpc: '2.0',
id: sub.id,
result: response.result
});
}
}
// clear request key
delete this.inflight[key];
}, chainId);
try {
// Exec the handler, and on success resolve all other promises
const response = await next(request);
_this.inflight[key].forEach(({
callback
}) => callback(undefined, response));
return response;
} catch (error) {
// If the request fails, reject all queued promises.
_this.inflight[key].forEach(({
callback
}) => callback(error, undefined));
throw error;
} finally {
delete _this.inflight[key];
}
};

@@ -828,24 +744,83 @@ };

function _classPrivateFieldBase(receiver, privateKey) {
if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
throw new TypeError("attempted to use private field on non-instance");
}
return receiver;
}
var id = 0;
function _classPrivateFieldKey(name) {
return "__private_" + id++ + "_" + name;
}
var _chainId = /*#__PURE__*/_classPrivateFieldKey("chainId");
var _nextId = /*#__PURE__*/_classPrivateFieldKey("nextId");
var _sender = /*#__PURE__*/_classPrivateFieldKey("sender");
// JsonRpcProvider with a middleware stack. By default it will use a simple caching middleware.
class JsonRpcProvider extends ethers.ethers.providers.JsonRpcProvider {
constructor(url, options) {
super(url, options == null ? void 0 : options.chainId);
this._chainId = void 0;
this._sender = void 0;
this.send = (method, params) => {
return this._sender.send(method, params);
};
this.fetch = (method, params) => {
const request = {
method: method,
params: params,
id: this._nextId++,
class JsonRpcProvider extends ethers.ethers.JsonRpcProvider {
constructor(url, options, jsonRpcApiProviderOptions) {
var _this;
super(url, options == null ? void 0 : options.chainId, jsonRpcApiProviderOptions);
_this = this;
this.url = url;
Object.defineProperty(this, _chainId, {
writable: true,
value: void 0
});
Object.defineProperty(this, _nextId, {
writable: true,
value: 1
});
Object.defineProperty(this, _sender, {
writable: true,
value: void 0
});
this.fetch = async function (request) {
if (_this.url === undefined) {
throw new Error('missing provider URL');
}
const {
method,
params
} = request;
const jsonRpcRequest = {
method,
params,
id: _classPrivateFieldBase(_this, _nextId)[_nextId]++,
jsonrpc: '2.0'
};
const result = ethers.ethers.utils.fetchJson(this.connection, JSON.stringify(request), getResult).then(result => {
return result;
}, error => {
throw error;
});
return result;
// const result = ethers.fetchJson(this.connection, JSON.stringify(request), getResult).then(
// result => {
// return result
// },
// error => {
// throw error
// }
// )
const fetchRequest = typeof _this.url === 'string' ? new ethers.ethers.FetchRequest(_this.url) : _this.url;
fetchRequest.body = JSON.stringify(jsonRpcRequest);
// TODOXXX: what about headers, etc..?
// we probably need these in the options of the construtor, etc..
try {
const res = await fetchRequest.send();
if (res.body) {
try {
const result = JSON.parse(ethers.ethers.toUtf8String(res.body));
// TODO: Process result
return getResult(result);
} catch (err) {
throw new Error('invalid JSON response');
}
}
return null;
} catch (err) {
throw err;
}
};

@@ -855,3 +830,3 @@ const chainId = options == null ? void 0 : options.chainId;

const blockCache = options == null ? void 0 : options.blockCache;
this._chainId = chainId;
_classPrivateFieldBase(this, _chainId)[_chainId] = chainId;

@@ -869,7 +844,17 @@ // NOTE: it will either use the middleware stack passed to the constructor

blockCache: blockCache
})], new JsonRpcSender(this.fetch, chainId));
this._sender = new JsonRpcSender(router, chainId);
})], new JsonRpcHandler(this.fetch, chainId));
_classPrivateFieldBase(this, _sender)[_sender] = router;
}
async request(request) {
return await _classPrivateFieldBase(this, _sender)[_sender].request(request);
}
send(method, params, chainId) {
return this.request({
method,
params: params,
chainId
});
}
async getNetwork() {
const chainId = this._chainId;
const chainId = _classPrivateFieldBase(this, _chainId)[_chainId];
if (chainId) {

@@ -879,10 +864,10 @@ const network = constants_dist_0xsequenceNetworkConstants.networks[chainId];

const ensAddress = network == null ? void 0 : network.ensAddress;
return {
name: name,
chainId: chainId,
ensAddress: ensAddress
};
return ethers.ethers.Network.from({
name,
chainId,
ensAddress
});
} else {
const chainIdHex = await this.send('eth_chainId', []);
this._chainId = ethers.ethers.BigNumber.from(chainIdHex).toNumber();
_classPrivateFieldBase(this, _chainId)[_chainId] = Number(BigInt(chainIdHex));
return this.getNetwork();

@@ -909,7 +894,5 @@ }

exports.EagerProvider = EagerProvider;
exports.JsonRpcExternalProvider = JsonRpcExternalProvider;
exports.JsonRpcHandler = JsonRpcHandler;
exports.JsonRpcProvider = JsonRpcProvider;
exports.JsonRpcRouter = JsonRpcRouter;
exports.JsonRpcSender = JsonRpcSender;
exports.JsonRpcVersion = JsonRpcVersion;
exports.PublicProvider = PublicProvider;

@@ -929,4 +912,4 @@ exports.SigningProvider = SigningProvider;

exports.indexerURL = indexerURL;
exports.isJsonRpcHandler = isJsonRpcHandler;
exports.isJsonRpcProvider = isJsonRpcProvider;
exports.isJsonRpcSender = isJsonRpcSender;
exports.isNetworkConfig = isNetworkConfig;

@@ -933,0 +916,0 @@ exports.isValidNetworkConfig = isValidNetworkConfig;

@@ -6,4 +6,4 @@ 'use strict';

var constants_dist_0xsequenceNetworkConstants = require('../constants/dist/0xsequence-network-constants.cjs.prod.js');
var utils = require('@0xsequence/utils');
var ethers = require('ethers');
var utils = require('@0xsequence/utils');

@@ -35,3 +35,3 @@ function _extends() {

}
return ethers.ethers.BigNumber.from(chainId).toNumber();
return Number(BigInt(chainId));
};

@@ -143,3 +143,3 @@ const maybeChainId = chainId => {

if (chainId.startsWith('0x')) {
const id = ethers.ethers.BigNumber.from(chainId).toNumber();
const id = Number(BigInt(chainId));
return networks.find(n => n.chainId === id);

@@ -153,4 +153,4 @@ } else {

return networks.find(n => n.chainId === chainId.chainId);
} else if (ethers.ethers.BigNumber.isBigNumber(chainId)) {
const id = chainId.toNumber();
} else if (typeof chainId === 'bigint') {
const id = Number(chainId);
return networks.find(n => n.chainId === id);

@@ -224,9 +224,9 @@ } else {

function toChainIdNumber(chainIdLike) {
if (ethers.ethers.BigNumber.isBigNumber(chainIdLike)) {
if (typeof chainIdLike === 'bigint') {
return chainIdLike;
}
if (utils.isBigNumberish(chainIdLike)) {
return ethers.ethers.BigNumber.from(chainIdLike);
return BigInt(chainIdLike);
}
return ethers.ethers.BigNumber.from(chainIdLike.chainId);
return BigInt(chainIdLike.chainId);
}

@@ -273,6 +273,2 @@ const genUrls = network => {

const JsonRpcVersion = '2.0';
// EIP-1193 function signature
class JsonRpcRouter {

@@ -288,10 +284,6 @@ constructor(middlewares, sender) {

setMiddleware(middlewares) {
this.handler = createJsonRpcMiddlewareStack(middlewares, this.sender.sendAsync);
this.handler = createJsonRpcMiddlewareStack(middlewares, this.sender);
}
sendAsync(request, callback, chainId) {
try {
this.handler(request, callback, chainId);
} catch (err) {
callback(err, undefined);
}
request(request) {
return this.handler.request(request);
}

@@ -302,4 +294,4 @@ }

const toMiddleware = v => {
if (v.sendAsyncMiddleware) {
return v.sendAsyncMiddleware;
if (v.requestHandler) {
return v.requestHandler;
} else {

@@ -310,80 +302,49 @@ return v;

let chain;
chain = toMiddleware(middlewares[middlewares.length - 1])(handler);
chain = toMiddleware(middlewares[middlewares.length - 1])(handler.request);
for (let i = middlewares.length - 2; i >= 0; i--) {
chain = toMiddleware(middlewares[i])(chain);
}
return chain;
return {
request: chain
};
};
// TODOXXX: review..
function isJsonRpcProvider(cand) {
return cand !== undefined && cand.send !== undefined && cand.constructor.defaultUrl !== undefined && cand.detectNetwork !== undefined && cand.getSigner !== undefined && cand.perform !== undefined;
}
function isJsonRpcHandler(cand) {
return cand !== undefined && cand.sendAsync !== undefined;
function isJsonRpcSender(cand) {
return cand !== undefined && cand.send !== undefined;
}
let _nextId = 0;
class JsonRpcSender {
class JsonRpcHandler {
constructor(provider, defaultChainId) {
this.send = void 0;
this.request = void 0;
this.provider = void 0;
this.defaultChainId = void 0;
this.sendAsync = (request, callback, chainId) => {
this.send(request.method, request.params, chainId || this.defaultChainId).then(r => {
callback(undefined, {
jsonrpc: '2.0',
id: request.id,
result: r
});
}).catch(e => {
callback(e, undefined);
});
};
this.defaultChainId = defaultChainId;
if (isJsonRpcProvider(provider)) {
// we can ignore defaultChainId for JsonRpcProviders as they are already chain-bound
this.send = provider.send.bind(provider);
} else if (isJsonRpcHandler(provider)) {
this.send = (method, params, chainId) => {
return new Promise((resolve, reject) => {
provider.sendAsync({
// TODO: really shouldn't have to set these here?
jsonrpc: JsonRpcVersion,
id: ++_nextId,
method,
params
}, (error, response) => {
if (error) {
reject(error);
} else if (response) {
resolve(response.result);
} else {
resolve(undefined);
}
}, chainId || this.defaultChainId);
});
if (isJsonRpcSender(provider)) {
this.provider = request => {
return provider.send(request.method, request.params, request.chainId);
};
} else if (isJsonRpcProvider(provider)) {
this.provider = request => {
return provider.send(request.method, request.params || []);
};
} else {
this.send = provider;
this.provider = provider;
}
this.request = (request, chainId) => {
return this.send(request.method, request.params, chainId);
};
this.defaultChainId = defaultChainId;
}
}
class JsonRpcExternalProvider {
constructor(provider) {
this.provider = provider;
this.sendAsync = (request, callback) => {
this.provider.send(request.method, request.params).then(r => {
callback(undefined, {
jsonrpc: '2.0',
id: request.id,
result: r
});
}).catch(e => {
callback(e, undefined);
});
request(request) {
if (!request.chainId) {
request.chainId = this.defaultChainId;
}
return this.provider(request);
}
send(method, params, chainId) {
const request = {
method,
params,
chainId
};
this.send = this.sendAsync;
return this.request(request);
}

@@ -394,3 +355,3 @@ }

constructor(isAllowedFunc) {
this.sendAsyncMiddleware = void 0;
this.requestHandler = void 0;
this.isAllowedFunc = void 0;

@@ -402,11 +363,11 @@ if (isAllowedFunc) {

}
this.sendAsyncMiddleware = allowProviderMiddleware(this.isAllowedFunc);
this.requestHandler = allowProviderMiddleware(this.isAllowedFunc);
}
setIsAllowedFunc(fn) {
this.isAllowedFunc = fn;
this.sendAsyncMiddleware = allowProviderMiddleware(this.isAllowedFunc);
this.requestHandler = allowProviderMiddleware(this.isAllowedFunc);
}
}
const allowProviderMiddleware = isAllowed => next => {
return (request, callback, chainId) => {
return request => {
// ensure precondition is met or do not allow the request to continue

@@ -418,3 +379,3 @@ if (!isAllowed(request)) {

// request is allowed. keep going..
next(request, callback, chainId);
return next(request);
};

@@ -425,2 +386,3 @@ };

constructor(options) {
var _this = this;
// cachableJsonRpcMethods which can be permanently cached for lifetime

@@ -444,15 +406,13 @@ // of the provider.

this.defaultChainId = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback, chainId) => {
this.requestHandler = next => {
return async function (request) {
// Respond early with cached result
if (this.cachableJsonRpcMethods.includes(request.method) || this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
const key = this.cacheKey(request.method, request.params, chainId || this.defaultChainId);
const result = this.getCacheValue(key);
if (result && result !== '') {
callback(undefined, {
jsonrpc: '2.0',
if (_this.cachableJsonRpcMethods.includes(request.method) || _this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
const key = _this.cacheKey(request.method, request.params, request.chainId || _this.defaultChainId);
const _result = _this.getCacheValue(key);
if (_result && _result !== '') {
return {
id: request.id,
result: result
});
return;
result: _result
};
}

@@ -462,19 +422,17 @@ }

// Continue down the handler chain
next(request, (error, response, chainId) => {
// Store result in cache and continue
if (this.cachableJsonRpcMethods.includes(request.method) || this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
if (response && response.result && this.shouldCacheResponse(request, response)) {
// cache the value
const key = this.cacheKey(request.method, request.params, chainId || this.defaultChainId);
if (this.cachableJsonRpcMethods.includes(request.method)) {
this.setCacheValue(key, response.result);
} else {
this.setCacheByBlockValue(key, response.result);
}
const result = await next(request);
// Store result in cache and continue
if (_this.cachableJsonRpcMethods.includes(request.method) || _this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
if (result && _this.shouldCacheResponse(request, result)) {
// cache the value
const key = _this.cacheKey(request.method, request.params, request.chainId || _this.defaultChainId);
if (_this.cachableJsonRpcMethods.includes(request.method)) {
_this.setCacheValue(key, result);
} else {
_this.setCacheByBlockValue(key, result);
}
}
// Exec next handler
callback(error, response);
}, chainId || this.defaultChainId);
}
return result;
};

@@ -528,5 +486,5 @@ };

};
this.shouldCacheResponse = (request, response) => {
this.shouldCacheResponse = (request, result) => {
// skip if we do not have response result
if (!response || !response.result) {
if (!result) {
return false;

@@ -536,3 +494,3 @@ }

// skip caching eth_getCode where resposne value is '0x' or empty
if (request.method === 'eth_getCode' && response.result.length <= 2) {
if (request.method === 'eth_getCode' && result.length <= 2) {
return false;

@@ -569,52 +527,29 @@ }

constructor(options) {
var _this = this;
this.options = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback, chainId) => {
const {
id,
method
} = request;
switch (method) {
this.requestHandler = next => {
return async function (request) {
switch (request.method) {
case 'net_version':
if (this.options.chainId) {
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: `${this.options.chainId}`
});
return;
if (_this.options.chainId) {
return `${_this.options.chainId}`;
}
break;
case 'eth_chainId':
if (this.options.chainId) {
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: ethers.ethers.utils.hexlify(this.options.chainId)
});
return;
if (_this.options.chainId) {
return ethers.ethers.toBeHex(_this.options.chainId);
}
break;
case 'eth_accounts':
if (this.options.accountAddress) {
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: [ethers.ethers.utils.getAddress(this.options.accountAddress)]
});
return;
if (_this.options.accountAddress) {
return [ethers.ethers.getAddress(_this.options.accountAddress)];
}
break;
case 'sequence_getWalletContext':
if (this.options.walletContext) {
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: this.options.walletContext
});
return;
if (_this.options.walletContext) {
return _this.options.walletContext;
}
break;
}
next(request, callback, chainId);
return next(request);
};

@@ -627,13 +562,12 @@ };

const exceptionProviderMiddleware = next => {
return (request, callback, chainId) => {
next(request, (error, response) => {
if (!error && response && response.error) {
if (typeof response.error === 'string') {
throw new Error(response.error);
} else {
throw new Error(response.error.message);
}
return async request => {
try {
return await next(request);
} catch (error) {
if (typeof error === 'string') {
throw new Error(error);
} else {
throw new Error(error.message);
}
callback(error, response);
}, chainId);
}
};

@@ -644,13 +578,12 @@ };

const loggingProviderMiddleware = next => {
return (request, callback, chainId) => {
const chainIdLabel = chainId ? ` chainId:${chainId}` : '';
return async request => {
const chainIdLabel = request.chainId ? ` chainId:${request.chainId}` : '';
utils.logger.info(`[provider request]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params);
next(request, (error, response) => {
if (error) {
utils.logger.warn(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `error:`, error);
} else {
utils.logger.info(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `response:`, response);
}
callback(error, response);
}, chainId);
try {
const result = await next(request);
utils.logger.info(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `result:`, result);
return result;
} catch (error) {
utils.logger.warn(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `error:`, error);
}
};

@@ -660,27 +593,17 @@ };

const networkProviderMiddleware = getChainId => next => {
return (request, callback, chainId) => {
return async request => {
const networkChainId = getChainId(request);
const {
id,
method
} = request;
switch (method) {
switch (request.method) {
case 'net_version':
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: `${networkChainId}`
});
return;
{
return `${networkChainId}`;
}
case 'eth_chainId':
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: ethers.ethers.utils.hexlify(networkChainId)
});
return;
{
return ethers.ethers.toBeHex(networkChainId);
}
}
// request is allowed. keep going..
next(request, callback, chainId);
return next(request);
};

@@ -698,12 +621,11 @@ };

this.provider = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback, chainId) => {
this.requestHandler = next => {
return request => {
// Forward signing requests to the signing provider
if (SignerJsonRpcMethods.includes(request.method)) {
this.provider.sendAsync(request, callback, chainId);
return;
return this.provider.request(request);
}
// Continue to next handler
next(request, callback, chainId);
return next(request);
};

@@ -720,14 +642,7 @@ };

this.rpcUrl = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback) => {
this.requestHandler = next => {
return request => {
// When provider is configured, send non-private methods to our local public provider
if (this.provider && !this.privateJsonRpcMethods.includes(request.method)) {
this.provider.send(request.method, request.params).then(r => {
callback(undefined, {
jsonrpc: '2.0',
id: request.id,
result: r
});
}).catch(e => callback(e));
return;
return this.provider.send(request.method, request.params || []);
}

@@ -737,3 +652,3 @@

utils.logger.debug('[public-provider] sending request to signer window', request.method);
next(request, callback);
return next(request);
};

@@ -756,3 +671,3 @@ };

// which supports better caching.
this.provider = new ethers.providers.JsonRpcProvider(rpcUrl);
this.provider = new ethers.ethers.JsonRpcProvider(rpcUrl);
}

@@ -764,47 +679,48 @@ }

constructor() {
var _this = this;
this.singleflightJsonRpcMethods = ['eth_chainId', 'net_version', 'eth_call', 'eth_getCode', 'eth_blockNumber', 'eth_getBalance', 'eth_getStorageAt', 'eth_getTransactionCount', 'eth_getBlockTransactionCountByHash', 'eth_getBlockTransactionCountByNumber', 'eth_getUncleCountByBlockHash', 'eth_getUncleCountByBlockNumber', 'eth_getBlockByHash', 'eth_getBlockByNumber', 'eth_getTransactionByHash', 'eth_getTransactionByBlockHashAndIndex', 'eth_getTransactionByBlockNumberAndIndex', 'eth_getTransactionReceipt', 'eth_getUncleByBlockHashAndIndex', 'eth_getUncleByBlockNumberAndIndex', 'eth_getLogs'];
this.inflight = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback, chainId) => {
this.requestHandler = next => {
return async function (request) {
// continue to next handler if method isn't part of methods list
if (!this.singleflightJsonRpcMethods.includes(request.method)) {
next(request, callback, chainId);
return;
if (!_this.singleflightJsonRpcMethods.includes(request.method)) {
return next(request);
}
const key = this.requestKey(request.method, request.params || [], chainId);
if (!this.inflight[key]) {
const key = _this.requestKey(request.method, request.params || [], request.chainId);
if (!_this.inflight[key]) {
// first request -- init the empty list
this.inflight[key] = [];
_this.inflight[key] = [];
} else {
// already in-flight, add the callback to the list and return
this.inflight[key].push({
id: request.id,
callback
return new Promise((resolve, reject) => {
_this.inflight[key].push({
id: request.id,
callback: (error, response) => {
if (error) {
reject(error);
} else {
resolve(response);
}
}
});
});
return;
}
// Continue down the handler chain
next(request, (error, response, chainId) => {
// callback the original request
callback(error, response);
// callback all other requests of the same kind in queue, with the
// same response result as from the first response.
for (let i = 0; i < this.inflight[key].length; i++) {
const sub = this.inflight[key][i];
if (error) {
sub.callback(error, response);
} else if (response) {
sub.callback(undefined, {
jsonrpc: '2.0',
id: sub.id,
result: response.result
});
}
}
// clear request key
delete this.inflight[key];
}, chainId);
try {
// Exec the handler, and on success resolve all other promises
const response = await next(request);
_this.inflight[key].forEach(({
callback
}) => callback(undefined, response));
return response;
} catch (error) {
// If the request fails, reject all queued promises.
_this.inflight[key].forEach(({
callback
}) => callback(error, undefined));
throw error;
} finally {
delete _this.inflight[key];
}
};

@@ -828,24 +744,83 @@ };

function _classPrivateFieldBase(receiver, privateKey) {
if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
throw new TypeError("attempted to use private field on non-instance");
}
return receiver;
}
var id = 0;
function _classPrivateFieldKey(name) {
return "__private_" + id++ + "_" + name;
}
var _chainId = /*#__PURE__*/_classPrivateFieldKey("chainId");
var _nextId = /*#__PURE__*/_classPrivateFieldKey("nextId");
var _sender = /*#__PURE__*/_classPrivateFieldKey("sender");
// JsonRpcProvider with a middleware stack. By default it will use a simple caching middleware.
class JsonRpcProvider extends ethers.ethers.providers.JsonRpcProvider {
constructor(url, options) {
super(url, options == null ? void 0 : options.chainId);
this._chainId = void 0;
this._sender = void 0;
this.send = (method, params) => {
return this._sender.send(method, params);
};
this.fetch = (method, params) => {
const request = {
method: method,
params: params,
id: this._nextId++,
class JsonRpcProvider extends ethers.ethers.JsonRpcProvider {
constructor(url, options, jsonRpcApiProviderOptions) {
var _this;
super(url, options == null ? void 0 : options.chainId, jsonRpcApiProviderOptions);
_this = this;
this.url = url;
Object.defineProperty(this, _chainId, {
writable: true,
value: void 0
});
Object.defineProperty(this, _nextId, {
writable: true,
value: 1
});
Object.defineProperty(this, _sender, {
writable: true,
value: void 0
});
this.fetch = async function (request) {
if (_this.url === undefined) {
throw new Error('missing provider URL');
}
const {
method,
params
} = request;
const jsonRpcRequest = {
method,
params,
id: _classPrivateFieldBase(_this, _nextId)[_nextId]++,
jsonrpc: '2.0'
};
const result = ethers.ethers.utils.fetchJson(this.connection, JSON.stringify(request), getResult).then(result => {
return result;
}, error => {
throw error;
});
return result;
// const result = ethers.fetchJson(this.connection, JSON.stringify(request), getResult).then(
// result => {
// return result
// },
// error => {
// throw error
// }
// )
const fetchRequest = typeof _this.url === 'string' ? new ethers.ethers.FetchRequest(_this.url) : _this.url;
fetchRequest.body = JSON.stringify(jsonRpcRequest);
// TODOXXX: what about headers, etc..?
// we probably need these in the options of the construtor, etc..
try {
const res = await fetchRequest.send();
if (res.body) {
try {
const result = JSON.parse(ethers.ethers.toUtf8String(res.body));
// TODO: Process result
return getResult(result);
} catch (err) {
throw new Error('invalid JSON response');
}
}
return null;
} catch (err) {
throw err;
}
};

@@ -855,3 +830,3 @@ const chainId = options == null ? void 0 : options.chainId;

const blockCache = options == null ? void 0 : options.blockCache;
this._chainId = chainId;
_classPrivateFieldBase(this, _chainId)[_chainId] = chainId;

@@ -869,7 +844,17 @@ // NOTE: it will either use the middleware stack passed to the constructor

blockCache: blockCache
})], new JsonRpcSender(this.fetch, chainId));
this._sender = new JsonRpcSender(router, chainId);
})], new JsonRpcHandler(this.fetch, chainId));
_classPrivateFieldBase(this, _sender)[_sender] = router;
}
async request(request) {
return await _classPrivateFieldBase(this, _sender)[_sender].request(request);
}
send(method, params, chainId) {
return this.request({
method,
params: params,
chainId
});
}
async getNetwork() {
const chainId = this._chainId;
const chainId = _classPrivateFieldBase(this, _chainId)[_chainId];
if (chainId) {

@@ -879,10 +864,10 @@ const network = constants_dist_0xsequenceNetworkConstants.networks[chainId];

const ensAddress = network == null ? void 0 : network.ensAddress;
return {
name: name,
chainId: chainId,
ensAddress: ensAddress
};
return ethers.ethers.Network.from({
name,
chainId,
ensAddress
});
} else {
const chainIdHex = await this.send('eth_chainId', []);
this._chainId = ethers.ethers.BigNumber.from(chainIdHex).toNumber();
_classPrivateFieldBase(this, _chainId)[_chainId] = Number(BigInt(chainIdHex));
return this.getNetwork();

@@ -909,7 +894,5 @@ }

exports.EagerProvider = EagerProvider;
exports.JsonRpcExternalProvider = JsonRpcExternalProvider;
exports.JsonRpcHandler = JsonRpcHandler;
exports.JsonRpcProvider = JsonRpcProvider;
exports.JsonRpcRouter = JsonRpcRouter;
exports.JsonRpcSender = JsonRpcSender;
exports.JsonRpcVersion = JsonRpcVersion;
exports.PublicProvider = PublicProvider;

@@ -929,4 +912,4 @@ exports.SigningProvider = SigningProvider;

exports.indexerURL = indexerURL;
exports.isJsonRpcHandler = isJsonRpcHandler;
exports.isJsonRpcProvider = isJsonRpcProvider;
exports.isJsonRpcSender = isJsonRpcSender;
exports.isNetworkConfig = isNetworkConfig;

@@ -933,0 +916,0 @@ exports.isValidNetworkConfig = isValidNetworkConfig;

import { networks, ChainId } from '../constants/dist/0xsequence-network-constants.esm.js';
export { ChainId, NetworkType, networks } from '../constants/dist/0xsequence-network-constants.esm.js';
import { ethers, providers } from 'ethers';
import { isBigNumberish, logger } from '@0xsequence/utils';
import { ethers } from 'ethers';

@@ -31,3 +31,3 @@ function _extends() {

}
return ethers.BigNumber.from(chainId).toNumber();
return Number(BigInt(chainId));
};

@@ -139,3 +139,3 @@ const maybeChainId = chainId => {

if (chainId.startsWith('0x')) {
const id = ethers.BigNumber.from(chainId).toNumber();
const id = Number(BigInt(chainId));
return networks.find(n => n.chainId === id);

@@ -149,4 +149,4 @@ } else {

return networks.find(n => n.chainId === chainId.chainId);
} else if (ethers.BigNumber.isBigNumber(chainId)) {
const id = chainId.toNumber();
} else if (typeof chainId === 'bigint') {
const id = Number(chainId);
return networks.find(n => n.chainId === id);

@@ -220,9 +220,9 @@ } else {

function toChainIdNumber(chainIdLike) {
if (ethers.BigNumber.isBigNumber(chainIdLike)) {
if (typeof chainIdLike === 'bigint') {
return chainIdLike;
}
if (isBigNumberish(chainIdLike)) {
return ethers.BigNumber.from(chainIdLike);
return BigInt(chainIdLike);
}
return ethers.BigNumber.from(chainIdLike.chainId);
return BigInt(chainIdLike.chainId);
}

@@ -269,6 +269,2 @@ const genUrls = network => {

const JsonRpcVersion = '2.0';
// EIP-1193 function signature
class JsonRpcRouter {

@@ -284,10 +280,6 @@ constructor(middlewares, sender) {

setMiddleware(middlewares) {
this.handler = createJsonRpcMiddlewareStack(middlewares, this.sender.sendAsync);
this.handler = createJsonRpcMiddlewareStack(middlewares, this.sender);
}
sendAsync(request, callback, chainId) {
try {
this.handler(request, callback, chainId);
} catch (err) {
callback(err, undefined);
}
request(request) {
return this.handler.request(request);
}

@@ -298,4 +290,4 @@ }

const toMiddleware = v => {
if (v.sendAsyncMiddleware) {
return v.sendAsyncMiddleware;
if (v.requestHandler) {
return v.requestHandler;
} else {

@@ -306,80 +298,49 @@ return v;

let chain;
chain = toMiddleware(middlewares[middlewares.length - 1])(handler);
chain = toMiddleware(middlewares[middlewares.length - 1])(handler.request);
for (let i = middlewares.length - 2; i >= 0; i--) {
chain = toMiddleware(middlewares[i])(chain);
}
return chain;
return {
request: chain
};
};
// TODOXXX: review..
function isJsonRpcProvider(cand) {
return cand !== undefined && cand.send !== undefined && cand.constructor.defaultUrl !== undefined && cand.detectNetwork !== undefined && cand.getSigner !== undefined && cand.perform !== undefined;
}
function isJsonRpcHandler(cand) {
return cand !== undefined && cand.sendAsync !== undefined;
function isJsonRpcSender(cand) {
return cand !== undefined && cand.send !== undefined;
}
let _nextId = 0;
class JsonRpcSender {
class JsonRpcHandler {
constructor(provider, defaultChainId) {
this.send = void 0;
this.request = void 0;
this.provider = void 0;
this.defaultChainId = void 0;
this.sendAsync = (request, callback, chainId) => {
this.send(request.method, request.params, chainId || this.defaultChainId).then(r => {
callback(undefined, {
jsonrpc: '2.0',
id: request.id,
result: r
});
}).catch(e => {
callback(e, undefined);
});
};
this.defaultChainId = defaultChainId;
if (isJsonRpcProvider(provider)) {
// we can ignore defaultChainId for JsonRpcProviders as they are already chain-bound
this.send = provider.send.bind(provider);
} else if (isJsonRpcHandler(provider)) {
this.send = (method, params, chainId) => {
return new Promise((resolve, reject) => {
provider.sendAsync({
// TODO: really shouldn't have to set these here?
jsonrpc: JsonRpcVersion,
id: ++_nextId,
method,
params
}, (error, response) => {
if (error) {
reject(error);
} else if (response) {
resolve(response.result);
} else {
resolve(undefined);
}
}, chainId || this.defaultChainId);
});
if (isJsonRpcSender(provider)) {
this.provider = request => {
return provider.send(request.method, request.params, request.chainId);
};
} else if (isJsonRpcProvider(provider)) {
this.provider = request => {
return provider.send(request.method, request.params || []);
};
} else {
this.send = provider;
this.provider = provider;
}
this.request = (request, chainId) => {
return this.send(request.method, request.params, chainId);
};
this.defaultChainId = defaultChainId;
}
}
class JsonRpcExternalProvider {
constructor(provider) {
this.provider = provider;
this.sendAsync = (request, callback) => {
this.provider.send(request.method, request.params).then(r => {
callback(undefined, {
jsonrpc: '2.0',
id: request.id,
result: r
});
}).catch(e => {
callback(e, undefined);
});
request(request) {
if (!request.chainId) {
request.chainId = this.defaultChainId;
}
return this.provider(request);
}
send(method, params, chainId) {
const request = {
method,
params,
chainId
};
this.send = this.sendAsync;
return this.request(request);
}

@@ -390,3 +351,3 @@ }

constructor(isAllowedFunc) {
this.sendAsyncMiddleware = void 0;
this.requestHandler = void 0;
this.isAllowedFunc = void 0;

@@ -398,11 +359,11 @@ if (isAllowedFunc) {

}
this.sendAsyncMiddleware = allowProviderMiddleware(this.isAllowedFunc);
this.requestHandler = allowProviderMiddleware(this.isAllowedFunc);
}
setIsAllowedFunc(fn) {
this.isAllowedFunc = fn;
this.sendAsyncMiddleware = allowProviderMiddleware(this.isAllowedFunc);
this.requestHandler = allowProviderMiddleware(this.isAllowedFunc);
}
}
const allowProviderMiddleware = isAllowed => next => {
return (request, callback, chainId) => {
return request => {
// ensure precondition is met or do not allow the request to continue

@@ -414,3 +375,3 @@ if (!isAllowed(request)) {

// request is allowed. keep going..
next(request, callback, chainId);
return next(request);
};

@@ -421,2 +382,3 @@ };

constructor(options) {
var _this = this;
// cachableJsonRpcMethods which can be permanently cached for lifetime

@@ -440,15 +402,13 @@ // of the provider.

this.defaultChainId = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback, chainId) => {
this.requestHandler = next => {
return async function (request) {
// Respond early with cached result
if (this.cachableJsonRpcMethods.includes(request.method) || this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
const key = this.cacheKey(request.method, request.params, chainId || this.defaultChainId);
const result = this.getCacheValue(key);
if (result && result !== '') {
callback(undefined, {
jsonrpc: '2.0',
if (_this.cachableJsonRpcMethods.includes(request.method) || _this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
const key = _this.cacheKey(request.method, request.params, request.chainId || _this.defaultChainId);
const _result = _this.getCacheValue(key);
if (_result && _result !== '') {
return {
id: request.id,
result: result
});
return;
result: _result
};
}

@@ -458,19 +418,17 @@ }

// Continue down the handler chain
next(request, (error, response, chainId) => {
// Store result in cache and continue
if (this.cachableJsonRpcMethods.includes(request.method) || this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
if (response && response.result && this.shouldCacheResponse(request, response)) {
// cache the value
const key = this.cacheKey(request.method, request.params, chainId || this.defaultChainId);
if (this.cachableJsonRpcMethods.includes(request.method)) {
this.setCacheValue(key, response.result);
} else {
this.setCacheByBlockValue(key, response.result);
}
const result = await next(request);
// Store result in cache and continue
if (_this.cachableJsonRpcMethods.includes(request.method) || _this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
if (result && _this.shouldCacheResponse(request, result)) {
// cache the value
const key = _this.cacheKey(request.method, request.params, request.chainId || _this.defaultChainId);
if (_this.cachableJsonRpcMethods.includes(request.method)) {
_this.setCacheValue(key, result);
} else {
_this.setCacheByBlockValue(key, result);
}
}
// Exec next handler
callback(error, response);
}, chainId || this.defaultChainId);
}
return result;
};

@@ -524,5 +482,5 @@ };

};
this.shouldCacheResponse = (request, response) => {
this.shouldCacheResponse = (request, result) => {
// skip if we do not have response result
if (!response || !response.result) {
if (!result) {
return false;

@@ -532,3 +490,3 @@ }

// skip caching eth_getCode where resposne value is '0x' or empty
if (request.method === 'eth_getCode' && response.result.length <= 2) {
if (request.method === 'eth_getCode' && result.length <= 2) {
return false;

@@ -565,52 +523,29 @@ }

constructor(options) {
var _this = this;
this.options = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback, chainId) => {
const {
id,
method
} = request;
switch (method) {
this.requestHandler = next => {
return async function (request) {
switch (request.method) {
case 'net_version':
if (this.options.chainId) {
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: `${this.options.chainId}`
});
return;
if (_this.options.chainId) {
return `${_this.options.chainId}`;
}
break;
case 'eth_chainId':
if (this.options.chainId) {
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: ethers.utils.hexlify(this.options.chainId)
});
return;
if (_this.options.chainId) {
return ethers.toBeHex(_this.options.chainId);
}
break;
case 'eth_accounts':
if (this.options.accountAddress) {
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: [ethers.utils.getAddress(this.options.accountAddress)]
});
return;
if (_this.options.accountAddress) {
return [ethers.getAddress(_this.options.accountAddress)];
}
break;
case 'sequence_getWalletContext':
if (this.options.walletContext) {
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: this.options.walletContext
});
return;
if (_this.options.walletContext) {
return _this.options.walletContext;
}
break;
}
next(request, callback, chainId);
return next(request);
};

@@ -623,13 +558,12 @@ };

const exceptionProviderMiddleware = next => {
return (request, callback, chainId) => {
next(request, (error, response) => {
if (!error && response && response.error) {
if (typeof response.error === 'string') {
throw new Error(response.error);
} else {
throw new Error(response.error.message);
}
return async request => {
try {
return await next(request);
} catch (error) {
if (typeof error === 'string') {
throw new Error(error);
} else {
throw new Error(error.message);
}
callback(error, response);
}, chainId);
}
};

@@ -640,13 +574,12 @@ };

const loggingProviderMiddleware = next => {
return (request, callback, chainId) => {
const chainIdLabel = chainId ? ` chainId:${chainId}` : '';
return async request => {
const chainIdLabel = request.chainId ? ` chainId:${request.chainId}` : '';
logger.info(`[provider request]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params);
next(request, (error, response) => {
if (error) {
logger.warn(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `error:`, error);
} else {
logger.info(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `response:`, response);
}
callback(error, response);
}, chainId);
try {
const result = await next(request);
logger.info(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `result:`, result);
return result;
} catch (error) {
logger.warn(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `error:`, error);
}
};

@@ -656,27 +589,17 @@ };

const networkProviderMiddleware = getChainId => next => {
return (request, callback, chainId) => {
return async request => {
const networkChainId = getChainId(request);
const {
id,
method
} = request;
switch (method) {
switch (request.method) {
case 'net_version':
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: `${networkChainId}`
});
return;
{
return `${networkChainId}`;
}
case 'eth_chainId':
callback(undefined, {
jsonrpc: '2.0',
id: id,
result: ethers.utils.hexlify(networkChainId)
});
return;
{
return ethers.toBeHex(networkChainId);
}
}
// request is allowed. keep going..
next(request, callback, chainId);
return next(request);
};

@@ -694,12 +617,11 @@ };

this.provider = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback, chainId) => {
this.requestHandler = next => {
return request => {
// Forward signing requests to the signing provider
if (SignerJsonRpcMethods.includes(request.method)) {
this.provider.sendAsync(request, callback, chainId);
return;
return this.provider.request(request);
}
// Continue to next handler
next(request, callback, chainId);
return next(request);
};

@@ -716,14 +638,7 @@ };

this.rpcUrl = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback) => {
this.requestHandler = next => {
return request => {
// When provider is configured, send non-private methods to our local public provider
if (this.provider && !this.privateJsonRpcMethods.includes(request.method)) {
this.provider.send(request.method, request.params).then(r => {
callback(undefined, {
jsonrpc: '2.0',
id: request.id,
result: r
});
}).catch(e => callback(e));
return;
return this.provider.send(request.method, request.params || []);
}

@@ -733,3 +648,3 @@

logger.debug('[public-provider] sending request to signer window', request.method);
next(request, callback);
return next(request);
};

@@ -752,3 +667,3 @@ };

// which supports better caching.
this.provider = new providers.JsonRpcProvider(rpcUrl);
this.provider = new ethers.JsonRpcProvider(rpcUrl);
}

@@ -760,47 +675,48 @@ }

constructor() {
var _this = this;
this.singleflightJsonRpcMethods = ['eth_chainId', 'net_version', 'eth_call', 'eth_getCode', 'eth_blockNumber', 'eth_getBalance', 'eth_getStorageAt', 'eth_getTransactionCount', 'eth_getBlockTransactionCountByHash', 'eth_getBlockTransactionCountByNumber', 'eth_getUncleCountByBlockHash', 'eth_getUncleCountByBlockNumber', 'eth_getBlockByHash', 'eth_getBlockByNumber', 'eth_getTransactionByHash', 'eth_getTransactionByBlockHashAndIndex', 'eth_getTransactionByBlockNumberAndIndex', 'eth_getTransactionReceipt', 'eth_getUncleByBlockHashAndIndex', 'eth_getUncleByBlockNumberAndIndex', 'eth_getLogs'];
this.inflight = void 0;
this.sendAsyncMiddleware = next => {
return (request, callback, chainId) => {
this.requestHandler = next => {
return async function (request) {
// continue to next handler if method isn't part of methods list
if (!this.singleflightJsonRpcMethods.includes(request.method)) {
next(request, callback, chainId);
return;
if (!_this.singleflightJsonRpcMethods.includes(request.method)) {
return next(request);
}
const key = this.requestKey(request.method, request.params || [], chainId);
if (!this.inflight[key]) {
const key = _this.requestKey(request.method, request.params || [], request.chainId);
if (!_this.inflight[key]) {
// first request -- init the empty list
this.inflight[key] = [];
_this.inflight[key] = [];
} else {
// already in-flight, add the callback to the list and return
this.inflight[key].push({
id: request.id,
callback
return new Promise((resolve, reject) => {
_this.inflight[key].push({
id: request.id,
callback: (error, response) => {
if (error) {
reject(error);
} else {
resolve(response);
}
}
});
});
return;
}
// Continue down the handler chain
next(request, (error, response, chainId) => {
// callback the original request
callback(error, response);
// callback all other requests of the same kind in queue, with the
// same response result as from the first response.
for (let i = 0; i < this.inflight[key].length; i++) {
const sub = this.inflight[key][i];
if (error) {
sub.callback(error, response);
} else if (response) {
sub.callback(undefined, {
jsonrpc: '2.0',
id: sub.id,
result: response.result
});
}
}
// clear request key
delete this.inflight[key];
}, chainId);
try {
// Exec the handler, and on success resolve all other promises
const response = await next(request);
_this.inflight[key].forEach(({
callback
}) => callback(undefined, response));
return response;
} catch (error) {
// If the request fails, reject all queued promises.
_this.inflight[key].forEach(({
callback
}) => callback(error, undefined));
throw error;
} finally {
delete _this.inflight[key];
}
};

@@ -824,24 +740,83 @@ };

function _classPrivateFieldBase(receiver, privateKey) {
if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
throw new TypeError("attempted to use private field on non-instance");
}
return receiver;
}
var id = 0;
function _classPrivateFieldKey(name) {
return "__private_" + id++ + "_" + name;
}
var _chainId = /*#__PURE__*/_classPrivateFieldKey("chainId");
var _nextId = /*#__PURE__*/_classPrivateFieldKey("nextId");
var _sender = /*#__PURE__*/_classPrivateFieldKey("sender");
// JsonRpcProvider with a middleware stack. By default it will use a simple caching middleware.
class JsonRpcProvider extends ethers.providers.JsonRpcProvider {
constructor(url, options) {
super(url, options == null ? void 0 : options.chainId);
this._chainId = void 0;
this._sender = void 0;
this.send = (method, params) => {
return this._sender.send(method, params);
};
this.fetch = (method, params) => {
const request = {
method: method,
params: params,
id: this._nextId++,
class JsonRpcProvider extends ethers.JsonRpcProvider {
constructor(url, options, jsonRpcApiProviderOptions) {
var _this;
super(url, options == null ? void 0 : options.chainId, jsonRpcApiProviderOptions);
_this = this;
this.url = url;
Object.defineProperty(this, _chainId, {
writable: true,
value: void 0
});
Object.defineProperty(this, _nextId, {
writable: true,
value: 1
});
Object.defineProperty(this, _sender, {
writable: true,
value: void 0
});
this.fetch = async function (request) {
if (_this.url === undefined) {
throw new Error('missing provider URL');
}
const {
method,
params
} = request;
const jsonRpcRequest = {
method,
params,
id: _classPrivateFieldBase(_this, _nextId)[_nextId]++,
jsonrpc: '2.0'
};
const result = ethers.utils.fetchJson(this.connection, JSON.stringify(request), getResult).then(result => {
return result;
}, error => {
throw error;
});
return result;
// const result = ethers.fetchJson(this.connection, JSON.stringify(request), getResult).then(
// result => {
// return result
// },
// error => {
// throw error
// }
// )
const fetchRequest = typeof _this.url === 'string' ? new ethers.FetchRequest(_this.url) : _this.url;
fetchRequest.body = JSON.stringify(jsonRpcRequest);
// TODOXXX: what about headers, etc..?
// we probably need these in the options of the construtor, etc..
try {
const res = await fetchRequest.send();
if (res.body) {
try {
const result = JSON.parse(ethers.toUtf8String(res.body));
// TODO: Process result
return getResult(result);
} catch (err) {
throw new Error('invalid JSON response');
}
}
return null;
} catch (err) {
throw err;
}
};

@@ -851,3 +826,3 @@ const chainId = options == null ? void 0 : options.chainId;

const blockCache = options == null ? void 0 : options.blockCache;
this._chainId = chainId;
_classPrivateFieldBase(this, _chainId)[_chainId] = chainId;

@@ -865,7 +840,17 @@ // NOTE: it will either use the middleware stack passed to the constructor

blockCache: blockCache
})], new JsonRpcSender(this.fetch, chainId));
this._sender = new JsonRpcSender(router, chainId);
})], new JsonRpcHandler(this.fetch, chainId));
_classPrivateFieldBase(this, _sender)[_sender] = router;
}
async request(request) {
return await _classPrivateFieldBase(this, _sender)[_sender].request(request);
}
send(method, params, chainId) {
return this.request({
method,
params: params,
chainId
});
}
async getNetwork() {
const chainId = this._chainId;
const chainId = _classPrivateFieldBase(this, _chainId)[_chainId];
if (chainId) {

@@ -875,10 +860,10 @@ const network = networks[chainId];

const ensAddress = network == null ? void 0 : network.ensAddress;
return {
name: name,
chainId: chainId,
ensAddress: ensAddress
};
return ethers.Network.from({
name,
chainId,
ensAddress
});
} else {
const chainIdHex = await this.send('eth_chainId', []);
this._chainId = ethers.BigNumber.from(chainIdHex).toNumber();
_classPrivateFieldBase(this, _chainId)[_chainId] = Number(BigInt(chainIdHex));
return this.getNetwork();

@@ -899,2 +884,2 @@ }

export { AllowProvider, CachedProvider, EagerProvider, JsonRpcExternalProvider, JsonRpcProvider, JsonRpcRouter, JsonRpcSender, JsonRpcVersion, PublicProvider, SigningProvider, SingleflightMiddleware, allNetworks, allowProviderMiddleware, checkNetworkConfig, createJsonRpcMiddlewareStack, ensureUniqueNetworks, ensureValidNetworks, exceptionProviderMiddleware, findNetworkConfig, findSupportedNetwork, getChainId, indexerURL, isJsonRpcHandler, isJsonRpcProvider, isNetworkConfig, isValidNetworkConfig, loggingProviderMiddleware, maybeChainId, networkProviderMiddleware, networksIndex, nodesURL, relayerURL, sortNetworks, stringTemplate, toChainIdNumber, updateNetworkConfig, validateAndSortNetworks };
export { AllowProvider, CachedProvider, EagerProvider, JsonRpcHandler, JsonRpcProvider, JsonRpcRouter, PublicProvider, SigningProvider, SingleflightMiddleware, allNetworks, allowProviderMiddleware, checkNetworkConfig, createJsonRpcMiddlewareStack, ensureUniqueNetworks, ensureValidNetworks, exceptionProviderMiddleware, findNetworkConfig, findSupportedNetwork, getChainId, indexerURL, isJsonRpcProvider, isJsonRpcSender, isNetworkConfig, isValidNetworkConfig, loggingProviderMiddleware, maybeChainId, networkProviderMiddleware, networksIndex, nodesURL, relayerURL, sortNetworks, stringTemplate, toChainIdNumber, updateNetworkConfig, validateAndSortNetworks };

@@ -1,2 +0,2 @@

import { BigNumberish, ethers, providers } from 'ethers';
import { ethers } from 'ethers';
import { Indexer } from '@0xsequence/indexer';

@@ -7,3 +7,3 @@ import { Relayer, RpcRelayerOptions } from '@0xsequence/relayer';

rpcUrl: string;
provider?: providers.Provider;
provider?: ethers.Provider;
indexerUrl?: string;

@@ -19,4 +19,4 @@ indexer?: Indexer;

export declare function findSupportedNetwork(chainIdOrName: string | ChainIdLike): NetworkConfig | undefined;
export type ChainIdLike = NetworkConfig | BigNumberish;
export declare function toChainIdNumber(chainIdLike: ChainIdLike): ethers.BigNumber;
export type ChainIdLike = NetworkConfig | ethers.BigNumberish;
export declare function toChainIdNumber(chainIdLike: ChainIdLike): bigint;
export declare const allNetworks: NetworkConfig[];
import { ethers } from 'ethers';
import { JsonRpcMiddleware, JsonRpcMiddlewareHandler } from "./json-rpc/index.js";
import { JsonRpcMiddleware, JsonRpcMiddlewareHandler, EIP1193Provider, JsonRpcSender } from "./json-rpc/index.js";
export interface JsonRpcProviderOptions {

@@ -8,9 +8,14 @@ chainId?: number;

}
export declare class JsonRpcProvider extends ethers.providers.JsonRpcProvider {
private _chainId?;
private _sender;
constructor(url: ethers.utils.ConnectionInfo | string, options?: JsonRpcProviderOptions);
getNetwork(): Promise<ethers.providers.Network>;
send: (method: string, params: Array<any>) => Promise<any>;
export declare class JsonRpcProvider extends ethers.JsonRpcProvider implements EIP1193Provider, JsonRpcSender {
#private;
url: string | ethers.FetchRequest | undefined;
constructor(url: string | ethers.FetchRequest | undefined, options?: JsonRpcProviderOptions, jsonRpcApiProviderOptions?: ethers.JsonRpcApiProviderOptions);
request(request: {
method: string;
params?: any[];
chainId?: number;
}): Promise<any>;
send(method: string, params?: any[] | Record<string, any>, chainId?: number): Promise<any>;
getNetwork(): Promise<ethers.Network>;
private fetch;
}
export * from "./types.js";
export * from "./router.js";
export * from "./sender.js";
export * from "./handler.js";
export * from "./middleware/index.js";
export * from "./utils.js";
import { JsonRpcRequest, JsonRpcMiddleware, JsonRpcMiddlewareHandler } from "../types.js";
export declare class AllowProvider implements JsonRpcMiddlewareHandler {
sendAsyncMiddleware: JsonRpcMiddleware;
requestHandler: JsonRpcMiddleware;
private isAllowedFunc;

@@ -5,0 +5,0 @@ constructor(isAllowedFunc?: (request: JsonRpcRequest) => boolean);

@@ -1,2 +0,2 @@

import { JsonRpcHandlerFunc, JsonRpcRequest, JsonRpcResponse, JsonRpcResponseCallback, JsonRpcMiddlewareHandler } from "../types.js";
import { EIP1193ProviderFunc, JsonRpcRequest, JsonRpcMiddlewareHandler } from "../types.js";
export interface CachedProviderOptions {

@@ -15,3 +15,9 @@ defaultChainId?: number;

constructor(options?: CachedProviderOptions);
sendAsyncMiddleware: (next: JsonRpcHandlerFunc) => (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => void;
requestHandler: (next: EIP1193ProviderFunc) => (request: {
jsonrpc: '2.0';
id?: number;
method: string;
params?: any[];
chainId?: number;
}) => Promise<any>;
cacheKey: (method: string, params: any[], chainId?: number) => string;

@@ -27,5 +33,5 @@ getCache: () => {

setCacheByBlockValue: (key: string, value: any) => void;
shouldCacheResponse: (request: JsonRpcRequest, response?: JsonRpcResponse) => boolean;
shouldCacheResponse: (request: JsonRpcRequest, result?: any) => boolean;
onUpdate(callback: (key?: string, value?: any) => void): void;
clearCache: () => void;
}
import { commons } from '@0xsequence/core';
import { JsonRpcHandlerFunc, JsonRpcRequest, JsonRpcResponseCallback, JsonRpcMiddlewareHandler } from "../types.js";
import { EIP1193ProviderFunc, JsonRpcMiddlewareHandler } from "../types.js";
export type EagerProviderOptions = {

@@ -11,3 +11,9 @@ accountAddress?: string;

constructor(options: EagerProviderOptions);
sendAsyncMiddleware: (next: JsonRpcHandlerFunc) => (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => void;
requestHandler: (next: EIP1193ProviderFunc) => (request: {
jsonrpc: '2.0';
id?: number;
method: string;
params?: any[];
chainId?: number;
}) => Promise<any>;
}

@@ -1,2 +0,2 @@

import { JsonRpcHandlerFunc, JsonRpcRequest, JsonRpcResponseCallback, JsonRpcMiddlewareHandler } from "../types.js";
import { EIP1193ProviderFunc, JsonRpcMiddlewareHandler } from "../types.js";
export declare class PublicProvider implements JsonRpcMiddlewareHandler {

@@ -7,5 +7,10 @@ private privateJsonRpcMethods;

constructor(rpcUrl?: string);
sendAsyncMiddleware: (next: JsonRpcHandlerFunc) => (request: JsonRpcRequest, callback: JsonRpcResponseCallback) => void;
requestHandler: (next: EIP1193ProviderFunc) => (request: {
jsonrpc: '2.0';
method: string;
params?: any[];
chainId?: number;
}) => Promise<any>;
getRpcUrl(): string | undefined;
setRpcUrl(rpcUrl: string): void;
}

@@ -1,7 +0,12 @@

import { JsonRpcHandlerFunc, JsonRpcRequest, JsonRpcResponseCallback, JsonRpcMiddlewareHandler, JsonRpcHandler } from "../types.js";
import { EIP1193Provider, EIP1193ProviderFunc, JsonRpcMiddlewareHandler } from "../types.js";
export declare const SignerJsonRpcMethods: string[];
export declare class SigningProvider implements JsonRpcMiddlewareHandler {
private provider;
constructor(provider: JsonRpcHandler);
sendAsyncMiddleware: (next: JsonRpcHandlerFunc) => (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => void;
constructor(provider: EIP1193Provider);
requestHandler: (next: EIP1193ProviderFunc) => (request: {
jsonrpc: '2.0';
method: string;
params?: any[];
chainId?: number;
}) => Promise<any>;
}

@@ -1,2 +0,2 @@

import { JsonRpcHandlerFunc, JsonRpcRequest, JsonRpcResponseCallback, JsonRpcMiddlewareHandler } from "../types.js";
import { EIP1193ProviderFunc, JsonRpcResponseCallback, JsonRpcMiddlewareHandler } from "../types.js";
export declare class SingleflightMiddleware implements JsonRpcMiddlewareHandler {

@@ -11,4 +11,10 @@ private singleflightJsonRpcMethods;

constructor();
sendAsyncMiddleware: (next: JsonRpcHandlerFunc) => (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => void;
requestHandler: (next: EIP1193ProviderFunc) => (request: {
jsonrpc: '2.0';
id?: number;
method: string;
params?: any[];
chainId?: number;
}) => Promise<any>;
requestKey: (method: string, params: any[], chainId?: number) => string;
}

@@ -1,9 +0,14 @@

import { JsonRpcHandlerFunc, JsonRpcRequest, JsonRpcResponseCallback, JsonRpcHandler, JsonRpcMiddleware, JsonRpcMiddlewareHandler } from "./types.js";
export declare class JsonRpcRouter implements JsonRpcHandler {
import { EIP1193Provider, JsonRpcMiddleware, JsonRpcMiddlewareHandler } from "./types.js";
export declare class JsonRpcRouter implements EIP1193Provider {
private sender;
private handler;
constructor(middlewares: Array<JsonRpcMiddleware | JsonRpcMiddlewareHandler>, sender: JsonRpcHandler);
constructor(middlewares: Array<JsonRpcMiddleware | JsonRpcMiddlewareHandler>, sender: EIP1193Provider);
setMiddleware(middlewares: Array<JsonRpcMiddleware | JsonRpcMiddlewareHandler>): void;
sendAsync(request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number): void;
request(request: {
id?: number;
method: string;
params?: any[];
chainId?: number;
}): Promise<any>;
}
export declare const createJsonRpcMiddlewareStack: (middlewares: Array<JsonRpcMiddleware | JsonRpcMiddlewareHandler>, handler: JsonRpcHandlerFunc) => JsonRpcHandlerFunc;
export declare const createJsonRpcMiddlewareStack: (middlewares: Array<JsonRpcMiddleware | JsonRpcMiddlewareHandler>, handler: EIP1193Provider) => EIP1193Provider;

@@ -1,33 +0,40 @@

export declare const JsonRpcVersion = "2.0";
export interface JsonRpcRequest {
jsonrpc?: string;
export type JsonRpcRequest = {
jsonrpc?: '2.0';
id?: number;
method: string;
params?: any[];
}
export interface JsonRpcResponse {
jsonrpc: string;
chainId?: number;
};
export type JsonRpcResponse = {
jsonrpc?: string;
id: number;
result: any;
error?: ProviderRpcError;
error?: JsonRpcErrorPayload;
};
export type JsonRpcErrorPayload = {
code: number;
message?: string;
data?: any;
};
export interface EIP1193Provider<R = any> {
request(request: {
method: string;
params?: any[];
chainId?: number;
}): Promise<R>;
}
export type JsonRpcResponseCallback = (error?: ProviderRpcError, response?: JsonRpcResponse) => void;
export type JsonRpcHandlerFunc = (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => void;
export interface JsonRpcHandler {
sendAsync: JsonRpcHandlerFunc;
}
export type JsonRpcFetchFunc = (method: string, params?: any[], chainId?: number) => Promise<any>;
export type JsonRpcRequestFunc = (request: {
export type EIP1193ProviderFunc<R = any> = (request: {
method: string;
params?: any[];
}, chainId?: number) => Promise<any>;
export type JsonRpcMiddleware = (next: JsonRpcHandlerFunc) => JsonRpcHandlerFunc;
chainId?: number;
}) => Promise<R>;
export interface JsonRpcSender<R = any> {
send(method: string, params?: any[], chainId?: number): Promise<R>;
}
export type JsonRpcSendFunc<R = any> = (method: string, params?: any[], chainId?: number) => Promise<R>;
export type JsonRpcResponseCallback = (error: JsonRpcErrorPayload | undefined, response?: JsonRpcResponse) => void;
export type JsonRpcSendAsyncFunc = (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => void;
export type JsonRpcMiddleware = (next: EIP1193ProviderFunc) => EIP1193ProviderFunc;
export interface JsonRpcMiddlewareHandler {
sendAsyncMiddleware: JsonRpcMiddleware;
requestHandler: JsonRpcMiddleware;
}
export interface ProviderRpcError extends Error {
code?: number;
data?: {
[key: string]: any;
};
}

@@ -1,4 +0,4 @@

import { providers } from 'ethers';
import { JsonRpcHandler } from "./types.js";
export declare function isJsonRpcProvider(cand: any): cand is providers.JsonRpcProvider;
export declare function isJsonRpcHandler(cand: any): cand is JsonRpcHandler;
import { ethers } from 'ethers';
import { JsonRpcSender } from "./types.js";
export declare function isJsonRpcProvider(cand: any): cand is ethers.JsonRpcProvider;
export declare function isJsonRpcSender(cand: any): cand is JsonRpcSender;
{
"name": "@0xsequence/network",
"version": "0.0.0-20240613131211",
"version": "0.0.0-20240613194955",
"description": "network sub-package for Sequence",

@@ -12,12 +12,12 @@ "repository": "https://github.com/0xsequence/sequence.js/tree/master/packages/network",

"dependencies": {
"@0xsequence/core": "0.0.0-20240613131211",
"@0xsequence/relayer": "0.0.0-20240613131211",
"@0xsequence/indexer": "0.0.0-20240613131211",
"@0xsequence/utils": "0.0.0-20240613131211"
"@0xsequence/core": "0.0.0-20240613194955",
"@0xsequence/indexer": "0.0.0-20240613194955",
"@0xsequence/relayer": "0.0.0-20240613194955",
"@0xsequence/utils": "0.0.0-20240613194955"
},
"peerDependencies": {
"ethers": ">=5.5 < 6"
"ethers": ">=6"
},
"devDependencies": {
"ethers": "^5.7.2"
"ethers": "^6.13.0"
},

@@ -24,0 +24,0 @@ "files": [

@@ -1,2 +0,2 @@

import { BigNumberish, ethers, providers } from 'ethers'
import { ethers } from 'ethers'
import { Indexer } from '@0xsequence/indexer'

@@ -10,3 +10,3 @@ import { Relayer, RpcRelayerOptions } from '@0xsequence/relayer'

rpcUrl: string
provider?: providers.Provider
provider?: ethers.Provider
indexerUrl?: string

@@ -34,6 +34,6 @@ indexer?: Indexer

export type ChainIdLike = NetworkConfig | BigNumberish
export type ChainIdLike = NetworkConfig | ethers.BigNumberish
export function toChainIdNumber(chainIdLike: ChainIdLike): ethers.BigNumber {
if (ethers.BigNumber.isBigNumber(chainIdLike)) {
export function toChainIdNumber(chainIdLike: ChainIdLike): bigint {
if (typeof chainIdLike === 'bigint') {
return chainIdLike

@@ -43,6 +43,6 @@ }

if (isBigNumberish(chainIdLike)) {
return ethers.BigNumber.from(chainIdLike)
return BigInt(chainIdLike)
}
return ethers.BigNumber.from(chainIdLike.chainId)
return BigInt(chainIdLike.chainId)
}

@@ -49,0 +49,0 @@

import { ethers } from 'ethers'
import {
JsonRpcRouter,
JsonRpcSender,
loggingProviderMiddleware,
EagerProvider,

@@ -10,3 +8,6 @@ SingleflightMiddleware,

JsonRpcMiddleware,
JsonRpcMiddlewareHandler
JsonRpcMiddlewareHandler,
JsonRpcHandler,
EIP1193Provider,
JsonRpcSender
} from './json-rpc'

@@ -27,8 +28,13 @@ import { ChainId, networks } from './constants'

// JsonRpcProvider with a middleware stack. By default it will use a simple caching middleware.
export class JsonRpcProvider extends ethers.providers.JsonRpcProvider {
private _chainId?: number
private _sender: JsonRpcSender
export class JsonRpcProvider extends ethers.JsonRpcProvider implements EIP1193Provider, JsonRpcSender {
#chainId?: number
#nextId: number = 1
#sender: EIP1193Provider
constructor(url: ethers.utils.ConnectionInfo | string, options?: JsonRpcProviderOptions) {
super(url, options?.chainId)
constructor(
public url: string | ethers.FetchRequest | undefined,
options?: JsonRpcProviderOptions,
jsonRpcApiProviderOptions?: ethers.JsonRpcApiProviderOptions
) {
super(url, options?.chainId, jsonRpcApiProviderOptions)

@@ -39,3 +45,3 @@ const chainId = options?.chainId

this._chainId = chainId
this.#chainId = chainId

@@ -53,10 +59,18 @@ // NOTE: it will either use the middleware stack passed to the constructor

],
new JsonRpcSender(this.fetch, chainId)
new JsonRpcHandler(this.fetch, chainId)
)
this._sender = new JsonRpcSender(router, chainId)
this.#sender = router
}
async getNetwork(): Promise<ethers.providers.Network> {
const chainId = this._chainId
async request(request: { method: string; params?: any[]; chainId?: number }): Promise<any> {
return await this.#sender.request(request)
}
send(method: string, params?: any[] | Record<string, any>, chainId?: number): Promise<any> {
return this.request({ method, params: params as any, chainId })
}
async getNetwork(): Promise<ethers.Network> {
const chainId = this.#chainId
if (chainId) {

@@ -66,10 +80,10 @@ const network = networks[chainId as ChainId]

const ensAddress = network?.ensAddress
return {
name: name,
chainId: chainId,
ensAddress: ensAddress
}
return ethers.Network.from({
name,
chainId,
ensAddress
})
} else {
const chainIdHex = await this.send('eth_chainId', [])
this._chainId = ethers.BigNumber.from(chainIdHex).toNumber()
this.#chainId = Number(BigInt(chainIdHex))
return this.getNetwork()

@@ -79,24 +93,50 @@ }

send = (method: string, params: Array<any>): Promise<any> => {
return this._sender.send(method, params)
}
private fetch = async (request: { method: string; params?: any[]; chainId?: number }): Promise<any> => {
if (this.url === undefined) {
throw new Error('missing provider URL')
}
private fetch = (method: string, params: Array<any>): Promise<any> => {
const request = {
method: method,
params: params,
id: this._nextId++,
const { method, params } = request
const jsonRpcRequest = {
method,
params,
id: this.#nextId++,
jsonrpc: '2.0'
}
const result = ethers.utils.fetchJson(this.connection, JSON.stringify(request), getResult).then(
result => {
return result
},
error => {
throw error
// const result = ethers.fetchJson(this.connection, JSON.stringify(request), getResult).then(
// result => {
// return result
// },
// error => {
// throw error
// }
// )
const fetchRequest = typeof this.url === 'string' ? new ethers.FetchRequest(this.url) : this.url
fetchRequest.body = JSON.stringify(jsonRpcRequest)
// TODOXXX: what about headers, etc..?
// we probably need these in the options of the construtor, etc..
try {
const res = await fetchRequest.send()
if (res.body) {
try {
const result = JSON.parse(ethers.toUtf8String(res.body))
// TODO: Process result
return getResult(result)
} catch (err) {
throw new Error('invalid JSON response')
}
}
)
return result
return null
} catch (err) {
throw err
}
}

@@ -103,0 +143,0 @@ }

export * from './types'
export * from './router'
export * from './sender'
export * from './handler'
export * from './middleware'
export * from './utils'

@@ -1,11 +0,5 @@

import {
JsonRpcHandlerFunc,
JsonRpcRequest,
JsonRpcResponseCallback,
JsonRpcMiddleware,
JsonRpcMiddlewareHandler
} from '../types'
import { JsonRpcRequest, EIP1193ProviderFunc, JsonRpcMiddleware, JsonRpcMiddlewareHandler } from '../types'
export class AllowProvider implements JsonRpcMiddlewareHandler {
sendAsyncMiddleware: JsonRpcMiddleware
requestHandler: JsonRpcMiddleware

@@ -21,3 +15,3 @@ private isAllowedFunc: (request: JsonRpcRequest) => boolean

this.sendAsyncMiddleware = allowProviderMiddleware(this.isAllowedFunc)
this.requestHandler = allowProviderMiddleware(this.isAllowedFunc)
}

@@ -27,3 +21,3 @@

this.isAllowedFunc = fn
this.sendAsyncMiddleware = allowProviderMiddleware(this.isAllowedFunc)
this.requestHandler = allowProviderMiddleware(this.isAllowedFunc)
}

@@ -34,4 +28,4 @@ }

(isAllowed: (request: JsonRpcRequest) => boolean): JsonRpcMiddleware =>
(next: JsonRpcHandlerFunc) => {
return (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => {
(next: EIP1193ProviderFunc) => {
return (request: { jsonrpc: '2.0'; method: string; params?: any[]; chainId?: number }): Promise<any> => {
// ensure precondition is met or do not allow the request to continue

@@ -43,4 +37,4 @@ if (!isAllowed(request)) {

// request is allowed. keep going..
next(request, callback, chainId)
return next(request)
}
}

@@ -1,2 +0,2 @@

import { JsonRpcHandlerFunc, JsonRpcRequest, JsonRpcResponse, JsonRpcResponseCallback, JsonRpcMiddlewareHandler } from '../types'
import { EIP1193ProviderFunc, JsonRpcRequest, JsonRpcMiddlewareHandler } from '../types'

@@ -55,15 +55,13 @@ export interface CachedProviderOptions {

sendAsyncMiddleware = (next: JsonRpcHandlerFunc) => {
return (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => {
requestHandler = (next: EIP1193ProviderFunc) => {
return async (request: { jsonrpc: '2.0'; id?: number; method: string; params?: any[]; chainId?: number }): Promise<any> => {
// Respond early with cached result
if (this.cachableJsonRpcMethods.includes(request.method) || this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
const key = this.cacheKey(request.method, request.params!, chainId || this.defaultChainId)
const key = this.cacheKey(request.method, request.params! as any[], request.chainId || this.defaultChainId)
const result = this.getCacheValue(key)
if (result && result !== '') {
callback(undefined, {
jsonrpc: '2.0',
return {
id: request.id!,
result: result
})
return
result
}
}

@@ -73,27 +71,19 @@ }

// Continue down the handler chain
next(
request,
(error: any, response?: JsonRpcResponse, chainId?: number) => {
// Store result in cache and continue
if (
this.cachableJsonRpcMethods.includes(request.method) ||
this.cachableJsonRpcMethodsByBlock.includes(request.method)
) {
if (response && response.result && this.shouldCacheResponse(request, response)) {
// cache the value
const key = this.cacheKey(request.method, request.params!, chainId || this.defaultChainId)
const result = await next(request)
if (this.cachableJsonRpcMethods.includes(request.method)) {
this.setCacheValue(key, response.result)
} else {
this.setCacheByBlockValue(key, response.result)
}
}
// Store result in cache and continue
if (this.cachableJsonRpcMethods.includes(request.method) || this.cachableJsonRpcMethodsByBlock.includes(request.method)) {
if (result && this.shouldCacheResponse(request, result)) {
// cache the value
const key = this.cacheKey(request.method, request.params! as any[], request.chainId || this.defaultChainId)
if (this.cachableJsonRpcMethods.includes(request.method)) {
this.setCacheValue(key, result)
} else {
this.setCacheByBlockValue(key, result)
}
}
}
// Exec next handler
callback(error, response)
},
chainId || this.defaultChainId
)
return result
}

@@ -154,5 +144,5 @@ }

shouldCacheResponse = (request: JsonRpcRequest, response?: JsonRpcResponse): boolean => {
shouldCacheResponse = (request: JsonRpcRequest, result?: any): boolean => {
// skip if we do not have response result
if (!response || !response.result) {
if (!result) {
return false

@@ -162,3 +152,3 @@ }

// skip caching eth_getCode where resposne value is '0x' or empty
if (request.method === 'eth_getCode' && response.result.length <= 2) {
if (request.method === 'eth_getCode' && result.length <= 2) {
return false

@@ -165,0 +155,0 @@ }

import { commons } from '@0xsequence/core'
import { ethers } from 'ethers'
import { JsonRpcHandlerFunc, JsonRpcRequest, JsonRpcResponseCallback, JsonRpcResponse, JsonRpcMiddlewareHandler } from '../types'
import { EIP1193ProviderFunc, JsonRpcMiddlewareHandler } from '../types'

@@ -23,11 +23,8 @@ // EagerProvider will eagerly respond to a provider request from pre-initialized data values.

sendAsyncMiddleware = (next: JsonRpcHandlerFunc) => {
return (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => {
const { id, method } = request
switch (method) {
requestHandler = (next: EIP1193ProviderFunc) => {
return async (request: { jsonrpc: '2.0'; id?: number; method: string; params?: any[]; chainId?: number }): Promise<any> => {
switch (request.method) {
case 'net_version':
if (this.options.chainId) {
callback(undefined, { jsonrpc: '2.0', id: id!, result: `${this.options.chainId}` })
return
return `${this.options.chainId}`
}

@@ -38,4 +35,3 @@ break

if (this.options.chainId) {
callback(undefined, { jsonrpc: '2.0', id: id!, result: ethers.utils.hexlify(this.options.chainId) })
return
return ethers.toBeHex(this.options.chainId)
}

@@ -46,4 +42,3 @@ break

if (this.options.accountAddress) {
callback(undefined, { jsonrpc: '2.0', id: id!, result: [ethers.utils.getAddress(this.options.accountAddress)] })
return
return [ethers.getAddress(this.options.accountAddress)]
}

@@ -54,4 +49,3 @@ break

if (this.options.walletContext) {
callback(undefined, { jsonrpc: '2.0', id: id!, result: this.options.walletContext })
return
return this.options.walletContext
}

@@ -63,5 +57,5 @@ break

next(request, callback, chainId)
return next(request)
}
}
}

@@ -1,21 +0,15 @@

import { JsonRpcHandlerFunc, JsonRpcRequest, JsonRpcResponse, JsonRpcResponseCallback, JsonRpcMiddleware } from '../types'
import { EIP1193ProviderFunc, JsonRpcMiddleware } from '../types'
export const exceptionProviderMiddleware: JsonRpcMiddleware = (next: JsonRpcHandlerFunc) => {
return (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => {
next(
request,
(error: any, response?: JsonRpcResponse) => {
if (!error && response && response.error) {
if (typeof response.error === 'string') {
throw new Error(response.error)
} else {
throw new Error(response.error.message)
}
}
callback(error, response)
},
chainId
)
export const exceptionProviderMiddleware: JsonRpcMiddleware = (next: EIP1193ProviderFunc) => {
return async (request: { method: string; params?: any[]; chainId?: number }): Promise<any> => {
try {
return await next(request)
} catch (error) {
if (typeof error === 'string') {
throw new Error(error)
} else {
throw new Error(error.message)
}
}
}
}

@@ -1,33 +0,30 @@

import { JsonRpcHandlerFunc, JsonRpcRequest, JsonRpcResponse, JsonRpcResponseCallback, JsonRpcMiddleware } from '../types'
import { EIP1193ProviderFunc, JsonRpcMiddleware } from '../types'
import { logger } from '@0xsequence/utils'
// TODO: rename to loggerMiddleware
export const loggingProviderMiddleware: JsonRpcMiddleware = (next: JsonRpcHandlerFunc) => {
return (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => {
const chainIdLabel = chainId ? ` chainId:${chainId}` : ''
export const loggingProviderMiddleware: JsonRpcMiddleware = (next: EIP1193ProviderFunc) => {
return async (request: { jsonrpc: '2.0'; id?: number; method: string; params?: any[]; chainId?: number }): Promise<any> => {
const chainIdLabel = request.chainId ? ` chainId:${request.chainId}` : ''
logger.info(`[provider request]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params)
next(
request,
(error: any, response?: JsonRpcResponse) => {
if (error) {
logger.warn(
`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`,
request.params,
`error:`,
error
)
} else {
logger.info(
`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`,
request.params,
`response:`,
response
)
}
callback(error, response)
},
chainId
)
try {
const result = await next(request)
logger.info(
`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`,
request.params,
`result:`,
result
)
return result
} catch (error) {
logger.warn(
`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`,
request.params,
`error:`,
error
)
}
}
}
import { ethers } from 'ethers'
import {
JsonRpcHandlerFunc,
JsonRpcRequest,
JsonRpcResponseCallback,
JsonRpcMiddleware,
JsonRpcMiddlewareHandler
} from '../types'
import { EIP1193ProviderFunc, JsonRpcRequest, JsonRpcMiddleware } from '../types'
export const networkProviderMiddleware =
(getChainId: (request: JsonRpcRequest) => number): JsonRpcMiddleware =>
(next: JsonRpcHandlerFunc) => {
return (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => {
(next: EIP1193ProviderFunc) => {
return async (request: { jsonrpc: '2.0'; id?: number; method: string; params?: any[]; chainId?: number }): Promise<any> => {
const networkChainId = getChainId(request)
const { id, method } = request
switch (request.method) {
case 'net_version': {
return `${networkChainId}`
}
switch (method) {
case 'net_version':
callback(undefined, { jsonrpc: '2.0', id: id!, result: `${networkChainId}` })
return
case 'eth_chainId':
callback(undefined, { jsonrpc: '2.0', id: id!, result: ethers.utils.hexlify(networkChainId) })
return
default:
case 'eth_chainId': {
return ethers.toBeHex(networkChainId)
}
}
// request is allowed. keep going..
next(request, callback, chainId)
return next(request)
}
}

@@ -1,3 +0,3 @@

import { providers } from 'ethers'
import { JsonRpcHandlerFunc, JsonRpcRequest, JsonRpcResponseCallback, JsonRpcMiddlewareHandler } from '../types'
import { ethers } from 'ethers'
import { EIP1193ProviderFunc, JsonRpcMiddlewareHandler } from '../types'
import { SignerJsonRpcMethods } from './signing-provider'

@@ -9,3 +9,3 @@ import { logger } from '@0xsequence/utils'

private provider?: providers.JsonRpcProvider
private provider?: ethers.JsonRpcProvider
private rpcUrl?: string

@@ -19,17 +19,7 @@

sendAsyncMiddleware = (next: JsonRpcHandlerFunc) => {
return (request: JsonRpcRequest, callback: JsonRpcResponseCallback) => {
requestHandler = (next: EIP1193ProviderFunc) => {
return (request: { jsonrpc: '2.0'; method: string; params?: any[]; chainId?: number }): Promise<any> => {
// When provider is configured, send non-private methods to our local public provider
if (this.provider && !this.privateJsonRpcMethods.includes(request.method)) {
this.provider
.send(request.method, request.params!)
.then(r => {
callback(undefined, {
jsonrpc: '2.0',
id: request.id!,
result: r
})
})
.catch(e => callback(e))
return
return this.provider.send(request.method, request.params || [])
}

@@ -39,3 +29,3 @@

logger.debug('[public-provider] sending request to signer window', request.method)
next(request, callback)
return next(request)
}

@@ -56,5 +46,5 @@ }

// which supports better caching.
this.provider = new providers.JsonRpcProvider(rpcUrl)
this.provider = new ethers.JsonRpcProvider(rpcUrl)
}
}
}

@@ -1,2 +0,2 @@

import { JsonRpcHandlerFunc, JsonRpcRequest, JsonRpcResponseCallback, JsonRpcMiddlewareHandler, JsonRpcHandler } from '../types'
import { EIP1193Provider, EIP1193ProviderFunc, JsonRpcMiddlewareHandler } from '../types'

@@ -33,20 +33,19 @@ export const SignerJsonRpcMethods = [

export class SigningProvider implements JsonRpcMiddlewareHandler {
private provider: JsonRpcHandler
private provider: EIP1193Provider
constructor(provider: JsonRpcHandler) {
constructor(provider: EIP1193Provider) {
this.provider = provider
}
sendAsyncMiddleware = (next: JsonRpcHandlerFunc) => {
return (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => {
requestHandler = (next: EIP1193ProviderFunc) => {
return (request: { jsonrpc: '2.0'; method: string; params?: any[]; chainId?: number }): Promise<any> => {
// Forward signing requests to the signing provider
if (SignerJsonRpcMethods.includes(request.method)) {
this.provider.sendAsync(request, callback, chainId)
return
return this.provider.request(request)
}
// Continue to next handler
next(request, callback, chainId)
return next(request)
}
}
}

@@ -1,2 +0,2 @@

import { JsonRpcHandlerFunc, JsonRpcRequest, JsonRpcResponse, JsonRpcResponseCallback, JsonRpcMiddlewareHandler } from '../types'
import { EIP1193ProviderFunc, JsonRpcResponseCallback, JsonRpcMiddlewareHandler } from '../types'

@@ -34,11 +34,10 @@ export class SingleflightMiddleware implements JsonRpcMiddlewareHandler {

sendAsyncMiddleware = (next: JsonRpcHandlerFunc) => {
return (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => {
requestHandler = (next: EIP1193ProviderFunc) => {
return async (request: { jsonrpc: '2.0'; id?: number; method: string; params?: any[]; chainId?: number }): Promise<any> => {
// continue to next handler if method isn't part of methods list
if (!this.singleflightJsonRpcMethods.includes(request.method)) {
next(request, callback, chainId)
return
return next(request)
}
const key = this.requestKey(request.method, request.params || [], chainId)
const key = this.requestKey(request.method, request.params || [], request.chainId)

@@ -50,33 +49,29 @@ if (!this.inflight[key]) {

// already in-flight, add the callback to the list and return
this.inflight[key].push({ id: request.id!, callback })
return
return new Promise<any>((resolve, reject) => {
this.inflight[key].push({
id: request.id!,
callback: (error: any, response: any) => {
if (error) {
reject(error)
} else {
resolve(response)
}
}
})
})
}
// Continue down the handler chain
next(
request,
(error: any, response?: JsonRpcResponse, chainId?: number) => {
// callback the original request
callback(error, response)
// callback all other requests of the same kind in queue, with the
// same response result as from the first response.
for (let i = 0; i < this.inflight[key].length; i++) {
const sub = this.inflight[key][i]
if (error) {
sub.callback(error, response)
} else if (response) {
sub.callback(undefined, {
jsonrpc: '2.0',
id: sub.id,
result: response!.result
})
}
}
// clear request key
delete this.inflight[key]
},
chainId
)
try {
// Exec the handler, and on success resolve all other promises
const response = await next(request)
this.inflight[key].forEach(({ callback }) => callback(undefined, response))
return response
} catch (error) {
// If the request fails, reject all queued promises.
this.inflight[key].forEach(({ callback }) => callback(error, undefined))
throw error
} finally {
delete this.inflight[key]
}
}

@@ -83,0 +78,0 @@ }

@@ -1,15 +0,8 @@

import {
JsonRpcHandlerFunc,
JsonRpcRequest,
JsonRpcResponseCallback,
JsonRpcHandler,
JsonRpcMiddleware,
JsonRpcMiddlewareHandler
} from './types'
import { EIP1193Provider, EIP1193ProviderFunc, JsonRpcMiddleware, JsonRpcMiddlewareHandler } from './types'
export class JsonRpcRouter implements JsonRpcHandler {
private sender: JsonRpcHandler
private handler: JsonRpcHandlerFunc
export class JsonRpcRouter implements EIP1193Provider {
private sender: EIP1193Provider
private handler: EIP1193Provider
constructor(middlewares: Array<JsonRpcMiddleware | JsonRpcMiddlewareHandler>, sender: JsonRpcHandler) {
constructor(middlewares: Array<JsonRpcMiddleware | JsonRpcMiddlewareHandler>, sender: EIP1193Provider) {
this.sender = sender

@@ -22,11 +15,7 @@ if (middlewares) {

setMiddleware(middlewares: Array<JsonRpcMiddleware | JsonRpcMiddlewareHandler>) {
this.handler = createJsonRpcMiddlewareStack(middlewares, this.sender.sendAsync)
this.handler = createJsonRpcMiddlewareStack(middlewares, this.sender)
}
sendAsync(request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) {
try {
this.handler(request, callback, chainId)
} catch (err) {
callback(err, undefined)
}
request(request: { id?: number; method: string; params?: any[]; chainId?: number }): Promise<any> {
return this.handler.request(request)
}

@@ -37,9 +26,9 @@ }

middlewares: Array<JsonRpcMiddleware | JsonRpcMiddlewareHandler>,
handler: JsonRpcHandlerFunc
): JsonRpcHandlerFunc => {
handler: EIP1193Provider
): EIP1193Provider => {
if (middlewares.length === 0) return handler
const toMiddleware = (v: any): JsonRpcMiddleware => {
if (v.sendAsyncMiddleware) {
return (v as JsonRpcMiddlewareHandler).sendAsyncMiddleware
if (v.requestHandler) {
return (v as JsonRpcMiddlewareHandler).requestHandler
} else {

@@ -50,8 +39,8 @@ return v

let chain: JsonRpcHandlerFunc
chain = toMiddleware(middlewares[middlewares.length - 1])(handler)
let chain: EIP1193ProviderFunc
chain = toMiddleware(middlewares[middlewares.length - 1])(handler.request)
for (let i = middlewares.length - 2; i >= 0; i--) {
chain = toMiddleware(middlewares[i])(chain)
}
return chain
return { request: chain }
}

@@ -1,39 +0,45 @@

export const JsonRpcVersion = '2.0'
export interface JsonRpcRequest {
jsonrpc?: string
export type JsonRpcRequest = {
jsonrpc?: '2.0'
id?: number
method: string
params?: any[]
// ...
chainId?: number
}
export interface JsonRpcResponse {
jsonrpc: string
export type JsonRpcResponse = {
jsonrpc?: string
id: number
result: any
error?: ProviderRpcError
error?: JsonRpcErrorPayload
}
export type JsonRpcResponseCallback = (error?: ProviderRpcError, response?: JsonRpcResponse) => void
export type JsonRpcErrorPayload = {
code: number
message?: string
data?: any
}
export type JsonRpcHandlerFunc = (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => void
// EIP1193Provider with reponse of R (default any), but in most cases R will be of type JsonRpcResponse.
export interface EIP1193Provider<R = any> {
request(request: { method: string; params?: any[]; chainId?: number }): Promise<R>
}
export interface JsonRpcHandler {
sendAsync: JsonRpcHandlerFunc
export type EIP1193ProviderFunc<R = any> = (request: { method: string; params?: any[]; chainId?: number }) => Promise<R>
export interface JsonRpcSender<R = any> {
send(method: string, params?: any[], chainId?: number): Promise<R>
}
export type JsonRpcFetchFunc = (method: string, params?: any[], chainId?: number) => Promise<any>
export type JsonRpcSendFunc<R = any> = (method: string, params?: any[], chainId?: number) => Promise<R>
// EIP-1193 function signature
export type JsonRpcRequestFunc = (request: { method: string; params?: any[] }, chainId?: number) => Promise<any>
export type JsonRpcResponseCallback = (error: JsonRpcErrorPayload | undefined, response?: JsonRpcResponse) => void
export type JsonRpcMiddleware = (next: JsonRpcHandlerFunc) => JsonRpcHandlerFunc
export type JsonRpcSendAsyncFunc = (request: JsonRpcRequest, callback: JsonRpcResponseCallback, chainId?: number) => void
export type JsonRpcMiddleware = (next: EIP1193ProviderFunc) => EIP1193ProviderFunc
export interface JsonRpcMiddlewareHandler {
sendAsyncMiddleware: JsonRpcMiddleware
requestHandler: JsonRpcMiddleware
}
export interface ProviderRpcError extends Error {
code?: number
data?: { [key: string]: any }
}

@@ -1,5 +0,6 @@

import { providers } from 'ethers'
import { JsonRpcHandler } from './types'
import { ethers } from 'ethers'
import { JsonRpcSender } from './types'
export function isJsonRpcProvider(cand: any): cand is providers.JsonRpcProvider {
// TODOXXX: review..
export function isJsonRpcProvider(cand: any): cand is ethers.JsonRpcProvider {
return (

@@ -15,4 +16,4 @@ cand !== undefined &&

export function isJsonRpcHandler(cand: any): cand is JsonRpcHandler {
return cand !== undefined && cand.sendAsync !== undefined
export function isJsonRpcSender(cand: any): cand is JsonRpcSender {
return cand !== undefined && cand.send !== undefined
}

@@ -1,2 +0,2 @@

import { ethers, BigNumberish } from 'ethers'
import { ethers } from 'ethers'
import { ChainIdLike } from '.'

@@ -16,3 +16,3 @@ import { NetworkConfig } from './config'

}
return ethers.BigNumber.from(chainId as BigNumberish).toNumber()
return Number(BigInt(chainId as ethers.BigNumberish))
}

@@ -142,3 +142,3 @@

if (chainId.startsWith('0x')) {
const id = ethers.BigNumber.from(chainId).toNumber()
const id = Number(BigInt(chainId))
return networks.find(n => n.chainId === id)

@@ -152,4 +152,4 @@ } else {

return networks.find(n => n.chainId === (<NetworkConfig>chainId).chainId)
} else if (ethers.BigNumber.isBigNumber(chainId)) {
const id = chainId.toNumber()
} else if (typeof chainId === 'bigint') {
const id = Number(chainId)
return networks.find(n => n.chainId === id)

@@ -156,0 +156,0 @@ } else {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc