@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 CHANGED
@@ -74,11 +74,23 @@ await account.swap({selling: USDC, buying: EURC, amount: 10_000_000n, direction:
74
74
 
75
75
  **Allowances.** The contract holds no funds: an order is fillable up to `min(balance, allowance)` in the sold token, and
76
76
  one allowance record backs every order selling it. Before each `sell`, `buy`, `swap` and a growing `update`, the account
77
- checks the allowance and attaches to cover all active orders. A fill lowers the allowance and the order it fills in the
78
- same pushed ledger, so the memory state stays consistent. The allowance is read over RPC only when the push connection
79
- is down, the token is not tracked, or for 30 s after this client spent the token as a taker (the push reporting the
80
- spend may lag behind). An order this client created counts as committed right away (`pending: true`) until the indexer
81
- reports it.
77
+ checks the allowance and attaches to cover all active orders. An `update` that does not grow its orders still raises an
78
+ allowance that does not back them (the contract would reject it). `cancel`, `cancelAll` and a shrinking `update` lower
79
+ the allowance to what the remaining open orders selling the token need, and to zero when none remain. With more than one
80
+ batch, each batch carries the allowance its orders need, so a declined signature leaves the rest backed.
81
+ `revoke(assets, {cancelOrders?})` sets allowances to zero, optionally canceling the orders selling them in the same
82
+ transactions. A new allowance lives `account.approvalTtl` ledgers (`APPROVAL_TTL_LEDGERS`, ~180 days, unless set with
83
+ `axis.account(address, {approvalTtl})`), at most `MAX_APPROVAL_TTL_LEDGERS`. A fill lowers the allowance and the order
84
+ it fills in the same pushed ledger, so the memory state stays consistent. The allowance is read over RPC only when the
85
+ push connection is down, the token is not tracked, for 30 s after this client spent the token as a taker (the push
86
+ reporting the spend may lag behind), and after this client set it until the push reports the change (at most 6 minutes).
87
+ An order this client created counts as committed right away (`pending: true`) until the indexer reports it, and an order
88
+ it changed or canceled shows the change right away.
89
+
90
+ **One call at a time.** Calls that submit transactions (`sell`, `buy`, `swap`, `update`, `cancel`, `cancelAll`,
91
+ `revoke`, `crossfill`) run one after another: each one builds its transaction, which fixes its sequence number, and
92
+ plans its approvals only after the previous one settled. Concurrent calls of an account therefore never fail with
93
+ `tx_bad_seq` against each other.
82
94
 
83
95
  **Balances.** While an account is subscribed, the AXIS API tracks it in every market token.
84
96
  `account.balances` / `getBalance(asset)` give the spendable amount, and each change emits
@@ -96,7 +108,7 @@ selling the token oldest first), `backedPct` and `backingPending`.
96
108
  | `frozen`, `config`, `markets`, `loaded` | Contract state; `markets` is a `Map` of `AxisMarket` by canonical key. |
97
109
  | `getMarket(x, y)` | Market of the asset pair in either order, `undefined` if not open. |
98
110
  | `getOrder(id)` | Live order from a tracked account's memory or the AXIS API, `undefined` if gone. |
99
- | `account(address, {signTransaction})` | `AxisAccount` of the trader (one per address). |
111
+ | `account(address, {signTransaction, approvalTtl?})` | `AxisAccount` of the trader (one per address), `approvalTtl` sets the lifetime of the allowances it grants in ledgers. |
100
112
  | `subscribeTicker(cb)` | 24h ticker of every market (canonical orientation); also fills `market.ticker`. |
101
113
  | `keepalive({days?, signer?})` | Extend the contract instance and code lifetime, see `AxisContractClient.keepalive`. |
102
114
  | `close()` | Stop following the contract and every account. |
@@ -114,13 +126,15 @@ selling the token oldest first), `backedPct` and `backingPending`.
114
126
  | `AxisAccount` | Description |
115
127
  |---|---|
116
128
  | `orders`, `backing`, `ready`, `loaded` | Open orders by id and backing by token, in memory. |
129
+ | `approvalTtl` | Lifetime of the allowances granted by trading calls, in ledgers (`APPROVAL_TTL_LEDGERS` by default, at most `MAX_APPROVAL_TTL_LEDGERS`). |
117
130
  | `balances`, `getBalance(asset)`, `funded` | Spendable balances by token (every market token), whether the account exists. |
118
131
  | `getOrders({market?, selling?, buying?})` | Open orders, newest first, including `pending` ones this client created. |
119
132
  | `getOrder(id)`, `committed(asset)`, `getAllowance(asset)` | Order lookup, open amount selling a token, allowance summary. |
120
133
  | `sell(params)`, `buy(params)` | Trade (`{selling, buying, amount, price?, kind?, expires?, orders?, approve?}`); without `price` it is a market order. Without `orders`, a limit order crosses the orders a direct quote finds up to its price (partial crossings included) and rests with the remainder; a market order crosses the quote for the full amount. Returns `{sold, bought, orderId?, order?, approve?}`. |
121
134
  | `estimateSell(params)`, `estimateBuy(params)` | Simulate the same trade without signing or submitting it. Returns `{fee, inclusionFee, resourceFee, sold, bought, orderId?}` (fees in stroops, `fee` is the maximum total). |
122
- | `update(updates)` | Change orders (omitted fields keep their values). |
123
- | `cancel(ids)`, `cancelAll({market?})` | Remove orders (batches of 100). |
135
+ | `update(updates)` | Change orders (omitted fields keep their values), raising or lowering the allowance to what the open orders need. |
136
+ | `cancel(ids)`, `cancelAll({market?})` | Remove orders (batches of up to 90) and lower the allowance to what the remaining orders need. |
137
+ | `revoke(assets, {cancelOrders?})` | Set the allowances on the tokens to zero, optionally canceling the orders selling them. Returns `{revoked, canceled}`. |
124
138
  | `crossfill(takerOrderId, orders?)` | Fill an open order against the book. |
125
139
  | `swap({selling, buying, amount, direction?, slippage?})` | Swap along the best AXIS API route. |
126
140
  | events | `ready`, `new`, `pending`, `fill`, `filled`, `update`, `cancel`, `expire`, `remove`, `order`, `backing`, `approve`, `trade`, `swap`, `change`, `error` |
@@ -131,7 +145,7 @@ Wraps the on-chain AXIS smart contract for trading and order management.
131
145
 
132
146
  ```js
133
147
  import {Networks, rpc} from '@stellar/stellar-sdk'
134
- import {AxisContractClient, OrderKind, TradeDirection} from '@axis-markets/client'
148
+ import {AxisContractClient, OrderKind, TradeDirection, APPROVAL_TTL_LEDGERS} from '@axis-markets/client'
135
149
 
136
150
  const rpcUrl = 'https://soroban-testnet.stellar.org'
137
151
  const client = new AxisContractClient({
@@ -154,7 +168,7 @@ const [sold, bought, newOrderId] = await client.sell({
154
168
  price: 5n * 10n ** 17n, // at least 0.5 USDC per XLM (18 decimals)
155
169
  orders: [], // maker order ids to cross first (from a direct AXIS API quote)
156
170
  expires: Math.floor(Date.now() / 1000) + 86_400, // optional expiration of the created order (UNIX seconds)
157
- approve: {amount: 100_000_000n, liveUntil: sequence + 518_400} // optional in-call allowance on `selling` (~30 days)
171
+ approve: {amount: 100_000_000n, liveUntil: sequence + APPROVAL_TTL_LEDGERS} // optional in-call allowance on `selling` (~180 days)
158
172
  })
159
173
 
160
174
  // Fetch an order by id
@@ -221,10 +235,10 @@ of the assets to be quoted by the price oracle:
221
235
  - On an existing market the whole `amount` extends the price feeds access of its quoted assets.
222
236
  - `selling` and `buying` must differ (`InvalidMatch`, `704`).
223
237
 
224
- The listing fee is derived: the contract computes it as `daily_fee × listing_min_days` from the oracle's daily
225
- fee, and `loadConfig()` returns both values. `listing_min_days` is 90 at deployment, and the safety admin can set it
226
- from 0 to 255 days. The fee pays one `track` call split across the listed assets, so at 90 days a pair with one listed
227
- asset gets 90 days of feed and a pair with both listed 45 days each.
238
+ The listing fee is derived: the contract computes it as `daily_fee × listing_min_days` from the oracle's daily fee, and
239
+ `loadConfig()` returns both values. `listing_min_days` is 90 at deployment, and the safety admin can set it from 0 to
240
+ 255 days. The fee pays one `track` call split across the listed assets, so at 90 days a pair with one listed asset gets
241
+ 90 days of feed and a pair with both listed 45 days each.
228
242
 
229
243
  `buy`, `sell` and `update` never call the oracle. They value orders against the prices cached by `requote` and
230
244
  `subsidize`, on the selling asset when it is listed and priced and otherwise on the buying asset; no usable price on
@@ -252,17 +266,17 @@ the book are backed by the owner's balance and allowance. Matching never removes
252
266
 
253
267
  A listed order whose maker's backing left does not cover the fill, whose maker cannot receive the taker's asset (a
254
268
  missing or deauthorized trustline), or whose maker's asset cannot be collected is skipped and left unchanged, and a
255
- `skip` event names it. The order owner is the party at fault. In a `crossfill` the skipped order can be the taker
256
- order, whose owner cannot back it or be paid: the call then returns `[0n, 0n, 0n]`.
269
+ `skip` event names it. The order owner is the party at fault. In a `crossfill` the skipped order can be the taker order,
270
+ whose owner cannot back it or be paid: the call then returns `[0n, 0n, 0n]`.
257
271
 
258
- A payment to a maker that fails (the taker cannot pay, or the maker cannot be credited although authorized, e.g. a
259
- full trustline) fails the whole call with the token's own error. The client throws it with `tokenError: true` and
260
- blames neither side.
272
+ A payment to a maker that fails (the taker cannot pay, or the maker cannot be credited although authorized, e.g. a full
273
+ trustline) fails the whole call with the token's own error. The client throws it with `tokenError: true` and blames
274
+ neither side.
261
275
 
262
- A taker who cannot receive the bought asset fails the call with `CannotReceive` (`708`).
263
- The contract cannot hold an asset whose issuer requires authorization (`AUTH_REQUIRED`) until the issuer authorizes
264
- it: buying such an asset fails with `IntermediaryCannotReceive` (`712`). Selling it needs no contract authorization.
265
- A `swap` is strict: any transfer that fails fails the whole call.
276
+ A taker who cannot receive the bought asset fails the call with `CannotReceive` (`708`). The contract cannot hold an
277
+ asset whose issuer requires authorization (`AUTH_REQUIRED`) until the issuer authorizes it: buying such an asset fails
278
+ with `IntermediaryCannotReceive` (`712`). Selling it needs no contract authorization. A `swap` is strict: any transfer
279
+ that fails fails the whole call.
266
280
 
267
281
  Pass `approve: {amount, liveUntil}` to `buy`, `sell` or `swap` to grant (or reset) the allowance on the selling asset as
268
282
  part of the same transaction (set `asset` to approve another token). `update` takes a separate
@@ -456,7 +470,7 @@ trade or swap id; indexers derive one from the ledger, transaction and event pos
456
470
 
457
471
  | Event | Topics | Data | Notes |
458
472
  |---|---|---|---|
459
- | `trade` | `trade, selling, buying` (assets sold and bought by the taker) | `order, taker, maker, sold, bought, left` | One per fill. `left` is the order amount after the fill, `0` when the order was filled in full (or what is left became dust) and removed. Fills emit no order event. In a `crossfill` the maker fills name the taker order owner as the taker, and a last event reports the taker order fill with the caller as the taker. |
473
+ | `trade` | `trade, selling, buying` (assets sold and bought by the taker) | `order, taker, maker, sold, bought, left` | One per fill. `left` is the order amount after the fill, `0` when the order was filled in full (or what is left became dust) and removed. Fills emit no order event. `taker` is the account the fill is made for, never the contract: the trader on every `swap` hop, and the caller on every `crossfill` fill, the maker fills (paid by the taker order owner) and a last event reporting the taker order fill with the owner as the maker alike. Summed per account, the `trade` events of a call give each account's net token movement. |
460
474
  | `swap` | `swap, selling, buying` | `trader, sold, bought` | One per `swap` call, after the fills of every hop. |
461
475
  | `new` | `new, selling, buying` | `id, owner, price, amount, expires` | An order created. `id` is a `u128`, `expires` a `u64` (0 = none). |
462
476
  | `mod` | `mod` | `id, price, amount, expires` | An order changed outside a fill: `update` (new price, amount and expiration) or removal by `update`/`cancel` (`amount = 0`). Nothing is emitted when an order expires. |
@@ -475,9 +489,21 @@ Simulation failures caused by the contract are thrown as `Error` with `message`
475
489
  <name>` and a numeric `code` property. A failure raised by a token the call invoked (a settlement transfer) is thrown as
476
490
  an `Error` with the token's `code`, `tokenError: true` and the token `contract`, named after `TokenErrors` (for example
477
491
  `#10 BalanceError`, which a payer without the balance and a recipient at its trustline limit both raise). Other
478
- simulation failures are rethrown as the raw RPC error string, not an `Error`. A transaction that passes simulation but
479
- fails on-chain throws an `Error` with the transaction `hash` property and the transaction result in its `message`.
480
- `ContractErrors` maps the codes:
492
+ simulation failures are rethrown as the raw RPC error string, not an `Error`.
493
+
494
+ The client signs with the wallet callback (wallet errors pass through as the SDK throws them), then sends the
495
+ transaction over RPC and waits for its result. A submitted transaction that does not go through throws an `Error` with
496
+ the transaction `hash` and a `status`:
497
+
498
+ | `status` | Meaning | Other properties |
499
+ |---|---|---|
500
+ | `ERROR` | The network rejected it, nothing was charged. | `result`: the result code, Horizon style, for example `tx_bad_seq` (another transaction of the account went through first) or `tx_insufficient_fee`. A transaction the RPC server accepted but the network dropped because another transaction of the account used its sequence number is reported the same way. |
501
+ | `TRY_AGAIN_LATER` | Not accepted for now: the network is congested, or another transaction of the account is pending. | |
502
+ | `FAILED` | Applied and failed on-chain, the fee was charged. | `result` (`tx_failed`), `opResult` (for example `invoke_host_function_trapped`), and `code` (plus `tokenError` and `contract`) when the RPC server returns the diagnostic events of the transaction: a call that passed simulation can still fail when the book changes before it applies, for example `709` for a `FillOrKill` trade or a `swap`. |
503
+ | `TIMEOUT` | Not seen before its time bounds expired, it can no longer be included. | |
504
+
505
+ When the RPC server cannot be reached at submission, the client looks the transaction up for a few seconds before
506
+ rethrowing the request error with the transaction `hash`. `ContractErrors` maps the contract codes:
481
507
 
482
508
  | Code | Name | Meaning |
483
509
  |---|---|---|
