2019-05-14 18:25:46 -04:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
// See: https://github.com/ethereum/wiki/wiki/JSON-RPC
|
|
|
|
|
|
|
|
import { Provider, TransactionRequest, TransactionResponse } from "@ethersproject/abstract-provider";
|
2020-10-18 21:52:25 -04:00
|
|
|
import { Signer, TypedDataDomain, TypedDataField, TypedDataSigner } from "@ethersproject/abstract-signer";
|
2019-05-14 18:25:46 -04:00
|
|
|
import { BigNumber } from "@ethersproject/bignumber";
|
2020-11-22 17:43:32 -05:00
|
|
|
import { Bytes, hexlify, hexValue, isHexString } from "@ethersproject/bytes";
|
2020-10-18 21:52:25 -04:00
|
|
|
import { _TypedDataEncoder } from "@ethersproject/hash";
|
2019-11-01 23:51:08 +09:00
|
|
|
import { Network, Networkish } from "@ethersproject/networks";
|
2020-06-01 04:46:37 -04:00
|
|
|
import { checkProperties, deepCopy, Deferrable, defineReadOnly, getStatic, resolveProperties, shallowCopy } from "@ethersproject/properties";
|
2019-05-14 18:25:46 -04:00
|
|
|
import { toUtf8Bytes } from "@ethersproject/strings";
|
2021-03-26 16:16:56 -04:00
|
|
|
import { AccessList, accessListify } from "@ethersproject/transactions";
|
2019-05-14 18:25:46 -04:00
|
|
|
import { ConnectionInfo, fetchJson, poll } from "@ethersproject/web";
|
|
|
|
|
2019-08-01 18:04:06 -04:00
|
|
|
import { Logger } from "@ethersproject/logger";
|
|
|
|
import { version } from "./_version";
|
|
|
|
const logger = new Logger(version);
|
|
|
|
|
2020-03-12 18:53:34 +01:00
|
|
|
import { BaseProvider, Event } from "./base-provider";
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
|
2020-09-16 02:19:28 -04:00
|
|
|
const errorGas = [ "call", "estimateGas" ];
|
2020-09-11 01:10:15 -04:00
|
|
|
|
2020-11-22 17:43:32 -05:00
|
|
|
function checkError(method: string, error: any, params: any): any {
|
|
|
|
// Undo the "convenience" some nodes are attempting to prevent backwards
|
|
|
|
// incompatibility; maybe for v6 consider forwarding reverts as errors
|
|
|
|
if (method === "call" && error.code === Logger.errors.SERVER_ERROR) {
|
|
|
|
const e = error.error;
|
|
|
|
if (e && e.message.match("reverted") && isHexString(e.data)) {
|
|
|
|
return e.data;
|
|
|
|
}
|
2021-06-21 23:25:37 -04:00
|
|
|
|
|
|
|
logger.throwError("missing revert data in call exception", Logger.errors.CALL_EXCEPTION, {
|
|
|
|
error, data: "0x"
|
|
|
|
});
|
2020-11-22 17:43:32 -05:00
|
|
|
}
|
|
|
|
|
2020-09-11 01:10:15 -04: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 02:19:28 -04:00
|
|
|
} else if (typeof(error.body) === "string") {
|
|
|
|
message = error.body;
|
2020-09-11 01:10:15 -04:00
|
|
|
} else if (typeof(error.responseText) === "string") {
|
|
|
|
message = error.responseText;
|
|
|
|
}
|
2020-09-16 02:19:28 -04:00
|
|
|
message = (message || "").toLowerCase();
|
|
|
|
|
|
|
|
const transaction = params.transaction || params.signedTransaction;
|
|
|
|
|
|
|
|
// "insufficient funds for gas * price + value + cost(data)"
|
|
|
|
if (message.match(/insufficient funds/)) {
|
|
|
|
logger.throwError("insufficient funds for intrinsic transaction cost", Logger.errors.INSUFFICIENT_FUNDS, {
|
|
|
|
error, method, transaction
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// "nonce too low"
|
|
|
|
if (message.match(/nonce too low/)) {
|
|
|
|
logger.throwError("nonce has already been used", Logger.errors.NONCE_EXPIRED, {
|
|
|
|
error, method, transaction
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// "replacement transaction underpriced"
|
|
|
|
if (message.match(/replacement transaction underpriced/)) {
|
|
|
|
logger.throwError("replacement fee too low", Logger.errors.REPLACEMENT_UNDERPRICED, {
|
|
|
|
error, method, transaction
|
|
|
|
});
|
|
|
|
}
|
2021-04-17 18:10:27 -04:00
|
|
|
|
|
|
|
// "replacement transaction underpriced"
|
|
|
|
if (message.match(/only replay-protected/)) {
|
|
|
|
logger.throwError("legacy pre-eip-155 transactions not supported", Logger.errors.UNSUPPORTED_OPERATION, {
|
|
|
|
error, method, transaction
|
|
|
|
});
|
|
|
|
}
|
2020-09-16 02:19:28 -04: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 01:10:15 -04:00
|
|
|
}
|
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
function timer(timeout: number): Promise<any> {
|
|
|
|
return new Promise(function(resolve) {
|
2020-05-03 17:32:16 -04:00
|
|
|
setTimeout(resolve, timeout);
|
2019-05-14 18:25:46 -04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function getResult(payload: { error?: { code?: number, data?: any, message?: string }, result?: any }): any {
|
|
|
|
if (payload.error) {
|
|
|
|
// @TODO: not any
|
2020-06-03 03:17:42 -04:00
|
|
|
const error: any = new Error(payload.error.message);
|
2019-05-14 18:25:46 -04:00
|
|
|
error.code = payload.error.code;
|
|
|
|
error.data = payload.error.data;
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
|
|
|
return payload.result;
|
|
|
|
}
|
|
|
|
|
|
|
|
function getLowerCase(value: string): string {
|
|
|
|
if (value) { return value.toLowerCase(); }
|
|
|
|
return value;
|
|
|
|
}
|
|
|
|
|
|
|
|
const _constructorGuard = {};
|
|
|
|
|
2020-10-18 21:52:25 -04:00
|
|
|
export class JsonRpcSigner extends Signer implements TypedDataSigner {
|
2019-05-14 18:25:46 -04:00
|
|
|
readonly provider: JsonRpcProvider;
|
|
|
|
_index: number;
|
|
|
|
_address: string;
|
|
|
|
|
|
|
|
constructor(constructorGuard: any, provider: JsonRpcProvider, addressOrIndex?: string | number) {
|
2019-08-01 18:04:06 -04:00
|
|
|
logger.checkNew(new.target, JsonRpcSigner);
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
super();
|
|
|
|
|
|
|
|
if (constructorGuard !== _constructorGuard) {
|
|
|
|
throw new Error("do not call the JsonRpcSigner constructor directly; use provider.getSigner");
|
|
|
|
}
|
|
|
|
|
|
|
|
defineReadOnly(this, "provider", provider);
|
|
|
|
|
|
|
|
if (addressOrIndex == null) { addressOrIndex = 0; }
|
2019-05-30 20:18:21 -04:00
|
|
|
|
|
|
|
if (typeof(addressOrIndex) === "string") {
|
|
|
|
defineReadOnly(this, "_address", this.provider.formatter.address(addressOrIndex));
|
|
|
|
defineReadOnly(this, "_index", null);
|
|
|
|
|
|
|
|
} else if (typeof(addressOrIndex) === "number") {
|
|
|
|
defineReadOnly(this, "_index", addressOrIndex);
|
|
|
|
defineReadOnly(this, "_address", null);
|
|
|
|
|
|
|
|
} else {
|
2019-08-01 18:04:06 -04:00
|
|
|
logger.throwArgumentError("invalid address or index", "addressOrIndex", addressOrIndex);
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
connect(provider: Provider): JsonRpcSigner {
|
2019-08-01 18:04:06 -04:00
|
|
|
return logger.throwError("cannot alter JSON-RPC Signer connection", Logger.errors.UNSUPPORTED_OPERATION, {
|
2019-05-14 18:25:46 -04:00
|
|
|
operation: "connect"
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
connectUnchecked(): JsonRpcSigner {
|
|
|
|
return new UncheckedJsonRpcSigner(_constructorGuard, this.provider, this._address || this._index);
|
|
|
|
}
|
|
|
|
|
|
|
|
getAddress(): Promise<string> {
|
|
|
|
if (this._address) {
|
|
|
|
return Promise.resolve(this._address);
|
|
|
|
}
|
|
|
|
|
|
|
|
return this.provider.send("eth_accounts", []).then((accounts) => {
|
|
|
|
if (accounts.length <= this._index) {
|
2019-08-01 18:04:06 -04:00
|
|
|
logger.throwError("unknown account #" + this._index, Logger.errors.UNSUPPORTED_OPERATION, {
|
|
|
|
operation: "getAddress"
|
|
|
|
});
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
return this.provider.formatter.address(accounts[this._index])
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-06-01 04:46:37 -04:00
|
|
|
sendUncheckedTransaction(transaction: Deferrable<TransactionRequest>): Promise<string> {
|
2019-05-14 18:25:46 -04:00
|
|
|
transaction = shallowCopy(transaction);
|
|
|
|
|
2020-06-03 03:17:42 -04:00
|
|
|
const fromAddress = this.getAddress().then((address) => {
|
2019-05-14 18:25:46 -04: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 03:17:42 -04:00
|
|
|
const estimate = shallowCopy(transaction);
|
2019-05-14 18:25:46 -04:00
|
|
|
estimate.from = fromAddress;
|
|
|
|
transaction.gasLimit = this.provider.estimateGas(estimate);
|
|
|
|
}
|
|
|
|
|
2020-06-03 03:17:42 -04: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 = (<any>this.provider.constructor).hexlifyTransaction(tx, { from: true });
|
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
return this.provider.send("eth_sendTransaction", [ hexTx ]).then((hash) => {
|
|
|
|
return hash;
|
|
|
|
}, (error) => {
|
2020-09-16 02:19:28 -04:00
|
|
|
return checkError("sendTransaction", error, hexTx);
|
2019-05-14 18:25:46 -04:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-06-01 04:46:37 -04:00
|
|
|
signTransaction(transaction: Deferrable<TransactionRequest>): Promise<string> {
|
2019-08-01 18:04:06 -04:00
|
|
|
return logger.throwError("signing transactions is unsupported", Logger.errors.UNSUPPORTED_OPERATION, {
|
2019-05-14 18:25:46 -04:00
|
|
|
operation: "signTransaction"
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-06-10 18:22:02 -04:00
|
|
|
async sendTransaction(transaction: Deferrable<TransactionRequest>): Promise<TransactionResponse> {
|
|
|
|
// This cannot be mined any earlier than any recent block
|
|
|
|
const blockNumber = await this.provider._getInternalBlockNumber(100 + 2 * this.provider.pollingInterval);
|
|
|
|
|
|
|
|
// Send the transaction
|
|
|
|
const hash = await 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 await poll(async () => {
|
|
|
|
const tx = await this.provider.getTransaction(hash);
|
|
|
|
if (tx === null) { return undefined; }
|
|
|
|
return this.provider._wrapTransaction(tx, hash, blockNumber);
|
|
|
|
}, { oncePoll: this.provider });
|
|
|
|
} catch (error) {
|
|
|
|
(<any>error).transactionHash = hash;
|
|
|
|
throw error;
|
|
|
|
}
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
|
2020-10-18 21:52:25 -04:00
|
|
|
async signMessage(message: Bytes | string): Promise<string> {
|
2020-06-03 03:17:42 -04:00
|
|
|
const data = ((typeof(message) === "string") ? toUtf8Bytes(message): message);
|
2020-10-18 21:52:25 -04:00
|
|
|
const address = await this.getAddress();
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2020-10-18 21:52:25 -04:00
|
|
|
// https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
|
|
|
|
return await this.provider.send("eth_sign", [ address.toLowerCase(), hexlify(data) ]);
|
|
|
|
}
|
|
|
|
|
|
|
|
async _signTypedData(domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>): Promise<string> {
|
|
|
|
// Populate any ENS names (in-place)
|
|
|
|
const populated = await _TypedDataEncoder.resolveNames(domain, types, value, (name: string) => {
|
|
|
|
return this.provider.resolveName(name);
|
2019-05-14 18:25:46 -04:00
|
|
|
});
|
2020-10-18 21:52:25 -04:00
|
|
|
|
2020-10-19 01:17:36 -04:00
|
|
|
const address = await this.getAddress();
|
|
|
|
|
2020-10-18 21:52:25 -04:00
|
|
|
return await this.provider.send("eth_signTypedData_v4", [
|
2020-10-19 01:17:36 -04:00
|
|
|
address.toLowerCase(),
|
|
|
|
JSON.stringify(_TypedDataEncoder.getPayload(populated.domain, types, populated.value))
|
2020-10-18 21:52:25 -04:00
|
|
|
]);
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
|
2020-10-19 01:17:36 -04:00
|
|
|
async unlock(password: string): Promise<boolean> {
|
2020-06-03 03:17:42 -04:00
|
|
|
const provider = this.provider;
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2020-10-19 01:17:36 -04:00
|
|
|
const address = await this.getAddress();
|
|
|
|
|
|
|
|
return provider.send("personal_unlockAccount", [ address.toLowerCase(), password, null ]);
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class UncheckedJsonRpcSigner extends JsonRpcSigner {
|
2020-06-01 04:46:37 -04:00
|
|
|
sendTransaction(transaction: Deferrable<TransactionRequest>): Promise<TransactionResponse> {
|
2019-05-14 18:25:46 -04:00
|
|
|
return this.sendUncheckedTransaction(transaction).then((hash) => {
|
|
|
|
return <TransactionResponse>{
|
|
|
|
hash: hash,
|
|
|
|
nonce: null,
|
|
|
|
gasLimit: null,
|
|
|
|
gasPrice: null,
|
|
|
|
data: null,
|
|
|
|
value: null,
|
|
|
|
chainId: null,
|
|
|
|
confirmations: 0,
|
|
|
|
from: null,
|
|
|
|
wait: (confirmations?: number) => { return this.provider.waitForTransaction(hash, confirmations); }
|
|
|
|
};
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const allowedTransactionKeys: { [ key: string ]: boolean } = {
|
2021-03-26 16:16:56 -04:00
|
|
|
chainId: true, data: true, gasLimit: true, gasPrice:true, nonce: true, to: true, value: true,
|
|
|
|
type: true, accessList: true
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
export class JsonRpcProvider extends BaseProvider {
|
|
|
|
readonly connection: ConnectionInfo;
|
|
|
|
|
|
|
|
_pendingFilter: Promise<number>;
|
2019-05-24 15:31:30 -04:00
|
|
|
_nextId: number;
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2021-04-02 03:45:47 -04:00
|
|
|
// During any given event loop, the results for a given call will
|
|
|
|
// all be the same, so we can dedup the calls to save requests and
|
|
|
|
// bandwidth. @TODO: Try out generalizing this against send?
|
|
|
|
_eventLoopCache: Record<string, Promise<any>>;
|
2021-04-19 20:56:18 -04:00
|
|
|
get _cache(): Record<string, Promise<any>> {
|
|
|
|
if (this._eventLoopCache == null) {
|
|
|
|
this._eventLoopCache = { };
|
|
|
|
}
|
|
|
|
return this._eventLoopCache;
|
|
|
|
}
|
2021-04-02 03:45:47 -04:00
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
constructor(url?: ConnectionInfo | string, network?: Networkish) {
|
2019-08-01 18:04:06 -04:00
|
|
|
logger.checkNew(new.target, JsonRpcProvider);
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2020-05-08 15:12:02 -04:00
|
|
|
let networkOrReady: Networkish | Promise<Network> = 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-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
|
2020-05-08 15:12:02 -04:00
|
|
|
super(networkOrReady);
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
// Default URL
|
2020-03-12 18:53:34 +01:00
|
|
|
if (!url) { url = getStatic<() => string>(this.constructor, "defaultUrl")(); }
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
if (typeof(url) === "string") {
|
2020-05-08 15:12:02 -04:00
|
|
|
defineReadOnly(this, "connection",Object.freeze({
|
2019-05-14 18:25:46 -04:00
|
|
|
url: url
|
2020-05-08 15:12:02 -04:00
|
|
|
}));
|
2019-05-14 18:25:46 -04:00
|
|
|
} else {
|
2020-05-08 15:12:02 -04:00
|
|
|
defineReadOnly(this, "connection", Object.freeze(shallowCopy(url)));
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
|
2019-05-24 15:31:30 -04:00
|
|
|
this._nextId = 42;
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
|
2020-03-12 18:53:34 +01:00
|
|
|
static defaultUrl(): string {
|
2020-04-27 06:15:44 -04:00
|
|
|
return "http:/\/localhost:8545";
|
2020-03-12 18:53:34 +01:00
|
|
|
}
|
|
|
|
|
2021-04-02 03:45:47 -04:00
|
|
|
detectNetwork(): Promise<Network> {
|
2021-04-19 20:56:18 -04:00
|
|
|
if (!this._cache["detectNetwork"]) {
|
|
|
|
this._cache["detectNetwork"] = this._uncachedDetectNetwork();
|
2021-04-02 03:45:47 -04:00
|
|
|
|
|
|
|
// Clear this cache at the beginning of the next event loop
|
|
|
|
setTimeout(() => {
|
2021-04-19 20:56:18 -04:00
|
|
|
this._cache["detectNetwork"] = null;
|
2021-04-02 03:45:47 -04:00
|
|
|
}, 0);
|
|
|
|
}
|
2021-04-19 20:56:18 -04:00
|
|
|
return this._cache["detectNetwork"];
|
2021-04-02 03:45:47 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
async _uncachedDetectNetwork(): Promise<Network> {
|
2020-05-03 17:32:16 -04:00
|
|
|
await timer(0);
|
|
|
|
|
|
|
|
let chainId = null;
|
|
|
|
try {
|
|
|
|
chainId = await this.send("eth_chainId", [ ]);
|
|
|
|
} catch (error) {
|
|
|
|
try {
|
|
|
|
chainId = await this.send("net_version", [ ]);
|
|
|
|
} catch (error) { }
|
|
|
|
}
|
|
|
|
|
|
|
|
if (chainId != null) {
|
|
|
|
const getNetwork = getStatic<(network: Networkish) => Network>(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-13 21:26:50 -04:00
|
|
|
event: "invalidNetwork",
|
2020-05-03 17:32:16 -04:00
|
|
|
serverError: error
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-13 21:26:50 -04:00
|
|
|
return logger.throwError("could not detect network", Logger.errors.NETWORK_ERROR, {
|
|
|
|
event: "noNetwork"
|
|
|
|
});
|
2020-05-03 17:32:16 -04:00
|
|
|
}
|
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
getSigner(addressOrIndex?: string | number): JsonRpcSigner {
|
|
|
|
return new JsonRpcSigner(_constructorGuard, this, addressOrIndex);
|
|
|
|
}
|
|
|
|
|
|
|
|
getUncheckedSigner(addressOrIndex?: string | number): UncheckedJsonRpcSigner {
|
|
|
|
return this.getSigner(addressOrIndex).connectUnchecked();
|
|
|
|
}
|
|
|
|
|
|
|
|
listAccounts(): Promise<Array<string>> {
|
|
|
|
return this.send("eth_accounts", []).then((accounts: Array<string>) => {
|
|
|
|
return accounts.map((a) => this.formatter.address(a));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-02-10 15:39:38 -05:00
|
|
|
send(method: string, params: Array<any>): Promise<any> {
|
2020-06-03 03:17:42 -04:00
|
|
|
const request = {
|
2019-05-14 18:25:46 -04:00
|
|
|
method: method,
|
|
|
|
params: params,
|
2019-05-24 15:31:30 -04:00
|
|
|
id: (this._nextId++),
|
2019-05-14 18:25:46 -04:00
|
|
|
jsonrpc: "2.0"
|
|
|
|
};
|
|
|
|
|
2019-08-01 16:13:35 -04:00
|
|
|
this.emit("debug", {
|
|
|
|
action: "request",
|
|
|
|
request: deepCopy(request),
|
|
|
|
provider: this
|
|
|
|
});
|
|
|
|
|
2021-04-02 03:45:47 -04: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-19 20:56:18 -04:00
|
|
|
if (cache && this._cache[method]) {
|
|
|
|
return this._cache[method];
|
2021-04-02 03:45:47 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
const result = fetchJson(this.connection, JSON.stringify(request), getResult).then((result) => {
|
2019-05-14 18:25:46 -04:00
|
|
|
this.emit("debug", {
|
2019-08-01 16:13:35 -04:00
|
|
|
action: "response",
|
2019-05-14 18:25:46 -04:00
|
|
|
request: request,
|
|
|
|
response: result,
|
|
|
|
provider: this
|
|
|
|
});
|
2019-08-21 01:45:06 -04:00
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
return result;
|
2020-02-25 14:51:32 -05:00
|
|
|
|
|
|
|
}, (error) => {
|
|
|
|
this.emit("debug", {
|
|
|
|
action: "response",
|
|
|
|
error: error,
|
|
|
|
request: request,
|
|
|
|
provider: this
|
|
|
|
});
|
|
|
|
|
|
|
|
throw error;
|
2019-05-14 18:25:46 -04:00
|
|
|
});
|
2021-04-02 03:45:47 -04:00
|
|
|
|
|
|
|
// Cache the fetch, but clear it on the next event loop
|
|
|
|
if (cache) {
|
2021-04-19 20:56:18 -04:00
|
|
|
this._cache[method] = result;
|
2021-04-02 03:45:47 -04:00
|
|
|
setTimeout(() => {
|
2021-04-19 20:56:18 -04:00
|
|
|
this._cache[method] = null;
|
2021-04-02 03:45:47 -04:00
|
|
|
}, 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
|
2020-03-17 14:00:13 -04:00
|
|
|
prepareRequest(method: string, params: any): [ string, Array<any> ] {
|
2019-05-14 18:25:46 -04:00
|
|
|
switch (method) {
|
|
|
|
case "getBlockNumber":
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_blockNumber", [] ];
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
case "getGasPrice":
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_gasPrice", [] ];
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
case "getBalance":
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_getBalance", [ getLowerCase(params.address), params.blockTag ] ];
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
case "getTransactionCount":
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_getTransactionCount", [ getLowerCase(params.address), params.blockTag ] ];
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
case "getCode":
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_getCode", [ getLowerCase(params.address), params.blockTag ] ];
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
case "getStorageAt":
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_getStorageAt", [ getLowerCase(params.address), params.position, params.blockTag ] ];
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
case "sendTransaction":
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_sendRawTransaction", [ params.signedTransaction ] ]
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
case "getBlock":
|
|
|
|
if (params.blockTag) {
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_getBlockByNumber", [ params.blockTag, !!params.includeTransactions ] ];
|
2019-05-14 18:25:46 -04:00
|
|
|
} else if (params.blockHash) {
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_getBlockByHash", [ params.blockHash, !!params.includeTransactions ] ];
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
2020-03-17 14:00:13 -04:00
|
|
|
return null;
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
case "getTransaction":
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_getTransactionByHash", [ params.transactionHash ] ];
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
case "getTransactionReceipt":
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_getTransactionReceipt", [ params.transactionHash ] ];
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2019-11-01 23:51:08 +09:00
|
|
|
case "call": {
|
|
|
|
const hexlifyTransaction = getStatic<(t: TransactionRequest, a?: { [key: string]: boolean }) => { [key: string]: string }>(this.constructor, "hexlifyTransaction");
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_call", [ hexlifyTransaction(params.transaction, { from: true }), params.blockTag ] ];
|
2019-11-01 23:51:08 +09:00
|
|
|
}
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2019-11-01 23:51:08 +09:00
|
|
|
case "estimateGas": {
|
|
|
|
const hexlifyTransaction = getStatic<(t: TransactionRequest, a?: { [key: string]: boolean }) => { [key: string]: string }>(this.constructor, "hexlifyTransaction");
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_estimateGas", [ hexlifyTransaction(params.transaction, { from: true }) ] ];
|
2019-11-01 23:51:08 +09:00
|
|
|
}
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
case "getLogs":
|
|
|
|
if (params.filter && params.filter.address != null) {
|
|
|
|
params.filter.address = getLowerCase(params.filter.address);
|
|
|
|
}
|
2020-03-17 14:00:13 -04:00
|
|
|
return [ "eth_getLogs", [ params.filter ] ];
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
default:
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2020-03-17 14:00:13 -04:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2020-09-11 01:10:15 -04:00
|
|
|
async perform(method: string, params: any): Promise<any> {
|
2020-03-17 14:00:13 -04:00
|
|
|
const args = this.prepareRequest(method, params);
|
|
|
|
|
|
|
|
if (args == null) {
|
|
|
|
logger.throwError(method + " not implemented", Logger.errors.NOT_IMPLEMENTED, { operation: method });
|
|
|
|
}
|
2020-09-11 01:10:15 -04:00
|
|
|
try {
|
|
|
|
return await this.send(args[0], args[1])
|
|
|
|
} catch (error) {
|
2020-09-16 02:19:28 -04:00
|
|
|
return checkError(method, error, params);
|
2020-09-11 01:10:15 -04:00
|
|
|
}
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
|
2020-03-12 18:53:34 +01:00
|
|
|
_startEvent(event: Event): void {
|
|
|
|
if (event.tag === "pending") { this._startPending(); }
|
|
|
|
super._startEvent(event);
|
|
|
|
}
|
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
_startPending(): void {
|
|
|
|
if (this._pendingFilter != null) { return; }
|
2020-06-03 03:17:42 -04:00
|
|
|
const self = this;
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2020-06-03 03:17:42 -04:00
|
|
|
const pendingFilter: Promise<number> = this.send("eth_newPendingTransactionFilter", []);
|
2019-05-14 18:25:46 -04:00
|
|
|
this._pendingFilter = pendingFilter;
|
|
|
|
|
|
|
|
pendingFilter.then(function(filterId) {
|
|
|
|
function poll() {
|
|
|
|
self.send("eth_getFilterChanges", [ filterId ]).then(function(hashes: Array<string>) {
|
|
|
|
if (self._pendingFilter != pendingFilter) { return null; }
|
|
|
|
|
|
|
|
let seq = Promise.resolve();
|
|
|
|
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: Error) => { });
|
|
|
|
}
|
|
|
|
poll();
|
|
|
|
|
|
|
|
return filterId;
|
|
|
|
}).catch((error: Error) => { });
|
|
|
|
}
|
|
|
|
|
2020-03-12 18:53:34 +01:00
|
|
|
_stopEvent(event: Event): void {
|
|
|
|
if (event.tag === "pending" && this.listenerCount("pending") === 0) {
|
|
|
|
this._pendingFilter = null;
|
|
|
|
}
|
|
|
|
super._stopEvent(event);
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
|
2020-03-12 18:53:34 +01:00
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
// Convert an ethers.js transaction into a JSON-RPC transaction
|
|
|
|
// - gasLimit => gas
|
|
|
|
// - All values hexlified
|
|
|
|
// - All numeric values zero-striped
|
2020-03-17 14:00:13 -04:00
|
|
|
// - All addresses are lowercased
|
2019-05-14 18:25:46 -04:00
|
|
|
// NOTE: This allows a TransactionRequest, but all values should be resolved
|
|
|
|
// before this is called
|
2020-03-17 14:00:13 -04:00
|
|
|
// @TODO: This will likely be removed in future versions and prepareRequest
|
|
|
|
// will be the preferred method for this.
|
2021-03-26 16:16:56 -04:00
|
|
|
static hexlifyTransaction(transaction: TransactionRequest, allowExtra?: { [key: string]: boolean }): { [key: string]: string | AccessList } {
|
2019-05-14 18:25:46 -04:00
|
|
|
// Check only allowed properties are given
|
2019-11-01 23:51:08 +09:00
|
|
|
const allowed = shallowCopy(allowedTransactionKeys);
|
2019-05-14 18:25:46 -04:00
|
|
|
if (allowExtra) {
|
2020-06-03 03:17:42 -04:00
|
|
|
for (const key in allowExtra) {
|
2019-05-14 18:25:46 -04:00
|
|
|
if (allowExtra[key]) { allowed[key] = true; }
|
|
|
|
}
|
|
|
|
}
|
2021-03-26 16:16:56 -04:00
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
checkProperties(transaction, allowed);
|
|
|
|
|
2021-03-26 16:16:56 -04:00
|
|
|
const result: { [key: string]: string | AccessList } = {};
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
// Some nodes (INFURA ropsten; INFURA mainnet is fine) do not like leading zeros.
|
2021-05-30 17:47:04 -04:00
|
|
|
["gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach(function(key) {
|
2019-05-14 18:25:46 -04:00
|
|
|
if ((<any>transaction)[key] == null) { return; }
|
2019-11-01 23:51:08 +09:00
|
|
|
const value = hexValue((<any>transaction)[key]);
|
2019-05-14 18:25:46 -04:00
|
|
|
if (key === "gasLimit") { key = "gas"; }
|
|
|
|
result[key] = value;
|
|
|
|
});
|
|
|
|
|
|
|
|
["from", "to", "data"].forEach(function(key) {
|
|
|
|
if ((<any>transaction)[key] == null) { return; }
|
|
|
|
result[key] = hexlify((<any>transaction)[key]);
|
|
|
|
});
|
|
|
|
|
2021-03-26 16:16:56 -04:00
|
|
|
if ((<any>transaction).accessList) {
|
|
|
|
result["accessList"] = accessListify((<any>transaction).accessList);
|
|
|
|
}
|
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
return result;
|
|
|
|
}
|
|
|
|
}
|