@axis-markets/client 0.8.2 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -27
- package/lib/axis-client.cjs +1 -1
- package/lib/axis-client.cjs.map +1 -1
- package/package.json +1 -1
- package/src/allowance.js +40 -8
- package/src/axis-account.js +1376 -1015
- package/src/axis.js +470 -465
- package/src/errors.js +150 -21
- package/src/index.d.ts +1721 -1632
- package/src/index.js +175 -21
package/lib/axis-client.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"axis-client.cjs","mappings":"CAAA,SAAAA,EAAAC,GACA,iBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,EAAAG,QAAA,yBACA,mBAAAC,QAAAA,OAAAC,IACAD,OAAA,yBAAAJ,GACA,iBAAAC,QACAA,QAAA,WAAAD,EAAAG,QAAA,yBAEAJ,EAAA,WAAAC,EAAAD,EAAA,wBACC,CATD,CASCO,KAAAC,oCCTDL,EAAAD,QAAAM,ICCAC,EAAA,GAGA,SAAAC,EAAAC,GAEA,IAAAC,EAAAH,EAAAE,GACA,QAAAE,IAAAD,EACA,OAAAA,EAAAV,QAGA,IAAAC,EAAAM,EAAAE,GAAA,CAGAT,QAAA,IAOA,OAHAY,EAAAH,GAAAR,EAAAA,EAAAD,QAAAQ,GAGAP,EAAAD,OACA,CCrBAQ,EAAAK,EAAA,CAAAb,EAAAc,KACA,QAAAC,KAAAD,EACAN,EAAAQ,EAAAF,EAAAC,KAAAP,EAAAQ,EAAAhB,EAAAe,IACAE,OAAAC,eAAAlB,EAAAe,EAAA,CAAyCI,YAAA,EAAAC,IAAAN,EAAAC,MCJzCP,EAAAQ,EAAA,CAAAK,EAAAC,IAAAL,OAAAM,UAAAC,eAAAC,KAAAJ,EAAAC,GCCAd,EAAAkB,EAAA1B,IACA,oBAAA2B,QAAAA,OAAAC,aACAX,OAAAC,eAAAlB,EAAA2B,OAAAC,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AQ5G,EAAO4G,OACfiM,MAAO7S,EAAO6S,MACdgE,OAAQ7W,EAAO6W,QAAU,GACzBtL,QACA+N,QAASrV,OAAOjE,EAAOsZ,SAAW,GAClCI,QAASmG,GAAW7f,EAAO0Z,QAAS1Z,EAAO2G,UAEzCnI,QAAW+lB,EAAQvP,OAAO1X,MAAMmO,EAAS,CAACnB,IAAKia,EAAQja,MAC7D/L,EAAwBC,GAExB,MAAMomB,EAAY5kB,EAAOqb,OAASxP,EAAUC,MAAQ,CAACxH,EAAQtE,EAAOkC,OAAQqJ,IAAU,GAQtF,aANMgZ,EAAQtE,qBAAqBzhB,EAAI,CACnCqK,OAAQ,CAAC7I,EAAO2G,QAAS3G,EAAO4G,QAChC2Z,YAAa,CAACvgB,EAAO4G,QACrBuZ,SAAUngB,EAAOkC,OACjBkY,OAAQpa,EAAO4G,QAChB6E,EAAQoL,OAAQ+N,GACZpmB,CACX,CASA,SAASmhB,GAAWnhB,EAAIqmB,GACpB,MAAMva,EAAMrG,OAAOzF,EAAGwJ,MAAMsC,MACrB6P,EAAMC,EAAQ9V,GAAW9F,EAAGoT,OACnC,MAAO,CAACtH,MAAKua,aAAc5gB,OAAO4gB,GAAeha,YAAaP,EAAMrG,OAAO4gB,GAAe1K,OAAMC,SAAQ9V,QAASA,QAAW/I,EAChI,CCzfA,MACAupB,GADmB,IAAIC","sources":["webpack://@axis-markets/client/webpack/universalModuleDefinition","webpack://@axis-markets/client/external umd \"@stellar/stellar-sdk\"","webpack://@axis-markets/client/webpack/bootstrap","webpack://@axis-markets/client/webpack/runtime/define property getters","webpack://@axis-markets/client/webpack/runtime/hasOwnProperty shorthand","webpack://@axis-markets/client/webpack/runtime/make namespace object","webpack://@axis-markets/client/./src/contract-client.js","webpack://@axis-markets/client/./src/errors.js","webpack://@axis-markets/client/./src/api-client.js","webpack://@axis-markets/client/./src/footprint.js","webpack://@axis-markets/client/./src/order-id.js","webpack://@axis-markets/client/./src/constants.js","webpack://@axis-markets/client/./src/emitter.js","webpack://@axis-markets/client/./src/stream-client.js","webpack://@axis-markets/client/./src/token-balance.js","webpack://@axis-markets/client/./src/asset-pair.js","webpack://@axis-markets/client/./src/api-dates.js","webpack://@axis-markets/client/./src/axis-market.js","webpack://@axis-markets/client/./src/allowance.js","webpack://@axis-markets/client/./src/axis-account.js","webpack://@axis-markets/client/./src/axis.js","webpack://@axis-markets/client/./src/index.js","webpack://@axis-markets/client/./src/cjs.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"@stellar/stellar-sdk\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"@stellar/stellar-sdk\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"axisClient\"] = factory(require(\"@stellar/stellar-sdk\"));\n\telse\n\t\troot[\"axisClient\"] = factory(root[\"@stellar/stellar-sdk\"]);\n})(this, (__WEBPACK_EXTERNAL_MODULE__346__) => {\nreturn ","module.exports = __WEBPACK_EXTERNAL_MODULE__346__;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import {contract} from '@stellar/stellar-sdk'\r\n\r\nexport default class ContractClient extends contract.Client {\r\n options\r\n\r\n constructor(options) {\r\n super(new contract.Spec([\r\n \"AAAAAAAAA69Td2FwIHRva2VucyBhY3Jvc3Mgc2V2ZXJhbCBtYXJrZXRzLgpUaGUgY29udHJhY3QgaG9sZHMgdGhlIGludGVybWVkaWF0ZSBob3AgcHJvY2VlZHMgb25seSB3aXRoaW4gdGhlIGNhbGwuCgojIEFyZ3VtZW50cwoqIGBkaXJlY3Rpb25gIC0gVHJhZGUgZGlyZWN0aW9uOiBgU2VsbGAgb3IgYEJ1eWAKKiBgdHJhZGVyYCAtIFRyYWRlciBhZGRyZXNzCiogYHNlbGxpbmdgIC0gVG9rZW4gYWRkcmVzcyBzZW50IGJ5IHRoZSB0cmFkZXIKKiBgc2VsbGluZ19hbW91bnRgIC0gQW1vdW50IG9mIHNlbGxpbmcgdG9rZW5zIHRvIHNlbmQgKGBTZWxsYCkgb3IgdGhlIG1heGltdW0gdG8gc3BlbmQgKGBCdXlgKQoqIGBidXlpbmdfYW1vdW50YCAtIE1pbmltdW0gYW1vdW50IG9mIGJ1eWluZyB0b2tlbnMgdG8gcmVjZWl2ZSAoYFNlbGxgKSBvciB0aGUgZXhhY3QgYW1vdW50IChgQnV5YCkKKiBgcGF0aGAgLSBPcmRlcmVkIGxpc3Qgb2YgdGhlIHRyYWRlIHJvdXRlIHN0ZXBzCiogYGFwcHJvdmVgIC0gT3B0aW9uYWwgYWxsb3dhbmNlIGdyYW50ZWQgdG8gdGhlIGNvbnRyYWN0IGJlZm9yZSB0cmFkaW5nLCBub3JtYWxseSBvbiBgc2VsbGluZ2AKCiMgUmV0dXJucwoKKiBBbW91bnQgb2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Vjb3JkLCBzdG9yZWQgb24tY2hhaW4AAAAAAAAAAAAGTWFya2V0AAAAAAADAAAANEJhc2UgYXNzZXQsIHRoZSBmaXJzdCBvZiB0aGUgcGFpciBpbiBjYW5vbmljYWwgb3JkZXIAAAAEYmFzZQAAB9AAAAAKTWFya2V0U2lkZQAAAAAAEkNyZWF0aW9uIHRpbWVzdGFtcAAAAAAAB2NyZWF0ZWQAAAAABgAAADZRdW90ZSBhc3NldCwgdGhlIHNlY29uZCBvZiB0aGUgcGFpciBpbiBjYW5vbmljYWwgb3JkZXIAAAAAAAVxdW90ZQAAAAAAB9AAAAAKTWFya2V0U2lkZQAA\",\r\n \"AAAAAQAAABdNYXJrZXQgYXNzZXQgZGVzY3JpcHRvcgAAAAAAAAAACk1hcmtldFNpZGUAAAAAAAMAAAAWVG9rZW4gY29udHJhY3QgYWRkcmVzcwAAAAAABWFzc2V0AAAAAAAAEwAAAC9Ub2tlbiBkZWNpbWFscyAoZmV0Y2hlZCBvbmx5IGZvciBsaXN0ZWQgYXNzZXRzKQAAAAAIZGVjaW1hbHMAAAAEAAAAWFdoZXRoZXIgdGhlIGFzc2V0IGlzIHF1b3RlZCBieSB0aGUgb3JhY2xlICh3aXRoIHRva2VuIGRlY2ltYWxzIHRoZSB2YWx1YXRpb24gY2FuIGhhbmRsZSkAAAAGbGlzdGVkAAAAAAAB\"\r\n ]), options)\r\n this.options = options\r\n }\r\n\r\n fromJSON = {\r\n swap: this.txFromJSON,\r\n order: this.txFromJSON,\r\n trade: this.txFromJSON,\r\n config: this.txFromJSON,\r\n freeze: this.txFromJSON,\r\n frozen: this.txFromJSON,\r\n market: this.txFromJSON,\r\n update: this.txFromJSON,\r\n requote: this.txFromJSON,\r\n delegate: this.txFromJSON,\r\n crossfill: this.txFromJSON,\r\n set_floor: this.txFromJSON,\r\n subsidize: this.txFromJSON,\r\n set_oracle: this.txFromJSON,\r\n set_ledger_time: this.txFromJSON,\r\n set_listing_min_days: this.txFromJSON\r\n }\r\n}\r\n","import {contract} from '@stellar/stellar-sdk'\r\n\r\n/**\r\n * Standard contract errors\r\n */\r\nexport const ContractErrors = {\r\n 701: {message: \"NotAuthorized\"},\r\n 702: {message: \"InsufficientBalance\"},\r\n 703: {message: \"InsufficientAllowance\"},\r\n 704: {message: \"InvalidMatch\"},\r\n 705: {message: \"InvalidPrice\"},\r\n 706: {message: \"InvalidAmount\"},\r\n 707: {message: \"InvalidExpiration\"},\r\n 708: {message: \"CannotReceive\"},\r\n 709: {message: \"NotFilled\"},\r\n 710: {message: \"OrderNotFound\"},\r\n 711: {message: \"OrderExists\"},\r\n 712: {message: \"IntermediaryCannotReceive\"},\r\n 720: {message: \"OrderSizeTooSmall\"},\r\n 721: {message: \"AssetsNotVerifiedByOracle\"},\r\n 722: {message: \"AssetPriceOracleFetchFailed\"},\r\n 723: {message: \"InvalidOracleConfig\"},\r\n 730: {message: \"Frozen\"},\r\n 740: {message: \"Overflow\"}\r\n}\r\n\r\n/**\r\n * Errors of the Stellar Asset Contract, raised by the token transfers a trading call settles with\r\n */\r\nexport const TokenErrors = {\r\n 1: {message: \"InternalError\"},\r\n 2: {message: \"OperationNotSupportedError\"},\r\n 3: {message: \"AlreadyInitializedError\"},\r\n 4: {message: \"UnauthorizedError\"},\r\n 5: {message: \"AuthenticationError\"},\r\n 6: {message: \"AccountMissingError\"},\r\n 7: {message: \"AccountIsNotClassic\"},\r\n 8: {message: \"NegativeAmountError\"},\r\n 9: {message: \"AllowanceError\"},\r\n 10: {message: \"BalanceError\"},\r\n 11: {message: \"BalanceDeauthorizedError\"},\r\n 12: {message: \"OverflowError\"},\r\n 13: {message: \"TrustlineMissingError\"}\r\n}\r\n\r\n/**\r\n * Handle simulation errors if any. A contract error raised by the DEX contract is mapped by its code. An error raised by\r\n * another contract the call invoked (the token whose transfer failed) is reported with `tokenError` set: a failed\r\n * payment to a maker fails the whole call with the token's own error, and the contract does not tell whether the payer\r\n * could not pay or the maker could not be credited (e.g. a full trustline), so neither side is assumed\r\n * @param {contract.AssembledTransaction} tx\r\n * @throws {Error} - Error with numeric `code` property for known contract errors, plus `tokenError` and `contract`\r\n * for errors raised by a token\r\n * @internal\r\n */\r\nexport function processSimulationErrors(tx) {\r\n if (tx.simulation?.error) {\r\n const message = tx.simulation.error\r\n const contractErrorMatch = /HostError: Error\\(Contract, #(\\d+)\\)/.exec(message)\r\n if (contractErrorMatch) {\r\n const code = parseInt(contractErrorMatch[1], 10)\r\n const source = findErrorSource(message, code)\r\n const dexContract = tx.options?.contractId\r\n const raisedByToken = source && dexContract ? source.contract !== dexContract : !ContractErrors[code] && !!TokenErrors[code]\r\n if (raisedByToken)\r\n throw tokenError(code, source?.contract)\r\n const err = ContractErrors[code]\r\n if (err) {\r\n const error = new Error(`Contract execution error: #${code} ${err.message}`)\r\n error.code = code\r\n throw error\r\n }\r\n }\r\n throw message\r\n }\r\n}\r\n\r\n/**\r\n * Locate the contract that raised the error in a simulation event log. The log lists events newest first and an error\r\n * is re-emitted by every frame it fails, so the oldest `error` event with the code is where it was raised (errors of\r\n * caught calls carry other codes)\r\n * @param {string} message - Simulation error with its diagnostic event log\r\n * @param {number} code - Error code the simulation failed with\r\n * @return {{contract: string}|null}\r\n * @private\r\n */\r\nfunction findErrorSource(message, code) {\r\n let source = null\r\n for (const match of message.matchAll(/contract:(C[A-Z2-7]{55}),\\s*topics:\\[error, Error\\(Contract, #(\\d+)\\)/g)) {\r\n if (parseInt(match[2], 10) === code) {\r\n source = {contract: match[1]}\r\n }\r\n }\r\n return source\r\n}\r\n\r\n/**\r\n * Error raised by a token transfer during settlement\r\n * @param {number} code - Token error code\r\n * @param {string} [contract] - Token contract address, when the event log names it\r\n * @return {Error}\r\n * @private\r\n */\r\nfunction tokenError(code, contract) {\r\n const name = TokenErrors[code]?.message || 'token error'\r\n const error = new Error(`Token transfer failed: #${code} ${name}${contract ? ` (token ${contract})` : ''}. ` +\r\n `Either side of the transfer may be at fault: the payer's balance or allowance, or the recipient's trustline ` +\r\n `(e.g. a full trustline limit).`)\r\n error.code = code\r\n error.tokenError = true\r\n if (contract) {\r\n error.contract = contract\r\n }\r\n return error\r\n}\r\n\r\n/**\r\n * Handle the failure of a transaction applied on-chain\r\n * @param {contract.SentTransaction} sent\r\n * @throws {Error} - Error with the transaction `hash` and its result\r\n * @internal\r\n */\r\nexport function processTransactionErrors(sent) {\r\n const response = sent.getTransactionResponse\r\n if (response?.status !== 'FAILED')\r\n return\r\n const hash = sent.sendTransactionResponse?.hash\r\n const error = new Error(`Transaction ${hash} failed: ${JSON.stringify(response.resultXdr?.result, (key, value) => typeof value === 'bigint' ? value.toString() : value)}`)\r\n error.hash = hash\r\n throw error\r\n}\r\n","/**\n * Error thrown when the AXIS API responds with a non-success HTTP status\n */\nexport class AxisApiError extends Error {\n /**\n * @param {string} message - Error message returned by the API\n * @param {number} status - HTTP status code\n */\n constructor(message, status) {\n super(message)\n this.name = 'AxisApiError'\n this.status = status\n }\n\n /**\n * HTTP status code associated with the error\n * @type {number}\n * @readonly\n */\n status\n}\n\n/**\n * HTTP client for the AXIS REST API\n */\nexport class AxisApiClient {\n /**\n * @param {string} serverUrl - Base URL of the AXIS API server\n */\n constructor(serverUrl) {\n if (!serverUrl || typeof serverUrl !== 'string')\n throw new TypeError('AXIS API server URL is required')\n //trim trailing slashes to avoid double slashes when building request paths\n this.serverUrl = serverUrl.replace(/\\/+$/, '')\n }\n\n /**\n * Base URL of the AXIS API server\n * @type {string}\n * @readonly\n */\n serverUrl\n\n /**\n * Price quote and candidate trade routes for selling a fixed amount of the source asset\n * @param {QuoteParams} params - Quote request parameters\n * @return {Promise<QuoteResult>} - Best routes ranked by profitability\n * @throws {AxisApiError} - 409 if the server is not ready or routing fails, 400 on invalid parameters. Not enough\n * liquidity resolves with `status: 'unfeasible'`, a frozen contract with `status: 'rejected'`\n */\n async quoteSell(params) {\n return this.quote(params, 'strict_send')\n }\n\n /**\n * Price quote and candidate trade routes for buying a fixed amount of the destination asset\n * @param {QuoteParams} params - Quote request parameters\n * @return {Promise<QuoteResult>} - Best routes ranked by profitability\n * @throws {AxisApiError} - 409 if the server is not ready or routing fails, 400 on invalid parameters. Not enough\n * liquidity resolves with `status: 'unfeasible'`, a frozen contract with `status: 'rejected'`\n */\n async quoteBuy(params) {\n return this.quote(params, 'strict_receive')\n }\n\n /**\n * Find viable multi-hop paths between two assets, simulate trades on each path, and return the best routes\n * @param {QuoteParams} params - Quote request parameters\n * @param {'strict_send'|'strict_receive'} direction - Trade direction\n * @return {Promise<QuoteResult>}\n * @private\n */\n async quote({sellingAsset, buyingAsset, amount, direct, maxPrice}, direction) {\n return this.request('/quote', {sellingAsset, buyingAsset, amount, direction, direct, maxPrice: maxPrice?.toString()})\n }\n\n /**\n * Order book depth around the mid price, aggregated into price levels on multiples of `step` (bids rounded down,\n * asks up, so a level price crosses every order in it)\n * @param {DepthParams} params - Depth request parameters\n * @return {Promise<OrderbookDepth>} - Aggregated bids and asks\n */\n async getDepth({market, depth, step, limit}) {\n return this.request('/depth', {market, depth, step, limit})\n }\n\n /**\n * OHLCVT candlestick data (open, high, low, close, base volume, quote volume, trade count)\n * @param {CandlesParams} params - Candles request parameters\n * @return {Promise<Candle[]>} - Time-bucketed candles, max 200 per response\n */\n async getCandles({market, from, to, resolution, order}) {\n return this.request('/candles', {market, from, to, resolution, order})\n }\n\n /**\n * 24-hour ticker statistics for every available market\n * @return {Promise<Ticker24hResult>} - Aggregated 24h stats per market\n */\n async getTicker24h() {\n return this.request('/ticker/24h')\n }\n\n /**\n * List all active markets with pagination\n * @param {MarketsParams} [params] - Pagination parameters\n * @return {Promise<MarketInfo[]>} - Active markets\n */\n async getMarkets({cursor, limit} = {}) {\n return this.request('/markets', {cursor, limit})\n }\n\n /**\n * Contract state tracked by the indexer: frozen switch, configuration and active markets\n * @return {Promise<ContractInfo>} - Contract state\n */\n async getContract() {\n return this.request('/contract')\n }\n\n /**\n * Retrieve active orders, filterable by owner or asset\n * @param {OrdersParams} [params] - Filter parameters\n * @return {Promise<ApiOrder[]>} - Active orders matching the filter\n */\n async getOrders({owner, asset, cursor, limit} = {}) {\n return this.request('/order', {owner, asset, cursor, limit})\n }\n\n /**\n * Account state tracked by the indexer: every live order of the trader (not paginated) and their backing in each\n * asset they trade\n * @param {string} address - Trader address\n * @return {Promise<ApiAccount>}\n */\n async getAccount(address) {\n return this.request(`/account/${encodeURIComponent(address)}`)\n }\n\n /**\n * Retrieve a single order by ID\n * @param {bigint|string|number} id - Order ID\n * @return {Promise<ApiOrder>} - Order (throws AxisApiError with status 404 if not found)\n */\n async getOrder(id) {\n return this.request(`/order/${encodeURIComponent(id.toString())}`)\n }\n\n /**\n * Retrieve archived/historical orders\n * @param {OrderHistoryParams} [params] - Filter parameters\n * @return {Promise<ApiOrder[]>} - Archived orders matching the filter\n */\n async getOrderHistory({owner, pair, cursor, limit} = {}) {\n return this.request('/order-history', {owner, pair, cursor, limit})\n }\n\n /**\n * Retrieve recent trades and swaps, newest first\n * @param {TradesParams} [params] - Filter parameters\n * @return {Promise<Array<ApiTrade|ApiSwap>>} - Recent trades and swaps matching the filter (told apart by `type`)\n */\n async getTrades({trader, pair, cursor, limit} = {}) {\n return this.request('/trades', {trader, pair, cursor, limit})\n }\n\n /**\n * Failed AXIS calls, newest first (diagnostics: a failure changes no state, and a record never blames a party, see\n * {@link ApiFailure})\n * @param {FailuresParams} [params] - Filter parameters\n * @return {Promise<ApiFailure[]>}\n */\n async getFailures({account, fn, cursor, limit} = {}) {\n return this.request('/failures', {account, fn, cursor, limit})\n }\n\n /**\n * Execute a GET request against the AXIS API\n * @param {string} path - Relative route path\n * @param {object} [query] - Query parameters (undefined/null values skipped, arrays expanded to repeated params)\n * @return {Promise<*>} - Parsed JSON response\n * @throws {AxisApiError} - If the API responds with a non-success status\n * @private\n */\n async request(path, query) {\n let url = this.serverUrl + path\n if (query) {\n const search = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null)\n continue\n if (Array.isArray(value)) {\n for (const item of value)\n search.append(key, item)\n } else {\n search.append(key, value)\n }\n }\n const qs = search.toString()\n if (qs)\n url += '?' + qs\n }\n const response = await fetch(url)\n let body\n try {\n body = await response.json()\n } catch (e) {\n //non-JSON response (e.g. proxy/gateway error) - fall back to status text\n body = null\n }\n if (!response.ok)\n throw new AxisApiError(body?.error || response.statusText, body?.status || response.status)\n return body\n }\n}\n\n/**\n * @typedef {{}} QuoteParams\n * @property {string} sellingAsset - Asset to sell (`XLM` | `CODE:Issuer` | `CODE-Issuer` | contractId)\n * @property {string} buyingAsset - Asset to buy (same format as `sellingAsset`)\n * @property {string|number} amount - Trade amount in stroops (1 unit = 10,000,000 stroops)\n * @property {boolean} [direct] - Restrict to the direct market only (no intermediate-asset routes)\n * @property {bigint|string} [maxPrice] - Highest maker price to cross (requires `direct`), in the units of a hop\n * `worstPrice`: `sellingAsset` per unit of `buyingAsset`, scaled by 10^18. Quotes the crossing of a limit order: orders\n * priced above it are left out and the route may trade less than `amount`\n */\n\n/**\n * @typedef {{}} QuoteResult\n * @property {string} id - Base58-encoded quote id\n * @property {'success'|'unfeasible'|'rejected'} status - Quote status\n * @property {'strict_send'|'strict_receive'} direction - Trade direction\n * @property {string} sellingAsset - Selling asset contract id\n * @property {string} buyingAsset - Buying asset contract id\n * @property {number} ledger - Ledger sequence the quote was computed for\n * @property {QuotePath[]} paths - Candidate routes ranked by profitability (up to 10)\n * @property {string} [error] - Error message (present only if status is not `success`)\n */\n\n/**\n * @typedef {{}} QuotePath\n * @property {string} sold - Amount sold, in stroops\n * @property {string} bought - Amount bought, in stroops\n * @property {QuotePathStep[]} path - Ordered list of hops in the route\n */\n\n/**\n * @typedef {{}} QuotePathStep\n * @property {string} selling - Selling asset contract id at this hop\n * @property {string} buying - Buying asset contract id at this hop\n * @property {string[]} orders - Maker order IDs matched at this hop\n * @property {string} [worstPrice] - Highest price among the matched orders (maker `buying` per `selling`, 18 decimals):\n * a trade limit at this price crosses every listed order\n */\n\n/**\n * @typedef {{}} DepthParams\n * @property {string} market - Market identifier `BASE/QUOTE`\n * @property {number} [depth] - Percentage band (±) around the center price (0 < depth ≤ 100, default 20)\n * @property {string} [step] - Price step of the levels, a decimal such as `\"0.0005\"` (5 significant digits of the mid\n * price by default)\n * @property {number} [limit] - Price levels per side (default 100, max 500)\n */\n\n/**\n * @typedef {{}} OrderbookDepth\n * @property {number} ledger - Ledger sequence\n * @property {number} timestamp - UNIX timestamp (seconds)\n * @property {string|null} step - Price step of the levels (null for an empty book)\n * @property {string|null} bestBid - Exact best bid price, before the rounding to levels\n * @property {string|null} bestAsk - Exact best ask price, before the rounding to levels\n * @property {Array<[string, string]>} bids - `[price, quantity]` pairs sorted descending by price\n * @property {Array<[string, string]>} asks - `[price, quantity]` pairs sorted ascending by price\n */\n\n/**\n * @typedef {{}} CandlesParams\n * @property {string} market - Market identifier `BASE/QUOTE`\n * @property {number} [from] - Lower boundary (UNIX seconds, default 0)\n * @property {number} [to] - Upper boundary (UNIX seconds, defaults to `from + resolution * 200`)\n * @property {number|string} [resolution] - Resolution in seconds or alias (`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`12h`,`1d`,`3d`,`1w`,`2w`, default `auto`)\n * @property {'asc'|'desc'} [order] - Sort order (default `desc`)\n */\n\n/**\n * OHLCVT candle row: `[timestamp, open, high, low, close, baseVolume, quoteVolume, tradeCount]`\n * @typedef {[number, string, string, string, string, string, string, number]} Candle\n */\n\n/**\n * @typedef {{}} Ticker24hResult\n * @property {number} ledger - Ledger sequence\n * @property {number} timestamp - UNIX timestamp (seconds)\n * @property {TickerEntry[]} ticker - Per-market 24h stats, sorted by trade count descending\n */\n\n/**\n * @typedef {{}} TickerEntry\n * @property {string} symbol - Market symbol `BASE/QUOTE`\n * @property {string} openPrice - Opening price 24h ago\n * @property {string} highPrice - Highest price in the 24h window\n * @property {string} lowPrice - Lowest price in the 24h window\n * @property {string} lastPrice - Most recent trade price\n * @property {string} volume - 24h base asset volume\n * @property {string} quoteVolume - 24h quote asset volume\n * @property {number} change - 24h price change (percent)\n * @property {string} avgPrice - Volume-weighted average price\n * @property {number} trades - 24h trade count\n */\n\n/**\n * @typedef {{}} MarketsParams\n * @property {string} [cursor] - Pagination cursor (`baseAsset-quoteAsset`)\n * @property {number|string} [limit] - Max markets to return\n */\n\n/**\n * @typedef {{}} MarketInfo\n * @property {string} baseAsset - Base asset contract id\n * @property {string} quoteAsset - Quote asset contract id\n * @property {string} cursor - Pagination cursor for this market\n * @property {string[]} orderTypes - Supported order types\n */\n\n/**\n * @typedef {{}} ContractInfo - Contract state tracked by the indexer\n * @property {string} address - AXIS contract address\n * @property {boolean} frozen - Whether trading is blocked by the safety admin\n * @property {ContractInfoConfig} [config] - Contract configuration\n * @property {ContractInfoMarket[]} markets - Markets opened by `subsidize`\n */\n\n/**\n * @typedef {{}} ContractInfoConfig\n * @property {string} safetyAdmin - Safety admin address\n * @property {string} oracle - Price oracle contract address\n * @property {number} [listingMinDays] - Days of price feeds a new market must buy (0 opens markets without a fee)\n * @property {string} marketListingFee - Oracle fee tokens a market creator pays to provision the price feeds\n * @property {string} minTradeSize - Minimum trade value in USD with 7 decimals (0 = disabled)\n * @property {number} [ledgerTime] - Expected ledger close time in seconds\n */\n\n/**\n * @typedef {{}} ContractInfoMarket\n * @property {string} base - Base market asset, the first of the pair in canonical order\n * @property {string} quote - Quote market asset, the second of the pair in canonical order\n * @property {string} created - Creation timestamp (UTC)\n * @property {string} refreshed - Last oracle check timestamp (UTC)\n */\n\n/**\n * @typedef {{}} OrdersParams\n * @property {string} [owner] - Filter by order owner address\n * @property {string|string[]} [asset] - Filter by asset(s) - every listed asset must be one of the order assets (two assets select a pair)\n * @property {string|bigint} [cursor] - `cursor` of the last order received (its creation position, not the order id)\n * @property {number|string} [limit] - Max orders to return\n */\n\n/**\n * @typedef {{}} OrderHistoryParams\n * @property {string} [owner] - Filter by order owner address\n * @property {string[]} [pair] - Asset pair `[base, quote]` (contract ids)\n * @property {string|bigint} [cursor] - `cursor` of the last order received (its creation position, not the order id)\n * @property {number|string} [limit] - Max orders to return\n */\n\n/**\n * @typedef {{}} TradesParams\n * @property {string} [trader] - Filter by trader address\n * @property {string[]} [pair] - Asset pair `[base, quote]` (contract ids)\n * @property {string|bigint} [cursor] - `cursor` of the last record received (the trade or swap id)\n * @property {number|string} [limit] - Max trades to return\n */\n\n/**\n * @typedef {{}} FailuresParams\n * @property {string} [account] - Caller of the failed transaction, or a party of the failed transfer\n * @property {string} [fn] - Contract function (`trade`, `swap`, `crossfill`, `update`, ...)\n * @property {string|bigint} [cursor] - `cursor` of the last record received\n * @property {number|string} [limit] - Max records to return (20 by default, at most 500)\n */\n\n/**\n * @typedef {{}} ApiFailure - Failed AXIS call (made by the transaction or through another contract, the transaction failed\n * or a calling contract caught the failure). It changes no state and blames no party:\n * a token error on a settlement transfer does not tell the payer who could not pay from the recipient who could not be\n * credited (e.g. a full trustline), and in a `crossfill` the makers are paid by the taker order owner, not the caller\n * @property {'failure'} type - Record type\n * @property {string} id - Record id (position of the transaction plus the index of the failed call)\n * @property {string} txHash - Transaction hash\n * @property {number} ledger - Ledger sequence\n * @property {string} timestamp - Ledger close time (UTC)\n * @property {string} fn - Contract function called\n * @property {string} caller - The `trader` or `sponsor` argument, the transaction source for other functions\n * @property {string[]} orders - Maker order ids listed by the call\n * @property {string} [takerOrder] - Taker order id of a `crossfill`\n * @property {string} result - Operation result code\n * @property {boolean} [caught] - The transaction succeeded: a calling contract caught the failed AXIS call\n * @property {'contract'|'transfer'|'resources'|'auth'|'unknown'} reason - `contract`: a contract error (`error`),\n * `transfer`: a token transfer failed (`transfer`, either side may be at fault), `resources`: a resource limit, the\n * refundable fee or an archived entry, `auth`: an authorization failure, `unknown`: no diagnostic events\n * @property {{contract: string|null, code: number, name?: string}} [error] - Contract error that failed the call\n * @property {{token: string, fn: string, from: string, to: string, amount: string}} [transfer] - Token transfer that failed\n * @property {string} cursor - Pagination cursor\n */\n\n/**\n * @typedef {{}} ApiOrder - Serialized order returned by the API\n * @property {string} id - Order ID (decimal u128)\n * @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Order status: `ACTIVE`, `FILLED`, `CANCELED` (removed by the owner) or `EXPIRED` (archived once past `expires`)\n * @property {string} buying - Buying asset contract id\n * @property {string} selling - Selling asset contract id\n * @property {string} price - Order price\n * @property {string} rprice - Rational price representation\n * @property {string} quote - Selling amount at creation\n * @property {string} amount - Amount left to sell\n * @property {string} [backed] - Amount the maker can actually deliver, when the indexer tracks backing\n * @property {ApiOrderBacking} [backing] - Maker backing details, when the indexer tracks backing\n * @property {string} owner - Maker address\n * @property {string} [expires] - Expiration timestamp (UTC)\n * @property {string} [created] - Creation timestamp (UTC)\n * @property {string} [updated] - Last update timestamp (UTC)\n * @property {string} [cursor] - Pagination cursor\n */\n\n/**\n * @typedef {{}} ApiOrderBacking - Maker backing in the order's selling asset\n * @property {string} balance - Token balance\n * @property {string} allowance - Allowance granted to the AXIS contract\n * @property {number} liveUntil - Ledger sequence the allowance lives until\n * @property {boolean} authorized - Whether the maker can send and receive the token\n * @property {string} [updated] - Last load timestamp (UTC)\n * @property {boolean} [pending] - A reload confirming the latest event is still due: the values may predate it\n */\n\n/**\n * @typedef {{}} ApiBacking - Tracked backing of an account in a token\n * @property {string} owner - Account address\n * @property {string} asset - Token contract id\n * @property {string} balance - Token balance\n * @property {string} allowance - Allowance granted to the AXIS contract\n * @property {number} liveUntil - Ledger sequence the allowance lives until\n * @property {boolean} authorized - Whether the account can send and receive the token\n * @property {string} budget - Effective budget, min(balance, allowance), 0 when unauthorized or expired\n * @property {string} [headroom] - Amount the account can still receive (trustline limit minus balance and buying\n * liabilities), omitted when unlimited or unknown\n * @property {string} [updated] - Last load timestamp (UTC)\n * @property {string} [skipped] - Last `skip` event of an order selling the token (UTC)\n * @property {boolean} [pending] - A reload confirming the latest event is still due\n */\n\n/**\n * @typedef {{}} ApiAccount - Account state: every live order and the backing per traded asset\n * @property {string} address - Trader address\n * @property {number} ledger - Last processed ledger\n * @property {ApiOrder[]} orders - Live orders, oldest first\n * @property {Object<string, ApiBacking>} backing - Backing by token contract id\n */\n\n/**\n * @typedef {{}} ApiSwap - Serialized swap returned by the API, one per `swap` call\n * @property {'swap'} type - Record type\n * @property {string} id - Swap ID\n * @property {string} trader - Trader address\n * @property {string} soldAsset - Sold asset contract id\n * @property {string} boughtAsset - Bought asset contract id\n * @property {string} sold - Sold tokens amount\n * @property {string} bought - Bought tokens amount\n * @property {string} price - Approximate swap price\n * @property {string} cursor - Pagination cursor\n * @property {string} timestamp - Swap timestamp (UTC)\n */\n\n/**\n * @typedef {{}} ApiTrade - Serialized trade returned by the API\n * @property {'trade'} type - Record type\n * @property {string} id - Trade ID\n * @property {string} order - Matched order ID\n * @property {string} taker - Taker account address\n * @property {string} maker - Maker account address\n * @property {string} soldAsset - Sold asset contract id\n * @property {string} boughtAsset - Bought asset contract id\n * @property {string} sold - Sold tokens amount\n * @property {string} bought - Bought tokens amount\n * @property {string} [left] - Order amount left after the fill\n * @property {boolean} [crossfill] - The fill of a `crossfill` taker order: `taker` is the caller, paid the surplus, and the\n * amounts mirror the makers' fills of the same call (left out of candles and volume)\n * @property {string} price - Approximate trade price\n * @property {string} [cursor] - Pagination cursor\n * @property {string} timestamp - Trade timestamp (UTC)\n */\n","import {xdr, Address, Asset, Keypair, StrKey, TransactionBuilder, nativeToScVal, scValToNative, contract, rpc} from '@stellar/stellar-sdk'\r\n\r\n/**\r\n * Upper bound of a serialized `Order` ledger entry in bytes.\r\n * (positional vector of three addresses, i128 amount and price, optional u64 expires = at most 188-byte value,\r\n * about 264-byte ledger entry, rounded up to 320).\r\n * @type {number}\r\n */\r\nexport const ORDER_ENTRY_SIZE = 320\r\n\r\n/**\r\n * CPU instructions added to the declared budget for every order that was not matched at simulation time.\r\n * @type {number}\r\n */\r\nexport const ORDER_INSTRUCTIONS = 2_000_000\r\n\r\n/**\r\n * Resource fee (stroops) added for every order that was not matched at simulation time.\r\n * (write entry ~10k, read entry ~6k, writes ~12k, 2M instructions ~5k, trade/order events ~10k).\r\n * @type {bigint}\r\n */\r\nexport const ORDER_RESOURCE_FEE = 100_000n\r\n\r\n/**\r\n * Upper bound of a maker balance (account, trustline or token balance) or allowance ledger entry in bytes.\r\n * @type {number}\r\n */\r\nexport const MAKER_ENTRY_SIZE = 256\r\n\r\n/**\r\n * Resource fee (stroops) added for every maker entry declared read-write (write entry ~10k, its bytes charged as written ~6k).\r\n * @type {bigint}\r\n */\r\nexport const MAKER_ENTRY_RESOURCE_FEE = 20_000n\r\n\r\n/**\r\n * CPU instructions added for every maker whose entries were declared (two token transfers, backing and receive checks).\r\n * @type {number}\r\n */\r\nexport const MAKER_INSTRUCTIONS = 3_000_000\r\n\r\n/**\r\n * Resource fee (stroops) added for every maker whose entries were declared (instructions ~8k, two transfer events and\r\n * a `skip` event ~4k, rounded up).\r\n * @type {bigint}\r\n */\r\nexport const MAKER_RESOURCE_FEE = 20_000n\r\n\r\n/**\r\n * CPU instructions added when the settlement entries of the call were declared: the transfer forwarding what the makers\r\n * delivered from the DEX contract to the receiver, and the receive checks before it.\r\n * @type {number}\r\n */\r\nexport const FORWARD_INSTRUCTIONS = 2_000_000\r\n\r\n/**\r\n * Resource fee (stroops) added when the settlement entries of the call were declared (instructions ~5k, the forwarding\r\n * `transfer` event ~2k, rounded up).\r\n * @type {bigint}\r\n */\r\nexport const FORWARD_RESOURCE_FEE = 10_000n\r\n\r\n/**\r\n * Ledger entry types read from disk when a transaction is applied: every declared one counts towards the disk read\r\n * bytes, whether the execution touches it or not.\r\n * @type {Set<string>}\r\n */\r\nconst DISK_ENTRY_TYPES = new Set(['account', 'trustline'])\r\n\r\n/**\r\n * Network-wide per-transaction instructions limit.\r\n * @type {number}\r\n */\r\nconst MAX_TX_INSTRUCTIONS = 400_000_000\r\n\r\n/**\r\n * Network-wide per-transaction limits of read-write and total footprint entries.\r\n */\r\nconst MAX_READ_WRITE_ENTRIES = 200\r\nconst MAX_FOOTPRINT_ENTRIES = 400\r\n\r\n/**\r\n * Keys per `getLedgerEntries` request accepted by RPC.\r\n */\r\nconst LEDGER_ENTRIES_BATCH = 200\r\n\r\n/**\r\n * Flatten and deduplicate order ids from several lists, coercing them to bigint.\r\n * @param {...(Array<bigint|number|string>|undefined|null)} idLists - Lists of order ids\r\n * @return {bigint[]} - Unique order ids in the order of first appearance\r\n */\r\nexport function collectOrderIds(...idLists) {\r\n const seen = new Set()\r\n const res = []\r\n for (const list of idLists) {\r\n if (!list)\r\n continue\r\n for (const id of list) {\r\n if (id === undefined || id === null)\r\n continue\r\n const value = BigInt(id)\r\n const key = value.toString()\r\n if (seen.has(key))\r\n continue\r\n seen.add(key)\r\n res.push(value)\r\n }\r\n }\r\n return res\r\n}\r\n\r\n/**\r\n * Build persistent contract data ledger key of an order (the key is the raw u128 order id).\r\n * @param {string} contractId - DEX contract address\r\n * @param {bigint|number|string} orderId - Order id\r\n * @return {xdr.LedgerKey}\r\n */\r\nexport function orderLedgerKey(contractId, orderId) {\r\n return contractDataKey(contractId, nativeToScVal(BigInt(orderId), {type: 'u128'}), xdr.ContractDataDurability.persistent)\r\n}\r\n\r\n/**\r\n * Build the ledger key of a contract instance entry.\r\n * @param {string} contractId - Contract address\r\n * @return {xdr.LedgerKey}\r\n */\r\nexport function instanceLedgerKey(contractId) {\r\n return contractDataKey(contractId, xdr.ScVal.scvLedgerKeyContractInstance(), xdr.ContractDataDurability.persistent)\r\n}\r\n\r\n/**\r\n * Build the ledger key holding the balance of `owner` in a Stellar Asset Contract token.\r\n * @param {string} owner - Account or contract address\r\n * @param {string} token - Token contract address\r\n * @param {Asset|null} asset - Classic asset behind the token, `null` for a token that is not a Stellar Asset Contract\r\n * @return {xdr.LedgerKey|null} - `null` when the balance has no ledger entry of its own (issuer) or the token storage layout is unknown\r\n */\r\nexport function balanceLedgerKey(owner, token, asset) {\r\n if (!asset)\r\n return null\r\n if (StrKey.isValidContract(owner))\r\n return contractDataKey(token, xdr.ScVal.scvVec([xdr.ScVal.scvSymbol('Balance'), Address.fromString(owner).toScVal()]), xdr.ContractDataDurability.persistent)\r\n const accountId = Keypair.fromPublicKey(owner).xdrAccountId()\r\n if (asset.isNative())\r\n return xdr.LedgerKey.account(new xdr.LedgerKeyAccount({accountId}))\r\n //the issuer holds no trustline for its own asset\r\n if (asset.getIssuer() === owner)\r\n return null\r\n return xdr.LedgerKey.trustline(new xdr.LedgerKeyTrustLine({accountId, asset: asset.toTrustLineXDRObject()}))\r\n}\r\n\r\n/**\r\n * Build the ledger key of the allowance `owner` granted to `spender` in a Stellar Asset Contract token.\r\n * @param {string} owner - Account or contract address granting the allowance\r\n * @param {string} token - Token contract address\r\n * @param {string} spender - Spender address (the DEX contract)\r\n * @return {xdr.LedgerKey}\r\n */\r\nexport function allowanceLedgerKey(owner, token, spender) {\r\n const key = xdr.ScVal.scvVec([\r\n xdr.ScVal.scvSymbol('Allowance'),\r\n xdr.ScVal.scvMap([\r\n new xdr.ScMapEntry({key: xdr.ScVal.scvSymbol('from'), val: Address.fromString(owner).toScVal()}),\r\n new xdr.ScMapEntry({key: xdr.ScVal.scvSymbol('spender'), val: Address.fromString(spender).toScVal()})\r\n ])\r\n ])\r\n return contractDataKey(token, key, xdr.ContractDataDurability.temporary)\r\n}\r\n\r\n/**\r\n * Decode a stored order entry value: a positional vector `[owner, selling, buying, amount, price, expires?]`.\r\n * @param {xdr.ScVal} val - Contract data value of the order entry\r\n * @return {{owner: string, selling: string, buying: string}}\r\n */\r\nexport function decodeStoredOrder(val) {\r\n const [owner, selling, buying] = scValToNative(val)\r\n return {owner, selling, buying}\r\n}\r\n\r\n/**\r\n * Resolve the classic asset behind a token from its contract instance entry.\r\n * @param {xdr.ScVal} val - Contract data value of the token instance entry\r\n * @return {Asset|null} - `null` for a token that is not a Stellar Asset Contract\r\n */\r\nexport function decodeSacAsset(val) {\r\n if (val.type !== 'scvContractInstance' || val.instance.executable.type !== 'contractExecutableStellarAsset')\r\n return null\r\n const entry = (val.instance.storage ?? []).find(({key}) => scValToNative(key)?.[0] === 'AssetInfo')\r\n if (!entry)\r\n return null\r\n const [type, info] = scValToNative(entry.val)\r\n if (type === 'Native')\r\n return Asset.native()\r\n //alphanum codes are padded with zero bytes\r\n const code = info.asset_code.replace(/\\0+$/, '')\r\n return new Asset(code, StrKey.encodeEd25519PublicKey(info.issuer))\r\n}\r\n\r\n/**\r\n * Make sure every supplied order id declared in the read-write footprint of a simulated transaction.\r\n * @param {contract.AssembledTransaction} tx - Simulated transaction\r\n * @param {string} contractId - DEX contract address\r\n * @param {Array<bigint|number|string>} orderIds - Order ids passed to the contract call\r\n * @return {number} - Number of order entries added to the read-write footprint\r\n */\r\nexport function ensureOrdersFootprint(tx, contractId, orderIds) {\r\n if (!isPatchable(tx) || !orderIds?.length)\r\n return 0\r\n const data = tx.simulation.transactionData\r\n const added = declareReadWrite(data, collectOrderIds(orderIds).map(id => orderLedgerKey(contractId, id))).length\r\n if (added === 0)\r\n return 0\r\n applyResources(tx, data, {\r\n instructions: added * ORDER_INSTRUCTIONS,\r\n writeBytes: added * ORDER_ENTRY_SIZE,\r\n fee: BigInt(added) * ORDER_RESOURCE_FEE\r\n })\r\n return added\r\n}\r\n\r\n/**\r\n * Complete the footprint of a simulated trading transaction, so it still applies when the book moves between simulation\r\n * and execution (an order repriced back into range, a maker's backing restored, an earlier order shrunk). Every listed\r\n * order entry is declared read-write, then the entries the settlement writes for the call itself: the DEX contract's own\r\n * balance of every asset passing through it (makers deliver to the contract, which forwards to the receiver) and the\r\n * receiver's balance of the bought asset. Then, for every order's maker, the balance of the asset the maker sells, the\r\n * allowance on it granted to the DEX contract, and the balance of the asset the maker receives. Tokens that are not\r\n * Stellar Asset Contracts keep what the simulation recorded (their storage layout is unknown). Entries are added in that\r\n * order while the footprint limits allow.\r\n * @param {contract.AssembledTransaction} tx - Simulated transaction\r\n * @param {string} contractId - DEX contract address\r\n * @param {Array<bigint|number|string>} orderIds - Order ids passed to the contract call\r\n * @param {FootprintOptions} options\r\n * @return {Promise<{orders: number, settlementEntries: number, makerEntries: number}>} - Number of order, settlement and\r\n * maker entries added to the read-write footprint\r\n */\r\nexport async function completeFootprint(tx, contractId, orderIds, {server, tokens = [], assetCache = new Map(), passThrough = [], receiver, bought, takerOrder}) {\r\n if (!isPatchable(tx) || !orderIds?.length)\r\n return {orders: 0, settlementEntries: 0, makerEntries: 0}\r\n const ids = collectOrderIds(orderIds)\r\n const orderKeys = ids.map(id => orderLedgerKey(contractId, id))\r\n //one request for the orders and the known tokens, another one only for tokens first seen in the orders\r\n const knownTokens = unresolved([...tokens, ...passThrough, ...(bought ? [bought] : [])], assetCache)\r\n const entries = await loadEntries(server, [...orderKeys, ...knownTokens.map(instanceLedgerKey)])\r\n cacheAssets(entries, knownTokens, assetCache)\r\n const orders = []\r\n for (let i = 0; i < ids.length; i++) {\r\n const entry = entries.get(orderKeys[i].toXDR('base64'))\r\n if (entry) {\r\n orders.push({id: ids[i], ...decodeStoredOrder(entry.contractData.val)})\r\n }\r\n }\r\n //a crossfill buys what the taker order buys: it passes through the contract, which pays the owner and the receiver\r\n const passing = [...passThrough]\r\n if (takerOrder !== undefined && takerOrder !== null) {\r\n const taker = orders.find(order => order.id === BigInt(takerOrder))\r\n if (taker) {\r\n passing.push(taker.buying)\r\n bought ??= taker.buying\r\n }\r\n }\r\n const newTokens = unresolved(orders.flatMap(({selling, buying}) => [selling, buying]), assetCache)\r\n if (newTokens.length) {\r\n cacheAssets(await loadEntries(server, newTokens.map(instanceLedgerKey)), newTokens, assetCache)\r\n }\r\n //entries the settlement of the call writes whichever makers fill\r\n const settlementKeys = [\r\n ...[...new Set(passing)].map(token => balanceLedgerKey(contractId, token, assetCache.get(token) ?? null)),\r\n receiver && bought ? balanceLedgerKey(receiver, bought, assetCache.get(bought) ?? null) : null\r\n ].filter(Boolean)\r\n const settlementSet = new Set(settlementKeys.map(key => key.toXDR('base64')))\r\n //entries the settlement writes for each maker, tagged with the maker\r\n const makerOf = new Map()\r\n const makerKeys = []\r\n for (const {owner, selling, buying} of orders) {\r\n const sold = assetCache.get(selling)\r\n const keys = [\r\n balanceLedgerKey(owner, selling, sold),\r\n sold ? allowanceLedgerKey(owner, selling, contractId) : null,\r\n balanceLedgerKey(owner, buying, assetCache.get(buying))\r\n ]\r\n for (const key of keys) {\r\n if (!key)\r\n continue\r\n const encoded = key.toXDR('base64')\r\n if (settlementSet.has(encoded))\r\n continue //declared with the settlement entries\r\n makerOf.set(encoded, owner)\r\n makerKeys.push(key)\r\n }\r\n }\r\n const data = tx.simulation.transactionData\r\n //entries promoted from the read-only part are already counted as disk reads by the simulation\r\n const readOnly = new Set(data.getReadOnly().map(key => key.toXDR('base64')))\r\n const added = declareReadWrite(data, [...orderKeys, ...settlementKeys, ...makerKeys])\r\n if (!added.length)\r\n return {orders: 0, settlementEntries: 0, makerEntries: 0}\r\n const makers = new Set()\r\n let makerEntries = 0\r\n let settlementEntries = 0\r\n let diskEntries = 0\r\n for (const key of added) {\r\n const encoded = key.toXDR('base64')\r\n if (settlementSet.has(encoded)) {\r\n settlementEntries++\r\n } else if (makerOf.has(encoded)) {\r\n makerEntries++\r\n makers.add(makerOf.get(encoded))\r\n } else\r\n continue\r\n if (DISK_ENTRY_TYPES.has(key.type) && !readOnly.has(encoded)) {\r\n diskEntries++\r\n }\r\n }\r\n const orderEntries = added.length - makerEntries - settlementEntries\r\n //the forwarding transfer runs only when something settles, which the simulation did not see\r\n const forward = settlementEntries > 0 ? 1 : 0\r\n applyResources(tx, data, {\r\n instructions: orderEntries * ORDER_INSTRUCTIONS + makers.size * MAKER_INSTRUCTIONS + forward * FORWARD_INSTRUCTIONS,\r\n diskReadBytes: diskEntries * MAKER_ENTRY_SIZE,\r\n writeBytes: orderEntries * ORDER_ENTRY_SIZE + (makerEntries + settlementEntries) * MAKER_ENTRY_SIZE,\r\n fee: BigInt(orderEntries) * ORDER_RESOURCE_FEE + BigInt(makerEntries + settlementEntries) * MAKER_ENTRY_RESOURCE_FEE +\r\n BigInt(makers.size) * MAKER_RESOURCE_FEE + BigInt(forward) * FORWARD_RESOURCE_FEE\r\n })\r\n return {orders: orderEntries, settlementEntries, makerEntries}\r\n}\r\n\r\n/**\r\n * @param {string} contractId\r\n * @param {xdr.ScVal} key\r\n * @param {xdr.ContractDataDurability} durability\r\n * @return {xdr.LedgerKey}\r\n * @private\r\n */\r\nfunction contractDataKey(contractId, key, durability) {\r\n return xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({\r\n contract: Address.fromString(contractId).toScAddress(),\r\n key,\r\n durability\r\n }))\r\n}\r\n\r\n/**\r\n * Whether the simulation succeeded and can be patched\r\n * @param {contract.AssembledTransaction} tx\r\n * @return {boolean}\r\n * @private\r\n */\r\nfunction isPatchable(tx) {\r\n const simulation = tx.simulation\r\n return !!simulation && !simulation.error && !simulation.restorePreamble && !!tx.built\r\n}\r\n\r\n/**\r\n * Fetch ledger entries, keyed by the base64 XDR of their ledger keys\r\n * @param {rpc.Server} server\r\n * @param {xdr.LedgerKey[]} keys\r\n * @return {Promise<Map<string, xdr.LedgerEntryData>>}\r\n * @private\r\n */\r\nasync function loadEntries(server, keys) {\r\n const res = new Map()\r\n for (let i = 0; i < keys.length; i += LEDGER_ENTRIES_BATCH) {\r\n const {entries} = await server.getLedgerEntries(...keys.slice(i, i + LEDGER_ENTRIES_BATCH))\r\n for (const entry of entries) {\r\n res.set(entry.key.toXDR('base64'), entry.val)\r\n }\r\n }\r\n return res\r\n}\r\n\r\n/**\r\n * Tokens from the list not resolved yet, deduplicated\r\n * @param {string[]} tokens\r\n * @param {Map<string, Asset|null>} assetCache\r\n * @return {string[]}\r\n * @private\r\n */\r\nfunction unresolved(tokens, assetCache) {\r\n return [...new Set(tokens)].filter(token => !assetCache.has(token))\r\n}\r\n\r\n/**\r\n * Store the classic asset of every token from the loaded instance entries (`null` when unknown)\r\n * @param {Map<string, xdr.LedgerEntryData>} entries\r\n * @param {string[]} tokens\r\n * @param {Map<string, Asset|null>} assetCache\r\n * @private\r\n */\r\nfunction cacheAssets(entries, tokens, assetCache) {\r\n for (const token of tokens) {\r\n const entry = entries.get(instanceLedgerKey(token).toXDR('base64'))\r\n assetCache.set(token, entry ? decodeSacAsset(entry.contractData.val) : null)\r\n }\r\n}\r\n\r\n/**\r\n * Add keys to the read-write part of a simulated footprint, dropping them from the read-only part, while the\r\n * footprint limits allow\r\n * @param {SorobanDataBuilder} data - Simulation data to patch\r\n * @param {xdr.LedgerKey[]} keys - Keys to declare, in priority order\r\n * @return {xdr.LedgerKey[]} - Keys actually added\r\n * @private\r\n */\r\nfunction declareReadWrite(data, keys) {\r\n const readOnly = data.getReadOnly()\r\n const readWrite = data.getReadWrite()\r\n const roIndex = new Map(readOnly.map((key, i) => [key.toXDR('base64'), i]))\r\n const rwIndex = new Set(readWrite.map(key => key.toXDR('base64')))\r\n const dropFromReadOnly = new Set()\r\n const added = []\r\n for (const key of keys) {\r\n const encoded = key.toXDR('base64')\r\n if (rwIndex.has(encoded))\r\n continue\r\n //a key promoted from the read-only part does not grow the footprint\r\n const promoted = roIndex.has(encoded)\r\n const total = readOnly.length - dropFromReadOnly.size + readWrite.length\r\n if (readWrite.length >= MAX_READ_WRITE_ENTRIES || (!promoted && total >= MAX_FOOTPRINT_ENTRIES))\r\n continue\r\n //a key can't be listed in both parts of the footprint\r\n if (promoted) {\r\n dropFromReadOnly.add(roIndex.get(encoded))\r\n }\r\n readWrite.push(key)\r\n rwIndex.add(encoded)\r\n added.push(key)\r\n }\r\n if (added.length) {\r\n data.setFootprint(readOnly.filter((_, i) => !dropFromReadOnly.has(i)), readWrite)\r\n }\r\n return added\r\n}\r\n\r\n/**\r\n * Declare the resources of the added entries and rebuild the transaction from the patched simulation data\r\n * @param {contract.AssembledTransaction} tx - Simulated transaction\r\n * @param {SorobanDataBuilder} data - Patched simulation data\r\n * @param {{instructions: number, diskReadBytes?: number, writeBytes: number, fee: bigint}} extra - Resources and fee to add\r\n * @private\r\n */\r\nfunction applyResources(tx, data, {instructions, diskReadBytes = 0, writeBytes, fee}) {\r\n const resources = data.build().resources\r\n data.setResources(Math.min(resources.instructions + instructions, MAX_TX_INSTRUCTIONS), resources.diskReadBytes + diskReadBytes, resources.writeBytes + writeBytes)\r\n data.setResourceFee((data.build().resourceFee + fee).toString())\r\n\r\n //drop cached simulation data so the SDK picks up the patched builder when signing\r\n delete tx.simulationTransactionData\r\n //keep the built transaction consistent with the patched footprint and fee\r\n const timeout = tx.options?.timeoutInSeconds ?? 300\r\n tx.built = TransactionBuilder.cloneFrom(tx.built, {\r\n sorobanData: data.build(),\r\n timebounds: undefined\r\n })\r\n .setTimeout(timeout)\r\n .build()\r\n}\r\n\r\n/**\r\n * @typedef {{}} FootprintOptions\r\n * @property {rpc.Server} server - RPC server used to load the listed orders and the token instances\r\n * @property {string[]} [tokens] - Tokens the call trades, resolved together with the orders\r\n * @property {Map<string, Asset|null>} [assetCache] - Classic assets of resolved tokens (`null` for other tokens), reused between calls\r\n * @property {string[]} [passThrough] - Tokens the call moves through the DEX contract's own balance: the bought asset of a\r\n * trade, every hop asset of a swap\r\n * @property {string} [receiver] - Account the bought asset is forwarded to (the trader, or the crossfill caller paid the surplus)\r\n * @property {string} [bought] - Token the receiver gets (the taker order's `buying` by default for a crossfill)\r\n * @property {bigint|number|string} [takerOrder] - Taker order of a crossfill: the asset it buys passes through the contract\r\n */\r\n","import {xdr, Address, hash} from '@stellar/stellar-sdk'\n\nconst U64_MAX = (1n << 64n) - 1n\n\n/**\n * Compute the id of the order `owner` creates with `nonce`.\n * Mirrors the contract: the first 16 bytes of `sha256(xdr(ScVec[owner: Address, nonce: u64]))`\n * interpreted as a big-endian `u128` (the full 128 bits, no mask).\n * @param {string} owner - Order owner address (account or contract)\n * @param {bigint|number|string} nonce - Client-chosen u64 nonce\n * @return {bigint} - u128 order id\n */\nexport function orderId(owner, nonce) {\n nonce = BigInt(nonce)\n if (nonce < 0n || nonce > U64_MAX)\n throw new RangeError('Nonce must fit u64')\n const payload = xdr.ScVal.scvVec([\n Address.fromString(owner).toScVal(),\n xdr.ScVal.scvU64(nonce)\n ]).toXDR()\n const digest = hash(payload)\n let id = 0n\n for (let i = 0; i < 16; i++) {\n id = (id << 8n) | BigInt(digest[i])\n }\n return id\n}\n\n/**\n * Generate a u64 order nonce: wall clock (in milliseconds) shifted left by 22 bits plus 22 random bits.\n * The clock part fits 42 bits until the year 2109, so the nonce never overflows u64; the random part makes\n * collisions among the orders an account creates within the same millisecond negligible.\n * Internal to the client - consumers never supply or observe nonces, `buy`/`sell` generate one per call.\n * @return {bigint}\n * @internal\n */\nexport function generateNonce() {\n return (BigInt(Date.now()) << 22n) | BigInt(randomBits22())\n}\n\nfunction randomBits22() {\n const crypto = globalThis.crypto\n if (crypto?.getRandomValues) {\n return crypto.getRandomValues(new Uint32Array(1))[0] & 0x3fffff\n }\n return Math.floor(Math.random() * 0x400000)\n}\n","/** Trading order type */\nexport const OrderKind = {\n /** Execute trade, create a limit order if not executed in full */\n Limit: 1,\n /** Execute trade without creating a limit order */\n Fill: 2,\n /** Execute trade, cancel if was not executed in full */\n FillOrKill: 3\n}\n\n/** Trade direction instructions */\nexport const TradeDirection = {\n Sell: 1,\n Buy: 2\n}\n","/** Minimal event emitter that works in browsers and Node */\nexport class Emitter {\n /**\n * @type {Map<string, Set<function>>}\n * @private\n */\n listeners = new Map()\n\n /**\n * Subscribe to an event\n * @param {string} event\n * @param {function} listener\n * @return {function(): void} - Unsubscribe function\n */\n on(event, listener) {\n let set = this.listeners.get(event)\n if (!set) {\n set = new Set()\n this.listeners.set(event, set)\n }\n set.add(listener)\n return () => this.off(event, listener)\n }\n\n /**\n * Subscribe to the next occurrence of an event\n * @param {string} event\n * @param {function} listener\n * @return {function(): void} - Unsubscribe function\n */\n once(event, listener) {\n const off = this.on(event, (...args) => {\n off()\n listener(...args)\n })\n return off\n }\n\n /**\n * Unsubscribe from an event\n * @param {string} event\n * @param {function} listener\n */\n off(event, listener) {\n const set = this.listeners.get(event)\n if (!set)\n return\n set.delete(listener)\n if (!set.size) {\n this.listeners.delete(event)\n }\n }\n\n /**\n * @param {string} event\n * @param {...*} args\n * @protected\n */\n emit(event, ...args) {\n const set = this.listeners.get(event)\n if (!set)\n return\n for (const listener of [...set]) {\n try {\n listener(...args)\n } catch (e) {\n console.error(`Unhandled error in \"${event}\" listener`, e)\n }\n }\n }\n}\n","import {Emitter} from './emitter.js'\n\n/**\n * WebSocket client of the AXIS API push channel\n *\n * Emits `open`, `close` and `error` (server errors not tied to a subscription).\n */\nexport class AxisStreamClient extends Emitter {\n /**\n * @param {string} url - WebSocket endpoint, e.g. `wss://demo-api.axis.markets/ws` (testnet)\n * @param {StreamClientOptions} [options]\n */\n constructor(url, {WebSocket: WebSocketImpl, pingInterval = 20_000, minReconnectDelay = 1_000, maxReconnectDelay = 30_000} = {}) {\n super()\n if (!url || typeof url !== 'string')\n throw new TypeError('WebSocket URL is required')\n this.url = url\n this.WebSocket = WebSocketImpl || globalThis.WebSocket\n if (!this.WebSocket)\n throw new Error('WebSocket is not available in this environment, pass the `WebSocket` option')\n this.pingInterval = pingInterval\n this.minReconnectDelay = minReconnectDelay\n this.maxReconnectDelay = maxReconnectDelay\n }\n\n /**\n * WebSocket endpoint\n * @type {string}\n * @readonly\n */\n url\n /**\n * Active subscriptions\n * @type {Set<StreamSubscription>}\n * @private\n */\n subscriptions = new Set()\n /**\n * Subscriptions by the server topic\n * @type {Map<string, Set<StreamSubscription>>}\n * @private\n */\n topics = new Map()\n /**\n * Subscriptions waiting for their snapshot, by request id\n * @type {Map<number, StreamSubscription>}\n * @private\n */\n requests = new Map()\n /**\n * @type {number}\n * @private\n */\n nextId = 1\n /**\n * @type {WebSocket|undefined}\n * @private\n */\n socket\n /**\n * @type {number}\n * @private\n */\n failures = 0\n /**\n * @type {boolean}\n * @private\n */\n closed = false\n\n /**\n * Whether the connection is open\n * @return {boolean}\n */\n get connected() {\n return !!this.socket && this.socket.readyState === 1\n }\n\n /**\n * Subscribe to a channel; connects on the first subscription\n * @param {'contract'|'ticker'|'account'|'trades'|'depth'|'candles'} channel\n * @param {{address?: string, market?: string, depth?: number, step?: string, resolution?: number|string, limit?: number}} params -\n * Channel parameters\n * @param {function(StreamMessage): void} handler - Receives the snapshot (again after every reconnect), the\n * changes, and `{type: 'error'}` if the server rejects the subscription\n * @return {function(): void} - Unsubscribe function\n */\n subscribe(channel, params, handler) {\n /** @type {StreamSubscription} */\n const sub = {channel, params: params || {}, handler, topic: undefined}\n this.subscriptions.add(sub)\n this.closed = false\n if (this.connected) {\n this.sendSubscribe(sub)\n } else {\n this.connect()\n }\n return () => this.unsubscribe(sub)\n }\n\n /**\n * Close the connection and drop every subscription\n */\n close() {\n this.closed = true\n this.subscriptions.clear()\n this.topics.clear()\n this.requests.clear()\n clearTimeout(this.reconnectTimer)\n this.stopPing()\n if (this.socket) {\n const socket = this.socket\n this.socket = undefined\n socket.close()\n }\n }\n\n /**\n * @param {StreamSubscription} sub\n * @private\n */\n unsubscribe(sub) {\n if (!this.subscriptions.delete(sub))\n return\n const {topic} = sub\n if (topic) {\n const subs = this.topics.get(topic)\n subs?.delete(sub)\n if (subs && !subs.size) {\n this.topics.delete(topic)\n if (this.connected && ![...this.subscriptions].some(s => s.topic === topic)) {\n this.send({op: 'unsubscribe', channel: sub.channel, ...sub.params})\n }\n }\n }\n for (const [id, pending] of this.requests) {\n if (pending === sub) {\n this.requests.delete(id)\n }\n }\n }\n\n /**\n * @private\n */\n connect() {\n if (this.socket || this.closed)\n return\n clearTimeout(this.reconnectTimer)\n let socket\n try {\n socket = new this.WebSocket(this.url)\n } catch (e) {\n this.scheduleReconnect()\n return\n }\n this.socket = socket\n socket.onopen = () => {\n if (this.socket !== socket)\n return\n this.failures = 0\n this.lastMessage = Date.now()\n this.startPing()\n for (const sub of this.subscriptions) {\n this.sendSubscribe(sub)\n }\n this.emit('open')\n }\n socket.onmessage = e => {\n if (this.socket !== socket)\n return\n this.lastMessage = Date.now()\n let message\n try {\n message = JSON.parse(typeof e.data === 'string' ? e.data : e.data.toString())\n } catch (err) {\n return\n }\n this.route(message)\n }\n socket.onclose = () => {\n if (this.socket !== socket)\n return\n this.socket = undefined\n this.stopPing()\n //topics are per connection\n this.topics.clear()\n this.requests.clear()\n for (const sub of this.subscriptions) {\n sub.topic = undefined\n }\n this.emit('close')\n this.scheduleReconnect()\n }\n socket.onerror = () => {\n //followed by close\n }\n }\n\n /**\n * @private\n */\n scheduleReconnect() {\n if (this.closed || !this.subscriptions.size)\n return\n const delay = Math.min(this.maxReconnectDelay, this.minReconnectDelay * 2 ** this.failures)\n this.failures++\n this.reconnectTimer = setTimeout(() => this.connect(), delay)\n }\n\n /**\n * @private\n */\n startPing() {\n this.stopPing()\n this.pingTimer = setInterval(() => {\n //no traffic for two periods: the connection is dead even if it was not closed\n if (Date.now() - this.lastMessage > this.pingInterval * 2) {\n this.socket?.close()\n return\n }\n this.send({op: 'ping'})\n }, this.pingInterval)\n }\n\n /**\n * @private\n */\n stopPing() {\n clearInterval(this.pingTimer)\n this.pingTimer = undefined\n }\n\n /**\n * @param {StreamSubscription} sub\n * @private\n */\n sendSubscribe(sub) {\n const id = this.nextId++\n this.requests.set(id, sub)\n this.send({op: 'subscribe', id, channel: sub.channel, ...sub.params})\n }\n\n /**\n * @param {{}} message\n * @private\n */\n send(message) {\n if (this.connected) {\n this.socket.send(JSON.stringify(message))\n }\n }\n\n /**\n * Deliver a server message to its subscriptions\n * @param {StreamMessage} message\n * @private\n */\n route(message) {\n if (message.type === 'pong' || message.type === 'unsubscribed')\n return\n if (message.id !== undefined && this.requests.has(message.id)) {\n //subscription response: snapshot (learn the topic) or rejection\n const sub = this.requests.get(message.id)\n this.requests.delete(message.id)\n if (message.type === 'error') {\n this.subscriptions.delete(sub)\n return deliver(sub, message)\n }\n if (message.topic) {\n sub.topic = message.topic\n let subs = this.topics.get(message.topic)\n if (!subs) {\n subs = new Set()\n this.topics.set(message.topic, subs)\n }\n subs.add(sub)\n }\n return deliver(sub, message)\n }\n if (message.topic) {\n for (const sub of this.topics.get(message.topic) || []) {\n deliver(sub, message)\n }\n return\n }\n if (message.type === 'error') {\n this.emit('error', new Error(message.error))\n }\n }\n}\n\n/**\n * @param {StreamSubscription} sub\n * @param {StreamMessage} message\n */\nfunction deliver(sub, message) {\n try {\n sub.handler(message)\n } catch (e) {\n console.error(`Unhandled error in the \"${sub.channel}\" subscription handler`, e)\n }\n}\n\n/**\n * @typedef {{}} StreamClientOptions\n * @property {typeof WebSocket} [WebSocket] - WebSocket implementation (the global one by default)\n * @property {number} [pingInterval] - Application-level ping period, in milliseconds (20 s by default)\n * @property {number} [minReconnectDelay] - First reconnect delay, doubled after each failure (1 s by default)\n * @property {number} [maxReconnectDelay] - Reconnect delay cap (30 s by default)\n */\n\n/**\n * @typedef {{}} StreamMessage - Server message; `type` names the payload, `topic` the subscription it belongs to\n * @property {string} type\n * @property {string} [topic]\n * @property {number} [id]\n */\n\n/**\n * @typedef {{}} StreamSubscription\n * @property {string} channel\n * @property {{}} params\n * @property {function(StreamMessage): void} handler\n * @property {string} [topic]\n * @internal\n */\n","import {Account, Address, Contract, Keypair, TransactionBuilder, scValToNative, rpc, xdr} from '@stellar/stellar-sdk'\n\n/**\n * Token state for allowance calculation, token balances, and current ledger\n */\nexport class TokenBalance {\n /**\n * @param {{rpcUrl: string, networkPassphrase: string, spender: string, server?: rpc.Server}} options - `spender`\n * is the AXIS contract\n */\n constructor({rpcUrl, networkPassphrase, spender, server}) {\n this.server = server || new rpc.Server(rpcUrl, {allowHttp: rpcUrl.startsWith('http://')})\n this.networkPassphrase = networkPassphrase\n this.spender = spender\n }\n\n /**\n * Allowance `owner` granted to the AXIS contract on a token, 0 when expired\n * @param {string} token - Token contract address\n * @param {string} owner - Token holder address\n * @return {Promise<bigint>}\n * @throws {Error} - If the simulation fails\n */\n async getAllowance(token, owner) {\n const retval = await this.load(token, 'allowance', [new Address(owner).toScVal(), new Address(this.spender).toScVal()], owner)\n return toBigInt(retval)\n }\n\n /**\n * Token balance of an account\n * @param {string} token - Token contract address\n * @param {string} owner - Token holder address\n * @return {Promise<bigint>} - 0 if the account holds no balance entry\n */\n async getBalance(token, owner) {\n try {\n return toBigInt(await this.load(token, 'balance', [new Address(owner).toScVal()], owner))\n } catch (e) {\n return 0n\n }\n }\n\n /**\n * Latest closed ledger sequence\n * @return {Promise<number>}\n */\n async getLatestLedger() {\n const {sequence} = await this.server.getLatestLedger()\n return sequence\n }\n\n /**\n * @param {string} token\n * @param {string} method\n * @param {xdr.ScVal[]} args\n * @param {string} source - Transaction source address\n * @return {Promise<xdr.ScVal>}\n * @private\n */\n async load(token, method, args, source) {\n //a contract address cannot be a transaction source\n const sourceAccount = source.startsWith('G') ? source : Keypair.random().publicKey()\n const tx = new TransactionBuilder(new Account(sourceAccount, '0'), {fee: '100', networkPassphrase: this.networkPassphrase})\n .addOperation(new Contract(token).call(method, ...args))\n .setTimeout(30)\n .build()\n const sim = await this.server.simulateTransaction(tx)\n if (rpc.Api.isSimulationError(sim))\n throw new Error(`Token ${method} simulation failed for ${token}: ${sim.error}`)\n return sim.result.retval\n }\n}\n\n/**\n * @param {xdr.ScVal} retval\n * @return {bigint}\n */\nfunction toBigInt(retval) {\n const value = scValToNative(retval)\n return typeof value === 'bigint' ? value : BigInt(value ?? 0)\n}\n","import {Address} from '@stellar/stellar-sdk'\n\n/** Price scale of the contract (18 decimals) */\nexport const PRICE_SCALE = 10n ** 18n\n\n/**\n * Serialized `ScAddress` by address string\n * @type {Map<string, Uint8Array>}\n */\nconst keyCache = new Map()\n\n/**\n * @param {string} address\n * @return {Uint8Array}\n */\nfunction getAddressKey(address) {\n let key = keyCache.get(address)\n if (!key) {\n key = Address.fromString(address).toScAddress().toXDR()\n if (keyCache.size >= 10_000) { //will never happen in real life\n keyCache.clear()\n }\n keyCache.set(address, key)\n }\n return key\n}\n\n/**\n * Compare two assets in the contract canonical order\n * @param {string} a - Token contract address\n * @param {string} b - Token contract address\n * @return {number} - Negative if `a` first, positive if `b` first, 0 if equal\n */\nexport function compareAssets(a, b) {\n if (a === b)\n return 0\n const key1 = getAddressKey(a)\n const key2 = getAddressKey(b)\n const length = Math.min(key1.length, key2.length)\n for (let i = 0; i < length; i++) {\n if (key1[i] !== key2[i])\n return key1[i] - key2[i]\n }\n return key1.length - key2.length\n}\n\n/**\n * Reorder an asset pair the way the contract stores markets\n * @param {string} x - Token contract address\n * @param {string} y - Token contract address\n * @return {[string, string]} - `[a, b]`: `a` is the base, `b` the quote of the canonical market symbol\n */\nexport function canonicalPair(x, y) {\n return compareAssets(x, y) <= 0 ? [x, y] : [y, x]\n}\n\n/**\n * Canonical market key `a/b`\n * @param {string} a - Token contract address\n * @param {string} b - Token contract address\n * @return {string}\n */\nexport function pairKey(a, b) {\n const [a1, a2] = canonicalPair(a, b)\n return a1 + '/' + a2\n}\n\n/**\n * Calculate inverted price, rounded down: `floor(10^36 / price)`\n * @param {bigint} price - Price in the contract scale\n * @return {bigint}\n */\nexport function invertPrice(price) {\n if (price <= 0n)\n return 0n\n return PRICE_SCALE * PRICE_SCALE / price\n}\n\n/**\n * 24h ticker entry of the market seen in the inverted orientation (`b/a`)\n * @param {TickerEntry} entry - Standard ticker entry\n * @return {TickerEntry}\n */\nexport function invertTicker(entry) {\n const [a, b] = entry.symbol.split('/')\n const inv = value => {\n const n = Number(value)\n return n > 0 ? String(1 / n) : '0'\n }\n const open = Number(entry.openPrice)\n const last = Number(entry.lastPrice)\n return {\n ...entry,\n symbol: b + '/' + a,\n openPrice: inv(entry.openPrice),\n highPrice: inv(entry.lowPrice),\n lowPrice: inv(entry.highPrice),\n lastPrice: inv(entry.lastPrice),\n volume: entry.quoteVolume,\n quoteVolume: entry.volume,\n change: open > 0 && last > 0 ? Math.round((open / last - 1) * 100_000) / 1000 : 0,\n avgPrice: inv(entry.avgPrice)\n }\n}\n","/**\n * Parse an AXIS API timestamp (`YYYY-MM-DD HH:mm:ss` UTC)\n * @param {string|number|undefined} value\n * @return {number} - UNIX milliseconds, 0 when missing or invalid\n */\nexport function parseApiDate(value) {\n if (value === undefined || value === null || value === '')\n return 0\n if (typeof value === 'number')\n return value\n let text = String(value).trim().replace(' ', 'T')\n if (!/[zZ]|[+-]\\d\\d:?\\d\\d$/.test(text)) {\n text += 'Z'\n }\n const ms = Date.parse(text)\n return Number.isFinite(ms) ? ms : 0\n}\n","import {canonicalPair} from './asset-pair.js'\nimport {parseApiDate} from './api-dates.js'\n\n/**\n * DEX Market\n */\nexport class AxisMarket {\n /**\n * @param {Axis} axis\n * @param {{base: string, quote: string, created?: string, refreshed?: string}} record - Market data\n */\n constructor(axis, record) {\n this.axis = axis\n const [base, quote] = canonicalPair(record.base, record.quote)\n this.base = base\n this.quote = quote\n this.key = base + '/' + quote\n this.update(record)\n }\n\n /**\n * Base asset, the first of the pair in the contract canonical order\n * @type {string}\n * @readonly\n */\n base\n /**\n * Quote asset, the second of the pair in the contract canonical order\n * @type {string}\n * @readonly\n */\n quote\n /**\n * Canonical market key `base/quote`\n * @type {string}\n * @readonly\n */\n key\n /**\n * Creation timestamp (first oracle check) (UNIX milliseconds)\n * @type {number}\n */\n created = 0\n /**\n * Last oracle check (UNIX milliseconds)\n * @type {number}\n */\n refreshed = 0\n\n /**\n * Check whether the asset is one of the market assets\n * @param {string} asset\n * @return {boolean}\n */\n has(asset) {\n return asset === this.base || asset === this.quote\n }\n\n /**\n * The other market asset\n * @param {string} asset - One of the market assets\n * @return {string}\n */\n counter(asset) {\n if (asset === this.base)\n return this.quote\n if (asset === this.quote)\n return this.base\n throw new Error(`Asset ${asset} does not belong to the market ${this.key}`)\n }\n\n /**\n * Apply the contract state change record\n * @param {{created?: string, refreshed?: string}} record\n * @internal\n */\n update(record) {\n if (record.created) {\n this.created = parseApiDate(record.created)\n }\n if (record.refreshed) {\n this.refreshed = parseApiDate(record.refreshed)\n }\n }\n\n /**\n * Re-check both market assets against the price oracle and cache oracle prices\n * @param {Signer} [signer] - Transaction source, the {@link Axis} signer by default\n * @return {Promise<Market|undefined>}\n */\n async requote(signer) {\n const client = await this.axis.contractClient(signer)\n return client.requote(this.base, this.quote)\n }\n\n /**\n * Extend oracle price feeds access for the market\n * @param {{amount: bigint, sponsor?: string, signer?: Signer}} params - `amount` of fee tokens to burn\n * @return {Promise<bigint[]>} - New access expiration UNIX timestamps (in seconds) for each oracle-listed asset\n */\n async subsidize({amount, sponsor, signer}) {\n const client = await this.axis.contractClient(signer)\n return client.subsidize({sponsor: sponsor ?? client.publicKey, selling: this.base, buying: this.quote, amount})\n }\n\n /**\n * Orderbook depth data with given precision\n * @param {{base?: string, depth?: number, step?: string, limit?: number}} [params] - `base` is the base asset, `step` the price step (automatic by default)\n * @return {Promise<import('./api-client.js').OrderbookDepth>}\n */\n async getDepth({base = this.base, depth, step, limit} = {}) {\n return this.axis.api.getDepth({market: base + '/' + this.counter(base), depth, step, limit})\n }\n\n /**\n * Stream the orderbook depth\n * Returns a snapshot, then updates on book changes\n * @param {{base?: string, depth?: number, step?: string, limit?: number}} params\n * @param {function(OrderbookDepth): void} callback\n * @return {function(): void} - Unsubscribe function\n */\n subscribeDepth({base = this.base, depth, step, limit} = {}, callback) {\n const market = base + '/' + this.counter(base)\n return this.axis.stream.subscribe('depth', {market, depth, step, limit}, message => {\n if (message.type === 'depth') {\n callback(message.data)\n }\n })\n }\n\n /**\n * Stream the market trades\n * Returns a snapshot, then updates on trades\n * @param {function(ApiTrade[], boolean): void} callback - Trades and whether they are the snapshot\n * @return {function(): void} - Unsubscribe function\n */\n subscribeTrades(callback) {\n return this.axis.stream.subscribe('trades', {market: this.key}, message => {\n if (message.type === 'trades') {\n callback(message.trades, true)\n } else if (message.type === 'trade') {\n callback([message.trade], false)\n }\n })\n }\n\n /**\n * Stream the market candles\n * Returns a snapshot, then updates on trades\n * @param {{base?: string, resolution: number|string, limit?: number}} params - `base` is the base asset of the view, `resolution` in seconds or an alias (`5m`, `1h`, …), `limit` the candles in the snapshot (200 by default, at most 200)\n * @param {function(Candle[], boolean): void} callback - Candles\n * @return {function(): void} - Unsubscribe function\n */\n subscribeCandles({base = this.base, resolution, limit}, callback) {\n const market = base + '/' + this.counter(base)\n return this.axis.stream.subscribe('candles', {market, resolution, limit}, message => {\n if (message.type === 'candles') {\n callback(message.candles, true)\n } else if (message.type === 'candle') {\n callback([message.candle], false)\n }\n })\n }\n\n /**\n * Last 24h ticker entry of the market, available while {@link Axis#subscribeTicker} runs\n * @return {TickerEntry|undefined}\n */\n get ticker() {\n return this.axis.tickers.get(this.key)\n }\n\n toJSON() {\n return {base: this.base, quote: this.quote, key: this.key, created: this.created, refreshed: this.refreshed}\n }\n}\n\n/**\n * @typedef {{}} Signer - Account signing contract calls\n * @property {string} publicKey - Transaction source account\n * @property {SignTransactionCallback} signTransaction\n */\n","import {PRICE_SCALE} from './asset-pair.js'\n\n/**\n * Allowance lifetime granted with a trade, in ledgers: ~30 days at 5s per ledger (the maximum entry TTL ~180 days)\n */\nexport const APPROVAL_TTL_LEDGERS = 518_400\n\n/**\n * An allowance expiring within this number of ledgers is renewed with the next trade (~1 day)\n */\nexport const APPROVAL_RENEW_LEDGERS = 17_280\n\n/**\n * Decide whether a call needs an in-call approval and adjust it. The approval amount is absolute and one allowance backs\n * every order selling the token across all markets, so it has to cover this call plus every order selling the same asset\n * @param {ApprovalPlanParams} params\n * @return {{amount: bigint, liveUntil: number}|undefined} - Approval to pass with the call, undefined when the current allowance already covers it\n */\nexport function planApproval({required, committed, allowance, liveUntil, ledger}) {\n const target = required + committed\n const expiring = liveUntil > 0 && liveUntil < ledger + APPROVAL_RENEW_LEDGERS\n if (allowance >= target && !expiring)\n return undefined //TODO: reduce outstanding allowances if the backed amount is reduced (expired or cancelled)\n return {amount: target, liveUntil: ledger + APPROVAL_TTL_LEDGERS}\n}\n\n/**\n * Max amount of `selling` tokens a buy trade may cost: `ceil(amount × price / 10^18)`\n * @param {bigint} amount - Amount of `buying` tokens to acquire\n * @param {bigint} price - Limit price (`selling` per 1 `buying`, with AXIS standard price decimals)\n * @return {bigint}\n */\nexport function maxQuoteSpend(amount, price) {\n if (amount <= 0n || price <= 0n)\n return 0n\n return (amount * price + PRICE_SCALE - 1n) / PRICE_SCALE\n}\n\n/**\n * @typedef {{}} ApprovalPlanParams\n * @property {bigint} required - Max amount of the selling asset the call may spend\n * @property {bigint} committed - Remaining amount of orders in the book selling the asset\n * @property {bigint} allowance - Current allowance (0 once expired)\n * @property {number} ledger - Current ledger sequence\n * @property {number} [liveUntil] - Ledger the current allowance lives until (0 or omitted when unknown)\n */\n","import {Emitter} from './emitter.js'\nimport {pairKey, invertPrice} from './asset-pair.js'\nimport {parseApiDate} from './api-dates.js'\nimport {planApproval, maxQuoteSpend} from './allowance.js'\nimport {OrderKind, TradeDirection} from './constants.js'\n\n/** Orders per `update` transaction */\nconst UPDATE_BATCH = 90\n/** Time to wait for the account state before trading, in milliseconds */\nconst READY_TIMEOUT = 15_000\n/** How long an order created by this client counts as committed before the indexer reports it, in milliseconds */\nconst LOCAL_ORDER_TTL = 120_000\n\n/**\n * Trader wrapper that tracks every open order of an account across all markets and the account backing.\n * Create it with {@link import('./axis.js').Axis#account}.\n *\n * Emits:\n * - `ready` - the account state was loaded\n * - `new` {@link AccountOrder} - an order was created (confirmed by the indexer)\n * - `pending` {@link AccountOrder} - an order created by this client, not reported by the indexer yet\n * - `fill` {@link AccountFill} - an order was partially filled\n * - `filled` {@link AccountFill} - an order was filled in full\n * - `update` {@link AccountOrder} - an order changed (amount, price, expiration, revived)\n * - `cancel` {@link AccountOrder} - an order was removed by the owner\n * - `expire` {@link AccountOrder} - an order expired\n * - `remove` {@link AccountOrder} - an order left the open orders (after `filled`, `cancel`, `expire`)\n * - `order` `{action, order, fill?}` - any order change\n * - `backing` `{asset, backing}` - the balance, allowance or the backing split of the orders selling a token changed\n * - `approve` `{asset, amount, liveUntil}` - a trading call is about to grant an allowance\n * - `trade` {ApiTrade} - the account performed a trade\n * - `swap` {ApiSwap} - the account performed a swap\n * - `change` - the open orders or the backing changed\n * - `error` `Error` - the push API rejected the account subscription\n */\nexport class AxisAccount extends Emitter {\n /**\n * @param {Axis} axis\n * @param {string} address - Trader address\n * @param {{signTransaction?: SignTransactionCallback}} [options]\n */\n constructor(axis, address, {signTransaction} = {}) {\n super()\n this.axis = axis\n this.address = address\n this.signTransaction = signTransaction\n this.ready = new Promise(resolve => this.resolveReady = resolve)\n }\n\n /**\n * Trader address\n * @type {string}\n * @readonly\n */\n address\n /**\n * Wallet signing callback, required to trade\n * @type {SignTransactionCallback|undefined}\n */\n signTransaction\n /**\n * Open orders by id\n * @type {Map<string, AccountOrder>}\n * @readonly\n */\n orders = new Map()\n /**\n * Account backing by token contract id\n * @type {Map<string, AccountBacking>}\n * @readonly\n */\n backing = new Map()\n /**\n * Resolves once the account state has been loaded\n * @type {Promise<void>}\n * @readonly\n */\n ready\n /**\n * Whether the account state has been loaded\n * @type {boolean}\n */\n loaded = false\n /**\n * Orders created by this client that the indexer has not reported yet\n * @type {Map<string, {order: AccountOrder, expires: number}>}\n * @private\n */\n local = new Map()\n /**\n * Whether the backing in memory get updated from the push API\n * @type {boolean}\n * @private\n */\n live = false\n /**\n * Last taker spend of this client by token, UNIX milliseconds\n * @type {Map<string, number>}\n * @private\n */\n spent = new Map() //TODO: drop this\n /**\n * @type {function(): void}\n * @private\n */\n resolveReady\n\n /**\n * Start tracking this account\n * @internal\n */\n start() {\n const {stream} = this.axis\n this.unsubscribe = stream.subscribe('account', {address: this.address}, message => this.handle(message))\n this.offOpen = stream.on('open', () => this.stopFallback())\n this.offClose = stream.on('close', () => {\n this.live = false //changes are missed until the next snapshot\n this.startFallback()\n })\n //load over REST if the push API does not deliver the snapshot soon\n this.initTimer = setTimeout(() => {\n if (!this.loaded) {\n this.refresh().catch(() => this.startFallback())\n }\n }, 3_000)\n }\n\n /**\n * Stop tracking this account\n */\n close() {\n clearTimeout(this.initTimer)\n this.stopFallback()\n this.unsubscribe?.()\n this.offOpen?.()\n this.offClose?.()\n this.axis.releaseAccount(this)\n }\n\n /**\n * Reload current account state from the REST API\n * @return {Promise<void>}\n */\n async refresh() {\n //the REST state lists only the tokens of the orders once nobody subscribes: keep the other balances\n this.applySnapshot(await this.axis.api.getAccount(this.address), true)\n }\n\n /**\n * Retrieve open orders, newest first\n * @param {{market?: string|{base: string, quote: string}|string[], selling?: string, buying?: string}} [filter] - `market` is an {AxisMarket} or a pair of assets in any order\n * @return {AccountOrder[]}\n */\n getOrders({market, selling, buying} = {}) { //TODO: simplify market argument\n const key = toMarketKey(market)\n const res = []\n for (const order of this.allOrders()) {\n if (key && order.market !== key)\n continue\n if (selling && order.selling !== selling)\n continue\n if (buying && order.buying !== buying)\n continue\n res.push(order)\n }\n return res.sort(newestFirst)\n }\n\n /**\n * Get open order by id\n * @param {bigint|string} id\n * @return {AccountOrder|undefined}\n */\n getOrder(id) {\n const key = id.toString()\n return this.orders.get(key) ?? this.localOrders().find(order => order.id === key)\n }\n\n /**\n * Calculate the remaining amount of the open orders selling the token across every market (what the allowance must cover)\n * @param {string} asset - Token contract id\n * @return {bigint}\n */\n committed(asset) {\n let sum = 0n\n for (const order of this.allOrders()) {\n if (order.selling === asset) {\n sum += order.amount\n }\n }\n return sum\n }\n\n /**\n * Get spendable balance of the account in a token\n * @param {string} asset - Token contract id\n * @return {bigint|undefined} - Undefined if not tracked\n */\n getBalance(asset) {\n const backing = this.backing.get(asset)\n return backing?.updated ? backing.balance : undefined\n }\n\n /**\n * Get spendable balances in every tracked token by token contract id\n * @return {Map<string, bigint>}\n */\n get balances() {\n const res = new Map()\n for (const [asset, backing] of this.backing) {\n if (backing.updated) {\n res.set(asset, backing.balance)\n }\n }\n return res\n }\n\n /**\n * Whether the account exists on the ledger\n * @return {boolean|undefined}\n */\n get funded() {\n const backing = this.backing.get(this.axis.nativeAsset)\n return backing?.updated ? backing.authorized : undefined\n }\n\n /**\n * Get balance, allowance and commitments of the account in a token\n * @param {string} asset - Token contract id\n * @return {AccountAllowance}\n */\n getAllowance(asset) {\n const backing = this.backing.get(asset)\n const committed = this.committed(asset)\n if (!backing?.updated)\n return {asset, known: false, committed}\n return {\n asset,\n known: true,\n balance: backing.balance,\n allowance: backing.allowance,\n liveUntil: backing.liveUntil,\n authorized: backing.authorized,\n pending: backing.pending,\n available: backing.budget,\n committed\n }\n }\n\n /**\n * Sell tokens creating a limit remainder order if not executed in full\n * @param {TradeParams} params - `amount` of `selling` to sell; `price` is the minimum `buying` per 1 `selling`\n * @return {Promise<TradeResult>}\n */\n async sell(params) {\n return this.trade(TradeDirection.Sell, params)\n }\n\n /**\n * Buy tokens creating a limit remainder order if not executed in full\n * @param {TradeParams} params - `amount` of `buying` to acquire; `price` is the maximum `selling` per 1 `buying`\n * @return {Promise<TradeResult>}\n */\n async buy(params) {\n return this.trade(TradeDirection.Buy, params)\n }\n\n /**\n * Simulate a sell with the same crossing and approval as `sell`, without signing or submitting it\n * @param {TradeParams} params - Same as `sell`\n * @return {Promise<import('./index.js').TradeEstimate>} - Network fee and expected result\n */\n async estimateSell(params) {\n const {payload} = await this.prepareTrade(TradeDirection.Sell, params)\n const client = await this.client()\n return client.estimateSell(payload)\n }\n\n /**\n * Simulate a buy with the same crossing and approval as `buy`, without signing or submitting it\n * @param {TradeParams} params - Same as `buy`\n * @return {Promise<import('./index.js').TradeEstimate>} - Network fee and expected result\n */\n async estimateBuy(params) {\n const {payload} = await this.prepareTrade(TradeDirection.Buy, params)\n const client = await this.client()\n return client.estimateBuy(payload)\n }\n\n /**\n * Change the amount, price or expiration of open orders (omitted fields keep their current values)\n * @param {Array<{id: bigint|string, amount?: bigint, price?: bigint, expires?: number}>} updates\n * @return {Promise<bigint[]>} - Updated order ids\n */\n async update(updates) {\n await this.whenReady()\n const normalized = updates.map(update => {\n const current = this.getOrder(update.id)\n if (!current && (update.amount === undefined || update.price === undefined))\n throw new Error(`Order ${update.id} is not an open order of ${this.address}`)\n return {\n current,\n update: {\n id: BigInt(update.id),\n amount: update.amount ?? current.amount,\n price: update.price ?? current.price,\n expires: update.expires ?? current?.expires ?? 0\n }\n }\n })\n //extra commitment per sold token\n const growth = new Map()\n for (const {current, update} of normalized) {\n if (!current)\n continue\n growth.set(current.selling, (growth.get(current.selling) ?? 0n) + update.amount - current.amount)\n }\n const approvals = []\n for (const [asset, delta] of growth) {\n if (delta <= 0n)\n continue\n const approve = await this.planApproval(asset, delta)\n if (approve) {\n this.emit('approve', {asset, ...approve})\n approvals.push({asset, ...approve})\n }\n }\n const client = await this.client()\n const res = []\n for (let i = 0; i < normalized.length; i += UPDATE_BATCH) {\n const batch = normalized.slice(i, i + UPDATE_BATCH).map(n => n.update)\n //approvals travel with the first batch, before its backing check\n const ids = await client.update({trader: this.address, updates: batch, approvals: i === 0 ? approvals : []})\n res.push(...ids)\n }\n return res\n }\n\n /**\n * Cancel open orders\n * @param {Array<bigint|string>} ids\n * @return {Promise<void>}\n */\n async cancel(ids) {\n const client = await this.client()\n const all = ids.map(id => BigInt(id))\n for (let i = 0; i < all.length; i += UPDATE_BATCH) {\n await client.cancel(this.address, all.slice(i, i + UPDATE_BATCH))\n }\n for (const id of all) {\n this.local.delete(id.toString())\n }\n }\n\n /**\n * Cancel all open orders\n * @param {{market?: string|{base: string, quote: string}|string[]}} [filter]\n * @return {Promise<string[]>} - Canceled order ids\n */\n async cancelAll({market} = {}) {\n await this.whenReady()\n const ids = this.getOrders({market}).map(order => order.id)\n if (ids.length) {\n await this.cancel(ids)\n }\n return ids\n }\n\n /**\n * Fill an open order against the book while keeping profits from price inefficiencies\n * @param {bigint|string} takerOrderId - Order acting as the taker\n * @param {Array<bigint|string>} [orders] - Counter orders, looked up automatically when omitted\n * @return {Promise<{sold: bigint, bought: bigint, surplus: bigint}>}\n */\n async crossfill(takerOrderId, orders) {\n if (!orders) {\n const taker = this.getOrder(takerOrderId) ?? await this.axis.getOrder(takerOrderId)\n if (!taker)\n throw new Error(`Order ${takerOrderId} not found`)\n orders = (await this.findQuote(TradeDirection.Sell, taker.selling, taker.buying, taker.amount)).orders\n }\n const client = await this.client()\n const [sold, bought, surplus] = await client.crossfill(this.address, BigInt(takerOrderId), orders.map(id => BigInt(id)))\n return {sold, bought, surplus}\n }\n\n /**\n * Swap across one or several markets along the best route found by the AXIS API\n * @param {SwapParams} params\n * @return {Promise<{sold: bigint, bought: bigint, approve?: import('./index.js').Approval}>}\n */\n async swap({selling, buying, amount, direction = TradeDirection.Sell, slippage = 0}) {\n await this.whenReady()\n const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString()}\n const quote = direction === TradeDirection.Buy ?\n await this.axis.api.quoteBuy(params) :\n await this.axis.api.quoteSell(params)\n const best = quote.paths?.[0]\n if (quote.status !== 'success' || !best?.path?.length)\n throw new Error(quote.error || 'No route available')\n const path = best.path.map(hop => ({asset: hop.buying, orders: hop.orders.filter(Boolean).map(id => BigInt(id))}))\n const tolerance = BigInt(Math.round(slippage * 10_000))\n let sellingAmount = BigInt(best.sold)\n let buyingAmount = BigInt(best.bought)\n if (direction === TradeDirection.Buy) {\n sellingAmount = (sellingAmount * (10_000n + tolerance) + 9_999n) / 10_000n\n } else {\n buyingAmount = buyingAmount * (10_000n - tolerance) / 10_000n\n }\n //`sellingAmount` is the exact spend of a sell and the most a buy may spend\n const approve = await this.planApproval(selling, sellingAmount)\n if (approve) {\n this.emit('approve', {asset: selling, ...approve})\n }\n const client = await this.client()\n const [sold, bought] = await client.swap({\n direction,\n trader: this.address,\n selling,\n sellingAmount,\n buyingAmount,\n path,\n approve\n })\n this.spent.set(selling, Date.now())\n return {sold, bought, approve}\n }\n\n /**\n * Compute approval for a call\n * @param {string} asset - Token contract id\n * @param {bigint} required - Max amount the call may spend\n * @return {Promise<{amount: bigint, liveUntil: number}|undefined>}\n */\n async planApproval(asset, required) {\n await this.whenReady()\n const backing = this.backing.get(asset)\n let allowance\n if (this.isAllowanceCurrent(asset) || (backing?.updated && !this.axis.tokenBalances)) {\n allowance = backing.allowance\n } else {\n const {tokenBalances} = this.axis\n if (!tokenBalances)\n throw new Error(`The allowance of ${this.address} in ${asset} is not tracked: set the \\`rpcUrl\\` option to read it`)\n await this.axis.getContractId() //the allowance spender\n allowance = await tokenBalances.getAllowance(asset, this.address).catch(() => 0n) //unknown: a redundant approval, never a shortfall\n }\n return planApproval({\n required,\n committed: this.committed(asset),\n allowance,\n liveUntil: backing?.liveUntil ?? 0,\n ledger: await this.axis.getLedger()\n })\n }\n\n /**\n * Check whether the pushed allowance of a token can be used as is\n * @param {string} asset - Token contract id\n * @return {boolean}\n * @private\n */\n isAllowanceCurrent(asset) {\n const backing = this.backing.get(asset)\n if (!this.live || !this.axis.stream.connected || !backing?.updated || backing.pending)\n return false\n const spent = this.spent.get(asset)\n if (spent === undefined)\n return true\n if (Date.now() - spent < 30_000) //the spend lowers the allowance before the push reporting it arrives\n return false //TODO: try to read allowance change from tx result meta changes\n this.spent.delete(asset)\n return true\n }\n\n /**\n * @param {number} direction\n * @param {TradeParams} params\n * @return {Promise<TradeResult>}\n * @private\n */\n async trade(direction, params) {\n const {payload, planned} = await this.prepareTrade(direction, params)\n const {selling, buying, amount, price, expires, approve} = payload\n if (planned && approve) {\n this.emit('approve', {asset: selling, ...approve})\n }\n const client = await this.client()\n const [sold, bought, createdId] = direction === TradeDirection.Buy ?\n await client.buy(payload) :\n await client.sell(payload)\n this.spent.set(selling, Date.now())\n let order\n if (createdId) {\n order = await this.trackCreated(createdId, {direction, selling, buying, amount, price, sold, bought, expires})\n }\n return {sold, bought, orderId: createdId ? createdId.toString() : undefined, order, approve}\n }\n\n /**\n * Resolve the crossing orders, the price of a market order and the approval of a trade\n * @param {number} direction\n * @param {TradeParams} params\n * @return {Promise<{payload: import('./index.js').TradeArguments, planned: boolean}>} - Contract call arguments,\n * `planned` if the approval was planned by the account rather than supplied\n * @private\n */\n async prepareTrade(direction, {selling, buying, amount, price, kind, expires, orders, approve}) {\n await this.whenReady()\n amount = BigInt(amount)\n const market = price === undefined || price === null\n if (kind === undefined) {\n kind = market ? OrderKind.Fill : OrderKind.Limit\n }\n let crossing\n if (!orders || market) {\n //a limit order crosses only the orders its price reaches (the contract threshold: the price of a buy, the\n //inverted price of a sell) and rests with the remainder, so a partial crossing is quoted as well\n const maxPrice = market ? undefined : direction === TradeDirection.Buy ? BigInt(price) : invertPrice(BigInt(price))\n crossing = await this.findQuote(direction, selling, buying, amount, maxPrice)\n }\n if (market) {\n //cross everything the quote found: the limit is the worst maker price (makers price `selling` per\n //`buying` of a buyer; seen from a seller, invert it)\n if (!crossing.worstPrice)\n throw new Error('Not enough liquidity for a market order')\n price = direction === TradeDirection.Buy ? crossing.worstPrice : invertPrice(crossing.worstPrice)\n }\n price = BigInt(price)\n const planned = approve === undefined\n if (planned) {\n const required = direction === TradeDirection.Buy ? maxQuoteSpend(amount, price) : amount\n approve = await this.planApproval(selling, required)\n }\n const payload = {\n kind,\n trader: this.address,\n amount,\n selling,\n buying,\n price,\n orders: (orders ?? crossing.orders).map(id => BigInt(id)),\n expires,\n approve: approve || undefined\n }\n return {payload, planned}\n }\n\n /**\n * Count an order this client created as committed until the indexer reports it\n * @param {bigint} id\n * @param {{}} trade - Trade parameters and result, for an estimate if the order cannot be read\n * @return {Promise<AccountOrder|undefined>}\n * @private\n */\n async trackCreated(id, {direction, selling, buying, amount, price, sold, bought, expires}) {\n const key = id.toString()\n if (this.orders.has(key))\n return this.orders.get(key) //already reported\n let stored\n try {\n const client = await this.client()\n stored = await client.order(id)\n } catch (e) {\n //estimate below\n }\n if (this.orders.has(key))\n return this.orders.get(key)\n let orderAmount\n let orderPrice\n if (stored) {\n orderAmount = stored.amount\n orderPrice = stored.price\n } else if (direction === TradeDirection.Sell) {\n orderAmount = amount - sold\n orderPrice = price\n } else {\n //the remainder of a buy sells `selling` for the rest of `buying` at the limit\n orderAmount = maxQuoteSpend(amount - bought, price)\n orderPrice = invertPrice(price)\n }\n const now = Date.now()\n /** @type {AccountOrder} */\n const order = {\n id: key,\n owner: this.address,\n selling,\n buying,\n market: pairKey(selling, buying),\n status: 'ACTIVE',\n price: orderPrice,\n amount: orderAmount,\n quote: orderAmount,\n expires: Number(stored?.expires ?? expires ?? 0),\n created: now,\n updated: now,\n cursor: undefined,\n backed: null,\n backedPct: null,\n backingPending: true,\n filledPct: 0,\n pending: true\n }\n this.local.set(key, {order, expires: now + LOCAL_ORDER_TTL})\n this.emit('pending', order)\n this.emit('change')\n return order\n }\n\n /**\n * Crossing orders of a direct-market trade and the worst price among them\n * @param {number} direction\n * @param {string} selling\n * @param {string} buying\n * @param {bigint} amount - `selling` amount of a sell, `buying` amount of a buy\n * @param {bigint} [maxPrice] - Highest maker price to cross, for a limit order\n * @return {Promise<{orders: string[], worstPrice: bigint|null}>}\n * @private\n */\n async findQuote(direction, selling, buying, amount, maxPrice) {\n const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString(), direct: true, maxPrice}\n try {\n const quote = direction === TradeDirection.Buy ?\n await this.axis.api.quoteBuy(params) :\n await this.axis.api.quoteSell(params)\n const hop = quote.status === 'success' ? quote.paths?.[0]?.path?.[0] : null\n if (hop)\n return {orders: hop.orders ?? [], worstPrice: hop.worstPrice ? BigInt(hop.worstPrice) : null}\n } catch (e) {\n //nothing to cross: a limit order simply rests\n }\n return {orders: [], worstPrice: null}\n }\n\n /**\n * @return {Promise<AxisContractClient>}\n * @private\n */\n async client() {\n if (!this.signTransaction)\n throw new Error(`No signTransaction callback for ${this.address}: pass it to axis.account()`)\n return this.axis.contractClient({publicKey: this.address, signTransaction: this.signTransaction})\n }\n\n /**\n * @param {number} [timeout]\n * @return {Promise<void>}\n * @private\n */\n async whenReady(timeout = READY_TIMEOUT) {\n if (this.loaded)\n return\n let timer\n try {\n await Promise.race([\n this.ready,\n new Promise((resolve, reject) => {\n timer = setTimeout(() => reject(new Error('The account state is not available: check the AXIS API connection')), timeout)\n })\n ])\n } finally {\n clearTimeout(timer)\n }\n }\n\n /**\n * @param {StreamMessage} message\n * @private\n */\n handle(message) {\n switch (message.type) {\n case 'account':\n this.live = true\n return this.applySnapshot(message)\n case 'order':\n return this.applyOrder(message)\n case 'backing':\n return this.applyBacking(message)\n case 'trade':\n return this.emit('trade', message.trade)\n case 'swap':\n return this.emit('swap', message.swap)\n case 'error':\n return this.emit('error', new Error(message.error))\n }\n }\n\n /**\n * Replace the state with a snapshot\n * @param {ApiAccount} state\n * @param {boolean} [mergeBacking] - Keep the tokens missing from the snapshot\n * @private\n */\n applySnapshot(state, mergeBacking = false) {\n const previous = this.orders\n const next = new Map()\n for (const raw of state.orders || []) {\n const order = parseApiOrder(raw)\n next.set(order.id, order)\n this.local.delete(order.id)\n }\n this.orders = next\n const backing = mergeBacking ? new Map(this.backing) : new Map()\n for (const [asset, raw] of Object.entries(state.backing || {})) {\n backing.set(asset, parseBacking(asset, raw))\n }\n this.backing = backing\n if (this.loaded) {\n for (const [id, order] of previous) {\n if (!next.has(id)) {\n this.emit('remove', order)\n }\n }\n for (const [id, order] of next) {\n if (!previous.has(id)) {\n this.emit('new', order)\n }\n }\n }\n if (!this.loaded) {\n this.loaded = true\n this.resolveReady()\n this.emit('ready')\n }\n this.emit('change')\n }\n\n /**\n * @param {{action: string, order: import('./api-client.js').ApiOrder, fill?: {}}} message\n * @private\n */\n applyOrder({action, order: raw, fill: rawFill}) {\n const order = parseApiOrder(raw)\n this.local.delete(order.id)\n const previous = this.orders.get(order.id)\n const removed = action === 'filled' || action === 'cancel' || action === 'expire'\n if (removed) {\n this.orders.delete(order.id)\n } else {\n if (previous && order.backed === null) {\n //the event serialization may lack the split; keep the last known one until the backing update\n order.backed = previous.backed\n order.backedPct = previous.backedPct\n order.backingPending = previous.backingPending\n }\n this.orders.set(order.id, order)\n }\n const fill = rawFill && {\n order,\n sold: BigInt(rawFill.sold),\n bought: BigInt(rawFill.bought),\n taker: rawFill.taker,\n trade: rawFill.trade?.toString(),\n ts: Number(rawFill.ts) * 1000,\n partial: action === 'fill'\n }\n this.emit(action, fill || order)\n if (removed) {\n this.emit('remove', order)\n }\n this.emit('order', {action, order, fill})\n this.emit('change')\n }\n\n /**\n * @param {{asset: string, backing: import('./api-client.js').ApiBacking|null, backed?: Object<string, string>}} message\n * @private\n */\n applyBacking({asset, backing: raw, backed}) {\n const backing = raw ? parseBacking(asset, raw) : undefined\n if (backing) {\n this.backing.set(asset, backing)\n } else {\n this.backing.delete(asset)\n }\n for (const [id, amount] of Object.entries(backed || {})) {\n const order = this.orders.get(id)\n if (!order)\n continue\n order.backed = BigInt(amount)\n order.backedPct = share(order.backed, order.amount)\n order.backingPending = !backing || backing.pending || !backing.updated\n }\n this.emit('backing', {asset, backing})\n this.emit('change')\n }\n\n /**\n * @return {Iterable<AccountOrder>}\n * @private\n */\n * allOrders() {\n yield* this.orders.values()\n yield* this.localOrders()\n }\n\n /**\n * Get local orders that haven't expired\n * @return {AccountOrder[]}\n * @private\n */\n localOrders() {\n const now = Date.now()\n const res = []\n for (const [id, {order, expires}] of this.local) {\n if (expires < now || this.orders.has(id)) {\n this.local.delete(id)\n } else {\n res.push(order)\n }\n }\n return res\n }\n\n /**\n * @private\n */\n startFallback() {\n if (this.fallbackTimer)\n return\n this.fallbackTimer = setInterval(() => {\n this.refresh().catch(() => {\n //retried on the next tick\n })\n }, this.axis.fallbackPollInterval)\n }\n\n /**\n * @private\n */\n stopFallback() {\n clearInterval(this.fallbackTimer)\n this.fallbackTimer = undefined\n }\n}\n\n/**\n * Convert an API order to the client form (bigint amounts and prices, numeric timestamps)\n * @param {ApiOrder} raw\n * @return {AccountOrder}\n */\nexport function parseApiOrder(raw) {\n const amount = BigInt(raw.amount)\n const quote = BigInt(raw.quote ?? raw.amount)\n //unconfirmed until loaded, and while a reload confirming the latest event is due\n const confirmed = raw.backed !== undefined && !!raw.backing?.updated && !raw.backing?.pending\n const backed = raw.backed !== undefined ? BigInt(raw.backed) : null\n return {\n id: raw.id,\n owner: raw.owner,\n selling: raw.selling,\n buying: raw.buying,\n market: pairKey(raw.selling, raw.buying),\n status: raw.status,\n price: BigInt(raw.price),\n amount,\n quote,\n expires: raw.expires ? Math.floor(parseApiDate(raw.expires) / 1000) : 0,\n created: parseApiDate(raw.created),\n updated: parseApiDate(raw.updated),\n cursor: raw.cursor !== undefined ? BigInt(raw.cursor) : undefined,\n backed,\n backedPct: backed === null ? null : share(backed, amount),\n backingPending: !confirmed,\n filledPct: quote > 0n ? Math.max(0, Math.min(1, 1 - Number(amount * 10_000n / quote) / 10_000)) : 0,\n pending: false\n }\n}\n\n/**\n * @param {string} asset\n * @param {ApiBacking} raw\n * @return {AccountBacking}\n */\nfunction parseBacking(asset, raw) {\n return {\n asset,\n balance: BigInt(raw.balance),\n allowance: BigInt(raw.allowance),\n liveUntil: raw.liveUntil || 0,\n authorized: raw.authorized !== false,\n budget: BigInt(raw.budget ?? 0),\n updated: parseApiDate(raw.updated),\n skipped: parseApiDate(raw.skipped),\n pending: raw.pending === true\n }\n}\n\n/**\n * @param {bigint} part\n * @param {bigint} total\n * @return {number} - 0..1\n */\nfunction share(part, total) {\n if (total <= 0n)\n return 1\n return Math.max(0, Math.min(1, Number(part * 10_000n / total) / 10_000))\n}\n\n/**\n * @param {string|{base: string, quote: string}|string[]|undefined} market\n * @return {string|undefined}\n */\nfunction toMarketKey(market) {\n if (!market)\n return undefined\n if (typeof market === 'string') {\n const [x, y] = market.split('/')\n return pairKey(x, y)\n }\n if (Array.isArray(market))\n return pairKey(market[0], market[1])\n return pairKey(market.base, market.quote)\n}\n\n/**\n * Newest first: unconfirmed local orders, then by creation position\n * @param {AccountOrder} x\n * @param {AccountOrder} y\n * @return {number}\n */\nfunction newestFirst(x, y) {\n if (x.cursor === undefined || y.cursor === undefined)\n return (x.cursor === undefined ? 0 : 1) - (y.cursor === undefined ? 0 : 1) || y.created - x.created\n return x.cursor < y.cursor ? 1 : x.cursor > y.cursor ? -1 : 0\n}\n\n/**\n * @typedef {{}} AccountOrder - Open order of a tracked account\n * @property {string} id - Order id (decimal u128)\n * @property {string} owner - Maker address\n * @property {string} selling - Sold token\n * @property {string} buying - Bought token\n * @property {string} market - Market key\n * @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Current status\n * @property {bigint} price - `buying` per 1 `selling`, contract scale (18 decimals)\n * @property {bigint} amount - Amount of `selling` left\n * @property {bigint} quote - Amount of `selling` at creation\n * @property {number} expires - Expiration UNIX timestamp in seconds, 0 = none\n * @property {number} created - Creation time, UNIX milliseconds\n * @property {number} updated - Last change, UNIX milliseconds\n * @property {bigint} [cursor] - Paging cursor (undefined for unconfirmed local orders)\n * @property {bigint|null} backed - Share of the account budget in `selling` that backs the order\n * @property {number|null} backedPct - `backed / amount` (0..1), null when unknown\n * @property {boolean} backingPending - The backing is not confirmed yet\n * @property {number} filledPct - Filled share of the initial amount (0..1)\n * @property {boolean} pending - Created by this client, not reported by the indexer yet\n */\n\n/**\n * @typedef {{}} AccountBacking - Balance and allowance of the account in a token, as tracked by the indexer\n * @property {string} asset\n * @property {bigint} balance - Spendable amount (balance minus reserve and liabilities)\n * @property {bigint} allowance - Allowance granted to the AXIS contract\n * @property {number} liveUntil - Ledger sequence the allowance lives until\n * @property {boolean} authorized - Whether the account can send and receive the token\n * @property {bigint} budget - min(balance, allowance), 0 when unauthorized or expired\n * @property {number} updated - Last load, UNIX milliseconds (0 = not loaded)\n * @property {number} skipped - Last skipped fill of an order selling the token, UNIX milliseconds (0 = none)\n * @property {boolean} pending - A reload confirming the latest change is due\n */\n\n/**\n * @typedef {{}} AccountAllowance\n * @property {string} asset\n * @property {boolean} known - Whether the backing is tracked and loaded\n * @property {bigint} [balance]\n * @property {bigint} [allowance]\n * @property {number} [liveUntil]\n * @property {boolean} [authorized]\n * @property {boolean} [pending]\n * @property {bigint} [available] - min(balance, allowance)\n * @property {bigint} committed - Remaining amount of the open orders selling the token\n */\n\n/**\n * @typedef {{}} AccountFill\n * @property {AccountOrder} order - Order after the fill\n * @property {bigint} sold - Amount of `selling` delivered\n * @property {bigint} bought - Amount of `buying` received\n * @property {string} taker - Taker address\n * @property {string} trade - Trade id\n * @property {number} ts - Trade time, UNIX milliseconds\n * @property {boolean} partial - Whether the order is still open\n */\n\n/**\n * @typedef {{}} TradeParams\n * @property {string} selling - Token sent\n * @property {string} buying - Token received\n * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)\n * @property {bigint|string} [price] - Limit price, contract scale; omitted for a market order\n * @property {number} [kind] - {@link OrderKind}: `Limit` by default, `Fill` for a market order\n * @property {number} [expires] - Expiration UNIX timestamp (seconds) of the resting remainder\n * @property {Array<bigint|string>} [orders] - Counter orders to cross, looked up automatically when omitted\n * @property {Approval|null} [approve] - Explicit approval (`null` for none)\n */\n\n/**\n * @typedef {{}} TradeResult\n * @property {bigint} sold - Amount of `selling` sent\n * @property {bigint} bought - Amount of `buying` received\n * @property {string} [orderId] - ID of the order created for a limit remainder\n * @property {AccountOrder} [order] - The created order (unconfirmed until the indexer reports it)\n * @property {Approval} [approve] - Approval granted with the trade\n */\n\n/**\n * @typedef {{}} SwapParams\n * @property {string} selling - Token sent\n * @property {string} buying - Token received\n * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)\n * @property {number} [direction] - {@link TradeDirection}, `Sell` by default\n * @property {number} [slippage] - Price tolerance as a fraction (0.005 = 0.5%), 0 by default\n */\n","import {Asset, Networks} from '@stellar/stellar-sdk'\nimport {Emitter} from './emitter.js'\nimport {AxisApiClient, AxisApiError} from './api-client.js'\nimport {AxisStreamClient} from './stream-client.js'\nimport {TokenBalance} from './token-balance.js'\nimport {AxisMarket} from './axis-market.js'\nimport {AxisAccount, parseApiOrder} from './axis-account.js'\nimport {pairKey} from './asset-pair.js'\nimport {parseApiDate} from './api-dates.js'\nimport {AxisContractClient} from './index.js'\n\n/** Max stale ledger threshold, in ms */\nconst LEDGER_STALE_THRESHOLD = 60_000\n\n/**\n * High-level AXIS DEX state\n *\n * Emits:\n * - `change` - anything in the contract state changed\n * - `frozen` `boolean` - the frozen state toggled\n * - `config` {ContractInfoConfig} - contract configuration changed\n * - `market` `{market: AxisMarket, created: boolean}` - a market was opened or updated\n * - `connection` `boolean` - WebSocket push connection opened or dropped\n * - `ledger` `number` - new ledger processed by the indexer\n */\nexport class Axis extends Emitter {\n /**\n * @param {AxisOptions} options\n */\n constructor({apiUrl, wsUrl, rpcUrl, contractId, networkPassphrase = Networks.PUBLIC, fee, signer, WebSocket, fallbackPollInterval = 15_000}) {\n super()\n this.api = new AxisApiClient(apiUrl)\n this.stream = new AxisStreamClient(wsUrl || toWsUrl(this.api.serverUrl), {WebSocket})\n this.rpcUrl = rpcUrl\n this.contractId = contractId\n this.networkPassphrase = networkPassphrase\n this.fee = fee\n this.signer = signer\n this.fallbackPollInterval = fallbackPollInterval\n this.tokenBalances = rpcUrl ? new TokenBalance({rpcUrl, networkPassphrase, spender: contractId}) : undefined\n this.nativeAsset = Asset.native().contractId(networkPassphrase)\n this.stream.on('open', () => {\n this.stopFallback()\n this.emit('connection', true)\n })\n this.stream.on('close', () => {\n this.startFallback()\n this.emit('connection', false)\n })\n }\n\n /**\n * AXIS REST API client\n * @type {AxisApiClient}\n * @readonly\n */\n api\n /**\n * AXIS contract address\n * @type {string|undefined}\n * @readonly\n */\n contractId\n /**\n * AXIS API WebSocket client\n * @type {AxisStreamClient}\n * @readonly\n */\n stream\n /**\n * Token balance wrappers\n * @type {TokenBalance}\n * @readonly\n */\n tokenBalances\n /**\n * Contract address of the native XLM token\n * @type {string}\n * @readonly\n */\n nativeAsset\n /**\n * Last known ledger\n * @type {number}\n */\n ledger = 0\n /**\n * Last updated UNIX milliseconds\n * @type {number}\n */\n ledgerTime = 0\n /**\n * Whether trading is suspended\n * @type {boolean}\n */\n frozen = false\n /**\n * Contract configuration\n * @type {ContractInfoConfig}\n */\n config\n /**\n * Available AXIS markets\n * @type {Map<string, AxisMarket>}\n * @readonly\n */\n markets = new Map()\n /**\n * 24h ticker entries\n * @type {Map<string, TickerEntry>}\n * @readonly\n */\n tickers = new Map() //TODO: move inside AxisMarket\n /**\n * Tracked accounts\n * @type {Map<string, AxisAccount>}\n * @private\n */\n accounts = new Map()\n /**\n * Contract clients by signer\n * @type {Map<string, {signTransaction: function, client: AxisContractClient}>}\n * @private\n */\n clients = new Map() //TODO: check if we can use a single AxisContractClient instance instead\n /**\n * @type {Promise<Axis>}\n * @private\n */\n connecting\n\n /**\n * Whether the contract state loaded\n * @return {boolean}\n */\n get loaded() {\n return !!this.loadedAt\n }\n\n /**\n * Load the contract state and track its changes\n * @return {Promise<Axis>}\n */\n connect() {\n if (!this.connecting) {\n this.connecting = new Promise((resolve, reject) => {\n //works with the push API, or the REST API if the push connection is not available\n let settled = false\n const done = () => {\n if (!settled) {\n settled = true\n resolve(this)\n }\n }\n const fail = e => {\n if (!settled) {\n settled = true\n this.connecting = undefined\n this.unsubscribeContract?.()\n reject(e)\n }\n }\n this.unsubscribeContract = this.stream.subscribe('contract', {}, message => {\n if (message.ledger) {\n this.applyLedger(message.ledger)\n }\n if (message.type === 'contract') {\n try {\n this.applyContractSnapshot(message.data)\n } catch (e) {\n return fail(e) //a snapshot of another contract is ignored after connecting\n }\n done()\n }\n })\n //do not wait for a push connection that may never open\n this.api.getContract()\n .then(data => {\n if (!this.loaded) {\n this.applyContractSnapshot(data)\n }\n done()\n }, e => {\n if (!settled && !this.stream.connected) {\n this.startFallback()\n fail(e)\n }\n })\n .catch(fail)\n })\n }\n return this.connecting\n }\n\n /**\n * AXIS contract address\n * @return {Promise<string>}\n */\n async getContractId() {\n if (!this.contractId) {\n await this.connect()\n }\n return this.contractId\n }\n\n /**\n * Current ledger sequence\n * @return {Promise<number>}\n */\n async getLedger() {\n if (this.ledger && this.stream.connected && Date.now() - this.ledgerTime < LEDGER_STALE_THRESHOLD)\n return this.ledger\n if (this.tokenBalances)\n return this.tokenBalances.getLatestLedger()\n if (this.ledger)\n return this.ledger\n throw new Error('The current ledger is unknown: connect to the AXIS API or set the `rpcUrl` option')\n }\n\n /**\n * Get market of the asset pair\n * @param {string} asset1 - Token contract address\n * @param {string} asset2 - Token contract address\n * @return {AxisMarket|undefined}\n */\n getMarket(asset1, asset2) {\n return this.markets.get(pairKey(asset1, asset2)) //TODO: accept also stellar classic asset format CODE:ISSUER and convert it to contract address automatically\n }\n\n /**\n * Get live order by id\n * @param {bigint|string} id - Order id\n * @return {Promise<AccountOrder|undefined>} - Undefined if not found (filled, removed, expired)\n */\n async getOrder(id) {\n const key = id.toString()\n for (const account of this.accounts.values()) {\n const order = account.orders.get(key)\n if (order)\n return order\n }\n try {\n return parseApiOrder(await this.api.getOrder(key))\n } catch (e) {\n if (e instanceof AxisApiError && e.status === 404)\n return undefined\n throw e\n }\n }\n\n /**\n * Trader wrapper tracking the orders and allowances for an account (one instance per account address)\n * @param {string} address - Trader address\n * @param {{signTransaction: [SignTransactionCallback]}} [options] - Transaction signing callback\n * @return {AxisAccount}\n */\n account(address, {signTransaction} = {}) {\n let account = this.accounts.get(address)\n if (!account) {\n account = new AxisAccount(this, address, {signTransaction})\n this.accounts.set(address, account)\n account.start()\n } else if (signTransaction) {\n account.signTransaction = signTransaction\n }\n return account\n }\n\n /**\n * Stream the 24h ticker of every market\n * Sends a full snapshot, then updates caused by trades\n * @param {function(Ticker24hResult): void} [callback]\n * @return {function(): void} - Unsubscribe function\n */\n subscribeTicker(callback) {\n return this.stream.subscribe('ticker', {}, message => {\n if (message.type !== 'ticker')\n return\n for (const entry of message.data.ticker) {\n this.tickers.set(entry.symbol, entry)\n }\n callback?.(message.data)\n })\n }\n\n /**\n * Extend the contract instance and code lifetime with an `ExtendFootprintTTL` operation, restoring them first if archived\n * @param {{days?: number, signer?: Signer}} [params] - Lifetime in days (30 by default) and the transaction source\n * (the default signer by default)\n * @return {Promise<number>} - Ledger sequence both entries live until, at least\n */\n async keepalive({days, signer} = {}) {\n const client = await this.contractClient(signer)\n return client.keepalive(days)\n }\n\n /**\n * Stop following the contract state and tracked accounts\n */\n close() {\n this.stopFallback()\n this.unsubscribeContract?.()\n for (const account of [...this.accounts.values()]) {\n account.close()\n }\n this.stream.close()\n this.connecting = undefined\n }\n\n /**\n * Contract client signing with the given account\n * @param {Signer} [signer] - The default signer if omitted\n * @return {Promise<AxisContractClient>}\n * @internal\n */\n async contractClient(signer = this.signer) {\n if (!signer?.publicKey || !signer.signTransaction)\n throw new Error('A signer ({publicKey, signTransaction}) is required to submit transactions')\n if (!this.rpcUrl)\n throw new Error('The `rpcUrl` option is required to submit transactions')\n await this.getContractId()\n const cached = this.clients.get(signer.publicKey)\n if (cached && cached.signTransaction === signer.signTransaction)\n return cached.client\n const client = new AxisContractClient({\n publicKey: signer.publicKey,\n signTransaction: signer.signTransaction,\n rpcUrl: this.rpcUrl,\n contractId: this.contractId,\n networkPassphrase: this.networkPassphrase,\n fee: this.fee\n })\n this.clients.set(signer.publicKey, {signTransaction: signer.signTransaction, client})\n return client\n }\n\n /**\n * @param {AxisAccount} account\n * @internal\n */\n releaseAccount(account) {\n if (this.accounts.get(account.address) === account) {\n this.accounts.delete(account.address)\n }\n }\n\n /**\n * Apply a contract state snapshot\n * @param {ContractInfo} data\n * @private\n */\n applyContractSnapshot(data) {\n this.checkContractAddress(data.address)\n this.loadedAt = Date.now()\n const frozen = data.frozen === true\n if (frozen !== this.frozen) {\n this.frozen = frozen\n this.emit('frozen', frozen)\n }\n if (data.config && JSON.stringify(data.config) !== JSON.stringify(this.config)) {\n this.config = data.config\n this.emit('config', data.config)\n }\n for (const record of data.markets || []) {\n const key = pairKey(record.base, record.quote)\n const market = this.markets.get(key)\n if (!market) {\n const created = new AxisMarket(this, record)\n this.markets.set(key, created)\n this.emit('market', {market: created, created: true})\n } else if (record.refreshed && market.refreshed !== parseApiDate(record.refreshed)) {\n market.update(record)\n this.emit('market', {market, created: false})\n }\n }\n this.emit('change')\n }\n\n /**\n * Take the contract address reported by the AXIS API, or check it against the explicitly set\n * @param {string} [address]\n * @throws {Error} - If the API tracks another contract or the address is unknown\n * @private\n */\n checkContractAddress(address) {\n if (!address) {\n if (!this.contractId)\n throw new Error('The AXIS API does not report the contract address: set the `contractId` option')\n return\n }\n if (!this.contractId) {\n this.setContractId(address)\n } else if (address !== this.contractId)\n throw new Error(`The AXIS API tracks contract ${address}, not ${this.contractId}`)\n }\n\n /**\n * @param {string} contractId\n * @private\n */\n setContractId(contractId) {\n this.contractId = contractId\n if (this.tokenBalances) {\n this.tokenBalances.spender = contractId\n }\n }\n\n /**\n * @param {number} ledger\n * @private\n */\n applyLedger(ledger) {\n this.ledgerTime = Date.now()\n if (ledger > this.ledger) {\n this.ledger = ledger\n this.emit('ledger', ledger)\n }\n }\n\n /**\n * Poll the contract state over REST while the push connection is down\n * @private\n */\n startFallback() {\n if (this.fallbackTimer || !this.connecting)\n return\n this.fallbackTimer = setInterval(() => {\n this.api.getContract()\n .then(data => this.applyContractSnapshot(data))\n .catch(() => {\n //retried on the next tick\n })\n }, this.fallbackPollInterval)\n }\n\n /**\n * @private\n */\n stopFallback() {\n clearInterval(this.fallbackTimer)\n this.fallbackTimer = undefined\n }\n}\n\n/**\n * Derive the push API endpoint from the REST API URL\n * @param {string} apiUrl\n * @return {string}\n */\nexport function toWsUrl(apiUrl) {\n return apiUrl.replace(/^http/i, 'ws').replace(/\\/+$/, '') + '/ws'\n}\n\n/**\n * @typedef {{}} AxisOptions\n * @property {string} apiUrl - AXIS REST API URL\n * @property {string} [contractId] - AXIS contract address, by default pulled from the AXIS API\n * @property {string} [wsUrl] - AXIS API push channel URL (`<apiUrl>/ws` with the `ws(s)` scheme by default)\n * @property {string} [rpcUrl] - Stellar RPC URL\n * @property {string} [networkPassphrase] - Network passphrase (Pubnet by default)\n * @property {string} [fee] - Transaction fee\n * @property {Signer} [signer] - Default signer settings for contract operations\n * @property {number} [fallbackPollInterval] - REST polling period while the push connection is down, in milliseconds\n * @property {typeof WebSocket} [WebSocket] - WebSocket implementation\n */\n","import {Contract, Networks, Operation, SorobanDataBuilder, TransactionBuilder, contract, rpc, xdr} from '@stellar/stellar-sdk'\nimport ContractClient from './contract-client.js'\nimport {ContractErrors, TokenErrors, processSimulationErrors, processTransactionErrors} from './errors.js'\nimport {AxisApiClient, AxisApiError} from './api-client.js'\nimport {collectOrderIds, completeFootprint, ensureOrdersFootprint} from './footprint.js'\nimport {orderId, generateNonce} from './order-id.js'\nimport {OrderKind, TradeDirection} from './constants.js'\n\nexport {ContractErrors, TokenErrors, AxisApiClient, AxisApiError, orderId, OrderKind, TradeDirection}\nexport {Axis, toWsUrl} from './axis.js'\nexport {AxisMarket} from './axis-market.js'\nexport {AxisAccount, parseApiOrder} from './axis-account.js'\nexport {AxisStreamClient} from './stream-client.js'\nexport {TokenBalance} from './token-balance.js'\nexport {Emitter} from './emitter.js'\nexport {planApproval, maxQuoteSpend, APPROVAL_TTL_LEDGERS, APPROVAL_RENEW_LEDGERS} from './allowance.js'\nexport {canonicalPair, compareAssets, pairKey, invertPrice, invertTicker, PRICE_SCALE} from './asset-pair.js'\nexport {parseApiDate} from './api-dates.js'\n\nconst SECONDS_PER_DAY = 86_400\n//ledger close time assumed when the contract configuration cannot be read, in seconds (the contract's default)\nconst DEFAULT_LEDGER_TIME = 5\n//default lifetime `keepalive` extends the contract instance and code to, in days\nconst KEEPALIVE_DAYS = 30\n//validity window of transactions built by the client, in seconds\nconst TX_TIMEOUT = 60\n\n/**\n * Smart contract client for trading with AXIS DEX\n */\nexport class AxisContractClient {\n /**\n * @param {ClientInitializationParams} params\n */\n constructor(params) {\n const options = {\n publicKey: params.publicKey,\n signTransaction: params.signTransaction,\n rpcUrl: params.rpcUrl,\n allowHttp: true,\n networkPassphrase: params.networkPassphrase || Networks.PUBLIC,\n contractId: params.contractId\n }\n this.client = new ContractClient(options)\n this.fee = params.fee || '100000'\n this.autoFootprint = params.autoFootprint !== false\n this.server = new rpc.Server(params.rpcUrl, {allowHttp: true})\n this.assetCache = new Map()\n }\n\n /**\n * Account that signs and pays for the transactions\n * @return {string}\n */\n get publicKey() {\n return this.client.options.publicKey\n }\n\n /**\n * Fetch existing order.\n * @param {bigint} id - ID of the order to fetch\n * @return {Promise<Order|undefined>} - Order fetched from the storage, undefined if not found or expired\n */\n async order(id) {\n const tx = await this.client.order({id})\n processSimulationErrors(tx)\n return tx.result ?? undefined\n }\n\n /**\n * Fetch contract configuration.\n * @return {Promise<Config>}\n */\n async loadConfig() {\n const tx = await this.client.config()\n processSimulationErrors(tx)\n return tx.result\n }\n\n /**\n * Check whether the contract is frozen.\n * @return {Promise<boolean>} - `true` if contract is frozen (trading and order management operations blocked)\n */\n async isFrozen() {\n const tx = await this.client.frozen()\n processSimulationErrors(tx)\n return tx.result\n }\n\n /**\n * Fetch market for the given asset pair.\n * @param {string} selling - First market asset\n * @param {string} buying - Second market asset\n * @return {Promise<Market|undefined>} - Market record if the market exists\n */\n async getMarket(selling, buying) {\n const tx = await this.client.market({selling, buying})\n processSimulationErrors(tx)\n return tx.result ?? undefined\n }\n\n /**\n * Trade with DEX and create a buy limit order if the quote not executed in full.\n * @param {BuyTradeArguments} params\n * @return {Promise<[bigint, bigint, bigint|undefined]>} - Amount of sold and bought tokens, ID of the newly created order if any\n * @throws {Error} - If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade targets a pair without a market,\n * no reference price is available, a live order with the same id exists, the trader cannot receive `buying` (`CannotReceive`), or the contract\n * cannot hold `buying` until its issuer authorizes it (`IntermediaryCannotReceive`).\n */\n async buy(params) {\n return await execTrade(params, TradeDirection.Buy, this)\n }\n\n /**\n * Trade with DEX and create a sell limit order if the quote not executed in full.\n * @param {SellTradeArguments} params\n * @return {Promise<[bigint, bigint, bigint|undefined]>} - Amount of sold and bought tokens, ID of the newly created order if any\n * @throws {Error} - If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade targets a pair without a market,\n * no reference price is available, a live order with the same id exists, the trader cannot receive `buying` (`CannotReceive`), or the contract\n * cannot hold `buying` until its issuer authorizes it (`IntermediaryCannotReceive`). \n */\n async sell(params) {\n return await execTrade(params, TradeDirection.Sell, this)\n }\n\n /**\n * Simulate a buy trade without signing or submitting it, to show the network fee before the trade.\n * @param {BuyTradeArguments} params\n * @return {Promise<TradeEstimate>}\n * @throws {Error} - If the simulation fails, for the same reasons as `buy`\n */\n async estimateBuy(params) {\n return estimateTx(await prepareTrade(params, TradeDirection.Buy, this), this.fee)\n }\n\n /**\n * Simulate a sell trade without signing or submitting it, to show the network fee before the trade.\n * @param {SellTradeArguments} params\n * @return {Promise<TradeEstimate>}\n * @throws {Error} - If the simulation fails, for the same reasons as `sell`\n */\n async estimateSell(params) {\n return estimateTx(await prepareTrade(params, TradeDirection.Sell, this), this.fee)\n }\n\n /**\n * Update the amount, price, or expiration of several orders in place, or remove them.\n * Orders that no longer exist are skipped; expired orders revived with the new expiration.\n * A zero amount removes the order, expired ones included. An updated order's entry lifetime is extended to cover its expiration +1 day.\n * Approvals and removals work in a frozen contract and on a market without quoted assets.\n * A transaction can process up to 90 orders in one batch.\n * @param {UpdateArguments} params\n * @return {Promise<bigint[]>} - IDs of the orders to update\n * @throws {Error} - If the trader does not own an updated order, if order parameters are invalid, if an order is below the minimum value,\n * if the new amounts are not backed by the trader's balance and allowance, an update changes an order on the frozen or not-quoted market\n */\n async update(params) {\n const updates = params.updates.map(update => ({\n id: update.id,\n amount: update.amount,\n price: update.price,\n expires: BigInt(update.expires ?? 0)\n }))\n const approvals = (params.approvals ?? []).map(approval => {\n if (!approval.asset)\n throw new TypeError('An update approval must name its asset')\n return toApproval(approval, approval.asset)\n })\n const tx = await this.client.update({trader: params.trader, updates, approvals}, {fee: this.fee})\n processSimulationErrors(tx)\n this.updateFootprint(tx, updates.map(update => update.id))\n const result = await signAndSend(tx)\n return result\n }\n\n /**\n * Cancel existing orders, expired ones included. A transaction can process up to 90 orders in one batch.\n * @param {string} trader - Trader address\n * @param {bigint[]} ids - IDs of the orders to cancel (non-existent orders are ignored)\n * @return {Promise<void>}\n * @throws {Error} - If trader is not the owner of any existing order in `ids` (works while the contract is frozen)\n */\n async cancel(trader, ids) {\n await this.update({trader, updates: ids.map(id => ({id, amount: 0n, price: 0n}))})\n }\n\n /**\n * Fill an existing order against matching orders from the orderbook. Profits from inefficiencies go to the trader.\n * @param {string} trader - Trader address\n * @param {bigint} takerOrderId - ID of the order that serves as a taker\n * @param {bigint[]} orders - List of order IDs to match against\n * @return {Promise<[bigint, bigint, bigint]>} - Amount the taker order sold, amount the makers delivered, surplus paid to the trader.\n * @throws {Error} - If the taker order does not exist or has expired, if the trader cannot receive the bought asset, if the\n * contract cannot hold the bought asset, if the contract is frozen.\n */\n async crossfill(trader, takerOrderId, orders) {\n const tx = await this.client.crossfill({trader, taker_order_id: takerOrderId, orders}, {fee: this.fee})\n processSimulationErrors(tx)\n //the traded assets come from the taker order, resolved while completing the footprint: what it buys passes\n //through the contract, which pays the owner and the surplus to the trader\n await this.updateTradeFootprint(tx, {takerOrder: takerOrderId, receiver: trader}, [takerOrderId], orders)\n const result = await signAndSend(tx)\n return [result[0], result[1], result[2]]\n }\n\n /**\n * Swap tokens across several markets. The contract holds the intermediate hop proceeds only within the call.\n * @param {SwapArguments} params\n * @return {Promise<[bigint, bigint]>} - Amount of sold and bought tokens\n * @throws {Error} - If the route cannot satisfy the selling/buying amount, if `path` is empty or an amount is invalid,\n * if the contract cannot hold an asset of the path, if the contract is frozen.\n */\n async swap(params) {\n const tx = await this.client.swap({\n direction: params.direction,\n trader: params.trader,\n selling: params.selling,\n selling_amount: params.sellingAmount,\n buying_amount: params.buyingAmount,\n path: params.path.map(step => ({asset: step.asset, orders: step.orders})),\n approve: toApproval(params.approve, params.selling)\n }, {fee: this.fee})\n processSimulationErrors(tx)\n const hops = params.path.map(step => step.asset)\n //every hop asset passes through the contract, the last one is forwarded to the trader\n await this.updateTradeFootprint(tx, {\n tokens: [params.selling, ...hops],\n passThrough: hops,\n receiver: params.trader,\n bought: hops[hops.length - 1]\n }, ...params.path.map(step => step.orders))\n const result = await signAndSend(tx)\n return [result[0], result[1]]\n }\n\n /**\n * Re-check both market assets against the price oracle and cache oracle prices.\n * A cached price is valid for up to 72 hours. A market without quoted assets stops accepting\n * new limit orders; its outstanding orders stay cancellable and fillable. The record and the\n * cached prices are rewritten only when they change. When the simulation writes nothing (the market and the\n * cached prices are current, or the oracle has no newer price), the simulated result is\n * returned and no transaction is submitted.\n * @param {string} selling - First market asset\n * @param {string} buying - Second market asset\n * @return {Promise<Market|undefined>} - Updated market record, undefined if the market does not exist\n * @throws {Error} - If the contract is frozen\n */\n async requote(selling, buying) {\n const tx = await this.client.requote({selling, buying}, {fee: this.fee})\n processSimulationErrors(tx)\n if (tx.isReadCall)\n return tx.result ?? undefined //nothing changed on-chain\n const result = await signAndSend(tx)\n return result ?? undefined\n }\n\n /**\n * Extend oracle price feeds access for a market, creating the market if it does not exist yet.\n * @param {SubsidizeArguments} params\n * @return {Promise<bigint[]>} - New access expiration UNIX timestamps (in seconds) per oracle-listed asset\n * @throws {Error} - If `amount` is invalid, if `selling` equals `buying`, if the market does not exist and the amount is below\n * the market listing fee, if neither market asset is quoted by the oracle, if the contract is frozen\n */\n async subsidize(params) {\n const tx = await this.client.subsidize({\n sponsor: params.sponsor,\n selling: params.selling,\n buying: params.buying,\n amount: params.amount\n }, {fee: this.fee})\n processSimulationErrors(tx)\n const result = await signAndSend(tx)\n return result\n }\n\n /**\n * Extend the contract instance and code lifetime with an `ExtendFootprintTTL` operation, restoring the archived\n * ones first with a `RestoreFootprint` transaction.\n * @param {number} [days] - Lifetime in days, 30 by default, at most the network maximum (180 days on mainnet)\n * @return {Promise<number>} - Ledger sequence both entries live at least until\n * @throws {Error} - If `days` is invalid, if the instance is not found, if a simulation or a transaction fails\n */\n async keepalive(days = KEEPALIVE_DAYS) {\n if (!Number.isInteger(days) || days <= 0)\n throw new TypeError(`Invalid keepalive days: ${days}`)\n const {keys, archived} = await contractLifetimeEntries(this.server, this.client.options.contractId)\n if (archived.length)\n await this.submitFootprintOperation(Operation.restoreFootprint({}), new SorobanDataBuilder().setReadWrite(archived))\n //read after the restoration: the configuration is stored in the instance\n const extendTo = Math.ceil(days * SECONDS_PER_DAY / await this.loadLedgerTime())\n const simulation = await this.submitFootprintOperation(Operation.extendFootprintTtl({extendTo}), new SorobanDataBuilder().setReadOnly(keys))\n return simulation.latestLedger + extendTo\n }\n\n /**\n * Build, simulate, sign and submit a transaction with a single footprint operation (`ExtendFootprintTTL` or `RestoreFootprint`)\n * @param {xdr.Operation} operation\n * @param {SorobanDataBuilder} sorobanData - Footprint of the operation\n * @return {Promise<rpc.Api.SimulateTransactionSuccessResponse>} - Simulation the submitted transaction was assembled from\n * @private\n */\n async submitFootprintOperation(operation, sorobanData) {\n const {networkPassphrase, signTransaction} = this.client.options\n const tx = new TransactionBuilder(await this.server.getAccount(this.publicKey), {fee: this.fee, networkPassphrase})\n .addOperation(operation)\n .setSorobanData(sorobanData.build())\n .setTimeout(TX_TIMEOUT)\n .build()\n const simulation = await this.server.simulateTransaction(tx)\n if (rpc.Api.isSimulationError(simulation))\n throw new Error(simulation.error)\n if (rpc.Api.isSimulationRestore(simulation))\n throw new Error('The contract instance or code was archived during the keepalive, retry it to restore them')\n //assembled here, not through the contract client: its signing path declares the resource fee twice\n const prepared = rpc.assembleTransaction(tx, simulation).build()\n if (typeof signTransaction !== 'function')\n throw new Error('No signTransaction callback to sign the keepalive transaction')\n const {signedTxXdr, error} = await signTransaction(prepared.toXDR(), {networkPassphrase, address: this.publicKey})\n if (error)\n throw new Error(`Keepalive transaction was not signed: ${error.message ?? error}`)\n await submitTransaction(this.server, TransactionBuilder.fromXDR(signedTxXdr, networkPassphrase))\n return simulation\n }\n\n /**\n * Ledger close time the contract converts lifetimes with\n * @return {Promise<number>} - Seconds per ledger\n * @private\n */\n async loadLedgerTime() {\n try {\n return Number((await this.loadConfig())?.ledger_time) || DEFAULT_LEDGER_TIME\n } catch (e) {\n return DEFAULT_LEDGER_TIME //the extension itself reports an unreachable or archived contract\n }\n }\n\n /**\n * Declare all order ids of a simulated call in the read-write footprint (if enabled).\n * @param {contract.AssembledTransaction} tx - Simulated transaction\n * @param {...Array<bigint>} idLists - Order ids passed to the contract call\n * @private\n */\n updateFootprint(tx, ...idLists) {\n if (this.autoFootprint) {\n const orderIds = collectOrderIds(...idLists)\n ensureOrdersFootprint(tx, this.client.options.contractId, orderIds)\n }\n }\n\n /**\n * Declare all order ids of a simulated trading call, and the entries the settlement may write for their makers,\n * in the read-write footprint (if enabled), so the transaction survives book changes before it is applied.\n * @param {contract.AssembledTransaction} tx - Simulated transaction\n * @param {{tokens?: string[], passThrough?: string[], receiver?: string, bought?: string, takerOrder?: bigint}} settlement - Tokens\n * the call trades and how it settles (see `FootprintOptions`)\n * @param {...Array<bigint>} idLists - Order ids passed to the contract call\n * @return {Promise<void>}\n * @private\n */\n async updateTradeFootprint(tx, settlement, ...idLists) {\n if (this.autoFootprint) {\n const orderIds = collectOrderIds(...idLists)\n await completeFootprint(tx, this.client.options.contractId, orderIds, {...settlement, server: this.server, assetCache: this.assetCache})\n }\n }\n}\n\n/**\n * Ledger keys of the contract instance and its Wasm code, and those of them that are archived\n * @param {rpc.Server} server\n * @param {string} contractId\n * @return {Promise<{keys: xdr.LedgerKey[], archived: xdr.LedgerKey[]}>}\n * @internal\n */\nasync function contractLifetimeEntries(server, contractId) {\n const instanceKey = new Contract(contractId).getFootprint()\n const instance = await server.getLedgerEntries(instanceKey)\n const executable = instance.entries[0]?.val?.contractData?.val?.instance?.executable\n if (!executable)\n throw new Error(`Contract ${contractId} instance not found`)\n if (!executable.wasmHash)\n throw new Error(`Contract ${contractId} has no Wasm code`)\n const codeKey = xdr.LedgerKey.contractCode(new xdr.LedgerKeyContractCode({hash: executable.wasmHash}))\n const code = await server.getLedgerEntries(codeKey)\n const archived = []\n if (isArchived(instance.entries[0], instance.latestLedger))\n archived.push(instanceKey)\n //code the RPC does not return is evicted, the restoration brings it back\n if (!code.entries[0] || isArchived(code.entries[0], code.latestLedger))\n archived.push(codeKey)\n return {keys: [instanceKey, codeKey], archived}\n}\n\n/**\n * Whether a ledger entry is no longer live for the transactions following the latest ledger\n * @param {rpc.Api.LedgerEntryResult} entry\n * @param {number} latestLedger\n * @return {boolean}\n * @internal\n */\nfunction isArchived(entry, latestLedger) {\n return entry.liveUntilLedgerSeq !== undefined && entry.liveUntilLedgerSeq <= latestLedger\n}\n\n/**\n * Submit a signed transaction and wait for its result\n * @param {rpc.Server} server\n * @param {import('@stellar/stellar-sdk').Transaction} tx\n * @return {Promise<void>}\n * @throws {Error} - If the transaction is rejected, fails or is not included in time\n * @internal\n */\nasync function submitTransaction(server, tx) {\n const sent = await server.sendTransaction(tx)\n if (sent.status !== 'PENDING' && sent.status !== 'DUPLICATE')\n throw new Error(`Transaction ${sent.hash} rejected: ${sent.errorResult?.result?.type ?? sent.status}`)\n const res = await server.pollTransaction(sent.hash, {attempts: TX_TIMEOUT})\n if (res.status === 'FAILED') {\n const error = new Error(`Transaction ${sent.hash} failed: ${res.resultXdr?.result?.type ?? 'unknown result'}`)\n error.hash = sent.hash\n throw error\n }\n if (res.status !== 'SUCCESS')\n throw new Error(`Transaction ${sent.hash} was not included in time`)\n}\n\n/**\n * Map the client-side approval to the contract `Approval` argument\n * @param {Approval} [approve]\n * @param {string} defaultAsset - Asset approved when `approve.asset` is not set\n * @return {{asset: string, amount: bigint, live_until: number}|undefined}\n * @internal\n */\nfunction toApproval(approve, defaultAsset) {\n if (!approve)\n return undefined\n return {asset: approve.asset ?? defaultAsset, amount: approve.amount, live_until: approve.liveUntil}\n}\n\n/**\n * Sign and submit a simulated transaction\n * @param {contract.AssembledTransaction} tx\n * @return {Promise<*>} - Parsed contract call result\n * @throws {Error} - If the transaction failed on-chain\n * @internal\n */\nasync function signAndSend(tx) {\n const sent = await tx.signAndSend()\n processTransactionErrors(sent)\n return sent.result\n}\n\nasync function execTrade(params, direction, context) {\n const result = await signAndSend(await prepareTrade(params, direction, context))\n return [result[0], result[1], result[2] ?? undefined]\n}\n\n/**\n * Simulate a trade and complete its footprint\n * @param {BuyTradeArguments|SellTradeArguments} params\n * @param {number} direction\n * @param {AxisContractClient} context\n * @return {Promise<contract.AssembledTransaction>}\n * @internal\n */\nasync function prepareTrade(params, direction, context) {\n //the id of the order created for the remainder derives from the trader and this nonce; generated per call, never supplied by the caller\n const nonce = generateNonce()\n const payload = {\n direction: direction,\n kind: params.kind,\n trader: params.trader,\n amount: params.amount,\n selling: params.selling,\n buying: params.buying,\n price: params.price,\n orders: params.orders ?? [],\n nonce,\n expires: BigInt(params.expires ?? 0),\n approve: toApproval(params.approve, params.selling)\n }\n const tx = await context.client.trade(payload, {fee: context.fee})\n processSimulationErrors(tx)\n //the remainder of a Limit trade becomes an order under an id known in advance - declare it even if the simulation filled the quote\n const remainder = params.kind === OrderKind.Limit ? [orderId(params.trader, nonce)] : []\n //the bought asset passes through the contract on its way to the trader\n await context.updateTradeFootprint(tx, {\n tokens: [params.selling, params.buying],\n passThrough: [params.buying],\n receiver: params.trader,\n bought: params.buying\n }, payload.orders, remainder)\n return tx\n}\n\n/**\n * Fee and expected result of a simulated transaction\n * @param {contract.AssembledTransaction} tx - Simulated transaction with its footprint completed\n * @param {string} inclusionFee - Inclusion fee bid of the client\n * @return {TradeEstimate}\n * @internal\n */\nfunction estimateTx(tx, inclusionFee) {\n const fee = BigInt(tx.built.fee)\n const [sold, bought, orderId] = tx.result\n return {fee, inclusionFee: BigInt(inclusionFee), resourceFee: fee - BigInt(inclusionFee), sold, bought, orderId: orderId ?? undefined}\n}\n\n/**\n * @typedef {{}} ClientInitializationParams\n * @property {string} publicKey - Public key of the account that will interact with the contract\n * @property {SignTransactionCallback} signTransaction - Callback for signing transactions generated by the client\n * @property {string} rpcUrl - URL of the RPC server\n * @property {string} contractId - DEX contract ID\n * @property {string} [networkPassphrase] - Network passphrase (Pubnet passphrase by default)\n * @property {string} [fee] - Inclusion fee bid in stroops (100,000 = 0.01 XLM by default), the simulated resource fee is added on top\n * @property {boolean} [autoFootprint] - Declare every supplied order id, and the balances and allowances of the makers behind them, in the read-write footprint of trading transactions (enabled by default)\n */\n\n/**\n * @callback SignTransactionCallback - Callback for signing transactions generated by the client (`@stellar/stellar-sdk` 17 contract client shape)\n * @param {string} xdr - Transaction XDR to sign\n * @param {{networkPassphrase?: string, address?: string, submit?: boolean, submitUrl?: string}} [opts] - Signing options passed by the SDK\n * @return {Promise<{signedTxXdr: string, signerAddress?: string, error?: *}>} - Signed transaction response\n */\n\n/**\n * @typedef {{}} Approval - Token allowance granted to the contract as part of the call\n * @property {string} [asset] - Token the allowance is granted on\n * @property {bigint} amount - Absolute allowance amount (0 revokes the approval)\n * @property {number} liveUntil - Ledger sequence the allowance lives until\n */\n\n/**\n * @typedef {{}} TradeArguments\n * @property {OrderKind} kind - Trading order behavior\n * @property {string} trader - Trader address\n * @property {bigint} amount - Tokens amount\n * @property {string} selling - Selling token address\n * @property {string} buying - Buying token address\n * @property {bigint} price - Price a trader willing to accept\n * @property {Array<bigint>} [orders] - List of order IDs to match before creating the order on-chain\n * @property {bigint|number} [expires] - Expiration UNIX timestamp (in seconds) of the order created for a `Limit` remainder, 0 or omitted = no expiration\n * @property {Approval} [approve] - Optional allowance granted to the contract before trading (on `selling` unless `asset` is set)\n */\n\n/**\n * @typedef {{}} SellTradeArguments\n * @extends TradeArguments\n * @property {bigint} amount - Amount of `selling` tokens to sell\n * @property {bigint} price - Price a trader willing to accept, minimum `buying` tokens per 1 `selling`\n */\n\n/**\n * @typedef {{}} BuyTradeArguments\n * @extends TradeArguments\n * @property {bigint} amount - Amount of `buying` tokens to acquire\n * @property {bigint} price - Price a trader willing to accept, maximum `selling` tokens per 1 `buying`\n */\n\n/**\n * @typedef {{}} TradeEstimate - Simulated trade, nothing signed or submitted\n * @property {bigint} fee - Maximum total network fee of the transaction, in stroops (inclusion fee bid plus resource fee)\n * @property {bigint} inclusionFee - Inclusion fee bid, in stroops (the network charges the market rate up to it)\n * @property {bigint} resourceFee - Resource fee, in stroops, including the rent of an order created for the remainder\n * @property {bigint} sold - Expected amount of sold tokens\n * @property {bigint} bought - Expected amount of bought tokens\n * @property {bigint} [orderId] - ID of the order the remainder would create\n */\n\n/**\n * @typedef {{}} TradeStep - A trade step in a multi-market swap path\n * @property {string} asset - Asset to buy at this step\n * @property {Array<bigint>} orders - Maker order IDs to match\n */\n\n/**\n * @typedef {{}} SwapArguments - Swap path and settings\n * @property {TradeDirection} direction - Trade direction: `Sell` or `Buy`\n * @property {string} trader - Trader address\n * @property {string} selling - Token address sent by the trader\n * @property {bigint} sellingAmount - Amount of selling tokens to send (`Sell`) or the maximum to spend (`Buy`)\n * @property {bigint} buyingAmount - Minimum amount of buying tokens to receive (`Sell`) or the exact amount (`Buy`)\n * @property {Array<TradeStep>} path - Ordered list of the trade route steps\n * @property {Approval} [approve] - Optional allowance granted to the contract before trading (on `selling` unless `asset` is set)\n */\n\n/**\n * @typedef {{}} OrderUpdate - New amount, price and expiration for an existing order\n * @property {bigint} id - Order id\n * @property {bigint} amount - New amount to sell, 0 removes the order\n * @property {bigint} price - New order price (ignored for a removal)\n * @property {bigint|number} [expires] - New expiration UNIX timestamp (in seconds), 0 or omitted = no expiration\n */\n\n/**\n * @typedef {{}} UpdateArguments\n * @property {string} trader - Orders owner\n * @property {Array<OrderUpdate>} updates - New amount, price and expiration per order\n * @property {Array<Approval>} [approvals] - Allowances granted before the backing check, each naming its `asset`; an asset\n * without an approval keeps its current allowance\n */\n\n/**\n * @typedef {{}} SubsidizeArguments\n * @property {string} sponsor - Address paying for the oracle feeds (and the listing fee of a new market)\n * @property {string} selling - First market asset\n * @property {string} buying - Second market asset (either order opens the same market)\n * @property {bigint} amount - Amount of XRF fee tokens to burn, at least `Config.market_listing_fee` to open a market\n */\n\n/**\n * @typedef {{}} MethodOptions\n * @property {string} [fee] - Inclusion fee bid in stroops (100,000 = 0.01 XLM by default), the simulated resource fee is added on top\n */\n\n/**\n * @typedef {{}} Order - Order properties, stored on-chain\n * @property {bigint} id - Unique order identifier, derived from the owner and the client nonce\n * @property {string} owner - Maker address\n * @property {string} selling - Selling token address\n * @property {string} buying - Buying token address\n * @property {bigint} amount - Amount left to sell\n * @property {bigint} price - Order price (`buying` per 1 `selling`, 18 decimals)\n * @property {bigint} expires - Expiration UNIX timestamp in seconds (0 = no expiration)\n */\n\n/**\n * @typedef {{}} Config - Contract configuration\n * @property {string} safety_admin - Address of the account allowed to freeze the contract and change the configuration\n * @property {string} oracle - Oracle contract address\n * @property {number} listing_min_days - Days of price feeds a new market must buy (0 opens markets without a fee)\n * @property {bigint} market_listing_fee - Amount of oracle fee tokens paid by the market creator to provision the oracle price feeds\n * (the oracle daily fee x `listing_min_days`)\n * @property {bigint} min_trade_size - Minimum trade value in USD, with 7 decimals precision (0 disables the limit)\n * @property {number} ledger_time - Expected average ledger close time in seconds, used to convert entry lifetimes into ledgers\n */\n\n/**\n * @typedef {{}} MarketSide - Market asset descriptor\n * @property {string} asset - Token contract address\n * @property {boolean} listed - Whether the asset is quoted by the oracle (with token decimals the valuation can handle)\n * @property {number} decimals - Token decimals (fetched only for listed assets)\n */\n\n/**\n * @typedef {{}} Market - Market record, stored on-chain\n * @property {MarketSide} base - Base asset, the first of the pair in canonical order\n * @property {MarketSide} quote - Quote asset, the second of the pair in canonical order\n * @property {bigint} created - Creation UNIX timestamp in seconds\n */\n\n/**\n * @typedef {object} TradeContractEvent - Orderbook `trade` event, one per fill\n * @property {string} selling - Asset sold by the taker (topic)\n * @property {string} buying - Asset bought by the taker (topic)\n * @property {bigint} order - Maker order id\n * @property {string} taker - Trader account address\n * @property {string} maker - Seller account address\n * @property {bigint} sold - Sold tokens amount\n * @property {bigint} bought - Bought tokens amount\n * @property {bigint} left - Order amount left after the fill (0 = removed)\n */\n\n/**\n * @typedef {object} SwapContractEvent - Orderbook `swap` event, one per call\n * @property {string} selling - Asset sold by the trader (topic)\n * @property {string} buying - Asset received by the trader (topic)\n * @property {string} trader - Trader account address\n * @property {bigint} sold - Amount of `selling` tokens sold\n * @property {bigint} bought - Amount of `buying` tokens received\n */\n\n/**\n * @typedef {object} OrderCreatedContractEvent - Orderbook `new` event, an order created\n * @property {string} selling - Selling asset address (topic)\n * @property {string} buying - Buying asset address (topic)\n * @property {bigint} id - Unique order identifier\n * @property {string} owner - Maker address\n * @property {bigint} price - Order price\n * @property {bigint} amount - Current amount\n * @property {bigint} expires - Expiration UNIX timestamp in seconds (0 = no expiration)\n */\n\n/**\n * @typedef {object} OrderUpdatedContractEvent - Orderbook `mod` event, an order changed outside a fill\n * @property {bigint} id - Unique order identifier\n * @property {bigint} price - Order price\n * @property {bigint} amount - Current amount (0 = removed)\n * @property {bigint} expires - Expiration UNIX timestamp in seconds (0 = no expiration)\n */\n\n/**\n * @typedef {object} OrderSkippedContractEvent - Orderbook `skip` event, a listed order its maker could not settle: backing\n * short of the fill, a missing or deauthorized trustline for the taker's asset, or the maker's asset could not be collected.\n * The order is left unchanged. For `crossfill` it also flags a taker order its owner cannot back or be paid for\n * @property {bigint} order - Order id\n */\n\n/**\n * @typedef {object} MarketRefreshContractEvent - Orderbook `refresh` event, a market checked against the oracle\n * (topics: `refresh`, `base`, `quote`, no data)\n * @property {string} base - Base market asset (canonical order, topic)\n * @property {string} quote - Quote market asset (canonical order, topic)\n */\n\n/**\n * @typedef {object} FreezeContractEvent - `freeze` event\n * @property {boolean} frozen - Whether trading is blocked after the call\n */\n\n/**\n * @typedef {object} ConfigChangedContractEvent - `config` update notification event (constructor, `delegate`, `set_oracle`,\n * `set_floor`, `set_listing_min_days`, `set_ledger_time`)\n * @property {Config} config - Contract configuration after the call\n */\n","import * as axis from './index.js'\n\nconst axisClient = {...axis}\nexport default axisClient\n"],"names":["root","factory","exports","module","require","define","amd","this","__WEBPACK_EXTERNAL_MODULE__346__","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","d","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","ContractClient","stellar_sdk_","contract","Client","options","constructor","super","Spec","fromJSON","swap","txFromJSON","order","trade","config","freeze","frozen","market","update","requote","delegate","crossfill","set_floor","subsidize","set_oracle","set_ledger_time","set_listing_min_days","ContractErrors","message","TokenErrors","processSimulationErrors","tx","simulation","error","contractErrorMatch","exec","code","parseInt","source","match","matchAll","findErrorSource","dexContract","contractId","name","Error","tokenError","err","AxisApiError","status","AxisApiClient","serverUrl","TypeError","replace","quoteSell","params","quote","quoteBuy","sellingAsset","buyingAsset","amount","direct","maxPrice","direction","request","toString","getDepth","depth","step","limit","getCandles","from","to","resolution","getTicker24h","getMarkets","cursor","getContract","getOrders","owner","asset","getAccount","address","encodeURIComponent","getOrder","id","getOrderHistory","pair","getTrades","trader","getFailures","account","fn","path","query","url","search","URLSearchParams","entries","Array","isArray","item","append","qs","response","fetch","body","json","e","ok","statusText","ORDER_INSTRUCTIONS","ORDER_RESOURCE_FEE","DISK_ENTRY_TYPES","Set","collectOrderIds","idLists","seen","res","list","BigInt","has","add","push","orderLedgerKey","orderId","contractDataKey","nativeToScVal","type","xdr","ContractDataDurability","persistent","instanceLedgerKey","ScVal","scvLedgerKeyContractInstance","balanceLedgerKey","token","StrKey","isValidContract","scvVec","scvSymbol","Address","fromString","toScVal","accountId","Keypair","fromPublicKey","xdrAccountId","isNative","LedgerKey","LedgerKeyAccount","getIssuer","trustline","LedgerKeyTrustLine","toTrustLineXDRObject","allowanceLedgerKey","spender","scvMap","ScMapEntry","val","temporary","decodeStoredOrder","selling","buying","scValToNative","decodeSacAsset","instance","executable","entry","storage","find","info","Asset","native","asset_code","encodeEd25519PublicKey","issuer","durability","contractData","LedgerKeyContractData","toScAddress","isPatchable","restorePreamble","built","async","loadEntries","server","keys","Map","i","length","getLedgerEntries","slice","set","toXDR","unresolved","tokens","assetCache","filter","cacheAssets","declareReadWrite","data","readOnly","getReadOnly","readWrite","getReadWrite","roIndex","map","rwIndex","dropFromReadOnly","added","encoded","promoted","total","size","setFootprint","_","applyResources","instructions","diskReadBytes","writeBytes","fee","resources","build","setResources","Math","min","setResourceFee","resourceFee","simulationTransactionData","timeout","timeoutInSeconds","TransactionBuilder","cloneFrom","sorobanData","timebounds","setTimeout","U64_MAX","nonce","RangeError","payload","scvU64","digest","hash","OrderKind","Limit","Fill","FillOrKill","TradeDirection","Sell","Buy","Emitter","listeners","on","event","listener","off","once","args","delete","emit","console","AxisStreamClient","WebSocket","WebSocketImpl","pingInterval","minReconnectDelay","maxReconnectDelay","globalThis","subscriptions","topics","requests","nextId","socket","failures","closed","connected","readyState","subscribe","channel","handler","sub","topic","sendSubscribe","connect","unsubscribe","close","clear","clearTimeout","reconnectTimer","stopPing","subs","some","s","send","op","pending","scheduleReconnect","onopen","lastMessage","Date","now","startPing","onmessage","JSON","parse","route","onclose","onerror","delay","pingTimer","setInterval","clearInterval","stringify","deliver","TokenBalance","rpcUrl","networkPassphrase","rpc","Server","allowHttp","startsWith","getAllowance","toBigInt","load","getBalance","getLatestLedger","sequence","method","sourceAccount","random","publicKey","Account","addOperation","Contract","sim","simulateTransaction","Api","isSimulationError","result","retval","PRICE_SCALE","keyCache","getAddressKey","compareAssets","a","b","key1","key2","canonicalPair","x","y","pairKey","a1","a2","invertPrice","price","invertTicker","symbol","split","inv","n","Number","String","open","openPrice","last","lastPrice","highPrice","lowPrice","volume","quoteVolume","change","round","avgPrice","parseApiDate","text","trim","test","ms","isFinite","AxisMarket","axis","record","base","created","refreshed","counter","signer","contractClient","sponsor","client","api","subscribeDepth","callback","stream","subscribeTrades","trades","subscribeCandles","candles","candle","ticker","tickers","toJSON","APPROVAL_TTL_LEDGERS","APPROVAL_RENEW_LEDGERS","planApproval","required","committed","allowance","liveUntil","ledger","target","maxQuoteSpend","AxisAccount","signTransaction","ready","Promise","resolve","resolveReady","orders","backing","loaded","local","live","spent","start","handle","offOpen","stopFallback","offClose","startFallback","initTimer","refresh","catch","releaseAccount","applySnapshot","toMarketKey","allOrders","sort","newestFirst","localOrders","sum","updated","balance","balances","funded","nativeAsset","authorized","known","available","budget","sell","buy","estimateSell","prepareTrade","estimateBuy","updates","whenReady","normalized","current","expires","growth","approvals","delta","approve","batch","ids","cancel","all","cancelAll","takerOrderId","taker","findQuote","sold","bought","surplus","slippage","best","paths","hop","Boolean","tolerance","sellingAmount","buyingAmount","isAllowanceCurrent","tokenBalances","getContractId","getLedger","planned","createdId","trackCreated","kind","crossing","worstPrice","stored","orderAmount","orderPrice","backed","backedPct","backingPending","filledPct","timer","race","reject","applyOrder","applyBacking","state","mergeBacking","previous","next","raw","parseApiOrder","parseBacking","action","fill","rawFill","removed","ts","partial","share","values","fallbackTimer","fallbackPollInterval","confirmed","floor","max","skipped","part","Axis","apiUrl","wsUrl","Networks","PUBLIC","toWsUrl","ledgerTime","markets","accounts","clients","connecting","loadedAt","settled","done","fail","unsubscribeContract","applyLedger","applyContractSnapshot","then","getMarket","asset1","asset2","subscribeTicker","keepalive","days","cached","AxisContractClient","checkContractAddress","setContractId","autoFootprint","loadConfig","isFrozen","execTrade","estimateTx","approval","toApproval","updateFootprint","signAndSend","taker_order_id","updateTradeFootprint","takerOrder","receiver","selling_amount","buying_amount","hops","passThrough","isReadCall","isInteger","archived","instanceKey","getFootprint","wasmHash","codeKey","contractCode","LedgerKeyContractCode","isArchived","latestLedger","contractLifetimeEntries","submitFootprintOperation","Operation","restoreFootprint","SorobanDataBuilder","setReadWrite","extendTo","ceil","loadLedgerTime","extendFootprintTtl","setReadOnly","operation","setSorobanData","isSimulationRestore","prepared","assembleTransaction","signedTxXdr","sent","sendTransaction","errorResult","pollTransaction","attempts","resultXdr","submitTransaction","fromXDR","ledger_time","orderIds","transactionData","ensureOrdersFootprint","settlement","settlementEntries","makerEntries","orderKeys","knownTokens","passing","newTokens","flatMap","settlementKeys","settlementSet","makerOf","makerKeys","makers","diskEntries","orderEntries","forward","completeFootprint","liveUntilLedgerSeq","defaultAsset","live_until","getTransactionResponse","sendTransactionResponse","processTransactionErrors","context","crypto","getRandomValues","Uint32Array","randomBits22","remainder","inclusionFee","cjs","src_namespaceObject"],"sourceRoot":""}
|
|
1
|
+
{"version":3,"file":"axis-client.cjs","mappings":"CAAA,SAAAA,EAAAC,GACA,iBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,EAAAG,QAAA,yBACA,mBAAAC,QAAAA,OAAAC,IACAD,OAAA,yBAA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QL,EAAOK,OACfgG,QAASrG,EAAOqG,QAChBC,OAAQtG,EAAOsG,OACf0L,MAAOhS,EAAOgS,MACdoE,OAAQpW,EAAOoW,QAAU,GACzBrL,QACAmO,QAASpV,OAAO9D,EAAOkZ,SAAW,GAClC8B,QAASkG,GAAWlhB,EAAOgb,QAAShb,EAAOqG,UAEzCjK,QAAW+qB,EAAQjT,OAAOhZ,MAAM+P,EAAS,CAACnB,IAAKqd,EAAQrd,MAC7D3N,EAAwBC,GAExB,MAAMorB,EAAYxnB,EAAO0b,OAAStQ,EAAUC,MAAQ,CAACnH,EAAQlE,EAAOgC,OAAQ+I,IAAU,GAQtF,aANMoc,EAAQ7F,qBAAqBllB,EAAI,CACnCiM,OAAQ,CAACrI,EAAOqG,QAASrG,EAAOsG,QAChCsb,YAAa,CAAC5hB,EAAOsG,QACrBkb,SAAUxhB,EAAOgC,OACjBqY,OAAQra,EAAOsG,QAChB2E,EAAQmL,OAAQoR,GACZprB,CACX,CASA,SAAS6kB,GAAW7kB,EAAIqrB,GACpB,MAAM3d,EAAMhG,OAAO1H,EAAGqL,MAAMqC,MACrBsQ,EAAMC,EAAQnW,GAAW9H,EAAGqB,OACnC,MAAO,CAACqM,MAAK2d,aAAc3jB,OAAO2jB,GAAepd,YAAaP,EAAMhG,OAAO2jB,GAAerN,OAAMC,SAAQnW,QAASA,QAAW/K,EAChI,CCnpBA,MACAuuB,GADmB,IAAIC","sources":["webpack://@axis-markets/client/webpack/universalModuleDefinition","webpack://@axis-markets/client/external umd \"@stellar/stellar-sdk\"","webpack://@axis-markets/client/webpack/bootstrap","webpack://@axis-markets/client/webpack/runtime/define property getters","webpack://@axis-markets/client/webpack/runtime/hasOwnProperty shorthand","webpack://@axis-markets/client/webpack/runtime/make namespace object","webpack://@axis-markets/client/./src/contract-client.js","webpack://@axis-markets/client/./src/errors.js","webpack://@axis-markets/client/./src/api-client.js","webpack://@axis-markets/client/./src/footprint.js","webpack://@axis-markets/client/./src/order-id.js","webpack://@axis-markets/client/./src/constants.js","webpack://@axis-markets/client/./src/emitter.js","webpack://@axis-markets/client/./src/stream-client.js","webpack://@axis-markets/client/./src/token-balance.js","webpack://@axis-markets/client/./src/asset-pair.js","webpack://@axis-markets/client/./src/api-dates.js","webpack://@axis-markets/client/./src/axis-market.js","webpack://@axis-markets/client/./src/allowance.js","webpack://@axis-markets/client/./src/axis-account.js","webpack://@axis-markets/client/./src/axis.js","webpack://@axis-markets/client/./src/index.js","webpack://@axis-markets/client/./src/cjs.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"@stellar/stellar-sdk\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"@stellar/stellar-sdk\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"axisClient\"] = factory(require(\"@stellar/stellar-sdk\"));\n\telse\n\t\troot[\"axisClient\"] = factory(root[\"@stellar/stellar-sdk\"]);\n})(this, (__WEBPACK_EXTERNAL_MODULE__346__) => {\nreturn ","module.exports = __WEBPACK_EXTERNAL_MODULE__346__;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import {contract} from '@stellar/stellar-sdk'\r\n\r\nexport default class ContractClient extends contract.Client {\r\n options\r\n\r\n constructor(options) {\r\n super(new contract.Spec([\r\n \"AAAAAAAAA69Td2FwIHRva2VucyBhY3Jvc3Mgc2V2ZXJhbCBtYXJrZXRzLgpUaGUgY29udHJhY3QgaG9sZHMgdGhlIGludGVybWVkaWF0ZSBob3AgcHJvY2VlZHMgb25seSB3aXRoaW4gdGhlIGNhbGwuCgojIEFyZ3VtZW50cwoqIGBkaXJlY3Rpb25gIC0gVHJhZGUgZGlyZWN0aW9uOiBgU2VsbGAgb3IgYEJ1eWAKKiBgdHJhZGVyYCAtIFRyYWRlciBhZGRyZXNzCiogYHNlbGxpbmdgIC0gVG9rZW4gYWRkcmVzcyBzZW50IGJ5IHRoZSB0cmFkZXIKKiBgc2VsbGluZ19hbW91bnRgIC0gQW1vdW50IG9mIHNlbGxpbmcgdG9rZW5zIHRvIHNlbmQgKGBTZWxsYCkgb3IgdGhlIG1heGltdW0gdG8gc3BlbmQgKGBCdXlgKQoqIGBidXlpbmdfYW1vdW50YCAtIE1pbmltdW0gYW1vdW50IG9mIGJ1eWluZyB0b2tlbnMgdG8gcmVjZWl2ZSAoYFNlbGxgKSBvciB0aGUgZXhhY3QgYW1vdW50IChgQnV5YCkKKiBgcGF0aGAgLSBPcmRlcmVkIGxpc3Qgb2YgdGhlIHRyYWRlIHJvdXRlIHN0ZXBzCiogYGFwcHJvdmVgIC0gT3B0aW9uYWwgYWxsb3dhbmNlIGdyYW50ZWQgdG8gdGhlIGNvbnRyYWN0IGJlZm9yZSB0cmFkaW5nLCBub3JtYWxseSBvbiBgc2VsbGluZ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Ew==\",\r\n \"AAAAAQAAAB5NYXJrZXQgcmVjb3JkLCBzdG9yZWQgb24tY2hhaW4AAAAAAAAAAAAGTWFya2V0AAAAAAADAAAANEJhc2UgYXNzZXQsIHRoZSBmaXJzdCBvZiB0aGUgcGFpciBpbiBjYW5vbmljYWwgb3JkZXIAAAAEYmFzZQAAB9AAAAAKTWFya2V0U2lkZQAAAAAAEkNyZWF0aW9uIHRpbWVzdGFtcAAAAAAAB2NyZWF0ZWQAAAAABgAAADZRdW90ZSBhc3NldCwgdGhlIHNlY29uZCBvZiB0aGUgcGFpciBpbiBjYW5vbmljYWwgb3JkZXIAAAAAAAVxdW90ZQAAAAAAB9AAAAAKTWFya2V0U2lkZQAA\",\r\n \"AAAAAQAAABdNYXJrZXQgYXNzZXQgZGVzY3JpcHRvcgAAAAAAAAAACk1hcmtldFNpZGUAAAAAAAMAAAAWVG9rZW4gY29udHJhY3QgYWRkcmVzcwAAAAAABWFzc2V0AAAAAAAAEwAAAC9Ub2tlbiBkZWNpbWFscyAoZmV0Y2hlZCBvbmx5IGZvciBsaXN0ZWQgYXNzZXRzKQAAAAAIZGVjaW1hbHMAAAAEAAAAWFdoZXRoZXIgdGhlIGFzc2V0IGlzIHF1b3RlZCBieSB0aGUgb3JhY2xlICh3aXRoIHRva2VuIGRlY2ltYWxzIHRoZSB2YWx1YXRpb24gY2FuIGhhbmRsZSkAAAAGbGlzdGVkAAAAAAAB\"\r\n ]), options)\r\n this.options = options\r\n }\r\n\r\n fromJSON = {\r\n swap: this.txFromJSON,\r\n order: this.txFromJSON,\r\n trade: this.txFromJSON,\r\n config: this.txFromJSON,\r\n freeze: this.txFromJSON,\r\n frozen: this.txFromJSON,\r\n market: this.txFromJSON,\r\n update: this.txFromJSON,\r\n requote: this.txFromJSON,\r\n delegate: this.txFromJSON,\r\n crossfill: this.txFromJSON,\r\n set_floor: this.txFromJSON,\r\n subsidize: this.txFromJSON,\r\n set_oracle: this.txFromJSON,\r\n set_ledger_time: this.txFromJSON,\r\n set_listing_min_days: this.txFromJSON\r\n }\r\n}\r\n","import {StrKey, contract} from '@stellar/stellar-sdk'\r\n\r\n/**\r\n * Standard contract errors\r\n */\r\nexport const ContractErrors = {\r\n 701: {message: \"NotAuthorized\"},\r\n 702: {message: \"InsufficientBalance\"},\r\n 703: {message: \"InsufficientAllowance\"},\r\n 704: {message: \"InvalidMatch\"},\r\n 705: {message: \"InvalidPrice\"},\r\n 706: {message: \"InvalidAmount\"},\r\n 707: {message: \"InvalidExpiration\"},\r\n 708: {message: \"CannotReceive\"},\r\n 709: {message: \"NotFilled\"},\r\n 710: {message: \"OrderNotFound\"},\r\n 711: {message: \"OrderExists\"},\r\n 712: {message: \"IntermediaryCannotReceive\"},\r\n 720: {message: \"OrderSizeTooSmall\"},\r\n 721: {message: \"AssetsNotVerifiedByOracle\"},\r\n 722: {message: \"AssetPriceOracleFetchFailed\"},\r\n 723: {message: \"InvalidOracleConfig\"},\r\n 730: {message: \"Frozen\"},\r\n 740: {message: \"Overflow\"}\r\n}\r\n\r\n/**\r\n * Errors of the Stellar Asset Contract, raised by the token transfers a trading call settles with\r\n */\r\nexport const TokenErrors = {\r\n 1: {message: \"InternalError\"},\r\n 2: {message: \"OperationNotSupportedError\"},\r\n 3: {message: \"AlreadyInitializedError\"},\r\n 4: {message: \"UnauthorizedError\"},\r\n 5: {message: \"AuthenticationError\"},\r\n 6: {message: \"AccountMissingError\"},\r\n 7: {message: \"AccountIsNotClassic\"},\r\n 8: {message: \"NegativeAmountError\"},\r\n 9: {message: \"AllowanceError\"},\r\n 10: {message: \"BalanceError\"},\r\n 11: {message: \"BalanceDeauthorizedError\"},\r\n 12: {message: \"OverflowError\"},\r\n 13: {message: \"TrustlineMissingError\"}\r\n}\r\n\r\n/**\r\n * Handle simulation errors if any. A contract error raised by the DEX contract is mapped by its code. An error raised by\r\n * another contract the call invoked (the token whose transfer failed) is reported with `tokenError` set: a failed\r\n * payment to a maker fails the whole call with the token's own error, and the contract does not tell whether the payer\r\n * could not pay or the maker could not be credited (e.g. a full trustline), so neither side is assumed\r\n * @param {contract.AssembledTransaction} tx\r\n * @throws {Error} - Error with numeric `code` property for known contract errors, plus `tokenError` and `contract`\r\n * for errors raised by a token\r\n * @internal\r\n */\r\nexport function processSimulationErrors(tx) {\r\n if (tx.simulation?.error) {\r\n const message = tx.simulation.error\r\n const contractErrorMatch = /HostError: Error\\(Contract, #(\\d+)\\)/.exec(message)\r\n if (contractErrorMatch) {\r\n const code = parseInt(contractErrorMatch[1], 10)\r\n const error = contractError(code, findErrorSource(message, code)?.contract, tx.options?.contractId)\r\n if (error)\r\n throw error\r\n }\r\n throw message\r\n }\r\n}\r\n\r\n/**\r\n * Wrapped aggregated error - token error when another contract than the DEX raised it, a DEX contract error otherwise\r\n * @param {number} code - Contract error code\r\n * @param {string} [source] - Contract that raised the error, when known\r\n * @param {string} [dexContract] - DEX contract address, when known\r\n * @return {Error|null} - Null for an unknown code of the DEX\r\n * @private\r\n */\r\nfunction contractError(code, source, dexContract) {\r\n const raisedByToken = source && dexContract ? source !== dexContract : !ContractErrors[code] && !!TokenErrors[code]\r\n if (raisedByToken)\r\n return tokenError(code, source)\r\n const err = ContractErrors[code]\r\n if (!err)\r\n return null\r\n const error = new Error(`Contract execution error: #${code} ${err.message}`)\r\n error.code = code\r\n return error\r\n}\r\n\r\n/**\r\n * Locate the contract that raised the error in a simulation event log. The log lists events newest first and an error\r\n * is re-emitted by every frame it fails, so the oldest `error` event with the code is where it was raised (errors of\r\n * caught calls carry other codes)\r\n * @param {string} message - Simulation error with its diagnostic event log\r\n * @param {number} code - Error code the simulation failed with\r\n * @return {{contract: string}|null}\r\n * @private\r\n */\r\nfunction findErrorSource(message, code) {\r\n let source = null\r\n for (const match of message.matchAll(/contract:(C[A-Z2-7]{55}),\\s*topics:\\[error, Error\\(Contract, #(\\d+)\\)/g)) {\r\n if (parseInt(match[2], 10) === code) {\r\n source = {contract: match[1]}\r\n }\r\n }\r\n return source\r\n}\r\n\r\n/**\r\n * Error raised by a token transfer during settlement\r\n * @param {number} code - Token error code\r\n * @param {string} [contract] - Token contract address, when the event log names it\r\n * @return {Error}\r\n * @private\r\n */\r\nfunction tokenError(code, contract) {\r\n const name = TokenErrors[code]?.message || 'token error'\r\n const error = new Error(`Token transfer failed: #${code} ${name}${contract ? ` (token ${contract})` : ''}. ` +\r\n `Either side of the transfer may be at fault: the payer's balance or allowance, or the recipient's trustline ` +\r\n `(e.g. a full trustline limit).`)\r\n error.code = code\r\n error.tokenError = true\r\n if (contract) {\r\n error.contract = contract\r\n }\r\n return error\r\n}\r\n\r\n/**\r\n * Transaction-related error\r\n * @param {'ERROR'|'TRY_AGAIN_LATER'|'FAILED'|'TIMEOUT'} status - `ERROR`: rejected with a result code (`errorResult`\r\n * of `sendTransaction`), `TRY_AGAIN_LATER`: not accepted for now (congestion, or another transaction of the account\r\n * pending), `FAILED`: applied and failed, `TIMEOUT`: not seen before its time bounds expired\r\n * @param {{hash?: string, result?: xdr.TransactionResult, resultCode?: string, events?: xdr.DiagnosticEvent[], contractId?: string}} [details] -\r\n * Transaction hash, its result (or its result code, when known without the result), the diagnostic events of a failed\r\n * call and the DEX contract address\r\n * @return {Error} - Error with `status`, `hash`, `result` (Horizon-style transaction result code, e.g. `tx_bad_seq`),\r\n * `opResult` (operation result code of `tx_failed`, e.g. `invoke_host_function_trapped`), and `code` (plus `tokenError`\r\n * and `contract` for a token) when the diagnostic events name the contract error the call failed with\r\n * @internal\r\n */\r\nexport function transactionError(status, {hash, result, resultCode: knownCode, events, contractId} = {}) {\r\n const resultCode = knownCode ?? (result?.result?.type ? snakeCase(result.result.type) : undefined)\r\n const opResult = operationResultCode(result)\r\n const cause = events?.length ? findEventError(events) : undefined\r\n const causeError = cause ? contractError(cause.code, cause.contract, contractId) : null\r\n let message\r\n switch (status) {\r\n case 'ERROR':\r\n message = `Transaction ${hash} was not accepted by the network: ${resultCode ?? 'unknown result'}`\r\n break\r\n case 'TRY_AGAIN_LATER':\r\n message = `Transaction ${hash} was not accepted by the network for now, try again later`\r\n break\r\n case 'FAILED':\r\n message = `Transaction ${hash} failed: ${resultCode ?? 'unknown result'}${opResult ? ` (${opResult})` : ''}`\r\n break\r\n default:\r\n message = `Transaction ${hash} was not confirmed before its time bounds expired`\r\n }\r\n if (causeError) {\r\n message += `. ${causeError.message}`\r\n }\r\n const error = new Error(message)\r\n error.status = status\r\n error.hash = hash\r\n if (resultCode) {\r\n error.result = resultCode\r\n }\r\n if (opResult) {\r\n error.opResult = opResult\r\n }\r\n if (causeError) {\r\n error.code = causeError.code\r\n if (causeError.tokenError) {\r\n error.tokenError = true\r\n if (causeError.contract) {\r\n error.contract = causeError.contract\r\n }\r\n }\r\n }\r\n return error\r\n}\r\n\r\n/**\r\n * Code of the first failed operation of a `tx_failed` result\r\n * @param {xdr.TransactionResult} [result]\r\n * @return {string|undefined} - Horizon-style code, e.g. `invoke_host_function_trapped`\r\n * @private\r\n */\r\nfunction operationResultCode(result) {\r\n if (result?.result?.type !== 'txFailed')\r\n return undefined\r\n for (const op of result.result.results || []) {\r\n //an applied operation reports its own result code, an operation that could not run the outer code\r\n const code = op.type === 'opInner' ? op.tr?.value?.type : op.type\r\n if (code && !/Success$/.test(code))\r\n return snakeCase(code)\r\n }\r\n return undefined\r\n}\r\n\r\n/**\r\n * Contract error a failed call raised, from its diagnostic events (oldest first). An error is re-emitted by every frame\r\n * it fails, so the last error event carries the code the call failed with and the oldest event with that code names the\r\n * contract that raised it\r\n * @param {xdr.DiagnosticEvent[]} events\r\n * @return {{code: number, contract?: string}|undefined}\r\n * @private\r\n */\r\nfunction findEventError(events) {\r\n const errors = []\r\n for (const event of events) {\r\n const code = eventErrorCode(event)\r\n if (code !== undefined) {\r\n errors.push({code, contract: eventContract(event)})\r\n }\r\n }\r\n if (!errors.length)\r\n return undefined\r\n const {code} = errors[errors.length - 1]\r\n return {code, contract: errors.find(error => error.code === code && error.contract)?.contract}\r\n}\r\n\r\n/**\r\n * Contract error code of an `error` diagnostic event\r\n * @param {xdr.DiagnosticEvent} event\r\n * @return {number|undefined}\r\n * @private\r\n */\r\nfunction eventErrorCode(event) {\r\n const topics = event?.event?.body?.value?.topics\r\n if (!topics || topics.length < 2)\r\n return undefined\r\n const [name, value] = topics\r\n if (name.type !== 'scvSymbol' || name.sym.toString() !== 'error')\r\n return undefined\r\n if (value.type !== 'scvError' || value.error.type !== 'sceContract')\r\n return undefined\r\n return value.error.contractCode\r\n}\r\n\r\n/**\r\n * @param {xdr.DiagnosticEvent} event\r\n * @return {string|undefined} - Address of the contract that emitted the event\r\n * @private\r\n */\r\nfunction eventContract(event) {\r\n const id = event.event.contractId\r\n return id ? StrKey.encodeContract(id.toBytes()) : undefined\r\n}\r\n\r\n/**\r\n * @param {string} name - XDR union arm name, e.g. `txBadSeq`\r\n * @return {string} - Horizon-style code, e.g. `tx_bad_seq`\r\n * @private\r\n */\r\nfunction snakeCase(name) {\r\n return name.replace(/[A-Z]/g, letter => '_' + letter.toLowerCase())\r\n}\r\n","/**\n * Error thrown when the AXIS API responds with a non-success HTTP status\n */\nexport class AxisApiError extends Error {\n /**\n * @param {string} message - Error message returned by the API\n * @param {number} status - HTTP status code\n */\n constructor(message, status) {\n super(message)\n this.name = 'AxisApiError'\n this.status = status\n }\n\n /**\n * HTTP status code associated with the error\n * @type {number}\n * @readonly\n */\n status\n}\n\n/**\n * HTTP client for the AXIS REST API\n */\nexport class AxisApiClient {\n /**\n * @param {string} serverUrl - Base URL of the AXIS API server\n */\n constructor(serverUrl) {\n if (!serverUrl || typeof serverUrl !== 'string')\n throw new TypeError('AXIS API server URL is required')\n //trim trailing slashes to avoid double slashes when building request paths\n this.serverUrl = serverUrl.replace(/\\/+$/, '')\n }\n\n /**\n * Base URL of the AXIS API server\n * @type {string}\n * @readonly\n */\n serverUrl\n\n /**\n * Price quote and candidate trade routes for selling a fixed amount of the source asset\n * @param {QuoteParams} params - Quote request parameters\n * @return {Promise<QuoteResult>} - Best routes ranked by profitability\n * @throws {AxisApiError} - 409 if the server is not ready or routing fails, 400 on invalid parameters. Not enough\n * liquidity resolves with `status: 'unfeasible'`, a frozen contract with `status: 'rejected'`\n */\n async quoteSell(params) {\n return this.quote(params, 'strict_send')\n }\n\n /**\n * Price quote and candidate trade routes for buying a fixed amount of the destination asset\n * @param {QuoteParams} params - Quote request parameters\n * @return {Promise<QuoteResult>} - Best routes ranked by profitability\n * @throws {AxisApiError} - 409 if the server is not ready or routing fails, 400 on invalid parameters. Not enough\n * liquidity resolves with `status: 'unfeasible'`, a frozen contract with `status: 'rejected'`\n */\n async quoteBuy(params) {\n return this.quote(params, 'strict_receive')\n }\n\n /**\n * Find viable multi-hop paths between two assets, simulate trades on each path, and return the best routes\n * @param {QuoteParams} params - Quote request parameters\n * @param {'strict_send'|'strict_receive'} direction - Trade direction\n * @return {Promise<QuoteResult>}\n * @private\n */\n async quote({sellingAsset, buyingAsset, amount, direct, maxPrice}, direction) {\n return this.request('/quote', {sellingAsset, buyingAsset, amount, direction, direct, maxPrice: maxPrice?.toString()})\n }\n\n /**\n * Order book depth around the mid price, aggregated into price levels on multiples of `step` (bids rounded down,\n * asks up, so a level price crosses every order in it)\n * @param {DepthParams} params - Depth request parameters\n * @return {Promise<OrderbookDepth>} - Aggregated bids and asks\n */\n async getDepth({market, depth, step, limit}) {\n return this.request('/depth', {market, depth, step, limit})\n }\n\n /**\n * OHLCVT candlestick data (open, high, low, close, base volume, quote volume, trade count)\n * @param {CandlesParams} params - Candles request parameters\n * @return {Promise<Candle[]>} - Time-bucketed candles, max 200 per response\n */\n async getCandles({market, from, to, resolution, order}) {\n return this.request('/candles', {market, from, to, resolution, order})\n }\n\n /**\n * 24-hour ticker statistics for every available market\n * @return {Promise<Ticker24hResult>} - Aggregated 24h stats per market\n */\n async getTicker24h() {\n return this.request('/ticker/24h')\n }\n\n /**\n * List all active markets with pagination\n * @param {MarketsParams} [params] - Pagination parameters\n * @return {Promise<MarketInfo[]>} - Active markets\n */\n async getMarkets({cursor, limit} = {}) {\n return this.request('/markets', {cursor, limit})\n }\n\n /**\n * Contract state tracked by the indexer: frozen switch, configuration and active markets\n * @return {Promise<ContractInfo>} - Contract state\n */\n async getContract() {\n return this.request('/contract')\n }\n\n /**\n * Retrieve active orders, filterable by owner or asset\n * @param {OrdersParams} [params] - Filter parameters\n * @return {Promise<ApiOrder[]>} - Active orders matching the filter\n */\n async getOrders({owner, asset, cursor, limit} = {}) {\n return this.request('/order', {owner, asset, cursor, limit})\n }\n\n /**\n * Account state tracked by the indexer: every live order of the trader (not paginated) and their backing in each\n * asset they trade\n * @param {string} address - Trader address\n * @return {Promise<ApiAccount>}\n */\n async getAccount(address) {\n return this.request(`/account/${encodeURIComponent(address)}`)\n }\n\n /**\n * Retrieve a single order by ID\n * @param {bigint|string|number} id - Order ID\n * @return {Promise<ApiOrder>} - Order (throws AxisApiError with status 404 if not found)\n */\n async getOrder(id) {\n return this.request(`/order/${encodeURIComponent(id.toString())}`)\n }\n\n /**\n * Retrieve archived/historical orders\n * @param {OrderHistoryParams} [params] - Filter parameters\n * @return {Promise<ApiOrder[]>} - Archived orders matching the filter\n */\n async getOrderHistory({owner, pair, cursor, limit} = {}) {\n return this.request('/order-history', {owner, pair, cursor, limit})\n }\n\n /**\n * Retrieve recent trades and swaps, newest first\n * @param {TradesParams} [params] - Filter parameters\n * @return {Promise<Array<ApiTrade|ApiSwap>>} - Recent trades and swaps matching the filter (told apart by `type`)\n */\n async getTrades({trader, pair, cursor, limit} = {}) {\n return this.request('/trades', {trader, pair, cursor, limit})\n }\n\n /**\n * Failed AXIS calls, newest first (diagnostics: a failure changes no state, and a record never blames a party, see\n * {@link ApiFailure})\n * @param {FailuresParams} [params] - Filter parameters\n * @return {Promise<ApiFailure[]>}\n */\n async getFailures({account, fn, cursor, limit} = {}) {\n return this.request('/failures', {account, fn, cursor, limit})\n }\n\n /**\n * Execute a GET request against the AXIS API\n * @param {string} path - Relative route path\n * @param {object} [query] - Query parameters (undefined/null values skipped, arrays expanded to repeated params)\n * @return {Promise<*>} - Parsed JSON response\n * @throws {AxisApiError} - If the API responds with a non-success status\n * @private\n */\n async request(path, query) {\n let url = this.serverUrl + path\n if (query) {\n const search = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null)\n continue\n if (Array.isArray(value)) {\n for (const item of value)\n search.append(key, item)\n } else {\n search.append(key, value)\n }\n }\n const qs = search.toString()\n if (qs)\n url += '?' + qs\n }\n const response = await fetch(url)\n let body\n try {\n body = await response.json()\n } catch (e) {\n //non-JSON response (e.g. proxy/gateway error) - fall back to status text\n body = null\n }\n if (!response.ok)\n throw new AxisApiError(body?.error || response.statusText, body?.status || response.status)\n return body\n }\n}\n\n/**\n * @typedef {{}} QuoteParams\n * @property {string} sellingAsset - Asset to sell (`XLM` | `CODE:Issuer` | `CODE-Issuer` | contractId)\n * @property {string} buyingAsset - Asset to buy (same format as `sellingAsset`)\n * @property {string|number} amount - Trade amount in stroops (1 unit = 10,000,000 stroops)\n * @property {boolean} [direct] - Restrict to the direct market only (no intermediate-asset routes)\n * @property {bigint|string} [maxPrice] - Highest maker price to cross (requires `direct`), in the units of a hop\n * `worstPrice`: `sellingAsset` per unit of `buyingAsset`, scaled by 10^18. Quotes the crossing of a limit order: orders\n * priced above it are left out and the route may trade less than `amount`\n */\n\n/**\n * @typedef {{}} QuoteResult\n * @property {string} id - Base58-encoded quote id\n * @property {'success'|'unfeasible'|'rejected'} status - Quote status\n * @property {'strict_send'|'strict_receive'} direction - Trade direction\n * @property {string} sellingAsset - Selling asset contract id\n * @property {string} buyingAsset - Buying asset contract id\n * @property {number} ledger - Ledger sequence the quote was computed for\n * @property {QuotePath[]} paths - Candidate routes ranked by profitability (up to 10)\n * @property {string} [error] - Error message (present only if status is not `success`)\n */\n\n/**\n * @typedef {{}} QuotePath\n * @property {string} sold - Amount sold, in stroops\n * @property {string} bought - Amount bought, in stroops\n * @property {QuotePathStep[]} path - Ordered list of hops in the route\n */\n\n/**\n * @typedef {{}} QuotePathStep\n * @property {string} selling - Selling asset contract id at this hop\n * @property {string} buying - Buying asset contract id at this hop\n * @property {string[]} orders - Maker order IDs matched at this hop\n * @property {string} [worstPrice] - Highest price among the matched orders (maker `buying` per `selling`, 18 decimals):\n * a trade limit at this price crosses every listed order\n */\n\n/**\n * @typedef {{}} DepthParams\n * @property {string} market - Market identifier `BASE/QUOTE`\n * @property {number} [depth] - Percentage band (±) around the center price (0 < depth ≤ 100, default 20)\n * @property {string} [step] - Price step of the levels, a decimal such as `\"0.0005\"` (5 significant digits of the mid\n * price by default)\n * @property {number} [limit] - Price levels per side (default 100, max 500)\n */\n\n/**\n * @typedef {{}} OrderbookDepth\n * @property {number} ledger - Ledger sequence\n * @property {number} timestamp - UNIX timestamp (seconds)\n * @property {string|null} step - Price step of the levels (null for an empty book)\n * @property {string|null} bestBid - Exact best bid price, before the rounding to levels\n * @property {string|null} bestAsk - Exact best ask price, before the rounding to levels\n * @property {Array<[string, string]>} bids - `[price, quantity]` pairs sorted descending by price\n * @property {Array<[string, string]>} asks - `[price, quantity]` pairs sorted ascending by price\n */\n\n/**\n * @typedef {{}} CandlesParams\n * @property {string} market - Market identifier `BASE/QUOTE`\n * @property {number} [from] - Lower boundary (UNIX seconds, default 0)\n * @property {number} [to] - Upper boundary (UNIX seconds, defaults to `from + resolution * 200`)\n * @property {number|string} [resolution] - Resolution in seconds or alias (`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`12h`,`1d`,`3d`,`1w`,`2w`, default `auto`)\n * @property {'asc'|'desc'} [order] - Sort order (default `desc`)\n */\n\n/**\n * OHLCVT candle row: `[timestamp, open, high, low, close, baseVolume, quoteVolume, tradeCount]`\n * @typedef {[number, string, string, string, string, string, string, number]} Candle\n */\n\n/**\n * @typedef {{}} Ticker24hResult\n * @property {number} ledger - Ledger sequence\n * @property {number} timestamp - UNIX timestamp (seconds)\n * @property {TickerEntry[]} ticker - Per-market 24h stats, sorted by trade count descending\n */\n\n/**\n * @typedef {{}} TickerEntry\n * @property {string} symbol - Market symbol `BASE/QUOTE`\n * @property {string} openPrice - Opening price 24h ago\n * @property {string} highPrice - Highest price in the 24h window\n * @property {string} lowPrice - Lowest price in the 24h window\n * @property {string} lastPrice - Most recent trade price\n * @property {string} volume - 24h base asset volume\n * @property {string} quoteVolume - 24h quote asset volume\n * @property {number} change - 24h price change (percent)\n * @property {string} avgPrice - Volume-weighted average price\n * @property {number} trades - 24h trade count\n */\n\n/**\n * @typedef {{}} MarketsParams\n * @property {string} [cursor] - Pagination cursor (`baseAsset-quoteAsset`)\n * @property {number|string} [limit] - Max markets to return\n */\n\n/**\n * @typedef {{}} MarketInfo\n * @property {string} baseAsset - Base asset contract id\n * @property {string} quoteAsset - Quote asset contract id\n * @property {string} cursor - Pagination cursor for this market\n * @property {string[]} orderTypes - Supported order types\n */\n\n/**\n * @typedef {{}} ContractInfo - Contract state tracked by the indexer\n * @property {string} address - AXIS contract address\n * @property {boolean} frozen - Whether trading is blocked by the safety admin\n * @property {ContractInfoConfig} [config] - Contract configuration\n * @property {ContractInfoMarket[]} markets - Markets opened by `subsidize`\n */\n\n/**\n * @typedef {{}} ContractInfoConfig\n * @property {string} safetyAdmin - Safety admin address\n * @property {string} oracle - Price oracle contract address\n * @property {number} [listingMinDays] - Days of price feeds a new market must buy (0 opens markets without a fee)\n * @property {string} marketListingFee - Oracle fee tokens a market creator pays to provision the price feeds\n * @property {string} minTradeSize - Minimum trade value in USD with 7 decimals (0 = disabled)\n * @property {number} [ledgerTime] - Expected ledger close time in seconds\n */\n\n/**\n * @typedef {{}} ContractInfoMarket\n * @property {string} base - Base market asset, the first of the pair in canonical order\n * @property {string} quote - Quote market asset, the second of the pair in canonical order\n * @property {string} created - Creation timestamp (UTC)\n * @property {string} refreshed - Last oracle check timestamp (UTC)\n */\n\n/**\n * @typedef {{}} OrdersParams\n * @property {string} [owner] - Filter by order owner address\n * @property {string|string[]} [asset] - Filter by asset(s) - every listed asset must be one of the order assets (two assets select a pair)\n * @property {string|bigint} [cursor] - `cursor` of the last order received (its creation position, not the order id)\n * @property {number|string} [limit] - Max orders to return\n */\n\n/**\n * @typedef {{}} OrderHistoryParams\n * @property {string} [owner] - Filter by order owner address\n * @property {string[]} [pair] - Asset pair `[base, quote]` (contract ids)\n * @property {string|bigint} [cursor] - `cursor` of the last order received (its creation position, not the order id)\n * @property {number|string} [limit] - Max orders to return\n */\n\n/**\n * @typedef {{}} TradesParams\n * @property {string} [trader] - Filter by trader address\n * @property {string[]} [pair] - Asset pair `[base, quote]` (contract ids)\n * @property {string|bigint} [cursor] - `cursor` of the last record received (the trade or swap id)\n * @property {number|string} [limit] - Max trades to return\n */\n\n/**\n * @typedef {{}} FailuresParams\n * @property {string} [account] - Caller of the failed transaction, or a party of the failed transfer\n * @property {string} [fn] - Contract function (`trade`, `swap`, `crossfill`, `update`, ...)\n * @property {string|bigint} [cursor] - `cursor` of the last record received\n * @property {number|string} [limit] - Max records to return (20 by default, at most 500)\n */\n\n/**\n * @typedef {{}} ApiFailure - Failed AXIS call (made by the transaction or through another contract, the transaction failed\n * or a calling contract caught the failure). It changes no state and blames no party:\n * a token error on a settlement transfer does not tell the payer who could not pay from the recipient who could not be\n * credited (e.g. a full trustline), and in a `crossfill` the makers are paid by the taker order owner, not the caller\n * @property {'failure'} type - Record type\n * @property {string} id - Record id (position of the transaction plus the index of the failed call)\n * @property {string} txHash - Transaction hash\n * @property {number} ledger - Ledger sequence\n * @property {string} timestamp - Ledger close time (UTC)\n * @property {string} fn - Contract function called\n * @property {string} caller - The `trader` or `sponsor` argument, the transaction source for other functions\n * @property {string[]} orders - Maker order ids listed by the call\n * @property {string} [takerOrder] - Taker order id of a `crossfill`\n * @property {string} result - Operation result code\n * @property {boolean} [caught] - The transaction succeeded: a calling contract caught the failed AXIS call\n * @property {'contract'|'transfer'|'resources'|'auth'|'unknown'} reason - `contract`: a contract error (`error`),\n * `transfer`: a token transfer failed (`transfer`, either side may be at fault), `resources`: a resource limit, the\n * refundable fee or an archived entry, `auth`: an authorization failure, `unknown`: no diagnostic events\n * @property {{contract: string|null, code: number, name?: string}} [error] - Contract error that failed the call\n * @property {{token: string, fn: string, from: string, to: string, amount: string}} [transfer] - Token transfer that failed\n * @property {string} cursor - Pagination cursor\n */\n\n/**\n * @typedef {{}} ApiOrder - Serialized order returned by the API\n * @property {string} id - Order ID (decimal u128)\n * @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Order status: `ACTIVE`, `FILLED`, `CANCELED` (removed by the owner) or `EXPIRED` (archived once past `expires`)\n * @property {string} buying - Buying asset contract id\n * @property {string} selling - Selling asset contract id\n * @property {string} price - Order price\n * @property {string} rprice - Rational price representation\n * @property {string} quote - Selling amount at creation\n * @property {string} amount - Amount left to sell\n * @property {string} [backed] - Amount the maker can actually deliver, when the indexer tracks backing\n * @property {ApiOrderBacking} [backing] - Maker backing details, when the indexer tracks backing\n * @property {string} owner - Maker address\n * @property {string} [expires] - Expiration timestamp (UTC)\n * @property {string} [created] - Creation timestamp (UTC)\n * @property {string} [updated] - Last update timestamp (UTC)\n * @property {string} [cursor] - Pagination cursor\n */\n\n/**\n * @typedef {{}} ApiOrderBacking - Maker backing in the order's selling asset\n * @property {string} balance - Token balance\n * @property {string} allowance - Allowance granted to the AXIS contract\n * @property {number} liveUntil - Ledger sequence the allowance lives until\n * @property {boolean} authorized - Whether the maker can send and receive the token\n * @property {string} [updated] - Last load timestamp (UTC)\n * @property {boolean} [pending] - A reload confirming the latest event is still due: the values may predate it\n */\n\n/**\n * @typedef {{}} ApiBacking - Tracked backing of an account in a token\n * @property {string} owner - Account address\n * @property {string} asset - Token contract id\n * @property {string} balance - Token balance\n * @property {string} allowance - Allowance granted to the AXIS contract\n * @property {number} liveUntil - Ledger sequence the allowance lives until\n * @property {boolean} authorized - Whether the account can send and receive the token\n * @property {string} budget - Effective budget, min(balance, allowance), 0 when unauthorized or expired\n * @property {string} [headroom] - Amount the account can still receive (trustline limit minus balance and buying\n * liabilities), omitted when unlimited or unknown\n * @property {string} [updated] - Last load timestamp (UTC)\n * @property {string} [skipped] - Last `skip` event of an order selling the token (UTC)\n * @property {boolean} [pending] - A reload confirming the latest event is still due\n */\n\n/**\n * @typedef {{}} ApiAccount - Account state: every live order and the backing per traded asset\n * @property {string} address - Trader address\n * @property {number} ledger - Last processed ledger\n * @property {ApiOrder[]} orders - Live orders, oldest first\n * @property {Object<string, ApiBacking>} backing - Backing by token contract id\n */\n\n/**\n * @typedef {{}} ApiSwap - Serialized swap returned by the API, one per `swap` call\n * @property {'swap'} type - Record type\n * @property {string} id - Swap ID\n * @property {string} trader - Trader address\n * @property {string} soldAsset - Sold asset contract id\n * @property {string} boughtAsset - Bought asset contract id\n * @property {string} sold - Sold tokens amount\n * @property {string} bought - Bought tokens amount\n * @property {string} price - Approximate swap price\n * @property {string} cursor - Pagination cursor\n * @property {string} timestamp - Swap timestamp (UTC)\n */\n\n/**\n * @typedef {{}} ApiTrade - Serialized trade returned by the API\n * @property {'trade'} type - Record type\n * @property {string} id - Trade ID\n * @property {string} order - Matched order ID\n * @property {string} taker - Taker account address\n * @property {string} maker - Maker account address\n * @property {string} soldAsset - Sold asset contract id\n * @property {string} boughtAsset - Bought asset contract id\n * @property {string} sold - Sold tokens amount\n * @property {string} bought - Bought tokens amount\n * @property {string} [left] - Order amount left after the fill\n * @property {boolean} [crossfill] - The fill of a `crossfill` taker order: `taker` is the caller, paid the surplus, and the\n * amounts mirror the makers' fills of the same call (left out of candles and volume)\n * @property {string} price - Approximate trade price\n * @property {string} [cursor] - Pagination cursor\n * @property {string} timestamp - Trade timestamp (UTC)\n */\n","import {xdr, Address, Asset, Keypair, StrKey, TransactionBuilder, nativeToScVal, scValToNative, contract, rpc} from '@stellar/stellar-sdk'\r\n\r\n/**\r\n * Upper bound of a serialized `Order` ledger entry in bytes.\r\n * (positional vector of three addresses, i128 amount and price, optional u64 expires = at most 188-byte value,\r\n * about 264-byte ledger entry, rounded up to 320).\r\n * @type {number}\r\n */\r\nexport const ORDER_ENTRY_SIZE = 320\r\n\r\n/**\r\n * CPU instructions added to the declared budget for every order that was not matched at simulation time.\r\n * @type {number}\r\n */\r\nexport const ORDER_INSTRUCTIONS = 2_000_000\r\n\r\n/**\r\n * Resource fee (stroops) added for every order that was not matched at simulation time.\r\n * (write entry ~10k, read entry ~6k, writes ~12k, 2M instructions ~5k, trade/order events ~10k).\r\n * @type {bigint}\r\n */\r\nexport const ORDER_RESOURCE_FEE = 100_000n\r\n\r\n/**\r\n * Upper bound of a maker balance (account, trustline or token balance) or allowance ledger entry in bytes.\r\n * @type {number}\r\n */\r\nexport const MAKER_ENTRY_SIZE = 256\r\n\r\n/**\r\n * Resource fee (stroops) added for every maker entry declared read-write (write entry ~10k, its bytes charged as written ~6k).\r\n * @type {bigint}\r\n */\r\nexport const MAKER_ENTRY_RESOURCE_FEE = 20_000n\r\n\r\n/**\r\n * CPU instructions added for every maker whose entries were declared (two token transfers, backing and receive checks).\r\n * @type {number}\r\n */\r\nexport const MAKER_INSTRUCTIONS = 3_000_000\r\n\r\n/**\r\n * Resource fee (stroops) added for every maker whose entries were declared (instructions ~8k, two transfer events and\r\n * a `skip` event ~4k, rounded up).\r\n * @type {bigint}\r\n */\r\nexport const MAKER_RESOURCE_FEE = 20_000n\r\n\r\n/**\r\n * CPU instructions added when the settlement entries of the call were declared: the transfer forwarding what the makers\r\n * delivered from the DEX contract to the receiver, and the receive checks before it.\r\n * @type {number}\r\n */\r\nexport const FORWARD_INSTRUCTIONS = 2_000_000\r\n\r\n/**\r\n * Resource fee (stroops) added when the settlement entries of the call were declared (instructions ~5k, the forwarding\r\n * `transfer` event ~2k, rounded up).\r\n * @type {bigint}\r\n */\r\nexport const FORWARD_RESOURCE_FEE = 10_000n\r\n\r\n/**\r\n * Ledger entry types read from disk when a transaction is applied: every declared one counts towards the disk read\r\n * bytes, whether the execution touches it or not.\r\n * @type {Set<string>}\r\n */\r\nconst DISK_ENTRY_TYPES = new Set(['account', 'trustline'])\r\n\r\n/**\r\n * Network-wide per-transaction instructions limit.\r\n * @type {number}\r\n */\r\nconst MAX_TX_INSTRUCTIONS = 400_000_000\r\n\r\n/**\r\n * Network-wide per-transaction limits of read-write and total footprint entries.\r\n */\r\nconst MAX_READ_WRITE_ENTRIES = 200\r\nconst MAX_FOOTPRINT_ENTRIES = 400\r\n\r\n/**\r\n * Keys per `getLedgerEntries` request accepted by RPC.\r\n */\r\nconst LEDGER_ENTRIES_BATCH = 200\r\n\r\n/**\r\n * Flatten and deduplicate order ids from several lists, coercing them to bigint.\r\n * @param {...(Array<bigint|number|string>|undefined|null)} idLists - Lists of order ids\r\n * @return {bigint[]} - Unique order ids in the order of first appearance\r\n */\r\nexport function collectOrderIds(...idLists) {\r\n const seen = new Set()\r\n const res = []\r\n for (const list of idLists) {\r\n if (!list)\r\n continue\r\n for (const id of list) {\r\n if (id === undefined || id === null)\r\n continue\r\n const value = BigInt(id)\r\n const key = value.toString()\r\n if (seen.has(key))\r\n continue\r\n seen.add(key)\r\n res.push(value)\r\n }\r\n }\r\n return res\r\n}\r\n\r\n/**\r\n * Build persistent contract data ledger key of an order (the key is the raw u128 order id).\r\n * @param {string} contractId - DEX contract address\r\n * @param {bigint|number|string} orderId - Order id\r\n * @return {xdr.LedgerKey}\r\n */\r\nexport function orderLedgerKey(contractId, orderId) {\r\n return contractDataKey(contractId, nativeToScVal(BigInt(orderId), {type: 'u128'}), xdr.ContractDataDurability.persistent)\r\n}\r\n\r\n/**\r\n * Build the ledger key of a contract instance entry.\r\n * @param {string} contractId - Contract address\r\n * @return {xdr.LedgerKey}\r\n */\r\nexport function instanceLedgerKey(contractId) {\r\n return contractDataKey(contractId, xdr.ScVal.scvLedgerKeyContractInstance(), xdr.ContractDataDurability.persistent)\r\n}\r\n\r\n/**\r\n * Build the ledger key holding the balance of `owner` in a Stellar Asset Contract token.\r\n * @param {string} owner - Account or contract address\r\n * @param {string} token - Token contract address\r\n * @param {Asset|null} asset - Classic asset behind the token, `null` for a token that is not a Stellar Asset Contract\r\n * @return {xdr.LedgerKey|null} - `null` when the balance has no ledger entry of its own (issuer) or the token storage layout is unknown\r\n */\r\nexport function balanceLedgerKey(owner, token, asset) {\r\n if (!asset)\r\n return null\r\n if (StrKey.isValidContract(owner))\r\n return contractDataKey(token, xdr.ScVal.scvVec([xdr.ScVal.scvSymbol('Balance'), Address.fromString(owner).toScVal()]), xdr.ContractDataDurability.persistent)\r\n const accountId = Keypair.fromPublicKey(owner).xdrAccountId()\r\n if (asset.isNative())\r\n return xdr.LedgerKey.account(new xdr.LedgerKeyAccount({accountId}))\r\n //the issuer holds no trustline for its own asset\r\n if (asset.getIssuer() === owner)\r\n return null\r\n return xdr.LedgerKey.trustline(new xdr.LedgerKeyTrustLine({accountId, asset: asset.toTrustLineXDRObject()}))\r\n}\r\n\r\n/**\r\n * Build the ledger key of the allowance `owner` granted to `spender` in a Stellar Asset Contract token.\r\n * @param {string} owner - Account or contract address granting the allowance\r\n * @param {string} token - Token contract address\r\n * @param {string} spender - Spender address (the DEX contract)\r\n * @return {xdr.LedgerKey}\r\n */\r\nexport function allowanceLedgerKey(owner, token, spender) {\r\n const key = xdr.ScVal.scvVec([\r\n xdr.ScVal.scvSymbol('Allowance'),\r\n xdr.ScVal.scvMap([\r\n new xdr.ScMapEntry({key: xdr.ScVal.scvSymbol('from'), val: Address.fromString(owner).toScVal()}),\r\n new xdr.ScMapEntry({key: xdr.ScVal.scvSymbol('spender'), val: Address.fromString(spender).toScVal()})\r\n ])\r\n ])\r\n return contractDataKey(token, key, xdr.ContractDataDurability.temporary)\r\n}\r\n\r\n/**\r\n * Decode a stored order entry value: a positional vector `[owner, selling, buying, amount, price, expires?]`.\r\n * @param {xdr.ScVal} val - Contract data value of the order entry\r\n * @return {{owner: string, selling: string, buying: string}}\r\n */\r\nexport function decodeStoredOrder(val) {\r\n const [owner, selling, buying] = scValToNative(val)\r\n return {owner, selling, buying}\r\n}\r\n\r\n/**\r\n * Resolve the classic asset behind a token from its contract instance entry.\r\n * @param {xdr.ScVal} val - Contract data value of the token instance entry\r\n * @return {Asset|null} - `null` for a token that is not a Stellar Asset Contract\r\n */\r\nexport function decodeSacAsset(val) {\r\n if (val.type !== 'scvContractInstance' || val.instance.executable.type !== 'contractExecutableStellarAsset')\r\n return null\r\n const entry = (val.instance.storage ?? []).find(({key}) => scValToNative(key)?.[0] === 'AssetInfo')\r\n if (!entry)\r\n return null\r\n const [type, info] = scValToNative(entry.val)\r\n if (type === 'Native')\r\n return Asset.native()\r\n //alphanum codes are padded with zero bytes\r\n const code = info.asset_code.replace(/\\0+$/, '')\r\n return new Asset(code, StrKey.encodeEd25519PublicKey(info.issuer))\r\n}\r\n\r\n/**\r\n * Make sure every supplied order id declared in the read-write footprint of a simulated transaction.\r\n * @param {contract.AssembledTransaction} tx - Simulated transaction\r\n * @param {string} contractId - DEX contract address\r\n * @param {Array<bigint|number|string>} orderIds - Order ids passed to the contract call\r\n * @return {number} - Number of order entries added to the read-write footprint\r\n */\r\nexport function ensureOrdersFootprint(tx, contractId, orderIds) {\r\n if (!isPatchable(tx) || !orderIds?.length)\r\n return 0\r\n const data = tx.simulation.transactionData\r\n const added = declareReadWrite(data, collectOrderIds(orderIds).map(id => orderLedgerKey(contractId, id))).length\r\n if (added === 0)\r\n return 0\r\n applyResources(tx, data, {\r\n instructions: added * ORDER_INSTRUCTIONS,\r\n writeBytes: added * ORDER_ENTRY_SIZE,\r\n fee: BigInt(added) * ORDER_RESOURCE_FEE\r\n })\r\n return added\r\n}\r\n\r\n/**\r\n * Complete the footprint of a simulated trading transaction, so it still applies when the book moves between simulation\r\n * and execution (an order repriced back into range, a maker's backing restored, an earlier order shrunk). Every listed\r\n * order entry is declared read-write, then the entries the settlement writes for the call itself: the DEX contract's own\r\n * balance of every asset passing through it (makers deliver to the contract, which forwards to the receiver) and the\r\n * receiver's balance of the bought asset. Then, for every order's maker, the balance of the asset the maker sells, the\r\n * allowance on it granted to the DEX contract, and the balance of the asset the maker receives. Tokens that are not\r\n * Stellar Asset Contracts keep what the simulation recorded (their storage layout is unknown). Entries are added in that\r\n * order while the footprint limits allow.\r\n * @param {contract.AssembledTransaction} tx - Simulated transaction\r\n * @param {string} contractId - DEX contract address\r\n * @param {Array<bigint|number|string>} orderIds - Order ids passed to the contract call\r\n * @param {FootprintOptions} options\r\n * @return {Promise<{orders: number, settlementEntries: number, makerEntries: number}>} - Number of order, settlement and\r\n * maker entries added to the read-write footprint\r\n */\r\nexport async function completeFootprint(tx, contractId, orderIds, {server, tokens = [], assetCache = new Map(), passThrough = [], receiver, bought, takerOrder}) {\r\n if (!isPatchable(tx) || !orderIds?.length)\r\n return {orders: 0, settlementEntries: 0, makerEntries: 0}\r\n const ids = collectOrderIds(orderIds)\r\n const orderKeys = ids.map(id => orderLedgerKey(contractId, id))\r\n //one request for the orders and the known tokens, another one only for tokens first seen in the orders\r\n const knownTokens = unresolved([...tokens, ...passThrough, ...(bought ? [bought] : [])], assetCache)\r\n const entries = await loadEntries(server, [...orderKeys, ...knownTokens.map(instanceLedgerKey)])\r\n cacheAssets(entries, knownTokens, assetCache)\r\n const orders = []\r\n for (let i = 0; i < ids.length; i++) {\r\n const entry = entries.get(orderKeys[i].toXDR('base64'))\r\n if (entry) {\r\n orders.push({id: ids[i], ...decodeStoredOrder(entry.contractData.val)})\r\n }\r\n }\r\n //a crossfill buys what the taker order buys: it passes through the contract, which pays the owner and the receiver\r\n const passing = [...passThrough]\r\n if (takerOrder !== undefined && takerOrder !== null) {\r\n const taker = orders.find(order => order.id === BigInt(takerOrder))\r\n if (taker) {\r\n passing.push(taker.buying)\r\n bought ??= taker.buying\r\n }\r\n }\r\n const newTokens = unresolved(orders.flatMap(({selling, buying}) => [selling, buying]), assetCache)\r\n if (newTokens.length) {\r\n cacheAssets(await loadEntries(server, newTokens.map(instanceLedgerKey)), newTokens, assetCache)\r\n }\r\n //entries the settlement of the call writes whichever makers fill\r\n const settlementKeys = [\r\n ...[...new Set(passing)].map(token => balanceLedgerKey(contractId, token, assetCache.get(token) ?? null)),\r\n receiver && bought ? balanceLedgerKey(receiver, bought, assetCache.get(bought) ?? null) : null\r\n ].filter(Boolean)\r\n const settlementSet = new Set(settlementKeys.map(key => key.toXDR('base64')))\r\n //entries the settlement writes for each maker, tagged with the maker\r\n const makerOf = new Map()\r\n const makerKeys = []\r\n for (const {owner, selling, buying} of orders) {\r\n const sold = assetCache.get(selling)\r\n const keys = [\r\n balanceLedgerKey(owner, selling, sold),\r\n sold ? allowanceLedgerKey(owner, selling, contractId) : null,\r\n balanceLedgerKey(owner, buying, assetCache.get(buying))\r\n ]\r\n for (const key of keys) {\r\n if (!key)\r\n continue\r\n const encoded = key.toXDR('base64')\r\n if (settlementSet.has(encoded))\r\n continue //declared with the settlement entries\r\n makerOf.set(encoded, owner)\r\n makerKeys.push(key)\r\n }\r\n }\r\n const data = tx.simulation.transactionData\r\n //entries promoted from the read-only part are already counted as disk reads by the simulation\r\n const readOnly = new Set(data.getReadOnly().map(key => key.toXDR('base64')))\r\n const added = declareReadWrite(data, [...orderKeys, ...settlementKeys, ...makerKeys])\r\n if (!added.length)\r\n return {orders: 0, settlementEntries: 0, makerEntries: 0}\r\n const makers = new Set()\r\n let makerEntries = 0\r\n let settlementEntries = 0\r\n let diskEntries = 0\r\n for (const key of added) {\r\n const encoded = key.toXDR('base64')\r\n if (settlementSet.has(encoded)) {\r\n settlementEntries++\r\n } else if (makerOf.has(encoded)) {\r\n makerEntries++\r\n makers.add(makerOf.get(encoded))\r\n } else\r\n continue\r\n if (DISK_ENTRY_TYPES.has(key.type) && !readOnly.has(encoded)) {\r\n diskEntries++\r\n }\r\n }\r\n const orderEntries = added.length - makerEntries - settlementEntries\r\n //the forwarding transfer runs only when something settles, which the simulation did not see\r\n const forward = settlementEntries > 0 ? 1 : 0\r\n applyResources(tx, data, {\r\n instructions: orderEntries * ORDER_INSTRUCTIONS + makers.size * MAKER_INSTRUCTIONS + forward * FORWARD_INSTRUCTIONS,\r\n diskReadBytes: diskEntries * MAKER_ENTRY_SIZE,\r\n writeBytes: orderEntries * ORDER_ENTRY_SIZE + (makerEntries + settlementEntries) * MAKER_ENTRY_SIZE,\r\n fee: BigInt(orderEntries) * ORDER_RESOURCE_FEE + BigInt(makerEntries + settlementEntries) * MAKER_ENTRY_RESOURCE_FEE +\r\n BigInt(makers.size) * MAKER_RESOURCE_FEE + BigInt(forward) * FORWARD_RESOURCE_FEE\r\n })\r\n return {orders: orderEntries, settlementEntries, makerEntries}\r\n}\r\n\r\n/**\r\n * @param {string} contractId\r\n * @param {xdr.ScVal} key\r\n * @param {xdr.ContractDataDurability} durability\r\n * @return {xdr.LedgerKey}\r\n * @private\r\n */\r\nfunction contractDataKey(contractId, key, durability) {\r\n return xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({\r\n contract: Address.fromString(contractId).toScAddress(),\r\n key,\r\n durability\r\n }))\r\n}\r\n\r\n/**\r\n * Whether the simulation succeeded and can be patched\r\n * @param {contract.AssembledTransaction} tx\r\n * @return {boolean}\r\n * @private\r\n */\r\nfunction isPatchable(tx) {\r\n const simulation = tx.simulation\r\n return !!simulation && !simulation.error && !simulation.restorePreamble && !!tx.built\r\n}\r\n\r\n/**\r\n * Fetch ledger entries, keyed by the base64 XDR of their ledger keys\r\n * @param {rpc.Server} server\r\n * @param {xdr.LedgerKey[]} keys\r\n * @return {Promise<Map<string, xdr.LedgerEntryData>>}\r\n * @private\r\n */\r\nasync function loadEntries(server, keys) {\r\n const res = new Map()\r\n for (let i = 0; i < keys.length; i += LEDGER_ENTRIES_BATCH) {\r\n const {entries} = await server.getLedgerEntries(...keys.slice(i, i + LEDGER_ENTRIES_BATCH))\r\n for (const entry of entries) {\r\n res.set(entry.key.toXDR('base64'), entry.val)\r\n }\r\n }\r\n return res\r\n}\r\n\r\n/**\r\n * Tokens from the list not resolved yet, deduplicated\r\n * @param {string[]} tokens\r\n * @param {Map<string, Asset|null>} assetCache\r\n * @return {string[]}\r\n * @private\r\n */\r\nfunction unresolved(tokens, assetCache) {\r\n return [...new Set(tokens)].filter(token => !assetCache.has(token))\r\n}\r\n\r\n/**\r\n * Store the classic asset of every token from the loaded instance entries (`null` when unknown)\r\n * @param {Map<string, xdr.LedgerEntryData>} entries\r\n * @param {string[]} tokens\r\n * @param {Map<string, Asset|null>} assetCache\r\n * @private\r\n */\r\nfunction cacheAssets(entries, tokens, assetCache) {\r\n for (const token of tokens) {\r\n const entry = entries.get(instanceLedgerKey(token).toXDR('base64'))\r\n assetCache.set(token, entry ? decodeSacAsset(entry.contractData.val) : null)\r\n }\r\n}\r\n\r\n/**\r\n * Add keys to the read-write part of a simulated footprint, dropping them from the read-only part, while the\r\n * footprint limits allow\r\n * @param {SorobanDataBuilder} data - Simulation data to patch\r\n * @param {xdr.LedgerKey[]} keys - Keys to declare, in priority order\r\n * @return {xdr.LedgerKey[]} - Keys actually added\r\n * @private\r\n */\r\nfunction declareReadWrite(data, keys) {\r\n const readOnly = data.getReadOnly()\r\n const readWrite = data.getReadWrite()\r\n const roIndex = new Map(readOnly.map((key, i) => [key.toXDR('base64'), i]))\r\n const rwIndex = new Set(readWrite.map(key => key.toXDR('base64')))\r\n const dropFromReadOnly = new Set()\r\n const added = []\r\n for (const key of keys) {\r\n const encoded = key.toXDR('base64')\r\n if (rwIndex.has(encoded))\r\n continue\r\n //a key promoted from the read-only part does not grow the footprint\r\n const promoted = roIndex.has(encoded)\r\n const total = readOnly.length - dropFromReadOnly.size + readWrite.length\r\n if (readWrite.length >= MAX_READ_WRITE_ENTRIES || (!promoted && total >= MAX_FOOTPRINT_ENTRIES))\r\n continue\r\n //a key can't be listed in both parts of the footprint\r\n if (promoted) {\r\n dropFromReadOnly.add(roIndex.get(encoded))\r\n }\r\n readWrite.push(key)\r\n rwIndex.add(encoded)\r\n added.push(key)\r\n }\r\n if (added.length) {\r\n data.setFootprint(readOnly.filter((_, i) => !dropFromReadOnly.has(i)), readWrite)\r\n }\r\n return added\r\n}\r\n\r\n/**\r\n * Declare the resources of the added entries and rebuild the transaction from the patched simulation data\r\n * @param {contract.AssembledTransaction} tx - Simulated transaction\r\n * @param {SorobanDataBuilder} data - Patched simulation data\r\n * @param {{instructions: number, diskReadBytes?: number, writeBytes: number, fee: bigint}} extra - Resources and fee to add\r\n * @private\r\n */\r\nfunction applyResources(tx, data, {instructions, diskReadBytes = 0, writeBytes, fee}) {\r\n const resources = data.build().resources\r\n data.setResources(Math.min(resources.instructions + instructions, MAX_TX_INSTRUCTIONS), resources.diskReadBytes + diskReadBytes, resources.writeBytes + writeBytes)\r\n data.setResourceFee((data.build().resourceFee + fee).toString())\r\n\r\n //drop cached simulation data so the SDK picks up the patched builder when signing\r\n delete tx.simulationTransactionData\r\n //keep the built transaction consistent with the patched footprint and fee\r\n const timeout = tx.options?.timeoutInSeconds ?? 300\r\n tx.built = TransactionBuilder.cloneFrom(tx.built, {\r\n sorobanData: data.build(),\r\n timebounds: undefined\r\n })\r\n .setTimeout(timeout)\r\n .build()\r\n}\r\n\r\n/**\r\n * @typedef {{}} FootprintOptions\r\n * @property {rpc.Server} server - RPC server used to load the listed orders and the token instances\r\n * @property {string[]} [tokens] - Tokens the call trades, resolved together with the orders\r\n * @property {Map<string, Asset|null>} [assetCache] - Classic assets of resolved tokens (`null` for other tokens), reused between calls\r\n * @property {string[]} [passThrough] - Tokens the call moves through the DEX contract's own balance: the bought asset of a\r\n * trade, every hop asset of a swap\r\n * @property {string} [receiver] - Account the bought asset is forwarded to (the trader, or the crossfill caller paid the surplus)\r\n * @property {string} [bought] - Token the receiver gets (the taker order's `buying` by default for a crossfill)\r\n * @property {bigint|number|string} [takerOrder] - Taker order of a crossfill: the asset it buys passes through the contract\r\n */\r\n","import {xdr, Address, hash} from '@stellar/stellar-sdk'\n\nconst U64_MAX = (1n << 64n) - 1n\n\n/**\n * Compute the id of the order `owner` creates with `nonce`.\n * Mirrors the contract: the first 16 bytes of `sha256(xdr(ScVec[owner: Address, nonce: u64]))`\n * interpreted as a big-endian `u128` (the full 128 bits, no mask).\n * @param {string} owner - Order owner address (account or contract)\n * @param {bigint|number|string} nonce - Client-chosen u64 nonce\n * @return {bigint} - u128 order id\n */\nexport function orderId(owner, nonce) {\n nonce = BigInt(nonce)\n if (nonce < 0n || nonce > U64_MAX)\n throw new RangeError('Nonce must fit u64')\n const payload = xdr.ScVal.scvVec([\n Address.fromString(owner).toScVal(),\n xdr.ScVal.scvU64(nonce)\n ]).toXDR()\n const digest = hash(payload)\n let id = 0n\n for (let i = 0; i < 16; i++) {\n id = (id << 8n) | BigInt(digest[i])\n }\n return id\n}\n\n/**\n * Generate a u64 order nonce: wall clock (in milliseconds) shifted left by 22 bits plus 22 random bits.\n * The clock part fits 42 bits until the year 2109, so the nonce never overflows u64; the random part makes\n * collisions among the orders an account creates within the same millisecond negligible.\n * Internal to the client - consumers never supply or observe nonces, `buy`/`sell` generate one per call.\n * @return {bigint}\n * @internal\n */\nexport function generateNonce() {\n return (BigInt(Date.now()) << 22n) | BigInt(randomBits22())\n}\n\nfunction randomBits22() {\n const crypto = globalThis.crypto\n if (crypto?.getRandomValues) {\n return crypto.getRandomValues(new Uint32Array(1))[0] & 0x3fffff\n }\n return Math.floor(Math.random() * 0x400000)\n}\n","/** Trading order type */\nexport const OrderKind = {\n /** Execute trade, create a limit order if not executed in full */\n Limit: 1,\n /** Execute trade without creating a limit order */\n Fill: 2,\n /** Execute trade, cancel if was not executed in full */\n FillOrKill: 3\n}\n\n/** Trade direction instructions */\nexport const TradeDirection = {\n Sell: 1,\n Buy: 2\n}\n","/** Minimal event emitter that works in browsers and Node */\nexport class Emitter {\n /**\n * @type {Map<string, Set<function>>}\n * @private\n */\n listeners = new Map()\n\n /**\n * Subscribe to an event\n * @param {string} event\n * @param {function} listener\n * @return {function(): void} - Unsubscribe function\n */\n on(event, listener) {\n let set = this.listeners.get(event)\n if (!set) {\n set = new Set()\n this.listeners.set(event, set)\n }\n set.add(listener)\n return () => this.off(event, listener)\n }\n\n /**\n * Subscribe to the next occurrence of an event\n * @param {string} event\n * @param {function} listener\n * @return {function(): void} - Unsubscribe function\n */\n once(event, listener) {\n const off = this.on(event, (...args) => {\n off()\n listener(...args)\n })\n return off\n }\n\n /**\n * Unsubscribe from an event\n * @param {string} event\n * @param {function} listener\n */\n off(event, listener) {\n const set = this.listeners.get(event)\n if (!set)\n return\n set.delete(listener)\n if (!set.size) {\n this.listeners.delete(event)\n }\n }\n\n /**\n * @param {string} event\n * @param {...*} args\n * @protected\n */\n emit(event, ...args) {\n const set = this.listeners.get(event)\n if (!set)\n return\n for (const listener of [...set]) {\n try {\n listener(...args)\n } catch (e) {\n console.error(`Unhandled error in \"${event}\" listener`, e)\n }\n }\n }\n}\n","import {Emitter} from './emitter.js'\n\n/**\n * WebSocket client of the AXIS API push channel\n *\n * Emits `open`, `close` and `error` (server errors not tied to a subscription).\n */\nexport class AxisStreamClient extends Emitter {\n /**\n * @param {string} url - WebSocket endpoint, e.g. `wss://demo-api.axis.markets/ws` (testnet)\n * @param {StreamClientOptions} [options]\n */\n constructor(url, {WebSocket: WebSocketImpl, pingInterval = 20_000, minReconnectDelay = 1_000, maxReconnectDelay = 30_000} = {}) {\n super()\n if (!url || typeof url !== 'string')\n throw new TypeError('WebSocket URL is required')\n this.url = url\n this.WebSocket = WebSocketImpl || globalThis.WebSocket\n if (!this.WebSocket)\n throw new Error('WebSocket is not available in this environment, pass the `WebSocket` option')\n this.pingInterval = pingInterval\n this.minReconnectDelay = minReconnectDelay\n this.maxReconnectDelay = maxReconnectDelay\n }\n\n /**\n * WebSocket endpoint\n * @type {string}\n * @readonly\n */\n url\n /**\n * Active subscriptions\n * @type {Set<StreamSubscription>}\n * @private\n */\n subscriptions = new Set()\n /**\n * Subscriptions by the server topic\n * @type {Map<string, Set<StreamSubscription>>}\n * @private\n */\n topics = new Map()\n /**\n * Subscriptions waiting for their snapshot, by request id\n * @type {Map<number, StreamSubscription>}\n * @private\n */\n requests = new Map()\n /**\n * @type {number}\n * @private\n */\n nextId = 1\n /**\n * @type {WebSocket|undefined}\n * @private\n */\n socket\n /**\n * @type {number}\n * @private\n */\n failures = 0\n /**\n * @type {boolean}\n * @private\n */\n closed = false\n\n /**\n * Whether the connection is open\n * @return {boolean}\n */\n get connected() {\n return !!this.socket && this.socket.readyState === 1\n }\n\n /**\n * Subscribe to a channel; connects on the first subscription\n * @param {'contract'|'ticker'|'account'|'trades'|'depth'|'candles'} channel\n * @param {{address?: string, market?: string, depth?: number, step?: string, resolution?: number|string, limit?: number}} params -\n * Channel parameters\n * @param {function(StreamMessage): void} handler - Receives the snapshot (again after every reconnect), the\n * changes, and `{type: 'error'}` if the server rejects the subscription\n * @return {function(): void} - Unsubscribe function\n */\n subscribe(channel, params, handler) {\n /** @type {StreamSubscription} */\n const sub = {channel, params: params || {}, handler, topic: undefined}\n this.subscriptions.add(sub)\n this.closed = false\n if (this.connected) {\n this.sendSubscribe(sub)\n } else {\n this.connect()\n }\n return () => this.unsubscribe(sub)\n }\n\n /**\n * Close the connection and drop every subscription\n */\n close() {\n this.closed = true\n this.subscriptions.clear()\n this.topics.clear()\n this.requests.clear()\n clearTimeout(this.reconnectTimer)\n this.stopPing()\n if (this.socket) {\n const socket = this.socket\n this.socket = undefined\n socket.close()\n }\n }\n\n /**\n * @param {StreamSubscription} sub\n * @private\n */\n unsubscribe(sub) {\n if (!this.subscriptions.delete(sub))\n return\n const {topic} = sub\n if (topic) {\n const subs = this.topics.get(topic)\n subs?.delete(sub)\n if (subs && !subs.size) {\n this.topics.delete(topic)\n if (this.connected && ![...this.subscriptions].some(s => s.topic === topic)) {\n this.send({op: 'unsubscribe', channel: sub.channel, ...sub.params})\n }\n }\n }\n for (const [id, pending] of this.requests) {\n if (pending === sub) {\n this.requests.delete(id)\n }\n }\n }\n\n /**\n * @private\n */\n connect() {\n if (this.socket || this.closed)\n return\n clearTimeout(this.reconnectTimer)\n let socket\n try {\n socket = new this.WebSocket(this.url)\n } catch (e) {\n this.scheduleReconnect()\n return\n }\n this.socket = socket\n socket.onopen = () => {\n if (this.socket !== socket)\n return\n this.failures = 0\n this.lastMessage = Date.now()\n this.startPing()\n for (const sub of this.subscriptions) {\n this.sendSubscribe(sub)\n }\n this.emit('open')\n }\n socket.onmessage = e => {\n if (this.socket !== socket)\n return\n this.lastMessage = Date.now()\n let message\n try {\n message = JSON.parse(typeof e.data === 'string' ? e.data : e.data.toString())\n } catch (err) {\n return\n }\n this.route(message)\n }\n socket.onclose = () => {\n if (this.socket !== socket)\n return\n this.socket = undefined\n this.stopPing()\n //topics are per connection\n this.topics.clear()\n this.requests.clear()\n for (const sub of this.subscriptions) {\n sub.topic = undefined\n }\n this.emit('close')\n this.scheduleReconnect()\n }\n socket.onerror = () => {\n //followed by close\n }\n }\n\n /**\n * @private\n */\n scheduleReconnect() {\n if (this.closed || !this.subscriptions.size)\n return\n const delay = Math.min(this.maxReconnectDelay, this.minReconnectDelay * 2 ** this.failures)\n this.failures++\n this.reconnectTimer = setTimeout(() => this.connect(), delay)\n }\n\n /**\n * @private\n */\n startPing() {\n this.stopPing()\n this.pingTimer = setInterval(() => {\n //no traffic for two periods: the connection is dead even if it was not closed\n if (Date.now() - this.lastMessage > this.pingInterval * 2) {\n this.socket?.close()\n return\n }\n this.send({op: 'ping'})\n }, this.pingInterval)\n }\n\n /**\n * @private\n */\n stopPing() {\n clearInterval(this.pingTimer)\n this.pingTimer = undefined\n }\n\n /**\n * @param {StreamSubscription} sub\n * @private\n */\n sendSubscribe(sub) {\n const id = this.nextId++\n this.requests.set(id, sub)\n this.send({op: 'subscribe', id, channel: sub.channel, ...sub.params})\n }\n\n /**\n * @param {{}} message\n * @private\n */\n send(message) {\n if (this.connected) {\n this.socket.send(JSON.stringify(message))\n }\n }\n\n /**\n * Deliver a server message to its subscriptions\n * @param {StreamMessage} message\n * @private\n */\n route(message) {\n if (message.type === 'pong' || message.type === 'unsubscribed')\n return\n if (message.id !== undefined && this.requests.has(message.id)) {\n //subscription response: snapshot (learn the topic) or rejection\n const sub = this.requests.get(message.id)\n this.requests.delete(message.id)\n if (message.type === 'error') {\n this.subscriptions.delete(sub)\n return deliver(sub, message)\n }\n if (message.topic) {\n sub.topic = message.topic\n let subs = this.topics.get(message.topic)\n if (!subs) {\n subs = new Set()\n this.topics.set(message.topic, subs)\n }\n subs.add(sub)\n }\n return deliver(sub, message)\n }\n if (message.topic) {\n for (const sub of this.topics.get(message.topic) || []) {\n deliver(sub, message)\n }\n return\n }\n if (message.type === 'error') {\n this.emit('error', new Error(message.error))\n }\n }\n}\n\n/**\n * @param {StreamSubscription} sub\n * @param {StreamMessage} message\n */\nfunction deliver(sub, message) {\n try {\n sub.handler(message)\n } catch (e) {\n console.error(`Unhandled error in the \"${sub.channel}\" subscription handler`, e)\n }\n}\n\n/**\n * @typedef {{}} StreamClientOptions\n * @property {typeof WebSocket} [WebSocket] - WebSocket implementation (the global one by default)\n * @property {number} [pingInterval] - Application-level ping period, in milliseconds (20 s by default)\n * @property {number} [minReconnectDelay] - First reconnect delay, doubled after each failure (1 s by default)\n * @property {number} [maxReconnectDelay] - Reconnect delay cap (30 s by default)\n */\n\n/**\n * @typedef {{}} StreamMessage - Server message; `type` names the payload, `topic` the subscription it belongs to\n * @property {string} type\n * @property {string} [topic]\n * @property {number} [id]\n */\n\n/**\n * @typedef {{}} StreamSubscription\n * @property {string} channel\n * @property {{}} params\n * @property {function(StreamMessage): void} handler\n * @property {string} [topic]\n * @internal\n */\n","import {Account, Address, Contract, Keypair, TransactionBuilder, scValToNative, rpc, xdr} from '@stellar/stellar-sdk'\n\n/**\n * Token state for allowance calculation, token balances, and current ledger\n */\nexport class TokenBalance {\n /**\n * @param {{rpcUrl: string, networkPassphrase: string, spender: string, server?: rpc.Server}} options - `spender`\n * is the AXIS contract\n */\n constructor({rpcUrl, networkPassphrase, spender, server}) {\n this.server = server || new rpc.Server(rpcUrl, {allowHttp: rpcUrl.startsWith('http://')})\n this.networkPassphrase = networkPassphrase\n this.spender = spender\n }\n\n /**\n * Allowance `owner` granted to the AXIS contract on a token, 0 when expired\n * @param {string} token - Token contract address\n * @param {string} owner - Token holder address\n * @return {Promise<bigint>}\n * @throws {Error} - If the simulation fails\n */\n async getAllowance(token, owner) {\n const retval = await this.load(token, 'allowance', [new Address(owner).toScVal(), new Address(this.spender).toScVal()], owner)\n return toBigInt(retval)\n }\n\n /**\n * Token balance of an account\n * @param {string} token - Token contract address\n * @param {string} owner - Token holder address\n * @return {Promise<bigint>} - 0 if the account holds no balance entry\n */\n async getBalance(token, owner) {\n try {\n return toBigInt(await this.load(token, 'balance', [new Address(owner).toScVal()], owner))\n } catch (e) {\n return 0n\n }\n }\n\n /**\n * Latest closed ledger sequence\n * @return {Promise<number>}\n */\n async getLatestLedger() {\n const {sequence} = await this.server.getLatestLedger()\n return sequence\n }\n\n /**\n * @param {string} token\n * @param {string} method\n * @param {xdr.ScVal[]} args\n * @param {string} source - Transaction source address\n * @return {Promise<xdr.ScVal>}\n * @private\n */\n async load(token, method, args, source) {\n //a contract address cannot be a transaction source\n const sourceAccount = source.startsWith('G') ? source : Keypair.random().publicKey()\n const tx = new TransactionBuilder(new Account(sourceAccount, '0'), {fee: '100', networkPassphrase: this.networkPassphrase})\n .addOperation(new Contract(token).call(method, ...args))\n .setTimeout(30)\n .build()\n const sim = await this.server.simulateTransaction(tx)\n if (rpc.Api.isSimulationError(sim))\n throw new Error(`Token ${method} simulation failed for ${token}: ${sim.error}`)\n return sim.result.retval\n }\n}\n\n/**\n * @param {xdr.ScVal} retval\n * @return {bigint}\n */\nfunction toBigInt(retval) {\n const value = scValToNative(retval)\n return typeof value === 'bigint' ? value : BigInt(value ?? 0)\n}\n","import {Address} from '@stellar/stellar-sdk'\n\n/** Price scale of the contract (18 decimals) */\nexport const PRICE_SCALE = 10n ** 18n\n\n/**\n * Serialized `ScAddress` by address string\n * @type {Map<string, Uint8Array>}\n */\nconst keyCache = new Map()\n\n/**\n * @param {string} address\n * @return {Uint8Array}\n */\nfunction getAddressKey(address) {\n let key = keyCache.get(address)\n if (!key) {\n key = Address.fromString(address).toScAddress().toXDR()\n if (keyCache.size >= 10_000) { //will never happen in real life\n keyCache.clear()\n }\n keyCache.set(address, key)\n }\n return key\n}\n\n/**\n * Compare two assets in the contract canonical order\n * @param {string} a - Token contract address\n * @param {string} b - Token contract address\n * @return {number} - Negative if `a` first, positive if `b` first, 0 if equal\n */\nexport function compareAssets(a, b) {\n if (a === b)\n return 0\n const key1 = getAddressKey(a)\n const key2 = getAddressKey(b)\n const length = Math.min(key1.length, key2.length)\n for (let i = 0; i < length; i++) {\n if (key1[i] !== key2[i])\n return key1[i] - key2[i]\n }\n return key1.length - key2.length\n}\n\n/**\n * Reorder an asset pair the way the contract stores markets\n * @param {string} x - Token contract address\n * @param {string} y - Token contract address\n * @return {[string, string]} - `[a, b]`: `a` is the base, `b` the quote of the canonical market symbol\n */\nexport function canonicalPair(x, y) {\n return compareAssets(x, y) <= 0 ? [x, y] : [y, x]\n}\n\n/**\n * Canonical market key `a/b`\n * @param {string} a - Token contract address\n * @param {string} b - Token contract address\n * @return {string}\n */\nexport function pairKey(a, b) {\n const [a1, a2] = canonicalPair(a, b)\n return a1 + '/' + a2\n}\n\n/**\n * Calculate inverted price, rounded down: `floor(10^36 / price)`\n * @param {bigint} price - Price in the contract scale\n * @return {bigint}\n */\nexport function invertPrice(price) {\n if (price <= 0n)\n return 0n\n return PRICE_SCALE * PRICE_SCALE / price\n}\n\n/**\n * 24h ticker entry of the market seen in the inverted orientation (`b/a`)\n * @param {TickerEntry} entry - Standard ticker entry\n * @return {TickerEntry}\n */\nexport function invertTicker(entry) {\n const [a, b] = entry.symbol.split('/')\n const inv = value => {\n const n = Number(value)\n return n > 0 ? String(1 / n) : '0'\n }\n const open = Number(entry.openPrice)\n const last = Number(entry.lastPrice)\n return {\n ...entry,\n symbol: b + '/' + a,\n openPrice: inv(entry.openPrice),\n highPrice: inv(entry.lowPrice),\n lowPrice: inv(entry.highPrice),\n lastPrice: inv(entry.lastPrice),\n volume: entry.quoteVolume,\n quoteVolume: entry.volume,\n change: open > 0 && last > 0 ? Math.round((open / last - 1) * 100_000) / 1000 : 0,\n avgPrice: inv(entry.avgPrice)\n }\n}\n","/**\n * Parse an AXIS API timestamp (`YYYY-MM-DD HH:mm:ss` UTC)\n * @param {string|number|undefined} value\n * @return {number} - UNIX milliseconds, 0 when missing or invalid\n */\nexport function parseApiDate(value) {\n if (value === undefined || value === null || value === '')\n return 0\n if (typeof value === 'number')\n return value\n let text = String(value).trim().replace(' ', 'T')\n if (!/[zZ]|[+-]\\d\\d:?\\d\\d$/.test(text)) {\n text += 'Z'\n }\n const ms = Date.parse(text)\n return Number.isFinite(ms) ? ms : 0\n}\n","import {canonicalPair} from './asset-pair.js'\nimport {parseApiDate} from './api-dates.js'\n\n/**\n * DEX Market\n */\nexport class AxisMarket {\n /**\n * @param {Axis} axis\n * @param {{base: string, quote: string, created?: string, refreshed?: string}} record - Market data\n */\n constructor(axis, record) {\n this.axis = axis\n const [base, quote] = canonicalPair(record.base, record.quote)\n this.base = base\n this.quote = quote\n this.key = base + '/' + quote\n this.update(record)\n }\n\n /**\n * Base asset, the first of the pair in the contract canonical order\n * @type {string}\n * @readonly\n */\n base\n /**\n * Quote asset, the second of the pair in the contract canonical order\n * @type {string}\n * @readonly\n */\n quote\n /**\n * Canonical market key `base/quote`\n * @type {string}\n * @readonly\n */\n key\n /**\n * Creation timestamp (first oracle check) (UNIX milliseconds)\n * @type {number}\n */\n created = 0\n /**\n * Last oracle check (UNIX milliseconds)\n * @type {number}\n */\n refreshed = 0\n\n /**\n * Check whether the asset is one of the market assets\n * @param {string} asset\n * @return {boolean}\n */\n has(asset) {\n return asset === this.base || asset === this.quote\n }\n\n /**\n * The other market asset\n * @param {string} asset - One of the market assets\n * @return {string}\n */\n counter(asset) {\n if (asset === this.base)\n return this.quote\n if (asset === this.quote)\n return this.base\n throw new Error(`Asset ${asset} does not belong to the market ${this.key}`)\n }\n\n /**\n * Apply the contract state change record\n * @param {{created?: string, refreshed?: string}} record\n * @internal\n */\n update(record) {\n if (record.created) {\n this.created = parseApiDate(record.created)\n }\n if (record.refreshed) {\n this.refreshed = parseApiDate(record.refreshed)\n }\n }\n\n /**\n * Re-check both market assets against the price oracle and cache oracle prices\n * @param {Signer} [signer] - Transaction source, the {@link Axis} signer by default\n * @return {Promise<Market|undefined>}\n */\n async requote(signer) {\n const client = await this.axis.contractClient(signer)\n return client.requote(this.base, this.quote)\n }\n\n /**\n * Extend oracle price feeds access for the market\n * @param {{amount: bigint, sponsor?: string, signer?: Signer}} params - `amount` of fee tokens to burn\n * @return {Promise<bigint[]>} - New access expiration UNIX timestamps (in seconds) for each oracle-listed asset\n */\n async subsidize({amount, sponsor, signer}) {\n const client = await this.axis.contractClient(signer)\n return client.subsidize({sponsor: sponsor ?? client.publicKey, selling: this.base, buying: this.quote, amount})\n }\n\n /**\n * Orderbook depth data with given precision\n * @param {{base?: string, depth?: number, step?: string, limit?: number}} [params] - `base` is the base asset, `step` the price step (automatic by default)\n * @return {Promise<import('./api-client.js').OrderbookDepth>}\n */\n async getDepth({base = this.base, depth, step, limit} = {}) {\n return this.axis.api.getDepth({market: base + '/' + this.counter(base), depth, step, limit})\n }\n\n /**\n * Stream the orderbook depth\n * Returns a snapshot, then updates on book changes\n * @param {{base?: string, depth?: number, step?: string, limit?: number}} params\n * @param {function(OrderbookDepth): void} callback\n * @return {function(): void} - Unsubscribe function\n */\n subscribeDepth({base = this.base, depth, step, limit} = {}, callback) {\n const market = base + '/' + this.counter(base)\n return this.axis.stream.subscribe('depth', {market, depth, step, limit}, message => {\n if (message.type === 'depth') {\n callback(message.data)\n }\n })\n }\n\n /**\n * Stream the market trades\n * Returns a snapshot, then updates on trades\n * @param {function(ApiTrade[], boolean): void} callback - Trades and whether they are the snapshot\n * @return {function(): void} - Unsubscribe function\n */\n subscribeTrades(callback) {\n return this.axis.stream.subscribe('trades', {market: this.key}, message => {\n if (message.type === 'trades') {\n callback(message.trades, true)\n } else if (message.type === 'trade') {\n callback([message.trade], false)\n }\n })\n }\n\n /**\n * Stream the market candles\n * Returns a snapshot, then updates on trades\n * @param {{base?: string, resolution: number|string, limit?: number}} params - `base` is the base asset of the view, `resolution` in seconds or an alias (`5m`, `1h`, …), `limit` the candles in the snapshot (200 by default, at most 200)\n * @param {function(Candle[], boolean): void} callback - Candles\n * @return {function(): void} - Unsubscribe function\n */\n subscribeCandles({base = this.base, resolution, limit}, callback) {\n const market = base + '/' + this.counter(base)\n return this.axis.stream.subscribe('candles', {market, resolution, limit}, message => {\n if (message.type === 'candles') {\n callback(message.candles, true)\n } else if (message.type === 'candle') {\n callback([message.candle], false)\n }\n })\n }\n\n /**\n * Last 24h ticker entry of the market, available while {@link Axis#subscribeTicker} runs\n * @return {TickerEntry|undefined}\n */\n get ticker() {\n return this.axis.tickers.get(this.key)\n }\n\n toJSON() {\n return {base: this.base, quote: this.quote, key: this.key, created: this.created, refreshed: this.refreshed}\n }\n}\n\n/**\n * @typedef {{}} Signer - Account signing contract calls\n * @property {string} publicKey - Transaction source account\n * @property {SignTransactionCallback} signTransaction\n */\n","import {PRICE_SCALE} from './asset-pair.js'\n\n/**\n * Longest allowance lifetime the client grants, in ledgers: ~180 days at 5s per ledger, one hour (720 ledgers) short of\n * the network maximum entry TTL (3,110,400 ledgers).\n */\nexport const MAX_APPROVAL_TTL_LEDGERS = 3_109_680\n\n/** Default allowance lifetime granted with a trade, in ledgers (~180 days) */\nexport const APPROVAL_TTL_LEDGERS = MAX_APPROVAL_TTL_LEDGERS\n\n/** An allowance expiring within this number of ledgers is renewed with the next trade (~1 day) */\nexport const APPROVAL_RENEW_LEDGERS = 17_280\n\n/**\n * Decide whether a call needs an in-call approval and adjust it. The approval amount is absolute and one allowance backs\n * every order selling the token across all markets, so it has to cover this call plus every order selling the same asset\n * @param {ApprovalPlanParams} params\n * @return {{amount: bigint, liveUntil: number}|undefined} - Approval to pass with the call, undefined when the current allowance already covers it\n */\nexport function planApproval({required, committed, allowance, liveUntil, ledger, ttl = APPROVAL_TTL_LEDGERS}) {\n const target = required + committed\n const expiring = liveUntil > 0 && liveUntil < ledger + APPROVAL_RENEW_LEDGERS\n if (allowance >= target && !expiring)\n return undefined\n return {amount: target, liveUntil: ledger + Math.min(ttl, MAX_APPROVAL_TTL_LEDGERS)}\n}\n\n/**\n * Decide whether the allowance can be lowered once the open orders selling the token have been canceled or shrunk.\n * @param {ReductionPlanParams} params\n * @return {{amount: bigint, liveUntil: number}|undefined} - Approval to pass with the call, undefined when the allowance does not exceed the target\n */\nexport function planReduction({target, allowance, liveUntil = 0, ledger, ttl = APPROVAL_TTL_LEDGERS}) {\n if (liveUntil > 0 && liveUntil < ledger)\n return undefined //an expired allowance reads as zero\n if (allowance <= target)\n return undefined\n if (target <= 0n)\n return {amount: 0n, liveUntil: 0} //the token checks no lifetime for a zero amount\n //a nonzero approval must outlive the ledger it applies in: keep a lifetime that does, renew a short one\n if (liveUntil > ledger + APPROVAL_RENEW_LEDGERS)\n return {amount: target, liveUntil}\n return {amount: target, liveUntil: ledger + Math.min(ttl, MAX_APPROVAL_TTL_LEDGERS)}\n}\n\n/**\n * Max amount of `selling` tokens a buy trade may cost: `ceil(amount × price / 10^18)`\n * @param {bigint} amount - Amount of `buying` tokens to acquire\n * @param {bigint} price - Limit price (`selling` per 1 `buying`, with AXIS standard price decimals)\n * @return {bigint}\n */\nexport function maxQuoteSpend(amount, price) {\n if (amount <= 0n || price <= 0n)\n return 0n\n return (amount * price + PRICE_SCALE - 1n) / PRICE_SCALE\n}\n\n/**\n * @typedef {{}} ApprovalPlanParams\n * @property {bigint} required - Max amount of the selling asset the call may spend\n * @property {bigint} committed - Remaining amount of orders in the book selling the asset\n * @property {bigint} allowance - Current allowance (0 once expired)\n * @property {number} ledger - Current ledger sequence\n * @property {number} [liveUntil] - Ledger the current allowance lives until (0 or omitted when unknown)\n * @property {number} [ttl] - Lifetime of a new allowance in ledgers, {@link APPROVAL_TTL_LEDGERS} by default, at most\n * {@link MAX_APPROVAL_TTL_LEDGERS}\n */\n\n/**\n * @typedef {{}} ReductionPlanParams\n * @property {bigint} target - Amount the open orders selling the asset still need after the call\n * @property {bigint} allowance - Current allowance\n * @property {number} ledger - Current ledger sequence\n * @property {number} [liveUntil] - Ledger the current allowance lives until (0 or omitted when unknown)\n * @property {number} [ttl] - Lifetime of a renewed allowance in ledgers, {@link APPROVAL_TTL_LEDGERS} by default, at\n * most {@link MAX_APPROVAL_TTL_LEDGERS}\n */\n","import {Emitter} from './emitter.js'\r\nimport {pairKey, invertPrice} from './asset-pair.js'\r\nimport {parseApiDate} from './api-dates.js'\r\nimport {planApproval, planReduction, maxQuoteSpend, APPROVAL_TTL_LEDGERS} from './allowance.js'\r\nimport {OrderKind, TradeDirection} from './constants.js'\r\n\r\n/** Orders per `update` transaction */\r\nconst UPDATE_BATCH = 90\r\n/** Orders an approval takes the place of in an `update` batch: the token `approve` event is about twice the size of the\r\n * `mod` event of a removal, within the 16 KB of events a transaction may emit */\r\nconst APPROVAL_BATCH_WEIGHT = 2\r\n/** Time to wait for the account state before trading, in milliseconds */\r\nconst READY_TIMEOUT = 15_000\r\n/** How long an order created by this client counts as committed before the indexer reports it, in milliseconds */\r\nconst LOCAL_ORDER_TTL = 120_000\r\n/** How long an allowance set by this client overrides pushed records still showing the allowance it replaced, in\r\n * milliseconds: the indexer may reload an allowance only with its periodic sweep */\r\nconst APPROVAL_CONFIRM_TIMEOUT = 360_000\r\n\r\n/**\r\n * Trader wrapper that tracks every open order of an account across all markets and the account backing.\r\n * Create it with {@link import('./axis.js').Axis#account}.\r\n *\r\n * Emits:\r\n * - `ready` - the account state was loaded\r\n * - `new` {@link AccountOrder} - an order was created (confirmed by the indexer)\r\n * - `pending` {@link AccountOrder} - an order created by this client, not reported by the indexer yet\r\n * - `fill` {@link AccountFill} - an order was partially filled\r\n * - `filled` {@link AccountFill} - an order was filled in full\r\n * - `update` {@link AccountOrder} - an order changed (amount, price, expiration, revived)\r\n * - `cancel` {@link AccountOrder} - an order was removed by the owner\r\n * - `expire` {@link AccountOrder} - an order expired\r\n * - `remove` {@link AccountOrder} - an order left the open orders (after `filled`, `cancel`, `expire`)\r\n * - `order` `{action, order, fill?}` - any order change\r\n * - `backing` `{asset, backing}` - the balance, allowance or the backing split of the orders selling a token changed\r\n * - `approve` `{asset, amount, liveUntil}` - a call is about to set an allowance (grant, renew, lower or revoke it)\r\n * - `trade` {ApiTrade} - the account performed a trade\r\n * - `swap` {ApiSwap} - the account performed a swap\r\n * - `change` - the open orders or the backing changed\r\n * - `error` `Error` - the push API rejected the account subscription\r\n */\r\nexport class AxisAccount extends Emitter {\r\n /**\r\n * @param {Axis} axis\r\n * @param {string} address - Trader address\r\n * @param {{signTransaction?: SignTransactionCallback, approvalTtl?: number}} [options]\r\n */\r\n constructor(axis, address, {signTransaction, approvalTtl} = {}) {\r\n super()\r\n this.axis = axis\r\n this.address = address\r\n this.signTransaction = signTransaction\r\n this.approvalTtl = approvalTtl || APPROVAL_TTL_LEDGERS\r\n this.ready = new Promise(resolve => this.resolveReady = resolve)\r\n }\r\n\r\n /**\r\n * Trader address\r\n * @type {string}\r\n * @readonly\r\n */\r\n address\r\n /**\r\n * Wallet signing callback, required to trade\r\n * @type {SignTransactionCallback|undefined}\r\n */\r\n signTransaction\r\n /**\r\n * Lifetime of the allowances granted by trading calls, in ledgers\r\n * @type {number}\r\n */\r\n approvalTtl\r\n /**\r\n * Open orders by id\r\n * @type {Map<string, AccountOrder>}\r\n * @readonly\r\n */\r\n orders = new Map()\r\n /**\r\n * Account backing by token contract id\r\n * @type {Map<string, AccountBacking>}\r\n * @readonly\r\n */\r\n backing = new Map()\r\n /**\r\n * Resolves once the account state has been loaded\r\n * @type {Promise<void>}\r\n * @readonly\r\n */\r\n ready\r\n /**\r\n * Whether the account state has been loaded\r\n * @type {boolean}\r\n */\r\n loaded = false\r\n /**\r\n * Orders created by this client that the indexer has not reported yet\r\n * @type {Map<string, {order: AccountOrder, expires: number}>}\r\n * @private\r\n */\r\n local = new Map()\r\n /**\r\n * Whether the backing in memory get updated from the push API\r\n * @type {boolean}\r\n * @private\r\n */\r\n live = false\r\n /**\r\n * Last taker spend of this client by token, UNIX milliseconds\r\n * @type {Map<string, number>}\r\n * @private\r\n */\r\n spent = new Map() //TODO: drop this\r\n /**\r\n * Calls submitting transactions, run one at a time\r\n * @type {Promise<void>}\r\n * @private\r\n */\r\n queue = Promise.resolve()\r\n /**\r\n * Orders removed by this client that the indexer has not reported yet: expiration by order id, UNIX milliseconds\r\n * @type {Map<string, number>}\r\n * @private\r\n */\r\n removed = new Map()\r\n /**\r\n * Allowances set by this client that the pushed state may not reflect yet, by token contract id\r\n * @type {Map<string, {amount: bigint, liveUntil: number, replaced?: {allowance: bigint, liveUntil: number}, until: number}>}\r\n * @private\r\n */\r\n approved = new Map()\r\n /**\r\n * @type {function(): void}\r\n * @private\r\n */\r\n resolveReady\r\n\r\n /**\r\n * Start tracking this account\r\n * @internal\r\n */\r\n start() {\r\n const {stream} = this.axis\r\n this.unsubscribe = stream.subscribe('account', {address: this.address}, message => this.handle(message))\r\n this.offOpen = stream.on('open', () => this.stopFallback())\r\n this.offClose = stream.on('close', () => {\r\n this.live = false //changes are missed until the next snapshot\r\n this.startFallback()\r\n })\r\n //load over REST if the push API does not deliver the snapshot soon\r\n this.initTimer = setTimeout(() => {\r\n if (!this.loaded) {\r\n this.refresh().catch(() => this.startFallback())\r\n }\r\n }, 3_000)\r\n }\r\n\r\n /**\r\n * Stop tracking this account\r\n */\r\n close() {\r\n clearTimeout(this.initTimer)\r\n this.stopFallback()\r\n this.unsubscribe?.()\r\n this.offOpen?.()\r\n this.offClose?.()\r\n this.axis.releaseAccount(this)\r\n }\r\n\r\n /**\r\n * Reload current account state from the REST API\r\n * @return {Promise<void>}\r\n */\r\n async refresh() {\r\n //the REST state lists only the tokens of the orders once nobody subscribes: keep the other balances\r\n this.applySnapshot(await this.axis.api.getAccount(this.address), true)\r\n }\r\n\r\n /**\r\n * Retrieve open orders, newest first\r\n * @param {{market?: string|{base: string, quote: string}|string[], selling?: string, buying?: string}} [filter] - `market` is an {AxisMarket} or a pair of assets in any order\r\n * @return {AccountOrder[]}\r\n */\r\n getOrders({market, selling, buying} = {}) { //TODO: simplify market argument\r\n const key = toMarketKey(market)\r\n const res = []\r\n for (const order of this.allOrders()) {\r\n if (key && order.market !== key)\r\n continue\r\n if (selling && order.selling !== selling)\r\n continue\r\n if (buying && order.buying !== buying)\r\n continue\r\n res.push(order)\r\n }\r\n return res.sort(newestFirst)\r\n }\r\n\r\n /**\r\n * Get open order by id\r\n * @param {bigint|string} id\r\n * @return {AccountOrder|undefined}\r\n */\r\n getOrder(id) {\r\n const key = id.toString()\r\n if (this.isRemoved(key))\r\n return undefined\r\n return this.orders.get(key) ?? this.localOrders().find(order => order.id === key)\r\n }\r\n\r\n /**\r\n * Calculate the remaining amount of the open orders selling the token across every market (what the allowance must cover)\r\n * @param {string} asset - Token contract id\r\n * @return {bigint}\r\n */\r\n committed(asset) {\r\n let sum = 0n\r\n for (const order of this.allOrders()) {\r\n if (order.selling === asset) {\r\n sum += order.amount\r\n }\r\n }\r\n return sum\r\n }\r\n\r\n /**\r\n * Get spendable balance of the account in a token\r\n * @param {string} asset - Token contract id\r\n * @return {bigint|undefined} - Undefined if not tracked\r\n */\r\n getBalance(asset) {\r\n const backing = this.backing.get(asset)\r\n return backing?.updated ? backing.balance : undefined\r\n }\r\n\r\n /**\r\n * Get spendable balances in every tracked token by token contract id\r\n * @return {Map<string, bigint>}\r\n */\r\n get balances() {\r\n const res = new Map()\r\n for (const [asset, backing] of this.backing) {\r\n if (backing.updated) {\r\n res.set(asset, backing.balance)\r\n }\r\n }\r\n return res\r\n }\r\n\r\n /**\r\n * Whether the account exists on the ledger\r\n * @return {boolean|undefined}\r\n */\r\n get funded() {\r\n const backing = this.backing.get(this.axis.nativeAsset)\r\n return backing?.updated ? backing.authorized : undefined\r\n }\r\n\r\n /**\r\n * Get balance, allowance and commitments of the account in a token\r\n * @param {string} asset - Token contract id\r\n * @return {AccountAllowance}\r\n */\r\n getAllowance(asset) {\r\n const backing = this.backing.get(asset)\r\n const committed = this.committed(asset)\r\n if (!backing?.updated)\r\n return {asset, known: false, committed}\r\n return {\r\n asset,\r\n known: true,\r\n balance: backing.balance,\r\n allowance: backing.allowance,\r\n liveUntil: backing.liveUntil,\r\n authorized: backing.authorized,\r\n pending: backing.pending,\r\n available: backing.budget,\r\n committed\r\n }\r\n }\r\n\r\n /**\r\n * Sell tokens creating a limit remainder order if not executed in full\r\n * @param {TradeParams} params - `amount` of `selling` to sell; `price` is the minimum `buying` per 1 `selling`\r\n * @return {Promise<TradeResult>}\r\n */\r\n async sell(params) {\r\n return this.serialize(() => this.trade(TradeDirection.Sell, params))\r\n }\r\n\r\n /**\r\n * Buy tokens creating a limit remainder order if not executed in full\r\n * @param {TradeParams} params - `amount` of `buying` to acquire; `price` is the maximum `selling` per 1 `buying`\r\n * @return {Promise<TradeResult>}\r\n */\r\n async buy(params) {\r\n return this.serialize(() => this.trade(TradeDirection.Buy, params))\r\n }\r\n\r\n /**\r\n * Simulate a sell with the same crossing and approval as `sell`, without signing or submitting it\r\n * @param {TradeParams} params - Same as `sell`\r\n * @return {Promise<import('./index.js').TradeEstimate>} - Network fee and expected result\r\n */\r\n async estimateSell(params) {\r\n const {payload} = await this.prepareTrade(TradeDirection.Sell, params)\r\n const client = await this.client()\r\n return client.estimateSell(payload)\r\n }\r\n\r\n /**\r\n * Simulate a buy with the same crossing and approval as `buy`, without signing or submitting it\r\n * @param {TradeParams} params - Same as `buy`\r\n * @return {Promise<import('./index.js').TradeEstimate>} - Network fee and expected result\r\n */\r\n async estimateBuy(params) {\r\n const {payload} = await this.prepareTrade(TradeDirection.Buy, params)\r\n const client = await this.client()\r\n return client.estimateBuy(payload)\r\n }\r\n\r\n /**\r\n * Change the amount, price or expiration of open orders (omitted fields keep their current values). The allowance of\r\n * every sold token follows what its open orders need: raised when they grow, or when it does not back the changed\r\n * orders, lowered when they shrink\r\n * @param {Array<{id: bigint|string, amount?: bigint, price?: bigint, expires?: number}>} updates\r\n * @return {Promise<bigint[]>} - Updated order ids\r\n */\r\n async update(updates) {\r\n return this.serialize(async () => {\r\n await this.whenReady()\r\n const changes = updates.map(update => {\r\n const current = this.getOrder(update.id)\r\n if (!current && (update.amount === undefined || update.price === undefined))\r\n throw new Error(`Order ${update.id} is not an open order of ${this.address}`)\r\n return {\r\n current,\r\n update: {\r\n id: BigInt(update.id),\r\n amount: update.amount ?? current.amount,\r\n price: update.price ?? current.price,\r\n expires: update.expires ?? current?.expires ?? 0\r\n }\r\n }\r\n })\r\n return this.submitUpdates(changes, {grow: true})\r\n })\r\n }\r\n\r\n /**\r\n * Cancel open orders, lowering the allowance of every sold token to what its remaining open orders need\r\n * @param {Array<bigint|string>} ids\r\n * @return {Promise<void>}\r\n */\r\n async cancel(ids) {\r\n await this.serialize(() => this.removeOrders(ids))\r\n }\r\n\r\n /**\r\n * Cancel all open orders, lowering the allowances like `cancel`\r\n * @param {{market?: string|{base: string, quote: string}|string[]}} [filter]\r\n * @return {Promise<string[]>} - Canceled order ids\r\n */\r\n async cancelAll({market} = {}) {\r\n return this.serialize(async () => {\r\n await this.whenReady()\r\n const ids = this.getOrders({market}).map(order => order.id)\r\n if (ids.length) {\r\n await this.removeOrders(ids)\r\n }\r\n return ids\r\n })\r\n }\r\n\r\n /**\r\n * Set the allowances granted to the AXIS contract on tokens to zero, optionally canceling the open orders selling them\r\n * in the same transactions. The revocation goes with the first transaction. Works while the contract is frozen\r\n * @param {string[]} assets - Token contract ids\r\n * @param {{cancelOrders?: boolean}} [options] - Also cancel every open order selling these tokens\r\n * @return {Promise<AccountRevokeResult>}\r\n * @throws {Error} - The submission error, with the `revoked` tokens and the `canceled` order ids done before it\r\n */\r\n async revoke(assets, {cancelOrders = false} = {}) {\r\n return this.serialize(async () => {\r\n const tokens = [...new Set(assets)]\r\n let ids = []\r\n if (cancelOrders) {\r\n await this.whenReady()\r\n ids = [...this.allOrders()].filter(order => tokens.includes(order.selling)).map(order => order.id)\r\n }\r\n try {\r\n const canceled = await this.removeOrders(ids, tokens)\r\n return {revoked: tokens, canceled: canceled.map(id => id.toString())}\r\n } catch (e) {\r\n if (e instanceof Error) {\r\n e.revoked = e.progress?.batches > 0 ? tokens : []\r\n e.canceled = (e.progress?.updated ?? []).map(id => id.toString())\r\n }\r\n throw e\r\n }\r\n })\r\n }\r\n\r\n /**\r\n * Fill an open order against the book while keeping profits from price inefficiencies\r\n * @param {bigint|string} takerOrderId - Order acting as the taker\r\n * @param {Array<bigint|string>} [orders] - Counter orders, looked up automatically when omitted\r\n * @return {Promise<{sold: bigint, bought: bigint, surplus: bigint}>}\r\n */\r\n async crossfill(takerOrderId, orders) {\r\n return this.serialize(async () => {\r\n if (!orders) {\r\n const taker = this.getOrder(takerOrderId) ?? await this.axis.getOrder(takerOrderId)\r\n if (!taker)\r\n throw new Error(`Order ${takerOrderId} not found`)\r\n orders = (await this.findQuote(TradeDirection.Sell, taker.selling, taker.buying, taker.amount)).orders\r\n }\r\n const client = await this.client()\r\n const [sold, bought, surplus] = await client.crossfill(this.address, BigInt(takerOrderId), orders.map(id => BigInt(id)))\r\n return {sold, bought, surplus}\r\n })\r\n }\r\n\r\n /**\r\n * Swap across one or several markets along the best route found by the AXIS API\r\n * @param {SwapParams} params\r\n * @return {Promise<{sold: bigint, bought: bigint, approve?: import('./index.js').Approval}>}\r\n */\r\n async swap(params) {\r\n return this.serialize(() => this.trySwap(params))\r\n }\r\n\r\n /**\r\n * @param {SwapParams} params\r\n * @return {Promise<{sold: bigint, bought: bigint, approve?: import('./index.js').Approval}>}\r\n * @private\r\n */\r\n async trySwap({selling, buying, amount, direction = TradeDirection.Sell, slippage = 0}) {\r\n await this.whenReady()\r\n const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString()}\r\n const quote = direction === TradeDirection.Buy ?\r\n await this.axis.api.quoteBuy(params) :\r\n await this.axis.api.quoteSell(params)\r\n const best = quote.paths?.[0]\r\n if (quote.status !== 'success' || !best?.path?.length)\r\n throw new Error(quote.error || 'No route available')\r\n const path = best.path.map(hop => ({asset: hop.buying, orders: hop.orders.filter(Boolean).map(id => BigInt(id))}))\r\n const tolerance = BigInt(Math.round(slippage * 10_000))\r\n let sellingAmount = BigInt(best.sold)\r\n let buyingAmount = BigInt(best.bought)\r\n if (direction === TradeDirection.Buy) {\r\n sellingAmount = (sellingAmount * (10_000n + tolerance) + 9_999n) / 10_000n\r\n } else {\r\n buyingAmount = buyingAmount * (10_000n - tolerance) / 10_000n\r\n }\r\n //`sellingAmount` is the exact spend of a sell and the most a buy may spend\r\n const approve = await this.planApproval(selling, sellingAmount)\r\n if (approve) {\r\n this.emit('approve', {asset: selling, ...approve})\r\n }\r\n const client = await this.client()\r\n const [sold, bought] = await client.swap({\r\n direction,\r\n trader: this.address,\r\n selling,\r\n sellingAmount,\r\n buyingAmount,\r\n path,\r\n approve\r\n })\r\n this.spent.set(selling, Date.now())\r\n return {sold, bought, approve}\r\n }\r\n\r\n /**\r\n * Compute approval for a call\r\n * @param {string} asset - Token contract id\r\n * @param {bigint} required - Max amount the call may spend\r\n * @return {Promise<{amount: bigint, liveUntil: number}|undefined>}\r\n */\r\n async planApproval(asset, required) {\r\n await this.whenReady()\r\n const allowance = await this.readAllowance(asset) ?? 0n //unknown: a redundant approval, never a shortfall\r\n return planApproval({\r\n required,\r\n committed: this.committed(asset),\r\n allowance,\r\n liveUntil: this.backing.get(asset)?.liveUntil ?? 0,\r\n ledger: await this.axis.getLedger(),\r\n ttl: this.approvalTtl\r\n })\r\n }\r\n\r\n /**\r\n * Current allowance of a token: the pushed value while it can be trusted, otherwise read over RPC\r\n * @param {string} asset - Token contract id\r\n * @return {Promise<bigint|undefined>} - Undefined when the RPC read fails\r\n * @throws {Error} - If the token is not tracked and there is no RPC to read it from\r\n * @private\r\n */\r\n async readAllowance(asset) {\r\n const backing = this.backing.get(asset)\r\n if (this.isAllowanceCurrent(asset) || (backing?.updated && !this.axis.tokenBalances))\r\n return backing.allowance\r\n const {tokenBalances} = this.axis\r\n if (!tokenBalances)\r\n throw new Error(`The allowance of ${this.address} in ${asset} is not tracked: set the \\`rpcUrl\\` option to read it`)\r\n await this.axis.getContractId() //the allowance spender\r\n return tokenBalances.getAllowance(asset, this.address).catch(() => undefined)\r\n }\r\n\r\n /**\r\n * Check whether the pushed allowance of a token can be used as is\r\n * @param {string} asset - Token contract id\r\n * @return {boolean}\r\n * @private\r\n */\r\n isAllowanceCurrent(asset) {\r\n const backing = this.backing.get(asset)\r\n if (!this.live || !this.axis.stream.connected || !backing?.updated || backing.pending)\r\n return false\r\n if (this.pendingApproval(asset))\r\n return false //set by this client, not confirmed by the push yet\r\n const spent = this.spent.get(asset)\r\n if (spent === undefined)\r\n return true\r\n if (Date.now() - spent < 30_000) //the spend lowers the allowance before the push reporting it arrives\r\n return false //TODO: try to read allowance change from tx result meta changes\r\n this.spent.delete(asset)\r\n return true\r\n }\r\n\r\n /**\r\n * @param {number} direction\r\n * @param {TradeParams} params\r\n * @return {Promise<TradeResult>}\r\n * @private\r\n */\r\n async trade(direction, params) {\r\n const {payload, planned} = await this.prepareTrade(direction, params)\r\n const {selling, buying, amount, price, expires, approve} = payload\r\n if (planned && approve) {\r\n this.emit('approve', {asset: selling, ...approve})\r\n }\r\n const client = await this.client()\r\n const [sold, bought, createdId] = direction === TradeDirection.Buy ?\r\n await client.buy(payload) :\r\n await client.sell(payload)\r\n this.spent.set(selling, Date.now())\r\n let order\r\n if (createdId) {\r\n order = await this.trackCreated(createdId, {direction, selling, buying, amount, price, sold, bought, expires})\r\n }\r\n return {sold, bought, orderId: createdId ? createdId.toString() : undefined, order, approve}\r\n }\r\n\r\n /**\r\n * Resolve the crossing orders, the price of a market order and the approval of a trade\r\n * @param {number} direction\r\n * @param {TradeParams} params\r\n * @return {Promise<{payload: import('./index.js').TradeArguments, planned: boolean}>} - Contract call arguments,\r\n * `planned` if the approval was planned by the account rather than supplied\r\n * @private\r\n */\r\n async prepareTrade(direction, {selling, buying, amount, price, kind, expires, orders, approve}) {\r\n await this.whenReady()\r\n amount = BigInt(amount)\r\n const market = price === undefined || price === null\r\n if (kind === undefined) {\r\n kind = market ? OrderKind.Fill : OrderKind.Limit\r\n }\r\n let crossing\r\n if (!orders || market) {\r\n //a limit order crosses only the orders its price reaches (the contract threshold: the price of a buy, the\r\n //inverted price of a sell) and rests with the remainder, so a partial crossing is quoted as well\r\n const maxPrice = market ? undefined : direction === TradeDirection.Buy ? BigInt(price) : invertPrice(BigInt(price))\r\n crossing = await this.findQuote(direction, selling, buying, amount, maxPrice)\r\n }\r\n if (market) {\r\n //cross everything the quote found: the limit is the worst maker price (makers price `selling` per\r\n //`buying` of a buyer; seen from a seller, invert it)\r\n if (!crossing.worstPrice)\r\n throw new Error('Not enough liquidity for a market order')\r\n price = direction === TradeDirection.Buy ? crossing.worstPrice : invertPrice(crossing.worstPrice)\r\n }\r\n price = BigInt(price)\r\n const planned = approve === undefined\r\n if (planned) {\r\n const required = direction === TradeDirection.Buy ? maxQuoteSpend(amount, price) : amount\r\n approve = await this.planApproval(selling, required)\r\n }\r\n const payload = {\r\n kind,\r\n trader: this.address,\r\n amount,\r\n selling,\r\n buying,\r\n price,\r\n orders: (orders ?? crossing.orders).map(id => BigInt(id)),\r\n expires,\r\n approve: approve || undefined\r\n }\r\n return {payload, planned}\r\n }\r\n\r\n /**\r\n * Count an order this client created as committed until the indexer reports it\r\n * @param {bigint} id\r\n * @param {{}} trade - Trade parameters and result, for an estimate if the order cannot be read\r\n * @return {Promise<AccountOrder|undefined>}\r\n * @private\r\n */\r\n async trackCreated(id, {direction, selling, buying, amount, price, sold, bought, expires}) {\r\n const key = id.toString()\r\n if (this.orders.has(key))\r\n return this.orders.get(key) //already reported\r\n let stored\r\n try {\r\n const client = await this.client()\r\n stored = await client.order(id)\r\n } catch (e) {\r\n //estimate below\r\n }\r\n if (this.orders.has(key))\r\n return this.orders.get(key)\r\n let orderAmount\r\n let orderPrice\r\n if (stored) {\r\n orderAmount = stored.amount\r\n orderPrice = stored.price\r\n } else if (direction === TradeDirection.Sell) {\r\n orderAmount = amount - sold\r\n orderPrice = price\r\n } else {\r\n //the remainder of a buy sells `selling` for the rest of `buying` at the limit\r\n orderAmount = maxQuoteSpend(amount - bought, price)\r\n orderPrice = invertPrice(price)\r\n }\r\n const now = Date.now()\r\n /** @type {AccountOrder} */\r\n const order = {\r\n id: key,\r\n owner: this.address,\r\n selling,\r\n buying,\r\n market: pairKey(selling, buying),\r\n status: 'ACTIVE',\r\n price: orderPrice,\r\n amount: orderAmount,\r\n quote: orderAmount,\r\n expires: Number(stored?.expires ?? expires ?? 0),\r\n created: now,\r\n updated: now,\r\n cursor: undefined,\r\n backed: null,\r\n backedPct: null,\r\n backingPending: true,\r\n filledPct: 0,\r\n pending: true\r\n }\r\n this.local.set(key, {order, expires: now + LOCAL_ORDER_TTL})\r\n this.emit('pending', order)\r\n this.emit('change')\r\n return order\r\n }\r\n\r\n /**\r\n * Crossing orders of a direct-market trade and the worst price among them\r\n * @param {number} direction\r\n * @param {string} selling\r\n * @param {string} buying\r\n * @param {bigint} amount - `selling` amount of a sell, `buying` amount of a buy\r\n * @param {bigint} [maxPrice] - Highest maker price to cross, for a limit order\r\n * @return {Promise<{orders: string[], worstPrice: bigint|null}>}\r\n * @private\r\n */\r\n async findQuote(direction, selling, buying, amount, maxPrice) {\r\n const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString(), direct: true, maxPrice}\r\n try {\r\n const quote = direction === TradeDirection.Buy ?\r\n await this.axis.api.quoteBuy(params) :\r\n await this.axis.api.quoteSell(params)\r\n const hop = quote.status === 'success' ? quote.paths?.[0]?.path?.[0] : null\r\n if (hop)\r\n return {orders: hop.orders ?? [], worstPrice: hop.worstPrice ? BigInt(hop.worstPrice) : null}\r\n } catch (e) {\r\n //nothing to cross: a limit order simply rests\r\n }\r\n return {orders: [], worstPrice: null}\r\n }\r\n\r\n /**\r\n * Run calls submitting transactions one at a time: each one reads the sequence number and plans its approvals only\r\n * after the previous one settled, so concurrent calls neither collide on the sequence number nor overwrite each\r\n * other's approvals\r\n * @template T\r\n * @param {function(): Promise<T>} call\r\n * @return {Promise<T>}\r\n * @private\r\n */\r\n serialize(call) {\r\n const result = this.queue.then(call)\r\n this.queue = result.then(() => undefined, () => undefined)\r\n return result\r\n }\r\n\r\n /**\r\n * Remove orders, lowering the allowances to what the remaining orders need\r\n * @param {Array<bigint|string>} ids\r\n * @param {string[]} [revoke] - Tokens to revoke the allowance on with the first transaction\r\n * @return {Promise<bigint[]>} - Removed order ids\r\n * @private\r\n */\r\n removeOrders(ids, revoke) {\r\n const changes = ids.map(id => ({current: this.getOrder(id), update: {id: BigInt(id), amount: 0n, price: 0n, expires: 0}}))\r\n return this.submitUpdates(changes, {revoke})\r\n }\r\n\r\n /**\r\n * Send order changes in `update` batches. Each batch carries the approvals that keep the allowance of every token it\r\n * changes at what the open orders selling it need once the batch applies: raised when they grow (`grow` only), or\r\n * when the allowance does not back the changed orders, lowered when they shrink. The `revoke` tokens are set to zero\r\n * with the first batch\r\n * @param {Array<{current?: AccountOrder, update: OrderUpdate}>} changes - New values per order, with the order in\r\n * memory when known\r\n * @param {{grow?: boolean, revoke?: string[]}} [options] - `grow`: allowances may be raised (updates, never cancels)\r\n * @return {Promise<bigint[]>} - Updated or removed order ids\r\n * @throws {Error} - The submission error, with `progress` `{updated, batches}` done before it\r\n * @private\r\n */\r\n async submitUpdates(changes, {grow = false, revoke = []} = {}) {\r\n const batches = splitBatches(changes, revoke)\r\n if (!batches.length)\r\n return []\r\n const plan = await this.snapshotAllowances(changes, revoke, grow)\r\n const client = await this.client()\r\n const ids = []\r\n for (let i = 0; i < batches.length; i++) {\r\n const batch = batches[i]\r\n const approvals = i === 0 ? revoke.map(asset => ({asset, amount: 0n, liveUntil: 0})) : []\r\n if (plan) {\r\n approvals.push(...planBatch(plan, batch, grow))\r\n }\r\n for (const approval of approvals) {\r\n this.emit('approve', approval)\r\n }\r\n try {\r\n ids.push(...await client.update({trader: this.address, updates: batch.map(change => change.update), approvals}))\r\n } catch (e) {\r\n if (e instanceof Error) {\r\n e.progress = {updated: ids, batches: i}\r\n }\r\n throw e\r\n }\r\n this.applyBatch(batch, approvals)\r\n }\r\n return ids\r\n }\r\n\r\n /**\r\n * Committed amounts and allowances of the tokens the changed orders sell, read once before the first batch: every\r\n * batch target derives from them, as pushes arriving between batches already drop the removed orders\r\n * @param {Array<{current?: AccountOrder}>} changes\r\n * @param {string[]} revoke - Tokens revoked anyway\r\n * @param {boolean} grow - Whether allowances may be raised: a failed read throws then, otherwise nothing is planned\r\n * @return {Promise<AllowancePlan|null>} - Null when no allowance is planned\r\n * @private\r\n */\r\n async snapshotAllowances(changes, revoke, grow) {\r\n const assets = new Set()\r\n for (const {current} of changes) {\r\n if (current && !revoke.includes(current.selling)) {\r\n assets.add(current.selling)\r\n }\r\n }\r\n if (!assets.size || !this.loaded)\r\n return null\r\n try {\r\n const ledger = await this.axis.getLedger()\r\n const tokens = new Map()\r\n for (const asset of assets) {\r\n const liveUntil = this.backing.get(asset)?.liveUntil ?? 0\r\n let allowance = await this.readAllowance(asset)\r\n if (allowance !== undefined && liveUntil > 0 && liveUntil < ledger) {\r\n allowance = 0n //an expired allowance reads as zero\r\n }\r\n tokens.set(asset, {committed: this.committed(asset), allowance, liveUntil, change: 0n})\r\n }\r\n return {ledger, ttl: this.approvalTtl, tokens}\r\n } catch (e) {\r\n if (grow)\r\n throw e\r\n return null //a cancel goes through without lowering the allowances\r\n }\r\n }\r\n\r\n /**\r\n * Reflect a confirmed `update` batch before the indexer reports it: removed orders leave the open orders, changed\r\n * ones take their new values, approved allowances replace the pushed ones\r\n * @param {Array<{current?: AccountOrder, update: OrderUpdate}>} batch\r\n * @param {import('./index.js').Approval[]} approvals\r\n * @private\r\n */\r\n applyBatch(batch, approvals) {\r\n const until = Date.now() + LOCAL_ORDER_TTL\r\n for (const {current, update} of batch) {\r\n const key = update.id.toString()\r\n if (update.amount === 0n) {\r\n this.local.delete(key)\r\n if (this.orders.has(key)) {\r\n this.removed.set(key, until)\r\n }\r\n } else if (current) {\r\n Object.assign(current, {amount: update.amount, price: update.price, expires: Number(update.expires)})\r\n }\r\n }\r\n for (const {asset, amount, liveUntil} of approvals) {\r\n const backing = this.backing.get(asset)\r\n this.approved.set(asset, {\r\n amount,\r\n liveUntil,\r\n replaced: backing && {allowance: backing.allowance, liveUntil: backing.liveUntil},\r\n until: Date.now() + APPROVAL_CONFIRM_TIMEOUT\r\n })\r\n if (backing) {\r\n const updated = withAllowance(backing, amount, liveUntil)\r\n this.backing.set(asset, updated)\r\n this.emit('backing', {asset, backing: updated})\r\n }\r\n }\r\n this.emit('change')\r\n }\r\n\r\n /**\r\n * Keep an allowance this client set over an incoming record that still shows the allowance it replaced\r\n * @param {string} asset\r\n * @param {AccountBacking} backing - Incoming record\r\n * @return {AccountBacking}\r\n * @private\r\n */\r\n reconcileBacking(asset, backing) {\r\n const expected = this.pendingApproval(asset)\r\n if (!expected)\r\n return backing\r\n const {replaced} = expected\r\n if (replaced && backing.allowance === replaced.allowance && backing.liveUntil === replaced.liveUntil)\r\n return withAllowance(backing, expected.amount, expected.liveUntil)\r\n this.approved.delete(asset) //the record shows the approval, or a later change\r\n return backing\r\n }\r\n\r\n /**\r\n * Allowance set by this client that the pushed state did not confirm yet\r\n * @param {string} asset\r\n * @return {{amount: bigint, liveUntil: number, replaced?: {allowance: bigint, liveUntil: number}}|undefined}\r\n * @private\r\n */\r\n pendingApproval(asset) {\r\n const expected = this.approved.get(asset)\r\n if (expected && expected.until < Date.now()) {\r\n this.approved.delete(asset)\r\n return undefined\r\n }\r\n return expected\r\n }\r\n\r\n /**\r\n * Whether an order was removed by this client and the indexer has not reported it yet\r\n * @param {string} id\r\n * @return {boolean}\r\n * @private\r\n */\r\n isRemoved(id) {\r\n const until = this.removed.get(id)\r\n if (until === undefined)\r\n return false\r\n if (until < Date.now()) {\r\n this.removed.delete(id)\r\n return false\r\n }\r\n return true\r\n }\r\n\r\n /**\r\n * @return {Promise<AxisContractClient>}\r\n * @private\r\n */\r\n async client() {\r\n if (!this.signTransaction)\r\n throw new Error(`No signTransaction callback for ${this.address}: pass it to axis.account()`)\r\n return this.axis.contractClient({publicKey: this.address, signTransaction: this.signTransaction})\r\n }\r\n\r\n /**\r\n * @param {number} [timeout]\r\n * @return {Promise<void>}\r\n * @private\r\n */\r\n async whenReady(timeout = READY_TIMEOUT) {\r\n if (this.loaded)\r\n return\r\n let timer\r\n try {\r\n await Promise.race([\r\n this.ready,\r\n new Promise((resolve, reject) => {\r\n timer = setTimeout(() => reject(new Error('The account state is not available: check the AXIS API connection')), timeout)\r\n })\r\n ])\r\n } finally {\r\n clearTimeout(timer)\r\n }\r\n }\r\n\r\n /**\r\n * @param {StreamMessage} message\r\n * @private\r\n */\r\n handle(message) {\r\n switch (message.type) {\r\n case 'account':\r\n this.live = true\r\n return this.applySnapshot(message)\r\n case 'order':\r\n return this.applyOrder(message)\r\n case 'backing':\r\n return this.applyBacking(message)\r\n case 'trade':\r\n return this.emit('trade', message.trade)\r\n case 'swap':\r\n return this.emit('swap', message.swap)\r\n case 'error':\r\n return this.emit('error', new Error(message.error))\r\n }\r\n }\r\n\r\n /**\r\n * Replace the state with a snapshot\r\n * @param {ApiAccount} state\r\n * @param {boolean} [mergeBacking] - Keep the tokens missing from the snapshot\r\n * @private\r\n */\r\n applySnapshot(state, mergeBacking = false) {\r\n const previous = this.orders\r\n const next = new Map()\r\n for (const raw of state.orders || []) {\r\n const order = parseApiOrder(raw)\r\n next.set(order.id, order)\r\n this.local.delete(order.id)\r\n }\r\n this.orders = next\r\n for (const id of this.removed.keys()) {\r\n if (!next.has(id)) {\r\n this.removed.delete(id)\r\n }\r\n }\r\n const backing = mergeBacking ? new Map(this.backing) : new Map()\r\n for (const [asset, raw] of Object.entries(state.backing || {})) {\r\n backing.set(asset, this.reconcileBacking(asset, parseBacking(asset, raw)))\r\n }\r\n this.backing = backing\r\n if (this.loaded) {\r\n for (const [id, order] of previous) {\r\n if (!next.has(id)) {\r\n this.emit('remove', order)\r\n }\r\n }\r\n for (const [id, order] of next) {\r\n if (!previous.has(id)) {\r\n this.emit('new', order)\r\n }\r\n }\r\n }\r\n if (!this.loaded) {\r\n this.loaded = true\r\n this.resolveReady()\r\n this.emit('ready')\r\n }\r\n this.emit('change')\r\n }\r\n\r\n /**\r\n * @param {{action: string, order: import('./api-client.js').ApiOrder, fill?: {}}} message\r\n * @private\r\n */\r\n applyOrder({action, order: raw, fill: rawFill}) {\r\n const order = parseApiOrder(raw)\r\n this.local.delete(order.id)\r\n const previous = this.orders.get(order.id)\r\n const removed = action === 'filled' || action === 'cancel' || action === 'expire'\r\n if (removed) {\r\n this.orders.delete(order.id)\r\n this.removed.delete(order.id)\r\n } else {\r\n if (previous && order.backed === null) {\r\n //the event serialization may lack the split; keep the last known one until the backing update\r\n order.backed = previous.backed\r\n order.backedPct = previous.backedPct\r\n order.backingPending = previous.backingPending\r\n }\r\n this.orders.set(order.id, order)\r\n }\r\n const fill = rawFill && {\r\n order,\r\n sold: BigInt(rawFill.sold),\r\n bought: BigInt(rawFill.bought),\r\n taker: rawFill.taker,\r\n trade: rawFill.trade?.toString(),\r\n ts: Number(rawFill.ts) * 1000,\r\n partial: action === 'fill'\r\n }\r\n this.emit(action, fill || order)\r\n if (removed) {\r\n this.emit('remove', order)\r\n }\r\n this.emit('order', {action, order, fill})\r\n this.emit('change')\r\n }\r\n\r\n /**\r\n * @param {{asset: string, backing: import('./api-client.js').ApiBacking|null, backed?: Object<string, string>}} message\r\n * @private\r\n */\r\n applyBacking({asset, backing: raw, backed}) {\r\n const backing = raw ? this.reconcileBacking(asset, parseBacking(asset, raw)) : undefined\r\n if (backing) {\r\n this.backing.set(asset, backing)\r\n } else {\r\n this.backing.delete(asset)\r\n }\r\n for (const [id, amount] of Object.entries(backed || {})) {\r\n const order = this.orders.get(id)\r\n if (!order)\r\n continue\r\n order.backed = BigInt(amount)\r\n order.backedPct = share(order.backed, order.amount)\r\n order.backingPending = !backing || backing.pending || !backing.updated\r\n }\r\n this.emit('backing', {asset, backing})\r\n this.emit('change')\r\n }\r\n\r\n /**\r\n * @return {Iterable<AccountOrder>}\r\n * @private\r\n */\r\n * allOrders() {\r\n for (const order of this.orders.values()) {\r\n if (!this.isRemoved(order.id)) {\r\n yield order\r\n }\r\n }\r\n yield* this.localOrders()\r\n }\r\n\r\n /**\r\n * Get local orders that haven't expired\r\n * @return {AccountOrder[]}\r\n * @private\r\n */\r\n localOrders() {\r\n const now = Date.now()\r\n const res = []\r\n for (const [id, {order, expires}] of this.local) {\r\n if (expires < now || this.orders.has(id)) {\r\n this.local.delete(id)\r\n } else {\r\n res.push(order)\r\n }\r\n }\r\n return res\r\n }\r\n\r\n /**\r\n * @private\r\n */\r\n startFallback() {\r\n if (this.fallbackTimer)\r\n return\r\n this.fallbackTimer = setInterval(() => {\r\n this.refresh().catch(() => {\r\n //retried on the next tick\r\n })\r\n }, this.axis.fallbackPollInterval)\r\n }\r\n\r\n /**\r\n * @private\r\n */\r\n stopFallback() {\r\n clearInterval(this.fallbackTimer)\r\n this.fallbackTimer = undefined\r\n }\r\n}\r\n\r\n/**\r\n * Convert an API order to the client form (bigint amounts and prices, numeric timestamps)\r\n * @param {ApiOrder} raw\r\n * @return {AccountOrder}\r\n */\r\nexport function parseApiOrder(raw) {\r\n const amount = BigInt(raw.amount)\r\n const quote = BigInt(raw.quote ?? raw.amount)\r\n //unconfirmed until loaded, and while a reload confirming the latest event is due\r\n const confirmed = raw.backed !== undefined && !!raw.backing?.updated && !raw.backing?.pending\r\n const backed = raw.backed !== undefined ? BigInt(raw.backed) : null\r\n return {\r\n id: raw.id,\r\n owner: raw.owner,\r\n selling: raw.selling,\r\n buying: raw.buying,\r\n market: pairKey(raw.selling, raw.buying),\r\n status: raw.status,\r\n price: BigInt(raw.price),\r\n amount,\r\n quote,\r\n expires: raw.expires ? Math.floor(parseApiDate(raw.expires) / 1000) : 0,\r\n created: parseApiDate(raw.created),\r\n updated: parseApiDate(raw.updated),\r\n cursor: raw.cursor !== undefined ? BigInt(raw.cursor) : undefined,\r\n backed,\r\n backedPct: backed === null ? null : share(backed, amount),\r\n backingPending: !confirmed,\r\n filledPct: quote > 0n ? Math.max(0, Math.min(1, 1 - Number(amount * 10_000n / quote) / 10_000)) : 0,\r\n pending: false\r\n }\r\n}\r\n\r\n/**\r\n * @param {string} asset\r\n * @param {ApiBacking} raw\r\n * @return {AccountBacking}\r\n */\r\nfunction parseBacking(asset, raw) {\r\n return {\r\n asset,\r\n balance: BigInt(raw.balance),\r\n allowance: BigInt(raw.allowance),\r\n liveUntil: raw.liveUntil || 0,\r\n authorized: raw.authorized !== false,\r\n budget: BigInt(raw.budget ?? 0),\r\n updated: parseApiDate(raw.updated),\r\n skipped: parseApiDate(raw.skipped),\r\n pending: raw.pending === true\r\n }\r\n}\r\n\r\n/**\r\n * @param {bigint} part\r\n * @param {bigint} total\r\n * @return {number} - 0..1\r\n */\r\nfunction share(part, total) {\r\n if (total <= 0n)\r\n return 1\r\n return Math.max(0, Math.min(1, Number(part * 10_000n / total) / 10_000))\r\n}\r\n\r\n/**\r\n * Split order changes into `update` batches, leaving event room for the approvals a batch may carry\r\n * @param {Array<{current?: AccountOrder, update: OrderUpdate}>} changes\r\n * @param {string[]} revoke - Tokens revoked with the first batch\r\n * @return {Array<Array<{current?: AccountOrder, update: OrderUpdate}>>}\r\n */\r\nfunction splitBatches(changes, revoke) {\r\n const batches = []\r\n let batch\r\n let tokens\r\n for (const change of changes) {\r\n const asset = change.current?.selling\r\n if (batch) {\r\n const approvals = tokens.size + (asset && !tokens.has(asset) ? 1 : 0)\r\n if (batch.length + 1 + APPROVAL_BATCH_WEIGHT * approvals > UPDATE_BATCH) {\r\n batch = undefined\r\n }\r\n }\r\n if (!batch) {\r\n batch = []\r\n tokens = new Set(batches.length ? [] : revoke)\r\n batches.push(batch)\r\n }\r\n batch.push(change)\r\n if (asset) {\r\n tokens.add(asset)\r\n }\r\n }\r\n if (!batches.length && revoke.length) {\r\n batches.push([]) //a revocation alone\r\n }\r\n return batches\r\n}\r\n\r\n/**\r\n * Approvals of one `update` batch, advancing the planned allowances: an allowance grows only when the batch\r\n * grows the orders selling the token, or when it does not back the changed orders (the contract checks that), and\r\n * lowered when the batch shrinks them\r\n * @param {AllowancePlan} plan\r\n * @param {Array<{current?: AccountOrder, update: OrderUpdate}>} batch\r\n * @param {boolean} grow - Whether allowances may be raised\r\n * @return {import('./index.js').Approval[]}\r\n */\r\nfunction planBatch({ledger, ttl, tokens}, batch, grow) {\r\n //change of the committed amount and the new amounts of the changed orders, per sold token\r\n const changed = new Map()\r\n for (const {current, update} of batch) {\r\n if (!current || !tokens.has(current.selling))\r\n continue\r\n const entry = changed.get(current.selling) ?? {delta: 0n, need: 0n}\r\n entry.delta += update.amount - current.amount\r\n entry.need += update.amount\r\n changed.set(current.selling, entry)\r\n }\r\n const approvals = []\r\n for (const [asset, {delta, need}] of changed) {\r\n const token = tokens.get(asset)\r\n token.change += delta\r\n let approval\r\n if (grow && (delta > 0n || (token.allowance ?? 0n) < need)) {\r\n //unknown: a redundant approval, never a shortfall\r\n approval = planApproval({required: token.change, committed: token.committed, allowance: token.allowance ?? 0n, liveUntil: token.liveUntil, ledger, ttl})\r\n } else if (delta < 0n && token.allowance !== undefined) {\r\n approval = planReduction({target: token.committed + token.change, allowance: token.allowance, liveUntil: token.liveUntil, ledger, ttl})\r\n }\r\n if (approval) {\r\n approvals.push({asset, ...approval})\r\n token.allowance = approval.amount\r\n token.liveUntil = approval.liveUntil\r\n }\r\n }\r\n return approvals\r\n}\r\n\r\n/**\r\n * @param {AccountBacking} backing\r\n * @param {bigint} allowance\r\n * @param {number} liveUntil\r\n * @return {AccountBacking} - The record with another allowance\r\n */\r\nfunction withAllowance(backing, allowance, liveUntil) {\r\n const budget = !backing.authorized ? 0n : backing.balance < allowance ? backing.balance : allowance\r\n return {...backing, allowance, liveUntil, budget}\r\n}\r\n\r\n/**\r\n * @param {string|{base: string, quote: string}|string[]|undefined} market\r\n * @return {string|undefined}\r\n */\r\nfunction toMarketKey(market) {\r\n if (!market)\r\n return undefined\r\n if (typeof market === 'string') {\r\n const [x, y] = market.split('/')\r\n return pairKey(x, y)\r\n }\r\n if (Array.isArray(market))\r\n return pairKey(market[0], market[1])\r\n return pairKey(market.base, market.quote)\r\n}\r\n\r\n/**\r\n * Newest first: unconfirmed local orders, then by creation position\r\n * @param {AccountOrder} x\r\n * @param {AccountOrder} y\r\n * @return {number}\r\n */\r\nfunction newestFirst(x, y) {\r\n if (x.cursor === undefined || y.cursor === undefined)\r\n return (x.cursor === undefined ? 0 : 1) - (y.cursor === undefined ? 0 : 1) || y.created - x.created\r\n return x.cursor < y.cursor ? 1 : x.cursor > y.cursor ? -1 : 0\r\n}\r\n\r\n/**\r\n * @typedef {{}} AccountOrder - Open order of a tracked account\r\n * @property {string} id - Order id (decimal u128)\r\n * @property {string} owner - Maker address\r\n * @property {string} selling - Sold token\r\n * @property {string} buying - Bought token\r\n * @property {string} market - Market key\r\n * @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Current status\r\n * @property {bigint} price - `buying` per 1 `selling`, contract scale (18 decimals)\r\n * @property {bigint} amount - Amount of `selling` left\r\n * @property {bigint} quote - Amount of `selling` at creation\r\n * @property {number} expires - Expiration UNIX timestamp in seconds, 0 = none\r\n * @property {number} created - Creation time, UNIX milliseconds\r\n * @property {number} updated - Last change, UNIX milliseconds\r\n * @property {bigint} [cursor] - Paging cursor (undefined for unconfirmed local orders)\r\n * @property {bigint|null} backed - Share of the account budget in `selling` that backs the order\r\n * @property {number|null} backedPct - `backed / amount` (0..1), null when unknown\r\n * @property {boolean} backingPending - The backing is not confirmed yet\r\n * @property {number} filledPct - Filled share of the initial amount (0..1)\r\n * @property {boolean} pending - Created by this client, not reported by the indexer yet\r\n */\r\n\r\n/**\r\n * @typedef {{}} AccountBacking - Balance and allowance of the account in a token, as tracked by the indexer\r\n * @property {string} asset\r\n * @property {bigint} balance - Spendable amount (balance minus reserve and liabilities)\r\n * @property {bigint} allowance - Allowance granted to the AXIS contract\r\n * @property {number} liveUntil - Ledger sequence the allowance lives until\r\n * @property {boolean} authorized - Whether the account can send and receive the token\r\n * @property {bigint} budget - min(balance, allowance), 0 when unauthorized or expired\r\n * @property {number} updated - Last load, UNIX milliseconds (0 = not loaded)\r\n * @property {number} skipped - Last skipped fill of an order selling the token, UNIX milliseconds (0 = none)\r\n * @property {boolean} pending - A reload confirming the latest change is due\r\n */\r\n\r\n/**\r\n * @typedef {{}} AccountAllowance\r\n * @property {string} asset\r\n * @property {boolean} known - Whether the backing is tracked and loaded\r\n * @property {bigint} [balance]\r\n * @property {bigint} [allowance]\r\n * @property {number} [liveUntil]\r\n * @property {boolean} [authorized]\r\n * @property {boolean} [pending]\r\n * @property {bigint} [available] - min(balance, allowance)\r\n * @property {bigint} committed - Remaining amount of the open orders selling the token\r\n */\r\n\r\n/**\r\n * @typedef {{}} AccountFill\r\n * @property {AccountOrder} order - Order after the fill\r\n * @property {bigint} sold - Amount of `selling` delivered\r\n * @property {bigint} bought - Amount of `buying` received\r\n * @property {string} taker - Taker address\r\n * @property {string} trade - Trade id\r\n * @property {number} ts - Trade time, UNIX milliseconds\r\n * @property {boolean} partial - Whether the order is still open\r\n */\r\n\r\n/**\r\n * @typedef {{}} TradeParams\r\n * @property {string} selling - Token sent\r\n * @property {string} buying - Token received\r\n * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)\r\n * @property {bigint|string} [price] - Limit price, contract scale; omitted for a market order\r\n * @property {number} [kind] - {@link OrderKind}: `Limit` by default, `Fill` for a market order\r\n * @property {number} [expires] - Expiration UNIX timestamp (seconds) of the resting remainder\r\n * @property {Array<bigint|string>} [orders] - Counter orders to cross, looked up automatically when omitted\r\n * @property {Approval|null} [approve] - Explicit approval (`null` for none)\r\n */\r\n\r\n/**\r\n * @typedef {{}} TradeResult\r\n * @property {bigint} sold - Amount of `selling` sent\r\n * @property {bigint} bought - Amount of `buying` received\r\n * @property {string} [orderId] - ID of the order created for a limit remainder\r\n * @property {AccountOrder} [order] - The created order (unconfirmed until the indexer reports it)\r\n * @property {Approval} [approve] - Approval granted with the trade\r\n */\r\n\r\n/**\r\n * @typedef {{}} AccountRevokeResult\r\n * @property {string[]} revoked - Tokens whose allowance was set to zero\r\n * @property {string[]} canceled - Canceled order ids\r\n */\r\n\r\n/**\r\n * @typedef {{}} AllowancePlan - Allowances planned across the `update` batches of a call\r\n * @property {number} ledger - Current ledger sequence\r\n * @property {number} ttl - Lifetime of a new allowance, in ledgers\r\n * @property {Map<string, {committed: bigint, allowance?: bigint, liveUntil: number, change: bigint}>} tokens - Open amount before the call, the current allowance (undefined when unknown) and the committed change of the batches planned so far for each sold token\r\n */\r\n\r\n/**\r\n * @typedef {import('./index.js').OrderUpdate} OrderUpdate\r\n */\r\n\r\n/**\r\n * @typedef {{}} SwapParams\r\n * @property {string} selling - Token sent\r\n * @property {string} buying - Token received\r\n * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)\r\n * @property {number} [direction] - {@link TradeDirection}, `Sell` by default\r\n * @property {number} [slippage] - Price tolerance as a fraction (0.005 = 0.5%), 0 by default\r\n */\r\n","import {Asset, Networks} from '@stellar/stellar-sdk'\r\nimport {Emitter} from './emitter.js'\r\nimport {AxisApiClient, AxisApiError} from './api-client.js'\r\nimport {AxisStreamClient} from './stream-client.js'\r\nimport {TokenBalance} from './token-balance.js'\r\nimport {AxisMarket} from './axis-market.js'\r\nimport {AxisAccount, parseApiOrder} from './axis-account.js'\r\nimport {pairKey} from './asset-pair.js'\r\nimport {parseApiDate} from './api-dates.js'\r\nimport {AxisContractClient} from './index.js'\r\n\r\n/** Max stale ledger threshold, in ms */\r\nconst LEDGER_STALE_THRESHOLD = 60_000\r\n\r\n/**\r\n * High-level AXIS DEX state\r\n *\r\n * Emits:\r\n * - `change` - anything in the contract state changed\r\n * - `frozen` `boolean` - the frozen state toggled\r\n * - `config` {ContractInfoConfig} - contract configuration changed\r\n * - `market` `{market: AxisMarket, created: boolean}` - a market was opened or updated\r\n * - `connection` `boolean` - WebSocket push connection opened or dropped\r\n * - `ledger` `number` - new ledger processed by the indexer\r\n */\r\nexport class Axis extends Emitter {\r\n /**\r\n * @param {AxisOptions} options\r\n */\r\n constructor({apiUrl, wsUrl, rpcUrl, contractId, networkPassphrase = Networks.PUBLIC, fee, signer, WebSocket, fallbackPollInterval = 15_000}) {\r\n super()\r\n this.api = new AxisApiClient(apiUrl)\r\n this.stream = new AxisStreamClient(wsUrl || toWsUrl(this.api.serverUrl), {WebSocket})\r\n this.rpcUrl = rpcUrl\r\n this.contractId = contractId\r\n this.networkPassphrase = networkPassphrase\r\n this.fee = fee\r\n this.signer = signer\r\n this.fallbackPollInterval = fallbackPollInterval\r\n this.tokenBalances = rpcUrl ? new TokenBalance({rpcUrl, networkPassphrase, spender: contractId}) : undefined\r\n this.nativeAsset = Asset.native().contractId(networkPassphrase)\r\n this.stream.on('open', () => {\r\n this.stopFallback()\r\n this.emit('connection', true)\r\n })\r\n this.stream.on('close', () => {\r\n this.startFallback()\r\n this.emit('connection', false)\r\n })\r\n }\r\n\r\n /**\r\n * AXIS REST API client\r\n * @type {AxisApiClient}\r\n * @readonly\r\n */\r\n api\r\n /**\r\n * AXIS contract address\r\n * @type {string|undefined}\r\n * @readonly\r\n */\r\n contractId\r\n /**\r\n * AXIS API WebSocket client\r\n * @type {AxisStreamClient}\r\n * @readonly\r\n */\r\n stream\r\n /**\r\n * Token balance wrappers\r\n * @type {TokenBalance}\r\n * @readonly\r\n */\r\n tokenBalances\r\n /**\r\n * Contract address of the native XLM token\r\n * @type {string}\r\n * @readonly\r\n */\r\n nativeAsset\r\n /**\r\n * Last known ledger\r\n * @type {number}\r\n */\r\n ledger = 0\r\n /**\r\n * Last updated UNIX milliseconds\r\n * @type {number}\r\n */\r\n ledgerTime = 0\r\n /**\r\n * Whether trading is suspended\r\n * @type {boolean}\r\n */\r\n frozen = false\r\n /**\r\n * Contract configuration\r\n * @type {ContractInfoConfig}\r\n */\r\n config\r\n /**\r\n * Available AXIS markets\r\n * @type {Map<string, AxisMarket>}\r\n * @readonly\r\n */\r\n markets = new Map()\r\n /**\r\n * 24h ticker entries\r\n * @type {Map<string, TickerEntry>}\r\n * @readonly\r\n */\r\n tickers = new Map() //TODO: move inside AxisMarket\r\n /**\r\n * Tracked accounts\r\n * @type {Map<string, AxisAccount>}\r\n * @private\r\n */\r\n accounts = new Map()\r\n /**\r\n * Contract clients by signer\r\n * @type {Map<string, {signTransaction: function, client: AxisContractClient}>}\r\n * @private\r\n */\r\n clients = new Map() //TODO: check if we can use a single AxisContractClient instance instead\r\n /**\r\n * @type {Promise<Axis>}\r\n * @private\r\n */\r\n connecting\r\n\r\n /**\r\n * Whether the contract state loaded\r\n * @return {boolean}\r\n */\r\n get loaded() {\r\n return !!this.loadedAt\r\n }\r\n\r\n /**\r\n * Load the contract state and track its changes\r\n * @return {Promise<Axis>}\r\n */\r\n connect() {\r\n if (!this.connecting) {\r\n this.connecting = new Promise((resolve, reject) => {\r\n //works with the push API, or the REST API if the push connection is not available\r\n let settled = false\r\n const done = () => {\r\n if (!settled) {\r\n settled = true\r\n resolve(this)\r\n }\r\n }\r\n const fail = e => {\r\n if (!settled) {\r\n settled = true\r\n this.connecting = undefined\r\n this.unsubscribeContract?.()\r\n reject(e)\r\n }\r\n }\r\n this.unsubscribeContract = this.stream.subscribe('contract', {}, message => {\r\n if (message.ledger) {\r\n this.applyLedger(message.ledger)\r\n }\r\n if (message.type === 'contract') {\r\n try {\r\n this.applyContractSnapshot(message.data)\r\n } catch (e) {\r\n return fail(e) //a snapshot of another contract is ignored after connecting\r\n }\r\n done()\r\n }\r\n })\r\n //do not wait for a push connection that may never open\r\n this.api.getContract()\r\n .then(data => {\r\n if (!this.loaded) {\r\n this.applyContractSnapshot(data)\r\n }\r\n done()\r\n }, e => {\r\n if (!settled && !this.stream.connected) {\r\n this.startFallback()\r\n fail(e)\r\n }\r\n })\r\n .catch(fail)\r\n })\r\n }\r\n return this.connecting\r\n }\r\n\r\n /**\r\n * AXIS contract address\r\n * @return {Promise<string>}\r\n */\r\n async getContractId() {\r\n if (!this.contractId) {\r\n await this.connect()\r\n }\r\n return this.contractId\r\n }\r\n\r\n /**\r\n * Current ledger sequence\r\n * @return {Promise<number>}\r\n */\r\n async getLedger() {\r\n if (this.ledger && this.stream.connected && Date.now() - this.ledgerTime < LEDGER_STALE_THRESHOLD)\r\n return this.ledger\r\n if (this.tokenBalances)\r\n return this.tokenBalances.getLatestLedger()\r\n if (this.ledger)\r\n return this.ledger\r\n throw new Error('The current ledger is unknown: connect to the AXIS API or set the `rpcUrl` option')\r\n }\r\n\r\n /**\r\n * Get market of the asset pair\r\n * @param {string} asset1 - Token contract address\r\n * @param {string} asset2 - Token contract address\r\n * @return {AxisMarket|undefined}\r\n */\r\n getMarket(asset1, asset2) {\r\n return this.markets.get(pairKey(asset1, asset2)) //TODO: accept also stellar classic asset format CODE:ISSUER and convert it to contract address automatically\r\n }\r\n\r\n /**\r\n * Get live order by id\r\n * @param {bigint|string} id - Order id\r\n * @return {Promise<AccountOrder|undefined>} - Undefined if not found (filled, removed, expired)\r\n */\r\n async getOrder(id) {\r\n const key = id.toString()\r\n for (const account of this.accounts.values()) {\r\n const order = account.orders.get(key)\r\n if (order)\r\n return order\r\n }\r\n try {\r\n return parseApiOrder(await this.api.getOrder(key))\r\n } catch (e) {\r\n if (e instanceof AxisApiError && e.status === 404)\r\n return undefined\r\n throw e\r\n }\r\n }\r\n\r\n /**\r\n * Trader wrapper tracking the orders and allowances for an account (one instance per account address)\r\n * @param {string} address - Trader address\r\n * @param {{signTransaction?: SignTransactionCallback, approvalTtl?: number}} [options] - Transaction signing callback and lifetime of the allowances granted by trading calls, in ledgers\r\n * @return {AxisAccount}\r\n */\r\n account(address, {signTransaction, approvalTtl} = {}) {\r\n let account = this.accounts.get(address)\r\n if (!account) {\r\n account = new AxisAccount(this, address, {signTransaction, approvalTtl})\r\n this.accounts.set(address, account)\r\n account.start()\r\n } else {\r\n if (signTransaction) {\r\n account.signTransaction = signTransaction\r\n }\r\n if (approvalTtl) {\r\n account.approvalTtl = approvalTtl\r\n }\r\n }\r\n return account\r\n }\r\n\r\n /**\r\n * Stream the 24h ticker of every market\r\n * Sends a full snapshot, then updates caused by trades\r\n * @param {function(Ticker24hResult): void} [callback]\r\n * @return {function(): void} - Unsubscribe function\r\n */\r\n subscribeTicker(callback) {\r\n return this.stream.subscribe('ticker', {}, message => {\r\n if (message.type !== 'ticker')\r\n return\r\n for (const entry of message.data.ticker) {\r\n this.tickers.set(entry.symbol, entry)\r\n }\r\n callback?.(message.data)\r\n })\r\n }\r\n\r\n /**\r\n * Extend the contract instance and code lifetime with an `ExtendFootprintTTL` operation, restoring them first if archived\r\n * @param {{days?: number, signer?: Signer}} [params] - Lifetime in days (30 by default) and the transaction source\r\n * (the default signer by default)\r\n * @return {Promise<number>} - Ledger sequence both entries live until, at least\r\n */\r\n async keepalive({days, signer} = {}) {\r\n const client = await this.contractClient(signer)\r\n return client.keepalive(days)\r\n }\r\n\r\n /**\r\n * Stop following the contract state and tracked accounts\r\n */\r\n close() {\r\n this.stopFallback()\r\n this.unsubscribeContract?.()\r\n for (const account of [...this.accounts.values()]) {\r\n account.close()\r\n }\r\n this.stream.close()\r\n this.connecting = undefined\r\n }\r\n\r\n /**\r\n * Contract client signing with the given account\r\n * @param {Signer} [signer] - The default signer if omitted\r\n * @return {Promise<AxisContractClient>}\r\n * @internal\r\n */\r\n async contractClient(signer = this.signer) {\r\n if (!signer?.publicKey || !signer.signTransaction)\r\n throw new Error('A signer ({publicKey, signTransaction}) is required to submit transactions')\r\n if (!this.rpcUrl)\r\n throw new Error('The `rpcUrl` option is required to submit transactions')\r\n await this.getContractId()\r\n const cached = this.clients.get(signer.publicKey)\r\n if (cached && cached.signTransaction === signer.signTransaction)\r\n return cached.client\r\n const client = new AxisContractClient({\r\n publicKey: signer.publicKey,\r\n signTransaction: signer.signTransaction,\r\n rpcUrl: this.rpcUrl,\r\n contractId: this.contractId,\r\n networkPassphrase: this.networkPassphrase,\r\n fee: this.fee\r\n })\r\n this.clients.set(signer.publicKey, {signTransaction: signer.signTransaction, client})\r\n return client\r\n }\r\n\r\n /**\r\n * @param {AxisAccount} account\r\n * @internal\r\n */\r\n releaseAccount(account) {\r\n if (this.accounts.get(account.address) === account) {\r\n this.accounts.delete(account.address)\r\n }\r\n }\r\n\r\n /**\r\n * Apply a contract state snapshot\r\n * @param {ContractInfo} data\r\n * @private\r\n */\r\n applyContractSnapshot(data) {\r\n this.checkContractAddress(data.address)\r\n this.loadedAt = Date.now()\r\n const frozen = data.frozen === true\r\n if (frozen !== this.frozen) {\r\n this.frozen = frozen\r\n this.emit('frozen', frozen)\r\n }\r\n if (data.config && JSON.stringify(data.config) !== JSON.stringify(this.config)) {\r\n this.config = data.config\r\n this.emit('config', data.config)\r\n }\r\n for (const record of data.markets || []) {\r\n const key = pairKey(record.base, record.quote)\r\n const market = this.markets.get(key)\r\n if (!market) {\r\n const created = new AxisMarket(this, record)\r\n this.markets.set(key, created)\r\n this.emit('market', {market: created, created: true})\r\n } else if (record.refreshed && market.refreshed !== parseApiDate(record.refreshed)) {\r\n market.update(record)\r\n this.emit('market', {market, created: false})\r\n }\r\n }\r\n this.emit('change')\r\n }\r\n\r\n /**\r\n * Take the contract address reported by the AXIS API, or check it against the explicitly set\r\n * @param {string} [address]\r\n * @throws {Error} - If the API tracks another contract or the address is unknown\r\n * @private\r\n */\r\n checkContractAddress(address) {\r\n if (!address) {\r\n if (!this.contractId)\r\n throw new Error('The AXIS API does not report the contract address: set the `contractId` option')\r\n return\r\n }\r\n if (!this.contractId) {\r\n this.setContractId(address)\r\n } else if (address !== this.contractId)\r\n throw new Error(`The AXIS API tracks contract ${address}, not ${this.contractId}`)\r\n }\r\n\r\n /**\r\n * @param {string} contractId\r\n * @private\r\n */\r\n setContractId(contractId) {\r\n this.contractId = contractId\r\n if (this.tokenBalances) {\r\n this.tokenBalances.spender = contractId\r\n }\r\n }\r\n\r\n /**\r\n * @param {number} ledger\r\n * @private\r\n */\r\n applyLedger(ledger) {\r\n this.ledgerTime = Date.now()\r\n if (ledger > this.ledger) {\r\n this.ledger = ledger\r\n this.emit('ledger', ledger)\r\n }\r\n }\r\n\r\n /**\r\n * Poll the contract state over REST while the push connection is down\r\n * @private\r\n */\r\n startFallback() {\r\n if (this.fallbackTimer || !this.connecting)\r\n return\r\n this.fallbackTimer = setInterval(() => {\r\n this.api.getContract()\r\n .then(data => this.applyContractSnapshot(data))\r\n .catch(() => {\r\n //retried on the next tick\r\n })\r\n }, this.fallbackPollInterval)\r\n }\r\n\r\n /**\r\n * @private\r\n */\r\n stopFallback() {\r\n clearInterval(this.fallbackTimer)\r\n this.fallbackTimer = undefined\r\n }\r\n}\r\n\r\n/**\r\n * Derive the push API endpoint from the REST API URL\r\n * @param {string} apiUrl\r\n * @return {string}\r\n */\r\nexport function toWsUrl(apiUrl) {\r\n return apiUrl.replace(/^http/i, 'ws').replace(/\\/+$/, '') + '/ws'\r\n}\r\n\r\n/**\r\n * @typedef {{}} AxisOptions\r\n * @property {string} apiUrl - AXIS REST API URL\r\n * @property {string} [contractId] - AXIS contract address, by default pulled from the AXIS API\r\n * @property {string} [wsUrl] - AXIS API push channel URL (`<apiUrl>/ws` with the `ws(s)` scheme by default)\r\n * @property {string} [rpcUrl] - Stellar RPC URL\r\n * @property {string} [networkPassphrase] - Network passphrase (Pubnet by default)\r\n * @property {string} [fee] - Transaction fee\r\n * @property {Signer} [signer] - Default signer settings for contract operations\r\n * @property {number} [fallbackPollInterval] - REST polling period while the push connection is down, in milliseconds\r\n * @property {typeof WebSocket} [WebSocket] - WebSocket implementation\r\n */\r\n","import {Contract, Keypair, Networks, Operation, SorobanDataBuilder, TransactionBuilder, contract, rpc, xdr} from '@stellar/stellar-sdk'\nimport ContractClient from './contract-client.js'\nimport {ContractErrors, TokenErrors, processSimulationErrors, transactionError} from './errors.js'\nimport {AxisApiClient, AxisApiError} from './api-client.js'\nimport {collectOrderIds, completeFootprint, ensureOrdersFootprint} from './footprint.js'\nimport {orderId, generateNonce} from './order-id.js'\nimport {OrderKind, TradeDirection} from './constants.js'\n\nexport {ContractErrors, TokenErrors, AxisApiClient, AxisApiError, orderId, OrderKind, TradeDirection}\nexport {Axis, toWsUrl} from './axis.js'\nexport {AxisMarket} from './axis-market.js'\nexport {AxisAccount, parseApiOrder} from './axis-account.js'\nexport {AxisStreamClient} from './stream-client.js'\nexport {TokenBalance} from './token-balance.js'\nexport {Emitter} from './emitter.js'\nexport {planApproval, planReduction, maxQuoteSpend, APPROVAL_TTL_LEDGERS, MAX_APPROVAL_TTL_LEDGERS, APPROVAL_RENEW_LEDGERS} from './allowance.js'\nexport {canonicalPair, compareAssets, pairKey, invertPrice, invertTicker, PRICE_SCALE} from './asset-pair.js'\nexport {parseApiDate} from './api-dates.js'\n\nconst SECONDS_PER_DAY = 86_400\n//ledger close time assumed when the contract configuration cannot be read, in seconds (the contract's default)\nconst DEFAULT_LEDGER_TIME = 5\n//default lifetime `keepalive` extends the contract instance and code to, in days\nconst KEEPALIVE_DAYS = 30\n//validity window of transactions built by the client, in seconds\nconst TX_TIMEOUT = 60\n//delay between transaction status checks: grows by 1 s per check, up to 3 s\nconst POLL_STEP = 1_000\nconst POLL_MAX_DELAY = 3_000\n//how long to look for a transaction whose submission request failed, in milliseconds\nconst SEND_FAILURE_WINDOW = 30_000\n//failed status requests in a row after which a transaction whose submission request failed is reported as not sent\nconst SEND_FAILURE_REQUESTS = 3\n//margin for the local clock when the RPC server reports no ledger close time, in seconds\nconst CLOCK_MARGIN = 15\n//how long to wait for a transaction without time bounds, in milliseconds\nconst UNBOUNDED_WAIT = 300_000\n//status checks after which a transaction not found yet is checked against the sequence number of its source account\nconst SEQUENCE_CHECK_AFTER = 3\n//a pending transaction another transaction of the account replaced: dropped by the network\nconst SUPERSEDED = Symbol('superseded')\n\n/**\n * Smart contract client for trading with AXIS DEX\n */\nexport class AxisContractClient {\n /**\n * @param {ClientInitializationParams} params\n */\n constructor(params) {\n const options = {\n publicKey: params.publicKey,\n signTransaction: params.signTransaction,\n rpcUrl: params.rpcUrl,\n allowHttp: true,\n networkPassphrase: params.networkPassphrase || Networks.PUBLIC,\n contractId: params.contractId\n }\n this.client = new ContractClient(options)\n this.fee = params.fee || '100000'\n this.autoFootprint = params.autoFootprint !== false\n this.server = new rpc.Server(params.rpcUrl, {allowHttp: true})\n this.assetCache = new Map()\n }\n\n /**\n * Account that signs and pays for the transactions\n * @return {string}\n */\n get publicKey() {\n return this.client.options.publicKey\n }\n\n /**\n * Fetch existing order.\n * @param {bigint} id - ID of the order to fetch\n * @return {Promise<Order|undefined>} - Order fetched from the storage, undefined if not found or expired\n */\n async order(id) {\n const tx = await this.client.order({id})\n processSimulationErrors(tx)\n return tx.result ?? undefined\n }\n\n /**\n * Fetch contract configuration.\n * @return {Promise<Config>}\n */\n async loadConfig() {\n const tx = await this.client.config()\n processSimulationErrors(tx)\n return tx.result\n }\n\n /**\n * Check whether the contract is frozen.\n * @return {Promise<boolean>} - `true` if contract is frozen (trading and order management operations blocked)\n */\n async isFrozen() {\n const tx = await this.client.frozen()\n processSimulationErrors(tx)\n return tx.result\n }\n\n /**\n * Fetch market for the given asset pair.\n * @param {string} selling - First market asset\n * @param {string} buying - Second market asset\n * @return {Promise<Market|undefined>} - Market record if the market exists\n */\n async getMarket(selling, buying) {\n const tx = await this.client.market({selling, buying})\n processSimulationErrors(tx)\n return tx.result ?? undefined\n }\n\n /**\n * Trade with DEX and create a buy limit order if the quote not executed in full.\n * @param {BuyTradeArguments} params\n * @return {Promise<[bigint, bigint, bigint|undefined]>} - Amount of sold and bought tokens, ID of the newly created order if any\n * @throws {Error} - If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade targets a pair without a market,\n * no reference price is available, a live order with the same id exists, the trader cannot receive `buying` (`CannotReceive`), or the contract\n * cannot hold `buying` until its issuer authorizes it (`IntermediaryCannotReceive`).\n */\n async buy(params) {\n return await execTrade(params, TradeDirection.Buy, this)\n }\n\n /**\n * Trade with DEX and create a sell limit order if the quote not executed in full.\n * @param {SellTradeArguments} params\n * @return {Promise<[bigint, bigint, bigint|undefined]>} - Amount of sold and bought tokens, ID of the newly created order if any\n * @throws {Error} - If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade targets a pair without a market,\n * no reference price is available, a live order with the same id exists, the trader cannot receive `buying` (`CannotReceive`), or the contract\n * cannot hold `buying` until its issuer authorizes it (`IntermediaryCannotReceive`). \n */\n async sell(params) {\n return await execTrade(params, TradeDirection.Sell, this)\n }\n\n /**\n * Simulate a buy trade without signing or submitting it, to show the network fee before the trade.\n * @param {BuyTradeArguments} params\n * @return {Promise<TradeEstimate>}\n * @throws {Error} - If the simulation fails, for the same reasons as `buy`\n */\n async estimateBuy(params) {\n return estimateTx(await prepareTrade(params, TradeDirection.Buy, this), this.fee)\n }\n\n /**\n * Simulate a sell trade without signing or submitting it, to show the network fee before the trade.\n * @param {SellTradeArguments} params\n * @return {Promise<TradeEstimate>}\n * @throws {Error} - If the simulation fails, for the same reasons as `sell`\n */\n async estimateSell(params) {\n return estimateTx(await prepareTrade(params, TradeDirection.Sell, this), this.fee)\n }\n\n /**\n * Update the amount, price, or expiration of several orders in place, or remove them.\n * Orders that no longer exist are skipped; expired orders revived with the new expiration.\n * A zero amount removes the order, expired ones included. An updated order's entry lifetime is extended to cover its expiration +1 day.\n * Approvals and removals work in a frozen contract and on a market without quoted assets.\n * A transaction can process up to 90 orders in one batch.\n * @param {UpdateArguments} params\n * @return {Promise<bigint[]>} - IDs of the orders to update\n * @throws {Error} - If the trader does not own an updated order, if order parameters are invalid, if an order is below the minimum value,\n * if the new amounts are not backed by the trader's balance and allowance, an update changes an order on the frozen or not-quoted market\n */\n async update(params) {\n const updates = params.updates.map(update => ({\n id: update.id,\n amount: update.amount,\n price: update.price,\n expires: BigInt(update.expires ?? 0)\n }))\n const approvals = (params.approvals ?? []).map(approval => {\n if (!approval.asset)\n throw new TypeError('An update approval must name its asset')\n return toApproval(approval, approval.asset)\n })\n const tx = await this.client.update({trader: params.trader, updates, approvals}, {fee: this.fee})\n processSimulationErrors(tx)\n this.updateFootprint(tx, updates.map(update => update.id))\n const result = await signAndSend(tx)\n return result\n }\n\n /**\n * Cancel existing orders, expired ones included. A transaction can process up to 90 orders in one batch.\n * @param {string} trader - Trader address\n * @param {bigint[]} ids - IDs of the orders to cancel (non-existent orders are ignored)\n * @return {Promise<void>}\n * @throws {Error} - If trader is not the owner of any existing order in `ids` (works while the contract is frozen)\n */\n async cancel(trader, ids) {\n await this.update({trader, updates: ids.map(id => ({id, amount: 0n, price: 0n}))})\n }\n\n /**\n * Fill an existing order against matching orders from the orderbook. Profits from inefficiencies go to the trader.\n * @param {string} trader - Trader address\n * @param {bigint} takerOrderId - ID of the order that serves as a taker\n * @param {bigint[]} orders - List of order IDs to match against\n * @return {Promise<[bigint, bigint, bigint]>} - Amount the taker order sold, amount the makers delivered, surplus paid to the trader.\n * @throws {Error} - If the taker order does not exist or has expired, if the trader cannot receive the bought asset, if the\n * contract cannot hold the bought asset, if the contract is frozen.\n */\n async crossfill(trader, takerOrderId, orders) {\n const tx = await this.client.crossfill({trader, taker_order_id: takerOrderId, orders}, {fee: this.fee})\n processSimulationErrors(tx)\n //the traded assets come from the taker order, resolved while completing the footprint: what it buys passes\n //through the contract, which pays the owner and the surplus to the trader\n await this.updateTradeFootprint(tx, {takerOrder: takerOrderId, receiver: trader}, [takerOrderId], orders)\n const result = await signAndSend(tx)\n return [result[0], result[1], result[2]]\n }\n\n /**\n * Swap tokens across several markets. The contract holds the intermediate hop proceeds only within the call.\n * @param {SwapArguments} params\n * @return {Promise<[bigint, bigint]>} - Amount of sold and bought tokens\n * @throws {Error} - If the route cannot satisfy the selling/buying amount, if `path` is empty or an amount is invalid,\n * if the contract cannot hold an asset of the path, if the contract is frozen.\n */\n async swap(params) {\n const tx = await this.client.swap({\n direction: params.direction,\n trader: params.trader,\n selling: params.selling,\n selling_amount: params.sellingAmount,\n buying_amount: params.buyingAmount,\n path: params.path.map(step => ({asset: step.asset, orders: step.orders})),\n approve: toApproval(params.approve, params.selling)\n }, {fee: this.fee})\n processSimulationErrors(tx)\n const hops = params.path.map(step => step.asset)\n //every hop asset passes through the contract, the last one is forwarded to the trader\n await this.updateTradeFootprint(tx, {\n tokens: [params.selling, ...hops],\n passThrough: hops,\n receiver: params.trader,\n bought: hops[hops.length - 1]\n }, ...params.path.map(step => step.orders))\n const result = await signAndSend(tx)\n return [result[0], result[1]]\n }\n\n /**\n * Re-check both market assets against the price oracle and cache oracle prices.\n * A cached price is valid for up to 72 hours. A market without quoted assets stops accepting\n * new limit orders; its outstanding orders stay cancellable and fillable. The record and the\n * cached prices are rewritten only when they change. When the simulation writes nothing (the market and the\n * cached prices are current, or the oracle has no newer price), the simulated result is\n * returned and no transaction is submitted.\n * @param {string} selling - First market asset\n * @param {string} buying - Second market asset\n * @return {Promise<Market|undefined>} - Updated market record, undefined if the market does not exist\n * @throws {Error} - If the contract is frozen\n */\n async requote(selling, buying) {\n const tx = await this.client.requote({selling, buying}, {fee: this.fee})\n processSimulationErrors(tx)\n if (tx.isReadCall)\n return tx.result ?? undefined //nothing changed on-chain\n const result = await signAndSend(tx)\n return result ?? undefined\n }\n\n /**\n * Extend oracle price feeds access for a market, creating the market if it does not exist yet.\n * @param {SubsidizeArguments} params\n * @return {Promise<bigint[]>} - New access expiration UNIX timestamps (in seconds) per oracle-listed asset\n * @throws {Error} - If `amount` is invalid, if `selling` equals `buying`, if the market does not exist and the amount is below\n * the market listing fee, if neither market asset is quoted by the oracle, if the contract is frozen\n */\n async subsidize(params) {\n const tx = await this.client.subsidize({\n sponsor: params.sponsor,\n selling: params.selling,\n buying: params.buying,\n amount: params.amount\n }, {fee: this.fee})\n processSimulationErrors(tx)\n const result = await signAndSend(tx)\n return result\n }\n\n /**\n * Extend the contract instance and code lifetime with an `ExtendFootprintTTL` operation, restoring the archived\n * ones first with a `RestoreFootprint` transaction.\n * @param {number} [days] - Lifetime in days, 30 by default, at most the network maximum (180 days on mainnet)\n * @return {Promise<number>} - Ledger sequence both entries live at least until\n * @throws {Error} - If `days` is invalid, if the instance is not found, if a simulation or a transaction fails\n */\n async keepalive(days = KEEPALIVE_DAYS) {\n if (!Number.isInteger(days) || days <= 0)\n throw new TypeError(`Invalid keepalive days: ${days}`)\n const {keys, archived} = await contractLifetimeEntries(this.server, this.client.options.contractId)\n if (archived.length)\n await this.submitFootprintOperation(Operation.restoreFootprint({}), new SorobanDataBuilder().setReadWrite(archived))\n //read after the restoration: the configuration is stored in the instance\n const extendTo = Math.ceil(days * SECONDS_PER_DAY / await this.loadLedgerTime())\n const simulation = await this.submitFootprintOperation(Operation.extendFootprintTtl({extendTo}), new SorobanDataBuilder().setReadOnly(keys))\n return simulation.latestLedger + extendTo\n }\n\n /**\n * Build, simulate, sign and submit a transaction with a single footprint operation (`ExtendFootprintTTL` or `RestoreFootprint`)\n * @param {xdr.Operation} operation\n * @param {SorobanDataBuilder} sorobanData - Footprint of the operation\n * @return {Promise<rpc.Api.SimulateTransactionSuccessResponse>} - Simulation the submitted transaction was assembled from\n * @private\n */\n async submitFootprintOperation(operation, sorobanData) {\n const {networkPassphrase, signTransaction} = this.client.options\n const tx = new TransactionBuilder(await this.server.getAccount(this.publicKey), {fee: this.fee, networkPassphrase})\n .addOperation(operation)\n .setSorobanData(sorobanData.build())\n .setTimeout(TX_TIMEOUT)\n .build()\n const simulation = await this.server.simulateTransaction(tx)\n if (rpc.Api.isSimulationError(simulation))\n throw new Error(simulation.error)\n if (rpc.Api.isSimulationRestore(simulation))\n throw new Error('The contract instance or code was archived during the keepalive, retry it to restore them')\n //assembled here, not through the contract client: its signing path declares the resource fee twice\n const prepared = rpc.assembleTransaction(tx, simulation).build()\n if (typeof signTransaction !== 'function')\n throw new Error('No signTransaction callback to sign the keepalive transaction')\n const {signedTxXdr, error} = await signTransaction(prepared.toXDR(), {networkPassphrase, address: this.publicKey})\n if (error)\n throw new Error(`Keepalive transaction was not signed: ${error.message ?? error}`)\n await submitTransaction(this.server, TransactionBuilder.fromXDR(signedTxXdr, networkPassphrase))\n return simulation\n }\n\n /**\n * Ledger close time the contract converts lifetimes with\n * @return {Promise<number>} - Seconds per ledger\n * @private\n */\n async loadLedgerTime() {\n try {\n return Number((await this.loadConfig())?.ledger_time) || DEFAULT_LEDGER_TIME\n } catch (e) {\n return DEFAULT_LEDGER_TIME //the extension itself reports an unreachable or archived contract\n }\n }\n\n /**\n * Declare all order ids of a simulated call in the read-write footprint (if enabled).\n * @param {contract.AssembledTransaction} tx - Simulated transaction\n * @param {...Array<bigint>} idLists - Order ids passed to the contract call\n * @private\n */\n updateFootprint(tx, ...idLists) {\n if (this.autoFootprint) {\n const orderIds = collectOrderIds(...idLists)\n ensureOrdersFootprint(tx, this.client.options.contractId, orderIds)\n }\n }\n\n /**\n * Declare all order ids of a simulated trading call, and the entries the settlement may write for their makers,\n * in the read-write footprint (if enabled), so the transaction survives book changes before it is applied.\n * @param {contract.AssembledTransaction} tx - Simulated transaction\n * @param {{tokens?: string[], passThrough?: string[], receiver?: string, bought?: string, takerOrder?: bigint}} settlement - Tokens\n * the call trades and how it settles (see `FootprintOptions`)\n * @param {...Array<bigint>} idLists - Order ids passed to the contract call\n * @return {Promise<void>}\n * @private\n */\n async updateTradeFootprint(tx, settlement, ...idLists) {\n if (this.autoFootprint) {\n const orderIds = collectOrderIds(...idLists)\n await completeFootprint(tx, this.client.options.contractId, orderIds, {...settlement, server: this.server, assetCache: this.assetCache})\n }\n }\n}\n\n/**\n * Ledger keys of the contract instance and its Wasm code, and those of them that are archived\n * @param {rpc.Server} server\n * @param {string} contractId\n * @return {Promise<{keys: xdr.LedgerKey[], archived: xdr.LedgerKey[]}>}\n * @internal\n */\nasync function contractLifetimeEntries(server, contractId) {\n const instanceKey = new Contract(contractId).getFootprint()\n const instance = await server.getLedgerEntries(instanceKey)\n const executable = instance.entries[0]?.val?.contractData?.val?.instance?.executable\n if (!executable)\n throw new Error(`Contract ${contractId} instance not found`)\n if (!executable.wasmHash)\n throw new Error(`Contract ${contractId} has no Wasm code`)\n const codeKey = xdr.LedgerKey.contractCode(new xdr.LedgerKeyContractCode({hash: executable.wasmHash}))\n const code = await server.getLedgerEntries(codeKey)\n const archived = []\n if (isArchived(instance.entries[0], instance.latestLedger))\n archived.push(instanceKey)\n //code the RPC does not return is evicted, the restoration brings it back\n if (!code.entries[0] || isArchived(code.entries[0], code.latestLedger))\n archived.push(codeKey)\n return {keys: [instanceKey, codeKey], archived}\n}\n\n/**\n * Whether a ledger entry is no longer live for the transactions following the latest ledger\n * @param {rpc.Api.LedgerEntryResult} entry\n * @param {number} latestLedger\n * @return {boolean}\n * @internal\n */\nfunction isArchived(entry, latestLedger) {\n return entry.liveUntilLedgerSeq !== undefined && entry.liveUntilLedgerSeq <= latestLedger\n}\n\n/**\n * Submit a signed transaction and wait for its result\n * @param {rpc.Server} server\n * @param {import('@stellar/stellar-sdk').Transaction} tx - Signed transaction\n * @param {string} [contractId] - DEX contract address, to tell its errors from the errors of the tokens it calls\n * @return {Promise<rpc.Api.GetSuccessfulTransactionResponse>}\n * @throws {Error} - A {@link transactionError} when the network does not accept the transaction (`ERROR`,\n * `TRY_AGAIN_LATER`), it fails on-chain (`FAILED`) or it is not seen before its time bounds expire (`TIMEOUT`); the\n * request error, with the transaction `hash`, when the RPC server cannot be reached\n * @internal\n */\nasync function submitTransaction(server, tx, contractId) {\n const hash = toHex(tx.hash())\n let sent\n try {\n sent = await server.sendTransaction(tx)\n } catch (e) {\n //the request may have reached the network before it failed: look for the transaction before reporting it\n const response = await waitForTransaction(server, tx, hash, {window: SEND_FAILURE_WINDOW, maxFailures: SEND_FAILURE_REQUESTS})\n if (!response) {\n if (e instanceof Error) {\n e.hash = hash\n }\n throw e\n }\n return checkTransaction(response, hash, contractId)\n }\n if (sent.status === 'ERROR')\n throw transactionError('ERROR', {hash, result: sent.errorResult, events: sent.diagnosticEvents, contractId})\n if (sent.status === 'TRY_AGAIN_LATER')\n throw transactionError('TRY_AGAIN_LATER', {hash})\n //PENDING, or DUPLICATE when the network already has it\n const response = await waitForTransaction(server, tx, hash)\n if (!response)\n throw transactionError('TIMEOUT', {hash})\n return checkTransaction(response, hash, contractId)\n}\n\n/**\n * Poll the status of a submitted transaction until it is found, or can no longer be included: its time bounds expired,\n * or another transaction of its source account consumed its sequence number (an RPC server behind a load balancer can\n * accept two transactions with the same sequence number, the network then drops one of them)\n * @param {rpc.Server} server\n * @param {import('@stellar/stellar-sdk').Transaction} tx - Submitted transaction\n * @param {string} hash - Transaction hash, hex\n * @param {{window?: number, maxFailures?: number}} [options] - Longest wait in milliseconds, and the number of failed\n * requests in a row to give up after\n * @return {Promise<rpc.Api.GetSuccessfulTransactionResponse|rpc.Api.GetFailedTransactionResponse|SUPERSEDED|undefined>} -\n * Undefined if not found\n * @internal\n */\nasync function waitForTransaction(server, tx, hash, {window, maxFailures} = {}) {\n const started = Date.now()\n const maxTime = Number(tx.timeBounds?.maxTime) || 0\n let failures = 0\n let consumedAt\n for (let attempt = 1; ; attempt++) {\n let response\n try {\n response = await server.getTransaction(hash)\n failures = 0\n } catch (e) {\n failures++ //a failed request tells nothing about the transaction\n }\n if (response && response.status !== 'NOT_FOUND')\n return response\n //the server had seen the ledger where the sequence number was consumed and still does not know the transaction\n if (consumedAt !== undefined && response?.latestLedger >= consumedAt)\n return SUPERSEDED\n if (consumedAt === undefined && response && attempt >= SEQUENCE_CHECK_AFTER) {\n consumedAt = await sequenceConsumedAt(server, tx)\n }\n if (maxFailures && failures >= maxFailures)\n return undefined\n if (window && Date.now() - started >= window)\n return undefined\n if (isPastTimeBounds(response, maxTime, started))\n return undefined\n await new Promise(resolve => setTimeout(resolve, Math.min(attempt * POLL_STEP, POLL_MAX_DELAY)))\n }\n}\n\n/**\n * Check whether the source account of a transaction moved past its sequence number\n * @param {rpc.Server} server\n * @param {import('@stellar/stellar-sdk').Transaction} tx\n * @return {Promise<number|undefined>} - Latest ledger of the RPC server when it reported the account past the\n * transaction sequence number, undefined otherwise\n * @internal\n */\nasync function sequenceConsumedAt(server, tx) {\n try {\n const key = xdr.LedgerKey.account(new xdr.LedgerKeyAccount({accountId: Keypair.fromPublicKey(tx.source).xdrPublicKey()}))\n const {entries, latestLedger} = await server.getLedgerEntries(key)\n const seqNum = entries[0]?.val?.value?.seqNum\n return seqNum !== undefined && BigInt(seqNum) >= BigInt(tx.sequence) ? latestLedger : undefined\n } catch (e) {\n return undefined //a muxed source, or the request failed\n }\n}\n\n/**\n * Whether a transaction not found yet can no longer be included: a ledger closing after its upper time bound cannot\n * include it, and the RPC server has seen every ledger up to the latest one it reports\n * @param {rpc.Api.GetTransactionResponse|undefined} response - Latest status response, if any\n * @param {number} maxTime - Upper time bound, UNIX seconds (0 = none)\n * @param {number} started - When polling started, UNIX milliseconds\n * @return {boolean}\n * @internal\n */\nfunction isPastTimeBounds(response, maxTime, started) {\n if (!maxTime)\n return Date.now() - started >= UNBOUNDED_WAIT\n const closeTime = Number(response?.latestLedgerCloseTime)\n if (closeTime)\n return closeTime > maxTime\n return Date.now() / 1000 > maxTime + CLOCK_MARGIN\n}\n\n/**\n * @param {rpc.Api.GetSuccessfulTransactionResponse|rpc.Api.GetFailedTransactionResponse|SUPERSEDED} response\n * @param {string} hash\n * @param {string} [contractId]\n * @return {rpc.Api.GetSuccessfulTransactionResponse}\n * @throws {Error} - A `FAILED` {@link transactionError}, or an `ERROR` one with `tx_bad_seq` for a transaction dropped\n * because another one consumed its sequence number\n * @internal\n */\nfunction checkTransaction(response, hash, contractId) {\n if (response === SUPERSEDED)\n throw transactionError('ERROR', {hash, resultCode: 'tx_bad_seq'})\n if (response.status === 'FAILED')\n throw transactionError('FAILED', {hash, result: response.resultXdr, events: diagnosticEvents(response), contractId})\n return response\n}\n\n/**\n * Diagnostic events of an applied transaction: reported separately by RPC servers that keep them, otherwise taken from\n * the transaction meta (empty when the network did not record them)\n * @param {rpc.Api.GetFailedTransactionResponse} response\n * @return {xdr.DiagnosticEvent[]}\n * @internal\n */\nfunction diagnosticEvents(response) {\n if (response.diagnosticEventsXdr?.length)\n return response.diagnosticEventsXdr\n const meta = response.resultMetaXdr?.value\n return meta?.diagnosticEvents ?? meta?.sorobanMeta?.diagnosticEvents ?? []\n}\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n * @internal\n */\nfunction toHex(bytes) {\n return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * Map the client-side approval to the contract `Approval` argument\n * @param {Approval} [approve]\n * @param {string} defaultAsset - Asset approved when `approve.asset` is not set\n * @return {{asset: string, amount: bigint, live_until: number}|undefined}\n * @internal\n */\nfunction toApproval(approve, defaultAsset) {\n if (!approve)\n return undefined\n return {asset: approve.asset ?? defaultAsset, amount: approve.amount, live_until: approve.liveUntil}\n}\n\n/**\n * Sign and submit a simulated transaction. Submitted over RPC directly rather than with `tx.signAndSend()`, whose send\n * failure carries the RPC response only as text\n * @param {contract.AssembledTransaction} tx\n * @return {Promise<*>} - Parsed contract call result\n * @throws {Error} - The wallet error when signing fails, a {@link transactionError} when the transaction is not\n * accepted, fails on-chain or is not confirmed in time\n * @internal\n */\nasync function signAndSend(tx) {\n await tx.sign()\n const response = await submitTransaction(tx.server, tx.signed, tx.options.contractId)\n return response.returnValue === undefined ? undefined : tx.options.parseResultXdr(response.returnValue)\n}\n\nasync function execTrade(params, direction, context) {\n const result = await signAndSend(await prepareTrade(params, direction, context))\n return [result[0], result[1], result[2] ?? undefined]\n}\n\n/**\n * Simulate a trade and complete its footprint\n * @param {BuyTradeArguments|SellTradeArguments} params\n * @param {number} direction\n * @param {AxisContractClient} context\n * @return {Promise<contract.AssembledTransaction>}\n * @internal\n */\nasync function prepareTrade(params, direction, context) {\n //the id of the order created for the remainder derives from the trader and this nonce; generated per call, never supplied by the caller\n const nonce = generateNonce()\n const payload = {\n direction: direction,\n kind: params.kind,\n trader: params.trader,\n amount: params.amount,\n selling: params.selling,\n buying: params.buying,\n price: params.price,\n orders: params.orders ?? [],\n nonce,\n expires: BigInt(params.expires ?? 0),\n approve: toApproval(params.approve, params.selling)\n }\n const tx = await context.client.trade(payload, {fee: context.fee})\n processSimulationErrors(tx)\n //the remainder of a Limit trade becomes an order under an id known in advance - declare it even if the simulation filled the quote\n const remainder = params.kind === OrderKind.Limit ? [orderId(params.trader, nonce)] : []\n //the bought asset passes through the contract on its way to the trader\n await context.updateTradeFootprint(tx, {\n tokens: [params.selling, params.buying],\n passThrough: [params.buying],\n receiver: params.trader,\n bought: params.buying\n }, payload.orders, remainder)\n return tx\n}\n\n/**\n * Fee and expected result of a simulated transaction\n * @param {contract.AssembledTransaction} tx - Simulated transaction with its footprint completed\n * @param {string} inclusionFee - Inclusion fee bid of the client\n * @return {TradeEstimate}\n * @internal\n */\nfunction estimateTx(tx, inclusionFee) {\n const fee = BigInt(tx.built.fee)\n const [sold, bought, orderId] = tx.result\n return {fee, inclusionFee: BigInt(inclusionFee), resourceFee: fee - BigInt(inclusionFee), sold, bought, orderId: orderId ?? undefined}\n}\n\n/**\n * @typedef {{}} ClientInitializationParams\n * @property {string} publicKey - Public key of the account that will interact with the contract\n * @property {SignTransactionCallback} signTransaction - Callback for signing transactions generated by the client\n * @property {string} rpcUrl - URL of the RPC server\n * @property {string} contractId - DEX contract ID\n * @property {string} [networkPassphrase] - Network passphrase (Pubnet passphrase by default)\n * @property {string} [fee] - Inclusion fee bid in stroops (100,000 = 0.01 XLM by default), the simulated resource fee is added on top\n * @property {boolean} [autoFootprint] - Declare every supplied order id, and the balances and allowances of the makers behind them, in the read-write footprint of trading transactions (enabled by default)\n */\n\n/**\n * @callback SignTransactionCallback - Callback for signing transactions generated by the client (`@stellar/stellar-sdk` 17 contract client shape)\n * @param {string} xdr - Transaction XDR to sign\n * @param {{networkPassphrase?: string, address?: string, submit?: boolean, submitUrl?: string}} [opts] - Signing options passed by the SDK\n * @return {Promise<{signedTxXdr: string, signerAddress?: string, error?: *}>} - Signed transaction response\n */\n\n/**\n * @typedef {{}} Approval - Token allowance granted to the contract as part of the call\n * @property {string} [asset] - Token the allowance is granted on\n * @property {bigint} amount - Absolute allowance amount (0 revokes the approval)\n * @property {number} liveUntil - Ledger sequence the allowance lives until\n */\n\n/**\n * @typedef {{}} TradeArguments\n * @property {OrderKind} kind - Trading order behavior\n * @property {string} trader - Trader address\n * @property {bigint} amount - Tokens amount\n * @property {string} selling - Selling token address\n * @property {string} buying - Buying token address\n * @property {bigint} price - Price a trader willing to accept\n * @property {Array<bigint>} [orders] - List of order IDs to match before creating the order on-chain\n * @property {bigint|number} [expires] - Expiration UNIX timestamp (in seconds) of the order created for a `Limit` remainder, 0 or omitted = no expiration\n * @property {Approval} [approve] - Optional allowance granted to the contract before trading (on `selling` unless `asset` is set)\n */\n\n/**\n * @typedef {{}} SellTradeArguments\n * @extends TradeArguments\n * @property {bigint} amount - Amount of `selling` tokens to sell\n * @property {bigint} price - Price a trader willing to accept, minimum `buying` tokens per 1 `selling`\n */\n\n/**\n * @typedef {{}} BuyTradeArguments\n * @extends TradeArguments\n * @property {bigint} amount - Amount of `buying` tokens to acquire\n * @property {bigint} price - Price a trader willing to accept, maximum `selling` tokens per 1 `buying`\n */\n\n/**\n * @typedef {{}} TradeEstimate - Simulated trade, nothing signed or submitted\n * @property {bigint} fee - Maximum total network fee of the transaction, in stroops (inclusion fee bid plus resource fee)\n * @property {bigint} inclusionFee - Inclusion fee bid, in stroops (the network charges the market rate up to it)\n * @property {bigint} resourceFee - Resource fee, in stroops, including the rent of an order created for the remainder\n * @property {bigint} sold - Expected amount of sold tokens\n * @property {bigint} bought - Expected amount of bought tokens\n * @property {bigint} [orderId] - ID of the order the remainder would create\n */\n\n/**\n * @typedef {{}} TradeStep - A trade step in a multi-market swap path\n * @property {string} asset - Asset to buy at this step\n * @property {Array<bigint>} orders - Maker order IDs to match\n */\n\n/**\n * @typedef {{}} SwapArguments - Swap path and settings\n * @property {TradeDirection} direction - Trade direction: `Sell` or `Buy`\n * @property {string} trader - Trader address\n * @property {string} selling - Token address sent by the trader\n * @property {bigint} sellingAmount - Amount of selling tokens to send (`Sell`) or the maximum to spend (`Buy`)\n * @property {bigint} buyingAmount - Minimum amount of buying tokens to receive (`Sell`) or the exact amount (`Buy`)\n * @property {Array<TradeStep>} path - Ordered list of the trade route steps\n * @property {Approval} [approve] - Optional allowance granted to the contract before trading (on `selling` unless `asset` is set)\n */\n\n/**\n * @typedef {{}} OrderUpdate - New amount, price and expiration for an existing order\n * @property {bigint} id - Order id\n * @property {bigint} amount - New amount to sell, 0 removes the order\n * @property {bigint} price - New order price (ignored for a removal)\n * @property {bigint|number} [expires] - New expiration UNIX timestamp (in seconds), 0 or omitted = no expiration\n */\n\n/**\n * @typedef {{}} UpdateArguments\n * @property {string} trader - Orders owner\n * @property {Array<OrderUpdate>} updates - New amount, price and expiration per order\n * @property {Array<Approval>} [approvals] - Allowances granted before the backing check, each naming its `asset`; an asset\n * without an approval keeps its current allowance\n */\n\n/**\n * @typedef {{}} SubsidizeArguments\n * @property {string} sponsor - Address paying for the oracle feeds (and the listing fee of a new market)\n * @property {string} selling - First market asset\n * @property {string} buying - Second market asset (either order opens the same market)\n * @property {bigint} amount - Amount of XRF fee tokens to burn, at least `Config.market_listing_fee` to open a market\n */\n\n/**\n * @typedef {{}} MethodOptions\n * @property {string} [fee] - Inclusion fee bid in stroops (100,000 = 0.01 XLM by default), the simulated resource fee is added on top\n */\n\n/**\n * @typedef {{}} Order - Order properties, stored on-chain\n * @property {bigint} id - Unique order identifier, derived from the owner and the client nonce\n * @property {string} owner - Maker address\n * @property {string} selling - Selling token address\n * @property {string} buying - Buying token address\n * @property {bigint} amount - Amount left to sell\n * @property {bigint} price - Order price (`buying` per 1 `selling`, 18 decimals)\n * @property {bigint} expires - Expiration UNIX timestamp in seconds (0 = no expiration)\n */\n\n/**\n * @typedef {{}} Config - Contract configuration\n * @property {string} safety_admin - Address of the account allowed to freeze the contract and change the configuration\n * @property {string} oracle - Oracle contract address\n * @property {number} listing_min_days - Days of price feeds a new market must buy (0 opens markets without a fee)\n * @property {bigint} market_listing_fee - Amount of oracle fee tokens paid by the market creator to provision the oracle price feeds\n * (the oracle daily fee x `listing_min_days`)\n * @property {bigint} min_trade_size - Minimum trade value in USD, with 7 decimals precision (0 disables the limit)\n * @property {number} ledger_time - Expected average ledger close time in seconds, used to convert entry lifetimes into ledgers\n */\n\n/**\n * @typedef {{}} MarketSide - Market asset descriptor\n * @property {string} asset - Token contract address\n * @property {boolean} listed - Whether the asset is quoted by the oracle (with token decimals the valuation can handle)\n * @property {number} decimals - Token decimals (fetched only for listed assets)\n */\n\n/**\n * @typedef {{}} Market - Market record, stored on-chain\n * @property {MarketSide} base - Base asset, the first of the pair in canonical order\n * @property {MarketSide} quote - Quote asset, the second of the pair in canonical order\n * @property {bigint} created - Creation UNIX timestamp in seconds\n */\n\n/**\n * @typedef {object} TradeContractEvent - Orderbook `trade` event, one per fill\n * @property {string} selling - Asset sold by the taker (topic)\n * @property {string} buying - Asset bought by the taker (topic)\n * @property {bigint} order - Maker order id\n * @property {string} taker - Trader account address\n * @property {string} maker - Seller account address\n * @property {bigint} sold - Sold tokens amount\n * @property {bigint} bought - Bought tokens amount\n * @property {bigint} left - Order amount left after the fill (0 = removed)\n */\n\n/**\n * @typedef {object} SwapContractEvent - Orderbook `swap` event, one per call\n * @property {string} selling - Asset sold by the trader (topic)\n * @property {string} buying - Asset received by the trader (topic)\n * @property {string} trader - Trader account address\n * @property {bigint} sold - Amount of `selling` tokens sold\n * @property {bigint} bought - Amount of `buying` tokens received\n */\n\n/**\n * @typedef {object} OrderCreatedContractEvent - Orderbook `new` event, an order created\n * @property {string} selling - Selling asset address (topic)\n * @property {string} buying - Buying asset address (topic)\n * @property {bigint} id - Unique order identifier\n * @property {string} owner - Maker address\n * @property {bigint} price - Order price\n * @property {bigint} amount - Current amount\n * @property {bigint} expires - Expiration UNIX timestamp in seconds (0 = no expiration)\n */\n\n/**\n * @typedef {object} OrderUpdatedContractEvent - Orderbook `mod` event, an order changed outside a fill\n * @property {bigint} id - Unique order identifier\n * @property {bigint} price - Order price\n * @property {bigint} amount - Current amount (0 = removed)\n * @property {bigint} expires - Expiration UNIX timestamp in seconds (0 = no expiration)\n */\n\n/**\n * @typedef {object} OrderSkippedContractEvent - Orderbook `skip` event, a listed order its maker could not settle: backing\n * short of the fill, a missing or deauthorized trustline for the taker's asset, or the maker's asset could not be collected.\n * The order is left unchanged. For `crossfill` it also flags a taker order its owner cannot back or be paid for\n * @property {bigint} order - Order id\n */\n\n/**\n * @typedef {object} MarketRefreshContractEvent - Orderbook `refresh` event, a market checked against the oracle\n * (topics: `refresh`, `base`, `quote`, no data)\n * @property {string} base - Base market asset (canonical order, topic)\n * @property {string} quote - Quote market asset (canonical order, topic)\n */\n\n/**\n * @typedef {object} FreezeContractEvent - `freeze` event\n * @property {boolean} frozen - Whether trading is blocked after the call\n */\n\n/**\n * @typedef {object} ConfigChangedContractEvent - `config` update notification event (constructor, `delegate`, `set_oracle`,\n * `set_floor`, `set_listing_min_days`, `set_ledger_time`)\n * @property {Config} config - Contract configuration after the call\n */\n","import * as axis from './index.js'\n\nconst axisClient = {...axis}\nexport default axisClient\n"],"names":["root","factory","exports","module","require","define","amd","this","__WEBPACK_EXTERNAL_MODULE__346__","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","d","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","ContractClient","stellar_sdk_","contract","Client","options","constructor","super","Spec","fromJSON","swap","txFromJSON","order","trade","config","freeze","frozen","market","update","requote","delegate","crossfill","set_floor","subsidize","set_oracle","set_ledger_time","set_listing_min_days","ContractErrors","message","TokenErrors","processSimulationErrors","tx","simulation","error","contractErrorMatch","exec","code","parseInt","contractError","source","match","matchAll","findErrorSource","contractId","dexContract","name","Error","tokenError","err","transactionError","status","hash","result","resultCode","knownCode","events","type","snakeCase","opResult","op","results","tr","test","operationResultCode","cause","length","errors","event","eventErrorCode","push","eventContract","find","findEventError","causeError","topics","body","sym","toString","contractCode","id","StrKey","encodeContract","toBytes","replace","letter","toLowerCase","AxisApiError","AxisApiClient","serverUrl","TypeError","quoteSell","params","quote","quoteBuy","sellingAsset","buyingAsset","amount","direct","maxPrice","direction","request","getDepth","depth","step","limit","getCandles","from","to","resolution","getTicker24h","getMarkets","cursor","getContract","getOrders","owner","asset","getAccount","address","encodeURIComponent","getOrder","getOrderHistory","pair","getTrades","trader","getFailures","account","fn","path","query","url","search","URLSearchParams","entries","Array","isArray","item","append","qs","response","fetch","json","e","ok","statusText","ORDER_INSTRUCTIONS","ORDER_RESOURCE_FEE","DISK_ENTRY_TYPES","Set","collectOrderIds","idLists","seen","res","list","BigInt","has","add","orderLedgerKey","orderId","contractDataKey","nativeToScVal","xdr","ContractDataDurability","persistent","instanceLedgerKey","ScVal","scvLedgerKeyContractInstance","balanceLedgerKey","token","isValidContract","scvVec","scvSymbol","Address","fromString","toScVal","accountId","Keypair","fromPublicKey","xdrAccountId","isNative","LedgerKey","LedgerKeyAccount","getIssuer","trustline","LedgerKeyTrustLine","toTrustLineXDRObject","allowanceLedgerKey","spender","scvMap","ScMapEntry","val","temporary","decodeStoredOrder","selling","buying","scValToNative","decodeSacAsset","instance","executable","entry","storage","info","Asset","native","asset_code","encodeEd25519PublicKey","issuer","durability","contractData","LedgerKeyContractData","toScAddress","isPatchable","restorePreamble","built","async","loadEntries","server","keys","Map","i","getLedgerEntries","slice","set","toXDR","unresolved","tokens","assetCache","filter","cacheAssets","declareReadWrite","data","readOnly","getReadOnly","readWrite","getReadWrite","roIndex","map","rwIndex","dropFromReadOnly","added","encoded","promoted","total","size","setFootprint","_","applyResources","instructions","diskReadBytes","writeBytes","fee","resources","build","setResources","Math","min","setResourceFee","resourceFee","simulationTransactionData","timeout","timeoutInSeconds","TransactionBuilder","cloneFrom","sorobanData","timebounds","setTimeout","U64_MAX","nonce","RangeError","payload","scvU64","digest","OrderKind","Limit","Fill","FillOrKill","TradeDirection","Sell","Buy","Emitter","listeners","on","listener","off","once","args","delete","emit","console","AxisStreamClient","WebSocket","WebSocketImpl","pingInterval","minReconnectDelay","maxReconnectDelay","globalThis","subscriptions","requests","nextId","socket","failures","closed","connected","readyState","subscribe","channel","handler","sub","topic","sendSubscribe","connect","unsubscribe","close","clear","clearTimeout","reconnectTimer","stopPing","subs","some","s","send","pending","scheduleReconnect","onopen","lastMessage","Date","now","startPing","onmessage","JSON","parse","route","onclose","onerror","delay","pingTimer","setInterval","clearInterval","stringify","deliver","TokenBalance","rpcUrl","networkPassphrase","rpc","Server","allowHttp","startsWith","getAllowance","toBigInt","load","getBalance","getLatestLedger","sequence","method","sourceAccount","random","publicKey","Account","addOperation","Contract","sim","simulateTransaction","Api","isSimulationError","retval","PRICE_SCALE","keyCache","getAddressKey","compareAssets","a","b","key1","key2","canonicalPair","x","y","pairKey","a1","a2","invertPrice","price","invertTicker","symbol","split","inv","n","Number","String","open","openPrice","last","lastPrice","highPrice","lowPrice","volume","quoteVolume","change","round","avgPrice","parseApiDate","text","trim","ms","isFinite","AxisMarket","axis","record","base","created","refreshed","counter","signer","contractClient","sponsor","client","api","subscribeDepth","callback","stream","subscribeTrades","trades","subscribeCandles","candles","candle","ticker","tickers","toJSON","MAX_APPROVAL_TTL_LEDGERS","APPROVAL_TTL_LEDGERS","APPROVAL_RENEW_LEDGERS","planApproval","required","committed","allowance","liveUntil","ledger","ttl","target","planReduction","maxQuoteSpend","LOCAL_ORDER_TTL","AxisAccount","signTransaction","approvalTtl","ready","Promise","resolve","resolveReady","orders","backing","loaded","local","live","spent","queue","removed","approved","start","handle","offOpen","stopFallback","offClose","startFallback","initTimer","refresh","catch","releaseAccount","applySnapshot","toMarketKey","allOrders","sort","newestFirst","isRemoved","localOrders","sum","updated","balance","balances","funded","nativeAsset","authorized","known","available","budget","sell","serialize","buy","estimateSell","prepareTrade","estimateBuy","updates","whenReady","changes","current","expires","submitUpdates","grow","cancel","ids","removeOrders","cancelAll","revoke","assets","cancelOrders","includes","canceled","revoked","progress","batches","takerOrderId","taker","findQuote","sold","bought","surplus","trySwap","slippage","best","paths","hop","Boolean","tolerance","sellingAmount","buyingAmount","approve","readAllowance","getLedger","isAllowanceCurrent","tokenBalances","getContractId","pendingApproval","planned","createdId","trackCreated","kind","crossing","worstPrice","stored","orderAmount","orderPrice","backed","backedPct","backingPending","filledPct","then","batch","approvals","splitBatches","plan","snapshotAllowances","planBatch","approval","applyBatch","until","assign","replaced","withAllowance","reconcileBacking","expected","timer","race","reject","applyOrder","applyBacking","state","mergeBacking","previous","next","raw","parseApiOrder","parseBacking","action","fill","rawFill","ts","partial","share","values","fallbackTimer","fallbackPollInterval","confirmed","floor","max","skipped","part","changed","delta","need","Axis","apiUrl","wsUrl","Networks","PUBLIC","toWsUrl","ledgerTime","markets","accounts","clients","connecting","loadedAt","settled","done","fail","unsubscribeContract","applyLedger","applyContractSnapshot","getMarket","asset1","asset2","subscribeTicker","keepalive","days","cached","AxisContractClient","checkContractAddress","setContractId","SUPERSEDED","autoFootprint","loadConfig","isFrozen","execTrade","estimateTx","toApproval","updateFootprint","signAndSend","taker_order_id","updateTradeFootprint","takerOrder","receiver","selling_amount","buying_amount","hops","passThrough","isReadCall","isInteger","archived","instanceKey","getFootprint","wasmHash","codeKey","LedgerKeyContractCode","isArchived","latestLedger","contractLifetimeEntries","submitFootprintOperation","Operation","restoreFootprint","SorobanDataBuilder","setReadWrite","extendTo","ceil","loadLedgerTime","extendFootprintTtl","setReadOnly","operation","setSorobanData","isSimulationRestore","prepared","assembleTransaction","signedTxXdr","submitTransaction","fromXDR","ledger_time","orderIds","transactionData","ensureOrdersFootprint","settlement","settlementEntries","makerEntries","orderKeys","knownTokens","passing","newTokens","flatMap","settlementKeys","settlementSet","makerOf","makerKeys","makers","diskEntries","orderEntries","forward","completeFootprint","liveUntilLedgerSeq","bytes","byte","padStart","join","sent","sendTransaction","waitForTransaction","window","maxFailures","checkTransaction","errorResult","diagnosticEvents","started","maxTime","timeBounds","consumedAt","attempt","getTransaction","sequenceConsumedAt","isPastTimeBounds","xdrPublicKey","seqNum","closeTime","latestLedgerCloseTime","resultXdr","diagnosticEventsXdr","meta","resultMetaXdr","sorobanMeta","defaultAsset","live_until","sign","signed","returnValue","parseResultXdr","context","crypto","getRandomValues","Uint32Array","randomBits22","remainder","inclusionFee","cjs","src_namespaceObject"],"sourceRoot":""}
|