ethers.js/packages/providers/lib.esm/json-rpc-provider.js

675 lines
27 KiB
JavaScript
Raw Normal View History

2019-05-15 01:48:48 +03:00
"use strict";
2019-11-20 12:57:38 +03:00
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { Signer } from "@ethersproject/abstract-signer";
import { BigNumber } from "@ethersproject/bignumber";
2022-05-21 02:13:03 +03:00
import { hexlify, hexValue, hexZeroPad, isHexString } from "@ethersproject/bytes";
2020-10-19 06:19:16 +03:00
import { _TypedDataEncoder } from "@ethersproject/hash";
2019-11-20 12:57:38 +03:00
import { checkProperties, deepCopy, defineReadOnly, getStatic, resolveProperties, shallowCopy } from "@ethersproject/properties";
import { toUtf8Bytes } from "@ethersproject/strings";
2021-03-30 22:22:45 +03:00
import { accessListify } from "@ethersproject/transactions";
import { fetchJson, poll } from "@ethersproject/web";
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
import { BaseProvider } from "./base-provider";
2020-09-16 10:08:36 +03:00
const errorGas = ["call", "estimateGas"];
2022-05-13 00:30:28 +03:00
function spelunk(value, requireData) {
2022-03-26 00:56:35 +03:00
if (value == null) {
return null;
}
// These *are* the droids we're looking for.
2022-05-13 00:30:28 +03:00
if (typeof (value.message) === "string" && value.message.match("reverted")) {
const data = isHexString(value.data) ? value.data : null;
if (!requireData || data) {
return { message: value.message, data };
}
2022-03-26 00:56:35 +03:00
}
// Spelunk further...
if (typeof (value) === "object") {
for (const key in value) {
2022-05-13 00:30:28 +03:00
const result = spelunk(value[key], requireData);
2022-03-26 00:56:35 +03:00
if (result) {
return result;
}
}
return null;
}
// Might be a JSON string we can further descend...
if (typeof (value) === "string") {
try {
2022-05-13 00:30:28 +03:00
return spelunk(JSON.parse(value), requireData);
2022-03-26 00:56:35 +03:00
}
catch (error) { }
}
return null;
}
2020-09-16 10:08:36 +03:00
function checkError(method, error, params) {
2022-05-13 00:30:28 +03:00
const transaction = params.transaction || params.signedTransaction;
2020-11-23 06:44:33 +03:00
// Undo the "convenience" some nodes are attempting to prevent backwards
// incompatibility; maybe for v6 consider forwarding reverts as errors
2022-03-26 00:56:35 +03:00
if (method === "call") {
2022-05-13 00:30:28 +03:00
const result = spelunk(error, true);
2022-03-26 00:56:35 +03:00
if (result) {
return result.data;
2020-11-23 06:44:33 +03:00
}
2022-05-13 00:30:28 +03:00
// Nothing descriptive..
2022-04-13 07:25:25 +03:00
logger.throwError("missing revert data in call exception; Transaction reverted without a reason string", Logger.errors.CALL_EXCEPTION, {
2022-05-13 00:30:28 +03:00
data: "0x", transaction, error
2021-06-24 09:13:06 +03:00
});
2020-11-23 06:44:33 +03:00
}
2022-05-13 00:30:28 +03:00
if (method === "estimateGas") {
// Try to find something, with a preference on SERVER_ERROR body
let result = spelunk(error.body, false);
if (result == null) {
result = spelunk(error, false);
}
// Found "reverted", this is a CALL_EXCEPTION
if (result) {
logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
reason: result.message, method, transaction, error
});
}
}
2022-03-26 00:56:35 +03:00
// @TODO: Should we spelunk for message too?
2020-09-11 09:10:58 +03:00
let message = error.message;
if (error.code === Logger.errors.SERVER_ERROR && error.error && typeof (error.error.message) === "string") {
message = error.error.message;
}
2020-09-16 10:08:36 +03:00
else if (typeof (error.body) === "string") {
message = error.body;
}
2020-09-11 09:10:58 +03:00
else if (typeof (error.responseText) === "string") {
message = error.responseText;
}
2020-09-16 10:08:36 +03:00
message = (message || "").toLowerCase();
// "insufficient funds for gas * price + value + cost(data)"
2022-05-01 09:11:22 +03:00
if (message.match(/insufficient funds|base fee exceeds gas limit/i)) {
2020-09-16 10:08:36 +03:00
logger.throwError("insufficient funds for intrinsic transaction cost", Logger.errors.INSUFFICIENT_FUNDS, {
error, method, transaction
});
}
// "nonce too low"
2022-05-01 09:11:22 +03:00
if (message.match(/nonce (is )?too low/i)) {
2020-09-16 10:08:36 +03:00
logger.throwError("nonce has already been used", Logger.errors.NONCE_EXPIRED, {
error, method, transaction
});
}
// "replacement transaction underpriced"
2022-05-01 09:11:22 +03:00
if (message.match(/replacement transaction underpriced|transaction gas price.*too low/i)) {
2020-09-16 10:08:36 +03:00
logger.throwError("replacement fee too low", Logger.errors.REPLACEMENT_UNDERPRICED, {
error, method, transaction
});
}
2021-04-18 05:41:09 +03:00
// "replacement transaction underpriced"
2022-05-01 09:11:22 +03:00
if (message.match(/only replay-protected/i)) {
2021-04-18 05:41:09 +03:00
logger.throwError("legacy pre-eip-155 transactions not supported", Logger.errors.UNSUPPORTED_OPERATION, {
error, method, transaction
});
}
2020-09-16 10:08:36 +03:00
if (errorGas.indexOf(method) >= 0 && message.match(/gas required exceeds allowance|always failing transaction|execution reverted/)) {
logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
error, method, transaction
});
}
throw error;
2020-09-11 09:10:58 +03:00
}
2019-05-15 01:48:48 +03:00
function timer(timeout) {
return new Promise(function (resolve) {
2020-05-04 00:53:58 +03:00
setTimeout(resolve, timeout);
2019-05-15 01:48:48 +03:00
});
}
function getResult(payload) {
if (payload.error) {
// @TODO: not any
2020-06-03 10:47:17 +03:00
const error = new Error(payload.error.message);
2019-05-15 01:48:48 +03:00
error.code = payload.error.code;
error.data = payload.error.data;
throw error;
}
return payload.result;
}
function getLowerCase(value) {
if (value) {
return value.toLowerCase();
}
return value;
}
const _constructorGuard = {};
export class JsonRpcSigner extends Signer {
constructor(constructorGuard, provider, addressOrIndex) {
super();
2019-05-15 01:48:48 +03:00
if (constructorGuard !== _constructorGuard) {
throw new Error("do not call the JsonRpcSigner constructor directly; use provider.getSigner");
}
defineReadOnly(this, "provider", provider);
2019-05-15 01:48:48 +03:00
if (addressOrIndex == null) {
addressOrIndex = 0;
}
2019-06-01 21:19:43 +03:00
if (typeof (addressOrIndex) === "string") {
defineReadOnly(this, "_address", this.provider.formatter.address(addressOrIndex));
defineReadOnly(this, "_index", null);
2019-06-01 21:19:43 +03:00
}
else if (typeof (addressOrIndex) === "number") {
defineReadOnly(this, "_index", addressOrIndex);
defineReadOnly(this, "_address", null);
2019-06-01 21:19:43 +03:00
}
else {
2019-08-02 09:10:58 +03:00
logger.throwArgumentError("invalid address or index", "addressOrIndex", addressOrIndex);
2019-05-15 01:48:48 +03:00
}
}
connect(provider) {
return logger.throwError("cannot alter JSON-RPC Signer connection", Logger.errors.UNSUPPORTED_OPERATION, {
2019-05-15 01:48:48 +03:00
operation: "connect"
});
}
connectUnchecked() {
2019-05-15 01:48:48 +03:00
return new UncheckedJsonRpcSigner(_constructorGuard, this.provider, this._address || this._index);
}
getAddress() {
2019-05-15 01:48:48 +03:00
if (this._address) {
return Promise.resolve(this._address);
}
return this.provider.send("eth_accounts", []).then((accounts) => {
if (accounts.length <= this._index) {
logger.throwError("unknown account #" + this._index, Logger.errors.UNSUPPORTED_OPERATION, {
2019-08-02 09:10:58 +03:00
operation: "getAddress"
});
2019-05-15 01:48:48 +03:00
}
return this.provider.formatter.address(accounts[this._index]);
2019-05-15 01:48:48 +03:00
});
}
sendUncheckedTransaction(transaction) {
transaction = shallowCopy(transaction);
2020-06-03 10:47:17 +03:00
const fromAddress = this.getAddress().then((address) => {
2019-05-15 01:48:48 +03:00
if (address) {
address = address.toLowerCase();
}
return address;
});
// The JSON-RPC for eth_sendTransaction uses 90000 gas; if the user
// wishes to use this, it is easy to specify explicitly, otherwise
// we look it up for them.
if (transaction.gasLimit == null) {
2020-06-03 10:47:17 +03:00
const estimate = shallowCopy(transaction);
2019-05-15 01:48:48 +03:00
estimate.from = fromAddress;
transaction.gasLimit = this.provider.estimateGas(estimate);
}
2021-06-26 08:55:19 +03:00
if (transaction.to != null) {
transaction.to = Promise.resolve(transaction.to).then((to) => __awaiter(this, void 0, void 0, function* () {
if (to == null) {
return null;
}
const address = yield this.provider.resolveName(to);
if (address == null) {
logger.throwArgumentError("provided ENS name resolves to null", "tx.to", to);
}
return address;
}));
}
2020-06-03 10:47:17 +03:00
return resolveProperties({
tx: resolveProperties(transaction),
sender: fromAddress
}).then(({ tx, sender }) => {
if (tx.from != null) {
if (tx.from.toLowerCase() !== sender) {
logger.throwArgumentError("from address mismatch", "transaction", transaction);
}
}
else {
tx.from = sender;
}
const hexTx = this.provider.constructor.hexlifyTransaction(tx, { from: true });
return this.provider.send("eth_sendTransaction", [hexTx]).then((hash) => {
2019-05-15 01:48:48 +03:00
return hash;
}, (error) => {
2022-08-18 21:48:39 +03:00
if (typeof (error.message) === "string" && error.message.match(/user denied/i)) {
logger.throwError("user rejected transaction", Logger.errors.ACTION_REJECTED, {
action: "sendTransaction",
transaction: tx
});
}
2020-09-16 10:08:36 +03:00
return checkError("sendTransaction", error, hexTx);
2019-05-15 01:48:48 +03:00
});
});
}
signTransaction(transaction) {
return logger.throwError("signing transactions is unsupported", Logger.errors.UNSUPPORTED_OPERATION, {
2019-05-15 01:48:48 +03:00
operation: "signTransaction"
});
}
sendTransaction(transaction) {
2021-06-11 01:29:05 +03:00
return __awaiter(this, void 0, void 0, function* () {
// This cannot be mined any earlier than any recent block
const blockNumber = yield this.provider._getInternalBlockNumber(100 + 2 * this.provider.pollingInterval);
// Send the transaction
const hash = yield this.sendUncheckedTransaction(transaction);
try {
// Unfortunately, JSON-RPC only provides and opaque transaction hash
// for a response, and we need the actual transaction, so we poll
// for it; it should show up very quickly
return yield poll(() => __awaiter(this, void 0, void 0, function* () {
const tx = yield this.provider.getTransaction(hash);
2019-05-15 01:48:48 +03:00
if (tx === null) {
return undefined;
}
2021-06-11 01:29:05 +03:00
return this.provider._wrapTransaction(tx, hash, blockNumber);
}), { oncePoll: this.provider });
}
catch (error) {
2019-05-15 01:48:48 +03:00
error.transactionHash = hash;
throw error;
2021-06-11 01:29:05 +03:00
}
2019-05-15 01:48:48 +03:00
});
}
signMessage(message) {
2020-10-19 06:19:16 +03:00
return __awaiter(this, void 0, void 0, function* () {
const data = ((typeof (message) === "string") ? toUtf8Bytes(message) : message);
const address = yield this.getAddress();
2022-08-18 21:48:39 +03:00
try {
return yield this.provider.send("personal_sign", [hexlify(data), address.toLowerCase()]);
}
catch (error) {
if (typeof (error.message) === "string" && error.message.match(/user denied/i)) {
logger.throwError("user rejected signing", Logger.errors.ACTION_REJECTED, {
action: "signMessage",
from: address,
message: data
});
}
throw error;
}
2021-10-16 09:29:27 +03:00
});
}
_legacySignMessage(message) {
return __awaiter(this, void 0, void 0, function* () {
const data = ((typeof (message) === "string") ? toUtf8Bytes(message) : message);
const address = yield this.getAddress();
2022-08-18 21:48:39 +03:00
try {
// https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
return yield this.provider.send("eth_sign", [address.toLowerCase(), hexlify(data)]);
}
catch (error) {
if (typeof (error.message) === "string" && error.message.match(/user denied/i)) {
logger.throwError("user rejected signing", Logger.errors.ACTION_REJECTED, {
action: "_legacySignMessage",
from: address,
message: data
});
}
throw error;
}
2020-10-19 06:19:16 +03:00
});
}
_signTypedData(domain, types, value) {
return __awaiter(this, void 0, void 0, function* () {
// Populate any ENS names (in-place)
const populated = yield _TypedDataEncoder.resolveNames(domain, types, value, (name) => {
return this.provider.resolveName(name);
});
2020-10-19 08:27:15 +03:00
const address = yield this.getAddress();
2022-08-18 21:48:39 +03:00
try {
return yield this.provider.send("eth_signTypedData_v4", [
address.toLowerCase(),
JSON.stringify(_TypedDataEncoder.getPayload(populated.domain, types, populated.value))
]);
}
catch (error) {
if (typeof (error.message) === "string" && error.message.match(/user denied/i)) {
logger.throwError("user rejected signing", Logger.errors.ACTION_REJECTED, {
action: "_signTypedData",
from: address,
message: { domain: populated.domain, types, value: populated.value }
});
}
throw error;
}
2019-05-15 01:48:48 +03:00
});
}
unlock(password) {
2020-10-19 08:27:15 +03:00
return __awaiter(this, void 0, void 0, function* () {
const provider = this.provider;
const address = yield this.getAddress();
2019-05-15 01:48:48 +03:00
return provider.send("personal_unlockAccount", [address.toLowerCase(), password, null]);
});
}
}
class UncheckedJsonRpcSigner extends JsonRpcSigner {
sendTransaction(transaction) {
return this.sendUncheckedTransaction(transaction).then((hash) => {
2019-05-15 01:48:48 +03:00
return {
hash: hash,
nonce: null,
gasLimit: null,
gasPrice: null,
data: null,
value: null,
chainId: null,
confirmations: 0,
from: null,
wait: (confirmations) => { return this.provider.waitForTransaction(hash, confirmations); }
2019-05-15 01:48:48 +03:00
};
});
}
}
const allowedTransactionKeys = {
2021-03-30 22:22:45 +03:00
chainId: true, data: true, gasLimit: true, gasPrice: true, nonce: true, to: true, value: true,
2021-06-29 19:25:07 +03:00
type: true, accessList: true,
maxFeePerGas: true, maxPriorityFeePerGas: true
2019-05-15 01:48:48 +03:00
};
export class JsonRpcProvider extends BaseProvider {
constructor(url, network) {
let networkOrReady = network;
// The network is unknown, query the JSON-RPC for it
if (networkOrReady == null) {
networkOrReady = new Promise((resolve, reject) => {
setTimeout(() => {
this.detectNetwork().then((network) => {
resolve(network);
}, (error) => {
reject(error);
});
}, 0);
});
2019-05-15 01:48:48 +03:00
}
super(networkOrReady);
2019-05-15 01:48:48 +03:00
// Default URL
if (!url) {
2020-03-12 21:14:50 +03:00
url = getStatic(this.constructor, "defaultUrl")();
2019-05-15 01:48:48 +03:00
}
if (typeof (url) === "string") {
defineReadOnly(this, "connection", Object.freeze({
2019-05-15 01:48:48 +03:00
url: url
}));
2019-05-15 01:48:48 +03:00
}
else {
defineReadOnly(this, "connection", Object.freeze(shallowCopy(url)));
2019-05-15 01:48:48 +03:00
}
this._nextId = 42;
2019-05-15 01:48:48 +03:00
}
2021-04-20 04:30:28 +03:00
get _cache() {
if (this._eventLoopCache == null) {
this._eventLoopCache = {};
}
return this._eventLoopCache;
}
2020-03-12 21:14:50 +03:00
static defaultUrl() {
2020-04-27 13:31:43 +03:00
return "http:/\/localhost:8545";
2020-03-12 21:14:50 +03:00
}
2020-05-04 00:53:58 +03:00
detectNetwork() {
2021-04-20 04:30:28 +03:00
if (!this._cache["detectNetwork"]) {
this._cache["detectNetwork"] = this._uncachedDetectNetwork();
2021-04-18 05:41:09 +03:00
// Clear this cache at the beginning of the next event loop
setTimeout(() => {
2021-04-20 04:30:28 +03:00
this._cache["detectNetwork"] = null;
2021-04-18 05:41:09 +03:00
}, 0);
}
2021-04-20 04:30:28 +03:00
return this._cache["detectNetwork"];
2021-04-18 05:41:09 +03:00
}
_uncachedDetectNetwork() {
2020-05-04 00:53:58 +03:00
return __awaiter(this, void 0, void 0, function* () {
yield timer(0);
let chainId = null;
try {
chainId = yield this.send("eth_chainId", []);
}
catch (error) {
try {
chainId = yield this.send("net_version", []);
}
catch (error) { }
}
if (chainId != null) {
const getNetwork = getStatic(this.constructor, "getNetwork");
try {
return getNetwork(BigNumber.from(chainId).toNumber());
}
catch (error) {
return logger.throwError("could not detect network", Logger.errors.NETWORK_ERROR, {
chainId: chainId,
2020-06-14 04:39:36 +03:00
event: "invalidNetwork",
2020-05-04 00:53:58 +03:00
serverError: error
});
}
}
2020-06-14 04:39:36 +03:00
return logger.throwError("could not detect network", Logger.errors.NETWORK_ERROR, {
event: "noNetwork"
});
2020-05-04 00:53:58 +03:00
});
}
getSigner(addressOrIndex) {
2019-05-15 01:48:48 +03:00
return new JsonRpcSigner(_constructorGuard, this, addressOrIndex);
}
getUncheckedSigner(addressOrIndex) {
2019-05-15 01:48:48 +03:00
return this.getSigner(addressOrIndex).connectUnchecked();
}
listAccounts() {
return this.send("eth_accounts", []).then((accounts) => {
return accounts.map((a) => this.formatter.address(a));
2019-05-15 01:48:48 +03:00
});
}
send(method, params) {
2020-06-03 10:47:17 +03:00
const request = {
2019-05-15 01:48:48 +03:00
method: method,
params: params,
2019-05-25 01:15:42 +03:00
id: (this._nextId++),
2019-05-15 01:48:48 +03:00
jsonrpc: "2.0"
};
2019-08-02 09:10:58 +03:00
this.emit("debug", {
action: "request",
request: deepCopy(request),
2019-08-02 09:10:58 +03:00
provider: this
});
2021-04-18 05:41:09 +03:00
// We can expand this in the future to any call, but for now these
// are the biggest wins and do not require any serializing parameters.
const cache = (["eth_chainId", "eth_blockNumber"].indexOf(method) >= 0);
2021-04-20 04:30:28 +03:00
if (cache && this._cache[method]) {
return this._cache[method];
2021-04-18 05:41:09 +03:00
}
const result = fetchJson(this.connection, JSON.stringify(request), getResult).then((result) => {
this.emit("debug", {
2019-08-02 09:10:58 +03:00
action: "response",
2019-05-15 01:48:48 +03:00
request: request,
response: result,
provider: this
2019-05-15 01:48:48 +03:00
});
return result;
2020-02-26 13:06:48 +03:00
}, (error) => {
this.emit("debug", {
action: "response",
error: error,
request: request,
provider: this
});
throw error;
2019-05-15 01:48:48 +03:00
});
2021-04-18 05:41:09 +03:00
// Cache the fetch, but clear it on the next event loop
if (cache) {
2021-04-20 04:30:28 +03:00
this._cache[method] = result;
2021-04-18 05:41:09 +03:00
setTimeout(() => {
2021-04-20 04:30:28 +03:00
this._cache[method] = null;
2021-04-18 05:41:09 +03:00
}, 0);
}
return result;
}
2020-03-21 19:48:22 +03:00
prepareRequest(method, params) {
2019-05-15 01:48:48 +03:00
switch (method) {
case "getBlockNumber":
2020-03-21 19:48:22 +03:00
return ["eth_blockNumber", []];
2019-05-15 01:48:48 +03:00
case "getGasPrice":
2020-03-21 19:48:22 +03:00
return ["eth_gasPrice", []];
2019-05-15 01:48:48 +03:00
case "getBalance":
2020-03-21 19:48:22 +03:00
return ["eth_getBalance", [getLowerCase(params.address), params.blockTag]];
2019-05-15 01:48:48 +03:00
case "getTransactionCount":
2020-03-21 19:48:22 +03:00
return ["eth_getTransactionCount", [getLowerCase(params.address), params.blockTag]];
2019-05-15 01:48:48 +03:00
case "getCode":
2020-03-21 19:48:22 +03:00
return ["eth_getCode", [getLowerCase(params.address), params.blockTag]];
2019-05-15 01:48:48 +03:00
case "getStorageAt":
2022-05-21 02:13:03 +03:00
return ["eth_getStorageAt", [getLowerCase(params.address), hexZeroPad(params.position, 32), params.blockTag]];
2019-05-15 01:48:48 +03:00
case "sendTransaction":
2020-03-21 19:48:22 +03:00
return ["eth_sendRawTransaction", [params.signedTransaction]];
2019-05-15 01:48:48 +03:00
case "getBlock":
if (params.blockTag) {
2020-03-21 19:48:22 +03:00
return ["eth_getBlockByNumber", [params.blockTag, !!params.includeTransactions]];
2019-05-15 01:48:48 +03:00
}
else if (params.blockHash) {
2020-03-21 19:48:22 +03:00
return ["eth_getBlockByHash", [params.blockHash, !!params.includeTransactions]];
2019-05-15 01:48:48 +03:00
}
2020-03-21 19:48:22 +03:00
return null;
2019-05-15 01:48:48 +03:00
case "getTransaction":
2020-03-21 19:48:22 +03:00
return ["eth_getTransactionByHash", [params.transactionHash]];
2019-05-15 01:48:48 +03:00
case "getTransactionReceipt":
2020-03-21 19:48:22 +03:00
return ["eth_getTransactionReceipt", [params.transactionHash]];
2019-11-20 12:57:38 +03:00
case "call": {
const hexlifyTransaction = getStatic(this.constructor, "hexlifyTransaction");
2020-03-21 19:48:22 +03:00
return ["eth_call", [hexlifyTransaction(params.transaction, { from: true }), params.blockTag]];
2019-11-20 12:57:38 +03:00
}
case "estimateGas": {
const hexlifyTransaction = getStatic(this.constructor, "hexlifyTransaction");
2020-03-21 19:48:22 +03:00
return ["eth_estimateGas", [hexlifyTransaction(params.transaction, { from: true })]];
2019-11-20 12:57:38 +03:00
}
2019-05-15 01:48:48 +03:00
case "getLogs":
if (params.filter && params.filter.address != null) {
params.filter.address = getLowerCase(params.filter.address);
}
2020-03-21 19:48:22 +03:00
return ["eth_getLogs", [params.filter]];
2019-05-15 01:48:48 +03:00
default:
break;
}
2020-03-21 19:48:22 +03:00
return null;
}
perform(method, params) {
2020-09-11 09:10:58 +03:00
return __awaiter(this, void 0, void 0, function* () {
2021-07-30 06:30:17 +03:00
// Legacy networks do not like the type field being passed along (which
// is fair), so we delete type if it is 0 and a non-EIP-1559 network
if (method === "call" || method === "estimateGas") {
const tx = params.transaction;
if (tx && tx.type != null && BigNumber.from(tx.type).isZero()) {
2022-05-01 09:11:22 +03:00
// If there are no EIP-1559 properties, it might be non-EIP-1559
2021-07-30 06:30:17 +03:00
if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) {
const feeData = yield this.getFeeData();
if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) {
// Network doesn't know about EIP-1559 (and hence type)
params = shallowCopy(params);
params.transaction = shallowCopy(tx);
delete params.transaction.type;
}
}
}
}
2020-09-11 09:10:58 +03:00
const args = this.prepareRequest(method, params);
if (args == null) {
logger.throwError(method + " not implemented", Logger.errors.NOT_IMPLEMENTED, { operation: method });
}
try {
return yield this.send(args[0], args[1]);
}
catch (error) {
2020-09-16 10:08:36 +03:00
return checkError(method, error, params);
2020-09-11 09:10:58 +03:00
}
});
}
2020-03-12 21:14:50 +03:00
_startEvent(event) {
if (event.tag === "pending") {
this._startPending();
}
super._startEvent(event);
}
_startPending() {
2019-05-15 01:48:48 +03:00
if (this._pendingFilter != null) {
return;
}
2020-06-03 10:47:17 +03:00
const self = this;
const pendingFilter = this.send("eth_newPendingTransactionFilter", []);
2019-05-15 01:48:48 +03:00
this._pendingFilter = pendingFilter;
pendingFilter.then(function (filterId) {
function poll() {
self.send("eth_getFilterChanges", [filterId]).then(function (hashes) {
if (self._pendingFilter != pendingFilter) {
return null;
}
let seq = Promise.resolve();
2019-05-15 01:48:48 +03:00
hashes.forEach(function (hash) {
// @TODO: This should be garbage collected at some point... How? When?
self._emitted["t:" + hash.toLowerCase()] = "pending";
seq = seq.then(function () {
return self.getTransaction(hash).then(function (tx) {
self.emit("pending", tx);
return null;
});
});
});
return seq.then(function () {
return timer(1000);
});
}).then(function () {
if (self._pendingFilter != pendingFilter) {
self.send("eth_uninstallFilter", [filterId]);
return;
}
setTimeout(function () { poll(); }, 0);
return null;
}).catch((error) => { });
2019-05-15 01:48:48 +03:00
}
poll();
return filterId;
}).catch((error) => { });
}
2020-03-12 21:14:50 +03:00
_stopEvent(event) {
if (event.tag === "pending" && this.listenerCount("pending") === 0) {
this._pendingFilter = null;
}
super._stopEvent(event);
}
2019-05-15 01:48:48 +03:00
// Convert an ethers.js transaction into a JSON-RPC transaction
// - gasLimit => gas
// - All values hexlified
// - All numeric values zero-striped
2020-03-21 19:48:22 +03:00
// - All addresses are lowercased
2019-05-15 01:48:48 +03:00
// NOTE: This allows a TransactionRequest, but all values should be resolved
// before this is called
2020-03-21 19:48:22 +03:00
// @TODO: This will likely be removed in future versions and prepareRequest
// will be the preferred method for this.
static hexlifyTransaction(transaction, allowExtra) {
2019-05-15 01:48:48 +03:00
// Check only allowed properties are given
2019-11-20 12:57:38 +03:00
const allowed = shallowCopy(allowedTransactionKeys);
2019-05-15 01:48:48 +03:00
if (allowExtra) {
2020-06-03 10:47:17 +03:00
for (const key in allowExtra) {
2019-05-15 01:48:48 +03:00
if (allowExtra[key]) {
allowed[key] = true;
}
}
}
checkProperties(transaction, allowed);
2019-11-20 12:57:38 +03:00
const result = {};
2022-03-09 10:56:08 +03:00
// JSON-RPC now requires numeric values to be "quantity" values
["chainId", "gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach(function (key) {
2019-05-15 01:48:48 +03:00
if (transaction[key] == null) {
return;
}
2022-05-01 09:11:22 +03:00
const value = hexValue(BigNumber.from(transaction[key]));
2019-05-15 01:48:48 +03:00
if (key === "gasLimit") {
key = "gas";
}
result[key] = value;
});
["from", "to", "data"].forEach(function (key) {
if (transaction[key] == null) {
return;
}
result[key] = hexlify(transaction[key]);
2019-05-15 01:48:48 +03:00
});
2021-03-30 22:22:45 +03:00
if (transaction.accessList) {
result["accessList"] = accessListify(transaction.accessList);
}
2019-05-15 01:48:48 +03:00
return result;
}
}
2020-07-13 15:03:56 +03:00
//# sourceMappingURL=json-rpc-provider.js.map