index.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. /*
  2. This file is part of web3.js.
  3. web3.js is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. web3.js is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /**
  15. * @file index.js
  16. * @author Fabian Vogelsteller <fabian@ethereum.org>
  17. * @author Marek Kotewicz <marek@parity.io>
  18. * @date 2017
  19. */
  20. 'use strict';
  21. var errors = require('web3-core-helpers').errors;
  22. var formatters = require('web3-core-helpers').formatters;
  23. var utils = require('web3-utils');
  24. var promiEvent = require('web3-core-promievent');
  25. var Subscriptions = require('web3-core-subscriptions').subscriptions;
  26. var EthersTransactionUtils = require('@ethersproject/transactions');
  27. var Method = function Method(options) {
  28. if (!options.call || !options.name) {
  29. throw new Error('When creating a method you need to provide at least the "name" and "call" property.');
  30. }
  31. this.name = options.name;
  32. this.call = options.call;
  33. this.params = options.params || 0;
  34. this.inputFormatter = options.inputFormatter;
  35. this.outputFormatter = options.outputFormatter;
  36. this.transformPayload = options.transformPayload;
  37. this.extraFormatters = options.extraFormatters;
  38. this.abiCoder = options.abiCoder; // Will be used to encode the revert reason string
  39. this.requestManager = options.requestManager;
  40. // reference to eth.accounts
  41. this.accounts = options.accounts;
  42. this.defaultBlock = options.defaultBlock || 'latest';
  43. this.defaultAccount = options.defaultAccount || null;
  44. this.transactionBlockTimeout = options.transactionBlockTimeout || 50;
  45. this.transactionConfirmationBlocks = options.transactionConfirmationBlocks || 24;
  46. this.transactionPollingTimeout = options.transactionPollingTimeout || 750;
  47. this.transactionPollingInterval = options.transactionPollingInterval || 1000;
  48. this.blockHeaderTimeout = options.blockHeaderTimeout || 10; // 10 seconds
  49. this.defaultCommon = options.defaultCommon;
  50. this.defaultChain = options.defaultChain;
  51. this.defaultHardfork = options.defaultHardfork;
  52. this.handleRevert = options.handleRevert;
  53. };
  54. Method.prototype.setRequestManager = function (requestManager, accounts) {
  55. this.requestManager = requestManager;
  56. // reference to eth.accounts
  57. if (accounts) {
  58. this.accounts = accounts;
  59. }
  60. };
  61. Method.prototype.createFunction = function (requestManager, accounts) {
  62. var func = this.buildCall();
  63. Object.defineProperty(func, 'call', { configurable: true, writable: true, value: this.call });
  64. this.setRequestManager(requestManager || this.requestManager, accounts || this.accounts);
  65. return func;
  66. };
  67. Method.prototype.attachToObject = function (obj) {
  68. var func = this.buildCall();
  69. Object.defineProperty(func, 'call', { configurable: true, writable: true, value: this.call });
  70. var name = this.name.split('.');
  71. if (name.length > 1) {
  72. obj[name[0]] = obj[name[0]] || {};
  73. obj[name[0]][name[1]] = func;
  74. }
  75. else {
  76. obj[name[0]] = func;
  77. }
  78. };
  79. /**
  80. * Should be used to determine name of the jsonrpc method based on arguments
  81. *
  82. * @method getCall
  83. * @param {Array} arguments
  84. * @return {String} name of jsonrpc method
  85. */
  86. Method.prototype.getCall = function (args) {
  87. return typeof this.call === 'function' ? this.call(args) : this.call;
  88. };
  89. /**
  90. * Should be used to extract callback from array of arguments. Modifies input param
  91. *
  92. * @method extractCallback
  93. * @param {Array} arguments
  94. * @return {Function|Null} callback, if exists
  95. */
  96. Method.prototype.extractCallback = function (args) {
  97. if (typeof (args[args.length - 1]) === 'function') {
  98. return args.pop(); // modify the args array!
  99. }
  100. };
  101. /**
  102. * Should be called to check if the number of arguments is correct
  103. *
  104. * @method validateArgs
  105. * @param {Array} arguments
  106. * @throws {Error} if it is not
  107. */
  108. Method.prototype.validateArgs = function (args) {
  109. if (args.length !== this.params) {
  110. throw errors.InvalidNumberOfParams(args.length, this.params, this.name);
  111. }
  112. };
  113. /**
  114. * Should be called to format input args of method
  115. *
  116. * @method formatInput
  117. * @param {Array}
  118. * @return {Array}
  119. */
  120. Method.prototype.formatInput = function (args) {
  121. var _this = this;
  122. if (!this.inputFormatter) {
  123. return args;
  124. }
  125. return this.inputFormatter.map(function (formatter, index) {
  126. // bind this for defaultBlock, and defaultAccount
  127. return formatter ? formatter.call(_this, args[index]) : args[index];
  128. });
  129. };
  130. /**
  131. * Should be called to format output(result) of method
  132. *
  133. * @method formatOutput
  134. * @param {Object}
  135. * @return {Object}
  136. */
  137. Method.prototype.formatOutput = function (result) {
  138. var _this = this;
  139. if (Array.isArray(result)) {
  140. return result.map(function (res) {
  141. return _this.outputFormatter && res ? _this.outputFormatter(res, this?.hexFormat) : res;
  142. });
  143. }
  144. else {
  145. return this.outputFormatter && result ? this.outputFormatter(result, this?.hexFormat) : result;
  146. }
  147. };
  148. /**
  149. * Should create payload from given input args
  150. *
  151. * @method toPayload
  152. * @param {Array} args
  153. * @return {Object}
  154. */
  155. Method.prototype.toPayload = function (args) {
  156. var call = this.getCall(args);
  157. var callback = this.extractCallback(args);
  158. var params = this.formatInput(args);
  159. this.validateArgs(params);
  160. var payload = {
  161. method: call,
  162. params: params,
  163. callback: callback
  164. };
  165. if (this.transformPayload) {
  166. payload = this.transformPayload(payload);
  167. }
  168. return payload;
  169. };
  170. Method.prototype._confirmTransaction = function (defer, result, payload) {
  171. var method = this, promiseResolved = false, canUnsubscribe = true, timeoutCount = 0, confirmationCount = 0, intervalId = null, blockHeaderTimeoutId = null, lastBlock = null, receiptJSON = '', gasProvided = ((!!payload.params[0] && typeof payload.params[0] === 'object') && payload.params[0].gas) ? payload.params[0].gas : null, isContractDeployment = (!!payload.params[0] && typeof payload.params[0] === 'object') &&
  172. payload.params[0].data &&
  173. payload.params[0].from &&
  174. !payload.params[0].to, hasBytecode = isContractDeployment && payload.params[0].data.length > 2;
  175. // add custom send Methods
  176. var _ethereumCalls = [
  177. new Method({
  178. name: 'getBlockByNumber',
  179. call: 'eth_getBlockByNumber',
  180. params: 2,
  181. inputFormatter: [formatters.inputBlockNumberFormatter, function (val) {
  182. return !!val;
  183. }],
  184. outputFormatter: formatters.outputBlockFormatter
  185. }),
  186. new Method({
  187. name: 'getTransactionReceipt',
  188. call: 'eth_getTransactionReceipt',
  189. params: 1,
  190. inputFormatter: [null],
  191. outputFormatter: formatters.outputTransactionReceiptFormatter
  192. }),
  193. new Method({
  194. name: 'getCode',
  195. call: 'eth_getCode',
  196. params: 2,
  197. inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter]
  198. }),
  199. new Method({
  200. name: 'getTransactionByHash',
  201. call: 'eth_getTransactionByHash',
  202. params: 1,
  203. inputFormatter: [null],
  204. outputFormatter: formatters.outputTransactionFormatter
  205. }),
  206. new Subscriptions({
  207. name: 'subscribe',
  208. type: 'eth',
  209. subscriptions: {
  210. 'newBlockHeaders': {
  211. subscriptionName: 'newHeads',
  212. params: 0,
  213. outputFormatter: formatters.outputBlockFormatter
  214. }
  215. }
  216. })
  217. ];
  218. // attach methods to this._ethereumCall
  219. var _ethereumCall = {};
  220. _ethereumCalls.forEach(mthd => {
  221. mthd.attachToObject(_ethereumCall);
  222. mthd.requestManager = method.requestManager; // assign rather than call setRequestManager()
  223. });
  224. // fire "receipt" and confirmation events and resolve after
  225. var checkConfirmation = function (existingReceipt, isPolling, err, blockHeader, sub) {
  226. if (!err) {
  227. // create fake unsubscribe
  228. if (!sub) {
  229. sub = {
  230. unsubscribe: function () {
  231. clearInterval(intervalId);
  232. clearTimeout(blockHeaderTimeoutId);
  233. }
  234. };
  235. }
  236. // if we have a valid receipt we don't need to send a request
  237. return (existingReceipt ? promiEvent.resolve(existingReceipt) : _ethereumCall.getTransactionReceipt(result))
  238. // catch error from requesting receipt
  239. .catch(function (err) {
  240. sub.unsubscribe();
  241. promiseResolved = true;
  242. utils._fireError({
  243. message: 'Failed to check for transaction receipt:',
  244. data: err
  245. }, defer.eventEmitter, defer.reject);
  246. })
  247. // if CONFIRMATION listener exists check for confirmations, by setting canUnsubscribe = false
  248. .then(async function (receipt) {
  249. if (!receipt || !receipt.blockHash) {
  250. throw new Error('Receipt missing or blockHash null');
  251. }
  252. // apply extra formatters
  253. if (method.extraFormatters && method.extraFormatters.receiptFormatter) {
  254. receipt = method.extraFormatters.receiptFormatter(receipt);
  255. }
  256. // check if confirmation listener exists
  257. if (defer.eventEmitter.listeners('confirmation').length > 0) {
  258. var block;
  259. // If there was an immediately retrieved receipt, it's already
  260. // been confirmed by the direct call to checkConfirmation needed
  261. // for parity instant-seal
  262. if (existingReceipt === undefined || confirmationCount !== 0) {
  263. // Get latest block to emit with confirmation
  264. var latestBlock = await _ethereumCall.getBlockByNumber('latest');
  265. var latestBlockHash = latestBlock ? latestBlock.hash : null;
  266. if (isPolling) { // Check if actually a new block is existing on polling
  267. if (lastBlock) {
  268. block = await _ethereumCall.getBlockByNumber(lastBlock.number + 1);
  269. if (block) {
  270. lastBlock = block;
  271. defer.eventEmitter.emit('confirmation', confirmationCount, receipt, latestBlockHash);
  272. }
  273. }
  274. else {
  275. block = await _ethereumCall.getBlockByNumber(receipt.blockNumber);
  276. lastBlock = block;
  277. defer.eventEmitter.emit('confirmation', confirmationCount, receipt, latestBlockHash);
  278. }
  279. }
  280. else {
  281. defer.eventEmitter.emit('confirmation', confirmationCount, receipt, latestBlockHash);
  282. }
  283. }
  284. if ((isPolling && block) || !isPolling) {
  285. confirmationCount++;
  286. }
  287. canUnsubscribe = false;
  288. if (confirmationCount === method.transactionConfirmationBlocks + 1) { // add 1 so we account for conf 0
  289. sub.unsubscribe();
  290. defer.eventEmitter.removeAllListeners();
  291. }
  292. }
  293. return receipt;
  294. })
  295. // CHECK for CONTRACT DEPLOYMENT
  296. .then(async function (receipt) {
  297. if (isContractDeployment && !promiseResolved) {
  298. if (!receipt.contractAddress) {
  299. if (canUnsubscribe) {
  300. sub.unsubscribe();
  301. promiseResolved = true;
  302. }
  303. utils._fireError(errors.NoContractAddressFoundError(receipt), defer.eventEmitter, defer.reject, null, receipt);
  304. return;
  305. }
  306. var code;
  307. try {
  308. code = await _ethereumCall.getCode(receipt.contractAddress);
  309. }
  310. catch (err) {
  311. // ignore;
  312. }
  313. if (!code) {
  314. return;
  315. }
  316. // If deployment is status.true and there was a real
  317. // bytecode string, assume it was successful.
  318. var deploymentSuccess = receipt.status === true && hasBytecode;
  319. if (deploymentSuccess || code.length > 2) {
  320. defer.eventEmitter.emit('receipt', receipt);
  321. // if contract, return instance instead of receipt
  322. if (method.extraFormatters && method.extraFormatters.contractDeployFormatter) {
  323. defer.resolve(method.extraFormatters.contractDeployFormatter(receipt));
  324. }
  325. else {
  326. defer.resolve(receipt);
  327. }
  328. // need to remove listeners, as they aren't removed automatically when succesfull
  329. if (canUnsubscribe) {
  330. defer.eventEmitter.removeAllListeners();
  331. }
  332. }
  333. else {
  334. utils._fireError(errors.ContractCodeNotStoredError(receipt), defer.eventEmitter, defer.reject, null, receipt);
  335. }
  336. if (canUnsubscribe) {
  337. sub.unsubscribe();
  338. }
  339. promiseResolved = true;
  340. }
  341. return receipt;
  342. })
  343. // CHECK for normal tx check for receipt only
  344. .then(async function (receipt) {
  345. if (!isContractDeployment && !promiseResolved) {
  346. if (!receipt.outOfGas &&
  347. (!gasProvided || gasProvided !== receipt.gasUsed) &&
  348. (receipt.status === true || receipt.status === '0x1' || typeof receipt.status === 'undefined')) {
  349. defer.eventEmitter.emit('receipt', receipt);
  350. defer.resolve(receipt);
  351. // need to remove listeners, as they aren't removed automatically when succesfull
  352. if (canUnsubscribe) {
  353. defer.eventEmitter.removeAllListeners();
  354. }
  355. }
  356. else {
  357. receiptJSON = JSON.stringify(receipt, null, 2);
  358. if (receipt.status === false || receipt.status === '0x0') {
  359. try {
  360. var revertMessage = null;
  361. if (method.handleRevert &&
  362. (method.call === 'eth_sendTransaction' || method.call === 'eth_sendRawTransaction')) {
  363. var txReplayOptions = payload.params[0];
  364. // If send was raw, fetch the transaction and reconstitute the
  365. // original params so they can be replayed with `eth_call`
  366. if (method.call === 'eth_sendRawTransaction') {
  367. var rawTransactionHex = payload.params[0];
  368. var parsedTx = EthersTransactionUtils.parse(rawTransactionHex);
  369. txReplayOptions = formatters.inputTransactionFormatter({
  370. data: parsedTx.data,
  371. to: parsedTx.to,
  372. from: parsedTx.from,
  373. gas: parsedTx.gasLimit.toHexString(),
  374. gasPrice: parsedTx.gasPrice ? parsedTx.gasPrice.toHexString() : undefined,
  375. value: parsedTx.value.toHexString()
  376. });
  377. }
  378. // Get revert reason string with eth_call
  379. revertMessage = await method.getRevertReason(txReplayOptions, receipt.blockNumber);
  380. if (revertMessage) { // Only throw a revert error if a revert reason is existing
  381. utils._fireError(errors.TransactionRevertInstructionError(revertMessage.reason, revertMessage.signature, receipt), defer.eventEmitter, defer.reject, null, receipt);
  382. }
  383. else {
  384. throw false; // Throw false and let the try/catch statement handle the error correctly after
  385. }
  386. }
  387. else {
  388. throw false; // Throw false and let the try/catch statement handle the error correctly after
  389. }
  390. }
  391. catch (error) {
  392. // Throw an normal revert error if no revert reason is given or the detection of it is disabled
  393. utils._fireError(errors.TransactionRevertedWithoutReasonError(receipt), defer.eventEmitter, defer.reject, null, receipt);
  394. }
  395. }
  396. else {
  397. // Throw OOG if status is not existing and provided gas and used gas are equal
  398. utils._fireError(errors.TransactionOutOfGasError(receipt), defer.eventEmitter, defer.reject, null, receipt);
  399. }
  400. }
  401. if (canUnsubscribe) {
  402. sub.unsubscribe();
  403. }
  404. promiseResolved = true;
  405. }
  406. })
  407. // time out the transaction if not mined after 50 blocks
  408. .catch(function () {
  409. timeoutCount++;
  410. // check to see if we are http polling
  411. if (!!isPolling) {
  412. // polling timeout is different than transactionBlockTimeout blocks since we are triggering every second
  413. if (timeoutCount - 1 >= method.transactionPollingTimeout) {
  414. sub.unsubscribe();
  415. promiseResolved = true;
  416. utils._fireError(errors.TransactionError('Transaction was not mined within ' + method.transactionPollingTimeout + ' seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject);
  417. }
  418. }
  419. else {
  420. if (timeoutCount - 1 >= method.transactionBlockTimeout) {
  421. sub.unsubscribe();
  422. promiseResolved = true;
  423. utils._fireError(errors.TransactionError('Transaction was not mined within ' + method.transactionBlockTimeout + ' blocks, please make sure your transaction was properly sent. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject);
  424. }
  425. }
  426. });
  427. }
  428. else {
  429. sub.unsubscribe();
  430. promiseResolved = true;
  431. utils._fireError({
  432. message: 'Failed to subscribe to new newBlockHeaders to confirm the transaction receipts.',
  433. data: err
  434. }, defer.eventEmitter, defer.reject);
  435. }
  436. };
  437. // start watching for confirmation depending on the support features of the provider
  438. var startWatching = function (existingReceipt) {
  439. let blockHeaderArrived = false;
  440. const startInterval = () => {
  441. intervalId = setInterval(checkConfirmation.bind(null, existingReceipt, true), method.transactionPollingInterval);
  442. };
  443. // If provider do not support event subscription use polling
  444. if (!this.requestManager.provider.on) {
  445. return startInterval();
  446. }
  447. // Subscribe to new block headers to look for tx receipt
  448. _ethereumCall.subscribe('newBlockHeaders', function (err, blockHeader, sub) {
  449. blockHeaderArrived = true;
  450. if (err || !blockHeader) {
  451. // fall back to polling
  452. return startInterval();
  453. }
  454. checkConfirmation(existingReceipt, false, err, blockHeader, sub);
  455. });
  456. // Fallback to polling if tx receipt didn't arrived in "blockHeaderTimeout" [10 seconds]
  457. blockHeaderTimeoutId = setTimeout(() => {
  458. if (!blockHeaderArrived) {
  459. startInterval();
  460. }
  461. }, this.blockHeaderTimeout * 1000);
  462. }.bind(this);
  463. // first check if we already have a confirmed transaction
  464. _ethereumCall.getTransactionReceipt(result)
  465. .then(function (receipt) {
  466. if (receipt && receipt.blockHash) {
  467. if (defer.eventEmitter.listeners('confirmation').length > 0) {
  468. // We must keep on watching for new Blocks, if a confirmation listener is present
  469. startWatching(receipt);
  470. }
  471. checkConfirmation(receipt, false);
  472. }
  473. else if (!promiseResolved) {
  474. startWatching();
  475. }
  476. })
  477. .catch(function () {
  478. if (!promiseResolved)
  479. startWatching();
  480. });
  481. };
  482. var getWallet = function (from, accounts) {
  483. var wallet = null;
  484. // is index given
  485. if (typeof from === 'number') {
  486. wallet = accounts.wallet[from];
  487. // is account given
  488. }
  489. else if (!!from && typeof from === 'object' && from.address && from.privateKey) {
  490. wallet = from;
  491. // search in wallet for address
  492. }
  493. else {
  494. wallet = accounts.wallet[from.toLowerCase()];
  495. }
  496. return wallet;
  497. };
  498. Method.prototype.buildCall = function () {
  499. var method = this, isSendTx = (method.call === 'eth_sendTransaction' || method.call === 'eth_sendRawTransaction'), // || method.call === 'personal_sendTransaction'
  500. isCall = (method.call === 'eth_call');
  501. // actual send function
  502. var send = function () {
  503. let args = Array.prototype.slice.call(arguments);
  504. var defer = promiEvent(!isSendTx), payload = method.toPayload(args);
  505. method.hexFormat = false;
  506. if (method.call === 'eth_getTransactionReceipt'
  507. || method.call === 'eth_getTransactionByHash'
  508. || method.name === 'getBlock') {
  509. method.hexFormat = (payload.params.length < args.length && args[args.length - 1] === 'hex');
  510. }
  511. // CALLBACK function
  512. var sendTxCallback = function (err, result) {
  513. if (method.handleRevert && isCall && method.abiCoder) {
  514. var reasonData;
  515. // Ganache / Geth <= 1.9.13 return the reason data as a successful eth_call response
  516. // Geth >= 1.9.15 attaches the reason data to an error object.
  517. // Geth 1.9.14 is missing revert reason (https://github.com/ethereum/web3.js/issues/3520)
  518. if (!err && method.isRevertReasonString(result)) {
  519. reasonData = result.substring(10);
  520. }
  521. else if (err && err.data) {
  522. // workaround embedded error details got from some providers like MetaMask
  523. if (typeof err.data === 'object') {
  524. // Ganache has no `originalError` sub-object unlike others
  525. var originalError = err.data.originalError ?? err.data;
  526. reasonData = originalError.data.substring(10);
  527. }
  528. else {
  529. reasonData = err.data.substring(10);
  530. }
  531. }
  532. if (reasonData) {
  533. var reason = method.abiCoder.decodeParameter('string', '0x' + reasonData);
  534. var signature = 'Error(String)';
  535. utils._fireError(errors.RevertInstructionError(reason, signature), defer.eventEmitter, defer.reject, payload.callback, {
  536. reason: reason,
  537. signature: signature
  538. });
  539. return;
  540. }
  541. }
  542. try {
  543. result = method.formatOutput(result);
  544. }
  545. catch (e) {
  546. err = e;
  547. }
  548. if (result instanceof Error) {
  549. err = result;
  550. }
  551. if (!err) {
  552. if (payload.callback) {
  553. payload.callback(null, result);
  554. }
  555. }
  556. else {
  557. if (err.error) {
  558. err = err.error;
  559. }
  560. return utils._fireError(err, defer.eventEmitter, defer.reject, payload.callback);
  561. }
  562. // return PROMISE
  563. if (!isSendTx) {
  564. if (!err) {
  565. defer.resolve(result);
  566. }
  567. // return PROMIEVENT
  568. }
  569. else {
  570. defer.eventEmitter.emit('transactionHash', result);
  571. method._confirmTransaction(defer, result, payload);
  572. }
  573. };
  574. // SENDS the SIGNED SIGNATURE
  575. var sendSignedTx = function (sign) {
  576. var signedPayload = { ...payload,
  577. method: 'eth_sendRawTransaction',
  578. params: [sign.rawTransaction]
  579. };
  580. method.requestManager.send(signedPayload, sendTxCallback);
  581. };
  582. var sendRequest = function (payload, method) {
  583. if (method && method.accounts && method.accounts.wallet && method.accounts.wallet.length) {
  584. var wallet;
  585. // ETH_SENDTRANSACTION
  586. if (payload.method === 'eth_sendTransaction') {
  587. var tx = payload.params[0];
  588. wallet = getWallet((!!tx && typeof tx === 'object') ? tx.from : null, method.accounts);
  589. // If wallet was found, sign tx, and send using sendRawTransaction
  590. if (wallet && wallet.privateKey) {
  591. var tx = JSON.parse(JSON.stringify(tx));
  592. delete tx.from;
  593. if (method.defaultChain && !tx.chain) {
  594. tx.chain = method.defaultChain;
  595. }
  596. if (method.defaultHardfork && !tx.hardfork) {
  597. tx.hardfork = method.defaultHardfork;
  598. }
  599. if (method.defaultCommon && !tx.common) {
  600. tx.common = method.defaultCommon;
  601. }
  602. method.accounts.signTransaction(tx, wallet.privateKey)
  603. .then(sendSignedTx)
  604. .catch(function (err) {
  605. if (typeof defer.eventEmitter.listeners === 'function' && defer.eventEmitter.listeners('error').length) {
  606. try {
  607. defer.eventEmitter.emit('error', err);
  608. }
  609. catch (err) {
  610. // Ignore userland error prevent it to bubble up within web3.
  611. }
  612. defer.eventEmitter.removeAllListeners();
  613. defer.eventEmitter.catch(function () {
  614. });
  615. }
  616. defer.reject(err);
  617. });
  618. return;
  619. }
  620. // ETH_SIGN
  621. }
  622. else if (payload.method === 'eth_sign') {
  623. var data = payload.params[1];
  624. wallet = getWallet(payload.params[0], method.accounts);
  625. // If wallet was found, sign tx, and send using sendRawTransaction
  626. if (wallet && wallet.privateKey) {
  627. var sign = method.accounts.sign(data, wallet.privateKey);
  628. if (payload.callback) {
  629. payload.callback(null, sign.signature);
  630. }
  631. defer.resolve(sign.signature);
  632. return;
  633. }
  634. }
  635. }
  636. return method.requestManager.send(payload, sendTxCallback);
  637. };
  638. const hasSendTxObject = isSendTx
  639. && !!payload.params[0]
  640. && typeof payload.params[0] === 'object';
  641. if (hasSendTxObject &&
  642. payload.params[0].type === '0x1'
  643. && typeof payload.params[0].accessList === 'undefined') {
  644. payload.params[0].accessList = [];
  645. }
  646. // Send the actual transaction
  647. if (hasSendTxObject
  648. && (typeof payload.params[0].gasPrice === 'undefined'
  649. && (typeof payload.params[0].maxPriorityFeePerGas === 'undefined'
  650. || typeof payload.params[0].maxFeePerGas === 'undefined'))) {
  651. _handleTxPricing(method, payload.params[0]).then(txPricing => {
  652. if (txPricing.gasPrice !== undefined) {
  653. payload.params[0].gasPrice = txPricing.gasPrice;
  654. }
  655. else if (txPricing.maxPriorityFeePerGas !== undefined
  656. && txPricing.maxFeePerGas !== undefined) {
  657. payload.params[0].maxPriorityFeePerGas = txPricing.maxPriorityFeePerGas;
  658. payload.params[0].maxFeePerGas = txPricing.maxFeePerGas;
  659. }
  660. if (isSendTx) {
  661. setTimeout(() => {
  662. defer.eventEmitter.emit('sending', payload);
  663. }, 0);
  664. }
  665. sendRequest(payload, method);
  666. });
  667. }
  668. else {
  669. if (isSendTx) {
  670. setTimeout(() => {
  671. defer.eventEmitter.emit('sending', payload);
  672. }, 0);
  673. }
  674. sendRequest(payload, method);
  675. }
  676. if (isSendTx) {
  677. setTimeout(() => {
  678. defer.eventEmitter.emit('sent', payload);
  679. }, 0);
  680. }
  681. return defer.eventEmitter;
  682. };
  683. // necessary to attach things to the method
  684. send.method = method;
  685. // necessary for batch requests
  686. send.request = this.request.bind(this);
  687. return send;
  688. };
  689. function _handleTxPricing(method, tx) {
  690. return new Promise((resolve, reject) => {
  691. try {
  692. var getBlockByNumber = (new Method({
  693. name: 'getBlockByNumber',
  694. call: 'eth_getBlockByNumber',
  695. params: 2,
  696. inputFormatter: [function (blockNumber) {
  697. return blockNumber ? utils.toHex(blockNumber) : 'latest';
  698. }, function () {
  699. return false;
  700. }]
  701. })).createFunction(method.requestManager);
  702. var getGasPrice = (new Method({
  703. name: 'getGasPrice',
  704. call: 'eth_gasPrice',
  705. params: 0
  706. })).createFunction(method.requestManager);
  707. Promise.all([
  708. getBlockByNumber(),
  709. getGasPrice()
  710. ]).then(responses => {
  711. const [block, gasPrice] = responses;
  712. if ((tx.type === '0x2' || tx.type === undefined) &&
  713. (block && block.baseFeePerGas)) {
  714. // The network supports EIP-1559
  715. // Taken from https://github.com/ethers-io/ethers.js/blob/ba6854bdd5a912fe873d5da494cb5c62c190adde/packages/abstract-provider/src.ts/index.ts#L230
  716. let maxPriorityFeePerGas, maxFeePerGas;
  717. if (tx.gasPrice) {
  718. // Using legacy gasPrice property on an eip-1559 network,
  719. // so use gasPrice as both fee properties
  720. maxPriorityFeePerGas = tx.gasPrice;
  721. maxFeePerGas = tx.gasPrice;
  722. delete tx.gasPrice;
  723. }
  724. else {
  725. maxPriorityFeePerGas = tx.maxPriorityFeePerGas || '0x9502F900'; // 2.5 Gwei
  726. maxFeePerGas = tx.maxFeePerGas ||
  727. utils.toHex(utils.toBN(block.baseFeePerGas)
  728. .mul(utils.toBN(2))
  729. .add(utils.toBN(maxPriorityFeePerGas)));
  730. }
  731. resolve({ maxFeePerGas, maxPriorityFeePerGas });
  732. }
  733. else {
  734. if (tx.maxPriorityFeePerGas || tx.maxFeePerGas)
  735. throw Error("Network doesn't support eip-1559");
  736. resolve({ gasPrice });
  737. }
  738. });
  739. }
  740. catch (error) {
  741. reject(error);
  742. }
  743. });
  744. }
  745. /**
  746. * Returns the revert reason string if existing or otherwise false.
  747. *
  748. * @method getRevertReason
  749. *
  750. * @param {Object} txOptions
  751. * @param {Number} blockNumber
  752. *
  753. * @returns {Promise<Boolean|String>}
  754. */
  755. Method.prototype.getRevertReason = function (txOptions, blockNumber) {
  756. var self = this;
  757. return new Promise(function (resolve, reject) {
  758. (new Method({
  759. name: 'call',
  760. call: 'eth_call',
  761. params: 2,
  762. abiCoder: self.abiCoder,
  763. handleRevert: true
  764. }))
  765. .createFunction(self.requestManager)(txOptions, utils.numberToHex(blockNumber))
  766. .then(function () {
  767. resolve(false);
  768. })
  769. .catch(function (error) {
  770. if (error.reason) {
  771. resolve({
  772. reason: error.reason,
  773. signature: error.signature
  774. });
  775. }
  776. else {
  777. reject(error);
  778. }
  779. });
  780. });
  781. };
  782. /**
  783. * Checks if the given hex string is a revert message from the EVM
  784. *
  785. * @method isRevertReasonString
  786. *
  787. * @param {String} data - Hex string prefixed with 0x
  788. *
  789. * @returns {Boolean}
  790. */
  791. Method.prototype.isRevertReasonString = function (data) {
  792. return typeof data === 'string' && ((data.length - 2) / 2) % 32 === 4 && data.substring(0, 10) === '0x08c379a0';
  793. };
  794. /**
  795. * Should be called to create the pure JSONRPC request which can be used in a batch request
  796. *
  797. * @method request
  798. * @return {Object} jsonrpc request
  799. */
  800. Method.prototype.request = function () {
  801. var payload = this.toPayload(Array.prototype.slice.call(arguments));
  802. payload.format = this.formatOutput.bind(this);
  803. return payload;
  804. };
  805. module.exports = Method;