UNPKG

ripple-lib

Version:

Deprecated - consider migrating to xrpl.js: https://xrpl.org/xrpljs2-migration-guide.html

86 lines (66 loc) 2.93 MB
/* * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development"). * This devtool is neither made for production nor for readable output files. * It uses "eval()" calls to create a separate source file in the browser devtools. * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/) * or disable the default devtool with "devtool: false". * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/). */ var ripple; /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ "./dist/npm/api.js": /*!*************************!*\ !*** ./dist/npm/api.js ***! \*************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; eval("\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.RippleAPI = void 0;\nconst events_1 = __webpack_require__(/*! events */ \"./node_modules/events/events.js\");\nconst common_1 = __webpack_require__(/*! ./common */ \"./dist/npm/common/index.js\");\nconst server_1 = __webpack_require__(/*! ./server/server */ \"./dist/npm/server/server.js\");\nconst transaction_1 = __importDefault(__webpack_require__(/*! ./ledger/transaction */ \"./dist/npm/ledger/transaction.js\"));\nconst transactions_1 = __importDefault(__webpack_require__(/*! ./ledger/transactions */ \"./dist/npm/ledger/transactions.js\"));\nconst trustlines_1 = __importDefault(__webpack_require__(/*! ./ledger/trustlines */ \"./dist/npm/ledger/trustlines.js\"));\nconst balances_1 = __importDefault(__webpack_require__(/*! ./ledger/balances */ \"./dist/npm/ledger/balances.js\"));\nconst balance_sheet_1 = __importDefault(__webpack_require__(/*! ./ledger/balance-sheet */ \"./dist/npm/ledger/balance-sheet.js\"));\nconst pathfind_1 = __importDefault(__webpack_require__(/*! ./ledger/pathfind */ \"./dist/npm/ledger/pathfind.js\"));\nconst orders_1 = __importDefault(__webpack_require__(/*! ./ledger/orders */ \"./dist/npm/ledger/orders.js\"));\nconst orderbook_1 = __webpack_require__(/*! ./ledger/orderbook */ \"./dist/npm/ledger/orderbook.js\");\nconst settings_1 = __webpack_require__(/*! ./ledger/settings */ \"./dist/npm/ledger/settings.js\");\nconst accountinfo_1 = __importDefault(__webpack_require__(/*! ./ledger/accountinfo */ \"./dist/npm/ledger/accountinfo.js\"));\nconst accountobjects_1 = __importDefault(__webpack_require__(/*! ./ledger/accountobjects */ \"./dist/npm/ledger/accountobjects.js\"));\nconst payment_channel_1 = __importDefault(__webpack_require__(/*! ./ledger/payment-channel */ \"./dist/npm/ledger/payment-channel.js\"));\nconst payment_1 = __importDefault(__webpack_require__(/*! ./transaction/payment */ \"./dist/npm/transaction/payment.js\"));\nconst trustline_1 = __importDefault(__webpack_require__(/*! ./transaction/trustline */ \"./dist/npm/transaction/trustline.js\"));\nconst order_1 = __importDefault(__webpack_require__(/*! ./transaction/order */ \"./dist/npm/transaction/order.js\"));\nconst ordercancellation_1 = __importDefault(__webpack_require__(/*! ./transaction/ordercancellation */ \"./dist/npm/transaction/ordercancellation.js\"));\nconst escrow_creation_1 = __importDefault(__webpack_require__(/*! ./transaction/escrow-creation */ \"./dist/npm/transaction/escrow-creation.js\"));\nconst escrow_execution_1 = __importDefault(__webpack_require__(/*! ./transaction/escrow-execution */ \"./dist/npm/transaction/escrow-execution.js\"));\nconst escrow_cancellation_1 = __importDefault(__webpack_require__(/*! ./transaction/escrow-cancellation */ \"./dist/npm/transaction/escrow-cancellation.js\"));\nconst payment_channel_create_1 = __importDefault(__webpack_require__(/*! ./transaction/payment-channel-create */ \"./dist/npm/transaction/payment-channel-create.js\"));\nconst payment_channel_fund_1 = __importDefault(__webpack_require__(/*! ./transaction/payment-channel-fund */ \"./dist/npm/transaction/payment-channel-fund.js\"));\nconst payment_channel_claim_1 = __importDefault(__webpack_require__(/*! ./transaction/payment-channel-claim */ \"./dist/npm/transaction/payment-channel-claim.js\"));\nconst check_create_1 = __importDefault(__webpack_require__(/*! ./transaction/check-create */ \"./dist/npm/transaction/check-create.js\"));\nconst check_cancel_1 = __importDefault(__webpack_require__(/*! ./transaction/check-cancel */ \"./dist/npm/transaction/check-cancel.js\"));\nconst check_cash_1 = __importDefault(__webpack_require__(/*! ./transaction/check-cash */ \"./dist/npm/transaction/check-cash.js\"));\nconst settings_2 = __importDefault(__webpack_require__(/*! ./transaction/settings */ \"./dist/npm/transaction/settings.js\"));\nconst ticket_1 = __importDefault(__webpack_require__(/*! ./transaction/ticket */ \"./dist/npm/transaction/ticket.js\"));\nconst sign_1 = __importDefault(__webpack_require__(/*! ./transaction/sign */ \"./dist/npm/transaction/sign.js\"));\nconst combine_1 = __importDefault(__webpack_require__(/*! ./transaction/combine */ \"./dist/npm/transaction/combine.js\"));\nconst submit_1 = __importDefault(__webpack_require__(/*! ./transaction/submit */ \"./dist/npm/transaction/submit.js\"));\nconst utils_1 = __webpack_require__(/*! ./offline/utils */ \"./dist/npm/offline/utils.js\");\nconst derive_1 = __webpack_require__(/*! ./offline/derive */ \"./dist/npm/offline/derive.js\");\nconst ledgerhash_1 = __importDefault(__webpack_require__(/*! ./offline/ledgerhash */ \"./dist/npm/offline/ledgerhash.js\"));\nconst sign_payment_channel_claim_1 = __importDefault(__webpack_require__(/*! ./offline/sign-payment-channel-claim */ \"./dist/npm/offline/sign-payment-channel-claim.js\"));\nconst verify_payment_channel_claim_1 = __importDefault(__webpack_require__(/*! ./offline/verify-payment-channel-claim */ \"./dist/npm/offline/verify-payment-channel-claim.js\"));\nconst ledger_1 = __importDefault(__webpack_require__(/*! ./ledger/ledger */ \"./dist/npm/ledger/ledger.js\"));\nconst rangeset_1 = __importDefault(__webpack_require__(/*! ./common/rangeset */ \"./dist/npm/common/rangeset.js\"));\nconst ledgerUtils = __importStar(__webpack_require__(/*! ./ledger/utils */ \"./dist/npm/ledger/utils.js\"));\nconst transactionUtils = __importStar(__webpack_require__(/*! ./transaction/utils */ \"./dist/npm/transaction/utils.js\"));\nconst schemaValidator = __importStar(__webpack_require__(/*! ./common/schema-validator */ \"./dist/npm/common/schema-validator.js\"));\nconst serverinfo_1 = __webpack_require__(/*! ./common/serverinfo */ \"./dist/npm/common/serverinfo.js\");\nconst utils_2 = __webpack_require__(/*! ./ledger/utils */ \"./dist/npm/ledger/utils.js\");\nconst ripple_address_codec_1 = __webpack_require__(/*! ripple-address-codec */ \"./node_modules/ripple-address-codec/dist/index.js\");\nconst hashes_1 = __webpack_require__(/*! ./common/hashes */ \"./dist/npm/common/hashes/index.js\");\nconst wallet_generation_1 = __importDefault(__webpack_require__(/*! ./wallet/wallet-generation */ \"./dist/npm/wallet/wallet-generation.js\"));\nfunction getCollectKeyFromCommand(command) {\n switch (command) {\n case 'account_offers':\n case 'book_offers':\n return 'offers';\n case 'account_lines':\n return 'lines';\n default:\n return undefined;\n }\n}\nclass RippleAPI extends events_1.EventEmitter {\n constructor(options = {}) {\n super();\n this.generateAddress = utils_1.generateAddress;\n this.generateXAddress = utils_1.generateXAddress;\n this.connect = server_1.connect;\n this.disconnect = server_1.disconnect;\n this.isConnected = server_1.isConnected;\n this.getServerInfo = serverinfo_1.getServerInfo;\n this.getFee = serverinfo_1.getFee;\n this.getLedgerVersion = server_1.getLedgerVersion;\n this.getTransaction = transaction_1.default;\n this.getTransactions = transactions_1.default;\n this.getTrustlines = trustlines_1.default;\n this.getBalances = balances_1.default;\n this.getBalanceSheet = balance_sheet_1.default;\n this.getPaths = pathfind_1.default;\n this.getOrderbook = orderbook_1.getOrderbook;\n this.getOrders = orders_1.default;\n this.getSettings = settings_1.getSettings;\n this.getAccountInfo = accountinfo_1.default;\n this.getAccountObjects = accountobjects_1.default;\n this.getPaymentChannel = payment_channel_1.default;\n this.getLedger = ledger_1.default;\n this.parseAccountFlags = settings_1.parseAccountFlags;\n this.preparePayment = payment_1.default;\n this.prepareTrustline = trustline_1.default;\n this.prepareOrder = order_1.default;\n this.prepareOrderCancellation = ordercancellation_1.default;\n this.prepareEscrowCreation = escrow_creation_1.default;\n this.prepareEscrowExecution = escrow_execution_1.default;\n this.prepareEscrowCancellation = escrow_cancellation_1.default;\n this.preparePaymentChannelCreate = payment_channel_create_1.default;\n this.preparePaymentChannelFund = payment_channel_fund_1.default;\n this.preparePaymentChannelClaim = payment_channel_claim_1.default;\n this.prepareCheckCreate = check_create_1.default;\n this.prepareCheckCash = check_cash_1.default;\n this.prepareCheckCancel = check_cancel_1.default;\n this.prepareTicketCreate = ticket_1.default;\n this.prepareSettings = settings_2.default;\n this.sign = sign_1.default;\n this.combine = combine_1.default;\n this.submit = submit_1.default;\n this.deriveKeypair = derive_1.deriveKeypair;\n this.deriveAddress = derive_1.deriveAddress;\n this.computeLedgerHash = ledgerhash_1.default;\n this.signPaymentChannelClaim = sign_payment_channel_claim_1.default;\n this.verifyPaymentChannelClaim = verify_payment_channel_claim_1.default;\n this.generateFaucetWallet = wallet_generation_1.default;\n this.errors = common_1.errors;\n this.xrpToDrops = common_1.xrpToDrops;\n this.dropsToXrp = common_1.dropsToXrp;\n this.rippleTimeToISO8601 = common_1.rippleTimeToISO8601;\n this.iso8601ToRippleTime = common_1.iso8601ToRippleTime;\n this.txFlags = common_1.txFlags;\n this.accountSetFlags = common_1.constants.AccountSetFlags;\n this.isValidAddress = schemaValidator.isValidAddress;\n this.isValidSecret = schemaValidator.isValidSecret;\n common_1.validate.apiOptions(options);\n this._feeCushion = options.feeCushion || 1.2;\n this._maxFeeXRP = options.maxFeeXRP || '2';\n const serverURL = options.server;\n if (serverURL != null) {\n this.connection = new common_1.Connection(serverURL, options);\n this.connection.on('ledgerClosed', (message) => {\n this.emit('ledger', server_1.formatLedgerClose(message));\n });\n this.connection.on('error', (errorCode, errorMessage, data) => {\n this.emit('error', errorCode, errorMessage, data);\n });\n this.connection.on('connected', () => {\n this.emit('connected');\n });\n this.connection.on('disconnected', (code) => {\n let finalCode = code;\n if (finalCode === 1005 || finalCode === 4000) {\n finalCode = 1000;\n }\n this.emit('disconnected', finalCode);\n });\n }\n else {\n this.connection = new common_1.Connection(null, options);\n }\n }\n request(command, params = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.connection.request(Object.assign(Object.assign({}, params), { command, account: params.account ? common_1.ensureClassicAddress(params.account) : undefined }));\n });\n }\n hasNextPage(currentResponse) {\n return !!currentResponse.marker;\n }\n requestNextPage(command, params = {}, currentResponse) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!currentResponse.marker) {\n return Promise.reject(new common_1.errors.NotFoundError('response does not have a next page'));\n }\n const nextPageParams = Object.assign({}, params, {\n marker: currentResponse.marker\n });\n return this.request(command, nextPageParams);\n });\n }\n prepareTransaction(txJSON, instructions = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n return transactionUtils.prepareTransaction(txJSON, this, instructions);\n });\n }\n convertStringToHex(string) {\n return transactionUtils.convertStringToHex(string);\n }\n _requestAll(command, params = {}, options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const collectKey = options.collect || getCollectKeyFromCommand(command);\n if (!collectKey) {\n throw new common_1.errors.ValidationError(`no collect key for command ${command}`);\n }\n const countTo = params.limit != null ? params.limit : Infinity;\n let count = 0;\n let marker = params.marker;\n let lastBatchLength;\n const results = [];\n do {\n const countRemaining = utils_2.clamp(countTo - count, 10, 400);\n const repeatProps = Object.assign(Object.assign({}, params), { limit: countRemaining, marker });\n const singleResult = yield this.request(command, repeatProps);\n const collectedData = singleResult[collectKey];\n marker = singleResult['marker'];\n results.push(singleResult);\n const isExpectedFormat = Array.isArray(collectedData);\n if (isExpectedFormat) {\n count += collectedData.length;\n lastBatchLength = collectedData.length;\n }\n else {\n lastBatchLength = 0;\n }\n } while (!!marker && count < countTo && lastBatchLength !== 0);\n return results;\n });\n }\n}\nexports.RippleAPI = RippleAPI;\nRippleAPI._PRIVATE = {\n validate: common_1.validate,\n RangeSet: rangeset_1.default,\n ledgerUtils,\n schemaValidator\n};\nRippleAPI.renameCounterpartyToIssuer = utils_2.renameCounterpartyToIssuer;\nRippleAPI.formatBidsAndAsks = orderbook_1.formatBidsAndAsks;\nRippleAPI.deriveXAddress = derive_1.deriveXAddress;\nRippleAPI.deriveClassicAddress = derive_1.deriveAddress;\nRippleAPI.classicAddressToXAddress = ripple_address_codec_1.classicAddressToXAddress;\nRippleAPI.xAddressToClassicAddress = ripple_address_codec_1.xAddressToClassicAddress;\nRippleAPI.isValidXAddress = ripple_address_codec_1.isValidXAddress;\nRippleAPI.isValidClassicAddress = ripple_address_codec_1.isValidClassicAddress;\nRippleAPI.encodeSeed = ripple_address_codec_1.encodeSeed;\nRippleAPI.decodeSeed = ripple_address_codec_1.decodeSeed;\nRippleAPI.encodeAccountID = ripple_address_codec_1.encodeAccountID;\nRippleAPI.decodeAccountID = ripple_address_codec_1.decodeAccountID;\nRippleAPI.encodeNodePublic = ripple_address_codec_1.encodeNodePublic;\nRippleAPI.decodeNodePublic = ripple_address_codec_1.decodeNodePublic;\nRippleAPI.encodeAccountPublic = ripple_address_codec_1.encodeAccountPublic;\nRippleAPI.decodeAccountPublic = ripple_address_codec_1.decodeAccountPublic;\nRippleAPI.encodeXAddress = ripple_address_codec_1.encodeXAddress;\nRippleAPI.decodeXAddress = ripple_address_codec_1.decodeXAddress;\nRippleAPI.computeBinaryTransactionHash = hashes_1.computeBinaryTransactionHash;\nRippleAPI.computeTransactionHash = hashes_1.computeTransactionHash;\nRippleAPI.computeBinaryTransactionSigningHash = hashes_1.computeBinaryTransactionSigningHash;\nRippleAPI.computeAccountLedgerObjectID = hashes_1.computeAccountLedgerObjectID;\nRippleAPI.computeSignerListLedgerObjectID = hashes_1.computeSignerListLedgerObjectID;\nRippleAPI.computeOrderID = hashes_1.computeOrderID;\nRippleAPI.computeTrustlineHash = hashes_1.computeTrustlineHash;\nRippleAPI.computeTransactionTreeHash = hashes_1.computeTransactionTreeHash;\nRippleAPI.computeStateTreeHash = hashes_1.computeStateTreeHash;\nRippleAPI.computeLedgerHash = ledgerhash_1.default;\nRippleAPI.computeEscrowHash = hashes_1.computeEscrowHash;\nRippleAPI.computePaymentChannelHash = hashes_1.computePaymentChannelHash;\nRippleAPI.txFlags = common_1.txFlags;\nRippleAPI.accountSetFlags = common_1.constants.AccountSetFlags;\n//# sourceMappingURL=api.js.map\n\n//# sourceURL=webpack://ripple/./dist/npm/api.js?"); /***/ }), /***/ "./dist/npm/broadcast.js": /*!*******************************!*\ !*** ./dist/npm/broadcast.js ***! \*******************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.RippleAPIBroadcast = void 0;\nconst api_1 = __webpack_require__(/*! ./api */ \"./dist/npm/api.js\");\nclass RippleAPIBroadcast extends api_1.RippleAPI {\n constructor(servers, options = {}) {\n super(options);\n this.ledgerVersion = undefined;\n const apis = servers.map((server) => new api_1.RippleAPI(Object.assign({}, options, { server })));\n this._apis = apis;\n this.getMethodNames().forEach((name) => {\n this[name] = function () {\n return Promise.race(apis.map((api) => api[name](...arguments)));\n };\n });\n this.connect = function () {\n return __awaiter(this, void 0, void 0, function* () {\n yield Promise.all(apis.map((api) => api.connect()));\n });\n };\n this.disconnect = function () {\n return __awaiter(this, void 0, void 0, function* () {\n yield Promise.all(apis.map((api) => api.disconnect()));\n });\n };\n this.isConnected = function () {\n return apis.map((api) => api.isConnected()).every(Boolean);\n };\n const defaultAPI = apis[0];\n const syncMethods = ['sign', 'generateAddress', 'computeLedgerHash'];\n syncMethods.forEach((name) => {\n this[name] = defaultAPI[name].bind(defaultAPI);\n });\n apis.forEach((api) => {\n api.on('ledger', this.onLedgerEvent.bind(this));\n api.on('error', (errorCode, errorMessage, data) => this.emit('error', errorCode, errorMessage, data));\n });\n }\n onLedgerEvent(ledger) {\n if (ledger.ledgerVersion > this.ledgerVersion ||\n this.ledgerVersion == null) {\n this.ledgerVersion = ledger.ledgerVersion;\n this.emit('ledger', ledger);\n }\n }\n getMethodNames() {\n const methodNames = [];\n const rippleAPI = this._apis[0];\n for (const name of Object.getOwnPropertyNames(rippleAPI)) {\n if (typeof rippleAPI[name] === 'function') {\n methodNames.push(name);\n }\n }\n return methodNames;\n }\n}\nexports.RippleAPIBroadcast = RippleAPIBroadcast;\n//# sourceMappingURL=broadcast.js.map\n\n//# sourceURL=webpack://ripple/./dist/npm/broadcast.js?"); /***/ }), /***/ "./dist/npm/common/backoff.js": /*!************************************!*\ !*** ./dist/npm/common/backoff.js ***! \************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.ExponentialBackoff = void 0;\nclass ExponentialBackoff {\n constructor(opts = {}) {\n this.factor = 2;\n this.jitter = 0;\n this.attempts = 0;\n this.ms = opts.min || 100;\n this.max = opts.max || 10000;\n }\n duration() {\n var ms = this.ms * Math.pow(this.factor, this.attempts++);\n if (this.jitter) {\n var rand = Math.random();\n var deviation = Math.floor(rand * this.jitter * ms);\n ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;\n }\n return Math.min(ms, this.max) | 0;\n }\n reset() {\n this.attempts = 0;\n }\n}\nexports.ExponentialBackoff = ExponentialBackoff;\n//# sourceMappingURL=backoff.js.map\n\n//# sourceURL=webpack://ripple/./dist/npm/common/backoff.js?"); /***/ }), /***/ "./dist/npm/common/browser-hacks.js": /*!******************************************!*\ !*** ./dist/npm/common/browser-hacks.js ***! \******************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.setPrototypeOf = exports.getConstructorName = void 0;\nfunction setPrototypeOf(object, prototype) {\n Object.setPrototypeOf\n ? Object.setPrototypeOf(object, prototype)\n :\n (object.__proto__ = prototype);\n}\nexports.setPrototypeOf = setPrototypeOf;\nfunction getConstructorName(object) {\n if (object.constructor.name) {\n return object.constructor.name;\n }\n const constructorString = object.constructor.toString();\n const functionConstructor = constructorString.match(/^function\\s+([^(]*)/);\n const classConstructor = constructorString.match(/^class\\s([^\\s]*)/);\n return functionConstructor ? functionConstructor[1] : classConstructor[1];\n}\nexports.getConstructorName = getConstructorName;\n//# sourceMappingURL=browser-hacks.js.map\n\n//# sourceURL=webpack://ripple/./dist/npm/common/browser-hacks.js?"); /***/ }), /***/ "./dist/npm/common/connection.js": /*!***************************************!*\ !*** ./dist/npm/common/connection.js ***! \***************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; eval("/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\")[\"Buffer\"];\n\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Connection = void 0;\nconst _ = __importStar(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst events_1 = __webpack_require__(/*! events */ \"./node_modules/events/events.js\");\nconst url_1 = __webpack_require__(/*! url */ \"./node_modules/url/url.js\");\nconst ws_1 = __importDefault(__webpack_require__(/*! ws */ \"./dist/npm/common/wswrapper.js\"));\nconst rangeset_1 = __importDefault(__webpack_require__(/*! ./rangeset */ \"./dist/npm/common/rangeset.js\"));\nconst errors_1 = __webpack_require__(/*! ./errors */ \"./dist/npm/common/errors.js\");\nconst backoff_1 = __webpack_require__(/*! ./backoff */ \"./dist/npm/common/backoff.js\");\nconst INTENTIONAL_DISCONNECT_CODE = 4000;\nfunction createWebSocket(url, config) {\n const options = {};\n if (config.proxy != null) {\n const parsedURL = url_1.parse(url);\n const parsedProxyURL = url_1.parse(config.proxy);\n const proxyOverrides = _.omitBy({\n secureEndpoint: parsedURL.protocol === 'wss:',\n secureProxy: parsedProxyURL.protocol === 'https:',\n auth: config.proxyAuthorization,\n ca: config.trustedCertificates,\n key: config.key,\n passphrase: config.passphrase,\n cert: config.certificate\n }, (value) => value == null);\n const proxyOptions = Object.assign({}, parsedProxyURL, proxyOverrides);\n let HttpsProxyAgent;\n try {\n HttpsProxyAgent = __webpack_require__(/*! https-proxy-agent */ \"?d4ff\");\n }\n catch (error) {\n throw new Error('\"proxy\" option is not supported in the browser');\n }\n options.agent = new HttpsProxyAgent(proxyOptions);\n }\n if (config.authorization != null) {\n const base64 = Buffer.from(config.authorization).toString('base64');\n options.headers = { Authorization: `Basic ${base64}` };\n }\n const optionsOverrides = _.omitBy({\n ca: config.trustedCertificates,\n key: config.key,\n passphrase: config.passphrase,\n cert: config.certificate\n }, (value) => value == null);\n const websocketOptions = Object.assign({}, options, optionsOverrides);\n const websocket = new ws_1.default(url, null, websocketOptions);\n if (typeof websocket.setMaxListeners === 'function') {\n websocket.setMaxListeners(Infinity);\n }\n return websocket;\n}\nfunction websocketSendAsync(ws, message) {\n return new Promise((resolve, reject) => {\n ws.send(message, undefined, (error) => {\n if (error) {\n reject(new errors_1.DisconnectedError(error.message, error));\n }\n else {\n resolve();\n }\n });\n });\n}\nclass LedgerHistory {\n constructor() {\n this.feeBase = null;\n this.feeRef = null;\n this.latestVersion = null;\n this.reserveBase = null;\n this.availableVersions = new rangeset_1.default();\n }\n hasVersion(version) {\n return this.availableVersions.containsValue(version);\n }\n hasVersions(lowVersion, highVersion) {\n return this.availableVersions.containsRange(lowVersion, highVersion);\n }\n update(ledgerMessage) {\n this.feeBase = ledgerMessage.fee_base;\n this.feeRef = ledgerMessage.fee_ref;\n this.latestVersion = ledgerMessage.ledger_index;\n this.reserveBase = ledgerMessage.reserve_base;\n if (ledgerMessage.validated_ledgers) {\n this.availableVersions.reset();\n this.availableVersions.parseAndAddRanges(ledgerMessage.validated_ledgers);\n }\n else {\n this.availableVersions.addValue(this.latestVersion);\n }\n }\n}\nclass ConnectionManager {\n constructor() {\n this.promisesAwaitingConnection = [];\n }\n resolveAllAwaiting() {\n this.promisesAwaitingConnection.map(({ resolve }) => resolve());\n this.promisesAwaitingConnection = [];\n }\n rejectAllAwaiting(error) {\n this.promisesAwaitingConnection.map(({ reject }) => reject(error));\n this.promisesAwaitingConnection = [];\n }\n awaitConnection() {\n return new Promise((resolve, reject) => {\n this.promisesAwaitingConnection.push({ resolve, reject });\n });\n }\n}\nclass RequestManager {\n constructor() {\n this.nextId = 0;\n this.promisesAwaitingResponse = [];\n }\n cancel(id) {\n const { timer } = this.promisesAwaitingResponse[id];\n clearTimeout(timer);\n delete this.promisesAwaitingResponse[id];\n }\n resolve(id, data) {\n const { timer, resolve } = this.promisesAwaitingResponse[id];\n clearTimeout(timer);\n resolve(data);\n delete this.promisesAwaitingResponse[id];\n }\n reject(id, error) {\n const { timer, reject } = this.promisesAwaitingResponse[id];\n clearTimeout(timer);\n reject(error);\n delete this.promisesAwaitingResponse[id];\n }\n rejectAll(error) {\n this.promisesAwaitingResponse.forEach((_, id) => {\n this.reject(id, error);\n });\n }\n createRequest(data, timeout) {\n const newId = this.nextId++;\n const newData = JSON.stringify(Object.assign(Object.assign({}, data), { id: newId }));\n const timer = setTimeout(() => this.reject(newId, new errors_1.TimeoutError()), timeout);\n if (timer.unref) {\n timer.unref();\n }\n const newPromise = new Promise((resolve, reject) => {\n this.promisesAwaitingResponse[newId] = { resolve, reject, timer };\n });\n return [newId, newData, newPromise];\n }\n handleResponse(data) {\n if (!Number.isInteger(data.id) || data.id < 0) {\n throw new errors_1.ResponseFormatError('valid id not found in response', data);\n }\n if (!this.promisesAwaitingResponse[data.id]) {\n return;\n }\n if (data.status === 'error') {\n const error = new errors_1.RippledError(data.error_message || data.error, data);\n this.reject(data.id, error);\n return;\n }\n if (data.status !== 'success') {\n const error = new errors_1.ResponseFormatError(`unrecognized status: ${data.status}`, data);\n this.reject(data.id, error);\n return;\n }\n this.resolve(data.id, data.result);\n }\n}\nclass Connection extends events_1.EventEmitter {\n constructor(url, options = {}) {\n super();\n this._ws = null;\n this._reconnectTimeoutID = null;\n this._heartbeatIntervalID = null;\n this._retryConnectionBackoff = new backoff_1.ExponentialBackoff({\n min: 100,\n max: 60 * 1000\n });\n this._trace = () => { };\n this._ledger = new LedgerHistory();\n this._requestManager = new RequestManager();\n this._connectionManager = new ConnectionManager();\n this._clearHeartbeatInterval = () => {\n clearInterval(this._heartbeatIntervalID);\n };\n this._startHeartbeatInterval = () => {\n this._clearHeartbeatInterval();\n this._heartbeatIntervalID = setInterval(() => this._heartbeat(), this._config.timeout);\n };\n this._heartbeat = () => {\n return this.request({ command: 'ping' }).catch(() => {\n return this.reconnect().catch((error) => {\n this.emit('error', 'reconnect', error.message, error);\n });\n });\n };\n this._onConnectionFailed = (errorOrCode) => {\n if (this._ws) {\n this._ws.removeAllListeners();\n this._ws.on('error', () => {\n });\n this._ws.close();\n this._ws = null;\n }\n if (typeof errorOrCode === 'number') {\n this._connectionManager.rejectAllAwaiting(new errors_1.NotConnectedError(`Connection failed with code ${errorOrCode}.`, {\n code: errorOrCode\n }));\n }\n else if (errorOrCode && errorOrCode.message) {\n this._connectionManager.rejectAllAwaiting(new errors_1.NotConnectedError(errorOrCode.message, errorOrCode));\n }\n else {\n this._connectionManager.rejectAllAwaiting(new errors_1.NotConnectedError('Connection failed.'));\n }\n };\n this.setMaxListeners(Infinity);\n this._url = url;\n this._config = Object.assign({ timeout: 20 * 1000, connectionTimeout: 5 * 1000 }, options);\n if (typeof options.trace === 'function') {\n this._trace = options.trace;\n }\n else if (options.trace === true) {\n this._trace = console.log;\n }\n }\n _onMessage(message) {\n this._trace('receive', message);\n let data;\n try {\n data = JSON.parse(message);\n }\n catch (error) {\n this.emit('error', 'badMessage', error.message, message);\n return;\n }\n if (data.type == null && data.error) {\n this.emit('error', data.error, data.error_message, data);\n return;\n }\n if (data.type) {\n this.emit(data.type, data);\n }\n if (data.type === 'ledgerClosed') {\n this._ledger.update(data);\n }\n if (data.type === 'response') {\n try {\n this._requestManager.handleResponse(data);\n }\n catch (error) {\n this.emit('error', 'badMessage', error.message, message);\n }\n }\n }\n get _state() {\n return this._ws ? this._ws.readyState : ws_1.default.CLOSED;\n }\n get _shouldBeConnected() {\n return this._ws !== null;\n }\n _waitForReady() {\n return new Promise((resolve, reject) => {\n if (!this._shouldBeConnected) {\n reject(new errors_1.NotConnectedError());\n }\n else if (this._state === ws_1.default.OPEN) {\n resolve();\n }\n else {\n this.once('connected', () => resolve());\n }\n });\n }\n _subscribeToLedger() {\n return __awaiter(this, void 0, void 0, function* () {\n const data = yield this.request({\n command: 'subscribe',\n streams: ['ledger']\n });\n if (_.isEmpty(data) || !data.ledger_index) {\n try {\n yield this.disconnect();\n }\n catch (error) {\n }\n finally {\n throw new errors_1.RippledNotInitializedError('Rippled not initialized');\n }\n }\n this._ledger.update(data);\n });\n }\n isConnected() {\n return this._state === ws_1.default.OPEN;\n }\n connect() {\n if (this.isConnected()) {\n return Promise.resolve();\n }\n if (this._state === ws_1.default.CONNECTING) {\n return this._connectionManager.awaitConnection();\n }\n if (!this._url) {\n return Promise.reject(new errors_1.ConnectionError('Cannot connect because no server was specified'));\n }\n if (this._ws) {\n return Promise.reject(new errors_1.RippleError('Websocket connection never cleaned up.', {\n state: this._state\n }));\n }\n const connectionTimeoutID = setTimeout(() => {\n this._onConnectionFailed(new errors_1.ConnectionError(`Error: connect() timed out after ${this._config.connectionTimeout} ms. ` +\n `If your internet connection is working, the rippled server may be blocked or inaccessible. ` +\n `You can also try setting the 'connectionTimeout' option in the RippleAPI constructor.`));\n }, this._config.connectionTimeout);\n this._ws = createWebSocket(this._url, this._config);\n this._ws.on('error', this._onConnectionFailed);\n this._ws.on('error', () => clearTimeout(connectionTimeoutID));\n this._ws.on('close', this._onConnectionFailed);\n this._ws.on('close', () => clearTimeout(connectionTimeoutID));\n this._ws.once('open', () => __awaiter(this, void 0, void 0, function* () {\n this._ws.removeAllListeners();\n clearTimeout(connectionTimeoutID);\n this._ws.on('message', (message) => this._onMessage(message));\n this._ws.on('error', (error) => this.emit('error', 'websocket', error.message, error));\n this._ws.once('close', (code) => {\n this._clearHeartbeatInterval();\n this._requestManager.rejectAll(new errors_1.DisconnectedError('websocket was closed'));\n this._ws.removeAllListeners();\n this._ws = null;\n this.emit('disconnected', code);\n if (code !== INTENTIONAL_DISCONNECT_CODE) {\n const retryTimeout = this._retryConnectionBackoff.duration();\n this._trace('reconnect', `Retrying connection in ${retryTimeout}ms.`);\n this.emit('reconnecting', this._retryConnectionBackoff.attempts);\n this._reconnectTimeoutID = setTimeout(() => {\n this.reconnect().catch((error) => {\n this.emit('error', 'reconnect', error.message, error);\n });\n }, retryTimeout);\n }\n });\n try {\n this._retryConnectionBackoff.reset();\n yield this._subscribeToLedger();\n this._startHeartbeatInterval();\n this._connectionManager.resolveAllAwaiting();\n this.emit('connected');\n }\n catch (error) {\n this._connectionManager.rejectAllAwaiting(error);\n yield this.disconnect().catch(() => { });\n }\n }));\n return this._connectionManager.awaitConnection();\n }\n disconnect() {\n clearTimeout(this._reconnectTimeoutID);\n this._reconnectTimeoutID = null;\n if (this._state === ws_1.default.CLOSED || !this._ws) {\n return Promise.resolve(undefined);\n }\n return new Promise((resolve) => {\n this._ws.once('close', (code) => resolve(code));\n if (this._state !== ws_1.default.CLOSING) {\n this._ws.close(INTENTIONAL_DISCONNECT_CODE);\n }\n });\n }\n reconnect() {\n return __awaiter(this, void 0, void 0, function* () {\n this.emit('reconnect');\n yield this.disconnect();\n yield this.connect();\n });\n }\n getFeeBase() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._waitForReady();\n return this._ledger.feeBase;\n });\n }\n getFeeRef() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._waitForReady();\n return this._ledger.feeRef;\n });\n }\n getLedgerVersion() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._waitForReady();\n return this._ledger.latestVersion;\n });\n }\n getReserveBase() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._waitForReady();\n return this._ledger.reserveBase;\n });\n }\n hasLedgerVersions(lowLedgerVersion, highLedgerVersion) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!highLedgerVersion) {\n return this.hasLedgerVersion(lowLedgerVersion);\n }\n yield this._waitForReady();\n return this._ledger.hasVersions(lowLedgerVersion, highLedgerVersion);\n });\n }\n hasLedgerVersion(ledgerVersion) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._waitForReady();\n return this._ledger.hasVersion(ledgerVersion);\n });\n }\n request(request, timeout) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!this._shouldBeConnected) {\n throw new errors_1.NotConnectedError();\n }\n const [id, message, responsePromise] = this._requestManager.createRequest(request, timeout || this._config.timeout);\n this._trace('send', message);\n websocketSendAsync(this._ws, message).catch((error) => {\n this._requestManager.reject(id, error);\n });\n return responsePromise;\n });\n }\n getUrl() {\n return this._url;\n }\n}\nexports.Connection = Connection;\n//# sourceMappingURL=connection.js.map\n\n//# sourceURL=webpack://ripple/./dist/npm/common/connection.js?"); /***/ }), /***/ "./dist/npm/common/constants.js": /*!**************************************!*\ !*** ./dist/npm/common/constants.js ***! \**************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.AccountFlags = exports.AccountSetFlags = exports.AccountFields = void 0;\nconst txflags_1 = __webpack_require__(/*! ./txflags */ \"./dist/npm/common/txflags.js\");\nconst accountRootFlags = {\n DefaultRipple: 0x00800000,\n DepositAuth: 0x01000000,\n DisableMaster: 0x00100000,\n DisallowXRP: 0x00080000,\n GlobalFreeze: 0x00400000,\n NoFreeze: 0x00200000,\n PasswordSpent: 0x00010000,\n RequireAuth: 0x00040000,\n RequireDestTag: 0x00020000\n};\nconst AccountFlags = {\n passwordSpent: accountRootFlags.PasswordSpent,\n requireDestinationTag: accountRootFlags.RequireDestTag,\n requireAuthorization: accountRootFlags.RequireAuth,\n depositAuth: accountRootFlags.DepositAuth,\n disallowIncomingXRP: accountRootFlags.DisallowXRP,\n disableMasterKey: accountRootFlags.DisableMaster,\n noFreeze: accountRootFlags.NoFreeze,\n globalFreeze: accountRootFlags.GlobalFreeze,\n defaultRipple: accountRootFlags.DefaultRipple\n};\nexports.AccountFlags = AccountFlags;\nconst AccountSetFlags = {\n requireDestinationTag: txflags_1.txFlagIndices.AccountSet.asfRequireDest,\n requireAuthorization: txflags_1.txFlagIndices.AccountSet.asfRequireAuth,\n depositAuth: txflags_1.txFlagIndices.AccountSet.asfDepositAuth,\n disallowIncomingXRP: txflags_1.txFlagIndices.AccountSet.asfDisallowXRP,\n disableMasterKey: txflags_1.txFlagIndices.AccountSet.asfDisableMaster,\n enableTransactionIDTracking: txflags_1.txFlagIndices.AccountSet.asfAccountTxnID,\n noFreeze: txflags_1.txFlagIndices.AccountSet.asfNoFreeze,\n globalFreeze: txflags_1.txFlagIndices.AccountSet.asfGlobalFreeze,\n defaultRipple: txflags_1.txFlagIndices.AccountSet.asfDefaultRipple\n};\nexports.AccountSetFlags = AccountSetFlags;\nconst AccountFields = {\n EmailHash: {\n name: 'emailHash',\n encoding: 'hex',\n length: 32,\n defaults: '00000000000000000000000000000000'\n },\n WalletLocator: { name: 'walletLocator' },\n MessageKey: { name: 'messageKey' },\n Domain: { name: 'domain', encoding: 'hex' },\n TransferRate: { name: 'transferRate', defaults: 0, shift: 9 },\n TickSize: { name: 'tickSize', defaults: 0 }\n};\nexports.AccountFields = AccountFields;\n//# sourceMappingURL=constants.js.map\n\n//# sourceURL=webpack://ripple/./dist/npm/common/constants.js?"); /***/ }), /***/ "./dist/npm/common/errors.js": /*!***********************************!*\ !*** ./dist/npm/common/errors.js ***! \***********************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; eval("\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.XRPLFaucetError = exports.LedgerVersionError = exports.MissingLedgerHistoryError = exports.PendingLedgerVersionError = exports.NotFoundError = exports.ValidationError = exports.ResponseFormatError = exports.TimeoutError = exports.RippledNotInitializedError = exports.DisconnectedError = exports.NotConnectedError = exports.RippledError = exports.ConnectionError = exports.UnexpectedError = exports.RippleError = void 0;\nconst util_1 = __webpack_require__(/*! util */ \"./node_modules/util/util.js\");\nconst browserHacks = __importStar(__webpack_require__(/*! ./browser-hacks */ \"./dist/npm/common/browser-hacks.js\"));\nclass RippleError extends Error {\n constructor(message = '', data) {\n super(message);\n this.name = browserHacks.getConstructorName(this);\n this.message = message;\n this.data = data;\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n toString() {\n let result = '[' + this.name + '(' + this.message;\n if (this.data) {\n result += ', ' + util_1.inspect(this.data);\n }\n result += ')]';\n return result;\n }\n inspect() {\n return this.toString();\n }\n}\nexports.RippleError = RippleError;\nclass RippledError extends RippleError {\n}\nexports.RippledError = RippledError;\nclass UnexpectedError extends RippleError {\n}\nexports.UnexpectedError = UnexpectedError;\nclass LedgerVersionError extends RippleError {\n}\nexports.LedgerVersionError = LedgerVersionError;\nclass ConnectionError extends RippleError {\n}\nexports.ConnectionError = ConnectionError;\nclass NotConnectedError extends ConnectionError {\n}\nexports.NotConnectedError = NotConnectedError;\nclass DisconnectedError extends ConnectionError {\n}\nexports.DisconnectedError = DisconnectedError;\nclass RippledNotInitializedError extends ConnectionError {\n}\nexports.RippledNotInitializedError = RippledNotInitializedError;\nclass TimeoutError extends ConnectionError {\n}\nexports.TimeoutError = TimeoutError;\nclass ResponseFormatError extends ConnectionError {\n}\nexports.ResponseFormatError = ResponseFormatError;\nclass ValidationError extends RippleError {\n}\nexports.ValidationError = ValidationError;\nclass XRPLFaucetError extends RippleError {\n}\nexports.XRPL