UNPKG

web3-provider-engine

Version:

A JavaScript library for composing Ethereum provider objects using middleware modules

1,055 lines (1,030 loc) 1.47 MB
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ProviderEngine = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ "use strict"; var EventEmitter = require('events').EventEmitter; var inherits = require('util').inherits; var ethUtil = require('@ethereumjs/util'); var _require = require('eth-block-tracker'), PollingBlockTracker = _require.PollingBlockTracker; var map = require('async/map'); var eachSeries = require('async/eachSeries'); var Stoplight = require('./util/stoplight.js'); var cacheUtils = require('./util/rpc-cache-utils.js'); var createPayload = require('./util/create-payload.js'); var noop = function noop() {}; module.exports = Web3ProviderEngine; inherits(Web3ProviderEngine, EventEmitter); function Web3ProviderEngine(opts) { var self = this; EventEmitter.call(self); self.setMaxListeners(30); // parse options opts = opts || {}; // block polling var directProvider = { sendAsync: self._handleAsync.bind(self) }; var blockTrackerProvider = opts.blockTrackerProvider || directProvider; self._blockTracker = opts.blockTracker || new PollingBlockTracker({ provider: blockTrackerProvider, pollingInterval: opts.pollingInterval || 4000, setSkipCacheFlag: true }); // set initialization blocker self._ready = new Stoplight(); // local state self.currentBlock = null; self._providers = []; } // public Web3ProviderEngine.prototype.start = function () { var _this = this; var cb = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : noop; var self = this; // trigger start self._ready.go(); // on new block, request block body and emit as events self._blockTracker.on('latest', function (blockNumber) { // get block body self._getBlockByNumberWithRetry(blockNumber, function (err, block) { if (err) { _this.emit('error', err); return; } if (!block) { console.log(block); _this.emit('error', new Error("Could not find block")); return; } var bufferBlock = toBufferBlock(block); // set current + emit "block" event self._setCurrentBlock(bufferBlock); // emit other events self.emit('rawBlock', block); self.emit('latest', block); }); }); // forward other events self._blockTracker.on('sync', self.emit.bind(self, 'sync')); self._blockTracker.on('error', self.emit.bind(self, 'error')); // update state self._running = true; // signal that we started self.emit('start'); }; Web3ProviderEngine.prototype.stop = function () { var self = this; // stop block polling by removing event listeners self._blockTracker.removeAllListeners(); // update state self._running = false; // signal that we stopped self.emit('stop'); }; Web3ProviderEngine.prototype.isRunning = function () { var self = this; return self._running; }; Web3ProviderEngine.prototype.addProvider = function (source, index) { var self = this; if (typeof index === 'number') { self._providers.splice(index, 0, source); } else { self._providers.push(source); } source.setEngine(this); }; Web3ProviderEngine.prototype.removeProvider = function (source) { var self = this; var index = self._providers.indexOf(source); if (index < 0) throw new Error('Provider not found.'); self._providers.splice(index, 1); }; Web3ProviderEngine.prototype.send = function (payload) { throw new Error('Web3ProviderEngine does not support synchronous requests.'); }; Web3ProviderEngine.prototype.sendAsync = function (payload, cb) { var self = this; self._ready["await"](function () { if (Array.isArray(payload)) { // handle batch map(payload, self._handleAsync.bind(self), cb); } else { // handle single self._handleAsync(payload, cb); } }); }; // private Web3ProviderEngine.prototype._getBlockByNumberWithRetry = function (blockNumber, cb) { var self = this; var retriesRemaining = 5; attemptRequest(); return; function attemptRequest() { self._getBlockByNumber(blockNumber, afterRequest); } function afterRequest(err, block) { // anomalous error occurred if (err) return cb(err); // block not ready yet if (!block) { if (retriesRemaining > 0) { // wait 1s then try again retriesRemaining--; setTimeout(function () { attemptRequest(); }, 1000); return; } else { // give up, return a null block cb(null, null); return; } } // otherwise return result cb(null, block); return; } }; Web3ProviderEngine.prototype._getBlockByNumber = function (blockNumber, cb) { var req = createPayload({ method: 'eth_getBlockByNumber', params: [blockNumber, false], skipCache: true }); this._handleAsync(req, function (err, res) { if (err) return cb(err); return cb(null, res.result); }); }; Web3ProviderEngine.prototype._handleAsync = function (payload, finished) { var self = this; var currentProvider = -1; var result = null; var error = null; var stack = []; next(); function next(after) { currentProvider += 1; stack.unshift(after); // Bubbled down as far as we could go, and the request wasn't // handled. Return an error. if (currentProvider >= self._providers.length) { end(new Error('Request for method "' + payload.method + '" not handled by any subprovider. Please check your subprovider configuration to ensure this method is handled.')); } else { try { var provider = self._providers[currentProvider]; provider.handleRequest(payload, next, end); } catch (e) { end(e); } } } function end(_error, _result) { error = _error; result = _result; eachSeries(stack, function (fn, callback) { if (fn) { fn(error, result, callback); } else { callback(); } }, function () { var resultObj = { id: payload.id, jsonrpc: payload.jsonrpc, result: result }; if (error != null) { resultObj.error = { message: error.stack || error.message || error, code: -32000 }; // respond with both error formats finished(error, resultObj); } else { finished(null, resultObj); } }); } }; // // from remote-data // Web3ProviderEngine.prototype._setCurrentBlock = function (block) { var self = this; self.currentBlock = block; self.emit('block', block); }; // util function toBufferBlock(jsonBlock) { return { number: ethUtil.toBuffer(jsonBlock.number), hash: ethUtil.toBuffer(jsonBlock.hash), parentHash: ethUtil.toBuffer(jsonBlock.parentHash), nonce: ethUtil.toBuffer(jsonBlock.nonce), mixHash: ethUtil.toBuffer(jsonBlock.mixHash), sha3Uncles: ethUtil.toBuffer(jsonBlock.sha3Uncles), logsBloom: ethUtil.toBuffer(jsonBlock.logsBloom), transactionsRoot: ethUtil.toBuffer(jsonBlock.transactionsRoot), stateRoot: ethUtil.toBuffer(jsonBlock.stateRoot), receiptsRoot: ethUtil.toBuffer(jsonBlock.receiptRoot || jsonBlock.receiptsRoot), miner: ethUtil.toBuffer(jsonBlock.miner), difficulty: ethUtil.toBuffer(jsonBlock.difficulty), totalDifficulty: ethUtil.toBuffer(jsonBlock.totalDifficulty), size: ethUtil.toBuffer(jsonBlock.size), extraData: ethUtil.toBuffer(jsonBlock.extraData), gasLimit: ethUtil.toBuffer(jsonBlock.gasLimit), gasUsed: ethUtil.toBuffer(jsonBlock.gasUsed), timestamp: ethUtil.toBuffer(jsonBlock.timestamp), transactions: jsonBlock.transactions }; } },{"./util/create-payload.js":275,"./util/rpc-cache-utils.js":277,"./util/stoplight.js":278,"@ethereumjs/util":10,"async/eachSeries":117,"async/map":132,"eth-block-tracker":157,"events":162,"util":272}],2:[function(require,module,exports){ "use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports.RLP = exports.utils = exports.decode = exports.encode = void 0; /** * RLP Encoding based on https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/ * This function takes in data, converts it to Uint8Array if not, * and adds a length for recursion. * @param input Will be converted to Uint8Array * @returns Uint8Array of encoded data **/ function encode(input) { if (Array.isArray(input)) { var output = []; var outputLength = 0; for (var i = 0; i < input.length; i++) { var encoded = encode(input[i]); output.push(encoded); outputLength += encoded.length; } return concatBytes.apply(void 0, [encodeLength(outputLength, 192)].concat(output)); } var inputBuf = toBytes(input); if (inputBuf.length === 1 && inputBuf[0] < 128) { return inputBuf; } return concatBytes(encodeLength(inputBuf.length, 128), inputBuf); } exports.encode = encode; /** * Slices a Uint8Array, throws if the slice goes out-of-bounds of the Uint8Array. * E.g. `safeSlice(hexToBytes('aa'), 1, 2)` will throw. * @param input * @param start * @param end */ function safeSlice(input, start, end) { if (end > input.length) { throw new Error('invalid RLP (safeSlice): end slice of Uint8Array out-of-bounds'); } return input.slice(start, end); } /** * Parse integers. Check if there is no leading zeros * @param v The value to parse */ function decodeLength(v) { if (v[0] === 0) { throw new Error('invalid RLP: extra zeros'); } return parseHexByte(bytesToHex(v)); } function encodeLength(len, offset) { if (len < 56) { return Uint8Array.from([len + offset]); } var hexLength = numberToHex(len); var lLength = hexLength.length / 2; var firstByte = numberToHex(offset + 55 + lLength); return Uint8Array.from(hexToBytes(firstByte + hexLength)); } function decode(input) { var stream = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (typeof input === 'undefined' || input === null || input.length === 0) { return Uint8Array.from([]); } var inputBytes = toBytes(input); var decoded = _decode(inputBytes); if (stream) { return decoded; } if (decoded.remainder.length !== 0) { throw new Error('invalid RLP: remainder must be zero'); } return decoded.data; } exports.decode = decode; /** Decode an input with RLP */ function _decode(input) { var length, llength, data, innerRemainder, d; var decoded = []; var firstByte = input[0]; if (firstByte <= 0x7f) { // a single byte whose value is in the [0x00, 0x7f] range, that byte is its own RLP encoding. return { data: input.slice(0, 1), remainder: input.slice(1) }; } else if (firstByte <= 0xb7) { // string is 0-55 bytes long. A single byte with value 0x80 plus the length of the string followed by the string // The range of the first byte is [0x80, 0xb7] length = firstByte - 0x7f; // set 0x80 null to 0 if (firstByte === 0x80) { data = Uint8Array.from([]); } else { data = safeSlice(input, 1, length); } if (length === 2 && data[0] < 0x80) { throw new Error('invalid RLP encoding: invalid prefix, single byte < 0x80 are not prefixed'); } return { data: data, remainder: input.slice(length) }; } else if (firstByte <= 0xbf) { // string is greater than 55 bytes long. A single byte with the value (0xb7 plus the length of the length), // followed by the length, followed by the string llength = firstByte - 0xb6; if (input.length - 1 < llength) { throw new Error('invalid RLP: not enough bytes for string length'); } length = decodeLength(safeSlice(input, 1, llength)); if (length <= 55) { throw new Error('invalid RLP: expected string length to be greater than 55'); } data = safeSlice(input, llength, length + llength); return { data: data, remainder: input.slice(length + llength) }; } else if (firstByte <= 0xf7) { // a list between 0-55 bytes long length = firstByte - 0xbf; innerRemainder = safeSlice(input, 1, length); while (innerRemainder.length) { d = _decode(innerRemainder); decoded.push(d.data); innerRemainder = d.remainder; } return { data: decoded, remainder: input.slice(length) }; } else { // a list over 55 bytes long llength = firstByte - 0xf6; length = decodeLength(safeSlice(input, 1, llength)); if (length < 56) { throw new Error('invalid RLP: encoded list too short'); } var totalLength = llength + length; if (totalLength > input.length) { throw new Error('invalid RLP: total length is larger than the data'); } innerRemainder = safeSlice(input, llength, totalLength); while (innerRemainder.length) { d = _decode(innerRemainder); decoded.push(d.data); innerRemainder = d.remainder; } return { data: decoded, remainder: input.slice(totalLength) }; } } var cachedHexes = Array.from({ length: 256 }, function (_v, i) { return i.toString(16).padStart(2, '0'); }); function bytesToHex(uint8a) { // Pre-caching chars with `cachedHexes` speeds this up 6x var hex = ''; for (var i = 0; i < uint8a.length; i++) { hex += cachedHexes[uint8a[i]]; } return hex; } function parseHexByte(hexByte) { var _byte = Number.parseInt(hexByte, 16); if (Number.isNaN(_byte)) throw new Error('Invalid byte sequence'); return _byte; } // Caching slows it down 2-3x function hexToBytes(hex) { if (typeof hex !== 'string') { throw new TypeError('hexToBytes: expected string, got ' + _typeof(hex)); } if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex'); var array = new Uint8Array(hex.length / 2); for (var i = 0; i < array.length; i++) { var j = i * 2; array[i] = parseHexByte(hex.slice(j, j + 2)); } return array; } /** Concatenates two Uint8Arrays into one. */ function concatBytes() { for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { arrays[_key] = arguments[_key]; } if (arrays.length === 1) return arrays[0]; var length = arrays.reduce(function (a, arr) { return a + arr.length; }, 0); var result = new Uint8Array(length); for (var i = 0, pad = 0; i < arrays.length; i++) { var arr = arrays[i]; result.set(arr, pad); pad += arr.length; } return result; } function utf8ToBytes(utf) { return new TextEncoder().encode(utf); } /** Transform an integer into its hexadecimal value */ function numberToHex(integer) { if (integer < 0) { throw new Error('Invalid integer as argument, must be unsigned!'); } var hex = integer.toString(16); return hex.length % 2 ? "0".concat(hex) : hex; } /** Pad a string to be even */ function padToEven(a) { return a.length % 2 ? "0".concat(a) : a; } /** Check if a string is prefixed by 0x */ function isHexPrefixed(str) { return str.length >= 2 && str[0] === '0' && str[1] === 'x'; } /** Removes 0x from a given String */ function stripHexPrefix(str) { if (typeof str !== 'string') { return str; } return isHexPrefixed(str) ? str.slice(2) : str; } /** Transform anything into a Uint8Array */ function toBytes(v) { if (v instanceof Uint8Array) { return v; } if (typeof v === 'string') { if (isHexPrefixed(v)) { return hexToBytes(padToEven(stripHexPrefix(v))); } return utf8ToBytes(v); } if (typeof v === 'number' || typeof v === 'bigint') { if (!v) { return Uint8Array.from([]); } return hexToBytes(numberToHex(v)); } if (v === null || v === undefined) { return Uint8Array.from([]); } throw new Error('toBytes: received unsupported type ' + _typeof(v)); } exports.utils = { bytesToHex: bytesToHex, concatBytes: concatBytes, hexToBytes: hexToBytes, utf8ToBytes: utf8ToBytes }; exports.RLP = { encode: encode, decode: decode }; },{}],3:[function(require,module,exports){ (function (Buffer){(function (){ "use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } Object.defineProperty(exports, "__esModule", { value: true }); exports.accountBodyToRLP = exports.accountBodyToSlim = exports.accountBodyFromSlim = exports.isZeroAddress = exports.zeroAddress = exports.importPublic = exports.privateToAddress = exports.privateToPublic = exports.publicToAddress = exports.pubToAddress = exports.isValidPublic = exports.isValidPrivate = exports.generateAddress2 = exports.generateAddress = exports.isValidChecksumAddress = exports.toChecksumAddress = exports.isValidAddress = exports.Account = void 0; var rlp_1 = require("@ethereumjs/rlp"); var keccak_1 = require("ethereum-cryptography/keccak"); var secp256k1_1 = require("ethereum-cryptography/secp256k1"); var utils_1 = require("ethereum-cryptography/utils"); var bytes_1 = require("./bytes"); var constants_1 = require("./constants"); var helpers_1 = require("./helpers"); var internal_1 = require("./internal"); var _0n = BigInt(0); var Account = /*#__PURE__*/function () { /** * This constructor assigns and validates the values. * Use the static factory methods to assist in creating an Account from varying data types. */ function Account() { var nonce = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _0n; var balance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _0n; var storageRoot = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : constants_1.KECCAK256_RLP; var codeHash = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : constants_1.KECCAK256_NULL; _classCallCheck(this, Account); this.nonce = nonce; this.balance = balance; this.storageRoot = storageRoot; this.codeHash = codeHash; this._validate(); } _createClass(Account, [{ key: "_validate", value: function _validate() { if (this.nonce < _0n) { throw new Error('nonce must be greater than zero'); } if (this.balance < _0n) { throw new Error('balance must be greater than zero'); } if (this.storageRoot.length !== 32) { throw new Error('storageRoot must have a length of 32'); } if (this.codeHash.length !== 32) { throw new Error('codeHash must have a length of 32'); } } /** * Returns a Buffer Array of the raw Buffers for the account, in order. */ }, { key: "raw", value: function raw() { return [(0, bytes_1.bigIntToUnpaddedBuffer)(this.nonce), (0, bytes_1.bigIntToUnpaddedBuffer)(this.balance), this.storageRoot, this.codeHash]; } /** * Returns the RLP serialization of the account as a `Buffer`. */ }, { key: "serialize", value: function serialize() { return Buffer.from(rlp_1.RLP.encode((0, bytes_1.bufArrToArr)(this.raw()))); } /** * Returns a `Boolean` determining if the account is a contract. */ }, { key: "isContract", value: function isContract() { return !this.codeHash.equals(constants_1.KECCAK256_NULL); } /** * Returns a `Boolean` determining if the account is empty complying to the definition of * account emptiness in [EIP-161](https://eips.ethereum.org/EIPS/eip-161): * "An account is considered empty when it has no code and zero nonce and zero balance." */ }, { key: "isEmpty", value: function isEmpty() { return this.balance === _0n && this.nonce === _0n && this.codeHash.equals(constants_1.KECCAK256_NULL); } }], [{ key: "fromAccountData", value: function fromAccountData(accountData) { var nonce = accountData.nonce, balance = accountData.balance, storageRoot = accountData.storageRoot, codeHash = accountData.codeHash; return new Account(nonce !== undefined ? (0, bytes_1.bufferToBigInt)((0, bytes_1.toBuffer)(nonce)) : undefined, balance !== undefined ? (0, bytes_1.bufferToBigInt)((0, bytes_1.toBuffer)(balance)) : undefined, storageRoot !== undefined ? (0, bytes_1.toBuffer)(storageRoot) : undefined, codeHash !== undefined ? (0, bytes_1.toBuffer)(codeHash) : undefined); } }, { key: "fromRlpSerializedAccount", value: function fromRlpSerializedAccount(serialized) { var values = (0, bytes_1.arrToBufArr)(rlp_1.RLP.decode(Uint8Array.from(serialized))); if (!Array.isArray(values)) { throw new Error('Invalid serialized account input. Must be array'); } return this.fromValuesArray(values); } }, { key: "fromValuesArray", value: function fromValuesArray(values) { var _values = _slicedToArray(values, 4), nonce = _values[0], balance = _values[1], storageRoot = _values[2], codeHash = _values[3]; return new Account((0, bytes_1.bufferToBigInt)(nonce), (0, bytes_1.bufferToBigInt)(balance), storageRoot, codeHash); } }]); return Account; }(); exports.Account = Account; /** * Checks if the address is a valid. Accepts checksummed addresses too. */ var isValidAddress = function isValidAddress(hexAddress) { try { (0, helpers_1.assertIsString)(hexAddress); } catch (e) { return false; } return /^0x[0-9a-fA-F]{40}$/.test(hexAddress); }; exports.isValidAddress = isValidAddress; /** * Returns a checksummed address. * * If an eip1191ChainId is provided, the chainId will be included in the checksum calculation. This * has the effect of checksummed addresses for one chain having invalid checksums for others. * For more details see [EIP-1191](https://eips.ethereum.org/EIPS/eip-1191). * * WARNING: Checksums with and without the chainId will differ and the EIP-1191 checksum is not * backwards compatible to the original widely adopted checksum format standard introduced in * [EIP-55](https://eips.ethereum.org/EIPS/eip-55), so this will break in existing applications. * Usage of this EIP is therefore discouraged unless you have a very targeted use case. */ var toChecksumAddress = function toChecksumAddress(hexAddress, eip1191ChainId) { (0, helpers_1.assertIsHexString)(hexAddress); var address = (0, internal_1.stripHexPrefix)(hexAddress).toLowerCase(); var prefix = ''; if (eip1191ChainId !== undefined) { var chainId = (0, bytes_1.bufferToBigInt)((0, bytes_1.toBuffer)(eip1191ChainId)); prefix = chainId.toString() + '0x'; } var buf = Buffer.from(prefix + address, 'utf8'); var hash = (0, utils_1.bytesToHex)((0, keccak_1.keccak256)(buf)); var ret = '0x'; for (var i = 0; i < address.length; i++) { if (parseInt(hash[i], 16) >= 8) { ret += address[i].toUpperCase(); } else { ret += address[i]; } } return ret; }; exports.toChecksumAddress = toChecksumAddress; /** * Checks if the address is a valid checksummed address. * * See toChecksumAddress' documentation for details about the eip1191ChainId parameter. */ var isValidChecksumAddress = function isValidChecksumAddress(hexAddress, eip1191ChainId) { return (0, exports.isValidAddress)(hexAddress) && (0, exports.toChecksumAddress)(hexAddress, eip1191ChainId) === hexAddress; }; exports.isValidChecksumAddress = isValidChecksumAddress; /** * Generates an address of a newly created contract. * @param from The address which is creating this new address * @param nonce The nonce of the from account */ var generateAddress = function generateAddress(from, nonce) { (0, helpers_1.assertIsBuffer)(from); (0, helpers_1.assertIsBuffer)(nonce); if ((0, bytes_1.bufferToBigInt)(nonce) === BigInt(0)) { // in RLP we want to encode null in the case of zero nonce // read the RLP documentation for an answer if you dare return Buffer.from((0, keccak_1.keccak256)(rlp_1.RLP.encode((0, bytes_1.bufArrToArr)([from, null])))).slice(-20); } // Only take the lower 160bits of the hash return Buffer.from((0, keccak_1.keccak256)(rlp_1.RLP.encode((0, bytes_1.bufArrToArr)([from, nonce])))).slice(-20); }; exports.generateAddress = generateAddress; /** * Generates an address for a contract created using CREATE2. * @param from The address which is creating this new address * @param salt A salt * @param initCode The init code of the contract being created */ var generateAddress2 = function generateAddress2(from, salt, initCode) { (0, helpers_1.assertIsBuffer)(from); (0, helpers_1.assertIsBuffer)(salt); (0, helpers_1.assertIsBuffer)(initCode); if (from.length !== 20) { throw new Error('Expected from to be of length 20'); } if (salt.length !== 32) { throw new Error('Expected salt to be of length 32'); } var address = (0, keccak_1.keccak256)(Buffer.concat([Buffer.from('ff', 'hex'), from, salt, (0, keccak_1.keccak256)(initCode)])); return (0, bytes_1.toBuffer)(address).slice(-20); }; exports.generateAddress2 = generateAddress2; /** * Checks if the private key satisfies the rules of the curve secp256k1. */ var isValidPrivate = function isValidPrivate(privateKey) { return secp256k1_1.secp256k1.utils.isValidPrivateKey(privateKey); }; exports.isValidPrivate = isValidPrivate; /** * Checks if the public key satisfies the rules of the curve secp256k1 * and the requirements of Ethereum. * @param publicKey The two points of an uncompressed key, unless sanitize is enabled * @param sanitize Accept public keys in other formats */ var isValidPublic = function isValidPublic(publicKey) { var sanitize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; (0, helpers_1.assertIsBuffer)(publicKey); if (publicKey.length === 64) { // Convert to SEC1 for secp256k1 // Automatically checks whether point is on curve try { secp256k1_1.secp256k1.ProjectivePoint.fromHex(Buffer.concat([Buffer.from([4]), publicKey])); return true; } catch (e) { return false; } } if (!sanitize) { return false; } try { secp256k1_1.secp256k1.ProjectivePoint.fromHex(publicKey); return true; } catch (e) { return false; } }; exports.isValidPublic = isValidPublic; /** * Returns the ethereum address of a given public key. * Accepts "Ethereum public keys" and SEC1 encoded keys. * @param pubKey The two points of an uncompressed key, unless sanitize is enabled * @param sanitize Accept public keys in other formats */ var pubToAddress = function pubToAddress(pubKey) { var sanitize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; (0, helpers_1.assertIsBuffer)(pubKey); if (sanitize && pubKey.length !== 64) { pubKey = Buffer.from(secp256k1_1.secp256k1.ProjectivePoint.fromHex(pubKey).toRawBytes(false).slice(1)); } if (pubKey.length !== 64) { throw new Error('Expected pubKey to be of length 64'); } // Only take the lower 160bits of the hash return Buffer.from((0, keccak_1.keccak256)(pubKey)).slice(-20); }; exports.pubToAddress = pubToAddress; exports.publicToAddress = exports.pubToAddress; /** * Returns the ethereum public key of a given private key. * @param privateKey A private key must be 256 bits wide */ var privateToPublic = function privateToPublic(privateKey) { (0, helpers_1.assertIsBuffer)(privateKey); // skip the type flag and use the X, Y points return Buffer.from(secp256k1_1.secp256k1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(false).slice(1)); }; exports.privateToPublic = privateToPublic; /** * Returns the ethereum address of a given private key. * @param privateKey A private key must be 256 bits wide */ var privateToAddress = function privateToAddress(privateKey) { return (0, exports.publicToAddress)((0, exports.privateToPublic)(privateKey)); }; exports.privateToAddress = privateToAddress; /** * Converts a public key to the Ethereum format. */ var importPublic = function importPublic(publicKey) { (0, helpers_1.assertIsBuffer)(publicKey); if (publicKey.length !== 64) { publicKey = Buffer.from(secp256k1_1.secp256k1.ProjectivePoint.fromHex(publicKey).toRawBytes(false).slice(1)); } return publicKey; }; exports.importPublic = importPublic; /** * Returns the zero address. */ var zeroAddress = function zeroAddress() { var addressLength = 20; var addr = (0, bytes_1.zeros)(addressLength); return (0, bytes_1.bufferToHex)(addr); }; exports.zeroAddress = zeroAddress; /** * Checks if a given address is the zero address. */ var isZeroAddress = function isZeroAddress(hexAddress) { try { (0, helpers_1.assertIsString)(hexAddress); } catch (e) { return false; } var zeroAddr = (0, exports.zeroAddress)(); return zeroAddr === hexAddress; }; exports.isZeroAddress = isZeroAddress; function accountBodyFromSlim(body) { var _body = _slicedToArray(body, 4), nonce = _body[0], balance = _body[1], storageRoot = _body[2], codeHash = _body[3]; return [nonce, balance, (0, bytes_1.arrToBufArr)(storageRoot).length === 0 ? constants_1.KECCAK256_RLP : storageRoot, (0, bytes_1.arrToBufArr)(codeHash).length === 0 ? constants_1.KECCAK256_NULL : codeHash]; } exports.accountBodyFromSlim = accountBodyFromSlim; var emptyUint8Arr = new Uint8Array(0); function accountBodyToSlim(body) { var _body2 = _slicedToArray(body, 4), nonce = _body2[0], balance = _body2[1], storageRoot = _body2[2], codeHash = _body2[3]; return [nonce, balance, (0, bytes_1.arrToBufArr)(storageRoot).equals(constants_1.KECCAK256_RLP) ? emptyUint8Arr : storageRoot, (0, bytes_1.arrToBufArr)(codeHash).equals(constants_1.KECCAK256_NULL) ? emptyUint8Arr : codeHash]; } exports.accountBodyToSlim = accountBodyToSlim; /** * Converts a slim account (per snap protocol spec) to the RLP encoded version of the account * @param body Array of 4 Buffer-like items to represent the account * @returns RLP encoded version of the account */ function accountBodyToRLP(body) { var couldBeSlim = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var accountBody = couldBeSlim ? accountBodyFromSlim(body) : body; return (0, bytes_1.arrToBufArr)(rlp_1.RLP.encode(accountBody)); } exports.accountBodyToRLP = accountBodyToRLP; }).call(this)}).call(this,require("buffer").Buffer) },{"./bytes":6,"./constants":7,"./helpers":9,"./internal":11,"@ethereumjs/rlp":2,"buffer":138,"ethereum-cryptography/keccak":159,"ethereum-cryptography/secp256k1":160,"ethereum-cryptography/utils":161}],4:[function(require,module,exports){ (function (Buffer){(function (){ "use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } Object.defineProperty(exports, "__esModule", { value: true }); exports.Address = void 0; var account_1 = require("./account"); var bytes_1 = require("./bytes"); /** * Handling and generating Ethereum addresses */ var Address = /*#__PURE__*/function () { function Address(buf) { _classCallCheck(this, Address); if (buf.length !== 20) { throw new Error('Invalid address length'); } this.buf = buf; } /** * Returns the zero address. */ _createClass(Address, [{ key: "equals", value: /** * Is address equal to another. */ function equals(address) { return this.buf.equals(address.buf); } /** * Is address zero. */ }, { key: "isZero", value: function isZero() { return this.equals(Address.zero()); } /** * True if address is in the address range defined * by EIP-1352 */ }, { key: "isPrecompileOrSystemAddress", value: function isPrecompileOrSystemAddress() { var address = (0, bytes_1.bufferToBigInt)(this.buf); var rangeMin = BigInt(0); var rangeMax = BigInt('0xffff'); return address >= rangeMin && address <= rangeMax; } /** * Returns hex encoding of address. */ }, { key: "toString", value: function toString() { return '0x' + this.buf.toString('hex'); } /** * Returns Buffer representation of address. */ }, { key: "toBuffer", value: function toBuffer() { return Buffer.from(this.buf); } }], [{ key: "zero", value: function zero() { return new Address((0, bytes_1.zeros)(20)); } /** * Returns an Address object from a hex-encoded string. * @param str - Hex-encoded address */ }, { key: "fromString", value: function fromString(str) { if (!(0, account_1.isValidAddress)(str)) { throw new Error('Invalid address'); } return new Address((0, bytes_1.toBuffer)(str)); } /** * Returns an address for a given public key. * @param pubKey The two points of an uncompressed key */ }, { key: "fromPublicKey", value: function fromPublicKey(pubKey) { if (!Buffer.isBuffer(pubKey)) { throw new Error('Public key should be Buffer'); } var buf = (0, account_1.pubToAddress)(pubKey); return new Address(buf); } /** * Returns an address for a given private key. * @param privateKey A private key must be 256 bits wide */ }, { key: "fromPrivateKey", value: function fromPrivateKey(privateKey) { if (!Buffer.isBuffer(privateKey)) { throw new Error('Private key should be Buffer'); } var buf = (0, account_1.privateToAddress)(privateKey); return new Address(buf); } /** * Generates an address for a newly created contract. * @param from The address which is creating this new address * @param nonce The nonce of the from account */ }, { key: "generate", value: function generate(from, nonce) { if (typeof nonce !== 'bigint') { throw new Error('Expected nonce to be a bigint'); } return new Address((0, account_1.generateAddress)(from.buf, (0, bytes_1.bigIntToBuffer)(nonce))); } /** * Generates an address for a contract created using CREATE2. * @param from The address which is creating this new address * @param salt A salt * @param initCode The init code of the contract being created */ }, { key: "generate2", value: function generate2(from, salt, initCode) { if (!Buffer.isBuffer(salt)) { throw new Error('Expected salt to be a Buffer'); } if (!Buffer.isBuffer(initCode)) { throw new Error('Expected initCode to be a Buffer'); } return new Address((0, account_1.generateAddress2)(from.buf, salt, initCode)); } }]); return Address; }(); exports.Address = Address; }).call(this)}).call(this,require("buffer").Buffer) },{"./account":3,"./bytes":6,"buffer":138}],5:[function(require,module,exports){ "use strict"; /** * Ported to Typescript from original implementation below: * https://github.com/ahultgren/async-eventemitter -- MIT licensed * * Type Definitions based on work by: patarapolw <https://github.com/patarapolw> -- MIT licensed * that was contributed to Definitely Typed below: * https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/async-eventemitter */ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function _classCallC