You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. var desc = Object.getOwnPropertyDescriptor(m, k);
  5. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  6. desc = { enumerable: true, get: function() { return m[k]; } };
  7. }
  8. Object.defineProperty(o, k2, desc);
  9. }) : (function(o, m, k, k2) {
  10. if (k2 === undefined) k2 = k;
  11. o[k2] = m[k];
  12. }));
  13. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  14. Object.defineProperty(o, "default", { enumerable: true, value: v });
  15. }) : function(o, v) {
  16. o["default"] = v;
  17. });
  18. var __importStar = (this && this.__importStar) || function (mod) {
  19. if (mod && mod.__esModule) return mod;
  20. var result = {};
  21. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  22. __setModuleDefault(result, mod);
  23. return result;
  24. };
  25. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  26. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  27. return new (P || (P = Promise))(function (resolve, reject) {
  28. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  29. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  30. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  31. step((generator = generator.apply(thisArg, _arguments || [])).next());
  32. });
  33. };
  34. var __importDefault = (this && this.__importDefault) || function (mod) {
  35. return (mod && mod.__esModule) ? mod : { "default": mod };
  36. };
  37. Object.defineProperty(exports, "__esModule", { value: true });
  38. exports.Client = void 0;
  39. const assert = __importStar(require("assert"));
  40. const events_1 = require("events");
  41. const errors_1 = require("../errors");
  42. const sugar_1 = require("../sugar");
  43. const fundWallet_1 = __importDefault(require("../Wallet/fundWallet"));
  44. const connection_1 = require("./connection");
  45. const partialPayment_1 = require("./partialPayment");
  46. function getCollectKeyFromCommand(command) {
  47. switch (command) {
  48. case 'account_channels':
  49. return 'channels';
  50. case 'account_lines':
  51. return 'lines';
  52. case 'account_objects':
  53. return 'account_objects';
  54. case 'account_tx':
  55. return 'transactions';
  56. case 'account_offers':
  57. case 'book_offers':
  58. return 'offers';
  59. case 'ledger_data':
  60. return 'state';
  61. default:
  62. return null;
  63. }
  64. }
  65. function clamp(value, min, max) {
  66. assert.ok(min <= max, 'Illegal clamp bounds');
  67. return Math.min(Math.max(value, min), max);
  68. }
  69. const DEFAULT_FEE_CUSHION = 1.2;
  70. const DEFAULT_MAX_FEE_XRP = '2';
  71. const MIN_LIMIT = 10;
  72. const MAX_LIMIT = 400;
  73. const NORMAL_DISCONNECT_CODE = 1000;
  74. class Client extends events_1.EventEmitter {
  75. constructor(server, options = {}) {
  76. var _a, _b;
  77. super();
  78. this.autofill = sugar_1.autofill;
  79. this.submit = sugar_1.submit;
  80. this.submitAndWait = sugar_1.submitAndWait;
  81. this.prepareTransaction = sugar_1.autofill;
  82. this.getXrpBalance = sugar_1.getXrpBalance;
  83. this.getBalances = sugar_1.getBalances;
  84. this.getOrderbook = sugar_1.getOrderbook;
  85. this.getLedgerIndex = sugar_1.getLedgerIndex;
  86. this.fundWallet = fundWallet_1.default;
  87. if (typeof server !== 'string' || !/wss?(?:\+unix)?:\/\//u.exec(server)) {
  88. throw new errors_1.ValidationError('server URI must start with `wss://`, `ws://`, `wss+unix://`, or `ws+unix://`.');
  89. }
  90. this.feeCushion = (_a = options.feeCushion) !== null && _a !== void 0 ? _a : DEFAULT_FEE_CUSHION;
  91. this.maxFeeXRP = (_b = options.maxFeeXRP) !== null && _b !== void 0 ? _b : DEFAULT_MAX_FEE_XRP;
  92. this.connection = new connection_1.Connection(server, options);
  93. this.connection.on('error', (errorCode, errorMessage, data) => {
  94. this.emit('error', errorCode, errorMessage, data);
  95. });
  96. this.connection.on('connected', () => {
  97. this.emit('connected');
  98. });
  99. this.connection.on('disconnected', (code) => {
  100. let finalCode = code;
  101. if (finalCode === connection_1.INTENTIONAL_DISCONNECT_CODE) {
  102. finalCode = NORMAL_DISCONNECT_CODE;
  103. }
  104. this.emit('disconnected', finalCode);
  105. });
  106. this.connection.on('ledgerClosed', (ledger) => {
  107. this.emit('ledgerClosed', ledger);
  108. });
  109. this.connection.on('transaction', (tx) => {
  110. (0, partialPayment_1.handleStreamPartialPayment)(tx, this.connection.trace);
  111. this.emit('transaction', tx);
  112. });
  113. this.connection.on('validationReceived', (validation) => {
  114. this.emit('validationReceived', validation);
  115. });
  116. this.connection.on('manifestReceived', (manifest) => {
  117. this.emit('manifestReceived', manifest);
  118. });
  119. this.connection.on('peerStatusChange', (status) => {
  120. this.emit('peerStatusChange', status);
  121. });
  122. this.connection.on('consensusPhase', (consensus) => {
  123. this.emit('consensusPhase', consensus);
  124. });
  125. this.connection.on('path_find', (path) => {
  126. this.emit('path_find', path);
  127. });
  128. }
  129. get url() {
  130. return this.connection.getUrl();
  131. }
  132. request(req) {
  133. return __awaiter(this, void 0, void 0, function* () {
  134. const response = (yield this.connection.request(Object.assign(Object.assign({}, req), { account: req.account
  135. ?
  136. (0, sugar_1.ensureClassicAddress)(req.account)
  137. : undefined })));
  138. (0, partialPayment_1.handlePartialPayment)(req.command, response);
  139. return response;
  140. });
  141. }
  142. requestNextPage(req, resp) {
  143. return __awaiter(this, void 0, void 0, function* () {
  144. if (!resp.result.marker) {
  145. return Promise.reject(new errors_1.NotFoundError('response does not have a next page'));
  146. }
  147. const nextPageRequest = Object.assign(Object.assign({}, req), { marker: resp.result.marker });
  148. return this.request(nextPageRequest);
  149. });
  150. }
  151. on(eventName, listener) {
  152. return super.on(eventName, listener);
  153. }
  154. requestAll(request, collect) {
  155. return __awaiter(this, void 0, void 0, function* () {
  156. const collectKey = collect !== null && collect !== void 0 ? collect : getCollectKeyFromCommand(request.command);
  157. if (!collectKey) {
  158. throw new errors_1.ValidationError(`no collect key for command ${request.command}`);
  159. }
  160. const countTo = request.limit == null ? Infinity : request.limit;
  161. let count = 0;
  162. let marker = request.marker;
  163. let lastBatchLength;
  164. const results = [];
  165. do {
  166. const countRemaining = clamp(countTo - count, MIN_LIMIT, MAX_LIMIT);
  167. const repeatProps = Object.assign(Object.assign({}, request), { limit: countRemaining, marker });
  168. const singleResponse = yield this.connection.request(repeatProps);
  169. const singleResult = singleResponse.result;
  170. if (!(collectKey in singleResult)) {
  171. throw new errors_1.XrplError(`${collectKey} not in result`);
  172. }
  173. const collectedData = singleResult[collectKey];
  174. marker = singleResult.marker;
  175. results.push(singleResponse);
  176. if (Array.isArray(collectedData)) {
  177. count += collectedData.length;
  178. lastBatchLength = collectedData.length;
  179. }
  180. else {
  181. lastBatchLength = 0;
  182. }
  183. } while (Boolean(marker) && count < countTo && lastBatchLength !== 0);
  184. return results;
  185. });
  186. }
  187. connect() {
  188. return __awaiter(this, void 0, void 0, function* () {
  189. return this.connection.connect();
  190. });
  191. }
  192. disconnect() {
  193. return __awaiter(this, void 0, void 0, function* () {
  194. yield this.connection.disconnect();
  195. });
  196. }
  197. isConnected() {
  198. return this.connection.isConnected();
  199. }
  200. }
  201. exports.Client = Client;
  202. //# sourceMappingURL=index.js.map