2022-11-30 13:44:47 -05:00
|
|
|
/**
|
|
|
|
* About JSON-RPC...
|
|
|
|
*
|
|
|
|
* @_section: api/providers/jsonrpc:JSON-RPC Provider [about-jsonrpcProvider]
|
|
|
|
*/
|
|
|
|
|
2022-09-05 16:14:43 -04:00
|
|
|
// @TODO:
|
|
|
|
// - Add the batching API
|
|
|
|
|
|
|
|
// https://playground.open-rpc.org/?schemaUrl=https://raw.githubusercontent.com/ethereum/eth1.0-apis/assembled-spec/openrpc.json&uiSchema%5BappBar%5D%5Bui:splitView%5D=true&uiSchema%5BappBar%5D%5Bui:input%5D=false&uiSchema%5BappBar%5D%5Bui:examplesDropdown%5D=false
|
|
|
|
|
2022-11-27 21:58:07 -05:00
|
|
|
import { AbiCoder } from "../abi/index.js";
|
2022-09-17 23:17:52 -04:00
|
|
|
import { getAddress, resolveAddress } from "../address/index.js";
|
2022-09-15 22:30:27 -04:00
|
|
|
import { TypedDataEncoder } from "../hash/index.js";
|
2022-09-05 16:14:43 -04:00
|
|
|
import { accessListify } from "../transaction/index.js";
|
2022-09-08 23:21:08 -04:00
|
|
|
import {
|
2022-09-15 22:56:48 -04:00
|
|
|
defineProperties, getBigInt, hexlify, isHexString, toQuantity, toUtf8Bytes,
|
2022-11-04 18:08:37 -04:00
|
|
|
makeError, assert, assertArgument,
|
2022-09-17 23:17:52 -04:00
|
|
|
FetchRequest, resolveProperties
|
2022-09-08 23:21:08 -04:00
|
|
|
} from "../utils/index.js";
|
2022-09-05 16:14:43 -04:00
|
|
|
|
|
|
|
import { AbstractProvider, UnmanagedSubscriber } from "./abstract-provider.js";
|
|
|
|
import { AbstractSigner } from "./abstract-signer.js";
|
|
|
|
import { Network } from "./network.js";
|
|
|
|
import { FilterIdEventSubscriber, FilterIdPendingSubscriber } from "./subscriber-filterid.js";
|
2023-02-12 22:03:37 -05:00
|
|
|
import { PollingEventSubscriber } from "./subscriber-polling.js";
|
2022-09-05 16:14:43 -04:00
|
|
|
|
|
|
|
import type { TypedDataDomain, TypedDataField } from "../hash/index.js";
|
|
|
|
import type { TransactionLike } from "../transaction/index.js";
|
|
|
|
|
|
|
|
import type { PerformActionRequest, Subscriber, Subscription } from "./abstract-provider.js";
|
|
|
|
import type { Networkish } from "./network.js";
|
|
|
|
import type { Provider, TransactionRequest, TransactionResponse } from "./provider.js";
|
|
|
|
import type { Signer } from "./signer.js";
|
|
|
|
|
2022-11-30 17:19:21 -05:00
|
|
|
type Timer = ReturnType<typeof setTimeout>;
|
|
|
|
|
2022-09-05 16:14:43 -04:00
|
|
|
|
|
|
|
const Primitive = "bigint,boolean,function,number,string,symbol".split(/,/g);
|
|
|
|
//const Methods = "getAddress,then".split(/,/g);
|
|
|
|
function deepCopy<T = any>(value: T): T {
|
|
|
|
if (value == null || Primitive.indexOf(typeof(value)) >= 0) {
|
|
|
|
return value;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Keep any Addressable
|
|
|
|
if (typeof((<any>value).getAddress) === "function") {
|
|
|
|
return value;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Array.isArray(value)) { return <any>(value.map(deepCopy)); }
|
|
|
|
|
|
|
|
if (typeof(value) === "object") {
|
|
|
|
return Object.keys(value).reduce((accum, key) => {
|
|
|
|
accum[key] = (<any>value)[key];
|
|
|
|
return accum;
|
|
|
|
}, <any>{ });
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(`should not happen: ${ value } (${ typeof(value) })`);
|
|
|
|
}
|
|
|
|
|
2022-09-17 23:17:52 -04:00
|
|
|
function stall(duration: number): Promise<void> {
|
|
|
|
return new Promise((resolve) => { setTimeout(resolve, duration); });
|
|
|
|
}
|
|
|
|
|
2022-09-05 16:14:43 -04:00
|
|
|
function getLowerCase(value: string): string {
|
|
|
|
if (value) { return value.toLowerCase(); }
|
|
|
|
return value;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface Pollable {
|
|
|
|
pollingInterval: number;
|
|
|
|
}
|
|
|
|
|
|
|
|
function isPollable(value: any): value is Pollable {
|
|
|
|
return (value && typeof(value.pollingInterval) === "number");
|
|
|
|
}
|
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
|
|
|
* A JSON-RPC payload, which are sent to a JSON-RPC server.
|
|
|
|
*/
|
2022-09-05 16:14:43 -04:00
|
|
|
export type JsonRpcPayload = {
|
|
|
|
id: number;
|
|
|
|
method: string;
|
|
|
|
params: Array<any> | Record<string, any>;
|
|
|
|
jsonrpc: "2.0";
|
|
|
|
};
|
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
|
|
|
* A JSON-RPC result, which are returned on success from a JSON-RPC server.
|
|
|
|
*/
|
2022-09-05 16:14:43 -04:00
|
|
|
export type JsonRpcResult = {
|
|
|
|
id: number;
|
|
|
|
result: any;
|
|
|
|
};
|
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
|
|
|
* A JSON-RPC error, which are returned on failure from a JSON-RPC server.
|
|
|
|
*/
|
2022-09-05 16:14:43 -04:00
|
|
|
export type JsonRpcError = {
|
|
|
|
id: number;
|
|
|
|
error: {
|
|
|
|
code: number;
|
|
|
|
message?: string;
|
|
|
|
data?: any;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-11-30 13:44:47 -05:00
|
|
|
/**
|
|
|
|
* When subscribing to the ``"debug"`` event, the [[Listener]] will
|
|
|
|
* receive this object as the first parameter.
|
|
|
|
*/
|
2022-09-15 22:30:27 -04:00
|
|
|
export type DebugEventJsonRpcApiProvider = {
|
|
|
|
action: "sendRpcPayload",
|
|
|
|
payload: JsonRpcPayload | Array<JsonRpcPayload>
|
|
|
|
} | {
|
|
|
|
action: "receiveRpcResult",
|
|
|
|
result: Array<JsonRpcResult | JsonRpcError>
|
|
|
|
} | {
|
|
|
|
action: "receiveRpcError",
|
|
|
|
error: Error
|
|
|
|
};
|
2022-09-05 16:14:43 -04:00
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
|
|
|
* Options for configuring a [[JsonRpcApiProvider]]. Much of this
|
|
|
|
* is targetted towards sub-classes, which often will not expose
|
|
|
|
* any of these options to their consumers.
|
|
|
|
*
|
2022-11-30 13:44:47 -05:00
|
|
|
* **``polling``** - use the polling strategy is used immediately
|
|
|
|
* for events; otherwise, attempt to use filters and fall back onto
|
|
|
|
* polling (default: ``false``)
|
2022-09-15 22:30:27 -04:00
|
|
|
*
|
2022-11-30 13:44:47 -05:00
|
|
|
* **``staticNetwork``** - do not request chain ID on requests to
|
|
|
|
* validate the underlying chain has not changed (default: ``null``)
|
2022-09-15 22:30:27 -04:00
|
|
|
*
|
|
|
|
* This should **ONLY** be used if it is **certain** that the network
|
|
|
|
* cannot change, such as when using INFURA (since the URL dictates the
|
|
|
|
* network). If the network is assumed static and it does change, this
|
|
|
|
* can have tragic consequences. For example, this **CANNOT** be used
|
|
|
|
* with MetaMask, since the used can select a new network from the
|
|
|
|
* drop-down at any time.
|
|
|
|
*
|
2022-11-30 13:44:47 -05:00
|
|
|
* **``batchStallTime``** - how long (ms) to aggregate requests into a
|
|
|
|
* single batch. ``0`` indicates batching will only encompass the current
|
|
|
|
* event loop. If ``batchMaxCount = 1``, this is ignored. (default: ``10``)
|
2022-09-15 22:30:27 -04:00
|
|
|
*
|
2022-11-30 13:44:47 -05:00
|
|
|
* **``batchMaxSize``** - target maximum size (bytes) to allow per batch
|
|
|
|
* request (default: 1Mb)
|
2022-09-15 22:30:27 -04:00
|
|
|
*
|
2022-11-30 13:44:47 -05:00
|
|
|
* **``batchMaxCount``** - maximum number of requests to allow in a batch.
|
|
|
|
* If ``batchMaxCount = 1``, then batching is disabled. (default: ``100``)
|
2022-09-15 22:30:27 -04:00
|
|
|
*/
|
|
|
|
export type JsonRpcApiProviderOptions = {
|
|
|
|
polling?: boolean;
|
2022-09-05 16:14:43 -04:00
|
|
|
staticNetwork?: null | Network;
|
|
|
|
batchStallTime?: number;
|
|
|
|
batchMaxSize?: number;
|
|
|
|
batchMaxCount?: number;
|
|
|
|
};
|
|
|
|
|
|
|
|
const defaultOptions = {
|
|
|
|
polling: false,
|
|
|
|
staticNetwork: null,
|
|
|
|
|
|
|
|
batchStallTime: 10, // 10ms
|
|
|
|
batchMaxSize: (1 << 20), // 1Mb
|
|
|
|
batchMaxCount: 100 // 100 requests
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface JsonRpcTransactionRequest {
|
|
|
|
from?: string;
|
|
|
|
to?: string;
|
|
|
|
data?: string;
|
|
|
|
|
|
|
|
chainId?: string;
|
|
|
|
type?: string;
|
|
|
|
gas?: string;
|
|
|
|
|
|
|
|
gasPrice?: string;
|
|
|
|
maxFeePerGas?: string;
|
|
|
|
maxPriorityFeePerGas?: string;
|
|
|
|
|
|
|
|
nonce?: string;
|
|
|
|
value?: string;
|
|
|
|
|
|
|
|
accessList?: Array<{ address: string, storageKeys: Array<string> }>;
|
|
|
|
}
|
|
|
|
|
|
|
|
// @TODO: Unchecked Signers
|
|
|
|
|
|
|
|
export class JsonRpcSigner extends AbstractSigner<JsonRpcApiProvider> {
|
|
|
|
address!: string;
|
|
|
|
|
|
|
|
constructor(provider: JsonRpcApiProvider, address: string) {
|
|
|
|
super(provider);
|
2023-02-23 06:20:39 -05:00
|
|
|
address = getAddress(address);
|
2022-09-05 16:14:43 -04:00
|
|
|
defineProperties<JsonRpcSigner>(this, { address });
|
|
|
|
}
|
|
|
|
|
|
|
|
connect(provider: null | Provider): Signer {
|
2022-11-04 18:08:37 -04:00
|
|
|
assert(false, "cannot reconnect JsonRpcSigner", "UNSUPPORTED_OPERATION", {
|
2022-09-05 16:14:43 -04:00
|
|
|
operation: "signer.connect"
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async getAddress(): Promise<string> {
|
|
|
|
return this.address;
|
|
|
|
}
|
|
|
|
|
|
|
|
// JSON-RPC will automatially fill in nonce, etc. so we just check from
|
|
|
|
async populateTransaction(tx: TransactionRequest): Promise<TransactionLike<string>> {
|
|
|
|
return await this.populateCall(tx);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns just the hash of the transaction after sent, which is what
|
|
|
|
// the bare JSON-RPC API does;
|
|
|
|
async sendUncheckedTransaction(_tx: TransactionRequest): Promise<string> {
|
|
|
|
const tx = deepCopy(_tx);
|
|
|
|
|
|
|
|
const promises: Array<Promise<void>> = [];
|
|
|
|
|
|
|
|
// Make sure the from matches the sender
|
|
|
|
if (tx.from) {
|
|
|
|
const _from = tx.from;
|
|
|
|
promises.push((async () => {
|
|
|
|
const from = await resolveAddress(_from, this.provider);
|
2022-10-25 04:06:00 -04:00
|
|
|
assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(),
|
|
|
|
"from address mismatch", "transaction", _tx);
|
2022-09-05 16:14:43 -04:00
|
|
|
tx.from = from;
|
|
|
|
})());
|
|
|
|
} else {
|
|
|
|
tx.from = this.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 (tx.gasLimit == null) {
|
|
|
|
promises.push((async () => {
|
|
|
|
tx.gasLimit = await this.provider.estimateGas({ ...tx, from: this.address});
|
|
|
|
})());
|
|
|
|
}
|
|
|
|
|
|
|
|
// The address may be an ENS name or Addressable
|
|
|
|
if (tx.to != null) {
|
|
|
|
const _to = tx.to;
|
|
|
|
promises.push((async () => {
|
|
|
|
tx.to = await resolveAddress(_to, this.provider);
|
|
|
|
})());
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait until all of our properties are filled in
|
|
|
|
if (promises.length) { await Promise.all(promises); }
|
|
|
|
|
|
|
|
const hexTx = this.provider.getRpcTransaction(tx);
|
|
|
|
|
|
|
|
return this.provider.send("eth_sendTransaction", [ hexTx ]);
|
|
|
|
}
|
|
|
|
|
|
|
|
async sendTransaction(tx: TransactionRequest): Promise<TransactionResponse> {
|
|
|
|
// This cannot be mined any earlier than any recent block
|
|
|
|
const blockNumber = await this.provider.getBlockNumber();
|
|
|
|
|
|
|
|
// Send the transaction
|
|
|
|
const hash = await this.sendUncheckedTransaction(tx);
|
|
|
|
|
|
|
|
// 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 (new Promise((resolve, reject) => {
|
|
|
|
const timeouts = [ 1000, 100 ];
|
|
|
|
const checkTx = async () => {
|
|
|
|
// Try getting the transaction
|
|
|
|
const tx = await this.provider.getTransaction(hash);
|
|
|
|
if (tx != null) {
|
2022-09-17 23:17:52 -04:00
|
|
|
resolve(tx.replaceableTransaction(blockNumber));
|
2022-09-05 16:14:43 -04:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait another 4 seconds
|
|
|
|
this.provider._setTimeout(() => { checkTx(); }, timeouts.pop() || 4000);
|
|
|
|
};
|
|
|
|
checkTx();
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
async signTransaction(_tx: TransactionRequest): Promise<string> {
|
|
|
|
const tx = deepCopy(_tx);
|
|
|
|
|
|
|
|
// Make sure the from matches the sender
|
|
|
|
if (tx.from) {
|
|
|
|
const from = await resolveAddress(tx.from, this.provider);
|
2022-10-25 04:06:00 -04:00
|
|
|
assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(),
|
|
|
|
"from address mismatch", "transaction", _tx);
|
2022-09-05 16:14:43 -04:00
|
|
|
tx.from = from;
|
|
|
|
} else {
|
|
|
|
tx.from = this.address;
|
|
|
|
}
|
|
|
|
|
|
|
|
const hexTx = this.provider.getRpcTransaction(tx);
|
2022-10-20 04:54:26 -04:00
|
|
|
return await this.provider.send("eth_signTransaction", [ hexTx ]);
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async signMessage(_message: string | Uint8Array): Promise<string> {
|
|
|
|
const message = ((typeof(_message) === "string") ? toUtf8Bytes(_message): _message);
|
|
|
|
return await this.provider.send("personal_sign", [
|
|
|
|
hexlify(message), this.address.toLowerCase() ]);
|
|
|
|
}
|
|
|
|
|
|
|
|
async signTypedData(domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, _value: Record<string, any>): Promise<string> {
|
|
|
|
const value = deepCopy(_value);
|
|
|
|
|
|
|
|
// Populate any ENS names (in-place)
|
|
|
|
const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (value: string) => {
|
|
|
|
const address = await resolveAddress(value);
|
2022-10-25 04:06:00 -04:00
|
|
|
assertArgument(address != null, "TypedData does not support null address", "value", value);
|
2022-09-05 16:14:43 -04:00
|
|
|
return address;
|
|
|
|
});
|
|
|
|
|
|
|
|
return await this.provider.send("eth_signTypedData_v4", [
|
|
|
|
this.address.toLowerCase(),
|
|
|
|
JSON.stringify(TypedDataEncoder.getPayload(populated.domain, types, populated.value))
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
|
|
|
async unlock(password: string): Promise<boolean> {
|
|
|
|
return this.provider.send("personal_unlockAccount", [
|
|
|
|
this.address.toLowerCase(), password, null ]);
|
|
|
|
}
|
|
|
|
|
|
|
|
// https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
|
|
|
|
async _legacySignMessage(_message: string | Uint8Array): Promise<string> {
|
|
|
|
const message = ((typeof(_message) === "string") ? toUtf8Bytes(_message): _message);
|
|
|
|
return await this.provider.send("eth_sign", [
|
|
|
|
this.address.toLowerCase(), hexlify(message) ]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type ResolveFunc = (result: JsonRpcResult) => void;
|
|
|
|
type RejectFunc = (error: Error) => void;
|
|
|
|
|
|
|
|
type Payload = { payload: JsonRpcPayload, resolve: ResolveFunc, reject: RejectFunc };
|
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
|
|
|
* The JsonRpcApiProvider is an abstract class and **MUST** be
|
|
|
|
* sub-classed.
|
|
|
|
*
|
|
|
|
* It provides the base for all JSON-RPC-based Provider interaction.
|
2022-09-17 23:17:52 -04:00
|
|
|
*
|
|
|
|
* Sub-classing Notes:
|
|
|
|
* - a sub-class MUST override _send
|
|
|
|
* - a sub-class MUST call the `_start()` method once connected
|
2022-09-15 22:30:27 -04:00
|
|
|
*/
|
2022-11-30 13:44:47 -05:00
|
|
|
export abstract class JsonRpcApiProvider extends AbstractProvider {
|
2022-09-05 16:14:43 -04:00
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
#options: Required<JsonRpcApiProviderOptions>;
|
2022-09-05 16:14:43 -04:00
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
// The next ID to use for the JSON-RPC ID field
|
2022-09-05 16:14:43 -04:00
|
|
|
#nextId: number;
|
2022-09-17 23:17:52 -04:00
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
// Payloads are queued and triggered in batches using the drainTimer
|
|
|
|
#payloads: Array<Payload>;
|
2022-11-30 17:19:21 -05:00
|
|
|
#drainTimer: null | Timer;
|
2022-09-05 16:14:43 -04:00
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
#notReady: null | {
|
|
|
|
promise: Promise<void>,
|
|
|
|
resolve: null | ((v: void) => void)
|
|
|
|
};
|
2022-09-17 23:17:52 -04:00
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
#network: null | Network;
|
2022-09-17 23:17:52 -04:00
|
|
|
|
2022-09-05 16:14:43 -04:00
|
|
|
#scheduleDrain(): void {
|
2022-09-29 21:53:25 -04:00
|
|
|
if (this.#drainTimer) { return; }
|
2022-09-05 16:14:43 -04:00
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
// If we aren't using batching, no hard in sending it immeidately
|
|
|
|
const stallTime = (this._getOption("batchMaxCount") === 1) ? 0: this._getOption("batchStallTime");
|
|
|
|
|
2022-09-05 16:14:43 -04:00
|
|
|
this.#drainTimer = setTimeout(() => {
|
|
|
|
this.#drainTimer = null;
|
|
|
|
|
|
|
|
const payloads = this.#payloads;
|
|
|
|
this.#payloads = [ ];
|
|
|
|
|
|
|
|
while (payloads.length) {
|
|
|
|
|
|
|
|
// Create payload batches that satisfy our batch constraints
|
|
|
|
const batch = [ <Payload>(payloads.shift()) ];
|
|
|
|
while (payloads.length) {
|
|
|
|
if (batch.length === this.#options.batchMaxCount) { break; }
|
|
|
|
batch.push(<Payload>(payloads.shift()));
|
|
|
|
const bytes = JSON.stringify(batch.map((p) => p.payload));
|
|
|
|
if (bytes.length > this.#options.batchMaxSize) {
|
|
|
|
payloads.unshift(<Payload>(batch.pop()));
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Process the result to each payload
|
|
|
|
(async () => {
|
|
|
|
const payload = ((batch.length === 1) ? batch[0].payload: batch.map((p) => p.payload));
|
|
|
|
|
|
|
|
this.emit("debug", { action: "sendRpcPayload", payload });
|
|
|
|
|
|
|
|
try {
|
|
|
|
const result = await this._send(payload);
|
|
|
|
this.emit("debug", { action: "receiveRpcResult", result });
|
|
|
|
|
|
|
|
// Process results in batch order
|
|
|
|
for (const { resolve, reject, payload } of batch) {
|
|
|
|
|
|
|
|
// Find the matching result
|
|
|
|
const resp = result.filter((r) => (r.id === payload.id))[0];
|
|
|
|
|
|
|
|
// No result; the node failed us in unexpected ways
|
|
|
|
if (resp == null) {
|
2023-03-20 14:42:19 -04:00
|
|
|
return reject(makeError("no response from server", "BAD_DATA", { value: result, info: { payload } }));
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// The response is an error
|
|
|
|
if ("error" in resp) {
|
|
|
|
return reject(this.getRpcError(payload, resp));
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// All good; send the result
|
|
|
|
resolve(resp.result);
|
|
|
|
}
|
|
|
|
|
|
|
|
} catch (error: any) {
|
|
|
|
this.emit("debug", { action: "receiveRpcError", error });
|
|
|
|
|
|
|
|
for (const { reject } of batch) {
|
|
|
|
// @TODO: augment the error with the payload
|
|
|
|
reject(error);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})();
|
|
|
|
}
|
2022-09-15 22:30:27 -04:00
|
|
|
}, stallTime);
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
constructor(network?: Networkish, options?: JsonRpcApiProviderOptions) {
|
|
|
|
super(network);
|
|
|
|
|
|
|
|
this.#nextId = 1;
|
|
|
|
this.#options = Object.assign({ }, defaultOptions, options || { });
|
|
|
|
|
|
|
|
this.#payloads = [ ];
|
|
|
|
this.#drainTimer = null;
|
|
|
|
|
|
|
|
this.#network = null;
|
|
|
|
|
|
|
|
{
|
|
|
|
let resolve: null | ((value: void) => void) = null;
|
|
|
|
const promise = new Promise((_resolve: (value: void) => void) => {
|
|
|
|
resolve = _resolve;
|
|
|
|
});
|
|
|
|
this.#notReady = { promise, resolve };
|
|
|
|
}
|
|
|
|
|
|
|
|
// This could be relaxed in the future to just check equivalent networks
|
|
|
|
const staticNetwork = this._getOption("staticNetwork");
|
|
|
|
if (staticNetwork) {
|
2022-10-25 04:06:00 -04:00
|
|
|
assertArgument(staticNetwork === network,
|
|
|
|
"staticNetwork MUST match network object", "options", options);
|
2022-09-29 21:53:25 -04:00
|
|
|
this.#network = staticNetwork;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
2022-09-29 21:53:25 -04:00
|
|
|
* Returns the value associated with the option %%key%%.
|
2022-09-15 22:30:27 -04:00
|
|
|
*
|
2022-09-29 21:53:25 -04:00
|
|
|
* Sub-classes can use this to inquire about configuration options.
|
2022-09-15 22:30:27 -04:00
|
|
|
*/
|
2022-09-29 21:53:25 -04:00
|
|
|
_getOption<K extends keyof JsonRpcApiProviderOptions>(key: K): JsonRpcApiProviderOptions[K] {
|
|
|
|
return this.#options[key];
|
|
|
|
}
|
2022-09-05 16:14:43 -04:00
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
/**
|
|
|
|
* Gets the [[Network]] this provider has committed to. On each call, the network
|
|
|
|
* is detected, and if it has changed, the call will reject.
|
|
|
|
*/
|
|
|
|
get _network(): Network {
|
2022-11-04 18:08:37 -04:00
|
|
|
assert (this.#network, "network is not available yet", "NETWORK_ERROR");
|
2022-09-29 21:53:25 -04:00
|
|
|
return this.#network;
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
|
|
|
* Sends a JSON-RPC %%payload%% (or a batch) to the underlying channel.
|
|
|
|
*
|
|
|
|
* Sub-classes **MUST** override this.
|
|
|
|
*/
|
2022-11-30 13:44:47 -05:00
|
|
|
abstract _send(payload: JsonRpcPayload | Array<JsonRpcPayload>): Promise<Array<JsonRpcResult | JsonRpcError>>;
|
|
|
|
/*
|
|
|
|
{
|
2022-11-04 18:08:37 -04:00
|
|
|
assert(false, "sub-classes must override _send", "UNSUPPORTED_OPERATION", {
|
2022-09-05 16:14:43 -04:00
|
|
|
operation: "jsonRpcApiProvider._send"
|
|
|
|
});
|
|
|
|
}
|
2022-11-30 13:44:47 -05:00
|
|
|
*/
|
2022-09-05 16:14:43 -04:00
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
2022-09-29 21:53:25 -04:00
|
|
|
* Resolves to the non-normalized value by performing %%req%%.
|
2022-09-15 22:30:27 -04:00
|
|
|
*
|
2022-09-29 21:53:25 -04:00
|
|
|
* Sub-classes may override this to modify behavior of actions,
|
|
|
|
* and should generally call ``super._perform`` as a fallback.
|
2022-09-15 22:30:27 -04:00
|
|
|
*/
|
2022-09-29 21:53:25 -04:00
|
|
|
async _perform(req: PerformActionRequest): Promise<any> {
|
|
|
|
// 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 (req.method === "call" || req.method === "estimateGas") {
|
|
|
|
let tx = req.transaction;
|
|
|
|
if (tx && tx.type != null && getBigInt(tx.type)) {
|
|
|
|
// If there are no EIP-1559 properties, it might be non-EIP-a559
|
|
|
|
if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) {
|
|
|
|
const feeData = await this.getFeeData();
|
|
|
|
if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) {
|
|
|
|
// Network doesn't know about EIP-1559 (and hence type)
|
|
|
|
req = Object.assign({ }, req, {
|
|
|
|
transaction: Object.assign({ }, tx, { type: undefined })
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
const request = this.getRpcRequest(req);
|
2022-09-05 16:14:43 -04:00
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
if (request != null) {
|
|
|
|
return await this.send(request.method, request.args);
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
return super._perform(req);
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
2022-11-27 21:58:07 -05:00
|
|
|
/**
|
|
|
|
* Sub-classes may override this; it detects the *actual* network that
|
2022-09-17 23:17:52 -04:00
|
|
|
* we are **currently** connected to.
|
|
|
|
*
|
2022-09-29 21:53:25 -04:00
|
|
|
* Keep in mind that [[send]] may only be used once [[ready]], otherwise the
|
|
|
|
* _send primitive must be used instead.
|
2022-09-17 23:17:52 -04:00
|
|
|
*/
|
2022-09-05 16:14:43 -04:00
|
|
|
async _detectNetwork(): Promise<Network> {
|
|
|
|
const network = this._getOption("staticNetwork");
|
|
|
|
if (network) { return network; }
|
|
|
|
|
2022-09-17 23:17:52 -04:00
|
|
|
// If we are ready, use ``send``, which enabled requests to be batched
|
|
|
|
if (this.ready) {
|
|
|
|
return Network.from(getBigInt(await this.send("eth_chainId", [ ])));
|
|
|
|
}
|
|
|
|
|
|
|
|
// We are not ready yet; use the primitive _send
|
|
|
|
|
|
|
|
const payload: JsonRpcPayload = {
|
|
|
|
id: this.#nextId++, method: "eth_chainId", params: [ ], jsonrpc: "2.0"
|
|
|
|
};
|
|
|
|
|
|
|
|
this.emit("debug", { action: "sendRpcPayload", payload });
|
2022-09-29 21:53:25 -04:00
|
|
|
|
|
|
|
let result: JsonRpcResult | JsonRpcError;
|
|
|
|
try {
|
|
|
|
result = (await this._send(payload))[0];
|
|
|
|
} catch (error) {
|
|
|
|
this.emit("debug", { action: "receiveRpcError", error });
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
2022-09-17 23:17:52 -04:00
|
|
|
this.emit("debug", { action: "receiveRpcResult", result });
|
|
|
|
|
|
|
|
if ("result" in result) {
|
|
|
|
return Network.from(getBigInt(result.result));
|
|
|
|
}
|
|
|
|
|
|
|
|
throw this.getRpcError(payload, result);
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
/**
|
|
|
|
* Sub-classes **MUST** call this. Until [[_start]] has been called, no calls
|
|
|
|
* will be passed to [[_send]] from [[send]]. If it is overridden, then
|
|
|
|
* ``super._start()`` **MUST** be called.
|
|
|
|
*
|
|
|
|
* Calling it multiple times is safe and has no effect.
|
|
|
|
*/
|
|
|
|
_start(): void {
|
|
|
|
if (this.#notReady == null || this.#notReady.resolve == null) { return; }
|
|
|
|
|
|
|
|
this.#notReady.resolve();
|
|
|
|
this.#notReady = null;
|
|
|
|
|
|
|
|
(async () => {
|
|
|
|
|
|
|
|
// Bootstrap the network
|
|
|
|
while (this.#network == null) {
|
|
|
|
try {
|
|
|
|
this.#network = await this._detectNetwork();
|
|
|
|
} catch (error) {
|
|
|
|
console.log("JsonRpcProvider failed to startup; retry in 1s");
|
|
|
|
await stall(1000);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start dispatching requests
|
|
|
|
this.#scheduleDrain();
|
|
|
|
})();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Resolves once the [[_start]] has been called. This can be used in
|
|
|
|
* sub-classes to defer sending data until the connection has been
|
|
|
|
* established.
|
|
|
|
*/
|
|
|
|
async _waitUntilReady(): Promise<void> {
|
|
|
|
if (this.#notReady == null) { return; }
|
|
|
|
return await this.#notReady.promise;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
|
|
|
* Return a Subscriber that will manage the %%sub%%.
|
|
|
|
*
|
2022-09-29 21:53:25 -04:00
|
|
|
* Sub-classes may override this to modify the behavior of
|
2022-09-15 22:30:27 -04:00
|
|
|
* subscription management.
|
|
|
|
*/
|
2022-09-05 16:14:43 -04:00
|
|
|
_getSubscriber(sub: Subscription): Subscriber {
|
2022-11-04 18:08:37 -04:00
|
|
|
|
2022-09-05 16:14:43 -04:00
|
|
|
// Pending Filters aren't availble via polling
|
|
|
|
if (sub.type === "pending") { return new FilterIdPendingSubscriber(this); }
|
|
|
|
|
|
|
|
if (sub.type === "event") {
|
2023-02-12 22:03:37 -05:00
|
|
|
if (this._getOption("polling")) {
|
|
|
|
return new PollingEventSubscriber(this, sub.filter);
|
|
|
|
}
|
2022-09-05 16:14:43 -04:00
|
|
|
return new FilterIdEventSubscriber(this, sub.filter);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Orphaned Logs are handled automatically, by the filter, since
|
|
|
|
// logs with removed are emitted by it
|
|
|
|
if (sub.type === "orphan" && sub.filter.orphan === "drop-log") {
|
|
|
|
return new UnmanagedSubscriber("orphan");
|
|
|
|
}
|
|
|
|
|
|
|
|
return super._getSubscriber(sub);
|
|
|
|
}
|
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
/**
|
|
|
|
* Returns true only if the [[_start]] has been called.
|
|
|
|
*/
|
|
|
|
get ready(): boolean { return this.#notReady == null; }
|
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
|
|
|
* Returns %%tx%% as a normalized JSON-RPC transaction request,
|
|
|
|
* which has all values hexlified and any numeric values converted
|
|
|
|
* to Quantity values.
|
|
|
|
*/
|
2022-09-05 16:14:43 -04:00
|
|
|
getRpcTransaction(tx: TransactionRequest): JsonRpcTransactionRequest {
|
|
|
|
const result: JsonRpcTransactionRequest = {};
|
|
|
|
|
|
|
|
// JSON-RPC now requires numeric values to be "quantity" values
|
|
|
|
["chainId", "gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach((key) => {
|
|
|
|
if ((<any>tx)[key] == null) { return; }
|
|
|
|
let dstKey = key;
|
|
|
|
if (key === "gasLimit") { dstKey = "gas"; }
|
2022-09-08 23:21:08 -04:00
|
|
|
(<any>result)[dstKey] = toQuantity(getBigInt((<any>tx)[key], `tx.${ key }`));
|
2022-09-05 16:14:43 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
// Make sure addresses and data are lowercase
|
|
|
|
["from", "to", "data"].forEach((key) => {
|
|
|
|
if ((<any>tx)[key] == null) { return; }
|
|
|
|
(<any>result)[key] = hexlify((<any>tx)[key]);
|
|
|
|
});
|
|
|
|
|
|
|
|
// Normalize the access list object
|
|
|
|
if (tx.accessList) {
|
|
|
|
result["accessList"] = accessListify(tx.accessList);
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
|
|
|
* Returns the request method and arguments required to perform
|
|
|
|
* %%req%%.
|
|
|
|
*/
|
2022-09-05 16:14:43 -04:00
|
|
|
getRpcRequest(req: PerformActionRequest): null | { method: string, args: Array<any> } {
|
|
|
|
switch (req.method) {
|
|
|
|
case "chainId":
|
|
|
|
return { method: "eth_chainId", args: [ ] };
|
|
|
|
|
|
|
|
case "getBlockNumber":
|
|
|
|
return { method: "eth_blockNumber", args: [ ] };
|
|
|
|
|
|
|
|
case "getGasPrice":
|
|
|
|
return { method: "eth_gasPrice", args: [] };
|
|
|
|
|
|
|
|
case "getBalance":
|
|
|
|
return {
|
|
|
|
method: "eth_getBalance",
|
|
|
|
args: [ getLowerCase(req.address), req.blockTag ]
|
|
|
|
};
|
|
|
|
|
|
|
|
case "getTransactionCount":
|
|
|
|
return {
|
|
|
|
method: "eth_getTransactionCount",
|
|
|
|
args: [ getLowerCase(req.address), req.blockTag ]
|
|
|
|
};
|
|
|
|
|
|
|
|
case "getCode":
|
|
|
|
return {
|
|
|
|
method: "eth_getCode",
|
|
|
|
args: [ getLowerCase(req.address), req.blockTag ]
|
|
|
|
};
|
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
case "getStorage":
|
2022-09-05 16:14:43 -04:00
|
|
|
return {
|
|
|
|
method: "eth_getStorageAt",
|
|
|
|
args: [
|
|
|
|
getLowerCase(req.address),
|
|
|
|
("0x" + req.position.toString(16)),
|
|
|
|
req.blockTag
|
|
|
|
]
|
|
|
|
};
|
|
|
|
|
|
|
|
case "broadcastTransaction":
|
|
|
|
return {
|
|
|
|
method: "eth_sendRawTransaction",
|
|
|
|
args: [ req.signedTransaction ]
|
|
|
|
};
|
|
|
|
|
|
|
|
case "getBlock":
|
|
|
|
if ("blockTag" in req) {
|
|
|
|
return {
|
|
|
|
method: "eth_getBlockByNumber",
|
|
|
|
args: [ req.blockTag, !!req.includeTransactions ]
|
|
|
|
};
|
|
|
|
} else if ("blockHash" in req) {
|
|
|
|
return {
|
|
|
|
method: "eth_getBlockByHash",
|
|
|
|
args: [ req.blockHash, !!req.includeTransactions ]
|
|
|
|
};
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
|
|
|
|
case "getTransaction":
|
|
|
|
return {
|
|
|
|
method: "eth_getTransactionByHash",
|
|
|
|
args: [ req.hash ]
|
|
|
|
};
|
|
|
|
|
|
|
|
case "getTransactionReceipt":
|
|
|
|
return {
|
|
|
|
method: "eth_getTransactionReceipt",
|
|
|
|
args: [ req.hash ]
|
|
|
|
};
|
|
|
|
|
|
|
|
case "call":
|
|
|
|
return {
|
|
|
|
method: "eth_call",
|
|
|
|
args: [ this.getRpcTransaction(req.transaction), req.blockTag ]
|
|
|
|
};
|
|
|
|
|
|
|
|
case "estimateGas": {
|
|
|
|
return {
|
|
|
|
method: "eth_estimateGas",
|
|
|
|
args: [ this.getRpcTransaction(req.transaction) ]
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
case "getLogs":
|
|
|
|
if (req.filter && req.filter.address != null) {
|
|
|
|
if (Array.isArray(req.filter.address)) {
|
|
|
|
req.filter.address = req.filter.address.map(getLowerCase);
|
|
|
|
} else {
|
|
|
|
req.filter.address = getLowerCase(req.filter.address);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return { method: "eth_getLogs", args: [ req.filter ] };
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
|
|
|
* Returns an ethers-style Error for the given JSON-RPC error
|
2022-09-15 22:56:48 -04:00
|
|
|
* %%payload%%, coalescing the various strings and error shapes
|
|
|
|
* that different nodes return, coercing them into a machine-readable
|
|
|
|
* standardized error.
|
2022-09-15 22:30:27 -04:00
|
|
|
*/
|
2022-10-20 04:54:26 -04:00
|
|
|
getRpcError(payload: JsonRpcPayload, _error: JsonRpcError): Error {
|
2022-09-15 22:56:48 -04:00
|
|
|
const { method } = payload;
|
2022-10-20 04:54:26 -04:00
|
|
|
const { error } = _error;
|
2022-09-15 22:56:48 -04:00
|
|
|
|
2023-01-27 18:29:35 -05:00
|
|
|
if (method === "eth_estimateGas" && error.message) {
|
|
|
|
const msg = error.message;
|
|
|
|
if (!msg.match(/revert/i) && msg.match(/insufficient funds/i)) {
|
|
|
|
return makeError("insufficient funds", "INSUFFICIENT_FUNDS", {
|
|
|
|
transaction: ((<any>payload).params[0]),
|
2023-03-20 14:42:19 -04:00
|
|
|
info: { payload, error }
|
2023-01-27 18:29:35 -05:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-20 04:54:26 -04:00
|
|
|
if (method === "eth_call" || method === "eth_estimateGas") {
|
2022-09-05 16:14:43 -04:00
|
|
|
const result = spelunkData(error);
|
2022-10-20 04:54:26 -04:00
|
|
|
|
2022-11-27 21:58:07 -05:00
|
|
|
const e = AbiCoder.getBuiltinCallException(
|
2022-10-20 04:54:26 -04:00
|
|
|
(method === "eth_call") ? "call": "estimateGas",
|
|
|
|
((<any>payload).params[0]),
|
|
|
|
(result ? result.data: null)
|
|
|
|
);
|
|
|
|
e.info = { error, payload };
|
|
|
|
return e;
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
2022-10-20 04:54:26 -04:00
|
|
|
// Only estimateGas and call can return arbitrary contract-defined text, so now we
|
|
|
|
// we can process text safely.
|
|
|
|
|
2022-09-05 16:14:43 -04:00
|
|
|
const message = JSON.stringify(spelunkMessage(error));
|
|
|
|
|
2022-10-20 04:54:26 -04:00
|
|
|
if (typeof(error.message) === "string" && error.message.match(/user denied|ethers-user-denied/i)) {
|
|
|
|
const actionMap: Record<string, "requestAccess" | "sendTransaction" | "signMessage" | "signTransaction" | "signTypedData"> = {
|
|
|
|
eth_sign: "signMessage",
|
|
|
|
personal_sign: "signMessage",
|
|
|
|
eth_signTypedData_v4: "signTypedData",
|
|
|
|
eth_signTransaction: "signTransaction",
|
|
|
|
eth_sendTransaction: "sendTransaction",
|
|
|
|
eth_requestAccounts: "requestAccess",
|
|
|
|
wallet_requestAccounts: "requestAccess",
|
|
|
|
};
|
2022-09-05 16:14:43 -04:00
|
|
|
|
2022-10-20 04:54:26 -04:00
|
|
|
return makeError(`user rejected action`, "ACTION_REJECTED", {
|
|
|
|
action: (actionMap[method] || "unknown") ,
|
|
|
|
reason: "rejected",
|
|
|
|
info: { payload, error }
|
|
|
|
});
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
2022-09-15 22:56:48 -04:00
|
|
|
if (method === "eth_sendRawTransaction" || method === "eth_sendTransaction") {
|
|
|
|
const transaction = <TransactionLike<string>>((<any>payload).params[0]);
|
2022-09-05 16:14:43 -04:00
|
|
|
|
2022-12-30 16:27:46 -05:00
|
|
|
if (message.match(/insufficient funds|base fee exceeds gas limit/i)) {
|
2022-09-15 22:56:48 -04:00
|
|
|
return makeError("insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", {
|
2023-02-12 22:03:37 -05:00
|
|
|
transaction, info: { error }
|
2022-09-15 22:56:48 -04:00
|
|
|
});
|
|
|
|
}
|
2022-09-05 16:14:43 -04:00
|
|
|
|
2022-12-30 16:27:46 -05:00
|
|
|
if (message.match(/nonce/i) && message.match(/too low/i)) {
|
2023-03-20 14:42:19 -04:00
|
|
|
return makeError("nonce has already been used", "NONCE_EXPIRED", { transaction, info: { error } });
|
2022-09-15 22:56:48 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// "replacement transaction underpriced"
|
2022-12-30 16:27:46 -05:00
|
|
|
if (message.match(/replacement transaction/i) && message.match(/underpriced/i)) {
|
2023-03-20 14:42:19 -04:00
|
|
|
return makeError("replacement fee too low", "REPLACEMENT_UNDERPRICED", { transaction, info: { error } });
|
2022-09-15 22:56:48 -04:00
|
|
|
}
|
|
|
|
|
2022-12-30 16:27:46 -05:00
|
|
|
if (message.match(/only replay-protected/i)) {
|
2022-09-15 22:56:48 -04:00
|
|
|
return makeError("legacy pre-eip-155 transactions not supported", "UNSUPPORTED_OPERATION", {
|
2023-03-20 14:42:19 -04:00
|
|
|
operation: method, info: { transaction, info: { error } }
|
2022-09-15 22:56:48 -04:00
|
|
|
});
|
|
|
|
}
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
2022-10-20 04:54:26 -04:00
|
|
|
if (message.match(/the method .* does not exist/i)) {
|
|
|
|
return makeError("unsupported operation", "UNSUPPORTED_OPERATION", {
|
2023-02-12 22:03:37 -05:00
|
|
|
operation: payload.method, info: { error }
|
2022-10-20 04:54:26 -04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-09-15 22:56:48 -04:00
|
|
|
return makeError("could not coalesce error", "UNKNOWN_ERROR", { error });
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
2022-09-29 21:53:25 -04:00
|
|
|
* Requests the %%method%% with %%params%% via the JSON-RPC protocol
|
|
|
|
* over the underlying channel. This can be used to call methods
|
|
|
|
* on the backend that do not have a high-level API within the Provider
|
|
|
|
* API.
|
2022-09-15 22:30:27 -04:00
|
|
|
*
|
2022-09-29 21:53:25 -04:00
|
|
|
* This method queues requests according to the batch constraints
|
|
|
|
* in the options, assigns the request a unique ID.
|
|
|
|
*
|
|
|
|
* **Do NOT override** this method in sub-classes; instead
|
|
|
|
* override [[_send]] or force the options values in the
|
|
|
|
* call to the constructor to modify this method's behavior.
|
2022-09-15 22:30:27 -04:00
|
|
|
*/
|
2022-09-29 21:53:25 -04:00
|
|
|
send(method: string, params: Array<any> | Record<string, any>): Promise<any> {
|
|
|
|
// @TODO: cache chainId?? purge on switch_networks
|
|
|
|
|
|
|
|
const id = this.#nextId++;
|
|
|
|
const promise = new Promise((resolve, reject) => {
|
|
|
|
this.#payloads.push({
|
|
|
|
resolve, reject,
|
|
|
|
payload: { method, params, id, jsonrpc: "2.0" }
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
// If there is not a pending drainTimer, set one
|
|
|
|
this.#scheduleDrain();
|
|
|
|
|
|
|
|
return <Promise<JsonRpcResult>>promise;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Resolves to the [[Signer]] account for %%address%% managed by
|
|
|
|
* the client.
|
|
|
|
*
|
|
|
|
* If the %%address%% is a number, it is used as an index in the
|
|
|
|
* the accounts from [[listAccounts]].
|
|
|
|
*
|
|
|
|
* This can only be used on clients which manage accounts (such as
|
|
|
|
* Geth with imported account or MetaMask).
|
|
|
|
*
|
|
|
|
* Throws if the account doesn't exist.
|
|
|
|
*/
|
2022-11-27 21:58:07 -05:00
|
|
|
async getSigner(address?: number | string): Promise<JsonRpcSigner> {
|
|
|
|
if (address == null) { address = 0; }
|
2022-09-29 21:53:25 -04:00
|
|
|
|
|
|
|
const accountsPromise = this.send("eth_accounts", [ ]);
|
|
|
|
|
|
|
|
// Account index
|
|
|
|
if (typeof(address) === "number") {
|
|
|
|
const accounts = <Array<string>>(await accountsPromise);
|
2022-10-20 04:54:26 -04:00
|
|
|
if (address >= accounts.length) { throw new Error("no such account"); }
|
2022-09-29 21:53:25 -04:00
|
|
|
return new JsonRpcSigner(this, accounts[address]);
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
const { accounts } = await resolveProperties({
|
|
|
|
network: this.getNetwork(),
|
|
|
|
accounts: accountsPromise
|
|
|
|
});
|
2022-09-05 16:14:43 -04:00
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
// Account address
|
|
|
|
address = getAddress(address);
|
|
|
|
for (const account of accounts) {
|
2023-02-23 06:20:39 -05:00
|
|
|
if (getAddress(account) === address) {
|
|
|
|
return new JsonRpcSigner(this, address);
|
2022-09-29 21:53:25 -04:00
|
|
|
}
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
throw new Error("invalid account");
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
2023-03-03 17:59:05 -07:00
|
|
|
|
|
|
|
async listAccounts(): Promise<Array<JsonRpcSigner>> {
|
|
|
|
const accounts: Array<string> = await this.send("eth_accounts", [ ]);
|
|
|
|
return accounts.map((a) => new JsonRpcSigner(this, a));
|
|
|
|
}
|
2022-09-05 16:14:43 -04:00
|
|
|
}
|
|
|
|
|
2022-11-30 13:44:47 -05:00
|
|
|
export abstract class JsonRpcApiPollingProvider extends JsonRpcApiProvider {
|
2022-10-20 04:54:26 -04:00
|
|
|
#pollingInterval: number;
|
|
|
|
constructor(network?: Networkish, options?: JsonRpcApiProviderOptions) {
|
|
|
|
super(network, options);
|
|
|
|
|
|
|
|
this.#pollingInterval = 4000;
|
|
|
|
}
|
|
|
|
|
|
|
|
_getSubscriber(sub: Subscription): Subscriber {
|
|
|
|
const subscriber = super._getSubscriber(sub);
|
|
|
|
if (isPollable(subscriber)) {
|
|
|
|
subscriber.pollingInterval = this.#pollingInterval;
|
|
|
|
}
|
|
|
|
return subscriber;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* The polling interval (default: 4000 ms)
|
|
|
|
*/
|
|
|
|
get pollingInterval(): number { return this.#pollingInterval; }
|
|
|
|
set pollingInterval(value: number) {
|
|
|
|
if (!Number.isInteger(value) || value < 0) { throw new Error("invalid interval"); }
|
|
|
|
this.#pollingInterval = value;
|
|
|
|
this._forEachSubscriber((sub) => {
|
|
|
|
if (isPollable(sub)) {
|
|
|
|
sub.pollingInterval = this.#pollingInterval;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
/**
|
|
|
|
* The JsonRpcProvider is one of the most common Providers,
|
|
|
|
* which performs all operations over HTTP (or HTTPS) requests.
|
|
|
|
*
|
|
|
|
* Events are processed by polling the backend for the current block
|
|
|
|
* number; when it advances, all block-base events are then checked
|
|
|
|
* for updates.
|
|
|
|
*/
|
2022-10-20 04:54:26 -04:00
|
|
|
export class JsonRpcProvider extends JsonRpcApiPollingProvider {
|
2022-09-05 16:14:43 -04:00
|
|
|
#connect: FetchRequest;
|
|
|
|
|
2022-09-15 22:30:27 -04:00
|
|
|
constructor(url?: string | FetchRequest, network?: Networkish, options?: JsonRpcApiProviderOptions) {
|
2022-09-05 16:14:43 -04:00
|
|
|
if (url == null) { url = "http:/\/localhost:8545"; }
|
|
|
|
super(network, options);
|
|
|
|
|
|
|
|
if (typeof(url) === "string") {
|
|
|
|
this.#connect = new FetchRequest(url);
|
|
|
|
} else {
|
|
|
|
this.#connect = url.clone();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-29 21:53:25 -04:00
|
|
|
_getConnection(): FetchRequest {
|
|
|
|
return this.#connect.clone();
|
|
|
|
}
|
|
|
|
|
2022-09-17 23:17:52 -04:00
|
|
|
async send(method: string, params: Array<any> | Record<string, any>): Promise<any> {
|
|
|
|
// All requests are over HTTP, so we can just start handling requests
|
|
|
|
// We do this here rather than the constructor so that we don't send any
|
2022-09-29 21:53:25 -04:00
|
|
|
// requests to the network (i.e. eth_chainId) until we absolutely have to.
|
2022-09-17 23:17:52 -04:00
|
|
|
await this._start();
|
|
|
|
|
|
|
|
return await super.send(method, params);
|
|
|
|
}
|
|
|
|
|
2022-09-05 16:14:43 -04:00
|
|
|
async _send(payload: JsonRpcPayload | Array<JsonRpcPayload>): Promise<Array<JsonRpcResult>> {
|
|
|
|
// Configure a POST connection for the requested method
|
2022-09-29 21:53:25 -04:00
|
|
|
const request = this._getConnection();
|
2022-09-05 16:14:43 -04:00
|
|
|
request.body = JSON.stringify(payload);
|
2023-01-17 13:51:32 -05:00
|
|
|
request.setHeader("content-type", "application/json");
|
2022-09-05 16:14:43 -04:00
|
|
|
|
|
|
|
const response = await request.send();
|
|
|
|
response.assertOk();
|
|
|
|
|
|
|
|
let resp = response.bodyJson;
|
|
|
|
if (!Array.isArray(resp)) { resp = [ resp ]; }
|
|
|
|
|
|
|
|
return resp;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function spelunkData(value: any): null | { message: string, data: string } {
|
|
|
|
if (value == null) { return null; }
|
|
|
|
|
|
|
|
// These *are* the droids we're looking for.
|
|
|
|
if (typeof(value.message) === "string" && value.message.match("reverted") && isHexString(value.data)) {
|
|
|
|
return { message: value.message, data: value.data };
|
|
|
|
}
|
|
|
|
|
|
|
|
// Spelunk further...
|
|
|
|
if (typeof(value) === "object") {
|
|
|
|
for (const key in value) {
|
|
|
|
const result = spelunkData(value[key]);
|
|
|
|
if (result) { return result; }
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Might be a JSON string we can further descend...
|
|
|
|
if (typeof(value) === "string") {
|
|
|
|
try {
|
|
|
|
return spelunkData(JSON.parse(value));
|
|
|
|
} catch (error) { }
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
function _spelunkMessage(value: any, result: Array<string>): void {
|
|
|
|
if (value == null) { return; }
|
|
|
|
|
|
|
|
// These *are* the droids we're looking for.
|
|
|
|
if (typeof(value.message) === "string") {
|
|
|
|
result.push(value.message);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Spelunk further...
|
|
|
|
if (typeof(value) === "object") {
|
|
|
|
for (const key in value) {
|
|
|
|
_spelunkMessage(value[key], result);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Might be a JSON string we can further descend...
|
|
|
|
if (typeof(value) === "string") {
|
|
|
|
try {
|
|
|
|
return _spelunkMessage(JSON.parse(value), result);
|
|
|
|
} catch (error) { }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function spelunkMessage(value: any): Array<string> {
|
|
|
|
const result: Array<string> = [ ];
|
|
|
|
_spelunkMessage(value, result);
|
|
|
|
return result;
|
|
|
|
}
|