ethers.js/packages/providers/lib.esm/web3-provider.js

98 lines
3.5 KiB
JavaScript
Raw Normal View History

"use strict";
import { defineReadOnly } from "@ethersproject/properties";
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
import { JsonRpcProvider } from "./json-rpc-provider";
2020-04-27 13:31:43 +03:00
let _nextId = 1;
function buildWeb3LegacyFetcher(provider, sendFunc) {
return function (method, params) {
// Metamask complains about eth_sign (and on some versions hangs)
2020-04-27 13:31:43 +03:00
if (method == "eth_sign" && provider.isMetaMask) {
// https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
method = "personal_sign";
params = [params[1], params[0]];
}
2020-04-27 13:31:43 +03:00
const request = {
method: method,
params: params,
id: (_nextId++),
jsonrpc: "2.0"
};
return new Promise((resolve, reject) => {
2020-04-27 13:31:43 +03:00
sendFunc(request, function (error, result) {
if (error) {
2020-04-27 13:31:43 +03:00
return reject(error);
}
if (result.error) {
2019-11-20 12:57:38 +03:00
const error = new Error(result.error.message);
error.code = result.error.code;
error.data = result.error.data;
2020-04-27 13:31:43 +03:00
return reject(error);
}
resolve(result.result);
});
});
2020-04-27 13:31:43 +03:00
};
}
function buildEip1193Fetcher(provider) {
return function (method, params) {
if (params == null) {
params = [];
}
// Metamask complains about eth_sign (and on some versions hangs)
if (method == "eth_sign" && provider.isMetaMask) {
// https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
method = "personal_sign";
params = [params[1], params[0]];
}
return provider.request({ method, params });
};
}
export class Web3Provider extends JsonRpcProvider {
constructor(provider, network) {
logger.checkNew(new.target, Web3Provider);
if (provider == null) {
logger.throwArgumentError("missing provider", "provider", provider);
}
let path = null;
let jsonRpcFetchFunc = null;
let subprovider = null;
if (typeof (provider) === "function") {
path = "unknown:";
jsonRpcFetchFunc = provider;
}
else {
path = provider.host || provider.path || "";
if (!path && provider.isMetaMask) {
path = "metamask";
}
subprovider = provider;
if (provider.request) {
if (path === "") {
path = "eip-1193:";
}
jsonRpcFetchFunc = buildEip1193Fetcher(provider);
}
else if (provider.sendAsync) {
jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider, provider.sendAsync.bind(provider));
}
else if (provider.send) {
jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider, provider.send.bind(provider));
}
else {
logger.throwArgumentError("unsupported provider", "provider", provider);
}
if (!path) {
path = "unknown:";
}
}
super(path, network);
defineReadOnly(this, "jsonRpcFetchFunc", jsonRpcFetchFunc);
defineReadOnly(this, "provider", subprovider);
}
send(method, params) {
return this.jsonRpcFetchFunc(method, params);
}
}