@@ -1,2 +1,2 @@
1
- !function(A,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("@stellar/stellar-sdk")):"function"==typeof define&&define.amd?define(["@stellar/stellar-sdk"],t):"object"==typeof exports?exports.axisClient=t(require("@stellar/stellar-sdk")):A.axisClient=t(A["@stellar/stellar-sdk"])}(this,A=>(()=>{"use strict";var t={346(t){t.exports=A}},e={};function s(A){var r=e[A];if(void 0!==r)return r.exports;var i=e[A]={exports:{}};return t[A](i,i.exports,s),i.exports}s.d=(A,t)=>{for(var e in t)s.o(t,e)&&!s.o(A,e)&&Object.defineProperty(A,e,{enumerable:!0,get:t[e]})},s.o=(A,t)=>Object.prototype.hasOwnProperty.call(A,t),s.r=A=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(A,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(A,"__esModule",{value:!0})};var r={};s.d(r,{default:()=>hA});var i={};s.r(i),s.d(i,{APPROVAL_RENEW_LEDGERS:()=>O,APPROVAL_TTL_LEDGERS:()=>L,Axis:()=>rA,AxisAccount:()=>_,AxisApiClient:()=>g,AxisApiError:()=>d,AxisContractClient:()=>nA,AxisMarket:()=>P,AxisStreamClient:()=>N,ContractErrors:()=>c,Emitter:()=>J,OrderKind:()=>R,PRICE_SCALE:()=>x,TokenBalance:()=>Q,TokenErrors:()=>o,TradeDirection:()=>F,canonicalPair:()=>M,compareAssets:()=>E,invertPrice:()=>K,invertTicker:()=>j,maxQuoteSpend:()=>$,orderId:()=>C,pairKey:()=>T,parseApiDate:()=>D,parseApiOrder:()=>AA,planApproval:()=>q,toWsUrl:()=>iA});var n=s(346);class a extends n.contract.Client{options;constructor(A){super(new n.contract.Spec(["AAAAAAAAA69Td2FwIHRva2VucyBhY3Jvc3Mgc2V2ZXJhbCBtYXJrZXRzLgpUaGUgY29udHJhY3QgaG9sZHMgdGhlIGludGVybWVkaWF0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FdoZXRoZXIgdGhlIGFzc2V0IGlzIHF1b3RlZCBieSB0aGUgb3JhY2xlICh3aXRoIHRva2VuIGRlY2ltYWxzIHRoZSB2YWx1YXRpb24gY2FuIGhhbmRsZSkAAAAGbGlzdGVkAAAAAAAB"]),A),this.options=A}fromJSON={swap:this.txFromJSON,order:this.txFromJSON,trade:this.txFromJSON,config:this.txFromJSON,freeze:this.txFromJSON,frozen:this.txFromJSON,market:this.txFromJSON,update:this.txFromJSON,requote:this.txFromJSON,delegate:this.txFromJSON,crossfill:this.txFromJSON,set_floor:this.txFromJSON,subsidize:this.txFromJSON,set_oracle:this.txFromJSON,set_ledger_time:this.txFromJSON,set_listing_min_days:this.txFromJSON}}const c={701:{message:"NotAuthorized"},702:{message:"InsufficientBalance"},703:{message:"InsufficientAllowance"},704:{message:"InvalidMatch"},705:{message:"InvalidPrice"},706:{message:"InvalidAmount"},707:{message:"InvalidExpiration"},708:{message:"CannotReceive"},709:{message:"NotFilled"},710:{message:"OrderNotFound"},711:{message:"OrderExists"},712:{message:"IntermediaryCannotReceive"},720:{message:"OrderSizeTooSmall"},721:{message:"AssetsNotVerifiedByOracle"},722:{message:"AssetPriceOracleFetchFailed"},723:{message:"InvalidOracleConfig"},730:{message:"Frozen"},740:{message:"Overflow"}},o={1:{message:"InternalError"},2:{message:"OperationNotSupportedError"},3:{message:"AlreadyInitializedError"},4:{message:"UnauthorizedError"},5:{message:"AuthenticationError"},6:{message:"AccountMissingError"},7:{message:"AccountIsNotClassic"},8:{message:"NegativeAmountError"},9:{message:"AllowanceError"},10:{message:"BalanceError"},11:{message:"BalanceDeauthorizedError"},12:{message:"OverflowError"},13:{message:"TrustlineMissingError"}};function l(A){if(A.simulation?.error){const t=A.simulation.error,e=/HostError: Error\(Contract, #(\d+)\)/.exec(t);if(e){const s=parseInt(e[1],10),r=function(A,t){let e=null;for(const s of A.matchAll(/contract:(C[A-Z2-7]{55}),\s*topics:\[error, Error\(Contract, #(\d+)\)/g))parseInt(s[2],10)===t&&(e={contract:s[1]});return e}(t,s),i=A.options?.contractId;if(r&&i?r.contract!==i:!c[s]&&o[s])throw function(A,t){const e=o[A]?.message||"token error",s=new Error(`Token transfer failed: #${A} ${e}${t?` (token ${t})`:""}. Either side of the transfer may be at fault: the payer's balance or allowance, or the recipient's trustline (e.g. a full trustline limit).`);return s.code=A,s.tokenError=!0,t&&(s.contract=t),s}(s,r?.contract);const n=c[s];if(n){const A=new Error(`Contract execution error: #${s} ${n.message}`);throw A.code=s,A}}throw t}}class d extends Error{constructor(A,t){super(A),this.name="AxisApiError",this.status=t}status}class g{constructor(A){if(!A||"string"!=typeof A)throw new TypeError("AXIS API server URL is required");this.serverUrl=A.replace(/\/+$/,"")}serverUrl;async quoteSell(A){return this.quote(A,"strict_send")}async quoteBuy(A){return this.quote(A,"strict_receive")}async quote({sellingAsset:A,buyingAsset:t,amount:e,direct:s,maxPrice:r},i){return this.request("/quote",{sellingAsset:A,buyingAsset:t,amount:e,direction:i,direct:s,maxPrice:r?.toString()})}async getDepth({market:A,depth:t,step:e,limit:s}){return this.request("/depth",{market:A,depth:t,step:e,limit:s})}async getCandles({market:A,from:t,to:e,resolution:s,order:r}){return this.request("/candles",{market:A,from:t,to:e,resolution:s,order:r})}async getTicker24h(){return this.request("/ticker/24h")}async getMarkets({cursor:A,limit:t}={}){return this.request("/markets",{cursor:A,limit:t})}async getContract(){return this.request("/contract")}async getOrders({owner:A,asset:t,cursor:e,limit:s}={}){return this.request("/order",{owner:A,asset:t,cursor:e,limit:s})}async getAccount(A){return this.request(`/account/${encodeURIComponent(A)}`)}async getOrder(A){return this.request(`/order/${encodeURIComponent(A.toString())}`)}async getOrderHistory({owner:A,pair:t,cursor:e,limit:s}={}){return this.request("/order-history",{owner:A,pair:t,cursor:e,limit:s})}async getTrades({trader:A,pair:t,cursor:e,limit:s}={}){return this.request("/trades",{trader:A,pair:t,cursor:e,limit:s})}async getFailures({account:A,fn:t,cursor:e,limit:s}={}){return this.request("/failures",{account:A,fn:t,cursor:e,limit:s})}async request(A,t){let e=this.serverUrl+A;if(t){const A=new URLSearchParams;for(const[e,s]of Object.entries(t))if(null!=s)if(Array.isArray(s))for(const t of s)A.append(e,t);else A.append(e,s);const s=A.toString();s&&(e+="?"+s)}const s=await fetch(e);let r;try{r=await s.json()}catch(A){r=null}if(!s.ok)throw new d(r?.error||s.statusText,r?.status||s.status);return r}}const h=2e6,u=100000n,b=new Set(["account","trustline"]);function m(...A){const t=new Set,e=[];for(const s of A)if(s)for(const A of s){if(null==A)continue;const s=BigInt(A),r=s.toString();t.has(r)||(t.add(r),e.push(s))}return e}function p(A,t){return W(A,(0,n.nativeToScVal)(BigInt(t),{type:"u128"}),n.xdr.ContractDataDurability.persistent)}function G(A){return W(A,n.xdr.ScVal.scvLedgerKeyContractInstance(),n.xdr.ContractDataDurability.persistent)}function Z(A,t,e){if(!e)return null;if(n.StrKey.isValidContract(A))return W(t,n.xdr.ScVal.scvVec([n.xdr.ScVal.scvSymbol("Balance"),n.Address.fromString(A).toScVal()]),n.xdr.ContractDataDurability.persistent);const s=n.Keypair.fromPublicKey(A).xdrAccountId();return e.isNative()?n.xdr.LedgerKey.account(new n.xdr.LedgerKeyAccount({accountId:s})):e.getIssuer()===A?null:n.xdr.LedgerKey.trustline(new n.xdr.LedgerKeyTrustLine({accountId:s,asset:e.toTrustLineXDRObject()}))}function B(A,t,e){return W(t,n.xdr.ScVal.scvVec([n.xdr.ScVal.scvSymbol("Allowance"),n.xdr.ScVal.scvMap([new n.xdr.ScMapEntry({key:n.xdr.ScVal.scvSymbol("from"),val:n.Address.fromString(A).toScVal()}),new n.xdr.ScMapEntry({key:n.xdr.ScVal.scvSymbol("spender"),val:n.Address.fromString(e).toScVal()})])]),n.xdr.ContractDataDurability.temporary)}function I(A){const[t,e,s]=(0,n.scValToNative)(A);return{owner:t,selling:e,buying:s}}function y(A){if("scvContractInstance"!==A.type||"contractExecutableStellarAsset"!==A.instance.executable.type)return null;const t=(A.instance.storage??[]).find(({key:A})=>"AssetInfo"===(0,n.scValToNative)(A)?.[0]);if(!t)return null;const[e,s]=(0,n.scValToNative)(t.val);if("Native"===e)return n.Asset.native();const r=s.asset_code.replace(/\0+$/,"");return new n.Asset(r,n.StrKey.encodeEd25519PublicKey(s.issuer))}function W(A,t,e){return n.xdr.LedgerKey.contractData(new n.xdr.LedgerKeyContractData({contract:n.Address.fromString(A).toScAddress(),key:t,durability:e}))}function Y(A){const t=A.simulation;return!(!t||t.error||t.restorePreamble||!A.built)}async function V(A,t){const e=new Map;for(let s=0;s<t.length;s+=200){const{entries:r}=await A.getLedgerEntries(...t.slice(s,s+200));for(const A of r)e.set(A.key.toXDR("base64"),A.val)}return e}function w(A,t){return[...new Set(A)].filter(A=>!t.has(A))}function k(A,t,e){for(const s of t){const t=A.get(G(s).toXDR("base64"));e.set(s,t?y(t.contractData.val):null)}}function v(A,t){const e=A.getReadOnly(),s=A.getReadWrite(),r=new Map(e.map((A,t)=>[A.toXDR("base64"),t])),i=new Set(s.map(A=>A.toXDR("base64"))),n=new Set,a=[];for(const A of t){const t=A.toXDR("base64");if(i.has(t))continue;const c=r.has(t),o=e.length-n.size+s.length;s.length>=200||!c&&o>=400||(c&&n.add(r.get(t)),s.push(A),i.add(t),a.push(A))}return a.length&&A.setFootprint(e.filter((A,t)=>!n.has(t)),s),a}function X(A,t,{instructions:e,diskReadBytes:s=0,writeBytes:r,fee:i}){const a=t.build().resources;t.setResources(Math.min(a.instructions+e,4e8),a.diskReadBytes+s,a.writeBytes+r),t.setResourceFee((t.build().resourceFee+i).toString()),delete A.simulationTransactionData;const c=A.options?.timeoutInSeconds??300;A.built=n.TransactionBuilder.cloneFrom(A.built,{sorobanData:t.build(),timebounds:void 0}).setTimeout(c).build()}const f=(1n<<64n)-1n;function C(A,t){if((t=BigInt(t))<0n||t>f)throw new RangeError("Nonce must fit u64");const e=n.xdr.ScVal.scvVec([n.Address.fromString(A).toScVal(),n.xdr.ScVal.scvU64(t)]).toXDR(),s=(0,n.hash)(e);let r=0n;for(let A=0;A<16;A++)r=r<<8n|BigInt(s[A]);return r}const R={Limit:1,Fill:2,FillOrKill:3},F={Sell:1,Buy:2};class J{listeners=new Map;on(A,t){let e=this.listeners.get(A);return e||(e=new Set,this.listeners.set(A,e)),e.add(t),()=>this.off(A,t)}once(A,t){const e=this.on(A,(...A)=>{e(),t(...A)});return e}off(A,t){const e=this.listeners.get(A);e&&(e.delete(t),e.size||this.listeners.delete(A))}emit(A,...t){const e=this.listeners.get(A);if(e)for(const s of[...e])try{s(...t)}catch(t){console.error(`Unhandled error in "${A}" listener`,t)}}}class N extends J{constructor(A,{WebSocket:t,pingInterval:e=2e4,minReconnectDelay:s=1e3,maxReconnectDelay:r=3e4}={}){if(super(),!A||"string"!=typeof A)throw new TypeError("WebSocket URL is required");if(this.url=A,this.WebSocket=t||globalThis.WebSocket,!this.WebSocket)throw new Error("WebSocket is not available in this environment, pass the `WebSocket` option");this.pingInterval=e,this.minReconnectDelay=s,this.maxReconnectDelay=r}url;subscriptions=new Set;topics=new Map;requests=new Map;nextId=1;socket;failures=0;closed=!1;get connected(){return!!this.socket&&1===this.socket.readyState}subscribe(A,t,e){const s={channel:A,params:t||{},handler:e,topic:void 0};return this.subscriptions.add(s),this.closed=!1,this.connected?this.sendSubscribe(s):this.connect(),()=>this.unsubscribe(s)}close(){if(this.closed=!0,this.subscriptions.clear(),this.topics.clear(),this.requests.clear(),clearTimeout(this.reconnectTimer),this.stopPing(),this.socket){const A=this.socket;this.socket=void 0,A.close()}}unsubscribe(A){if(!this.subscriptions.delete(A))return;const{topic:t}=A;if(t){const e=this.topics.get(t);e?.delete(A),e&&!e.size&&(this.topics.delete(t),this.connected&&![...this.subscriptions].some(A=>A.topic===t)&&this.send({op:"unsubscribe",channel:A.channel,...A.params}))}for(const[t,e]of this.requests)e===A&&this.requests.delete(t)}connect(){if(this.socket||this.closed)return;let A;clearTimeout(this.reconnectTimer);try{A=new this.WebSocket(this.url)}catch(A){return void this.scheduleReconnect()}this.socket=A,A.onopen=()=>{if(this.socket===A){this.failures=0,this.lastMessage=Date.now(),this.startPing();for(const A of this.subscriptions)this.sendSubscribe(A);this.emit("open")}},A.onmessage=t=>{if(this.socket!==A)return;let e;this.lastMessage=Date.now();try{e=JSON.parse("string"==typeof t.data?t.data:t.data.toString())}catch(A){return}this.route(e)},A.onclose=()=>{if(this.socket===A){this.socket=void 0,this.stopPing(),this.topics.clear(),this.requests.clear();for(const A of this.subscriptions)A.topic=void 0;this.emit("close"),this.scheduleReconnect()}},A.onerror=()=>{}}scheduleReconnect(){if(this.closed||!this.subscriptions.size)return;const A=Math.min(this.maxReconnectDelay,this.minReconnectDelay*2**this.failures);this.failures++,this.reconnectTimer=setTimeout(()=>this.connect(),A)}startPing(){this.stopPing(),this.pingTimer=setInterval(()=>{Date.now()-this.lastMessage>2*this.pingInterval?this.socket?.close():this.send({op:"ping"})},this.pingInterval)}stopPing(){clearInterval(this.pingTimer),this.pingTimer=void 0}sendSubscribe(A){const t=this.nextId++;this.requests.set(t,A),this.send({op:"subscribe",id:t,channel:A.channel,...A.params})}send(A){this.connected&&this.socket.send(JSON.stringify(A))}route(A){if("pong"!==A.type&&"unsubscribed"!==A.type){if(void 0!==A.id&&this.requests.has(A.id)){const t=this.requests.get(A.id);if(this.requests.delete(A.id),"error"===A.type)return this.subscriptions.delete(t),S(t,A);if(A.topic){t.topic=A.topic;let e=this.topics.get(A.topic);e||(e=new Set,this.topics.set(A.topic,e)),e.add(t)}return S(t,A)}if(A.topic)for(const t of this.topics.get(A.topic)||[])S(t,A);else"error"===A.type&&this.emit("error",new Error(A.error))}}}function S(A,t){try{A.handler(t)}catch(t){console.error(`Unhandled error in the "${A.channel}" subscription handler`,t)}}class Q{constructor({rpcUrl:A,networkPassphrase:t,spender:e,server:s}){this.server=s||new n.rpc.Server(A,{allowHttp:A.startsWith("http://")}),this.networkPassphrase=t,this.spender=e}async getAllowance(A,t){return H(await this.load(A,"allowance",[new n.Address(t).toScVal(),new n.Address(this.spender).toScVal()],t))}async getBalance(A,t){try{return H(await this.load(A,"balance",[new n.Address(t).toScVal()],t))}catch(A){return 0n}}async getLatestLedger(){const{sequence:A}=await this.server.getLatestLedger();return A}async load(A,t,e,s){const r=s.startsWith("G")?s:n.Keypair.random().publicKey(),i=new n.TransactionBuilder(new n.Account(r,"0"),{fee:"100",networkPassphrase:this.networkPassphrase}).addOperation(new n.Contract(A).call(t,...e)).setTimeout(30).build(),a=await this.server.simulateTransaction(i);if(n.rpc.Api.isSimulationError(a))throw new Error(`Token ${t} simulation failed for ${A}: ${a.error}`);return a.result.retval}}function H(A){const t=(0,n.scValToNative)(A);return"bigint"==typeof t?t:BigInt(t??0)}const x=10n**18n,U=new Map;function z(A){let t=U.get(A);return t||(t=n.Address.fromString(A).toScAddress().toXDR(),U.size>=1e4&&U.clear(),U.set(A,t)),t}function E(A,t){if(A===t)return 0;const e=z(A),s=z(t),r=Math.min(e.length,s.length);for(let A=0;A<r;A++)if(e[A]!==s[A])return e[A]-s[A];return e.length-s.length}function M(A,t){return E(A,t)<=0?[A,t]:[t,A]}function T(A,t){const[e,s]=M(A,t);return e+"/"+s}function K(A){return A<=0n?0n:x*x/A}function j(A){const[t,e]=A.symbol.split("/"),s=A=>{const t=Number(A);return t>0?String(1/t):"0"},r=Number(A.openPrice),i=Number(A.lastPrice);return{...A,symbol:e+"/"+t,openPrice:s(A.openPrice),highPrice:s(A.lowPrice),lowPrice:s(A.highPrice),lastPrice:s(A.lastPrice),volume:A.quoteVolume,quoteVolume:A.volume,change:r>0&&i>0?Math.round(1e5*(r/i-1))/1e3:0,avgPrice:s(A.avgPrice)}}function D(A){if(null==A||""===A)return 0;if("number"==typeof A)return A;let t=String(A).trim().replace(" ","T");/[zZ]|[+-]\d\d:?\d\d$/.test(t)||(t+="Z");const e=Date.parse(t);return Number.isFinite(e)?e:0}class P{constructor(A,t){this.axis=A;const[e,s]=M(t.base,t.quote);this.base=e,this.quote=s,this.key=e+"/"+s,this.update(t)}base;quote;key;created=0;refreshed=0;has(A){return A===this.base||A===this.quote}counter(A){if(A===this.base)return this.quote;if(A===this.quote)return this.base;throw new Error(`Asset ${A} does not belong to the market ${this.key}`)}update(A){A.created&&(this.created=D(A.created)),A.refreshed&&(this.refreshed=D(A.refreshed))}async requote(A){return(await this.axis.contractClient(A)).requote(this.base,this.quote)}async subsidize({amount:A,sponsor:t,signer:e}){const s=await this.axis.contractClient(e);return s.subsidize({sponsor:t??s.publicKey,selling:this.base,buying:this.quote,amount:A})}async getDepth({base:A=this.base,depth:t,step:e,limit:s}={}){return this.axis.api.getDepth({market:A+"/"+this.counter(A),depth:t,step:e,limit:s})}subscribeDepth({base:A=this.base,depth:t,step:e,limit:s}={},r){const i=A+"/"+this.counter(A);return this.axis.stream.subscribe("depth",{market:i,depth:t,step:e,limit:s},A=>{"depth"===A.type&&r(A.data)})}subscribeTrades(A){return this.axis.stream.subscribe("trades",{market:this.key},t=>{"trades"===t.type?A(t.trades,!0):"trade"===t.type&&A([t.trade],!1)})}subscribeCandles({base:A=this.base,resolution:t,limit:e},s){const r=A+"/"+this.counter(A);return this.axis.stream.subscribe("candles",{market:r,resolution:t,limit:e},A=>{"candles"===A.type?s(A.candles,!0):"candle"===A.type&&s([A.candle],!1)})}get ticker(){return this.axis.tickers.get(this.key)}toJSON(){return{base:this.base,quote:this.quote,key:this.key,created:this.created,refreshed:this.refreshed}}}const L=518400,O=17280;function q({required:A,committed:t,allowance:e,liveUntil:s,ledger:r}){const i=A+t;if(!(e>=i)||s>0&&s<r+O)return{amount:i,liveUntil:r+L}}function $(A,t){return A<=0n||t<=0n?0n:(A*t+x-1n)/x}class _ extends J{constructor(A,t,{signTransaction:e}={}){super(),this.axis=A,this.address=t,this.signTransaction=e,this.ready=new Promise(A=>this.resolveReady=A)}address;signTransaction;orders=new Map;backing=new Map;ready;loaded=!1;local=new Map;live=!1;spent=new Map;resolveReady;start(){const{stream:A}=this.axis;this.unsubscribe=A.subscribe("account",{address:this.address},A=>this.handle(A)),this.offOpen=A.on("open",()=>this.stopFallback()),this.offClose=A.on("close",()=>{this.live=!1,this.startFallback()}),this.initTimer=setTimeout(()=>{this.loaded||this.refresh().catch(()=>this.startFallback())},3e3)}close(){clearTimeout(this.initTimer),this.stopFallback(),this.unsubscribe?.(),this.offOpen?.(),this.offClose?.(),this.axis.releaseAccount(this)}async refresh(){this.applySnapshot(await this.axis.api.getAccount(this.address),!0)}getOrders({market:A,selling:t,buying:e}={}){const s=function(A){if(A){if("string"==typeof A){const[t,e]=A.split("/");return T(t,e)}return Array.isArray(A)?T(A[0],A[1]):T(A.base,A.quote)}}(A),r=[];for(const A of this.allOrders())s&&A.market!==s||t&&A.selling!==t||e&&A.buying!==e||r.push(A);return r.sort(sA)}getOrder(A){const t=A.toString();return this.orders.get(t)??this.localOrders().find(A=>A.id===t)}committed(A){let t=0n;for(const e of this.allOrders())e.selling===A&&(t+=e.amount);return t}getBalance(A){const t=this.backing.get(A);return t?.updated?t.balance:void 0}get balances(){const A=new Map;for(const[t,e]of this.backing)e.updated&&A.set(t,e.balance);return A}get funded(){const A=this.backing.get(this.axis.nativeAsset);return A?.updated?A.authorized:void 0}getAllowance(A){const t=this.backing.get(A),e=this.committed(A);return t?.updated?{asset:A,known:!0,balance:t.balance,allowance:t.allowance,liveUntil:t.liveUntil,authorized:t.authorized,pending:t.pending,available:t.budget,committed:e}:{asset:A,known:!1,committed:e}}async sell(A){return this.trade(F.Sell,A)}async buy(A){return this.trade(F.Buy,A)}async estimateSell(A){const{payload:t}=await this.prepareTrade(F.Sell,A);return(await this.client()).estimateSell(t)}async estimateBuy(A){const{payload:t}=await this.prepareTrade(F.Buy,A);return(await this.client()).estimateBuy(t)}async update(A){await this.whenReady();const t=A.map(A=>{const t=this.getOrder(A.id);if(!t&&(void 0===A.amount||void 0===A.price))throw new Error(`Order ${A.id} is not an open order of ${this.address}`);return{current:t,update:{id:BigInt(A.id),amount:A.amount??t.amount,price:A.price??t.price,expires:A.expires??t?.expires??0}}}),e=new Map;for(const{current:A,update:s}of t)A&&e.set(A.selling,(e.get(A.selling)??0n)+s.amount-A.amount);const s=[];for(const[A,t]of e){if(t<=0n)continue;const e=await this.planApproval(A,t);e&&(this.emit("approve",{asset:A,...e}),s.push({asset:A,...e}))}const r=await this.client(),i=[];for(let A=0;A<t.length;A+=90){const e=t.slice(A,A+90).map(A=>A.update),n=await r.update({trader:this.address,updates:e,approvals:0===A?s:[]});i.push(...n)}return i}async cancel(A){const t=await this.client(),e=A.map(A=>BigInt(A));for(let A=0;A<e.length;A+=90)await t.cancel(this.address,e.slice(A,A+90));for(const A of e)this.local.delete(A.toString())}async cancelAll({market:A}={}){await this.whenReady();const t=this.getOrders({market:A}).map(A=>A.id);return t.length&&await this.cancel(t),t}async crossfill(A,t){if(!t){const e=this.getOrder(A)??await this.axis.getOrder(A);if(!e)throw new Error(`Order ${A} not found`);t=(await this.findQuote(F.Sell,e.selling,e.buying,e.amount)).orders}const e=await this.client(),[s,r,i]=await e.crossfill(this.address,BigInt(A),t.map(A=>BigInt(A)));return{sold:s,bought:r,surplus:i}}async swap({selling:A,buying:t,amount:e,direction:s=F.Sell,slippage:r=0}){await this.whenReady();const i={sellingAsset:A,buyingAsset:t,amount:e.toString()},n=s===F.Buy?await this.axis.api.quoteBuy(i):await this.axis.api.quoteSell(i),a=n.paths?.[0];if("success"!==n.status||!a?.path?.length)throw new Error(n.error||"No route available");const c=a.path.map(A=>({asset:A.buying,orders:A.orders.filter(Boolean).map(A=>BigInt(A))})),o=BigInt(Math.round(1e4*r));let l=BigInt(a.sold),d=BigInt(a.bought);s===F.Buy?l=(l*(10000n+o)+9999n)/10000n:d=d*(10000n-o)/10000n;const g=await this.planApproval(A,l);g&&this.emit("approve",{asset:A,...g});const h=await this.client(),[u,b]=await h.swap({direction:s,trader:this.address,selling:A,sellingAmount:l,buyingAmount:d,path:c,approve:g});return this.spent.set(A,Date.now()),{sold:u,bought:b,approve:g}}async planApproval(A,t){await this.whenReady();const e=this.backing.get(A);let s;if(this.isAllowanceCurrent(A)||e?.updated&&!this.axis.tokenBalances)s=e.allowance;else{const{tokenBalances:t}=this.axis;if(!t)throw new Error(`The allowance of ${this.address} in ${A} is not tracked: set the \`rpcUrl\` option to read it`);await this.axis.getContractId(),s=await t.getAllowance(A,this.address).catch(()=>0n)}return q({required:t,committed:this.committed(A),allowance:s,liveUntil:e?.liveUntil??0,ledger:await this.axis.getLedger()})}isAllowanceCurrent(A){const t=this.backing.get(A);if(!this.live||!this.axis.stream.connected||!t?.updated||t.pending)return!1;const e=this.spent.get(A);return void 0===e||!(Date.now()-e<3e4)&&(this.spent.delete(A),!0)}async trade(A,t){const{payload:e,planned:s}=await this.prepareTrade(A,t),{selling:r,buying:i,amount:n,price:a,expires:c,approve:o}=e;s&&o&&this.emit("approve",{asset:r,...o});const l=await this.client(),[d,g,h]=A===F.Buy?await l.buy(e):await l.sell(e);let u;return this.spent.set(r,Date.now()),h&&(u=await this.trackCreated(h,{direction:A,selling:r,buying:i,amount:n,price:a,sold:d,bought:g,expires:c})),{sold:d,bought:g,orderId:h?h.toString():void 0,order:u,approve:o}}async prepareTrade(A,{selling:t,buying:e,amount:s,price:r,kind:i,expires:n,orders:a,approve:c}){await this.whenReady(),s=BigInt(s);const o=null==r;let l;if(void 0===i&&(i=o?R.Fill:R.Limit),!a||o){const i=o?void 0:A===F.Buy?BigInt(r):K(BigInt(r));l=await this.findQuote(A,t,e,s,i)}if(o){if(!l.worstPrice)throw new Error("Not enough liquidity for a market order");r=A===F.Buy?l.worstPrice:K(l.worstPrice)}r=BigInt(r);const d=void 0===c;if(d){const e=A===F.Buy?$(s,r):s;c=await this.planApproval(t,e)}return{payload:{kind:i,trader:this.address,amount:s,selling:t,buying:e,price:r,orders:(a??l.orders).map(A=>BigInt(A)),expires:n,approve:c||void 0},planned:d}}async trackCreated(A,{direction:t,selling:e,buying:s,amount:r,price:i,sold:n,bought:a,expires:c}){const o=A.toString();if(this.orders.has(o))return this.orders.get(o);let l,d,g;try{const t=await this.client();l=await t.order(A)}catch(A){}if(this.orders.has(o))return this.orders.get(o);l?(d=l.amount,g=l.price):t===F.Sell?(d=r-n,g=i):(d=$(r-a,i),g=K(i));const h=Date.now(),u={id:o,owner:this.address,selling:e,buying:s,market:T(e,s),status:"ACTIVE",price:g,amount:d,quote:d,expires:Number(l?.expires??c??0),created:h,updated:h,cursor:void 0,backed:null,backedPct:null,backingPending:!0,filledPct:0,pending:!0};return this.local.set(o,{order:u,expires:h+12e4}),this.emit("pending",u),this.emit("change"),u}async findQuote(A,t,e,s,r){const i={sellingAsset:t,buyingAsset:e,amount:s.toString(),direct:!0,maxPrice:r};try{const t=A===F.Buy?await this.axis.api.quoteBuy(i):await this.axis.api.quoteSell(i),e="success"===t.status?t.paths?.[0]?.path?.[0]:null;if(e)return{orders:e.orders??[],worstPrice:e.worstPrice?BigInt(e.worstPrice):null}}catch(A){}return{orders:[],worstPrice:null}}async client(){if(!this.signTransaction)throw new Error(`No signTransaction callback for ${this.address}: pass it to axis.account()`);return this.axis.contractClient({publicKey:this.address,signTransaction:this.signTransaction})}async whenReady(A=15e3){if(this.loaded)return;let t;try{await Promise.race([this.ready,new Promise((e,s)=>{t=setTimeout(()=>s(new Error("The account state is not available: check the AXIS API connection")),A)})])}finally{clearTimeout(t)}}handle(A){switch(A.type){case"account":return this.live=!0,this.applySnapshot(A);case"order":return this.applyOrder(A);case"backing":return this.applyBacking(A);case"trade":return this.emit("trade",A.trade);case"swap":return this.emit("swap",A.swap);case"error":return this.emit("error",new Error(A.error))}}applySnapshot(A,t=!1){const e=this.orders,s=new Map;for(const t of A.orders||[]){const A=AA(t);s.set(A.id,A),this.local.delete(A.id)}this.orders=s;const r=t?new Map(this.backing):new Map;for(const[t,e]of Object.entries(A.backing||{}))r.set(t,tA(t,e));if(this.backing=r,this.loaded){for(const[A,t]of e)s.has(A)||this.emit("remove",t);for(const[A,t]of s)e.has(A)||this.emit("new",t)}this.loaded||(this.loaded=!0,this.resolveReady(),this.emit("ready")),this.emit("change")}applyOrder({action:A,order:t,fill:e}){const s=AA(t);this.local.delete(s.id);const r=this.orders.get(s.id),i="filled"===A||"cancel"===A||"expire"===A;i?this.orders.delete(s.id):(r&&null===s.backed&&(s.backed=r.backed,s.backedPct=r.backedPct,s.backingPending=r.backingPending),this.orders.set(s.id,s));const n=e&&{order:s,sold:BigInt(e.sold),bought:BigInt(e.bought),taker:e.taker,trade:e.trade?.toString(),ts:1e3*Number(e.ts),partial:"fill"===A};this.emit(A,n||s),i&&this.emit("remove",s),this.emit("order",{action:A,order:s,fill:n}),this.emit("change")}applyBacking({asset:A,backing:t,backed:e}){const s=t?tA(A,t):void 0;s?this.backing.set(A,s):this.backing.delete(A);for(const[A,t]of Object.entries(e||{})){const e=this.orders.get(A);e&&(e.backed=BigInt(t),e.backedPct=eA(e.backed,e.amount),e.backingPending=!s||s.pending||!s.updated)}this.emit("backing",{asset:A,backing:s}),this.emit("change")}*allOrders(){yield*this.orders.values(),yield*this.localOrders()}localOrders(){const A=Date.now(),t=[];for(const[e,{order:s,expires:r}]of this.local)r<A||this.orders.has(e)?this.local.delete(e):t.push(s);return t}startFallback(){this.fallbackTimer||(this.fallbackTimer=setInterval(()=>{this.refresh().catch(()=>{})},this.axis.fallbackPollInterval))}stopFallback(){clearInterval(this.fallbackTimer),this.fallbackTimer=void 0}}function AA(A){const t=BigInt(A.amount),e=BigInt(A.quote??A.amount),s=void 0!==A.backed&&!!A.backing?.updated&&!A.backing?.pending,r=void 0!==A.backed?BigInt(A.backed):null;return{id:A.id,owner:A.owner,selling:A.selling,buying:A.buying,market:T(A.selling,A.buying),status:A.status,price:BigInt(A.price),amount:t,quote:e,expires:A.expires?Math.floor(D(A.expires)/1e3):0,created:D(A.created),updated:D(A.updated),cursor:void 0!==A.cursor?BigInt(A.cursor):void 0,backed:r,backedPct:null===r?null:eA(r,t),backingPending:!s,filledPct:e>0n?Math.max(0,Math.min(1,1-Number(10000n*t/e)/1e4)):0,pending:!1}}function tA(A,t){return{asset:A,balance:BigInt(t.balance),allowance:BigInt(t.allowance),liveUntil:t.liveUntil||0,authorized:!1!==t.authorized,budget:BigInt(t.budget??0),updated:D(t.updated),skipped:D(t.skipped),pending:!0===t.pending}}function eA(A,t){return t<=0n?1:Math.max(0,Math.min(1,Number(10000n*A/t)/1e4))}function sA(A,t){return void 0===A.cursor||void 0===t.cursor?(void 0===A.cursor?0:1)-(void 0===t.cursor?0:1)||t.created-A.created:A.cursor<t.cursor?1:A.cursor>t.cursor?-1:0}class rA extends J{constructor({apiUrl:A,wsUrl:t,rpcUrl:e,contractId:s,networkPassphrase:r=n.Networks.PUBLIC,fee:i,signer:a,WebSocket:c,fallbackPollInterval:o=15e3}){super(),this.api=new g(A),this.stream=new N(t||iA(this.api.serverUrl),{WebSocket:c}),this.rpcUrl=e,this.contractId=s,this.networkPassphrase=r,this.fee=i,this.signer=a,this.fallbackPollInterval=o,this.tokenBalances=e?new Q({rpcUrl:e,networkPassphrase:r,spender:s}):void 0,this.nativeAsset=n.Asset.native().contractId(r),this.stream.on("open",()=>{this.stopFallback(),this.emit("connection",!0)}),this.stream.on("close",()=>{this.startFallback(),this.emit("connection",!1)})}api;contractId;stream;tokenBalances;nativeAsset;ledger=0;ledgerTime=0;frozen=!1;config;markets=new Map;tickers=new Map;accounts=new Map;clients=new Map;connecting;get loaded(){return!!this.loadedAt}connect(){return this.connecting||(this.connecting=new Promise((A,t)=>{let e=!1;const s=()=>{e||(e=!0,A(this))},r=A=>{e||(e=!0,this.connecting=void 0,this.unsubscribeContract?.(),t(A))};this.unsubscribeContract=this.stream.subscribe("contract",{},A=>{if(A.ledger&&this.applyLedger(A.ledger),"contract"===A.type){try{this.applyContractSnapshot(A.data)}catch(A){return r(A)}s()}}),this.api.getContract().then(A=>{this.loaded||this.applyContractSnapshot(A),s()},A=>{e||this.stream.connected||(this.startFallback(),r(A))}).catch(r)})),this.connecting}async getContractId(){return this.contractId||await this.connect(),this.contractId}async getLedger(){if(this.ledger&&this.stream.connected&&Date.now()-this.ledgerTime<6e4)return this.ledger;if(this.tokenBalances)return this.tokenBalances.getLatestLedger();if(this.ledger)return this.ledger;throw new Error("The current ledger is unknown: connect to the AXIS API or set the `rpcUrl` option")}getMarket(A,t){return this.markets.get(T(A,t))}async getOrder(A){const t=A.toString();for(const A of this.accounts.values()){const e=A.orders.get(t);if(e)return e}try{return AA(await this.api.getOrder(t))}catch(A){if(A instanceof d&&404===A.status)return;throw A}}account(A,{signTransaction:t}={}){let e=this.accounts.get(A);return e?t&&(e.signTransaction=t):(e=new _(this,A,{signTransaction:t}),this.accounts.set(A,e),e.start()),e}subscribeTicker(A){return this.stream.subscribe("ticker",{},t=>{if("ticker"===t.type){for(const A of t.data.ticker)this.tickers.set(A.symbol,A);A?.(t.data)}})}async keepalive({days:A,signer:t}={}){return(await this.contractClient(t)).keepalive(A)}close(){this.stopFallback(),this.unsubscribeContract?.();for(const A of[...this.accounts.values()])A.close();this.stream.close(),this.connecting=void 0}async contractClient(A=this.signer){if(!A?.publicKey||!A.signTransaction)throw new Error("A signer ({publicKey, signTransaction}) is required to submit transactions");if(!this.rpcUrl)throw new Error("The `rpcUrl` option is required to submit transactions");await this.getContractId();const t=this.clients.get(A.publicKey);if(t&&t.signTransaction===A.signTransaction)return t.client;const e=new nA({publicKey:A.publicKey,signTransaction:A.signTransaction,rpcUrl:this.rpcUrl,contractId:this.contractId,networkPassphrase:this.networkPassphrase,fee:this.fee});return this.clients.set(A.publicKey,{signTransaction:A.signTransaction,client:e}),e}releaseAccount(A){this.accounts.get(A.address)===A&&this.accounts.delete(A.address)}applyContractSnapshot(A){this.checkContractAddress(A.address),this.loadedAt=Date.now();const t=!0===A.frozen;t!==this.frozen&&(this.frozen=t,this.emit("frozen",t)),A.config&&JSON.stringify(A.config)!==JSON.stringify(this.config)&&(this.config=A.config,this.emit("config",A.config));for(const t of A.markets||[]){const A=T(t.base,t.quote),e=this.markets.get(A);if(e)t.refreshed&&e.refreshed!==D(t.refreshed)&&(e.update(t),this.emit("market",{market:e,created:!1}));else{const e=new P(this,t);this.markets.set(A,e),this.emit("market",{market:e,created:!0})}}this.emit("change")}checkContractAddress(A){if(A)if(this.contractId){if(A!==this.contractId)throw new Error(`The AXIS API tracks contract ${A}, not ${this.contractId}`)}else this.setContractId(A);else if(!this.contractId)throw new Error("The AXIS API does not report the contract address: set the `contractId` option")}setContractId(A){this.contractId=A,this.tokenBalances&&(this.tokenBalances.spender=A)}applyLedger(A){this.ledgerTime=Date.now(),A>this.ledger&&(this.ledger=A,this.emit("ledger",A))}startFallback(){!this.fallbackTimer&&this.connecting&&(this.fallbackTimer=setInterval(()=>{this.api.getContract().then(A=>this.applyContractSnapshot(A)).catch(()=>{})},this.fallbackPollInterval))}stopFallback(){clearInterval(this.fallbackTimer),this.fallbackTimer=void 0}}function iA(A){return A.replace(/^http/i,"ws").replace(/\/+$/,"")+"/ws"}class nA{constructor(A){const t={publicKey:A.publicKey,signTransaction:A.signTransaction,rpcUrl:A.rpcUrl,allowHttp:!0,networkPassphrase:A.networkPassphrase||n.Networks.PUBLIC,contractId:A.contractId};this.client=new a(t),this.fee=A.fee||"100000",this.autoFootprint=!1!==A.autoFootprint,this.server=new n.rpc.Server(A.rpcUrl,{allowHttp:!0}),this.assetCache=new Map}get publicKey(){return this.client.options.publicKey}async order(A){const t=await this.client.order({id:A});return l(t),t.result??void 0}async loadConfig(){const A=await this.client.config();return l(A),A.result}async isFrozen(){const A=await this.client.frozen();return l(A),A.result}async getMarket(A,t){const e=await this.client.market({selling:A,buying:t});return l(e),e.result??void 0}async buy(A){return await lA(A,F.Buy,this)}async sell(A){return await lA(A,F.Sell,this)}async estimateBuy(A){return gA(await dA(A,F.Buy,this),this.fee)}async estimateSell(A){return gA(await dA(A,F.Sell,this),this.fee)}async update(A){const t=A.updates.map(A=>({id:A.id,amount:A.amount,price:A.price,expires:BigInt(A.expires??0)})),e=(A.approvals??[]).map(A=>{if(!A.asset)throw new TypeError("An update approval must name its asset");return cA(A,A.asset)}),s=await this.client.update({trader:A.trader,updates:t,approvals:e},{fee:this.fee});return l(s),this.updateFootprint(s,t.map(A=>A.id)),await oA(s)}async cancel(A,t){await this.update({trader:A,updates:t.map(A=>({id:A,amount:0n,price:0n}))})}async crossfill(A,t,e){const s=await this.client.crossfill({trader:A,taker_order_id:t,orders:e},{fee:this.fee});l(s),await this.updateTradeFootprint(s,{takerOrder:t,receiver:A},[t],e);const r=await oA(s);return[r[0],r[1],r[2]]}async swap(A){const t=await this.client.swap({direction:A.direction,trader:A.trader,selling:A.selling,selling_amount:A.sellingAmount,buying_amount:A.buyingAmount,path:A.path.map(A=>({asset:A.asset,orders:A.orders})),approve:cA(A.approve,A.selling)},{fee:this.fee});l(t);const e=A.path.map(A=>A.asset);await this.updateTradeFootprint(t,{tokens:[A.selling,...e],passThrough:e,receiver:A.trader,bought:e[e.length-1]},...A.path.map(A=>A.orders));const s=await oA(t);return[s[0],s[1]]}async requote(A,t){const e=await this.client.requote({selling:A,buying:t},{fee:this.fee});return l(e),e.isReadCall?e.result??void 0:await oA(e)??void 0}async subsidize(A){const t=await this.client.subsidize({sponsor:A.sponsor,selling:A.selling,buying:A.buying,amount:A.amount},{fee:this.fee});return l(t),await oA(t)}async keepalive(A=30){if(!Number.isInteger(A)||A<=0)throw new TypeError(`Invalid keepalive days: ${A}`);const{keys:t,archived:e}=await async function(A,t){const e=new n.Contract(t).getFootprint(),s=await A.getLedgerEntries(e),r=s.entries[0]?.val?.contractData?.val?.instance?.executable;if(!r)throw new Error(`Contract ${t} instance not found`);if(!r.wasmHash)throw new Error(`Contract ${t} has no Wasm code`);const i=n.xdr.LedgerKey.contractCode(new n.xdr.LedgerKeyContractCode({hash:r.wasmHash})),a=await A.getLedgerEntries(i),c=[];return aA(s.entries[0],s.latestLedger)&&c.push(e),a.entries[0]&&!aA(a.entries[0],a.latestLedger)||c.push(i),{keys:[e,i],archived:c}}(this.server,this.client.options.contractId);e.length&&await this.submitFootprintOperation(n.Operation.restoreFootprint({}),(new n.SorobanDataBuilder).setReadWrite(e));const s=Math.ceil(86400*A/await this.loadLedgerTime());return(await this.submitFootprintOperation(n.Operation.extendFootprintTtl({extendTo:s}),(new n.SorobanDataBuilder).setReadOnly(t))).latestLedger+s}async submitFootprintOperation(A,t){const{networkPassphrase:e,signTransaction:s}=this.client.options,r=new n.TransactionBuilder(await this.server.getAccount(this.publicKey),{fee:this.fee,networkPassphrase:e}).addOperation(A).setSorobanData(t.build()).setTimeout(60).build(),i=await this.server.simulateTransaction(r);if(n.rpc.Api.isSimulationError(i))throw new Error(i.error);if(n.rpc.Api.isSimulationRestore(i))throw new Error("The contract instance or code was archived during the keepalive, retry it to restore them");const a=n.rpc.assembleTransaction(r,i).build();if("function"!=typeof s)throw new Error("No signTransaction callback to sign the keepalive transaction");const{signedTxXdr:c,error:o}=await s(a.toXDR(),{networkPassphrase:e,address:this.publicKey});if(o)throw new Error(`Keepalive transaction was not signed: ${o.message??o}`);return await async function(A,t){const e=await A.sendTransaction(t);if("PENDING"!==e.status&&"DUPLICATE"!==e.status)throw new Error(`Transaction ${e.hash} rejected: ${e.errorResult?.result?.type??e.status}`);const s=await A.pollTransaction(e.hash,{attempts:60});if("FAILED"===s.status){const A=new Error(`Transaction ${e.hash} failed: ${s.resultXdr?.result?.type??"unknown result"}`);throw A.hash=e.hash,A}if("SUCCESS"!==s.status)throw new Error(`Transaction ${e.hash} was not included in time`)}(this.server,n.TransactionBuilder.fromXDR(c,e)),i}async loadLedgerTime(){try{return Number((await this.loadConfig())?.ledger_time)||5}catch(A){return 5}}updateFootprint(A,...t){if(this.autoFootprint){const e=m(...t);!function(A,t,e){if(!Y(A)||!e?.length)return 0;const s=A.simulation.transactionData,r=v(s,m(e).map(A=>p(t,A))).length;0===r||X(A,s,{instructions:r*h,writeBytes:320*r,fee:BigInt(r)*u})}(A,this.client.options.contractId,e)}}async updateTradeFootprint(A,t,...e){if(this.autoFootprint){const s=m(...e);await async function(A,t,e,{server:s,tokens:r=[],assetCache:i=new Map,passThrough:n=[],receiver:a,bought:c,takerOrder:o}){if(!Y(A)||!e?.length)return{orders:0,settlementEntries:0,makerEntries:0};const l=m(e),d=l.map(A=>p(t,A)),g=w([...r,...n,...c?[c]:[]],i),y=await V(s,[...d,...g.map(G)]);k(y,g,i);const W=[];for(let A=0;A<l.length;A++){const t=y.get(d[A].toXDR("base64"));t&&W.push({id:l[A],...I(t.contractData.val)})}const f=[...n];if(null!=o){const A=W.find(A=>A.id===BigInt(o));A&&(f.push(A.buying),c??=A.buying)}const C=w(W.flatMap(({selling:A,buying:t})=>[A,t]),i);C.length&&k(await V(s,C.map(G)),C,i);const R=[...[...new Set(f)].map(A=>Z(t,A,i.get(A)??null)),a&&c?Z(a,c,i.get(c)??null):null].filter(Boolean),F=new Set(R.map(A=>A.toXDR("base64"))),J=new Map,N=[];for(const{owner:A,selling:e,buying:s}of W){const r=i.get(e),n=[Z(A,e,r),r?B(A,e,t):null,Z(A,s,i.get(s))];for(const t of n){if(!t)continue;const e=t.toXDR("base64");F.has(e)||(J.set(e,A),N.push(t))}}const S=A.simulation.transactionData,Q=new Set(S.getReadOnly().map(A=>A.toXDR("base64"))),H=v(S,[...d,...R,...N]);if(!H.length)return{orders:0,settlementEntries:0,makerEntries:0};const x=new Set;let U=0,z=0,E=0;for(const A of H){const t=A.toXDR("base64");if(F.has(t))z++;else{if(!J.has(t))continue;U++,x.add(J.get(t))}b.has(A.type)&&!Q.has(t)&&E++}const M=H.length-U-z,T=z>0?1:0;return X(A,S,{instructions:M*h+3e6*x.size+2e6*T,diskReadBytes:256*E,writeBytes:320*M+256*(U+z),fee:BigInt(M)*u+20000n*BigInt(U+z)+20000n*BigInt(x.size)+10000n*BigInt(T)}),{orders:M,settlementEntries:z,makerEntries:U}}(A,this.client.options.contractId,s,{...t,server:this.server,assetCache:this.assetCache})}}}function aA(A,t){return void 0!==A.liveUntilLedgerSeq&&A.liveUntilLedgerSeq<=t}function cA(A,t){if(A)return{asset:A.asset??t,amount:A.amount,live_until:A.liveUntil}}async function oA(A){const t=await A.signAndSend();return function(A){const t=A.getTransactionResponse;if("FAILED"!==t?.status)return;const e=A.sendTransactionResponse?.hash,s=new Error(`Transaction ${e} failed: ${JSON.stringify(t.resultXdr?.result,(A,t)=>"bigint"==typeof t?t.toString():t)}`);throw s.hash=e,s}(t),t.result}async function lA(A,t,e){const s=await oA(await dA(A,t,e));return[s[0],s[1],s[2]??void 0]}async function dA(A,t,e){const s=BigInt(Date.now())<<22n|BigInt(function(){const A=globalThis.crypto;return A?.getRandomValues?4194303&A.getRandomValues(new Uint32Array(1))[0]:Math.floor(4194304*Math.random())}()),r={direction:t,kind:A.kind,trader:A.trader,amount:A.amount,selling:A.selling,buying:A.buying,price:A.price,orders:A.orders??[],nonce:s,expires:BigInt(A.expires??0),approve:cA(A.approve,A.selling)},i=await e.client.trade(r,{fee:e.fee});l(i);const n=A.kind===R.Limit?[C(A.trader,s)]:[];return await e.updateTradeFootprint(i,{tokens:[A.selling,A.buying],passThrough:[A.buying],receiver:A.trader,bought:A.buying},r.orders,n),i}function gA(A,t){const e=BigInt(A.built.fee),[s,r,i]=A.result;return{fee:e,inclusionFee:BigInt(t),resourceFee:e-BigInt(t),sold:s,bought:r,orderId:i??void 0}}const hA={...i};return r.default})());
1
+ !function(A,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("@stellar/stellar-sdk")):"function"==typeof define&&define.amd?define(["@stellar/stellar-sdk"],t):"object"==typeof exports?exports.axisClient=t(require("@stellar/stellar-sdk")):A.axisClient=t(A["@stellar/stellar-sdk"])}(this,A=>(()=>{"use strict";var t={346(t){t.exports=A}},e={};function s(A){var r=e[A];if(void 0!==r)return r.exports;var n=e[A]={exports:{}};return t[A](n,n.exports,s),n.exports}s.d=(A,t)=>{for(var e in t)s.o(t,e)&&!s.o(A,e)&&Object.defineProperty(A,e,{enumerable:!0,get:t[e]})},s.o=(A,t)=>Object.prototype.hasOwnProperty.call(A,t),s.r=A=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(A,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(A,"__esModule",{value:!0})};var r={};s.d(r,{default:()=>XA});var n={};s.r(n),s.d(n,{APPROVAL_RENEW_LEDGERS:()=>eA,APPROVAL_TTL_LEDGERS:()=>tA,Axis:()=>uA,AxisAccount:()=>aA,AxisApiClient:()=>p,AxisApiError:()=>m,AxisContractClient:()=>pA,AxisMarket:()=>_,AxisStreamClient:()=>U,ContractErrors:()=>c,Emitter:()=>x,MAX_APPROVAL_TTL_LEDGERS:()=>AA,OrderKind:()=>Q,PRICE_SCALE:()=>M,TokenBalance:()=>E,TokenErrors:()=>o,TradeDirection:()=>H,canonicalPair:()=>P,compareAssets:()=>D,invertPrice:()=>O,invertTicker:()=>q,maxQuoteSpend:()=>nA,orderId:()=>S,pairKey:()=>L,parseApiDate:()=>$,parseApiOrder:()=>cA,planApproval:()=>sA,planReduction:()=>rA,toWsUrl:()=>bA});var i=s(346);class a extends i.contract.Client{options;constructor(A){super(new i.contract.Spec(["AAAAAAAAA69Td2FwIHRva2VucyBhY3Jvc3Mgc2V2ZXJhbCBtYXJrZXRzLgpUaGUgY29udHJhY3QgaG9sZHMgdGhlIGludGVybWVkaWF0ZSBob3AgcHJvY2VlZHMgb25seSB3aXRoaW4gdGhlIGNhbGwuCgojIEFyZ3VtZW50cwoqIGBkaXJlY3Rpb25gIC0gVHJhZGUgZGlyZWN0aW9uOiBgU2VsbGAgb3IgYEJ1eWAKKiBgdHJhZGVyYCAtIFRyYWRlciBhZGRyZXNzCiogYHNlbGxpbmdgIC0gVG9rZW4gYWRkcmVzcyBzZW50IGJ5IHRoZSB0cmFkZXIKKiBgc2VsbGluZ19hbW91bnRgIC0gQW1vdW50IG9mIHNlbGxpbmcgdG9rZW5zIHRvIHNlbmQgKGBTZWxsYCkgb3IgdGhlIG1heGltdW0gdG8gc3BlbmQgKGBCdXlgKQoqIGBidXlpbmdfYW1vdW50YCAtIE1pbmltdW0gYW1vdW50IG9mIGJ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gY29uZmlndXJhdGlvbgAAAAAMc2FmZXR5X2FkbWluAAAAEw==","AAAAAQAAAB5NYXJrZXQgcmVjb3JkLCBzdG9yZWQgb24tY2hhaW4AAAAAAAAAAAAGTWFya2V0AAAAAAADAAAANEJhc2UgYXNzZXQsIHRoZSBmaXJzdCBvZiB0aGUgcGFpciBpbiBjYW5vbmljYWwgb3JkZXIAAAAEYmFzZQAAB9AAAAAKTWFya2V0U2lkZQAAAAAAEkNyZWF0aW9uIHRpbWVzdGFtcAAAAAAAB2NyZWF0ZWQAAAAABgAAADZRdW90ZSBhc3NldCwgdGhlIHNlY29uZCBvZiB0aGUgcGFpciBpbiBjYW5vbmljYWwgb3JkZXIAAAAAAAVxdW90ZQAAAAAAB9AAAAAKTWFya2V0U2lkZQAA","AAAAAQAAABdNYXJrZXQgYXNzZXQgZGVzY3JpcHRvcgAAAAAAAAAACk1hcmtldFNpZGUAAAAAAAMAAAAWVG9rZW4gY29udHJhY3QgYWRkcmVzcwAAAAAABWFzc2V0AAAAAAAAEwAAAC9Ub2tlbiBkZWNpbWFscyAoZmV0Y2hlZCBvbmx5IGZvciBsaXN0ZWQgYXNzZXRzKQAAAAAIZGVjaW1hbHMAAAAEAAAAWFdoZXRoZXIgdGhlIGFzc2V0IGlzIHF1b3RlZCBieSB0aGUgb3JhY2xlICh3aXRoIHRva2VuIGRlY2ltYWxzIHRoZSB2YWx1YXRpb24gY2FuIGhhbmRsZSkAAAAGbGlzdGVkAAAAAAAB"]),A),this.options=A}fromJSON={swap:this.txFromJSON,order:this.txFromJSON,trade:this.txFromJSON,config:this.txFromJSON,freeze:this.txFromJSON,frozen:this.txFromJSON,market:this.txFromJSON,update:this.txFromJSON,requote:this.txFromJSON,delegate:this.txFromJSON,crossfill:this.txFromJSON,set_floor:this.txFromJSON,subsidize:this.txFromJSON,set_oracle:this.txFromJSON,set_ledger_time:this.txFromJSON,set_listing_min_days:this.txFromJSON}}const c={701:{message:"NotAuthorized"},702:{message:"InsufficientBalance"},703:{message:"InsufficientAllowance"},704:{message:"InvalidMatch"},705:{message:"InvalidPrice"},706:{message:"InvalidAmount"},707:{message:"InvalidExpiration"},708:{message:"CannotReceive"},709:{message:"NotFilled"},710:{message:"OrderNotFound"},711:{message:"OrderExists"},712:{message:"IntermediaryCannotReceive"},720:{message:"OrderSizeTooSmall"},721:{message:"AssetsNotVerifiedByOracle"},722:{message:"AssetPriceOracleFetchFailed"},723:{message:"InvalidOracleConfig"},730:{message:"Frozen"},740:{message:"Overflow"}},o={1:{message:"InternalError"},2:{message:"OperationNotSupportedError"},3:{message:"AlreadyInitializedError"},4:{message:"UnauthorizedError"},5:{message:"AuthenticationError"},6:{message:"AccountMissingError"},7:{message:"AccountIsNotClassic"},8:{message:"NegativeAmountError"},9:{message:"AllowanceError"},10:{message:"BalanceError"},11:{message:"BalanceDeauthorizedError"},12:{message:"OverflowError"},13:{message:"TrustlineMissingError"}};function l(A){if(A.simulation?.error){const t=A.simulation.error,e=/HostError: Error\(Contract, #(\d+)\)/.exec(t);if(e){const s=parseInt(e[1],10),r=d(s,function(A,t){let e=null;for(const s of A.matchAll(/contract:(C[A-Z2-7]{55}),\s*topics:\[error, Error\(Contract, #(\d+)\)/g))parseInt(s[2],10)===t&&(e={contract:s[1]});return e}(t,s)?.contract,A.options?.contractId);if(r)throw r}throw t}}function d(A,t,e){if(t&&e?t!==e:!c[A]&&o[A])return function(A,t){const e=o[A]?.message||"token error",s=new Error(`Token transfer failed: #${A} ${e}${t?` (token ${t})`:""}. Either side of the transfer may be at fault: the payer's balance or allowance, or the recipient's trustline (e.g. a full trustline limit).`);return s.code=A,s.tokenError=!0,t&&(s.contract=t),s}(A,t);const s=c[A];if(!s)return null;const r=new Error(`Contract execution error: #${A} ${s.message}`);return r.code=A,r}function g(A,{hash:t,result:e,resultCode:s,events:r,contractId:n}={}){const i=s??(e?.result?.type?b(e.result.type):void 0),a=function(A){if("txFailed"===A?.result?.type)for(const t of A.result.results||[]){const A="opInner"===t.type?t.tr?.value?.type:t.type;if(A&&!/Success$/.test(A))return b(A)}}(e),c=r?.length?function(A){const t=[];for(const e of A){const A=h(e);void 0!==A&&t.push({code:A,contract:u(e)})}if(!t.length)return;const{code:e}=t[t.length-1];return{code:e,contract:t.find(A=>A.code===e&&A.contract)?.contract}}(r):void 0,o=c?d(c.code,c.contract,n):null;let l;switch(A){case"ERROR":l=`Transaction ${t} was not accepted by the network: ${i??"unknown result"}`;break;case"TRY_AGAIN_LATER":l=`Transaction ${t} was not accepted by the network for now, try again later`;break;case"FAILED":l=`Transaction ${t} failed: ${i??"unknown result"}${a?` (${a})`:""}`;break;default:l=`Transaction ${t} was not confirmed before its time bounds expired`}o&&(l+=`. ${o.message}`);const g=new Error(l);return g.status=A,g.hash=t,i&&(g.result=i),a&&(g.opResult=a),o&&(g.code=o.code,o.tokenError&&(g.tokenError=!0,o.contract&&(g.contract=o.contract))),g}function h(A){const t=A?.event?.body?.value?.topics;if(!t||t.length<2)return;const[e,s]=t;return"scvSymbol"===e.type&&"error"===e.sym.toString()&&"scvError"===s.type&&"sceContract"===s.error.type?s.error.contractCode:void 0}function u(A){const t=A.event.contractId;return t?i.StrKey.encodeContract(t.toBytes()):void 0}function b(A){return A.replace(/[A-Z]/g,A=>"_"+A.toLowerCase())}class m extends Error{constructor(A,t){super(A),this.name="AxisApiError",this.status=t}status}class p{constructor(A){if(!A||"string"!=typeof A)throw new TypeError("AXIS API server URL is required");this.serverUrl=A.replace(/\/+$/,"")}serverUrl;async quoteSell(A){return this.quote(A,"strict_send")}async quoteBuy(A){return this.quote(A,"strict_receive")}async quote({sellingAsset:A,buyingAsset:t,amount:e,direct:s,maxPrice:r},n){return this.request("/quote",{sellingAsset:A,buyingAsset:t,amount:e,direction:n,direct:s,maxPrice:r?.toString()})}async getDepth({market:A,depth:t,step:e,limit:s}){return this.request("/depth",{market:A,depth:t,step:e,limit:s})}async getCandles({market:A,from:t,to:e,resolution:s,order:r}){return this.request("/candles",{market:A,from:t,to:e,resolution:s,order:r})}async getTicker24h(){return this.request("/ticker/24h")}async getMarkets({cursor:A,limit:t}={}){return this.request("/markets",{cursor:A,limit:t})}async getContract(){return this.request("/contract")}async getOrders({owner:A,asset:t,cursor:e,limit:s}={}){return this.request("/order",{owner:A,asset:t,cursor:e,limit:s})}async getAccount(A){return this.request(`/account/${encodeURIComponent(A)}`)}async getOrder(A){return this.request(`/order/${encodeURIComponent(A.toString())}`)}async getOrderHistory({owner:A,pair:t,cursor:e,limit:s}={}){return this.request("/order-history",{owner:A,pair:t,cursor:e,limit:s})}async getTrades({trader:A,pair:t,cursor:e,limit:s}={}){return this.request("/trades",{trader:A,pair:t,cursor:e,limit:s})}async getFailures({account:A,fn:t,cursor:e,limit:s}={}){return this.request("/failures",{account:A,fn:t,cursor:e,limit:s})}async request(A,t){let e=this.serverUrl+A;if(t){const A=new URLSearchParams;for(const[e,s]of Object.entries(t))if(null!=s)if(Array.isArray(s))for(const t of s)A.append(e,t);else A.append(e,s);const s=A.toString();s&&(e+="?"+s)}const s=await fetch(e);let r;try{r=await s.json()}catch(A){r=null}if(!s.ok)throw new m(r?.error||s.statusText,r?.status||s.status);return r}}const G=2e6,Z=100000n,B=new Set(["account","trustline"]);function y(...A){const t=new Set,e=[];for(const s of A)if(s)for(const A of s){if(null==A)continue;const s=BigInt(A),r=s.toString();t.has(r)||(t.add(r),e.push(s))}return e}function I(A,t){return f(A,(0,i.nativeToScVal)(BigInt(t),{type:"u128"}),i.xdr.ContractDataDurability.persistent)}function W(A){return f(A,i.xdr.ScVal.scvLedgerKeyContractInstance(),i.xdr.ContractDataDurability.persistent)}function w(A,t,e){if(!e)return null;if(i.StrKey.isValidContract(A))return f(t,i.xdr.ScVal.scvVec([i.xdr.ScVal.scvSymbol("Balance"),i.Address.fromString(A).toScVal()]),i.xdr.ContractDataDurability.persistent);const s=i.Keypair.fromPublicKey(A).xdrAccountId();return e.isNative()?i.xdr.LedgerKey.account(new i.xdr.LedgerKeyAccount({accountId:s})):e.getIssuer()===A?null:i.xdr.LedgerKey.trustline(new i.xdr.LedgerKeyTrustLine({accountId:s,asset:e.toTrustLineXDRObject()}))}function Y(A,t,e){return f(t,i.xdr.ScVal.scvVec([i.xdr.ScVal.scvSymbol("Allowance"),i.xdr.ScVal.scvMap([new i.xdr.ScMapEntry({key:i.xdr.ScVal.scvSymbol("from"),val:i.Address.fromString(A).toScVal()}),new i.xdr.ScMapEntry({key:i.xdr.ScVal.scvSymbol("spender"),val:i.Address.fromString(e).toScVal()})])]),i.xdr.ContractDataDurability.temporary)}function v(A){const[t,e,s]=(0,i.scValToNative)(A);return{owner:t,selling:e,buying:s}}function V(A){if("scvContractInstance"!==A.type||"contractExecutableStellarAsset"!==A.instance.executable.type)return null;const t=(A.instance.storage??[]).find(({key:A})=>"AssetInfo"===(0,i.scValToNative)(A)?.[0]);if(!t)return null;const[e,s]=(0,i.scValToNative)(t.val);if("Native"===e)return i.Asset.native();const r=s.asset_code.replace(/\0+$/,"");return new i.Asset(r,i.StrKey.encodeEd25519PublicKey(s.issuer))}function f(A,t,e){return i.xdr.LedgerKey.contractData(new i.xdr.LedgerKeyContractData({contract:i.Address.fromString(A).toScAddress(),key:t,durability:e}))}function k(A){const t=A.simulation;return!(!t||t.error||t.restorePreamble||!A.built)}async function X(A,t){const e=new Map;for(let s=0;s<t.length;s+=200){const{entries:r}=await A.getLedgerEntries(...t.slice(s,s+200));for(const A of r)e.set(A.key.toXDR("base64"),A.val)}return e}function R(A,t){return[...new Set(A)].filter(A=>!t.has(A))}function C(A,t,e){for(const s of t){const t=A.get(W(s).toXDR("base64"));e.set(s,t?V(t.contractData.val):null)}}function F(A,t){const e=A.getReadOnly(),s=A.getReadWrite(),r=new Map(e.map((A,t)=>[A.toXDR("base64"),t])),n=new Set(s.map(A=>A.toXDR("base64"))),i=new Set,a=[];for(const A of t){const t=A.toXDR("base64");if(n.has(t))continue;const c=r.has(t),o=e.length-i.size+s.length;s.length>=200||!c&&o>=400||(c&&i.add(r.get(t)),s.push(A),n.add(t),a.push(A))}return a.length&&A.setFootprint(e.filter((A,t)=>!i.has(t)),s),a}function J(A,t,{instructions:e,diskReadBytes:s=0,writeBytes:r,fee:n}){const a=t.build().resources;t.setResources(Math.min(a.instructions+e,4e8),a.diskReadBytes+s,a.writeBytes+r),t.setResourceFee((t.build().resourceFee+n).toString()),delete A.simulationTransactionData;const c=A.options?.timeoutInSeconds??300;A.built=i.TransactionBuilder.cloneFrom(A.built,{sorobanData:t.build(),timebounds:void 0}).setTimeout(c).build()}const N=(1n<<64n)-1n;function S(A,t){if((t=BigInt(t))<0n||t>N)throw new RangeError("Nonce must fit u64");const e=i.xdr.ScVal.scvVec([i.Address.fromString(A).toScVal(),i.xdr.ScVal.scvU64(t)]).toXDR(),s=(0,i.hash)(e);let r=0n;for(let A=0;A<16;A++)r=r<<8n|BigInt(s[A]);return r}const Q={Limit:1,Fill:2,FillOrKill:3},H={Sell:1,Buy:2};class x{listeners=new Map;on(A,t){let e=this.listeners.get(A);return e||(e=new Set,this.listeners.set(A,e)),e.add(t),()=>this.off(A,t)}once(A,t){const e=this.on(A,(...A)=>{e(),t(...A)});return e}off(A,t){const e=this.listeners.get(A);e&&(e.delete(t),e.size||this.listeners.delete(A))}emit(A,...t){const e=this.listeners.get(A);if(e)for(const s of[...e])try{s(...t)}catch(t){console.error(`Unhandled error in "${A}" listener`,t)}}}class U extends x{constructor(A,{WebSocket:t,pingInterval:e=2e4,minReconnectDelay:s=1e3,maxReconnectDelay:r=3e4}={}){if(super(),!A||"string"!=typeof A)throw new TypeError("WebSocket URL is required");if(this.url=A,this.WebSocket=t||globalThis.WebSocket,!this.WebSocket)throw new Error("WebSocket is not available in this environment, pass the `WebSocket` option");this.pingInterval=e,this.minReconnectDelay=s,this.maxReconnectDelay=r}url;subscriptions=new Set;topics=new Map;requests=new Map;nextId=1;socket;failures=0;closed=!1;get connected(){return!!this.socket&&1===this.socket.readyState}subscribe(A,t,e){const s={channel:A,params:t||{},handler:e,topic:void 0};return this.subscriptions.add(s),this.closed=!1,this.connected?this.sendSubscribe(s):this.connect(),()=>this.unsubscribe(s)}close(){if(this.closed=!0,this.subscriptions.clear(),this.topics.clear(),this.requests.clear(),clearTimeout(this.reconnectTimer),this.stopPing(),this.socket){const A=this.socket;this.socket=void 0,A.close()}}unsubscribe(A){if(!this.subscriptions.delete(A))return;const{topic:t}=A;if(t){const e=this.topics.get(t);e?.delete(A),e&&!e.size&&(this.topics.delete(t),this.connected&&![...this.subscriptions].some(A=>A.topic===t)&&this.send({op:"unsubscribe",channel:A.channel,...A.params}))}for(const[t,e]of this.requests)e===A&&this.requests.delete(t)}connect(){if(this.socket||this.closed)return;let A;clearTimeout(this.reconnectTimer);try{A=new this.WebSocket(this.url)}catch(A){return void this.scheduleReconnect()}this.socket=A,A.onopen=()=>{if(this.socket===A){this.failures=0,this.lastMessage=Date.now(),this.startPing();for(const A of this.subscriptions)this.sendSubscribe(A);this.emit("open")}},A.onmessage=t=>{if(this.socket!==A)return;let e;this.lastMessage=Date.now();try{e=JSON.parse("string"==typeof t.data?t.data:t.data.toString())}catch(A){return}this.route(e)},A.onclose=()=>{if(this.socket===A){this.socket=void 0,this.stopPing(),this.topics.clear(),this.requests.clear();for(const A of this.subscriptions)A.topic=void 0;this.emit("close"),this.scheduleReconnect()}},A.onerror=()=>{}}scheduleReconnect(){if(this.closed||!this.subscriptions.size)return;const A=Math.min(this.maxReconnectDelay,this.minReconnectDelay*2**this.failures);this.failures++,this.reconnectTimer=setTimeout(()=>this.connect(),A)}startPing(){this.stopPing(),this.pingTimer=setInterval(()=>{Date.now()-this.lastMessage>2*this.pingInterval?this.socket?.close():this.send({op:"ping"})},this.pingInterval)}stopPing(){clearInterval(this.pingTimer),this.pingTimer=void 0}sendSubscribe(A){const t=this.nextId++;this.requests.set(t,A),this.send({op:"subscribe",id:t,channel:A.channel,...A.params})}send(A){this.connected&&this.socket.send(JSON.stringify(A))}route(A){if("pong"!==A.type&&"unsubscribed"!==A.type){if(void 0!==A.id&&this.requests.has(A.id)){const t=this.requests.get(A.id);if(this.requests.delete(A.id),"error"===A.type)return this.subscriptions.delete(t),z(t,A);if(A.topic){t.topic=A.topic;let e=this.topics.get(A.topic);e||(e=new Set,this.topics.set(A.topic,e)),e.add(t)}return z(t,A)}if(A.topic)for(const t of this.topics.get(A.topic)||[])z(t,A);else"error"===A.type&&this.emit("error",new Error(A.error))}}}function z(A,t){try{A.handler(t)}catch(t){console.error(`Unhandled error in the "${A.channel}" subscription handler`,t)}}class E{constructor({rpcUrl:A,networkPassphrase:t,spender:e,server:s}){this.server=s||new i.rpc.Server(A,{allowHttp:A.startsWith("http://")}),this.networkPassphrase=t,this.spender=e}async getAllowance(A,t){return T(await this.load(A,"allowance",[new i.Address(t).toScVal(),new i.Address(this.spender).toScVal()],t))}async getBalance(A,t){try{return T(await this.load(A,"balance",[new i.Address(t).toScVal()],t))}catch(A){return 0n}}async getLatestLedger(){const{sequence:A}=await this.server.getLatestLedger();return A}async load(A,t,e,s){const r=s.startsWith("G")?s:i.Keypair.random().publicKey(),n=new i.TransactionBuilder(new i.Account(r,"0"),{fee:"100",networkPassphrase:this.networkPassphrase}).addOperation(new i.Contract(A).call(t,...e)).setTimeout(30).build(),a=await this.server.simulateTransaction(n);if(i.rpc.Api.isSimulationError(a))throw new Error(`Token ${t} simulation failed for ${A}: ${a.error}`);return a.result.retval}}function T(A){const t=(0,i.scValToNative)(A);return"bigint"==typeof t?t:BigInt(t??0)}const M=10n**18n,K=new Map;function j(A){let t=K.get(A);return t||(t=i.Address.fromString(A).toScAddress().toXDR(),K.size>=1e4&&K.clear(),K.set(A,t)),t}function D(A,t){if(A===t)return 0;const e=j(A),s=j(t),r=Math.min(e.length,s.length);for(let A=0;A<r;A++)if(e[A]!==s[A])return e[A]-s[A];return e.length-s.length}function P(A,t){return D(A,t)<=0?[A,t]:[t,A]}function L(A,t){const[e,s]=P(A,t);return e+"/"+s}function O(A){return A<=0n?0n:M*M/A}function q(A){const[t,e]=A.symbol.split("/"),s=A=>{const t=Number(A);return t>0?String(1/t):"0"},r=Number(A.openPrice),n=Number(A.lastPrice);return{...A,symbol:e+"/"+t,openPrice:s(A.openPrice),highPrice:s(A.lowPrice),lowPrice:s(A.highPrice),lastPrice:s(A.lastPrice),volume:A.quoteVolume,quoteVolume:A.volume,change:r>0&&n>0?Math.round(1e5*(r/n-1))/1e3:0,avgPrice:s(A.avgPrice)}}function $(A){if(null==A||""===A)return 0;if("number"==typeof A)return A;let t=String(A).trim().replace(" ","T");/[zZ]|[+-]\d\d:?\d\d$/.test(t)||(t+="Z");const e=Date.parse(t);return Number.isFinite(e)?e:0}class _{constructor(A,t){this.axis=A;const[e,s]=P(t.base,t.quote);this.base=e,this.quote=s,this.key=e+"/"+s,this.update(t)}base;quote;key;created=0;refreshed=0;has(A){return A===this.base||A===this.quote}counter(A){if(A===this.base)return this.quote;if(A===this.quote)return this.base;throw new Error(`Asset ${A} does not belong to the market ${this.key}`)}update(A){A.created&&(this.created=$(A.created)),A.refreshed&&(this.refreshed=$(A.refreshed))}async requote(A){return(await this.axis.contractClient(A)).requote(this.base,this.quote)}async subsidize({amount:A,sponsor:t,signer:e}){const s=await this.axis.contractClient(e);return s.subsidize({sponsor:t??s.publicKey,selling:this.base,buying:this.quote,amount:A})}async getDepth({base:A=this.base,depth:t,step:e,limit:s}={}){return this.axis.api.getDepth({market:A+"/"+this.counter(A),depth:t,step:e,limit:s})}subscribeDepth({base:A=this.base,depth:t,step:e,limit:s}={},r){const n=A+"/"+this.counter(A);return this.axis.stream.subscribe("depth",{market:n,depth:t,step:e,limit:s},A=>{"depth"===A.type&&r(A.data)})}subscribeTrades(A){return this.axis.stream.subscribe("trades",{market:this.key},t=>{"trades"===t.type?A(t.trades,!0):"trade"===t.type&&A([t.trade],!1)})}subscribeCandles({base:A=this.base,resolution:t,limit:e},s){const r=A+"/"+this.counter(A);return this.axis.stream.subscribe("candles",{market:r,resolution:t,limit:e},A=>{"candles"===A.type?s(A.candles,!0):"candle"===A.type&&s([A.candle],!1)})}get ticker(){return this.axis.tickers.get(this.key)}toJSON(){return{base:this.base,quote:this.quote,key:this.key,created:this.created,refreshed:this.refreshed}}}const AA=3109680,tA=AA,eA=17280;function sA({required:A,committed:t,allowance:e,liveUntil:s,ledger:r,ttl:n=tA}){const i=A+t;if(!(e>=i)||s>0&&s<r+eA)return{amount:i,liveUntil:r+Math.min(n,AA)}}function rA({target:A,allowance:t,liveUntil:e=0,ledger:s,ttl:r=tA}){if(!(e>0&&e<s||t<=A))return A<=0n?{amount:0n,liveUntil:0}:e>s+eA?{amount:A,liveUntil:e}:{amount:A,liveUntil:s+Math.min(r,AA)}}function nA(A,t){return A<=0n||t<=0n?0n:(A*t+M-1n)/M}const iA=12e4;class aA extends x{constructor(A,t,{signTransaction:e,approvalTtl:s}={}){super(),this.axis=A,this.address=t,this.signTransaction=e,this.approvalTtl=s||tA,this.ready=new Promise(A=>this.resolveReady=A)}address;signTransaction;approvalTtl;orders=new Map;backing=new Map;ready;loaded=!1;local=new Map;live=!1;spent=new Map;queue=Promise.resolve();removed=new Map;approved=new Map;resolveReady;start(){const{stream:A}=this.axis;this.unsubscribe=A.subscribe("account",{address:this.address},A=>this.handle(A)),this.offOpen=A.on("open",()=>this.stopFallback()),this.offClose=A.on("close",()=>{this.live=!1,this.startFallback()}),this.initTimer=setTimeout(()=>{this.loaded||this.refresh().catch(()=>this.startFallback())},3e3)}close(){clearTimeout(this.initTimer),this.stopFallback(),this.unsubscribe?.(),this.offOpen?.(),this.offClose?.(),this.axis.releaseAccount(this)}async refresh(){this.applySnapshot(await this.axis.api.getAccount(this.address),!0)}getOrders({market:A,selling:t,buying:e}={}){const s=function(A){if(A){if("string"==typeof A){const[t,e]=A.split("/");return L(t,e)}return Array.isArray(A)?L(A[0],A[1]):L(A.base,A.quote)}}(A),r=[];for(const A of this.allOrders())s&&A.market!==s||t&&A.selling!==t||e&&A.buying!==e||r.push(A);return r.sort(hA)}getOrder(A){const t=A.toString();if(!this.isRemoved(t))return this.orders.get(t)??this.localOrders().find(A=>A.id===t)}committed(A){let t=0n;for(const e of this.allOrders())e.selling===A&&(t+=e.amount);return t}getBalance(A){const t=this.backing.get(A);return t?.updated?t.balance:void 0}get balances(){const A=new Map;for(const[t,e]of this.backing)e.updated&&A.set(t,e.balance);return A}get funded(){const A=this.backing.get(this.axis.nativeAsset);return A?.updated?A.authorized:void 0}getAllowance(A){const t=this.backing.get(A),e=this.committed(A);return t?.updated?{asset:A,known:!0,balance:t.balance,allowance:t.allowance,liveUntil:t.liveUntil,authorized:t.authorized,pending:t.pending,available:t.budget,committed:e}:{asset:A,known:!1,committed:e}}async sell(A){return this.serialize(()=>this.trade(H.Sell,A))}async buy(A){return this.serialize(()=>this.trade(H.Buy,A))}async estimateSell(A){const{payload:t}=await this.prepareTrade(H.Sell,A);return(await this.client()).estimateSell(t)}async estimateBuy(A){const{payload:t}=await this.prepareTrade(H.Buy,A);return(await this.client()).estimateBuy(t)}async update(A){return this.serialize(async()=>{await this.whenReady();const t=A.map(A=>{const t=this.getOrder(A.id);if(!t&&(void 0===A.amount||void 0===A.price))throw new Error(`Order ${A.id} is not an open order of ${this.address}`);return{current:t,update:{id:BigInt(A.id),amount:A.amount??t.amount,price:A.price??t.price,expires:A.expires??t?.expires??0}}});return this.submitUpdates(t,{grow:!0})})}async cancel(A){await this.serialize(()=>this.removeOrders(A))}async cancelAll({market:A}={}){return this.serialize(async()=>{await this.whenReady();const t=this.getOrders({market:A}).map(A=>A.id);return t.length&&await this.removeOrders(t),t})}async revoke(A,{cancelOrders:t=!1}={}){return this.serialize(async()=>{const e=[...new Set(A)];let s=[];t&&(await this.whenReady(),s=[...this.allOrders()].filter(A=>e.includes(A.selling)).map(A=>A.id));try{const A=await this.removeOrders(s,e);return{revoked:e,canceled:A.map(A=>A.toString())}}catch(A){throw A instanceof Error&&(A.revoked=A.progress?.batches>0?e:[],A.canceled=(A.progress?.updated??[]).map(A=>A.toString())),A}})}async crossfill(A,t){return this.serialize(async()=>{if(!t){const e=this.getOrder(A)??await this.axis.getOrder(A);if(!e)throw new Error(`Order ${A} not found`);t=(await this.findQuote(H.Sell,e.selling,e.buying,e.amount)).orders}const e=await this.client(),[s,r,n]=await e.crossfill(this.address,BigInt(A),t.map(A=>BigInt(A)));return{sold:s,bought:r,surplus:n}})}async swap(A){return this.serialize(()=>this.trySwap(A))}async trySwap({selling:A,buying:t,amount:e,direction:s=H.Sell,slippage:r=0}){await this.whenReady();const n={sellingAsset:A,buyingAsset:t,amount:e.toString()},i=s===H.Buy?await this.axis.api.quoteBuy(n):await this.axis.api.quoteSell(n),a=i.paths?.[0];if("success"!==i.status||!a?.path?.length)throw new Error(i.error||"No route available");const c=a.path.map(A=>({asset:A.buying,orders:A.orders.filter(Boolean).map(A=>BigInt(A))})),o=BigInt(Math.round(1e4*r));let l=BigInt(a.sold),d=BigInt(a.bought);s===H.Buy?l=(l*(10000n+o)+9999n)/10000n:d=d*(10000n-o)/10000n;const g=await this.planApproval(A,l);g&&this.emit("approve",{asset:A,...g});const h=await this.client(),[u,b]=await h.swap({direction:s,trader:this.address,selling:A,sellingAmount:l,buyingAmount:d,path:c,approve:g});return this.spent.set(A,Date.now()),{sold:u,bought:b,approve:g}}async planApproval(A,t){await this.whenReady();const e=await this.readAllowance(A)??0n;return sA({required:t,committed:this.committed(A),allowance:e,liveUntil:this.backing.get(A)?.liveUntil??0,ledger:await this.axis.getLedger(),ttl:this.approvalTtl})}async readAllowance(A){const t=this.backing.get(A);if(this.isAllowanceCurrent(A)||t?.updated&&!this.axis.tokenBalances)return t.allowance;const{tokenBalances:e}=this.axis;if(!e)throw new Error(`The allowance of ${this.address} in ${A} is not tracked: set the \`rpcUrl\` option to read it`);return await this.axis.getContractId(),e.getAllowance(A,this.address).catch(()=>{})}isAllowanceCurrent(A){const t=this.backing.get(A);if(!this.live||!this.axis.stream.connected||!t?.updated||t.pending)return!1;if(this.pendingApproval(A))return!1;const e=this.spent.get(A);return void 0===e||!(Date.now()-e<3e4)&&(this.spent.delete(A),!0)}async trade(A,t){const{payload:e,planned:s}=await this.prepareTrade(A,t),{selling:r,buying:n,amount:i,price:a,expires:c,approve:o}=e;s&&o&&this.emit("approve",{asset:r,...o});const l=await this.client(),[d,g,h]=A===H.Buy?await l.buy(e):await l.sell(e);let u;return this.spent.set(r,Date.now()),h&&(u=await this.trackCreated(h,{direction:A,selling:r,buying:n,amount:i,price:a,sold:d,bought:g,expires:c})),{sold:d,bought:g,orderId:h?h.toString():void 0,order:u,approve:o}}async prepareTrade(A,{selling:t,buying:e,amount:s,price:r,kind:n,expires:i,orders:a,approve:c}){await this.whenReady(),s=BigInt(s);const o=null==r;let l;if(void 0===n&&(n=o?Q.Fill:Q.Limit),!a||o){const n=o?void 0:A===H.Buy?BigInt(r):O(BigInt(r));l=await this.findQuote(A,t,e,s,n)}if(o){if(!l.worstPrice)throw new Error("Not enough liquidity for a market order");r=A===H.Buy?l.worstPrice:O(l.worstPrice)}r=BigInt(r);const d=void 0===c;if(d){const e=A===H.Buy?nA(s,r):s;c=await this.planApproval(t,e)}return{payload:{kind:n,trader:this.address,amount:s,selling:t,buying:e,price:r,orders:(a??l.orders).map(A=>BigInt(A)),expires:i,approve:c||void 0},planned:d}}async trackCreated(A,{direction:t,selling:e,buying:s,amount:r,price:n,sold:i,bought:a,expires:c}){const o=A.toString();if(this.orders.has(o))return this.orders.get(o);let l,d,g;try{const t=await this.client();l=await t.order(A)}catch(A){}if(this.orders.has(o))return this.orders.get(o);l?(d=l.amount,g=l.price):t===H.Sell?(d=r-i,g=n):(d=nA(r-a,n),g=O(n));const h=Date.now(),u={id:o,owner:this.address,selling:e,buying:s,market:L(e,s),status:"ACTIVE",price:g,amount:d,quote:d,expires:Number(l?.expires??c??0),created:h,updated:h,cursor:void 0,backed:null,backedPct:null,backingPending:!0,filledPct:0,pending:!0};return this.local.set(o,{order:u,expires:h+iA}),this.emit("pending",u),this.emit("change"),u}async findQuote(A,t,e,s,r){const n={sellingAsset:t,buyingAsset:e,amount:s.toString(),direct:!0,maxPrice:r};try{const t=A===H.Buy?await this.axis.api.quoteBuy(n):await this.axis.api.quoteSell(n),e="success"===t.status?t.paths?.[0]?.path?.[0]:null;if(e)return{orders:e.orders??[],worstPrice:e.worstPrice?BigInt(e.worstPrice):null}}catch(A){}return{orders:[],worstPrice:null}}serialize(A){const t=this.queue.then(A);return this.queue=t.then(()=>{},()=>{}),t}removeOrders(A,t){const e=A.map(A=>({current:this.getOrder(A),update:{id:BigInt(A),amount:0n,price:0n,expires:0}}));return this.submitUpdates(e,{revoke:t})}async submitUpdates(A,{grow:t=!1,revoke:e=[]}={}){const s=function(A,t){const e=[];let s,r;for(const n of A){const A=n.current?.selling;if(s){const t=r.size+(A&&!r.has(A)?1:0);s.length+1+2*t>90&&(s=void 0)}s||(s=[],r=new Set(e.length?[]:t),e.push(s)),s.push(n),A&&r.add(A)}return!e.length&&t.length&&e.push([]),e}(A,e);if(!s.length)return[];const r=await this.snapshotAllowances(A,e,t),n=await this.client(),i=[];for(let A=0;A<s.length;A++){const a=s[A],c=0===A?e.map(A=>({asset:A,amount:0n,liveUntil:0})):[];r&&c.push(...dA(r,a,t));for(const A of c)this.emit("approve",A);try{i.push(...await n.update({trader:this.address,updates:a.map(A=>A.update),approvals:c}))}catch(t){throw t instanceof Error&&(t.progress={updated:i,batches:A}),t}this.applyBatch(a,c)}return i}async snapshotAllowances(A,t,e){const s=new Set;for(const{current:e}of A)e&&!t.includes(e.selling)&&s.add(e.selling);if(!s.size||!this.loaded)return null;try{const A=await this.axis.getLedger(),t=new Map;for(const e of s){const s=this.backing.get(e)?.liveUntil??0;let r=await this.readAllowance(e);void 0!==r&&s>0&&s<A&&(r=0n),t.set(e,{committed:this.committed(e),allowance:r,liveUntil:s,change:0n})}return{ledger:A,ttl:this.approvalTtl,tokens:t}}catch(A){if(e)throw A;return null}}applyBatch(A,t){const e=Date.now()+iA;for(const{current:t,update:s}of A){const A=s.id.toString();0n===s.amount?(this.local.delete(A),this.orders.has(A)&&this.removed.set(A,e)):t&&Object.assign(t,{amount:s.amount,price:s.price,expires:Number(s.expires)})}for(const{asset:A,amount:e,liveUntil:s}of t){const t=this.backing.get(A);if(this.approved.set(A,{amount:e,liveUntil:s,replaced:t&&{allowance:t.allowance,liveUntil:t.liveUntil},until:Date.now()+36e4}),t){const r=gA(t,e,s);this.backing.set(A,r),this.emit("backing",{asset:A,backing:r})}}this.emit("change")}reconcileBacking(A,t){const e=this.pendingApproval(A);if(!e)return t;const{replaced:s}=e;return s&&t.allowance===s.allowance&&t.liveUntil===s.liveUntil?gA(t,e.amount,e.liveUntil):(this.approved.delete(A),t)}pendingApproval(A){const t=this.approved.get(A);if(!(t&&t.until<Date.now()))return t;this.approved.delete(A)}isRemoved(A){const t=this.removed.get(A);return!(void 0===t||t<Date.now()&&(this.removed.delete(A),1))}async client(){if(!this.signTransaction)throw new Error(`No signTransaction callback for ${this.address}: pass it to axis.account()`);return this.axis.contractClient({publicKey:this.address,signTransaction:this.signTransaction})}async whenReady(A=15e3){if(this.loaded)return;let t;try{await Promise.race([this.ready,new Promise((e,s)=>{t=setTimeout(()=>s(new Error("The account state is not available: check the AXIS API connection")),A)})])}finally{clearTimeout(t)}}handle(A){switch(A.type){case"account":return this.live=!0,this.applySnapshot(A);case"order":return this.applyOrder(A);case"backing":return this.applyBacking(A);case"trade":return this.emit("trade",A.trade);case"swap":return this.emit("swap",A.swap);case"error":return this.emit("error",new Error(A.error))}}applySnapshot(A,t=!1){const e=this.orders,s=new Map;for(const t of A.orders||[]){const A=cA(t);s.set(A.id,A),this.local.delete(A.id)}this.orders=s;for(const A of this.removed.keys())s.has(A)||this.removed.delete(A);const r=t?new Map(this.backing):new Map;for(const[t,e]of Object.entries(A.backing||{}))r.set(t,this.reconcileBacking(t,oA(t,e)));if(this.backing=r,this.loaded){for(const[A,t]of e)s.has(A)||this.emit("remove",t);for(const[A,t]of s)e.has(A)||this.emit("new",t)}this.loaded||(this.loaded=!0,this.resolveReady(),this.emit("ready")),this.emit("change")}applyOrder({action:A,order:t,fill:e}){const s=cA(t);this.local.delete(s.id);const r=this.orders.get(s.id),n="filled"===A||"cancel"===A||"expire"===A;n?(this.orders.delete(s.id),this.removed.delete(s.id)):(r&&null===s.backed&&(s.backed=r.backed,s.backedPct=r.backedPct,s.backingPending=r.backingPending),this.orders.set(s.id,s));const i=e&&{order:s,sold:BigInt(e.sold),bought:BigInt(e.bought),taker:e.taker,trade:e.trade?.toString(),ts:1e3*Number(e.ts),partial:"fill"===A};this.emit(A,i||s),n&&this.emit("remove",s),this.emit("order",{action:A,order:s,fill:i}),this.emit("change")}applyBacking({asset:A,backing:t,backed:e}){const s=t?this.reconcileBacking(A,oA(A,t)):void 0;s?this.backing.set(A,s):this.backing.delete(A);for(const[A,t]of Object.entries(e||{})){const e=this.orders.get(A);e&&(e.backed=BigInt(t),e.backedPct=lA(e.backed,e.amount),e.backingPending=!s||s.pending||!s.updated)}this.emit("backing",{asset:A,backing:s}),this.emit("change")}*allOrders(){for(const A of this.orders.values())this.isRemoved(A.id)||(yield A);yield*this.localOrders()}localOrders(){const A=Date.now(),t=[];for(const[e,{order:s,expires:r}]of this.local)r<A||this.orders.has(e)?this.local.delete(e):t.push(s);return t}startFallback(){this.fallbackTimer||(this.fallbackTimer=setInterval(()=>{this.refresh().catch(()=>{})},this.axis.fallbackPollInterval))}stopFallback(){clearInterval(this.fallbackTimer),this.fallbackTimer=void 0}}function cA(A){const t=BigInt(A.amount),e=BigInt(A.quote??A.amount),s=void 0!==A.backed&&!!A.backing?.updated&&!A.backing?.pending,r=void 0!==A.backed?BigInt(A.backed):null;return{id:A.id,owner:A.owner,selling:A.selling,buying:A.buying,market:L(A.selling,A.buying),status:A.status,price:BigInt(A.price),amount:t,quote:e,expires:A.expires?Math.floor($(A.expires)/1e3):0,created:$(A.created),updated:$(A.updated),cursor:void 0!==A.cursor?BigInt(A.cursor):void 0,backed:r,backedPct:null===r?null:lA(r,t),backingPending:!s,filledPct:e>0n?Math.max(0,Math.min(1,1-Number(10000n*t/e)/1e4)):0,pending:!1}}function oA(A,t){return{asset:A,balance:BigInt(t.balance),allowance:BigInt(t.allowance),liveUntil:t.liveUntil||0,authorized:!1!==t.authorized,budget:BigInt(t.budget??0),updated:$(t.updated),skipped:$(t.skipped),pending:!0===t.pending}}function lA(A,t){return t<=0n?1:Math.max(0,Math.min(1,Number(10000n*A/t)/1e4))}function dA({ledger:A,ttl:t,tokens:e},s,r){const n=new Map;for(const{current:A,update:t}of s){if(!A||!e.has(A.selling))continue;const s=n.get(A.selling)??{delta:0n,need:0n};s.delta+=t.amount-A.amount,s.need+=t.amount,n.set(A.selling,s)}const i=[];for(const[s,{delta:a,need:c}]of n){const n=e.get(s);let o;n.change+=a,r&&(a>0n||(n.allowance??0n)<c)?o=sA({required:n.change,committed:n.committed,allowance:n.allowance??0n,liveUntil:n.liveUntil,ledger:A,ttl:t}):a<0n&&void 0!==n.allowance&&(o=rA({target:n.committed+n.change,allowance:n.allowance,liveUntil:n.liveUntil,ledger:A,ttl:t})),o&&(i.push({asset:s,...o}),n.allowance=o.amount,n.liveUntil=o.liveUntil)}return i}function gA(A,t,e){const s=A.authorized?A.balance<t?A.balance:t:0n;return{...A,allowance:t,liveUntil:e,budget:s}}function hA(A,t){return void 0===A.cursor||void 0===t.cursor?(void 0===A.cursor?0:1)-(void 0===t.cursor?0:1)||t.created-A.created:A.cursor<t.cursor?1:A.cursor>t.cursor?-1:0}class uA extends x{constructor({apiUrl:A,wsUrl:t,rpcUrl:e,contractId:s,networkPassphrase:r=i.Networks.PUBLIC,fee:n,signer:a,WebSocket:c,fallbackPollInterval:o=15e3}){super(),this.api=new p(A),this.stream=new U(t||bA(this.api.serverUrl),{WebSocket:c}),this.rpcUrl=e,this.contractId=s,this.networkPassphrase=r,this.fee=n,this.signer=a,this.fallbackPollInterval=o,this.tokenBalances=e?new E({rpcUrl:e,networkPassphrase:r,spender:s}):void 0,this.nativeAsset=i.Asset.native().contractId(r),this.stream.on("open",()=>{this.stopFallback(),this.emit("connection",!0)}),this.stream.on("close",()=>{this.startFallback(),this.emit("connection",!1)})}api;contractId;stream;tokenBalances;nativeAsset;ledger=0;ledgerTime=0;frozen=!1;config;markets=new Map;tickers=new Map;accounts=new Map;clients=new Map;connecting;get loaded(){return!!this.loadedAt}connect(){return this.connecting||(this.connecting=new Promise((A,t)=>{let e=!1;const s=()=>{e||(e=!0,A(this))},r=A=>{e||(e=!0,this.connecting=void 0,this.unsubscribeContract?.(),t(A))};this.unsubscribeContract=this.stream.subscribe("contract",{},A=>{if(A.ledger&&this.applyLedger(A.ledger),"contract"===A.type){try{this.applyContractSnapshot(A.data)}catch(A){return r(A)}s()}}),this.api.getContract().then(A=>{this.loaded||this.applyContractSnapshot(A),s()},A=>{e||this.stream.connected||(this.startFallback(),r(A))}).catch(r)})),this.connecting}async getContractId(){return this.contractId||await this.connect(),this.contractId}async getLedger(){if(this.ledger&&this.stream.connected&&Date.now()-this.ledgerTime<6e4)return this.ledger;if(this.tokenBalances)return this.tokenBalances.getLatestLedger();if(this.ledger)return this.ledger;throw new Error("The current ledger is unknown: connect to the AXIS API or set the `rpcUrl` option")}getMarket(A,t){return this.markets.get(L(A,t))}async getOrder(A){const t=A.toString();for(const A of this.accounts.values()){const e=A.orders.get(t);if(e)return e}try{return cA(await this.api.getOrder(t))}catch(A){if(A instanceof m&&404===A.status)return;throw A}}account(A,{signTransaction:t,approvalTtl:e}={}){let s=this.accounts.get(A);return s?(t&&(s.signTransaction=t),e&&(s.approvalTtl=e)):(s=new aA(this,A,{signTransaction:t,approvalTtl:e}),this.accounts.set(A,s),s.start()),s}subscribeTicker(A){return this.stream.subscribe("ticker",{},t=>{if("ticker"===t.type){for(const A of t.data.ticker)this.tickers.set(A.symbol,A);A?.(t.data)}})}async keepalive({days:A,signer:t}={}){return(await this.contractClient(t)).keepalive(A)}close(){this.stopFallback(),this.unsubscribeContract?.();for(const A of[...this.accounts.values()])A.close();this.stream.close(),this.connecting=void 0}async contractClient(A=this.signer){if(!A?.publicKey||!A.signTransaction)throw new Error("A signer ({publicKey, signTransaction}) is required to submit transactions");if(!this.rpcUrl)throw new Error("The `rpcUrl` option is required to submit transactions");await this.getContractId();const t=this.clients.get(A.publicKey);if(t&&t.signTransaction===A.signTransaction)return t.client;const e=new pA({publicKey:A.publicKey,signTransaction:A.signTransaction,rpcUrl:this.rpcUrl,contractId:this.contractId,networkPassphrase:this.networkPassphrase,fee:this.fee});return this.clients.set(A.publicKey,{signTransaction:A.signTransaction,client:e}),e}releaseAccount(A){this.accounts.get(A.address)===A&&this.accounts.delete(A.address)}applyContractSnapshot(A){this.checkContractAddress(A.address),this.loadedAt=Date.now();const t=!0===A.frozen;t!==this.frozen&&(this.frozen=t,this.emit("frozen",t)),A.config&&JSON.stringify(A.config)!==JSON.stringify(this.config)&&(this.config=A.config,this.emit("config",A.config));for(const t of A.markets||[]){const A=L(t.base,t.quote),e=this.markets.get(A);if(e)t.refreshed&&e.refreshed!==$(t.refreshed)&&(e.update(t),this.emit("market",{market:e,created:!1}));else{const e=new _(this,t);this.markets.set(A,e),this.emit("market",{market:e,created:!0})}}this.emit("change")}checkContractAddress(A){if(A)if(this.contractId){if(A!==this.contractId)throw new Error(`The AXIS API tracks contract ${A}, not ${this.contractId}`)}else this.setContractId(A);else if(!this.contractId)throw new Error("The AXIS API does not report the contract address: set the `contractId` option")}setContractId(A){this.contractId=A,this.tokenBalances&&(this.tokenBalances.spender=A)}applyLedger(A){this.ledgerTime=Date.now(),A>this.ledger&&(this.ledger=A,this.emit("ledger",A))}startFallback(){!this.fallbackTimer&&this.connecting&&(this.fallbackTimer=setInterval(()=>{this.api.getContract().then(A=>this.applyContractSnapshot(A)).catch(()=>{})},this.fallbackPollInterval))}stopFallback(){clearInterval(this.fallbackTimer),this.fallbackTimer=void 0}}function bA(A){return A.replace(/^http/i,"ws").replace(/\/+$/,"")+"/ws"}const mA=Symbol("superseded");class pA{constructor(A){const t={publicKey:A.publicKey,signTransaction:A.signTransaction,rpcUrl:A.rpcUrl,allowHttp:!0,networkPassphrase:A.networkPassphrase||i.Networks.PUBLIC,contractId:A.contractId};this.client=new a(t),this.fee=A.fee||"100000",this.autoFootprint=!1!==A.autoFootprint,this.server=new i.rpc.Server(A.rpcUrl,{allowHttp:!0}),this.assetCache=new Map}get publicKey(){return this.client.options.publicKey}async order(A){const t=await this.client.order({id:A});return l(t),t.result??void 0}async loadConfig(){const A=await this.client.config();return l(A),A.result}async isFrozen(){const A=await this.client.frozen();return l(A),A.result}async getMarket(A,t){const e=await this.client.market({selling:A,buying:t});return l(e),e.result??void 0}async buy(A){return await VA(A,H.Buy,this)}async sell(A){return await VA(A,H.Sell,this)}async estimateBuy(A){return kA(await fA(A,H.Buy,this),this.fee)}async estimateSell(A){return kA(await fA(A,H.Sell,this),this.fee)}async update(A){const t=A.updates.map(A=>({id:A.id,amount:A.amount,price:A.price,expires:BigInt(A.expires??0)})),e=(A.approvals??[]).map(A=>{if(!A.asset)throw new TypeError("An update approval must name its asset");return YA(A,A.asset)}),s=await this.client.update({trader:A.trader,updates:t,approvals:e},{fee:this.fee});return l(s),this.updateFootprint(s,t.map(A=>A.id)),await vA(s)}async cancel(A,t){await this.update({trader:A,updates:t.map(A=>({id:A,amount:0n,price:0n}))})}async crossfill(A,t,e){const s=await this.client.crossfill({trader:A,taker_order_id:t,orders:e},{fee:this.fee});l(s),await this.updateTradeFootprint(s,{takerOrder:t,receiver:A},[t],e);const r=await vA(s);return[r[0],r[1],r[2]]}async swap(A){const t=await this.client.swap({direction:A.direction,trader:A.trader,selling:A.selling,selling_amount:A.sellingAmount,buying_amount:A.buyingAmount,path:A.path.map(A=>({asset:A.asset,orders:A.orders})),approve:YA(A.approve,A.selling)},{fee:this.fee});l(t);const e=A.path.map(A=>A.asset);await this.updateTradeFootprint(t,{tokens:[A.selling,...e],passThrough:e,receiver:A.trader,bought:e[e.length-1]},...A.path.map(A=>A.orders));const s=await vA(t);return[s[0],s[1]]}async requote(A,t){const e=await this.client.requote({selling:A,buying:t},{fee:this.fee});return l(e),e.isReadCall?e.result??void 0:await vA(e)??void 0}async subsidize(A){const t=await this.client.subsidize({sponsor:A.sponsor,selling:A.selling,buying:A.buying,amount:A.amount},{fee:this.fee});return l(t),await vA(t)}async keepalive(A=30){if(!Number.isInteger(A)||A<=0)throw new TypeError(`Invalid keepalive days: ${A}`);const{keys:t,archived:e}=await async function(A,t){const e=new i.Contract(t).getFootprint(),s=await A.getLedgerEntries(e),r=s.entries[0]?.val?.contractData?.val?.instance?.executable;if(!r)throw new Error(`Contract ${t} instance not found`);if(!r.wasmHash)throw new Error(`Contract ${t} has no Wasm code`);const n=i.xdr.LedgerKey.contractCode(new i.xdr.LedgerKeyContractCode({hash:r.wasmHash})),a=await A.getLedgerEntries(n),c=[];return GA(s.entries[0],s.latestLedger)&&c.push(e),a.entries[0]&&!GA(a.entries[0],a.latestLedger)||c.push(n),{keys:[e,n],archived:c}}(this.server,this.client.options.contractId);e.length&&await this.submitFootprintOperation(i.Operation.restoreFootprint({}),(new i.SorobanDataBuilder).setReadWrite(e));const s=Math.ceil(86400*A/await this.loadLedgerTime());return(await this.submitFootprintOperation(i.Operation.extendFootprintTtl({extendTo:s}),(new i.SorobanDataBuilder).setReadOnly(t))).latestLedger+s}async submitFootprintOperation(A,t){const{networkPassphrase:e,signTransaction:s}=this.client.options,r=new i.TransactionBuilder(await this.server.getAccount(this.publicKey),{fee:this.fee,networkPassphrase:e}).addOperation(A).setSorobanData(t.build()).setTimeout(60).build(),n=await this.server.simulateTransaction(r);if(i.rpc.Api.isSimulationError(n))throw new Error(n.error);if(i.rpc.Api.isSimulationRestore(n))throw new Error("The contract instance or code was archived during the keepalive, retry it to restore them");const a=i.rpc.assembleTransaction(r,n).build();if("function"!=typeof s)throw new Error("No signTransaction callback to sign the keepalive transaction");const{signedTxXdr:c,error:o}=await s(a.toXDR(),{networkPassphrase:e,address:this.publicKey});if(o)throw new Error(`Keepalive transaction was not signed: ${o.message??o}`);return await ZA(this.server,i.TransactionBuilder.fromXDR(c,e)),n}async loadLedgerTime(){try{return Number((await this.loadConfig())?.ledger_time)||5}catch(A){return 5}}updateFootprint(A,...t){if(this.autoFootprint){const e=y(...t);!function(A,t,e){if(!k(A)||!e?.length)return 0;const s=A.simulation.transactionData,r=F(s,y(e).map(A=>I(t,A))).length;0===r||J(A,s,{instructions:r*G,writeBytes:320*r,fee:BigInt(r)*Z})}(A,this.client.options.contractId,e)}}async updateTradeFootprint(A,t,...e){if(this.autoFootprint){const s=y(...e);await async function(A,t,e,{server:s,tokens:r=[],assetCache:n=new Map,passThrough:i=[],receiver:a,bought:c,takerOrder:o}){if(!k(A)||!e?.length)return{orders:0,settlementEntries:0,makerEntries:0};const l=y(e),d=l.map(A=>I(t,A)),g=R([...r,...i,...c?[c]:[]],n),h=await X(s,[...d,...g.map(W)]);C(h,g,n);const u=[];for(let A=0;A<l.length;A++){const t=h.get(d[A].toXDR("base64"));t&&u.push({id:l[A],...v(t.contractData.val)})}const b=[...i];if(null!=o){const A=u.find(A=>A.id===BigInt(o));A&&(b.push(A.buying),c??=A.buying)}const m=R(u.flatMap(({selling:A,buying:t})=>[A,t]),n);m.length&&C(await X(s,m.map(W)),m,n);const p=[...[...new Set(b)].map(A=>w(t,A,n.get(A)??null)),a&&c?w(a,c,n.get(c)??null):null].filter(Boolean),V=new Set(p.map(A=>A.toXDR("base64"))),f=new Map,N=[];for(const{owner:A,selling:e,buying:s}of u){const r=n.get(e),i=[w(A,e,r),r?Y(A,e,t):null,w(A,s,n.get(s))];for(const t of i){if(!t)continue;const e=t.toXDR("base64");V.has(e)||(f.set(e,A),N.push(t))}}const S=A.simulation.transactionData,Q=new Set(S.getReadOnly().map(A=>A.toXDR("base64"))),H=F(S,[...d,...p,...N]);if(!H.length)return{orders:0,settlementEntries:0,makerEntries:0};const x=new Set;let U=0,z=0,E=0;for(const A of H){const t=A.toXDR("base64");if(V.has(t))z++;else{if(!f.has(t))continue;U++,x.add(f.get(t))}B.has(A.type)&&!Q.has(t)&&E++}const T=H.length-U-z,M=z>0?1:0;return J(A,S,{instructions:T*G+3e6*x.size+2e6*M,diskReadBytes:256*E,writeBytes:320*T+256*(U+z),fee:BigInt(T)*Z+20000n*BigInt(U+z)+20000n*BigInt(x.size)+10000n*BigInt(M)}),{orders:T,settlementEntries:z,makerEntries:U}}(A,this.client.options.contractId,s,{...t,server:this.server,assetCache:this.assetCache})}}}function GA(A,t){return void 0!==A.liveUntilLedgerSeq&&A.liveUntilLedgerSeq<=t}async function ZA(A,t,e){const s=(r=t.hash(),Array.from(r,A=>A.toString(16).padStart(2,"0")).join(""));var r;let n;try{n=await A.sendTransaction(t)}catch(r){const n=await BA(A,t,s,{window:3e4,maxFailures:3});if(!n)throw r instanceof Error&&(r.hash=s),r;return WA(n,s,e)}if("ERROR"===n.status)throw g("ERROR",{hash:s,result:n.errorResult,events:n.diagnosticEvents,contractId:e});if("TRY_AGAIN_LATER"===n.status)throw g("TRY_AGAIN_LATER",{hash:s});const i=await BA(A,t,s);if(!i)throw g("TIMEOUT",{hash:s});return WA(i,s,e)}async function BA(A,t,e,{window:s,maxFailures:r}={}){const n=Date.now(),i=Number(t.timeBounds?.maxTime)||0;let a,c=0;for(let o=1;;o++){let l;try{l=await A.getTransaction(e),c=0}catch(A){c++}if(l&&"NOT_FOUND"!==l.status)return l;if(void 0!==a&&l?.latestLedger>=a)return mA;if(void 0===a&&l&&o>=3&&(a=await yA(A,t)),r&&c>=r)return;if(s&&Date.now()-n>=s)return;if(IA(l,i,n))return;await new Promise(A=>setTimeout(A,Math.min(1e3*o,3e3)))}}async function yA(A,t){try{const e=i.xdr.LedgerKey.account(new i.xdr.LedgerKeyAccount({accountId:i.Keypair.fromPublicKey(t.source).xdrPublicKey()})),{entries:s,latestLedger:r}=await A.getLedgerEntries(e),n=s[0]?.val?.value?.seqNum;return void 0!==n&&BigInt(n)>=BigInt(t.sequence)?r:void 0}catch(A){return}}function IA(A,t,e){if(!t)return Date.now()-e>=3e5;const s=Number(A?.latestLedgerCloseTime);return s?s>t:Date.now()/1e3>t+15}function WA(A,t,e){if(A===mA)throw g("ERROR",{hash:t,resultCode:"tx_bad_seq"});if("FAILED"===A.status)throw g("FAILED",{hash:t,result:A.resultXdr,events:wA(A),contractId:e});return A}function wA(A){if(A.diagnosticEventsXdr?.length)return A.diagnosticEventsXdr;const t=A.resultMetaXdr?.value;return t?.diagnosticEvents??t?.sorobanMeta?.diagnosticEvents??[]}function YA(A,t){if(A)return{asset:A.asset??t,amount:A.amount,live_until:A.liveUntil}}async function vA(A){await A.sign();const t=await ZA(A.server,A.signed,A.options.contractId);return void 0===t.returnValue?void 0:A.options.parseResultXdr(t.returnValue)}async function VA(A,t,e){const s=await vA(await fA(A,t,e));return[s[0],s[1],s[2]??void 0]}async function fA(A,t,e){const s=BigInt(Date.now())<<22n|BigInt(function(){const A=globalThis.crypto;return A?.getRandomValues?4194303&A.getRandomValues(new Uint32Array(1))[0]:Math.floor(4194304*Math.random())}()),r={direction:t,kind:A.kind,trader:A.trader,amount:A.amount,selling:A.selling,buying:A.buying,price:A.price,orders:A.orders??[],nonce:s,expires:BigInt(A.expires??0),approve:YA(A.approve,A.selling)},n=await e.client.trade(r,{fee:e.fee});l(n);const i=A.kind===Q.Limit?[S(A.trader,s)]:[];return await e.updateTradeFootprint(n,{tokens:[A.selling,A.buying],passThrough:[A.buying],receiver:A.trader,bought:A.buying},r.orders,i),n}function kA(A,t){const e=BigInt(A.built.fee),[s,r,n]=A.result;return{fee:e,inclusionFee:BigInt(t),resourceFee:e-BigInt(t),sold:s,bought:r,orderId:n??void 0}}const XA={...n};return r.default})());
2
2
  //# sourceMappingURL=axis-client.cjs.map