UNPKG

12.2 kBTypeScriptView Raw
1/**
2 * One of the most common ways to interact with the blockchain is
3 * by a node running a JSON-RPC interface which can be connected to,
4 * based on the transport, using:
5 *
6 * - HTTP or HTTPS - [[JsonRpcProvider]]
7 * - WebSocket - [[WebSocketProvider]]
8 * - IPC - [[IpcSocketProvider]]
9 *
10 * @_section: api/providers/jsonrpc:JSON-RPC Provider [about-jsonrpcProvider]
11 */
12import { FetchRequest } from "../utils/index.js";
13import { AbstractProvider } from "./abstract-provider.js";
14import { AbstractSigner } from "./abstract-signer.js";
15import { Network } from "./network.js";
16import type { TypedDataDomain, TypedDataField } from "../hash/index.js";
17import type { TransactionLike } from "../transaction/index.js";
18import type { PerformActionRequest, Subscriber, Subscription } from "./abstract-provider.js";
19import type { Networkish } from "./network.js";
20import type { Provider, TransactionRequest, TransactionResponse } from "./provider.js";
21import type { Signer } from "./signer.js";
22/**
23 * A JSON-RPC payload, which are sent to a JSON-RPC server.
24 */
25export type JsonRpcPayload = {
26 /**
27 * The JSON-RPC request ID.
28 */
29 id: number;
30 /**
31 * The JSON-RPC request method.
32 */
33 method: string;
34 /**
35 * The JSON-RPC request parameters.
36 */
37 params: Array<any> | Record<string, any>;
38 /**
39 * A required constant in the JSON-RPC specification.
40 */
41 jsonrpc: "2.0";
42};
43/**
44 * A JSON-RPC result, which are returned on success from a JSON-RPC server.
45 */
46export type JsonRpcResult = {
47 /**
48 * The response ID to match it to the relevant request.
49 */
50 id: number;
51 /**
52 * The response result.
53 */
54 result: any;
55};
56/**
57 * A JSON-RPC error, which are returned on failure from a JSON-RPC server.
58 */
59export type JsonRpcError = {
60 /**
61 * The response ID to match it to the relevant request.
62 */
63 id: number;
64 /**
65 * The response error.
66 */
67 error: {
68 code: number;
69 message?: string;
70 data?: any;
71 };
72};
73/**
74 * When subscribing to the ``"debug"`` event, the [[Listener]] will
75 * receive this object as the first parameter.
76 */
77export type DebugEventJsonRpcApiProvider = {
78 action: "sendRpcPayload";
79 payload: JsonRpcPayload | Array<JsonRpcPayload>;
80} | {
81 action: "receiveRpcResult";
82 result: Array<JsonRpcResult | JsonRpcError>;
83} | {
84 action: "receiveRpcError";
85 error: Error;
86};
87/**
88 * Options for configuring a [[JsonRpcApiProvider]]. Much of this
89 * is targetted towards sub-classes, which often will not expose
90 * any of these options to their consumers.
91 *
92 * **``polling``** - use the polling strategy is used immediately
93 * for events; otherwise, attempt to use filters and fall back onto
94 * polling (default: ``false``)
95 *
96 * **``staticNetwork``** - do not request chain ID on requests to
97 * validate the underlying chain has not changed (default: ``null``)
98 *
99 * This should **ONLY** be used if it is **certain** that the network
100 * cannot change, such as when using INFURA (since the URL dictates the
101 * network). If the network is assumed static and it does change, this
102 * can have tragic consequences. For example, this **CANNOT** be used
103 * with MetaMask, since the user can select a new network from the
104 * drop-down at any time.
105 *
106 * **``batchStallTime``** - how long (ms) to aggregate requests into a
107 * single batch. ``0`` indicates batching will only encompass the current
108 * event loop. If ``batchMaxCount = 1``, this is ignored. (default: ``10``)
109 *
110 * **``batchMaxSize``** - target maximum size (bytes) to allow per batch
111 * request (default: 1Mb)
112 *
113 * **``batchMaxCount``** - maximum number of requests to allow in a batch.
114 * If ``batchMaxCount = 1``, then batching is disabled. (default: ``100``)
115 *
116 * **``cacheTimeout``** - passed as [[AbstractProviderOptions]].
117 */
118export type JsonRpcApiProviderOptions = {
119 polling?: boolean;
120 staticNetwork?: null | boolean | Network;
121 batchStallTime?: number;
122 batchMaxSize?: number;
123 batchMaxCount?: number;
124 cacheTimeout?: number;
125 pollingInterval?: number;
126};
127/**
128 * A **JsonRpcTransactionRequest** is formatted as needed by the JSON-RPC
129 * Ethereum API specification.
130 */
131export interface JsonRpcTransactionRequest {
132 /**
133 * The sender address to use when signing.
134 */
135 from?: string;
136 /**
137 * The target address.
138 */
139 to?: string;
140 /**
141 * The transaction data.
142 */
143 data?: string;
144 /**
145 * The chain ID the transaction is valid on.
146 */
147 chainId?: string;
148 /**
149 * The [[link-eip-2718]] transaction type.
150 */
151 type?: string;
152 /**
153 * The maximum amount of gas to allow a transaction to consume.
154 *
155 * In most other places in ethers, this is called ``gasLimit`` which
156 * differs from the JSON-RPC Ethereum API specification.
157 */
158 gas?: string;
159 /**
160 * The gas price per wei for transactions prior to [[link-eip-1559]].
161 */
162 gasPrice?: string;
163 /**
164 * The maximum fee per gas for [[link-eip-1559]] transactions.
165 */
166 maxFeePerGas?: string;
167 /**
168 * The maximum priority fee per gas for [[link-eip-1559]] transactions.
169 */
170 maxPriorityFeePerGas?: string;
171 /**
172 * The nonce for the transaction.
173 */
174 nonce?: string;
175 /**
176 * The transaction value (in wei).
177 */
178 value?: string;
179 /**
180 * The transaction access list.
181 */
182 accessList?: Array<{
183 address: string;
184 storageKeys: Array<string>;
185 }>;
186}
187export declare class JsonRpcSigner extends AbstractSigner<JsonRpcApiProvider> {
188 address: string;
189 constructor(provider: JsonRpcApiProvider, address: string);
190 connect(provider: null | Provider): Signer;
191 getAddress(): Promise<string>;
192 populateTransaction(tx: TransactionRequest): Promise<TransactionLike<string>>;
193 sendUncheckedTransaction(_tx: TransactionRequest): Promise<string>;
194 sendTransaction(tx: TransactionRequest): Promise<TransactionResponse>;
195 signTransaction(_tx: TransactionRequest): Promise<string>;
196 signMessage(_message: string | Uint8Array): Promise<string>;
197 signTypedData(domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, _value: Record<string, any>): Promise<string>;
198 unlock(password: string): Promise<boolean>;
199 _legacySignMessage(_message: string | Uint8Array): Promise<string>;
200}
201/**
202 * The JsonRpcApiProvider is an abstract class and **MUST** be
203 * sub-classed.
204 *
205 * It provides the base for all JSON-RPC-based Provider interaction.
206 *
207 * Sub-classing Notes:
208 * - a sub-class MUST override _send
209 * - a sub-class MUST call the `_start()` method once connected
210 */
211export declare abstract class JsonRpcApiProvider extends AbstractProvider {
212 #private;
213 constructor(network?: Networkish, options?: JsonRpcApiProviderOptions);
214 /**
215 * Returns the value associated with the option %%key%%.
216 *
217 * Sub-classes can use this to inquire about configuration options.
218 */
219 _getOption<K extends keyof JsonRpcApiProviderOptions>(key: K): JsonRpcApiProviderOptions[K];
220 /**
221 * Gets the [[Network]] this provider has committed to. On each call, the network
222 * is detected, and if it has changed, the call will reject.
223 */
224 get _network(): Network;
225 /**
226 * Sends a JSON-RPC %%payload%% (or a batch) to the underlying channel.
227 *
228 * Sub-classes **MUST** override this.
229 */
230 abstract _send(payload: JsonRpcPayload | Array<JsonRpcPayload>): Promise<Array<JsonRpcResult | JsonRpcError>>;
231 /**
232 * Resolves to the non-normalized value by performing %%req%%.
233 *
234 * Sub-classes may override this to modify behavior of actions,
235 * and should generally call ``super._perform`` as a fallback.
236 */
237 _perform(req: PerformActionRequest): Promise<any>;
238 /**
239 * Sub-classes may override this; it detects the *actual* network that
240 * we are **currently** connected to.
241 *
242 * Keep in mind that [[send]] may only be used once [[ready]], otherwise the
243 * _send primitive must be used instead.
244 */
245 _detectNetwork(): Promise<Network>;
246 /**
247 * Sub-classes **MUST** call this. Until [[_start]] has been called, no calls
248 * will be passed to [[_send]] from [[send]]. If it is overridden, then
249 * ``super._start()`` **MUST** be called.
250 *
251 * Calling it multiple times is safe and has no effect.
252 */
253 _start(): void;
254 /**
255 * Resolves once the [[_start]] has been called. This can be used in
256 * sub-classes to defer sending data until the connection has been
257 * established.
258 */
259 _waitUntilReady(): Promise<void>;
260 /**
261 * Return a Subscriber that will manage the %%sub%%.
262 *
263 * Sub-classes may override this to modify the behavior of
264 * subscription management.
265 */
266 _getSubscriber(sub: Subscription): Subscriber;
267 /**
268 * Returns true only if the [[_start]] has been called.
269 */
270 get ready(): boolean;
271 /**
272 * Returns %%tx%% as a normalized JSON-RPC transaction request,
273 * which has all values hexlified and any numeric values converted
274 * to Quantity values.
275 */
276 getRpcTransaction(tx: TransactionRequest): JsonRpcTransactionRequest;
277 /**
278 * Returns the request method and arguments required to perform
279 * %%req%%.
280 */
281 getRpcRequest(req: PerformActionRequest): null | {
282 method: string;
283 args: Array<any>;
284 };
285 /**
286 * Returns an ethers-style Error for the given JSON-RPC error
287 * %%payload%%, coalescing the various strings and error shapes
288 * that different nodes return, coercing them into a machine-readable
289 * standardized error.
290 */
291 getRpcError(payload: JsonRpcPayload, _error: JsonRpcError): Error;
292 /**
293 * Requests the %%method%% with %%params%% via the JSON-RPC protocol
294 * over the underlying channel. This can be used to call methods
295 * on the backend that do not have a high-level API within the Provider
296 * API.
297 *
298 * This method queues requests according to the batch constraints
299 * in the options, assigns the request a unique ID.
300 *
301 * **Do NOT override** this method in sub-classes; instead
302 * override [[_send]] or force the options values in the
303 * call to the constructor to modify this method's behavior.
304 */
305 send(method: string, params: Array<any> | Record<string, any>): Promise<any>;
306 /**
307 * Resolves to the [[Signer]] account for %%address%% managed by
308 * the client.
309 *
310 * If the %%address%% is a number, it is used as an index in the
311 * the accounts from [[listAccounts]].
312 *
313 * This can only be used on clients which manage accounts (such as
314 * Geth with imported account or MetaMask).
315 *
316 * Throws if the account doesn't exist.
317 */
318 getSigner(address?: number | string): Promise<JsonRpcSigner>;
319 listAccounts(): Promise<Array<JsonRpcSigner>>;
320 destroy(): void;
321}
322/**
323 * @_ignore:
324 */
325export declare abstract class JsonRpcApiPollingProvider extends JsonRpcApiProvider {
326 #private;
327 constructor(network?: Networkish, options?: JsonRpcApiProviderOptions);
328 _getSubscriber(sub: Subscription): Subscriber;
329 /**
330 * The polling interval (default: 4000 ms)
331 */
332 get pollingInterval(): number;
333 set pollingInterval(value: number);
334}
335/**
336 * The JsonRpcProvider is one of the most common Providers,
337 * which performs all operations over HTTP (or HTTPS) requests.
338 *
339 * Events are processed by polling the backend for the current block
340 * number; when it advances, all block-base events are then checked
341 * for updates.
342 */
343export declare class JsonRpcProvider extends JsonRpcApiPollingProvider {
344 #private;
345 constructor(url?: string | FetchRequest, network?: Networkish, options?: JsonRpcApiProviderOptions);
346 _getConnection(): FetchRequest;
347 send(method: string, params: Array<any> | Record<string, any>): Promise<any>;
348 _send(payload: JsonRpcPayload | Array<JsonRpcPayload>): Promise<Array<JsonRpcResult>>;
349}
350//# sourceMappingURL=provider-jsonrpc.d.ts.map
\No newline at end of file