json-rpc-provider.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. import { Signer } from "@ethersproject/abstract-signer";
  12. import { BigNumber } from "@ethersproject/bignumber";
  13. import { hexlify, hexValue, isHexString } from "@ethersproject/bytes";
  14. import { _TypedDataEncoder } from "@ethersproject/hash";
  15. import { checkProperties, deepCopy, defineReadOnly, getStatic, resolveProperties, shallowCopy } from "@ethersproject/properties";
  16. import { toUtf8Bytes } from "@ethersproject/strings";
  17. import { accessListify } from "@ethersproject/transactions";
  18. import { fetchJson, poll } from "@ethersproject/web";
  19. import { Logger } from "@ethersproject/logger";
  20. import { version } from "./_version";
  21. const logger = new Logger(version);
  22. import { BaseProvider } from "./base-provider";
  23. const errorGas = ["call", "estimateGas"];
  24. function checkError(method, error, params) {
  25. // Undo the "convenience" some nodes are attempting to prevent backwards
  26. // incompatibility; maybe for v6 consider forwarding reverts as errors
  27. if (method === "call" && error.code === Logger.errors.SERVER_ERROR) {
  28. const e = error.error;
  29. if (e && e.message.match("reverted") && isHexString(e.data)) {
  30. return e.data;
  31. }
  32. logger.throwError("missing revert data in call exception", Logger.errors.CALL_EXCEPTION, {
  33. error, data: "0x"
  34. });
  35. }
  36. let message = error.message;
  37. if (error.code === Logger.errors.SERVER_ERROR && error.error && typeof (error.error.message) === "string") {
  38. message = error.error.message;
  39. }
  40. else if (typeof (error.body) === "string") {
  41. message = error.body;
  42. }
  43. else if (typeof (error.responseText) === "string") {
  44. message = error.responseText;
  45. }
  46. message = (message || "").toLowerCase();
  47. const transaction = params.transaction || params.signedTransaction;
  48. // "insufficient funds for gas * price + value + cost(data)"
  49. if (message.match(/insufficient funds|base fee exceeds gas limit/)) {
  50. logger.throwError("insufficient funds for intrinsic transaction cost", Logger.errors.INSUFFICIENT_FUNDS, {
  51. error, method, transaction
  52. });
  53. }
  54. // "nonce too low"
  55. if (message.match(/nonce too low/)) {
  56. logger.throwError("nonce has already been used", Logger.errors.NONCE_EXPIRED, {
  57. error, method, transaction
  58. });
  59. }
  60. // "replacement transaction underpriced"
  61. if (message.match(/replacement transaction underpriced/)) {
  62. logger.throwError("replacement fee too low", Logger.errors.REPLACEMENT_UNDERPRICED, {
  63. error, method, transaction
  64. });
  65. }
  66. // "replacement transaction underpriced"
  67. if (message.match(/only replay-protected/)) {
  68. logger.throwError("legacy pre-eip-155 transactions not supported", Logger.errors.UNSUPPORTED_OPERATION, {
  69. error, method, transaction
  70. });
  71. }
  72. if (errorGas.indexOf(method) >= 0 && message.match(/gas required exceeds allowance|always failing transaction|execution reverted/)) {
  73. logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
  74. error, method, transaction
  75. });
  76. }
  77. throw error;
  78. }
  79. function timer(timeout) {
  80. return new Promise(function (resolve) {
  81. setTimeout(resolve, timeout);
  82. });
  83. }
  84. function getResult(payload) {
  85. if (payload.error) {
  86. // @TODO: not any
  87. const error = new Error(payload.error.message);
  88. error.code = payload.error.code;
  89. error.data = payload.error.data;
  90. throw error;
  91. }
  92. return payload.result;
  93. }
  94. function getLowerCase(value) {
  95. if (value) {
  96. return value.toLowerCase();
  97. }
  98. return value;
  99. }
  100. const _constructorGuard = {};
  101. export class JsonRpcSigner extends Signer {
  102. constructor(constructorGuard, provider, addressOrIndex) {
  103. logger.checkNew(new.target, JsonRpcSigner);
  104. super();
  105. if (constructorGuard !== _constructorGuard) {
  106. throw new Error("do not call the JsonRpcSigner constructor directly; use provider.getSigner");
  107. }
  108. defineReadOnly(this, "provider", provider);
  109. if (addressOrIndex == null) {
  110. addressOrIndex = 0;
  111. }
  112. if (typeof (addressOrIndex) === "string") {
  113. defineReadOnly(this, "_address", this.provider.formatter.address(addressOrIndex));
  114. defineReadOnly(this, "_index", null);
  115. }
  116. else if (typeof (addressOrIndex) === "number") {
  117. defineReadOnly(this, "_index", addressOrIndex);
  118. defineReadOnly(this, "_address", null);
  119. }
  120. else {
  121. logger.throwArgumentError("invalid address or index", "addressOrIndex", addressOrIndex);
  122. }
  123. }
  124. connect(provider) {
  125. return logger.throwError("cannot alter JSON-RPC Signer connection", Logger.errors.UNSUPPORTED_OPERATION, {
  126. operation: "connect"
  127. });
  128. }
  129. connectUnchecked() {
  130. return new UncheckedJsonRpcSigner(_constructorGuard, this.provider, this._address || this._index);
  131. }
  132. getAddress() {
  133. if (this._address) {
  134. return Promise.resolve(this._address);
  135. }
  136. return this.provider.send("eth_accounts", []).then((accounts) => {
  137. if (accounts.length <= this._index) {
  138. logger.throwError("unknown account #" + this._index, Logger.errors.UNSUPPORTED_OPERATION, {
  139. operation: "getAddress"
  140. });
  141. }
  142. return this.provider.formatter.address(accounts[this._index]);
  143. });
  144. }
  145. sendUncheckedTransaction(transaction) {
  146. transaction = shallowCopy(transaction);
  147. const fromAddress = this.getAddress().then((address) => {
  148. if (address) {
  149. address = address.toLowerCase();
  150. }
  151. return address;
  152. });
  153. // The JSON-RPC for eth_sendTransaction uses 90000 gas; if the user
  154. // wishes to use this, it is easy to specify explicitly, otherwise
  155. // we look it up for them.
  156. if (transaction.gasLimit == null) {
  157. const estimate = shallowCopy(transaction);
  158. estimate.from = fromAddress;
  159. transaction.gasLimit = this.provider.estimateGas(estimate);
  160. }
  161. if (transaction.to != null) {
  162. transaction.to = Promise.resolve(transaction.to).then((to) => __awaiter(this, void 0, void 0, function* () {
  163. if (to == null) {
  164. return null;
  165. }
  166. const address = yield this.provider.resolveName(to);
  167. if (address == null) {
  168. logger.throwArgumentError("provided ENS name resolves to null", "tx.to", to);
  169. }
  170. return address;
  171. }));
  172. }
  173. return resolveProperties({
  174. tx: resolveProperties(transaction),
  175. sender: fromAddress
  176. }).then(({ tx, sender }) => {
  177. if (tx.from != null) {
  178. if (tx.from.toLowerCase() !== sender) {
  179. logger.throwArgumentError("from address mismatch", "transaction", transaction);
  180. }
  181. }
  182. else {
  183. tx.from = sender;
  184. }
  185. const hexTx = this.provider.constructor.hexlifyTransaction(tx, { from: true });
  186. return this.provider.send("eth_sendTransaction", [hexTx]).then((hash) => {
  187. return hash;
  188. }, (error) => {
  189. return checkError("sendTransaction", error, hexTx);
  190. });
  191. });
  192. }
  193. signTransaction(transaction) {
  194. return logger.throwError("signing transactions is unsupported", Logger.errors.UNSUPPORTED_OPERATION, {
  195. operation: "signTransaction"
  196. });
  197. }
  198. sendTransaction(transaction) {
  199. return __awaiter(this, void 0, void 0, function* () {
  200. // This cannot be mined any earlier than any recent block
  201. const blockNumber = yield this.provider._getInternalBlockNumber(100 + 2 * this.provider.pollingInterval);
  202. // Send the transaction
  203. const hash = yield this.sendUncheckedTransaction(transaction);
  204. try {
  205. // Unfortunately, JSON-RPC only provides and opaque transaction hash
  206. // for a response, and we need the actual transaction, so we poll
  207. // for it; it should show up very quickly
  208. return yield poll(() => __awaiter(this, void 0, void 0, function* () {
  209. const tx = yield this.provider.getTransaction(hash);
  210. if (tx === null) {
  211. return undefined;
  212. }
  213. return this.provider._wrapTransaction(tx, hash, blockNumber);
  214. }), { oncePoll: this.provider });
  215. }
  216. catch (error) {
  217. error.transactionHash = hash;
  218. throw error;
  219. }
  220. });
  221. }
  222. signMessage(message) {
  223. return __awaiter(this, void 0, void 0, function* () {
  224. const data = ((typeof (message) === "string") ? toUtf8Bytes(message) : message);
  225. const address = yield this.getAddress();
  226. return yield this.provider.send("personal_sign", [hexlify(data), address.toLowerCase()]);
  227. });
  228. }
  229. _legacySignMessage(message) {
  230. return __awaiter(this, void 0, void 0, function* () {
  231. const data = ((typeof (message) === "string") ? toUtf8Bytes(message) : message);
  232. const address = yield this.getAddress();
  233. // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  234. return yield this.provider.send("eth_sign", [address.toLowerCase(), hexlify(data)]);
  235. });
  236. }
  237. _signTypedData(domain, types, value) {
  238. return __awaiter(this, void 0, void 0, function* () {
  239. // Populate any ENS names (in-place)
  240. const populated = yield _TypedDataEncoder.resolveNames(domain, types, value, (name) => {
  241. return this.provider.resolveName(name);
  242. });
  243. const address = yield this.getAddress();
  244. return yield this.provider.send("eth_signTypedData_v4", [
  245. address.toLowerCase(),
  246. JSON.stringify(_TypedDataEncoder.getPayload(populated.domain, types, populated.value))
  247. ]);
  248. });
  249. }
  250. unlock(password) {
  251. return __awaiter(this, void 0, void 0, function* () {
  252. const provider = this.provider;
  253. const address = yield this.getAddress();
  254. return provider.send("personal_unlockAccount", [address.toLowerCase(), password, null]);
  255. });
  256. }
  257. }
  258. class UncheckedJsonRpcSigner extends JsonRpcSigner {
  259. sendTransaction(transaction) {
  260. return this.sendUncheckedTransaction(transaction).then((hash) => {
  261. return {
  262. hash: hash,
  263. nonce: null,
  264. gasLimit: null,
  265. gasPrice: null,
  266. data: null,
  267. value: null,
  268. chainId: null,
  269. confirmations: 0,
  270. from: null,
  271. wait: (confirmations) => { return this.provider.waitForTransaction(hash, confirmations); }
  272. };
  273. });
  274. }
  275. }
  276. const allowedTransactionKeys = {
  277. chainId: true, data: true, gasLimit: true, gasPrice: true, nonce: true, to: true, value: true,
  278. type: true, accessList: true,
  279. maxFeePerGas: true, maxPriorityFeePerGas: true
  280. };
  281. export class JsonRpcProvider extends BaseProvider {
  282. constructor(url, network) {
  283. logger.checkNew(new.target, JsonRpcProvider);
  284. let networkOrReady = network;
  285. // The network is unknown, query the JSON-RPC for it
  286. if (networkOrReady == null) {
  287. networkOrReady = new Promise((resolve, reject) => {
  288. setTimeout(() => {
  289. this.detectNetwork().then((network) => {
  290. resolve(network);
  291. }, (error) => {
  292. reject(error);
  293. });
  294. }, 0);
  295. });
  296. }
  297. super(networkOrReady);
  298. // Default URL
  299. if (!url) {
  300. url = getStatic(this.constructor, "defaultUrl")();
  301. }
  302. if (typeof (url) === "string") {
  303. defineReadOnly(this, "connection", Object.freeze({
  304. url: url
  305. }));
  306. }
  307. else {
  308. defineReadOnly(this, "connection", Object.freeze(shallowCopy(url)));
  309. }
  310. this._nextId = 42;
  311. }
  312. get _cache() {
  313. if (this._eventLoopCache == null) {
  314. this._eventLoopCache = {};
  315. }
  316. return this._eventLoopCache;
  317. }
  318. static defaultUrl() {
  319. return "http:/\/localhost:8545";
  320. }
  321. detectNetwork() {
  322. if (!this._cache["detectNetwork"]) {
  323. this._cache["detectNetwork"] = this._uncachedDetectNetwork();
  324. // Clear this cache at the beginning of the next event loop
  325. setTimeout(() => {
  326. this._cache["detectNetwork"] = null;
  327. }, 0);
  328. }
  329. return this._cache["detectNetwork"];
  330. }
  331. _uncachedDetectNetwork() {
  332. return __awaiter(this, void 0, void 0, function* () {
  333. yield timer(0);
  334. let chainId = null;
  335. try {
  336. chainId = yield this.send("eth_chainId", []);
  337. }
  338. catch (error) {
  339. try {
  340. chainId = yield this.send("net_version", []);
  341. }
  342. catch (error) { }
  343. }
  344. if (chainId != null) {
  345. const getNetwork = getStatic(this.constructor, "getNetwork");
  346. try {
  347. return getNetwork(BigNumber.from(chainId).toNumber());
  348. }
  349. catch (error) {
  350. return logger.throwError("could not detect network", Logger.errors.NETWORK_ERROR, {
  351. chainId: chainId,
  352. event: "invalidNetwork",
  353. serverError: error
  354. });
  355. }
  356. }
  357. return logger.throwError("could not detect network", Logger.errors.NETWORK_ERROR, {
  358. event: "noNetwork"
  359. });
  360. });
  361. }
  362. getSigner(addressOrIndex) {
  363. return new JsonRpcSigner(_constructorGuard, this, addressOrIndex);
  364. }
  365. getUncheckedSigner(addressOrIndex) {
  366. return this.getSigner(addressOrIndex).connectUnchecked();
  367. }
  368. listAccounts() {
  369. return this.send("eth_accounts", []).then((accounts) => {
  370. return accounts.map((a) => this.formatter.address(a));
  371. });
  372. }
  373. send(method, params) {
  374. const request = {
  375. method: method,
  376. params: params,
  377. id: (this._nextId++),
  378. jsonrpc: "2.0"
  379. };
  380. this.emit("debug", {
  381. action: "request",
  382. request: deepCopy(request),
  383. provider: this
  384. });
  385. // We can expand this in the future to any call, but for now these
  386. // are the biggest wins and do not require any serializing parameters.
  387. const cache = (["eth_chainId", "eth_blockNumber"].indexOf(method) >= 0);
  388. if (cache && this._cache[method]) {
  389. return this._cache[method];
  390. }
  391. const result = fetchJson(this.connection, JSON.stringify(request), getResult).then((result) => {
  392. this.emit("debug", {
  393. action: "response",
  394. request: request,
  395. response: result,
  396. provider: this
  397. });
  398. return result;
  399. }, (error) => {
  400. this.emit("debug", {
  401. action: "response",
  402. error: error,
  403. request: request,
  404. provider: this
  405. });
  406. throw error;
  407. });
  408. // Cache the fetch, but clear it on the next event loop
  409. if (cache) {
  410. this._cache[method] = result;
  411. setTimeout(() => {
  412. this._cache[method] = null;
  413. }, 0);
  414. }
  415. return result;
  416. }
  417. prepareRequest(method, params) {
  418. switch (method) {
  419. case "getBlockNumber":
  420. return ["eth_blockNumber", []];
  421. case "getGasPrice":
  422. return ["eth_gasPrice", []];
  423. case "getBalance":
  424. return ["eth_getBalance", [getLowerCase(params.address), params.blockTag]];
  425. case "getTransactionCount":
  426. return ["eth_getTransactionCount", [getLowerCase(params.address), params.blockTag]];
  427. case "getCode":
  428. return ["eth_getCode", [getLowerCase(params.address), params.blockTag]];
  429. case "getStorageAt":
  430. return ["eth_getStorageAt", [getLowerCase(params.address), params.position, params.blockTag]];
  431. case "sendTransaction":
  432. return ["eth_sendRawTransaction", [params.signedTransaction]];
  433. case "getBlock":
  434. if (params.blockTag) {
  435. return ["eth_getBlockByNumber", [params.blockTag, !!params.includeTransactions]];
  436. }
  437. else if (params.blockHash) {
  438. return ["eth_getBlockByHash", [params.blockHash, !!params.includeTransactions]];
  439. }
  440. return null;
  441. case "getTransaction":
  442. return ["eth_getTransactionByHash", [params.transactionHash]];
  443. case "getTransactionReceipt":
  444. return ["eth_getTransactionReceipt", [params.transactionHash]];
  445. case "call": {
  446. const hexlifyTransaction = getStatic(this.constructor, "hexlifyTransaction");
  447. return ["eth_call", [hexlifyTransaction(params.transaction, { from: true }), params.blockTag]];
  448. }
  449. case "estimateGas": {
  450. const hexlifyTransaction = getStatic(this.constructor, "hexlifyTransaction");
  451. return ["eth_estimateGas", [hexlifyTransaction(params.transaction, { from: true })]];
  452. }
  453. case "getLogs":
  454. if (params.filter && params.filter.address != null) {
  455. params.filter.address = getLowerCase(params.filter.address);
  456. }
  457. return ["eth_getLogs", [params.filter]];
  458. default:
  459. break;
  460. }
  461. return null;
  462. }
  463. perform(method, params) {
  464. return __awaiter(this, void 0, void 0, function* () {
  465. // Legacy networks do not like the type field being passed along (which
  466. // is fair), so we delete type if it is 0 and a non-EIP-1559 network
  467. if (method === "call" || method === "estimateGas") {
  468. const tx = params.transaction;
  469. if (tx && tx.type != null && BigNumber.from(tx.type).isZero()) {
  470. // If there are no EIP-1559 properties, it might be non-EIP-a559
  471. if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) {
  472. const feeData = yield this.getFeeData();
  473. if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) {
  474. // Network doesn't know about EIP-1559 (and hence type)
  475. params = shallowCopy(params);
  476. params.transaction = shallowCopy(tx);
  477. delete params.transaction.type;
  478. }
  479. }
  480. }
  481. }
  482. const args = this.prepareRequest(method, params);
  483. if (args == null) {
  484. logger.throwError(method + " not implemented", Logger.errors.NOT_IMPLEMENTED, { operation: method });
  485. }
  486. try {
  487. return yield this.send(args[0], args[1]);
  488. }
  489. catch (error) {
  490. return checkError(method, error, params);
  491. }
  492. });
  493. }
  494. _startEvent(event) {
  495. if (event.tag === "pending") {
  496. this._startPending();
  497. }
  498. super._startEvent(event);
  499. }
  500. _startPending() {
  501. if (this._pendingFilter != null) {
  502. return;
  503. }
  504. const self = this;
  505. const pendingFilter = this.send("eth_newPendingTransactionFilter", []);
  506. this._pendingFilter = pendingFilter;
  507. pendingFilter.then(function (filterId) {
  508. function poll() {
  509. self.send("eth_getFilterChanges", [filterId]).then(function (hashes) {
  510. if (self._pendingFilter != pendingFilter) {
  511. return null;
  512. }
  513. let seq = Promise.resolve();
  514. hashes.forEach(function (hash) {
  515. // @TODO: This should be garbage collected at some point... How? When?
  516. self._emitted["t:" + hash.toLowerCase()] = "pending";
  517. seq = seq.then(function () {
  518. return self.getTransaction(hash).then(function (tx) {
  519. self.emit("pending", tx);
  520. return null;
  521. });
  522. });
  523. });
  524. return seq.then(function () {
  525. return timer(1000);
  526. });
  527. }).then(function () {
  528. if (self._pendingFilter != pendingFilter) {
  529. self.send("eth_uninstallFilter", [filterId]);
  530. return;
  531. }
  532. setTimeout(function () { poll(); }, 0);
  533. return null;
  534. }).catch((error) => { });
  535. }
  536. poll();
  537. return filterId;
  538. }).catch((error) => { });
  539. }
  540. _stopEvent(event) {
  541. if (event.tag === "pending" && this.listenerCount("pending") === 0) {
  542. this._pendingFilter = null;
  543. }
  544. super._stopEvent(event);
  545. }
  546. // Convert an ethers.js transaction into a JSON-RPC transaction
  547. // - gasLimit => gas
  548. // - All values hexlified
  549. // - All numeric values zero-striped
  550. // - All addresses are lowercased
  551. // NOTE: This allows a TransactionRequest, but all values should be resolved
  552. // before this is called
  553. // @TODO: This will likely be removed in future versions and prepareRequest
  554. // will be the preferred method for this.
  555. static hexlifyTransaction(transaction, allowExtra) {
  556. // Check only allowed properties are given
  557. const allowed = shallowCopy(allowedTransactionKeys);
  558. if (allowExtra) {
  559. for (const key in allowExtra) {
  560. if (allowExtra[key]) {
  561. allowed[key] = true;
  562. }
  563. }
  564. }
  565. checkProperties(transaction, allowed);
  566. const result = {};
  567. // JSON-RPC now requires numeric values to be "quantity" values
  568. ["chainId", "gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach(function (key) {
  569. if (transaction[key] == null) {
  570. return;
  571. }
  572. const value = hexValue(transaction[key]);
  573. if (key === "gasLimit") {
  574. key = "gas";
  575. }
  576. result[key] = value;
  577. });
  578. ["from", "to", "data"].forEach(function (key) {
  579. if (transaction[key] == null) {
  580. return;
  581. }
  582. result[key] = hexlify(transaction[key]);
  583. });
  584. if (transaction.accessList) {
  585. result["accessList"] = accessListify(transaction.accessList);
  586. }
  587. return result;
  588. }
  589. }
  590. //# sourceMappingURL=json-rpc-provider.js.map