@gala-chain/gswap-sdk 1.1.0 → 1.2.0-rc.1
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 +14 -5
- package/dist/browser/index.js +4 -3
- package/dist/browser/index.js.map +1 -1
- package/dist/index.cjs +2995 -600
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1806 -451
- package/dist/index.d.ts +1806 -451
- package/dist/index.mjs +2933 -598
- package/dist/index.mjs.map +1 -1
- package/package.json +10 -6
package/README.md
CHANGED
|
@@ -65,11 +65,11 @@ See the [realtime stream guide](./docs/docs/tutorial-basics/realtime-stream.md).
|
|
|
65
65
|
|
|
66
66
|
## Signers and identity
|
|
67
67
|
|
|
68
|
-
| Signer | Scheme
|
|
69
|
-
| --------------------- |
|
|
70
|
-
| `PrivateKeySigner` | GalaChain native signature
|
|
71
|
-
| `GalaWalletSigner` | Native `gala_signChainDto
|
|
72
|
-
| `BrowserWalletSigner` | EIP-1193 `personal_sign`
|
|
68
|
+
| Signer | Scheme | Identity resolved by the chain |
|
|
69
|
+
| --------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------- |
|
|
70
|
+
| `PrivateKeySigner` | GalaChain native signature | Recovered from the private key |
|
|
71
|
+
| `GalaWalletSigner` | Native `gala_signChainDto`; opt-in `personal-sign` needs a wallet with fix 3ad7ae6 | Selected Ethereum account (`0x...` form) |
|
|
72
|
+
| `BrowserWalletSigner` | EIP-1193 `personal_sign` | Selected Ethereum account (`0x...` form) |
|
|
73
73
|
|
|
74
74
|
Native signing is the default for server keys and current Gala Wallets.
|
|
75
75
|
Browser wallet personal-sign signs the bare serialized DTO (the wallet applies
|
|
@@ -77,6 +77,15 @@ the EIP-191 header) and sends that header as the DTO's `prefix`, which is what
|
|
|
77
77
|
the chain prepends when it recovers the signer. EIP-712 is
|
|
78
78
|
not part of the v2 write protocol.
|
|
79
79
|
|
|
80
|
+
## Wallet and app integration
|
|
81
|
+
|
|
82
|
+
The SDK core is platform neutral (only `fetch`, `globalThis.crypto` and timers) and ships the
|
|
83
|
+
building blocks a wallet or app needs, each behind an adapter: `confirmAppliedTrade` (apply-results
|
|
84
|
+
polling with `AbortSignal`, `AppliedTradeError`), `PendingSwapStore` (async `StorageAdapter`),
|
|
85
|
+
`DexFees` (DryRun fee quotes), `swaps.swapShadow` (dark swaps through `X-Shadow`), a configurable
|
|
86
|
+
`uniqueKeyPrefix`, and the realtime stream with an injected `WebSocket` (and an `apiKey` for
|
|
87
|
+
server-side clients). See [App and Wallet Integration](./docs/docs/other/app-integration.md).
|
|
88
|
+
|
|
80
89
|
## Documentation
|
|
81
90
|
|
|
82
91
|
Read the [gSwap SDK documentation](https://galachain.github.io/gswap-sdk/docs/intro)
|
package/dist/browser/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import e from"bignumber.js";import{Decimal as t}from"decimal.js";import n from"debug";import{serialize as r,signatures as i}from"@gala-chain/api";function a(e){"@babel/helpers - typeof";return a=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},a(e)}function o(e,t){if(a(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(a(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function s(e){var t=o(e,`string`);return a(t)==`symbol`?t:t+``}function c(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var l=class e extends Error{constructor(e,t,n,r,i){super(e),this.code=t,this.details=n,c(this,`chainMessage`,void 0),c(this,`retryAfterMs`,void 0),this.name=`GSwapSDKError`,this.chainMessage=r,this.retryAfterMs=i}static noSignerError(){return new e(`This method requires a signer. Please provide a signer to the GSwap constructor.`,`NO_SIGNER`)}static noWalletAddressError(){return new e(`Cannot confirm this write: no walletAddress was provided to the GSwap constructor, so the resulting position cannot be looked up to confirm it landed on chain.`,`NO_WALLET_ADDRESS`)}static noPoolAvailableError(t,n,r){return new e(`No pool is available for the requested pair.`,`NO_POOL_AVAILABLE`,{tokenIn:t,tokenOut:n,...r===void 0?{}:{fee:r}})}static insufficientLiquidityError(t,n,r){return new e(`The selected pool has insufficient liquidity for the requested quote.`,`INSUFFICIENT_LIQUIDITY`,{tokenIn:t,tokenOut:n,...r===void 0?{}:{fee:r}})}static fromGatewayBounce(t,n,r,i){let a={status:r,chainMessage:n};i!==void 0&&(a.retryAfterMs=i);let o=t===`CHAIN_DISPATCH_FAILED`?n:`Gateway rejected ${t}: ${n}`;return new e(o,t,a,n,i)}static fromChainError(t,n,r){return new e(`GalaChain error ${t}: ${n}`,t,{...r,errorKey:t,message:n},n)}static unknownTokenError(t){let n=typeof t==`string`?t:JSON.stringify(t);return new e(`Token ${n} has no trading symbol on the new DEX contract (no gcdex pool includes it yet).`,`UNKNOWN_TOKEN`,{token:t})}static confirmationTimeoutError(t,n){return new e(`Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.`,`CONFIRMATION_TIMEOUT`,{uniqueKey:t,...n===void 0?{}:{cause:n}})}static async fromErrorResponse(t,n){let r=await n.text(),i=f(r),a=u(i,`error`),o=d(a,`ErrorKey`),s=d(a,`Message`);return o!==void 0&&s!==void 0?new e(`GalaChain Error ${o} from ${t}: ${s}`,o,{message:s,errorKey:o,status:n.status,body:i,url:t},s):new e(`Unexpected HTTP Error ${n.status} from ${t}`,`HTTP_ERROR`,{status:n.status,body:i??r,url:t})}};function u(e,t){if(typeof e!=`object`||!e||!(t in e))return;let n=e[t];return typeof n==`object`&&n?n:void 0}function d(e,t){if(typeof e!=`object`||!e||!(t in e))return;let n=e[t];return typeof n==`string`?n:void 0}function f(e){try{return JSON.parse(e)}catch{return}}let p=/* @__PURE__ */ function(e){return e[e.PERCENT_00_00=0]=`PERCENT_00_00`,e[e.PERCENT_00_05=500]=`PERCENT_00_05`,e[e.PERCENT_00_30=3e3]=`PERCENT_00_30`,e[e.PERCENT_01_00=1e4]=`PERCENT_01_00`,e}({});const m={0:200,500:10,3e3:60,1e4:200},h=[0,500,3e3,1e4],g=-887272,_=887272,v=e.clone({DECIMAL_PLACES:60,ROUNDING_MODE:e.ROUND_DOWN}),y=t.clone({precision:60});function b(t){return new e(new y(1.0001).pow(t/2).toString())}function ee(e){let t;try{t=new v(e)}catch{return NaN}if(!t.isFinite()||t.isLessThanOrEqualTo(0))return NaN;let n=Math.log(t.toNumber()**2)/Math.log(1.0001);if(!Number.isFinite(n))return NaN;let r=Math.min(_,Math.max(g,Math.floor(n)));for(;r<887272&&b(r+1).isLessThanOrEqualTo(t);)r+=1;for(;r>-887272&&b(r).isGreaterThan(t);)--r;return r}function x(t){let n=typeof t==`string`?t:typeof t==`number`||e.isBigNumber(t)?t.toString():`NaN`,r=new y(n);if(!r.isFinite()||r.lessThanOrEqualTo(0)||!Number.isFinite(r.toNumber()))return NaN;let i=r.ln().dividedBy(new y(1.0001).ln()).floor().toNumber();return Number.isFinite(i)?i:NaN}function S(e,t){return ne(t),Math.floor(e/t)*t}function te(e,t){return ne(t),Math.ceil(e/t)*t}function C(e,t,n){let r=m[n];if(r===void 0)throw RangeError(`Unsupported fee tier: ${n}`);if(!Number.isInteger(e)||!Number.isInteger(t))throw RangeError(`Ticks must be integers`);if(e<-887272||t>887272||e>=t)throw RangeError(`Tick range must satisfy ${g} <= lower < upper <= ${_}`);if(e%r!==0||t%r!==0)throw RangeError(`Ticks must be aligned to spacing ${r}`)}function ne(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`Tick spacing must be positive`)}function w(t,n,r=!1){if(typeof t==`number`)throw new l(`Invalid ${n}: use a decimal string or BigNumber, not a JavaScript number`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,parameterName:n,value:t,reason:`number_input`});let i;try{i=e(t)}catch{i=e(NaN)}if(!i.isFinite())throw new l(`Invalid ${n}: must be a finite number`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,parameterName:n,value:t,reason:`not_finite`});if(!r&&i.isZero())throw new l(`Invalid ${n}: must be positive`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,parameterName:n,value:t,reason:`zero_not_allowed`});if(i.isNegative())throw new l(`Invalid ${n}: must be ${r?`non-negative`:`positive`}`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,parameterName:n,value:t,reason:`negative`})}function re(t,n,r){if([t,n,r].some(e=>typeof e==`number`))throw new l(`Invalid price values: use decimal strings or BigNumber values, not JavaScript numbers`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,reason:`number_input`});let i=t=>{try{return e(t)}catch{return e(NaN)}},a=i(t),o=i(n),s=i(r);if(s=s.isFinite()?s:e(0xde0b6b3a7640000),!a.isFinite()||!o.isFinite()||!s.isFinite()||!a.isPositive()||!o.isPositive()||!s.isPositive())throw new l(`Invalid price values: all prices must be finite and positive`,`VALIDATION_ERROR`,{type:`INVALID_PRICE_VALUES`,spotPrice:t,lowerPrice:n,upperPrice:r});if(o.isGreaterThan(s))throw new l(`Invalid price range: lower price must be less than or equal to upper price`,`VALIDATION_ERROR`,{type:`INVALID_PRICE_RANGE`,lowerPrice:n,upperPrice:r})}function ie(e,t){if(e<0||!Number.isInteger(e))throw new l(`Invalid ${t}: must be a non-negative integer`,`VALIDATION_ERROR`,{type:`INVALID_TOKEN_DECIMALS`,parameterName:t,value:e})}function ae(e,t){if(!Number.isInteger(e)||!Number.isInteger(t))throw new l(`Invalid tick values: ticks must be integers`,`VALIDATION_ERROR`,{type:`INVALID_TICK_VALUES`,tickLower:e,tickUpper:t});if(e>=t)throw new l(`Invalid tick range: tickLower must be less than tickUpper`,`VALIDATION_ERROR`,{type:`INVALID_TICK_RANGE`,tickLower:e,tickUpper:t});if(e<-887272||t>887272)throw new l(`Invalid tick range: ticks must be between ${g} and ${_}`,`VALIDATION_ERROR`,{type:`INVALID_TICK_BOUNDS`,tickLower:e,tickUpper:t,minTick:g,maxTick:_})}function T(e){if(!h.some(t=>Number(t)===e))throw new l(`Invalid fee tier: must be one of 0, 500, 3000, or 10000`,`VALIDATION_ERROR`,{type:`INVALID_FEE`,value:e})}function oe(e){if(!Number.isInteger(e)||e<=0)throw new l(`Invalid tick spacing: must be a positive integer`,`VALIDATION_ERROR`,{type:`INVALID_TICK_SPACING`,value:e})}function E(e){if(e===void 0)throw new l(`Invalid wallet address: No wallet address provided`,`VALIDATION_ERROR`,{type:`MISSING_WALLET_ADDRESS`,hint:`Either provide a wallet address to the function you are calling, or set one when instantiating GSwapSDK`});if(!e||typeof e!=`string`||e.trim().length===0)throw new l(`Invalid wallet address: must be a non-empty string`,`VALIDATION_ERROR`,{type:`INVALID_WALLET_ADDRESS`,value:e})}var D=class{constructor(e,t){this.dexBackendBaseUrl=e,this.httpClient=t}async getUserAssets(e,t=1,n=10){if(E(e),!Number.isInteger(t)||t<1)throw new l(`Invalid page: must be a positive integer`,`VALIDATION_ERROR`,{page:t});if(!Number.isInteger(n)||n<1||n>100)throw new l(`Invalid limit: must be an integer between 1 and 100`,`VALIDATION_ERROR`,{limit:n});return se(await this.httpClient.sendGetRequest(this.dexBackendBaseUrl,`/user/assets`,``,{address:e,page:t.toString(),limit:n.toString()}))}};function se(e){let t=u(e,`data`),n=t?.token;if(!Array.isArray(n)||!n.every(ce))throw new l(`Backend returned an invalid user assets response.`,`INVALID_CHAIN_RESPONSE`,{data:e});let r=t?.count;return{tokens:n.map(e=>({...e,decimals:parseInt(e.decimals,10)})),count:typeof r==`number`?r:0}}function ce(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.image==`string`&&typeof t.name==`string`&&typeof t.decimals==`string`&&/^\d+$/u.test(t.decimals)&&typeof t.verify==`boolean`&&typeof t.symbol==`string`&&typeof t.quantity==`string`}async function O(e,t,n,r){let i=new AbortController,a=setTimeout(()=>i.abort(),r),o=n.signal,s=()=>i.abort();o?.addEventListener(`abort`,s,{once:!0});try{return await e(t,{...n,signal:i.signal})}catch(e){throw i.signal.aborted?new l(`Request timed out after ${r} ms.`,`REQUEST_TIMEOUT`,{url:t,timeoutMs:r,cause:e}):e}finally{clearTimeout(a),o?.removeEventListener(`abort`,s)}}async function k(e){let t=await e.text();return f(t)??t}function A(e,t){let n=e.headers;if(n===void 0)return;if(de(n)){let e=n.get(t);return e===null||e===``?void 0:e}let r=Object.entries(n).find(([e])=>e.toLowerCase()===t.toLowerCase())?.[1];return r===void 0||r===``?void 0:r}function le(e){let t=A(e,`retry-after`);if(t===void 0)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n*1e3:void 0}function ue(e,t=`x-block-number`){let n=A(e,t);if(n===void 0)return;let r=Number(n);return Number.isInteger(r)&&r>=0?r:void 0}function de(e){return`get`in e&&typeof e.get==`function`}var j=class{constructor(e){c(this,`method`,void 0),c(this,`uniqueKey`,void 0),c(this,`transactionId`,void 0),c(this,`blockNumber`,void 0),c(this,`mode`,void 0),c(this,`result`,void 0),c(this,`backendBaseUrl`,void 0),c(this,`requestor`,void 0),c(this,`requestTimeoutMs`,void 0),c(this,`positionConfirmation`,void 0),this.method=e.method,this.uniqueKey=e.uniqueKey,this.transactionId=e.transactionId,this.blockNumber=e.blockNumber??null,this.mode=e.mode,this.result=e.result,this.backendBaseUrl=e.dexBackendBaseUrl.replace(/\/$/u,``),this.requestor=e.httpRequestor,this.requestTimeoutMs=e.requestTimeoutMs??3e4,this.positionConfirmation=e.positionConfirmation}async confirm(e){return this.method===`RequestTrade`?this.confirmApplied(e):this.confirmPosition(e)}async confirmApplied(e){let t=fe(e,3e3);await t.waitForRead();let n=`${this.backendBaseUrl}/v1/chain/apply-results/${encodeURIComponent(this.uniqueKey)}?channel=asset&contract=dex-contract`,r;for(;;){let e,i;try{e=await O(this.requestor,n,{method:`GET`},this.requestTimeoutMs),i=await k(e)}catch(e){if(r=e,!await t.waitForRead())break;continue}if(e.status===200)return this.readAppliedResult(e,i,n);if(e.status===404||e.status===429||me(e.status)){if(e.status===429){let n=le(e);if(n!==void 0){if(!await t.waitForRead(n))break;continue}}}else throw new l(he(i),`CONFIRMATION_FAILED`,{status:e.status,body:i,url:n});if(!await t.waitForRead())break}throw l.confirmationTimeoutError(this.uniqueKey,r)}readAppliedResult(e,t,n){let r=N(t),i=r?.Status,a=A(e,`x-apply-transaction-id`)??null,o=ue(e,`x-apply-block-number`)??null;if(i===0)throw l.fromChainError(d(r,`ErrorKey`)??`CHAIN_ERROR`,d(r,`Message`)??`The chain rejected this trade.`,{uniqueKey:this.uniqueKey,applyTransactionId:a,blockNumber:o,status:e.status,body:t,url:n});if(i!==1)throw M(e,t,n);let s=pe(r?.Data);if(s===void 0)throw M(e,t,n);return{uniqueKey:this.uniqueKey,transactionId:a,blockNumber:o,requestTransactionId:this.transactionId,result:s}}async confirmPosition(e){if(this.positionConfirmation===void 0)throw l.noWalletAddressError();let t=fe(e,0);for(await t.waitForRead();;){let e=new AbortController,n=setTimeout(()=>e.abort(),this.requestTimeoutMs);try{let t=await this.positionConfirmation(e.signal);if(t.confirmed)return t.position}finally{clearTimeout(n)}if(!await t.waitForRead())break}throw l.confirmationTimeoutError(this.uniqueKey)}};function fe(e,t){let n=Math.max(0,e?.timeoutMs??6e4),r=Math.max(500,e?.pollIntervalMs??2e3),i=Math.max(0,e?.initialDelayMs??t),a=Date.now()+n,o=!0,s=0;return{async waitForRead(e){if(o){o=!1;let e=Math.max(0,a-Date.now());return await P(Math.min(i,e)),!0}let t=Math.min(8e3,r*2**Math.min(s,5));s+=1;let n=e===void 0?ge(t):e;return Date.now()+n>a?!1:(await P(n),!0)}}}function pe(e){let t=N(e);if(t===void 0||typeof t.token0!=`string`||typeof t.token1!=`string`||typeof t.fee!=`number`)return;let n=[`sell0Qty`,`sell1Qty`,`buy0Qty`,`buy1Qty`,`tradingFees`,`protocolFees`,`totalFees`];for(let e of n)if(e in t&&typeof t[e]!=`string`)return;return{token0:t.token0,token1:t.token1,fee:t.fee,...Object.fromEntries(n.flatMap(e=>typeof t[e]==`string`?[[e,t[e]]]:[]))}}function M(e,t,n){return new l(`Transaction confirmation returned a malformed body`,`CONFIRMATION_FAILED`,{status:e.status,body:t,url:n})}function me(e){return e===500||e===502||e===503||e===504}function he(e){return d(e,`message`)??d(e,`Message`)??d(u(e,`error`),`message`)??d(u(e,`error`),`Message`)??(typeof e==`string`?e:`Transaction confirmation failed`)}function N(e){return typeof e==`object`&&e?e:void 0}function P(e){return new Promise(t=>setTimeout(t,e))}function ge(e){return Math.max(0,Math.round(e*(.9+Math.random()*.2)))}var F=class{constructor(e){c(this,`requestor`,void 0),c(this,`walletAddress`,void 0),c(this,`chainCallTimeoutMs`,void 0),c(this,`requestTimeoutMs`,void 0),c(this,`dexBackendBaseUrl`,void 0),this.dexBackendBaseUrl=_e(e.dexBackendBaseUrl),this.requestor=e.httpRequestor??fetch.bind(globalThis),this.walletAddress=e.walletAddress,this.chainCallTimeoutMs=e.chainCallTimeoutMs??3e4,this.requestTimeoutMs=this.chainCallTimeoutMs}async submit(e,t,n){if(e===`Trade`)throw new l(`The synchronous Trade method was removed; swaps are queued through RequestTrade.`,`METHOD_NOT_SUPPORTED`,{method:e});let r=`${this.dexBackendBaseUrl}/v1/chain/asset/dex-contract/${e}`,i={"content-type":`application/json`},a=n?.walletAddress??this.walletAddress;a!==void 0&&(i[`X-Wallet-Address`]=a);let o;try{o=await O(this.requestor,r,{method:`POST`,headers:i,body:JSON.stringify(t)},this.chainCallTimeoutMs)}catch(e){throw e instanceof l&&e.code===`REQUEST_TIMEOUT`?new l(`The submission outcome is unknown because the gateway request timed out. Confirm before retrying.`,`SUBMISSION_OUTCOME_UNKNOWN`,{uniqueKey:d(t,`uniqueKey`)??``,cause:e}):e}let s=await k(o);if(!o.ok)throw ve(o,s,r);let c=L(s),u=L(c?.data??c?.Data);if(u===void 0)throw I(o,s,r,`Expected a data object.`);let f=d(u,`transactionId`),p=d(u,`mode`),m=u.transactionId,h=u.blockNumber,g=`Gateway response must contain data.mode="sync" with data.result, or data.mode="queued".`;if(p!==`sync`&&p!==`queued`||`transactionId`in u&&typeof m!=`string`||h!=null&&!R(h))throw I(o,s,r,g);if(e===`RequestTrade`&&p===`sync`)throw I(o,s,r,`The gateway executed RequestTrade synchronously, which this SDK refuses; RequestTrade must be queued.`);if(e===`RequestTrade`&&p===`queued`){let e=d(t,`uniqueKey`);if(`uniqueKey`in u&&(typeof u.uniqueKey!=`string`||u.uniqueKey!==e))throw I(o,s,r,`Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey.`)}else if(p===`queued`||!(`result`in u))throw I(o,s,r,g);if(p===`sync`){let e=L(u.result);if(e!==void 0){let t=e.Status;if(t!==void 0&&t!==1)throw l.fromChainError(d(e,`ErrorKey`)??`CHAIN_ERROR`,d(e,`Message`)??`The chain rejected this write.`,{status:o.status,body:s,url:r})}}let _=d(t,`uniqueKey`)??``,v=A(o,`x-transaction-id`),y=f===void 0||f===``?v:f,b=h==null?ue(o):R(h)?h:void 0;return new j({method:e,uniqueKey:_,transactionId:y===void 0||y===``?null:y,blockNumber:b??null,mode:p,result:p===`queued`?void 0:u.result,dexBackendBaseUrl:this.dexBackendBaseUrl,httpRequestor:this.requestor,requestTimeoutMs:this.chainCallTimeoutMs,...n?.positionConfirmation===void 0?{}:{positionConfirmation:n.positionConfirmation}})}get httpRequestor(){return this.requestor}};function _e(e){return e.replace(/\/$/u,``)}function I(e,t,n,r){return new l(r,`INVALID_GATEWAY_RESPONSE`,{status:e.status,body:t,url:n})}function ve(e,t,n){let r=L(t),i=u(t,`error`),a=d(r,`code`)??d(i,`code`)??d(i,`ErrorKey`)??`HTTP_ERROR`,o=d(r,`message`)??d(i,`message`)??d(i,`Message`)??(typeof t==`string`?t:`Gateway request failed with HTTP ${e.status}`),s=e.status===429?le(e):void 0;return a===`HTTP_ERROR`?new l(o,a,{status:e.status,body:t,url:n}):l.fromGatewayBounce(a,o,e.status,s)}function L(e){return typeof e==`object`&&e?e:void 0}function R(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}const z={prod:{dexBackendBaseUrl:`https://dex-backend-prod1.defi.gala.com`,dexBackendWsUrl:`wss://dex-backend-prod1.defi.gala.com/ws`},stage:{dexBackendBaseUrl:`https://swap-backend.stage.defi.ovh.gala.com`,dexBackendWsUrl:`wss://swap-backend.stage.defi.ovh.gala.com/ws`}},B=n(`GSWAP_SDK`);var ye=class{constructor(e){this.options=e,c(this,`attempts`,0),c(this,`delayMs`,void 0),c(this,`maxDelayMs`,void 0),this.delayMs=e.baseDelayMs,this.maxDelayMs=e.maxDelayMs??3e4}shouldRetry(){return this.attempts<this.options.maxAttempts}nextDelayMs(){return this.delayMs}recordAttempt(){this.attempts+=1,this.delayMs=Math.min(this.delayMs*2,this.maxDelayMs)}reset(){this.attempts=0,this.delayMs=this.options.baseDelayMs}get attemptCount(){return this.attempts}get maxAttempts(){return this.options.maxAttempts}};const be=[`add`,`remove`,`collect`];function V(e){let{pool:t}=e;return(e.version===`v1`||e.version===`v2`)&&typeof t==`object`&&!!t&&typeof e.poolHash==`string`&&typeof e.transactionId==`string`&&be.includes(e.action)&&typeof e.owner==`string`&&typeof e.amount0==`string`&&typeof e.amount1==`string`&&typeof e.blockNumber==`number`&&typeof e.timestamp==`string`}var H=class extends Error{constructor(e,t,n){super(t),c(this,`code`,void 0),c(this,`data`,void 0),this.name=`GdexStreamError`,this.code=e,n!==void 0&&(this.data=n)}},U=class{constructor(e={}){c(this,`url`,void 0),c(this,`requestTimeoutMs`,void 0),c(this,`webSocketConstructor`,void 0),c(this,`backoff`,void 0),c(this,`socket`,void 0),c(this,`connectPromise`,void 0),c(this,`nextRequestId`,0),c(this,`pending`,/* @__PURE__ */ new Map),c(this,`subscriptionsByServerId`,/* @__PURE__ */ new Map),c(this,`activeSubscriptions`,/* @__PURE__ */ new Set),c(this,`intentionalClose`,!1),c(this,`reconnecting`,!1),c(this,`reconnectTimer`,void 0),c(this,`reconnectDelayResolve`,void 0),this.url=e.url??z.prod.dexBackendWsUrl,this.requestTimeoutMs=e.requestTimeoutMs??15e3,this.backoff=new ye({maxAttempts:e.reconnectAttempts??5,baseDelayMs:e.reconnectDelayMs??2e3});let t=e.webSocketImpl??globalThis.WebSocket;if(typeof t!=`function`)throw Error(`GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the "ws" package).`);this.webSocketConstructor=t}connect(){return this.isConnected()?Promise.resolve():this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.clearReconnectTimer(),this.connectPromise=this.openSocket(),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.reconnecting=!1,this.clearReconnectTimer(),this.rejectPending(/* @__PURE__ */ Error(`GDEX stream disconnected`));let e=this.socket;this.socket=void 0,this.connectPromise=void 0,e?.close(1e3,`client disconnect`)}isConnected(){return this.socket?.readyState===1}request(e,t){if(!this.isConnected()||!this.socket)return Promise.reject(/* @__PURE__ */ Error(`GDEX stream is not connected. Call connect() first.`));let n=++this.nextRequestId,r={jsonrpc:`2.0`,id:n,method:e};return t!==void 0&&(r.params=t),new Promise((t,i)=>{let a=setTimeout(()=>{this.pending.delete(n),i(/* @__PURE__ */ Error(`GDEX request "${e}" timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);this.pending.set(n,{resolve:e=>t(e),reject:i,timeout:a});try{this.socket?.send(JSON.stringify(r))}catch(e){clearTimeout(a),this.pending.delete(n),i(e instanceof Error?e:Error(String(e)))}})}serverInfo(){return this.request(`gdex_serverInfo`)}ping(){return this.request(`gdex_ping`)}getPool(e){return this.request(`gdex_getPool`,e)}getBalance(e,t){return this.request(`gdex_getBalance`,t===void 0?{owner:e}:{owner:e,tokenClassKey:t})}getPositions(e){return this.request(`gdex_getPositions`,e)}getBlockHeight(){return this.request(`gdex_getBlockHeight`)}quote(e){return this.request(`gdex_quote`,e)}getToken(e){return this.request(`gdex_getToken`,{tokenClassKey:e})}subscribeSwaps(e,t={}){return this.subscribe(`swap`,e,t)}subscribePool(e,t,n={}){return this.subscribe(`pool`,t,{...e,...n})}subscribeBalances(e,t,n={}){return this.subscribe(`balance`,t,{owner:e,...n})}subscribePoolCreated(e,t={}){return this.subscribe(`poolCreated`,e,t)}subscribeLiquidity(e,t={}){return this.subscribe(`liquidity`,t=>{V(t)?e(t):B(`Ignoring a malformed liquidity event from the GDEX stream`)},t)}subscribeBlocks(e,t={}){return this.subscribe(`blocks`,e,t)}openSocket(){return new Promise((e,t)=>{let n=!1,r=new this.webSocketConstructor(this.url,`gdex.jsonrpc.v1`);this.socket=r,r.onopen=()=>{this.socket===r&&(n=!0,this.connectPromise=void 0,this.reconnecting||this.backoff.reset(),B(`Connected to GDEX stream`),e())},r.onmessage=e=>this.handleMessage(e.data),r.onerror=()=>{n||t(/* @__PURE__ */ Error(`Failed to connect to GDEX stream at ${this.url}`))},r.onclose=e=>{this.socket===r&&(this.socket=void 0,this.connectPromise=void 0,n||t(/* @__PURE__ */ Error(`GDEX stream closed before connecting (code ${e.code??0})`)),this.rejectPending(/* @__PURE__ */ Error(`GDEX stream connection closed (code ${e.code??0})`)),!this.intentionalClose&&!this.reconnecting&&this.startReconnectLoop())}})}handleMessage(e){if(typeof e!=`string`){B(`Ignoring non-text GDEX WebSocket frame`);return}let t;try{t=JSON.parse(e)}catch{B(`Ignoring invalid JSON from GDEX stream`);return}if(typeof t.id==`number`){let e=this.pending.get(t.id);if(!e)return;if(clearTimeout(e.timeout),this.pending.delete(t.id),t.error){let n=typeof t.error.code==`number`?t.error.code:-32603,r=typeof t.error.message==`string`?t.error.message:`GDEX request failed`;e.reject(new H(n,r,t.error.data))}else e.resolve(t.result);return}if(t.method!==`gdex_subscription`||!this.isRecord(t.params))return;let n=t.params.subscription,r=t.params.result;if(typeof n!=`string`||!this.isRecord(r))return;let i=this.subscriptionsByServerId.get(n);if(i?.active)try{i.callback(r)}catch(e){B(`GDEX subscription callback failed`,e)}}async subscribe(e,t,n){let r={channel:e,...n},i=await this.request(`gdex_subscribe`,r),a,o={subscriptionId:i.subscriptionId,unsubscribe:async()=>this.unsubscribe(a)};return a={serverId:i.subscriptionId,params:r,callback:t,handle:o,active:!0},this.activeSubscriptions.add(a),this.subscriptionsByServerId.set(a.serverId,a),o}async unsubscribe(e){e.active&&(e.active=!1,this.activeSubscriptions.delete(e),this.subscriptionsByServerId.delete(e.serverId),this.isConnected()&&await this.request(`gdex_unsubscribe`,{subscriptionId:e.serverId}))}startReconnectLoop(){this.reconnecting||this.intentionalClose||(this.reconnecting=!0,this.reconnectLoop())}async reconnectLoop(){for(;!this.intentionalClose&&this.backoff.shouldRetry();){let e=this.backoff.nextDelayMs();if(this.backoff.recordAttempt(),B(`GDEX reconnect attempt ${this.backoff.attemptCount}/${this.backoff.maxAttempts} in ${e}ms`),await this.waitForReconnectDelay(e),this.intentionalClose)break;try{await this.openSocket(),await this.resubscribeAll(),this.backoff.reset(),this.reconnecting=!1;return}catch(e){B(`GDEX reconnect failed: ${e instanceof Error?e.message:String(e)}`)}}this.reconnecting=!1,this.intentionalClose||B(`GDEX reconnection attempts exhausted`)}async resubscribeAll(){this.subscriptionsByServerId.clear();for(let e of this.activeSubscriptions){if(!e.active)continue;let t={...e.params,snapshot:!0},n=await this.resubscribeWithRateLimitRetry(t);if(!e.active){await this.request(`gdex_unsubscribe`,{subscriptionId:n.subscriptionId});continue}e.serverId=n.subscriptionId,e.handle.subscriptionId=n.subscriptionId,this.subscriptionsByServerId.set(n.subscriptionId,e)}}async resubscribeWithRateLimitRetry(e){for(let t=0;;t++)try{return await this.request(`gdex_subscribe`,e)}catch(e){if(!(e instanceof H)||e.code!==-32003||t>=5)throw e;let n=this.readRetryAfterMs(e.data);B(`GDEX resubscribe rate limited; retrying in ${n}ms`),await new Promise(e=>setTimeout(e,n))}}waitForReconnectDelay(e){return new Promise(t=>{this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectDelayResolve=void 0,t()},e),this.reconnectDelayResolve=t})}clearReconnectTimer(){this.reconnectTimer!==void 0&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0;let e=this.reconnectDelayResolve;this.reconnectDelayResolve=void 0,e?.()}rejectPending(e){for(let t of this.pending.values())clearTimeout(t.timeout),t.reject(e);this.pending.clear()}readRetryAfterMs(e){return!this.isRecord(e)||typeof e.retryAfterMs!=`number`||e.retryAfterMs<0?1e3:e.retryAfterMs}isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}},W=class{constructor(e=fetch,t=3e4){this.httpRequestor=e,this.timeoutMs=t}async sendRequest(e,t,n,r,i,a){let o=`${t}${n}${r}`;B(`Sending request to ${o} with body:`,i);let s=await O(this.httpRequestor,o,{method:e,headers:{"Content-Type":`application/json`,"User-Agent":`GalaChain-SDK/1.1.0`},...i?{body:JSON.stringify(i)}:{},...a?.signal===void 0?{}:{signal:a.signal}},this.timeoutMs);if(!s.ok)throw await l.fromErrorResponse(o,s);let c=await k(s);return B(`Response from ${t}${n}${r}:`,c),c}async sendPostRequest(e,t,n,r){return this.sendRequest(`POST`,e,t,n,r)}async sendGetRequest(e,t,n,r,i){let a=r?new URLSearchParams(r):void 0,o=a?`${n}?${a.toString()}`:n;return this.sendRequest(`GET`,e,t,o,void 0,i)}};function G(e,t){return e<t?[e,t]:[t,e]}function K(e){if(Array.isArray(e)&&e.length>=2){let t=e[0],n=e[1];if(typeof t==`string`&&typeof n==`string`)return{token0:t,token1:n}}if(typeof e==`object`&&e){let t=e,n=t.token0,r=t.token1;if(typeof n==`string`&&typeof r==`string`)return{token0:n,token1:r}}throw new l(`Unable to order trading symbols.`,`VALIDATION_ERROR`,{value:e})}function q(e){return[e.collection,e.category,e.type,e.additionalKey].join(`$`)}function J(e){if(typeof e==`object`)return{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey};let t=e.includes(`|`)?`|`:`$`,n=e.split(t),r=n.slice(-3),i=n.slice(0,-3).join(t);if(n.length<4||i.length===0||r.some(e=>e.length===0))throw new l(`Invalid token class key: expected a collection followed by category, type and additionalKey`,`VALIDATION_ERROR`,{tokenClassKey:e});let[a,o,s]=r;return{collection:i,category:a,type:o,additionalKey:s}}var xe=class{constructor(e,t){this.gateway=e,this.symbols=t,c(this,`http`,void 0),this.http=new W(e.httpRequestor,e.requestTimeoutMs??3e4)}async getPools(e){let t=await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,`/pools`,void 0,e?.signal===void 0?void 0:{signal:e.signal});if(!Array.isArray(t.data)||!t.data.every(Se))throw new l(`Backend returned an invalid pool list.`,`INVALID_CHAIN_RESPONSE`,{data:t.data});return t.data}async getPool(e,t,n){return T(n),this.getBackend(`/pool`,await this.backendParams(e,t,n))}async getSlot0(e,t,n){return T(n),this.getBackend(`/slot0`,await this.backendParams(e,t,n))}async getCompositePool(e,t,n){T(n);let r=K(G(await Y(this.symbols,e),await Y(this.symbols,t)));return this.getBackend(`/composite-pool`,{token0:r.token0,token1:r.token1,fee:String(n)})}async backendParams(e,t,n){return{token0:await Y(this.symbols,e),token1:await Y(this.symbols,t),fee:String(n)}}async getBackend(e,t){try{return(await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,e,t)).data}catch(e){throw e instanceof l?e:new l(`Pool request failed.`,`HTTP_ERROR`,{cause:e})}}};async function Y(e,t){let n=await e.resolve(t);if(n.symbol.length>0)return n.symbol;throw new l(`Token could not be resolved to a trading symbol.`,`SYMBOL_NOT_FOUND`,{token:t})}function Se(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.contractVersion===`v2`&&typeof t.token0==`string`&&typeof t.token1==`string`&&typeof t.poolName==`string`&&typeof t.poolRef==`string`&&[`fee`,`tickSpacing`,`protocolFees`,`tradingFees`].every(e=>Ce(t[e]))&&[`token0CompositeKey`,`token1CompositeKey`,`creator`,`price`,`sqrtPrice`,`token0Tvl`,`token1Tvl`].every(e=>we(t[e]))&&[`tick`,`tvlUsd`,`volume1d`,`volume7d`,`volume30d`,`trades1d`,`fee24h`,`apr1d`,`token0Price`,`token1Price`].every(e=>Te(t[e]))}function Ce(e){return typeof e==`number`&&Number.isFinite(e)}function we(e){return e===void 0||typeof e==`string`}function Te(e){return e===void 0||Ce(e)}var Ee=class{constructor(e,t,n,r){this.gateway=e,this.symbols=t,this.signer=n,this.walletAddress=r,c(this,`http`,void 0),this.http=new W(e.httpRequestor,e.requestTimeoutMs??3e4)}async getUserPositions(e){return(await this.get(`/positions`,{user:e})).data.map(e=>this.mapPosition(e))}async getPosition(e,t){let n=await this.symbols.orderPair(e.token0,e.token1),r=this.canonicalTicks(e.tickLower,e.tickUpper,n.flipped),i=await this.getNullable(`/position`,{token0:n.token0.symbol,token1:n.token1.symbol,fee:`${e.fee}`,owner:e.owner,tickLower:`${r.tickLower}`,tickUpper:`${r.tickUpper}`},t);return i===null?null:this.mapPosition(i.data)}async estimateAddLiquidity(t){return w(t.amount,`amount`),(await this.get(`/add-liq-estimate`,{token0:this.requestToken(t.token0),token1:this.requestToken(t.token1),fee:`${t.fee}`,tickLower:`${t.tickLower}`,tickUpper:`${t.tickUpper}`,amount:new e(t.amount).toFixed(),amountIsToken0:String(t.amountIsToken0)})).data}async estimateRemoveLiquidity(t){return w(t.liquidity,`liquidity`),(await this.get(`/remove-liq-estimate`,{token0:this.requestToken(t.token0),token1:this.requestToken(t.token1),fee:`${t.fee}`,tickLower:`${t.tickLower}`,tickUpper:`${t.tickUpper}`,liquidity:new e(t.liquidity).toFixed()})).data}async addLiquidityByTicks(t){T(t.fee);let n=await this.symbols.orderPair(t.token0,t.token1),r=this.canonicalTicks(t.tickLower,t.tickUpper,n.flipped);C(r.tickLower,r.tickUpper,t.fee),w(t.amount,`amount`);let i=new e(t.amount).toFixed(),a={token0:n.token0.symbol,token1:n.token1.symbol,fee:t.fee,tickLower:r.tickLower,tickUpper:r.tickUpper,uniqueKey:this.uniqueKey(),...n.flipped===t.amountIsToken0?{depositQuantityToken1:i}:{depositQuantityToken0:i}};return this.submit(`AddLiquidity`,a,{kind:`add`,identity:{token0:n.token0.symbol,token1:n.token1.symbol,fee:t.fee,tickLower:r.tickLower,tickUpper:r.tickUpper}})}async addLiquidityByPrice(t){T(t.fee),this.rejectNumber(t.minPrice,`minPrice`),this.rejectNumber(t.maxPrice,`maxPrice`);let n=new e(t.minPrice),r=new e(t.maxPrice);if(!n.isFinite()||!r.isFinite()||n.isLessThanOrEqualTo(0)||r.isLessThanOrEqualTo(0))throw new l(`Price bounds must be finite and positive.`,`VALIDATION_ERROR`);if(n.isGreaterThan(r))throw new l(`minPrice must be less than or equal to maxPrice.`,`VALIDATION_ERROR`);let i=this.tickSpacing(t.fee),a=S(x(n),i),o=te(x(r),i);return this.addLiquidityByTicks({token0:t.token0,token1:t.token1,fee:t.fee,tickLower:a,tickUpper:o,amount:t.amount,amountIsToken0:t.amountIsToken0})}async removeLiquidity(t){T(t.fee);let n=await this.symbols.orderPair(t.token0,t.token1),r=this.canonicalTicks(t.tickLower,t.tickUpper,n.flipped);if(C(r.tickLower,r.tickUpper,t.fee),t.amount0!==void 0&&t.amount1!==void 0)throw new l(`Provide at most one of amount0 or amount1.`,`VALIDATION_ERROR`);t.amount0!==void 0&&w(t.amount0,`amount0`),t.amount1!==void 0&&w(t.amount1,`amount1`);let i=t.amount0===void 0?t.amount1===void 0?{}:n.flipped?{withdrawalQuantityToken0:new e(t.amount1).toFixed()}:{withdrawalQuantityToken1:new e(t.amount1).toFixed()}:n.flipped?{withdrawalQuantityToken1:new e(t.amount0).toFixed()}:{withdrawalQuantityToken0:new e(t.amount0).toFixed()},a={token0:n.token0.symbol,token1:n.token1.symbol,fee:t.fee,tickLower:r.tickLower,tickUpper:r.tickUpper,uniqueKey:this.uniqueKey(),...i},o=t.amount0===void 0&&t.amount1===void 0;return this.submit(`RemoveLiquidity`,a,{kind:o?`removeFull`:`removePartial`,identity:{token0:n.token0.symbol,token1:n.token1.symbol,fee:t.fee,tickLower:r.tickLower,tickUpper:r.tickUpper}})}async collectPositionFees(e){T(e.fee);let t=await this.symbols.orderPair(e.token0,e.token1),n=this.canonicalTicks(e.tickLower,e.tickUpper,t.flipped);C(n.tickLower,n.tickUpper,e.fee);let r={token0:t.token0.symbol,token1:t.token1.symbol,fee:e.fee,tickLower:n.tickLower,tickUpper:n.tickUpper,uniqueKey:this.uniqueKey()};return this.submit(`CollectPositionFees`,r,{kind:`collect`,identity:{token0:t.token0.symbol,token1:t.token1.symbol,fee:e.fee,tickLower:n.tickLower,tickUpper:n.tickUpper}})}async createPool(t){let n=t.startingPrice!==void 0;if(n===(t.startingSqrtPrice!==void 0))throw new l(`Provide exactly one of startingPrice or startingSqrtPrice.`,`VALIDATION_ERROR`);T(t.fee);let[r,i]=await Promise.all([this.resolveCreateToken(t.token0,t.token0Symbol),this.resolveCreateToken(t.token1,t.token1Symbol)]),a=r.symbol>i.symbol,[o,s]=a?[i,r]:[r,i],c=n?t.startingPrice:t.startingSqrtPrice;this.rejectNumber(c,n?`startingPrice`:`startingSqrtPrice`);let u=new e(c);if(!u.isFinite()||u.isLessThanOrEqualTo(0))throw new l(`Starting price must be finite and positive.`,`VALIDATION_ERROR`);let d=a?new e(1).dividedBy(u):u,f={token0Key:o.classKey,token1Key:s.classKey,token0Symbol:o.symbol,token1Symbol:s.symbol,fee:t.fee,uniqueKey:this.uniqueKey(),...n?{startingPrice:d.toFixed()}:{startingSqrtPrice:d.toFixed()},...t.isPrivate===void 0?{}:{isPrivate:t.isPrivate},...t.privateAccess===void 0?{}:{privateAccess:t.privateAccess}},p=await this.submit(`CreatePool`,f,{kind:`createPool`,token0:o.symbol,token1:s.symbol,fee:t.fee});return this.symbols.invalidate?.(),p}async submit(e,t,n){if(this.signer===void 0)throw l.noSignerError();let r=await this.signer.signObject(e,t),i=this.walletAddress===void 0?{}:{walletAddress:this.walletAddress},a=this.walletAddress,o=this.buildPositionConfirmation(n,a),s={...i,...o===void 0?{}:{positionConfirmation:o}};return this.gateway.submit(e,r,s)}buildPositionConfirmation(t,n){if(t===void 0)return;if(t.kind===`createPool`){let{token0:e,token1:n,fee:r}=t;return async t=>await this.getNullable(`/pool`,{token0:e,token1:n,fee:`${r}`},t)===null?{confirmed:!1}:{confirmed:!0,position:null}}if(n===void 0)return;let{kind:r,identity:i}=t,a;return async t=>{let o=await this.getPosition({...i,owner:n},t);if(a===void 0)return a={liquidity:new e(o?.liquidity??0),fees:new e(o?.fees0??0).plus(new e(o?.fees1??0))},r===`removeFull`&&o===null?{confirmed:!0,position:null}:{confirmed:!1};switch(r){case`add`:return o!==null&&new e(o.liquidity).isGreaterThan(a.liquidity)?{confirmed:!0,position:o}:{confirmed:!1};case`removePartial`:return o!==null&&new e(o.liquidity).isLessThan(a.liquidity)?{confirmed:!0,position:o}:{confirmed:!1};case`removeFull`:return o===null?{confirmed:!0,position:null}:{confirmed:!1};case`collect`:{if(o===null)return{confirmed:!1};let t=new e(o.fees0??0).plus(new e(o.fees1??0));return t.isLessThan(a.fees)||a.fees.isZero()&&t.isZero()?{confirmed:!0,position:o}:{confirmed:!1}}}}}async get(e,t,n){return this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,e,t,n===void 0?void 0:{signal:n})}async getNullable(e,t,n){try{return await this.get(e,t,n)}catch(e){if(this.isNotFound(e))return null;throw e}}isNotFound(e){return!(e instanceof l)||e.details===void 0?!1:e.details.status===404}mapPosition(e){return{token0Symbol:e.token0Symbol,token1Symbol:e.token1Symbol,...e.token0CompositeKey===void 0?{}:{token0CompositeKey:e.token0CompositeKey},...e.token1CompositeKey===void 0?{}:{token1CompositeKey:e.token1CompositeKey},fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,liquidity:e.liquidity,amount0:e.amount0,amount1:e.amount1,inRange:e.inRange,...e.currentTick===void 0?{}:{currentTick:e.currentTick},...e.sqrtPrice===void 0?{}:{sqrtPrice:e.sqrtPrice},pool:e.poolRef??e.pool??``,owner:e.owner,...e.fees0===void 0?{}:{fees0:e.fees0},...e.fees1===void 0?{}:{fees1:e.fees1}}}requestToken(e){return typeof e==`string`?e:q(e)}canonicalTicks(e,t,n){return n?{tickLower:-t,tickUpper:-e}:{tickLower:e,tickUpper:t}}tickSpacing(e){let t=m[e];if(t===void 0)throw new l(`Unsupported fee tier: ${e}.`,`VALIDATION_ERROR`);return t}rejectNumber(e,t){if(typeof e==`number`)throw new l(`Invalid ${t}: use a decimal string or BigNumber, not a JavaScript number`,`VALIDATION_ERROR`)}uniqueKey(){return`gswap-sdk-${globalThis.crypto.randomUUID()}`}async resolveCreateToken(e,t){try{let n=typeof e==`object`?q(e):e,r=await this.symbols.resolve(n);if(t!==void 0&&t!==``&&t!==r.symbol)throw new l(`Supplied symbol ${t} disagrees with the registered trading symbol ${r.symbol}.`,`VALIDATION_ERROR`,{token:e,suppliedSymbol:t,registeredSymbol:r.symbol});let i=this.tryParseClassKey(e);return{symbol:r.symbol,classKey:i??J({collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey})}}catch(n){if(!(n instanceof l)||n.code!==`UNKNOWN_TOKEN`)throw n;let r;try{r=J(e)}catch{throw n}if(t===void 0||t===``)throw new l(`Token is not registered in the trading-symbol registry yet; pass token0Symbol/token1Symbol (the token class symbol) to propose one. A symbol cannot be derived from a class key.`,`VALIDATION_ERROR`,{token:e});if(!/^[A-Za-z0-9]+$/u.test(t))throw new l(`Invalid trading symbol: must be ASCII letters and digits only.`,`VALIDATION_ERROR`,{symbol:t});return{symbol:t,classKey:r}}}tryParseClassKey(e){try{return J(e)}catch{return}}},De=class{constructor(e,t,n){this.dexBackendBaseUrl=e,this.http=t,this.symbols=n}async quoteExactInput(e,t,n,r){return w(n,`amountIn`),this.quote(e,t,{amountIn:Ie(n)},r)}async quoteExactOutput(e,t,n,r){return w(n,`amountOut`),this.quote(e,t,{amountOut:Ie(n)},r)}async quote(e,t,n,r){Fe(r);let i={tokenIn:await Le(this.symbols,e),tokenOut:await Le(this.symbols,t),...n};r!==void 0&&(i.fee=String(r));try{return Oe((await this.http.sendGetRequest(this.dexBackendBaseUrl,`/v2/trade`,`/quote`,i)).data)}catch(n){throw Me(n,e,t,r)}}};function Oe(t){if(!je(t))throw new l(`Backend returned an invalid quote.`,`INVALID_CHAIN_RESPONSE`,{data:t});let n=t,r=n.currentPrice===void 0?Ae(n.currentSqrtPrice,n.tokenInIsToken0):new e(n.currentPrice),i=n.newPrice===void 0?Ae(n.newSqrtPrice,n.tokenInIsToken0):new e(n.newPrice),a=i.minus(r).dividedBy(r);return{contractVersion:n.contractVersion,fee:n.fee,amountIn:n.amountIn,amountOut:n.amountOut,...n.currentSqrtPrice===void 0?{}:{currentSqrtPrice:n.currentSqrtPrice},...n.newSqrtPrice===void 0?{}:{newSqrtPrice:n.newSqrtPrice},feeTier:n.fee,newTick:n.newTick,tradingFees:n.tradingFees,protocolFees:n.protocolFees,totalFees:n.totalFees,feeTokenSymbol:n.feeTokenSymbol,token0Symbol:n.token0Symbol,token1Symbol:n.token1Symbol,tokenInIsToken0:n.tokenInIsToken0,currentPrice:r,newPrice:i,priceImpact:a}}const ke=e.clone({DECIMAL_PLACES:60});function Ae(e,t){let n=new ke(e).pow(2);return t?n:new ke(1).dividedBy(n)}function je(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.contractVersion===`v2`&&typeof t.fee==`number`&&Number.isFinite(t.fee)&&[`amountIn`,`amountOut`,`tradingFees`,`protocolFees`,`totalFees`,`feeTokenSymbol`,`token0Symbol`,`token1Symbol`].every(e=>typeof t[e]==`string`)&&typeof t.newTick==`number`&&Number.isInteger(t.newTick)&&typeof t.tokenInIsToken0==`boolean`&&X(t.currentSqrtPrice)&&X(t.newSqrtPrice)&&X(t.currentPrice)&&X(t.newPrice)&&(t.currentSqrtPrice!==void 0||t.currentPrice!==void 0)&&(t.newSqrtPrice!==void 0||t.newPrice!==void 0)}function X(t){if(t===void 0)return!0;if(typeof t!=`string`)return!1;try{let n=new e(t);return n.isFinite()&&n.isGreaterThan(0)}catch{return!1}}function Me(e,t,n,r){if(e instanceof l){let i=Ne(e.details),a=Pe(e.details)??e.message;return i===404||/no pool|no pools|pool does not exist/iu.test(a)?l.noPoolAvailableError(t,n,r):i===400&&/insufficient liquidity/iu.test(a)?l.insufficientLiquidityError(t,n,r):e}return new l(`Quote request failed.`,`HTTP_ERROR`,{cause:e,tokenIn:t,tokenOut:n,fee:r})}function Ne(e){let t=e?.status;return typeof t==`number`?t:void 0}function Pe(e){let t=e?.message;if(typeof t==`string`)return t;let n=e?.body;if(typeof n!=`object`||!n||Array.isArray(n))return;let r=n.message;return typeof r==`string`?r:void 0}function Fe(e){if(e!==void 0&&!h.some(t=>Number(t)===Number(e)))throw new l(`Invalid fee tier: ${e}`,`VALIDATION_ERROR`,{fee:e})}function Ie(t){return new e(t).toFixed()}async function Le(e,t){let n=await e.resolve(t);if(n.symbol.length>0)return n.symbol;throw new l(`Token could not be resolved to a trading symbol.`,`SYMBOL_NOT_FOUND`,{token:t})}var Re=class{constructor(e){this.gateway=e,c(this,`cachedSymbols`,void 0),c(this,`cachedAt`,0),c(this,`refreshInFlight`,void 0),c(this,`http`,void 0),this.http=new W(e.httpRequestor,e.requestTimeoutMs)}async list(){return this.cachedSymbols!==void 0&&Date.now()-this.cachedAt<6e4?this.cachedSymbols:(this.refreshInFlight===void 0&&(this.refreshInFlight=this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,`/symbols`).then(e=>ze(e.data)).then(e=>(this.cachedSymbols=e,this.cachedAt=Date.now(),e)).finally(()=>{this.refreshInFlight=void 0})),this.refreshInFlight)}invalidate(){this.cachedSymbols=void 0,this.cachedAt=0}async refresh(){return this.invalidate(),this.refreshInFlight=void 0,this.list()}async resolve(e){let t=await this.list(),n=typeof e==`string`?Ve(e)?q(J(e)):void 0:q(e),r=t.find(t=>t.symbol===e||n!==void 0&&q(t)===n);if(r===void 0){t=await this.refresh();let r=t.find(t=>t.symbol===e||n!==void 0&&q(t)===n);if(r===void 0)throw l.unknownTokenError(e);return r}return r}async orderPair(e,t){let[n,r]=await Promise.all([this.resolve(e),this.resolve(t)]),[i,a]=G(n.symbol,r.symbol);return{token0:i===n.symbol?n:r,token1:a===r.symbol?r:n,flipped:i!==n.symbol}}};function ze(e){if(!Array.isArray(e)||!e.every(Be))throw new l(`Backend returned an invalid symbol list.`,`INVALID_CHAIN_RESPONSE`,{data:e});return e}function Be(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.symbol==`string`&&typeof t.collection==`string`&&typeof t.category==`string`&&typeof t.type==`string`&&typeof t.additionalKey==`string`&&typeof t.decimals==`number`&&Number.isInteger(t.decimals)&&t.decimals>=0}function Ve(e){return e.includes(`|`)||e.includes(`$`)}const He=/^[A-Za-z0-9._:-]{1,128}$/u;var Ue=class{constructor(e,t,n,r){this.gateway=e,this.symbols=t,this.signer=n,this.walletAddress=r}async swap(e,t,n,r){T(n);let i=await this.buildRequestTradeDto(e,t,n,r);if(this.signer===void 0)throw l.noSignerError();let a=await this.signer.signObject(`RequestTrade`,i),o=this.walletAddress===void 0?{}:{walletAddress:this.walletAddress};return this.gateway.submit(`RequestTrade`,a,o)}async confirmSwap(e,t){if(!He.test(e))throw new l(`uniqueKey must be 1-128 characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".`,`VALIDATION_ERROR`,{uniqueKey:e});return new j({method:`RequestTrade`,uniqueKey:e,transactionId:null,mode:`queued`,result:void 0,dexBackendBaseUrl:this.gateway.dexBackendBaseUrl,httpRequestor:this.gateway.httpRequestor,requestTimeoutMs:this.gateway.requestTimeoutMs}).confirm({initialDelayMs:0,...t})}async buildRequestTradeDto(e,t,n,r){let i=await We(this.symbols,e),a=K(G(i,await We(this.symbols,t))),o=i===a.token0,s={token0:a.token0,token1:a.token1,fee:n,uniqueKey:`gswap-sdk-${globalThis.crypto.randomUUID()}`};if(`exactIn`in r){let e=r.exactIn;if(e===void 0)throw new l(`exactIn is required for an exact-input swap.`,`VALIDATION_ERROR`);w(e,`exactIn`),s[o?`sell0Qty`:`sell1Qty`]=Z(e),r.amountOutMinimum!==void 0&&(w(r.amountOutMinimum,`amountOutMinimum`,!0),s.amountOutMinimum=Z(r.amountOutMinimum))}else{let e=r.exactOut;if(e===void 0)throw new l(`exactOut is required for an exact-output swap.`,`VALIDATION_ERROR`);w(e,`exactOut`),s[o?`buy1Qty`:`buy0Qty`]=Z(e),r.amountInMaximum!==void 0&&(w(r.amountInMaximum,`amountInMaximum`,!0),s.amountInMaximum=Z(r.amountInMaximum))}return s}};function Z(t){return new e(t).toFixed()}async function We(e,t){let n=await e.resolve(t);if(n.symbol.length>0)return n.symbol;throw new l(`Token could not be resolved to a trading symbol.`,`SYMBOL_NOT_FOUND`,{token:t})}var Ge=class{constructor(e){c(this,`dexBackendBaseUrl`,void 0),c(this,`chainCallTimeoutMs`,void 0),c(this,`signer`,void 0),c(this,`walletAddress`,void 0),c(this,`gateway`,void 0),c(this,`symbols`,void 0),c(this,`quoting`,void 0),c(this,`pools`,void 0),c(this,`positions`,void 0),c(this,`swaps`,void 0),c(this,`assets`,void 0),c(this,`dexBackendWsUrl`,void 0),c(this,`webSocketImpl`,void 0),c(this,`streamClient`,void 0);let t=z[e?.env??`prod`];this.dexBackendBaseUrl=Ke(e?.dexBackendBaseUrl??t.dexBackendBaseUrl),this.chainCallTimeoutMs=e?.chainCallTimeoutMs??3e4,this.signer=e?.signer,this.walletAddress=e?.walletAddress;let n=new W(e?.httpRequestor,this.chainCallTimeoutMs);this.gateway=new F({dexBackendBaseUrl:this.dexBackendBaseUrl,chainCallTimeoutMs:this.chainCallTimeoutMs,...e?.httpRequestor===void 0?{}:{httpRequestor:e.httpRequestor},...this.walletAddress===void 0?{}:{walletAddress:this.walletAddress}}),this.symbols=new Re(this.gateway),this.quoting=new De(this.dexBackendBaseUrl,n,this.symbols),this.pools=new xe(this.gateway,this.symbols),this.positions=new Ee(this.gateway,this.symbols,this.signer,this.walletAddress),this.swaps=new Ue(this.gateway,this.symbols,this.signer,this.walletAddress),this.assets=new D(this.dexBackendBaseUrl,n),this.dexBackendWsUrl=e?.dexBackendWsUrl??(e?.dexBackendBaseUrl===void 0?t.dexBackendWsUrl:`${this.dexBackendBaseUrl.replace(/^http/u,`ws`)}/ws`),this.webSocketImpl=e?.webSocketImpl}get stream(){return this.streamClient??(this.streamClient=new U({url:this.dexBackendWsUrl,...this.webSocketImpl===void 0?{}:{webSocketImpl:this.webSocketImpl}})),this.streamClient}};function Ke(e){return e.replace(/\/$/u,``)}function qe(e,t){let n={};n[e]=[];function r(e){let t=n[e];
|
|
1
|
+
import e from"bignumber.js";import{Decimal as t}from"decimal.js";import n from"debug";import{secp256k1 as r}from"@noble/curves/secp256k1";import{keccak_256 as i}from"@noble/hashes/sha3";import{bytesToHex as a}from"@noble/hashes/utils";function o(e,t,n){let r=Math.max(0,e?.timeoutMs??6e4),i=Math.max(500,e?.pollIntervalMs??2e3),a=Math.max(0,e?.initialDelayMs??t),o=e?.signal,u=Date.now()+r,d=!0,f=0;return{async waitForRead(e){if(s(o,n),d){d=!1;let e=Math.max(0,u-Date.now());return await c(Math.min(a,e),o,n),!0}let t=Math.min(8e3,i*2**Math.min(f,5));f+=1;let r=e===void 0?l(t):Math.max(0,e);return Date.now()+r>u?!1:(await c(r,o,n),!0)}}}function s(e,t){if(e?.aborted===!0)throw t(e.reason)}function c(e,t,n){return t?.aborted===!0?Promise.reject(n(t.reason)):new Promise((r,i)=>{let a=()=>{clearTimeout(o),i(n(t?.reason))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function l(e){return Math.max(0,Math.round(e*(.9+Math.random()*.2)))}function u(e){"@babel/helpers - typeof";return u=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},u(e)}function d(e,t){if(u(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(u(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function f(e){var t=d(e,`string`);return u(t)==`symbol`?t:t+``}function p(e,t,n){return(t=f(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var m=class e extends Error{constructor(e,t,n,r,i){super(e),this.code=t,this.details=n,p(this,`chainMessage`,void 0),p(this,`retryAfterMs`,void 0),p(this,`status`,void 0),p(this,`body`,void 0),p(this,`bodyText`,void 0),this.name=`GSwapSDKError`,this.chainMessage=r,this.retryAfterMs=i;let a=n?.status;this.status=typeof a==`number`?a:void 0;let o=n?.body;this.body=typeof o==`string`?void 0:o,this.bodyText=typeof o==`string`?o:void 0}get userMessage(){return this.chainMessage!==void 0&&this.chainMessage!==``?this.chainMessage:this.code===`HTTP_ERROR`&&this.status!==void 0?`The server answered with an unexpected response (HTTP ${this.status}).`:this.message}get notFound(){return this.status===404||this.code===`NO_POOL_AVAILABLE`||this.code===`UNKNOWN_TOKEN`}static noSignerError(){return new e(`This method requires a signer. Please provide a signer to the GSwap constructor.`,`NO_SIGNER`)}static noWalletAddressError(){return new e(`Cannot confirm this write: no walletAddress was provided to the GSwap constructor, so the resulting position cannot be looked up to confirm it landed on chain.`,`NO_WALLET_ADDRESS`)}static noPoolAvailableError(t,n,r,i){return new e(`No pool is available for the requested pair.`,`NO_POOL_AVAILABLE`,{tokenIn:t,tokenOut:n,...r===void 0?{}:{fee:r},...h(i)},i?.serverMessage)}static insufficientLiquidityError(t,n,r,i){return new e(`The selected pool has insufficient liquidity for the requested quote.`,`INSUFFICIENT_LIQUIDITY`,{tokenIn:t,tokenOut:n,...r===void 0?{}:{fee:r},...h(i)},i?.serverMessage)}get serverMessage(){let e=this.details?.message;if(typeof e==`string`)return e;let t=this.body;return _(t,`message`)??_(t,`Message`)??_(g(t,`error`),`Message`)}static fromGatewayBounce(t,n,r,i){let a={status:r,chainMessage:n};i!==void 0&&(a.retryAfterMs=i);let o=t===`CHAIN_DISPATCH_FAILED`?n:`Gateway rejected ${t}: ${n}`;return new e(o,t,a,n,i)}static fromChainError(t,n,r){return new e(`GalaChain error ${t}: ${n}`,t,{...r,errorKey:t,message:n},n)}static unknownTokenError(t){let n=typeof t==`string`?t:JSON.stringify(t);return new e(`Token ${n} has no trading symbol on the new DEX contract (no gcdex pool includes it yet).`,`UNKNOWN_TOKEN`,{token:t})}static confirmationTimeoutError(t,n){return new e(`Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.`,`CONFIRMATION_TIMEOUT`,{uniqueKey:t,...n===void 0?{}:{cause:n}})}static async fromErrorResponse(t,n){let r=await n.text(),i=ee(r),a=g(i,`error`),o=_(a,`ErrorKey`),s=_(a,`Message`);return o!==void 0&&s!==void 0?new e(`GalaChain Error ${o} from ${t}: ${s}`,o,{message:s,errorKey:o,status:n.status,body:i,url:t},s):new e(`Unexpected HTTP Error ${n.status} from ${t}`,`HTTP_ERROR`,{status:n.status,body:i??r,url:t})}};function h(e){return e===void 0?{}:{...e.status===void 0?{}:{status:e.status},...e.body===void 0?{}:{body:e.body},...e.bodyText===void 0?{}:{body:e.bodyText}}}function g(e,t){if(typeof e!=`object`||!e||!(t in e))return;let n=e[t];return typeof n==`object`&&n?n:void 0}function _(e,t){if(typeof e!=`object`||!e||!(t in e))return;let n=e[t];return typeof n==`string`?n:void 0}function ee(e){try{return JSON.parse(e)}catch{return}}function v(e,t){if(t===1/0)return()=>void 0;let n=setTimeout(()=>e.abort(),t);return()=>clearTimeout(n)}function te(e,t){if(e===1/0||Number.isFinite(e)&&e>0)return e;throw new m(`${t} must be a positive number of milliseconds, or Infinity for no timeout.`,`VALIDATION_ERROR`,{[t]:e})}const ne=/[A-Za-z0-9\-._~!'()*$|:,]/u;function re(e){let t=``;for(let n of e)n===` `?t+=`+`:ne.test(n)?t+=n:t+=ie(n);return t}function ie(e){try{return encodeURIComponent(e)}catch{return`%EF%BF%BD`}}function ae(e,t=`standard`){return t===`readable`?Object.entries(e).map(([e,t])=>`${re(e)}=${re(t)}`).join(`&`):new URLSearchParams(e).toString()}async function oe(e,t,n,r){let i=new AbortController,a=v(i,r),o=n.signal,s=()=>i.abort();o?.addEventListener(`abort`,s,{once:!0});try{return await e(t,{...n,signal:i.signal})}catch(e){throw i.signal.aborted?new m(`Request timed out after ${r} ms.`,`REQUEST_TIMEOUT`,{url:t,timeoutMs:r,cause:e}):e}finally{a(),o?.removeEventListener(`abort`,s)}}async function y(e){let t=await e.text();return ee(t)??t}function se(e,t){let n=e.headers;if(n===void 0)return;if(ue(n)){let e=n.get(t);return e===null||e===``?void 0:e}let r=Object.entries(n).find(([e])=>e.toLowerCase()===t.toLowerCase())?.[1];return r===void 0||r===``?void 0:r}function ce(e){let t=se(e,`retry-after`);if(t===void 0)return;let n=Number(t);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}function le(e,t=`x-block-number`){let n=se(e,t);if(n===void 0)return;let r=Number(n);return Number.isInteger(r)&&r>=0?r:void 0}function ue(e){return`get`in e&&typeof e.get==`function`}const de=/^[A-Za-z0-9._:-]{1,128}$/u;var b=class extends m{constructor(e,t,n={},r){super(e,t,n,r),this.name=`AppliedTradeError`}};async function fe(e,t,n){let{uniqueKey:r}=t;if(!de.test(r))throw new b(`uniqueKey must be 1-128 characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".`,`CONFIRMATION_FAILED`,{uniqueKey:r});let i=e.httpRequestor??fetch.bind(globalThis),a=e.requestTimeoutMs??3e4,c=n?.signal,l=e=>new b(`Transaction confirmation was aborted.`,`CONFIRMATION_ABORTED`,{uniqueKey:r,...e===void 0?{}:{cause:e}}),u=`${e.dexBackendBaseUrl.replace(/\/$/u,``)}/v1/chain/apply-results/${encodeURIComponent(r)}?channel=asset&contract=dex-contract`,d=o(n,3e3,l);await d.waitForRead();let f;for(;;){s(c,l);let e,n;try{e=await oe(i,u,{method:`GET`,...c===void 0?{}:{signal:c}},a),n=await y(e)}catch(e){if(s(c,l),f=e,!await d.waitForRead())break;continue}if(s(c,l),e.status===200)return pe(t,e,n,u);if(e.status===404||e.status===429||ge(e.status)){let t=e.status===429?ce(e):void 0;if(!await d.waitForRead(t))break;continue}throw new b(_e(n),`CONFIRMATION_FAILED`,{uniqueKey:r,status:e.status,body:n,url:u})}throw new b(`Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.`,`CONFIRMATION_TIMEOUT`,{uniqueKey:r,requestTransactionId:t.requestTransactionId,url:u,...f===void 0?{}:{cause:f}})}function pe(e,t,n,r){let{uniqueKey:i}=e,a=ve(n),o=a?.uniqueKey??a?.UniqueKey;if(typeof o==`string`&&o!==i)throw me(e,t,n,r,`Apply result key did not match the requested key.`);let s=a?.Status,c=se(t,`x-apply-transaction-id`)??null,l=le(t,`x-apply-block-number`)??null;if(s===0){let o=_(a,`ErrorKey`)??`CHAIN_ERROR`,s=_(a,`Message`)??`The chain rejected this trade.`;throw new b(s,o,{uniqueKey:i,requestTransactionId:e.requestTransactionId,applyTransactionId:c,blockNumber:l,status:t.status,body:n,url:r,errorKey:o,message:s},s)}if(s!==1)throw me(e,t,n,r);let u=he(a?.Data);if(u===void 0)throw me(e,t,n,r);return{uniqueKey:i,transactionId:c,blockNumber:l,requestTransactionId:e.requestTransactionId,result:u}}function me(e,t,n,r,i=`Transaction confirmation returned a malformed body`){return new b(i,`CONFIRMATION_FAILED`,{uniqueKey:e.uniqueKey,status:t.status,body:n,url:r})}function he(e){let t=ve(e);if(t===void 0||typeof t.token0!=`string`||typeof t.token1!=`string`||typeof t.fee!=`number`)return;let n=[`sell0Qty`,`sell1Qty`,`buy0Qty`,`buy1Qty`,`tradingFees`,`protocolFees`,`totalFees`];for(let e of n)if(e in t&&typeof t[e]!=`string`)return;return{token0:t.token0,token1:t.token1,fee:t.fee,...Object.fromEntries(n.flatMap(e=>typeof t[e]==`string`?[[e,t[e]]]:[]))}}function ge(e){return e===500||e===502||e===503||e===504}function _e(e){return _(e,`message`)??_(e,`Message`)??_(g(e,`error`),`message`)??_(g(e,`error`),`Message`)??`Transaction confirmation failed`}function ve(e){return typeof e==`object`&&e?e:void 0}let ye=/* @__PURE__ */ function(e){return e[e.PERCENT_00_00=0]=`PERCENT_00_00`,e[e.PERCENT_00_05=500]=`PERCENT_00_05`,e[e.PERCENT_00_30=3e3]=`PERCENT_00_30`,e[e.PERCENT_01_00=1e4]=`PERCENT_01_00`,e}({});const be={0:200,500:10,3e3:60,1e4:200},xe=[0,500,3e3,1e4],x=-887272,S=887272,Se=e.clone({DECIMAL_PLACES:60,ROUNDING_MODE:e.ROUND_DOWN}),C=t.clone({precision:60});function Ce(t){return new e(new C(1.0001).pow(t/2).toString())}function we(e){let t;try{t=new Se(e)}catch{return NaN}if(!t.isFinite()||t.isLessThanOrEqualTo(0))return NaN;let n=Math.log(t.toNumber()**2)/Math.log(1.0001);if(!Number.isFinite(n))return NaN;let r=Math.min(S,Math.max(x,Math.floor(n)));for(;r<887272&&Ce(r+1).isLessThanOrEqualTo(t);)r+=1;for(;r>-887272&&Ce(r).isGreaterThan(t);)--r;return r}function Te(t){let n=typeof t==`string`?t:typeof t==`number`||e.isBigNumber(t)?t.toString():`NaN`,r=new C(n);if(!r.isFinite()||r.lessThanOrEqualTo(0)||!Number.isFinite(r.toNumber()))return NaN;let i=r.ln().dividedBy(new C(1.0001).ln()).floor().toNumber();return Number.isFinite(i)?i:NaN}function Ee(e,t){return Oe(t),Math.floor(e/t)*t}function De(e,t){return Oe(t),Math.ceil(e/t)*t}function w(e,t,n){let r=be[n];if(r===void 0)throw RangeError(`Unsupported fee tier: ${n}`);if(!Number.isInteger(e)||!Number.isInteger(t))throw RangeError(`Ticks must be integers`);if(e<-887272||t>887272||e>=t)throw RangeError(`Tick range must satisfy ${x} <= lower < upper <= ${S}`);if(e%r!==0||t%r!==0)throw RangeError(`Ticks must be aligned to spacing ${r}`)}function Oe(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`Tick spacing must be positive`)}function ke(e){if(e.flippedFromRequest!==!0)return{sqrtPrice:e.sqrtPrice,tick:e.tick};let t=new C(1).dividedBy(new C(e.sqrtPrice));if(!t.isFinite()||t.lessThanOrEqualTo(0))throw new m(`Cannot invert a non-positive sqrt price.`,`VALIDATION_ERROR`,{sqrtPrice:e.sqrtPrice});let n=t.toString();return{sqrtPrice:n,tick:we(n)}}function T(t,n,r=!1){if(typeof t==`number`)throw new m(`Invalid ${n}: use a decimal string or BigNumber, not a JavaScript number`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,parameterName:n,value:t,reason:`number_input`});let i;try{i=e(t)}catch{i=e(NaN)}if(!i.isFinite())throw new m(`Invalid ${n}: must be a finite number`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,parameterName:n,value:t,reason:`not_finite`});if(!r&&i.isZero())throw new m(`Invalid ${n}: must be positive`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,parameterName:n,value:t,reason:`zero_not_allowed`});if(i.isNegative())throw new m(`Invalid ${n}: must be ${r?`non-negative`:`positive`}`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,parameterName:n,value:t,reason:`negative`})}function Ae(t,n,r){if([t,n,r].some(e=>typeof e==`number`))throw new m(`Invalid price values: use decimal strings or BigNumber values, not JavaScript numbers`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,reason:`number_input`});let i=t=>{try{return e(t)}catch{return e(NaN)}},a=i(t),o=i(n),s=i(r);if(s=s.isFinite()?s:e(0xde0b6b3a7640000),!a.isFinite()||!o.isFinite()||!s.isFinite()||!a.isPositive()||!o.isPositive()||!s.isPositive())throw new m(`Invalid price values: all prices must be finite and positive`,`VALIDATION_ERROR`,{type:`INVALID_PRICE_VALUES`,spotPrice:t,lowerPrice:n,upperPrice:r});if(o.isGreaterThan(s))throw new m(`Invalid price range: lower price must be less than or equal to upper price`,`VALIDATION_ERROR`,{type:`INVALID_PRICE_RANGE`,lowerPrice:n,upperPrice:r})}function je(e,t){if(e<0||!Number.isInteger(e))throw new m(`Invalid ${t}: must be a non-negative integer`,`VALIDATION_ERROR`,{type:`INVALID_TOKEN_DECIMALS`,parameterName:t,value:e})}function Me(e,t){if(!Number.isInteger(e)||!Number.isInteger(t))throw new m(`Invalid tick values: ticks must be integers`,`VALIDATION_ERROR`,{type:`INVALID_TICK_VALUES`,tickLower:e,tickUpper:t});if(e>=t)throw new m(`Invalid tick range: tickLower must be less than tickUpper`,`VALIDATION_ERROR`,{type:`INVALID_TICK_RANGE`,tickLower:e,tickUpper:t});if(e<-887272||t>887272)throw new m(`Invalid tick range: ticks must be between ${x} and ${S}`,`VALIDATION_ERROR`,{type:`INVALID_TICK_BOUNDS`,tickLower:e,tickUpper:t,minTick:x,maxTick:S})}function E(e){if(!xe.some(t=>Number(t)===e))throw new m(`Invalid fee tier: must be one of 0, 500, 3000, or 10000`,`VALIDATION_ERROR`,{type:`INVALID_FEE`,value:e})}function Ne(e){if(!Number.isInteger(e)||e<=0)throw new m(`Invalid tick spacing: must be a positive integer`,`VALIDATION_ERROR`,{type:`INVALID_TICK_SPACING`,value:e})}function Pe(e){if(e===void 0)throw new m(`Invalid wallet address: No wallet address provided`,`VALIDATION_ERROR`,{type:`MISSING_WALLET_ADDRESS`,hint:`Either provide a wallet address to the function you are calling, or set one when instantiating GSwapSDK`});if(!e||typeof e!=`string`||e.trim().length===0)throw new m(`Invalid wallet address: must be a non-empty string`,`VALIDATION_ERROR`,{type:`INVALID_WALLET_ADDRESS`,value:e})}const Fe=/* @__PURE__ */ new Set([`Token`,`Unit`,`none`]),Ie=/^[A-Za-z0-9]+$/u;function D(e){return Ie.test(e)&&e.length<=32&&!Fe.has(e)}function O(e,t){if(!(e<t))throw new m(`The pair ${e}/${t} is not in canonical order: token0 must sort before token1.`,`VALIDATION_ERROR`,{type:`NON_CANONICAL_PAIR`,token0:e,token1:t})}var Le=class{constructor(e,t){this.dexBackendBaseUrl=e,this.httpClient=t}async getUserAssets(e,t=1,n=10){if(Pe(e),!Number.isInteger(t)||t<1)throw new m(`Invalid page: must be a positive integer`,`VALIDATION_ERROR`,{page:t});if(!Number.isInteger(n)||n<1||n>100)throw new m(`Invalid limit: must be an integer between 1 and 100`,`VALIDATION_ERROR`,{limit:n});return Re(await this.httpClient.sendGetRequest(this.dexBackendBaseUrl,`/user/assets`,``,{address:e,page:t.toString(),limit:n.toString()}))}};function Re(e){let t=g(e,`data`),n=t?.token;if(!Array.isArray(n)||!n.every(ze))throw new m(`Backend returned an invalid user assets response.`,`INVALID_CHAIN_RESPONSE`,{data:e});let r=t?.count;return{tokens:n.map(e=>({...e,decimals:parseInt(e.decimals,10)})),count:typeof r==`number`?r:0}}function ze(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.image==`string`&&typeof t.name==`string`&&typeof t.decimals==`string`&&/^\d+$/u.test(t.decimals)&&typeof t.verify==`boolean`&&typeof t.symbol==`string`&&typeof t.quantity==`string`}const Be=[`Swap`,`RequestTrade`,`AddLiquidity`,`RemoveLiquidity`,`CollectPositionFees`,`CreatePool`],Ve=`DryRun`,He=`galaconnect-operation-`;function Ue(e){return typeof e==`string`&&Be.includes(e)}function We(e,t){return Ue(t)&&typeof e?.token0==`string`&&typeof e.token1==`string`}function Ge(e){let t={...e};for(let e of[`signature`,`prefix`,`types`,`domain`,`trace`])delete t[e];return t}function Ke(e,t,n,r,i=He){return e.signObject(Ve,{callerPublicKey:t,method:n,dto:r,uniqueKey:`${i}${globalThis.crypto.randomUUID()}`})}var qe=class{constructor(e,t){this.signer=t,p(this,`requestor`,void 0),p(this,`baseUrl`,void 0),p(this,`requestTimeoutMs`,void 0),this.requestor=e.httpRequestor??fetch.bind(globalThis),this.baseUrl=e.dexBackendBaseUrl.replace(/\/$/u,``),this.requestTimeoutMs=e.requestTimeoutMs??3e4}async quote(e,t,n,r={}){if(this.signer===void 0)throw m.noSignerError();let i=r.channel??`asset`,a=r.contract??`dexv3-contract`,o=await Ke(this.signer,e,t,Ge(n)),s=`${this.baseUrl}/wallet/connect/galachain/api/${encodeURIComponent(i)}/${encodeURIComponent(a)}/${encodeURIComponent(t)}/fee`,c,l,u;try{let e=await oe(this.requestor,s,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(o)},this.requestTimeoutMs);c=e.status,l=e.ok,u=l?await y(e):void 0}catch{return null}return l?Je(u):a===`dex-contract`&&(c===403||c===404)?{source:`default`,fees:[{feeInGala:`0`}]}:null}};function Je(e){if(typeof e!=`object`||!e)return null;let t=e.fees;return!Array.isArray(t)||typeof t[0]?.feeInGala!=`string`?null:e}var Ye=class{constructor(e){p(this,`method`,void 0),p(this,`uniqueKey`,void 0),p(this,`transactionId`,void 0),p(this,`blockNumber`,void 0),p(this,`mode`,void 0),p(this,`result`,void 0),p(this,`envelope`,void 0),p(this,`backendBaseUrl`,void 0),p(this,`requestor`,void 0),p(this,`requestTimeoutMs`,void 0),p(this,`positionConfirmation`,void 0),this.method=e.method,this.uniqueKey=e.uniqueKey,this.transactionId=e.transactionId,this.blockNumber=e.blockNumber??null,this.mode=e.mode,this.result=e.result,this.envelope=e.envelope,this.backendBaseUrl=e.dexBackendBaseUrl.replace(/\/$/u,``),this.requestor=e.httpRequestor,this.requestTimeoutMs=e.requestTimeoutMs??3e4,this.positionConfirmation=e.positionConfirmation}async confirm(e){return this.method===`RequestTrade`?this.confirmApplied(e):this.confirmPosition(e)}confirmApplied(e){return fe({dexBackendBaseUrl:this.backendBaseUrl,httpRequestor:this.requestor,requestTimeoutMs:this.requestTimeoutMs},{uniqueKey:this.uniqueKey,requestTransactionId:this.transactionId},e)}async confirmPosition(e){if(this.positionConfirmation===void 0)throw m.noWalletAddressError();let t=e?.signal,n=e=>new m(`Transaction confirmation was aborted.`,`CONFIRMATION_ABORTED`,{uniqueKey:this.uniqueKey,...e===void 0?{}:{cause:e}}),r=o(e,0,n);for(await r.waitForRead();;){let e=new AbortController,i=v(e,this.requestTimeoutMs),a=()=>e.abort();t?.addEventListener(`abort`,a,{once:!0});try{let t=await this.positionConfirmation(e.signal);if(t.confirmed)return t.position}catch(e){throw s(t,n),e}finally{i(),t?.removeEventListener(`abort`,a)}if(!await r.waitForRead())break}throw m.confirmationTimeoutError(this.uniqueKey)}},Xe=class{constructor(e){p(this,`requestor`,void 0),p(this,`walletAddress`,void 0),p(this,`chainCallTimeoutMs`,void 0),p(this,`requestTimeoutMs`,void 0),p(this,`dexBackendBaseUrl`,void 0),p(this,`wire`,void 0),this.dexBackendBaseUrl=Ze(e.dexBackendBaseUrl),this.requestor=e.httpRequestor??fetch.bind(globalThis),this.walletAddress=e.walletAddress,this.chainCallTimeoutMs=te(e.chainCallTimeoutMs??3e4,`chainCallTimeoutMs`),this.requestTimeoutMs=this.chainCallTimeoutMs,this.wire=e.wire??{}}async submit(e,t,n){if(e===`Trade`)throw new m(`The synchronous Trade method was removed; swaps are queued through RequestTrade.`,`METHOD_NOT_SUPPORTED`,{method:e});let r=this.writeUrl(e),i={"content-type":`application/json`},a=n?.walletAddress??this.walletAddress;a!==void 0&&(i[`X-Wallet-Address`]=a);let o=await this.post(r,i,t),s=await y(o);if(!o.ok)throw Qe(o,s,r);let c=A(s),l=A(c?.data??c?.Data);if(l===void 0)throw k(o,s,r,`Expected a data object.`);let u=_(l,`transactionId`),d=_(l,`mode`),f=l.transactionId,p=l.blockNumber,h=`Gateway response must contain data.mode="sync" with data.result, or data.mode="queued".`;if(d!==`sync`&&d!==`queued`||`transactionId`in l&&typeof f!=`string`||p!=null&&!$e(p))throw k(o,s,r,h);if(e===`RequestTrade`&&d===`sync`)throw k(o,s,r,`The gateway executed RequestTrade synchronously, which this SDK refuses; RequestTrade must be queued.`);if(e===`RequestTrade`&&d===`queued`){let e=_(t,`uniqueKey`);if(`uniqueKey`in l&&(typeof l.uniqueKey!=`string`||l.uniqueKey!==e))throw k(o,s,r,`Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey.`)}else if(d===`queued`||!(`result`in l))throw k(o,s,r,h);if(d===`sync`){let e=A(l.result);if(e!==void 0){let t=e.Status;if(t!==void 0&&t!==1)throw m.fromChainError(_(e,`ErrorKey`)??`CHAIN_ERROR`,_(e,`Message`)??`The chain rejected this write.`,{status:o.status,body:s,url:r})}}let g=_(t,`uniqueKey`)??``,ee=se(o,`x-transaction-id`),v=u===void 0||u===``?ee:u,te=p==null?le(o):$e(p)?p:void 0;return new Ye({method:e,uniqueKey:g,transactionId:v===void 0||v===``?null:v,blockNumber:te??null,mode:d,result:d===`queued`?void 0:l.result,envelope:s,dexBackendBaseUrl:this.dexBackendBaseUrl,httpRequestor:this.requestor,requestTimeoutMs:this.chainCallTimeoutMs,...n?.positionConfirmation===void 0?{}:{positionConfirmation:n.positionConfirmation}})}async submitShadow(e,t,n){if(e===`Trade`)throw new m(`The synchronous Trade method was removed; swaps are queued through RequestTrade.`,`METHOD_NOT_SUPPORTED`,{method:e});let r=n?.walletAddress??this.walletAddress;if(r===void 0)throw new m(`A shadow submission needs a walletAddress (the X-Wallet-Address header): pass one to the GSwap constructor or to this call.`,`NO_WALLET_ADDRESS`);let i={"content-type":`application/json`,"X-Wallet-Address":r,"X-Shadow":`true`},a=await this.post(this.writeUrl(e),i,t);return{httpStatus:a.status,body:await y(a)}}writeUrl(e){return`${this.dexBackendBaseUrl}/v1/chain/asset/dex-contract/${e}`}async post(e,t,n){try{return await oe(this.requestor,e,{method:`POST`,headers:t,body:JSON.stringify(n)},this.chainCallTimeoutMs)}catch(e){throw e instanceof m&&e.code===`REQUEST_TIMEOUT`?new m(`The submission outcome is unknown because the gateway request timed out. Confirm before retrying.`,`SUBMISSION_OUTCOME_UNKNOWN`,{uniqueKey:_(n,`uniqueKey`)??``,cause:e}):e}}get httpRequestor(){return this.requestor}};function Ze(e){return e.replace(/\/$/u,``)}function k(e,t,n,r){return new m(r,`INVALID_GATEWAY_RESPONSE`,{status:e.status,body:t,url:n})}function Qe(e,t,n){let r=A(t),i=g(t,`error`),a=_(r,`code`)??_(i,`code`)??_(i,`ErrorKey`)??`HTTP_ERROR`,o=_(r,`message`)??_(i,`message`)??_(i,`Message`)??`Gateway request failed with HTTP ${e.status}`,s=e.status===429?ce(e):void 0;return a===`HTTP_ERROR`?new m(o,a,{status:e.status,body:t,url:n}):m.fromGatewayBounce(a,o,e.status,s)}function A(e){return typeof e==`object`&&e?e:void 0}function $e(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}const et={prod:{dexBackendBaseUrl:`https://dex-backend-prod1.defi.gala.com`,dexBackendWsUrl:`wss://dex-backend-prod1.defi.gala.com/ws`},stage:{dexBackendBaseUrl:`https://swap-backend.stage.defi.ovh.gala.com`,dexBackendWsUrl:`wss://swap-backend.stage.defi.ovh.gala.com/ws`}},j=n(`GSWAP_SDK`);var tt=class{constructor(e){this.options=e,p(this,`attempts`,0),p(this,`delayMs`,void 0),p(this,`maxDelayMs`,void 0),this.delayMs=e.baseDelayMs,this.maxDelayMs=e.maxDelayMs??3e4}shouldRetry(){return this.attempts<this.options.maxAttempts}nextDelayMs(){return this.delayMs}recordAttempt(){this.attempts+=1,this.delayMs=Math.min(this.delayMs*2,this.maxDelayMs)}reset(){this.attempts=0,this.delayMs=this.options.baseDelayMs}get attemptCount(){return this.attempts}get maxAttempts(){return this.options.maxAttempts}};const nt=`gdex.jsonrpc.v1`,rt=[`add`,`remove`,`collect`];function it(e){let{pool:t}=e;return(e.version===`v1`||e.version===`v2`)&&typeof t==`object`&&!!t&&typeof e.poolHash==`string`&&typeof e.transactionId==`string`&&rt.includes(e.action)&&typeof e.owner==`string`&&typeof e.amount0==`string`&&typeof e.amount1==`string`&&typeof e.blockNumber==`number`&&typeof e.timestamp==`string`}var M=class extends Error{constructor(e,t,n){super(t),p(this,`code`,void 0),p(this,`data`,void 0),this.name=`GdexStreamError`,this.code=e,n!==void 0&&(this.data=n)}};function at(e){let t=typeof e==`object`&&e?e.subscriptionId:void 0;if(typeof t!=`string`)throw new M(-32603,`GDEX subscribe response is missing its subscriptionId`);return t}var ot=class{constructor(e={}){p(this,`url`,void 0),p(this,`requestTimeoutMs`,void 0),p(this,`apiKey`,void 0),p(this,`webSocketConstructor`,void 0),p(this,`backoff`,void 0),p(this,`socket`,void 0),p(this,`connectPromise`,void 0),p(this,`nextRequestId`,0),p(this,`pending`,/* @__PURE__ */ new Map),p(this,`subscriptionsByServerId`,/* @__PURE__ */ new Map),p(this,`activeSubscriptions`,/* @__PURE__ */ new Set),p(this,`intentionalClose`,!1),p(this,`reconnecting`,!1),p(this,`reconnectTimer`,void 0),p(this,`reconnectDelayResolve`,void 0),this.url=e.url??et.prod.dexBackendWsUrl,this.requestTimeoutMs=e.requestTimeoutMs??15e3,this.backoff=new tt({maxAttempts:e.reconnectAttempts??5,baseDelayMs:e.reconnectDelayMs??2e3});let t=e.webSocketImpl??globalThis.WebSocket;if(typeof t!=`function`)throw Error(`GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the "ws" package).`);if(this.webSocketConstructor=t,e.apiKey!==void 0){if(e.apiKey===``||e.webSocketImpl===void 0)throw new m(`GdexStreamConfig.apiKey needs a non-empty key and an explicit webSocketImpl that accepts upgrade headers as its third argument (the "ws" package, or React Native). A browser WebSocket cannot send x-api-key, so the key would be silently dropped.`,`VALIDATION_ERROR`);this.apiKey=e.apiKey}}connect(){return this.isConnected()?Promise.resolve():this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.clearReconnectTimer(),this.connectPromise=this.openSocket(),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.reconnecting=!1,this.clearReconnectTimer(),this.rejectPending(/* @__PURE__ */ Error(`GDEX stream disconnected`));let e=this.socket;this.socket=void 0,this.connectPromise=void 0,e?.close(1e3,`client disconnect`)}isConnected(){return this.socket?.readyState===1}request(e,t){return this.send(e,t)}send(e,t,n){if(!this.isConnected()||!this.socket)return Promise.reject(/* @__PURE__ */ Error(`GDEX stream is not connected. Call connect() first.`));let r=++this.nextRequestId,i={jsonrpc:`2.0`,id:r,method:e};return t!==void 0&&(i.params=t),new Promise((t,a)=>{let o=setTimeout(()=>{this.pending.delete(r),a(/* @__PURE__ */ Error(`GDEX request "${e}" timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);this.pending.set(r,{resolve:e=>t(e),reject:a,timeout:o,onResult:n});try{this.socket?.send(JSON.stringify(i))}catch(e){clearTimeout(o),this.pending.delete(r),a(e instanceof Error?e:Error(String(e)))}})}serverInfo(){return this.request(`gdex_serverInfo`)}ping(){return this.request(`gdex_ping`)}getPool(e){return this.request(`gdex_getPool`,e)}getBalance(e,t){return this.request(`gdex_getBalance`,t===void 0?{owner:e}:{owner:e,tokenClassKey:t})}getPositions(e){return this.request(`gdex_getPositions`,e)}getBlockHeight(){return this.request(`gdex_getBlockHeight`)}quote(e){return this.request(`gdex_quote`,e)}getToken(e){return this.request(`gdex_getToken`,{tokenClassKey:e})}subscribeSwaps(e,t={}){return this.subscribe(`swap`,e,t)}subscribePool(e,t,n={}){return this.subscribe(`pool`,t,{...e,...n})}subscribeBalances(e,t,n={}){return this.subscribe(`balance`,t,{owner:e,...n})}subscribePoolCreated(e,t={}){return this.subscribe(`poolCreated`,e,t)}subscribeLiquidity(e,t={}){return this.subscribe(`liquidity`,t=>{it(t)?e(t):j(`Ignoring a malformed liquidity event from the GDEX stream`)},t)}subscribeBlocks(e,t={}){return this.subscribe(`blocks`,e,t)}openSocket(){return new Promise((e,t)=>{let n=!1,r=this.apiKey===void 0?new this.webSocketConstructor(this.url,nt):new this.webSocketConstructor(this.url,nt,{headers:{"x-api-key":this.apiKey}});this.socket=r,r.onopen=()=>{this.socket===r&&(n=!0,this.connectPromise=void 0,this.reconnecting||this.backoff.reset(),j(`Connected to GDEX stream`),e())},r.onmessage=e=>this.handleMessage(e.data),r.onerror=()=>{n||t(/* @__PURE__ */ Error(`Failed to connect to GDEX stream at ${this.url}`))},r.onclose=e=>{this.socket===r&&(this.socket=void 0,this.connectPromise=void 0,n||t(/* @__PURE__ */ Error(`GDEX stream closed before connecting (code ${e.code??0})`)),this.rejectPending(/* @__PURE__ */ Error(`GDEX stream connection closed (code ${e.code??0})`)),!this.intentionalClose&&!this.reconnecting&&this.startReconnectLoop())}})}handleMessage(e){if(typeof e!=`string`){j(`Ignoring non-text GDEX WebSocket frame`);return}let t;try{t=JSON.parse(e)}catch{j(`Ignoring invalid JSON from GDEX stream`);return}if(typeof t.id==`number`){let e=this.pending.get(t.id);if(!e)return;if(clearTimeout(e.timeout),this.pending.delete(t.id),t.error){let n=typeof t.error.code==`number`?t.error.code:-32603,r=typeof t.error.message==`string`?t.error.message:`GDEX request failed`;e.reject(new M(n,r,t.error.data))}else{try{e.onResult?.(t.result)}catch(t){e.reject(t instanceof Error?t:Error(String(t)));return}e.resolve(t.result)}return}if(t.method!==`gdex_subscription`||!this.isRecord(t.params))return;let n=t.params.subscription,r=t.params.result;if(typeof n!=`string`||!this.isRecord(r))return;let i=this.subscriptionsByServerId.get(n);if(i?.active)try{i.callback(r)}catch(e){j(`GDEX subscription callback failed`,e)}}async subscribe(e,t,n){let r={channel:e,...n},i={subscriptionId:``,unsubscribe:async()=>this.unsubscribe(a)},a={serverId:``,params:r,callback:t,handle:i,active:!0};return await this.send(`gdex_subscribe`,r,e=>{let t=at(e);a.serverId=t,i.subscriptionId=t,this.activeSubscriptions.add(a),this.subscriptionsByServerId.set(t,a)}),i}async unsubscribe(e){e.active&&(e.active=!1,this.activeSubscriptions.delete(e),this.subscriptionsByServerId.delete(e.serverId),this.isConnected()&&await this.request(`gdex_unsubscribe`,{subscriptionId:e.serverId}))}startReconnectLoop(){this.reconnecting||this.intentionalClose||(this.reconnecting=!0,this.reconnectLoop())}async reconnectLoop(){for(;!this.intentionalClose&&this.backoff.shouldRetry();){let e=this.backoff.nextDelayMs();if(this.backoff.recordAttempt(),j(`GDEX reconnect attempt ${this.backoff.attemptCount}/${this.backoff.maxAttempts} in ${e}ms`),await this.waitForReconnectDelay(e),this.intentionalClose)break;try{await this.openSocket(),await this.resubscribeAll(),this.backoff.reset(),this.reconnecting=!1;return}catch(e){j(`GDEX reconnect failed: ${e instanceof Error?e.message:String(e)}`)}}this.reconnecting=!1,this.intentionalClose||j(`GDEX reconnection attempts exhausted`)}async resubscribeAll(){this.subscriptionsByServerId.clear();for(let e of this.activeSubscriptions){if(!e.active)continue;let t={...e.params,snapshot:!0},n=await this.resubscribeWithRateLimitRetry(t,t=>{let n=at(t);e.active&&(e.serverId=n,e.handle.subscriptionId=n,this.subscriptionsByServerId.set(n,e))});e.active||await this.request(`gdex_unsubscribe`,{subscriptionId:n.subscriptionId})}}async resubscribeWithRateLimitRetry(e,t){for(let n=0;;n++)try{return await this.send(`gdex_subscribe`,e,t)}catch(e){if(!(e instanceof M)||e.code!==-32003||n>=5)throw e;let t=this.readRetryAfterMs(e.data);j(`GDEX resubscribe rate limited; retrying in ${t}ms`),await new Promise(e=>setTimeout(e,t))}}waitForReconnectDelay(e){return new Promise(t=>{this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectDelayResolve=void 0,t()},e),this.reconnectDelayResolve=t})}clearReconnectTimer(){this.reconnectTimer!==void 0&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0;let e=this.reconnectDelayResolve;this.reconnectDelayResolve=void 0,e?.()}rejectPending(e){for(let t of this.pending.values())clearTimeout(t.timeout),t.reject(e);this.pending.clear()}readRetryAfterMs(e){return!this.isRecord(e)||typeof e.retryAfterMs!=`number`||e.retryAfterMs<0?1e3:e.retryAfterMs}isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}},N=class{constructor(e=fetch,t=3e4,n={}){this.httpRequestor=e,this.timeoutMs=t,this.wire=n}async sendRequest(e,t,n,r,i,a){let o=`${t}${n}${r}`;j(`Sending request to ${o} with body:`,i);let s=!!i,c=await oe(this.httpRequestor,o,{method:e,headers:{...s?{"Content-Type":`application/json`}:{},...this.wire.userAgent===!1?{}:{"User-Agent":this.wire.userAgent??`GalaChain-SDK/1.2.0-rc.1`},...this.wire.headers},...s?{body:JSON.stringify(i)}:{},...a?.signal===void 0?{}:{signal:a.signal}},this.timeoutMs);if(!c.ok)throw await m.fromErrorResponse(o,c);let l=await y(c);return j(`Response from ${t}${n}${r}:`,l),l}async sendPostRequest(e,t,n,r){return this.sendRequest(`POST`,e,t,n,r)}async sendGetRequest(e,t,n,r,i){let a=r?`${n}?${ae(r,this.wire.queryEncoding)}`:n;return this.sendRequest(`GET`,e,t,a,void 0,i)}};function st(e){return{ok:!0,value:e}}function P(e){return{ok:!1,reason:e}}function ct(e,t,n,r){if(!Array.isArray(t))throw new m(`Backend returned an invalid ${e} list.`,`INVALID_CHAIN_RESPONSE`,{data:t});let i=[];return t.forEach((t,a)=>{let o=n(t);if(o.ok){i.push(o.value);return}try{r?.({source:e,index:a,entry:t,reason:o.reason})}catch{}}),i}function lt(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function ut(e){if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:void 0}}function F(e,t){return e<t?[e,t]:[t,e]}function dt(e){if(Array.isArray(e)&&e.length>=2){let t=e[0],n=e[1];if(typeof t==`string`&&typeof n==`string`)return{token0:t,token1:n}}if(typeof e==`object`&&e){let t=e,n=t.token0,r=t.token1;if(typeof n==`string`&&typeof r==`string`)return{token0:n,token1:r}}throw new m(`Unable to order trading symbols.`,`VALIDATION_ERROR`,{value:e})}function I(e){return[e.collection,e.category,e.type,e.additionalKey].join(`$`)}function L(e){if(typeof e==`object`)return{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey};let t=e.includes(`|`)?`|`:`$`,n=e.split(t),r=n.slice(-3),i=n.slice(0,-3).join(t);if(n.length<4||i.length===0||r.some(e=>e.length===0))throw new m(`Invalid token class key: expected a collection followed by category, type and additionalKey`,`VALIDATION_ERROR`,{tokenClassKey:e});let[a,o,s]=r;return{collection:i,category:a,type:o,additionalKey:s}}var ft=class{constructor(e,t={}){this.gateway=e,this.options=t,p(this,`cachedSymbols`,void 0),p(this,`cachedAt`,0),p(this,`refreshInFlight`,void 0),p(this,`http`,void 0),this.http=new N(e.httpRequestor,e.requestTimeoutMs,e.wire)}async list(){return this.cachedSymbols!==void 0&&Date.now()-this.cachedAt<6e4?this.cachedSymbols:(this.refreshInFlight===void 0&&(this.refreshInFlight=this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,`/symbols`).then(e=>ct(`symbols`,e.data,pt,this.options.onInvalidEntry)).then(e=>(this.cachedSymbols=e,this.cachedAt=Date.now(),e)).finally(()=>{this.refreshInFlight=void 0})),this.refreshInFlight)}invalidate(){this.cachedSymbols=void 0,this.cachedAt=0}async refresh(){return this.invalidate(),this.refreshInFlight=void 0,this.list()}async resolve(e){let t=await this.list(),n=typeof e==`string`?mt(e)?I(L(e)):void 0:I(e),r=t.find(t=>t.symbol===e||n!==void 0&&I(t)===n);if(r===void 0){t=await this.refresh();let r=t.find(t=>t.symbol===e||n!==void 0&&I(t)===n);if(r===void 0)throw m.unknownTokenError(e);return r}return r}async proposeSymbol(e,t,n={}){let r=[];try{r=await this.list()}catch(e){if(n.registryFailure!==`ignore`)throw e}let i=I(e),a=r.find(t=>t.collection===e.collection&&t.category===e.category&&t.type===e.type&&t.additionalKey===e.additionalKey);if(a!==void 0)return a.symbol;if(D(t))return t;throw new m(`No valid trading symbol for token class ${i}: "${t}" is not an acceptable symbol and none is registered`,`VALIDATION_ERROR`,{classKey:e,displaySymbol:t})}async orderPair(e,t){let[n,r]=await Promise.all([this.resolve(e),this.resolve(t)]),[i,a]=F(n.symbol,r.symbol);return{token0:i===n.symbol?n:r,token1:a===r.symbol?r:n,flipped:i!==n.symbol}}};function pt(e){let t=lt(e);if(t===void 0)return P(`the row is not an object`);let{symbol:n,collection:r,category:i,type:a,additionalKey:o,decimals:s}=t;return typeof n==`string`?n.length===0?P(`symbol is empty`):typeof r==`string`?typeof i==`string`?typeof a==`string`?typeof o==`string`?typeof s!=`number`||!Number.isInteger(s)||s<0?P(`decimals is not a non-negative integer`):st({symbol:n,collection:r,category:i,type:a,additionalKey:o,decimals:s}):P(`additionalKey is not a string`):P(`type is not a string`):P(`category is not a string`):P(`collection is not a string`):P(`symbol is not a string`)}function mt(e){return e.includes(`|`)||e.includes(`$`)}function R(e){return typeof e==`string`?e:I(e)}async function z(e,t){let n=await e.resolve(t);if(n.symbol.length>0)return n.symbol;throw new m(`Token could not be resolved to a trading symbol.`,`SYMBOL_NOT_FOUND`,{token:t})}async function B(e,t){return e.passthrough===!0?R(t):z(e,t)}var ht=class{constructor(){p(this,`passthrough`,!0)}resolve(e){return typeof e==`string`&&!mt(e)?Promise.resolve({symbol:e,collection:``,category:``,type:``,additionalKey:``,decimals:0}):Promise.reject(m.unknownTokenError(e))}async orderPair(e,t){let[n,r]=await Promise.all([this.resolve(e),this.resolve(t)]),[i]=F(n.symbol,r.symbol),a=i!==n.symbol;return{token0:a?r:n,token1:a?n:r,flipped:a}}invalidate(){}},gt=class{constructor(e,t,n={}){this.gateway=e,this.symbols=t,this.options=n,p(this,`http`,void 0),this.http=new N(e.httpRequestor,e.requestTimeoutMs??3e4,e.wire)}async getPools(e){return ct(`pools`,(await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,`/pools`,yt(e),e?.signal===void 0?void 0:{signal:e.signal})).data,Ct,e?.onInvalidEntry??this.options.onInvalidEntry)}async getPool(e,t,n){return E(n),this.getBackend(`/pool`,await this.backendParams(e,t,n))}async getSlot0(e,t,n){return E(n),this.getBackend(`/slot0`,await this.backendParams(e,t,n))}async getCompositePool(e,t,n){if(E(n),this.symbols.passthrough===!0)return this.getBackend(`/composite-pool`,{token0:R(e),token1:R(t),fee:String(n)});let r=dt(F(await z(this.symbols,e),await z(this.symbols,t)));return this.getBackend(`/composite-pool`,{token0:r.token0,token1:r.token1,fee:String(n)})}async backendParams(e,t,n){return{token0:await B(this.symbols,e),token1:await B(this.symbols,t),fee:String(n)}}async getBackend(e,t){try{return(await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,e,t)).data}catch(e){throw e instanceof m?e:new m(`Pool request failed.`,`HTTP_ERROR`,{cause:e})}}};const _t=[`tvl`,`volume1d`,`volume30d`],vt=1e3;function yt(e){if(e===void 0)return;let t={};if(e.search!==void 0){if(e.search.length>64)throw new m(`search must be at most 64 characters.`,`VALIDATION_ERROR`,{search:e.search});t.search=e.search}if(e.sortBy!==void 0){if(!_t.includes(e.sortBy))throw new m(`sortBy must be one of ${_t.join(`, `)}.`,`VALIDATION_ERROR`,{sortBy:e.sortBy});t.sortBy=e.sortBy}if(e.sortOrder!==void 0){if(e.sortOrder!==`asc`&&e.sortOrder!==`desc`)throw new m(`sortOrder must be asc or desc.`,`VALIDATION_ERROR`,{sortOrder:e.sortOrder});t.sortOrder=e.sortOrder}if(e.page!==void 0){if(!Number.isInteger(e.page)||e.page<1)throw new m(`page must be an integer of at least 1.`,`VALIDATION_ERROR`,{page:e.page});t.page=String(e.page)}if(e.limit!==void 0){if(!Number.isInteger(e.limit)||e.limit<1||e.limit>vt)throw new m(`limit must be an integer from 1 to ${vt}.`,`VALIDATION_ERROR`,{limit:e.limit});t.limit=String(e.limit)}return Object.keys(t).length===0?void 0:t}const bt=[`poolName`,`token0CompositeKey`,`token1CompositeKey`,`token0Image`,`token1Image`,`creator`,`price`,`sqrtPrice`,`token0Tvl`,`token1Tvl`],xt=[`tickSpacing`,`protocolFees`,`tradingFees`,`tick`,`volume1d`,`volume7d`,`volume30d`,`trades1d`,`fee24h`,`token0Price`,`token1Price`],St=[`fee`,`tvlUsd`,`apr1d`];function Ct(e){let t=lt(e);if(t===void 0)return P(`the row is not an object`);for(let e of[`token0`,`token1`,`poolRef`])if(typeof t[e]!=`string`)return P(`${e} is not a string`);if(t.contractVersion!==void 0&&t.contractVersion!==`v2`)return P(`contractVersion is not v2`);let n={...t};for(let e of St){let r=t[e];if(r===void 0&&e!==`fee`)continue;let i=ut(r);if(i===void 0)return P(`${e} is not a number`);n[e]=i}for(let e of bt)if(t[e]!==void 0&&typeof t[e]!=`string`)return P(`${e} is not a string`);for(let e of xt){let n=t[e];if(n!==void 0&&(typeof n!=`number`||!Number.isFinite(n)))return P(`${e} is not a number`)}return st(n)}const wt=`galaswap-operation-`,Tt=/^[A-Za-z0-9._:-]*$/u;function Et(e){if(e===void 0)return wt;if(!Tt.test(e)||e.length>92)throw new m(`uniqueKeyPrefix must be at most 92 characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".`,`VALIDATION_ERROR`,{uniqueKeyPrefix:e});return e}const Dt=/^[A-Za-z0-9._:-]{1,128}$/u;function V(e){if(typeof e!=`string`||!Dt.test(e))throw new m(`uniqueKey must be 1-128 characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".`,`VALIDATION_ERROR`,{uniqueKey:e})}function Ot(e){return`${e}${globalThis.crypto.randomUUID()}`}const H=t=>new e(t).toFixed();function U(e){E(e.fee),O(e.token0,e.token1),V(e.uniqueKey);let t={token0:e.token0,token1:e.token1,fee:e.fee,uniqueKey:e.uniqueKey};if(`exactIn`in e){let n=e.exactIn;if(n===void 0)throw new m(`exactIn is required for an exact-input swap.`,`VALIDATION_ERROR`);T(n,`exactIn`),t[e.tokenInIsToken0?`sell0Qty`:`sell1Qty`]=H(n),e.amountOutMinimum!==void 0&&(T(e.amountOutMinimum,`amountOutMinimum`,!0),t.amountOutMinimum=H(e.amountOutMinimum))}else{let n=e.exactOut;if(n===void 0)throw new m(`exactOut is required for an exact-output swap.`,`VALIDATION_ERROR`);T(n,`exactOut`),t[e.tokenInIsToken0?`buy1Qty`:`buy0Qty`]=H(n),e.amountInMaximum!==void 0&&(T(e.amountInMaximum,`amountInMaximum`,!0),t.amountInMaximum=H(e.amountInMaximum))}return e.priceLimit!==void 0&&(T(e.priceLimit,`priceLimit`),t.priceLimit=H(e.priceLimit)),t}function kt(e){E(e.fee),O(e.token0,e.token1),w(e.tickLower,e.tickUpper,e.fee),V(e.uniqueKey)}function W(e){kt(e);let t=Pt(e.depositQuantityToken0,e.depositQuantityToken1,`depositQuantityToken0`,`depositQuantityToken1`);if(t===void 0)throw new m(`Provide exactly one of depositQuantityToken0 or depositQuantityToken1.`,`VALIDATION_ERROR`);return T(t.amount,t.name),{token0:e.token0,token1:e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,uniqueKey:e.uniqueKey,[t.name]:H(t.amount)}}function At(e){kt(e);let t=Pt(e.withdrawalQuantityToken0,e.withdrawalQuantityToken1,`withdrawalQuantityToken0`,`withdrawalQuantityToken1`,!0);return t!==void 0&&T(t.amount,t.name),{token0:e.token0,token1:e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,uniqueKey:e.uniqueKey,...t===void 0?{}:{[t.name]:H(t.amount)}}}function jt(e){return kt(e),{token0:e.token0,token1:e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,uniqueKey:e.uniqueKey}}function Mt(t){E(t.fee),V(t.uniqueKey),O(t.token0Symbol,t.token1Symbol);for(let e of[t.token0Symbol,t.token1Symbol])if(!D(e))throw new m(`Invalid trading symbol: must be 1-32 ASCII letters and digits and not a reserved word (Token, Unit, none).`,`VALIDATION_ERROR`,{symbol:e});for(let e of[t.token0Key,t.token1Key])Nt(e);let n=Pt(t.startingPrice,t.startingSqrtPrice,`startingPrice`,`startingSqrtPrice`);if(n===void 0)throw new m(`Provide exactly one of startingPrice or startingSqrtPrice.`,`VALIDATION_ERROR`);if(typeof n.amount==`number`)throw new m(`Invalid ${n.name}: use a decimal string or BigNumber, not a JavaScript number`,`VALIDATION_ERROR`);let r=new e(n.amount);if(!r.isFinite()||r.isLessThanOrEqualTo(0))throw new m(`Starting price must be finite and positive.`,`VALIDATION_ERROR`);return{token0Key:t.token0Key,token1Key:t.token1Key,fee:t.fee,[n.name]:r.toFixed(),token0Symbol:t.token0Symbol,token1Symbol:t.token1Symbol,uniqueKey:t.uniqueKey,...t.name===void 0||t.name===``?{}:{name:t.name},...t.isPrivate===void 0?{}:{isPrivate:t.isPrivate},...t.privateAccess===void 0?{}:{privateAccess:t.privateAccess}}}function Nt(e){for(let t of[`collection`,`category`,`type`,`additionalKey`])if(typeof e[t]!=`string`||e[t].length===0)throw new m(`Token class key is missing ${t}.`,`VALIDATION_ERROR`,{key:e})}function Pt(e,t,n,r,i=!1){if(e!==void 0&&t!==void 0)throw new m(i?`Provide at most one of ${n} or ${r}.`:`Provide exactly one of ${n} or ${r}.`,`VALIDATION_ERROR`);if(e!==void 0)return{name:n,amount:e};if(t!==void 0)return{name:r,amount:t}}function G(e,t,n){return new m(`${e} DTO field ${t} must be ${n}.`,`VALIDATION_ERROR`,{type:`INVALID_DTO`,method:e,field:t})}function Ft(e,t){let n=n=>{let r=t[n];if(typeof r!=`string`)throw G(e,n,`a string`);return r},r=n=>{let r=t[n];if(typeof r!=`number`)throw G(e,n,`a number`);return r},i=e=>t[e]===void 0?void 0:n(e),a=n=>{let r=t[n];if(typeof r!=`object`||!r)throw G(e,n,`a class key`);let i=r,a=t=>{if(typeof i[t]!=`string`)throw G(e,`${n}.${t}`,`a string`);return i[t]};return{collection:a(`collection`),category:a(`category`),type:a(`type`),additionalKey:a(`additionalKey`)}},o=()=>({token0:n(`token0`),token1:n(`token1`),fee:r(`fee`)}),s=n(`uniqueKey`),c=()=>({...o(),uniqueKey:s,tickLower:r(`tickLower`),tickUpper:r(`tickUpper`)});switch(e){case`RequestTrade`:{let r=[`sell0Qty`,`sell1Qty`,`buy0Qty`,`buy1Qty`].filter(e=>t[e]!==void 0),[a]=r;if(r.length!==1||a===void 0)throw G(e,`sell0Qty|sell1Qty|buy0Qty|buy1Qty`,`present exactly once`);let c=a===`sell0Qty`||a===`buy1Qty`,l={...o(),uniqueKey:s,tokenInIsToken0:c},u=i(`priceLimit`);return a.startsWith(`sell`)?U({...l,exactIn:n(a),amountOutMinimum:i(`amountOutMinimum`),priceLimit:u}):U({...l,exactOut:n(a),amountInMaximum:i(`amountInMaximum`),priceLimit:u})}case`AddLiquidity`:{let e=i(`depositQuantityToken0`),t=i(`depositQuantityToken1`);return W({...c(),...e===void 0?{depositQuantityToken1:t}:{depositQuantityToken0:e}})}case`RemoveLiquidity`:return At({...c(),withdrawalQuantityToken0:i(`withdrawalQuantityToken0`),withdrawalQuantityToken1:i(`withdrawalQuantityToken1`)});case`CollectPositionFees`:return jt(c());case`CreatePool`:{let o=i(`startingPrice`),c=i(`startingSqrtPrice`),l=t.privateAccess;if(l!==void 0&&(!Array.isArray(l)||l.some(e=>typeof e!=`string`)))throw G(e,`privateAccess`,`an array of strings`);if(t.isPrivate!==void 0&&typeof t.isPrivate!=`boolean`)throw G(e,`isPrivate`,`a boolean`);return Mt({token0Key:a(`token0Key`),token1Key:a(`token1Key`),token0Symbol:n(`token0Symbol`),token1Symbol:n(`token1Symbol`),fee:r(`fee`),uniqueKey:s,name:i(`name`),isPrivate:t.isPrivate,privateAccess:l,...o===void 0?{startingSqrtPrice:c}:{startingPrice:o}})}}}function K(e,t){let n=Ft(e,t);if(JSON.stringify(n)!==JSON.stringify(t))throw new m(`The ${e} DTO is not in the form the SDK builders produce; build it with the matching build function and submit that.`,`VALIDATION_ERROR`,{type:`DTO_NOT_CANONICAL`,method:e})}function It(e){return{token0:e.token0,token1:e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper}}var Lt=class{constructor(e,t,n,r,i={}){this.gateway=e,this.symbols=t,this.signer=n,this.walletAddress=r,p(this,`http`,void 0),p(this,`uniqueKeyPrefix`,void 0),p(this,`onInvalidEntry`,void 0),this.http=new N(e.httpRequestor,e.requestTimeoutMs??3e4,e.wire),this.uniqueKeyPrefix=Et(i.uniqueKeyPrefix),this.onInvalidEntry=i.onInvalidEntry}async getUserPositions(e){return ct(`positions`,(await this.get(`/positions`,{user:e})).data,Vt,this.onInvalidEntry)}async getPosition(e,t){let n=await this.getNullable(`/position`,await this.positionParams(e),t);return n===null?null:Ht(n.data)}async readPosition(e,t){try{let n=await this.getPosition(e,t);return n===null?{kind:`not_found`}:{kind:`found`,data:n}}catch(e){if(t?.aborted===!0)throw e;return{kind:`unknown`,error:e instanceof m?e:new m(`Position request failed.`,`HTTP_ERROR`,{cause:e})}}}async positionParams(e){if(this.symbols.passthrough===!0)return{token0:R(e.token0),token1:R(e.token1),fee:`${e.fee}`,owner:e.owner,tickLower:`${e.tickLower}`,tickUpper:`${e.tickUpper}`};let t=await this.symbols.orderPair(e.token0,e.token1),n=this.canonicalTicks(e.tickLower,e.tickUpper,t.flipped);return{token0:t.token0.symbol,token1:t.token1.symbol,fee:`${e.fee}`,owner:e.owner,tickLower:`${n.tickLower}`,tickUpper:`${n.tickUpper}`}}async estimateAddLiquidity(t){return T(t.amount,`amount`),(await this.get(`/add-liq-estimate`,{token0:R(t.token0),token1:R(t.token1),fee:`${t.fee}`,tickLower:`${t.tickLower}`,tickUpper:`${t.tickUpper}`,amount:new e(t.amount).toFixed(),amountIsToken0:String(t.amountIsToken0)})).data}async estimateRemoveLiquidity(t){return T(t.liquidity,`liquidity`),(await this.get(`/remove-liq-estimate`,{token0:R(t.token0),token1:R(t.token1),fee:`${t.fee}`,tickLower:`${t.tickLower}`,tickUpper:`${t.tickUpper}`,liquidity:new e(t.liquidity).toFixed()})).data}async addLiquidityByTicks(e){return this.submitAddLiquidity(await this.buildAddLiquidity(e))}async buildAddLiquidity(e){E(e.fee);let t=await this.symbols.orderPair(e.token0,e.token1),n=this.canonicalTicks(e.tickLower,e.tickUpper,t.flipped);w(n.tickLower,n.tickUpper,e.fee),T(e.amount,`amount`);let r={token0:t.token0.symbol,token1:t.token1.symbol,fee:e.fee,tickLower:n.tickLower,tickUpper:n.tickUpper,uniqueKey:this.uniqueKeyFor(e.uniqueKey)};return t.flipped===e.amountIsToken0?W({...r,depositQuantityToken1:e.amount}):W({...r,depositQuantityToken0:e.amount})}async submitAddLiquidity(e){return K(`AddLiquidity`,e),this.submit(`AddLiquidity`,e,{kind:`add`,identity:It(e)})}async addLiquidityByPrice(t){E(t.fee),this.rejectNumber(t.minPrice,`minPrice`),this.rejectNumber(t.maxPrice,`maxPrice`);let n=new e(t.minPrice),r=new e(t.maxPrice);if(!n.isFinite()||!r.isFinite()||n.isLessThanOrEqualTo(0)||r.isLessThanOrEqualTo(0))throw new m(`Price bounds must be finite and positive.`,`VALIDATION_ERROR`);if(n.isGreaterThan(r))throw new m(`minPrice must be less than or equal to maxPrice.`,`VALIDATION_ERROR`);let i=this.tickSpacing(t.fee),a=Ee(Te(n),i),o=De(Te(r),i);return this.addLiquidityByTicks({token0:t.token0,token1:t.token1,fee:t.fee,tickLower:a,tickUpper:o,amount:t.amount,amountIsToken0:t.amountIsToken0,uniqueKey:t.uniqueKey})}async removeLiquidity(e){return this.submitRemoveLiquidity(await this.buildRemoveLiquidity(e))}async buildRemoveLiquidity(e){E(e.fee);let t=await this.symbols.orderPair(e.token0,e.token1),n=this.canonicalTicks(e.tickLower,e.tickUpper,t.flipped);if(w(n.tickLower,n.tickUpper,e.fee),e.amount0!==void 0&&e.amount1!==void 0)throw new m(`Provide at most one of amount0 or amount1.`,`VALIDATION_ERROR`);e.amount0!==void 0&&T(e.amount0,`amount0`),e.amount1!==void 0&&T(e.amount1,`amount1`);let[r,i]=t.flipped?[e.amount1,e.amount0]:[e.amount0,e.amount1];return At({token0:t.token0.symbol,token1:t.token1.symbol,fee:e.fee,tickLower:n.tickLower,tickUpper:n.tickUpper,uniqueKey:this.uniqueKeyFor(e.uniqueKey),withdrawalQuantityToken0:r,withdrawalQuantityToken1:i})}async submitRemoveLiquidity(e){K(`RemoveLiquidity`,e);let t=e.withdrawalQuantityToken0===void 0&&e.withdrawalQuantityToken1===void 0;return this.submit(`RemoveLiquidity`,e,{kind:t?`removeFull`:`removePartial`,identity:It(e)})}async collectPositionFees(e){return this.submitCollectPositionFees(await this.buildCollectPositionFees(e))}async buildCollectPositionFees(e){E(e.fee);let t=await this.symbols.orderPair(e.token0,e.token1),n=this.canonicalTicks(e.tickLower,e.tickUpper,t.flipped);return w(n.tickLower,n.tickUpper,e.fee),jt({token0:t.token0.symbol,token1:t.token1.symbol,fee:e.fee,tickLower:n.tickLower,tickUpper:n.tickUpper,uniqueKey:this.uniqueKeyFor(e.uniqueKey)})}async submitCollectPositionFees(e){return K(`CollectPositionFees`,e),this.submit(`CollectPositionFees`,e,{kind:`collect`,identity:It(e)})}async createPool(e){return this.submitCreatePool(await this.buildCreatePool(e))}async buildCreatePool(t){let n=t.startingPrice!==void 0;if(n===(t.startingSqrtPrice!==void 0))throw new m(`Provide exactly one of startingPrice or startingSqrtPrice.`,`VALIDATION_ERROR`);E(t.fee);let[r,i]=await Promise.all([this.resolveCreateToken(t.token0,t.token0Symbol),this.resolveCreateToken(t.token1,t.token1Symbol)]),a=r.symbol>i.symbol,[o,s]=a?[i,r]:[r,i],c=n?t.startingPrice:t.startingSqrtPrice;this.rejectNumber(c,n?`startingPrice`:`startingSqrtPrice`);let l=new e(c);if(!l.isFinite()||l.isLessThanOrEqualTo(0))throw new m(`Starting price must be finite and positive.`,`VALIDATION_ERROR`);let u=a?new e(1).dividedBy(l):l,d={token0Key:o.classKey,token1Key:s.classKey,token0Symbol:o.symbol,token1Symbol:s.symbol,fee:t.fee,uniqueKey:this.uniqueKeyFor(t.uniqueKey),name:t.name,isPrivate:t.isPrivate,privateAccess:t.privateAccess};return Mt(n?{...d,startingPrice:u}:{...d,startingSqrtPrice:u})}async submitCreatePool(e){K(`CreatePool`,e);let t=await this.submit(`CreatePool`,e,{kind:`createPool`,token0:e.token0Symbol,token1:e.token1Symbol,fee:e.fee});return this.symbols.invalidate?.(),t}async submit(e,t,n){if(this.signer===void 0)throw m.noSignerError();let r=await this.signer.signObject(e,t),i=this.walletAddress===void 0?{}:{walletAddress:this.walletAddress},a=this.walletAddress,o=this.buildPositionConfirmation(n,a),s={...i,...o===void 0?{}:{positionConfirmation:o}};return this.gateway.submit(e,r,s)}buildPositionConfirmation(t,n){if(t===void 0)return;if(t.kind===`createPool`){let{token0:e,token1:n,fee:r}=t;return async t=>await this.getNullable(`/pool`,{token0:e,token1:n,fee:`${r}`},t)===null?{confirmed:!1}:{confirmed:!0,position:null}}if(n===void 0)return;let{kind:r,identity:i}=t,a;return async t=>{let o=await this.getPosition({...i,owner:n},t);if(a===void 0)return a={liquidity:new e(o?.liquidity??0),fees:new e(o?.fees0??0).plus(new e(o?.fees1??0))},r===`removeFull`&&o===null?{confirmed:!0,position:null}:{confirmed:!1};switch(r){case`add`:return o!==null&&new e(o.liquidity).isGreaterThan(a.liquidity)?{confirmed:!0,position:o}:{confirmed:!1};case`removePartial`:return o!==null&&new e(o.liquidity).isLessThan(a.liquidity)?{confirmed:!0,position:o}:{confirmed:!1};case`removeFull`:return o===null?{confirmed:!0,position:null}:{confirmed:!1};case`collect`:{if(o===null)return{confirmed:!1};let t=new e(o.fees0??0).plus(new e(o.fees1??0));return t.isLessThan(a.fees)||a.fees.isZero()&&t.isZero()?{confirmed:!0,position:o}:{confirmed:!1}}}}}async get(e,t,n){return this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,e,t,n===void 0?void 0:{signal:n})}async getNullable(e,t,n){try{return await this.get(e,t,n)}catch(e){if(this.isNotFound(e))return null;throw e}}isNotFound(e){return!(e instanceof m)||e.details===void 0?!1:e.details.status===404}canonicalTicks(e,t,n){return n?{tickLower:-t,tickUpper:-e}:{tickLower:e,tickUpper:t}}tickSpacing(e){let t=be[e];if(t===void 0)throw new m(`Unsupported fee tier: ${e}.`,`VALIDATION_ERROR`);return t}rejectNumber(e,t){if(typeof e==`number`)throw new m(`Invalid ${t}: use a decimal string or BigNumber, not a JavaScript number`,`VALIDATION_ERROR`)}uniqueKeyFor(e){return e===void 0?Ot(this.uniqueKeyPrefix):(V(e),e)}async resolveCreateToken(e,t){try{let n=typeof e==`object`?I(e):e,r=await this.symbols.resolve(n);if(t!==void 0&&t!==``&&t!==r.symbol)throw new m(`Supplied symbol ${t} disagrees with the registered trading symbol ${r.symbol}.`,`VALIDATION_ERROR`,{token:e,suppliedSymbol:t,registeredSymbol:r.symbol});let i=this.tryParseClassKey(e);if(i===void 0&&r.collection===``)throw new m(`createPool needs each token as a class key; a bare trading symbol does not carry one.`,`VALIDATION_ERROR`,{token:e});return{symbol:r.symbol,classKey:i??L({collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey})}}catch(n){if(!(n instanceof m)||n.code!==`UNKNOWN_TOKEN`)throw n;let r;try{r=L(e)}catch{throw n}if(t===void 0||t===``)throw new m(`Token is not registered in the trading-symbol registry yet; pass token0Symbol/token1Symbol (the token class symbol) to propose one. A symbol cannot be derived from a class key.`,`VALIDATION_ERROR`,{token:e});if(!D(t))throw new m(`Invalid trading symbol: must be 1-32 ASCII letters and digits and not a reserved word (Token, Unit, none).`,`VALIDATION_ERROR`,{symbol:t});return{symbol:t,classKey:r}}}tryParseClassKey(e){try{return L(e)}catch{return}}};const Rt=[`token0Symbol`,`token1Symbol`,`owner`,`liquidity`,`amount0`,`amount1`],zt=[`fee`,`tickLower`,`tickUpper`],Bt=[`token0CompositeKey`,`token1CompositeKey`,`token0Image`,`token1Image`,`sqrtPrice`,`fees0`,`fees1`];function Vt(e){let t=lt(e);if(t===void 0)return P(`the row is not an object`);for(let e of Rt)if(typeof t[e]!=`string`)return P(`${e} is not a string`);for(let e of zt){let n=t[e];if(typeof n!=`number`||!Number.isFinite(n))return P(`${e} is not a number`)}if(typeof t.inRange!=`boolean`)return P(`inRange is not a boolean`);for(let e of Bt)if(t[e]!==void 0&&typeof t[e]!=`string`)return P(`${e} is not a string`);let n=t.currentTick;if(n!==void 0&&(typeof n!=`number`||!Number.isFinite(n)))return P(`currentTick is not a number`);let r=t.poolRef??t.pool??``;if(typeof r!=`string`)return P(`pool is not a string`);let i=Object.fromEntries([...Bt,`currentTick`].flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]));return st({token0Symbol:t.token0Symbol,token1Symbol:t.token1Symbol,fee:t.fee,tickLower:t.tickLower,tickUpper:t.tickUpper,liquidity:t.liquidity,amount0:t.amount0,amount1:t.amount1,inRange:t.inRange,pool:r,owner:t.owner,...i})}function Ht(e){let t=Vt(e);if(t.ok)return t.value;throw new m(`Backend returned an invalid position.`,`INVALID_CHAIN_RESPONSE`,{data:e,reason:t.reason})}var Ut=class{constructor(e,t){this.gateway=e,this.symbols=t,p(this,`http`,void 0),this.http=new N(e.httpRequestor,e.requestTimeoutMs??3e4,e.wire)}async quoteExactInput(e,t,n,r){return T(n,`amountIn`),this.quote(e,t,{amountIn:$t(n)},r)}async quoteExactOutput(e,t,n,r){return T(n,`amountOut`),this.quote(e,t,{amountOut:$t(n)},r)}async quote(e,t,n,r){Qt(r);let i={tokenIn:await B(this.symbols,e),tokenOut:await B(this.symbols,t),...n};r!==void 0&&(i.fee=String(r));try{return Wt((await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,`/quote`,i)).data)}catch(n){throw Yt(n,e,t,r)}}};function Wt(t){if(!qt(t))throw new m(`Backend returned an invalid quote.`,`INVALID_CHAIN_RESPONSE`,{data:t});let n=t,r=n.currentPrice===void 0?Kt(n.currentSqrtPrice,n.tokenInIsToken0):new e(n.currentPrice),i=n.newPrice===void 0?Kt(n.newSqrtPrice,n.tokenInIsToken0):new e(n.newPrice),a=i.minus(r).dividedBy(r);return{contractVersion:n.contractVersion,fee:n.fee,amountIn:n.amountIn,amountOut:n.amountOut,...n.currentSqrtPrice===void 0?{}:{currentSqrtPrice:n.currentSqrtPrice},...n.newSqrtPrice===void 0?{}:{newSqrtPrice:n.newSqrtPrice},feeTier:n.fee,newTick:n.newTick,tradingFees:n.tradingFees,protocolFees:n.protocolFees,totalFees:n.totalFees,feeTokenSymbol:n.feeTokenSymbol,token0Symbol:n.token0Symbol,token1Symbol:n.token1Symbol,tokenInIsToken0:n.tokenInIsToken0,currentPrice:r,newPrice:i,priceImpact:a}}const Gt=e.clone({DECIMAL_PLACES:60});function Kt(e,t){let n=new Gt(e).pow(2);return t?n:new Gt(1).dividedBy(n)}function qt(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.contractVersion===`v2`&&typeof t.fee==`number`&&Number.isFinite(t.fee)&&[`amountIn`,`amountOut`,`tradingFees`,`protocolFees`,`totalFees`,`feeTokenSymbol`,`token0Symbol`,`token1Symbol`].every(e=>typeof t[e]==`string`)&&typeof t.newTick==`number`&&Number.isInteger(t.newTick)&&typeof t.tokenInIsToken0==`boolean`&&q(t.currentSqrtPrice)&&q(t.newSqrtPrice)&&q(t.currentPrice)&&q(t.newPrice)&&(t.currentSqrtPrice!==void 0||t.currentPrice!==void 0)&&(t.newSqrtPrice!==void 0||t.newPrice!==void 0)}function q(t){if(t===void 0)return!0;if(typeof t!=`string`)return!1;try{let n=new e(t);return n.isFinite()&&n.isGreaterThan(0)}catch{return!1}}const Jt=/no pool|no pools|pool does not exist|has no trading symbol on the new DEX contract/iu;function Yt(e,t,n,r){if(e instanceof m){let i=Xt(e.details),a=Zt(e.details)??e.message;return i===404||Jt.test(a)?m.noPoolAvailableError(t,n,r,e):i===400&&/insufficient liquidity/iu.test(a)?m.insufficientLiquidityError(t,n,r,e):e}return new m(`Quote request failed.`,`HTTP_ERROR`,{cause:e,tokenIn:t,tokenOut:n,fee:r})}function Xt(e){let t=e?.status;return typeof t==`number`?t:void 0}function Zt(e){let t=e?.message;if(typeof t==`string`)return t;let n=e?.body;if(typeof n!=`object`||!n||Array.isArray(n))return;let r=n.message;return typeof r==`string`?r:void 0}function Qt(e){if(e!==void 0&&!xe.some(t=>Number(t)===Number(e)))throw new m(`Invalid fee tier: ${e}`,`VALIDATION_ERROR`,{fee:e})}function $t(t){return new e(t).toFixed()}function en(e){return e===503?`unavailable`:e===400?`disabled`:`unknown`}function tn(e,t){return t===`SHADOW_UNAVAILABLE`?`unavailable`:t===`SHADOW_RELAY_REJECTED`?`rejected`:t===`SHADOW_DISABLED`||t===`SHADOW_UNSUPPORTED_TYPE`?`disabled`:en(e)}function nn(e,t,n){let{httpStatus:r,body:i}=n,a=rn(i);if(r>=200&&r<300&&a?.error===!1){let n=rn(a.data),o=typeof n?.transactionId==`string`?n.transactionId:void 0;if(e===`RequestTrade`){let e=t.uniqueKey;if(n?.mode!==`queued`||typeof e!=`string`||n.uniqueKey!==e)throw new m(`The swap backend did not queue the request ${typeof e==`string`?e:``}.`,`INVALID_GATEWAY_RESPONSE`,{httpStatus:r,body:i});return{ok:!0,bundleId:o??``,queued:{uniqueKey:e,requestTransactionId:o??null}}}if(n?.mode===`sync`)return{ok:!0,bundleId:o??``}}let o=tn(r,_(i,`code`));return o===`rejected`?{ok:!1,kind:`rejected`,retryable:!1,message:_(i,`message`)??``}:o===`unavailable`?{ok:!1,kind:o,retryable:!0}:{ok:!1,kind:o,retryable:!1}}function rn(e){return typeof e==`object`&&e?e:void 0}function an(e){E(e.fee),O(e.token0Symbol,e.token1Symbol);let[t,n]=e.tokenInIsToken0?[e.token0Symbol,e.token1Symbol]:[e.token1Symbol,e.token0Symbol];return{tokenIn:t,tokenOut:n,fee:e.fee,pool:{token0:e.token0Symbol,token1:e.token1Symbol}}}var on=class{constructor(e,t,n,r,i={}){this.gateway=e,this.symbols=t,this.signer=n,this.walletAddress=r,p(this,`uniqueKeyPrefix`,void 0),this.uniqueKeyPrefix=Et(i.uniqueKeyPrefix)}async swap(e,t,n,r,i){return this.submitSwap(await this.buildSwap(e,t,n,r,i))}async swapShadow(e,t,n,r,i){return this.submitSwapShadow(await this.buildSwap(e,t,n,r,i))}async buildSwap(e,t,n,r,i){E(n);let a=i?.uniqueKey??Ot(this.uniqueKeyPrefix);V(a);let o=await z(this.symbols,e),s=await z(this.symbols,t),c=this.orientPool(o,s,i?.pool);return U({token0:c.token0,token1:c.token1,fee:n,tokenInIsToken0:o===c.token0,uniqueKey:a,...r})}async submitSwap(e){let t=await this.signRequestTrade(e);return this.gateway.submit(`RequestTrade`,t,this.submitOptions())}async submitSwapShadow(e){let t=await this.signRequestTrade(e);return nn(`RequestTrade`,t,await this.gateway.submitShadow(`RequestTrade`,t,this.submitOptions()))}submitOptions(){return this.walletAddress===void 0?{}:{walletAddress:this.walletAddress}}async signRequestTrade(e){if(K(`RequestTrade`,e),this.signer===void 0)throw m.noSignerError();return this.signer.signObject(`RequestTrade`,e)}orientPool(e,t,n){if(n===void 0)return dt(F(e,t));if(!(e===n.token0&&t===n.token1||e===n.token1&&t===n.token0))throw new m(`tokenIn and tokenOut must be the two tokens of the pinned pool.`,`VALIDATION_ERROR`,{type:`POOL_MISMATCH`,tokenIn:e,tokenOut:t,pool:n});return{token0:n.token0,token1:n.token1}}async confirmSwap(e,t){return V(e),new Ye({method:`RequestTrade`,uniqueKey:e,transactionId:null,mode:`queued`,result:void 0,dexBackendBaseUrl:this.gateway.dexBackendBaseUrl,httpRequestor:this.gateway.httpRequestor,requestTimeoutMs:this.gateway.requestTimeoutMs}).confirm({initialDelayMs:0,...t})}},sn=class{constructor(e){p(this,`dexBackendBaseUrl`,void 0),p(this,`chainCallTimeoutMs`,void 0),p(this,`signer`,void 0),p(this,`walletAddress`,void 0),p(this,`gateway`,void 0),p(this,`symbols`,void 0),p(this,`quoting`,void 0),p(this,`pools`,void 0),p(this,`positions`,void 0),p(this,`swaps`,void 0),p(this,`assets`,void 0),p(this,`fees`,void 0),p(this,`dexBackendWsUrl`,void 0),p(this,`webSocketImpl`,void 0),p(this,`streamApiKey`,void 0),p(this,`streamClient`,void 0);let t=et[e?.env??`prod`];this.dexBackendBaseUrl=cn(e?.dexBackendBaseUrl??t.dexBackendBaseUrl),this.chainCallTimeoutMs=e?.chainCallTimeoutMs??3e4,this.signer=e?.signer,this.walletAddress=e?.walletAddress;let n=new N(e?.httpRequestor,this.chainCallTimeoutMs,e?.wire);this.gateway=new Xe({dexBackendBaseUrl:this.dexBackendBaseUrl,chainCallTimeoutMs:this.chainCallTimeoutMs,...e?.wire===void 0?{}:{wire:e.wire},...e?.httpRequestor===void 0?{}:{httpRequestor:e.httpRequestor},...this.walletAddress===void 0?{}:{walletAddress:this.walletAddress}});let r={onInvalidEntry:e?.onInvalidEntry};this.symbols=new ft(this.gateway,r);let i=e?.symbolResolution===`canonical`?new ht:this.symbols;this.quoting=new Ut(this.gateway,i),this.pools=new gt(this.gateway,i,r);let a={uniqueKeyPrefix:e?.uniqueKeyPrefix,...r};this.positions=new Lt(this.gateway,i,this.signer,this.walletAddress,a),this.swaps=new on(this.gateway,i,this.signer,this.walletAddress,a),this.assets=new Le(this.dexBackendBaseUrl,n),this.fees=new qe(this.gateway,this.signer),this.dexBackendWsUrl=e?.dexBackendWsUrl??(e?.dexBackendBaseUrl===void 0?t.dexBackendWsUrl:`${this.dexBackendBaseUrl.replace(/^http/u,`ws`)}/ws`),this.webSocketImpl=e?.webSocketImpl,this.streamApiKey=e?.streamApiKey}get stream(){return this.streamClient??(this.streamClient=new ot({url:this.dexBackendWsUrl,...this.webSocketImpl===void 0?{}:{webSocketImpl:this.webSocketImpl},...this.streamApiKey===void 0?{}:{apiKey:this.streamApiKey}})),this.streamClient}};function cn(e){return e.replace(/\/$/u,``)}const ln=`pendingSwaps.v1`,un=6048e5;var dn=class{constructor(e,t={}){this.storage=e,p(this,`storageKey`,void 0),p(this,`darkFlagField`,void 0),p(this,`insertAt`,void 0),p(this,`listOrder`,void 0),p(this,`now`,void 0),p(this,`queue`,Promise.resolve()),p(this,`toStored`,e=>({uniqueKey:e.uniqueKey,requestTransactionId:e.requestTransactionId,wallet:e.wallet,token0Symbol:e.token0Symbol,token1Symbol:e.token1Symbol,[this.darkFlagField]:e.isDarkSwap,createdAt:e.createdAt})),this.storageKey=t.storageKey??`pendingSwaps.v1`,this.darkFlagField=t.darkFlagField??`isDarkSwap`,this.insertAt=t.insertAt??`end`,this.listOrder=t.listOrder??`stored`,this.now=t.now??Date.now}remember(e){return this.enqueue(async t=>{let n=(await this.read(t)).filter(t=>t.uniqueKey!==e.uniqueKey).map(this.toStored),r=this.toStored(e);await t.set(this.storageKey,this.insertAt===`end`?[...n,r]:[r,...n])})}forget(e){return this.enqueue(async t=>{let n=await this.read(t);await t.set(this.storageKey,n.filter(t=>t.uniqueKey!==e).map(this.toStored))})}async list(e){return await this.enqueue(async t=>{let n=await this.read(t),r=this.now(),i=n.filter(e=>r-e.createdAt<6048e5);i.length!==n.length&&await t.set(this.storageKey,i.map(this.toStored));let a=i.filter(t=>t.wallet===e);return this.listOrder===`newest-first`?a.sort((e,t)=>t.createdAt-e.createdAt):a})??[]}enqueue(e){let t=this.storage;if(t===void 0)return Promise.resolve(void 0);let n=this.queue.then(async()=>{try{return await e(t)}catch{return}});return this.queue=n,n}async read(e){let t=await e.get(this.storageKey);if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=this.fromStored(e);t!==void 0&&n.push(t)}return n}fromStored(e){if(typeof e!=`object`||!e)return;let t=e,n=t[this.darkFlagField],{uniqueKey:r,requestTransactionId:i,wallet:a,token0Symbol:o,token1Symbol:s,createdAt:c}=t;if(!(typeof r!=`string`||typeof i!=`string`&&i!==null||typeof a!=`string`||typeof o!=`string`||typeof s!=`string`||typeof n!=`boolean`||typeof c!=`number`||!Number.isFinite(c)))return{uniqueKey:r,requestTransactionId:i,wallet:a,token0Symbol:o,token1Symbol:s,isDarkSwap:n,createdAt:c}}};function fn(e,t){let n={};n[e]=[];function r(e){let t=n[e];
|
|
2
2
|
/* c8 ignore next */
|
|
3
|
-
if(!t)throw Error(`Missing EIP-712 type definition for ${e}`);return t}function i(e,t,a,o=!1){if(Array.isArray(t)){let n=t.length>0?i(e,t[0],a,!0):`string`;o||r(a).push({name:e,type:(n??e)+`[]`})}else if(typeof t==`object`&&t){if(n[e])throw Error(`Name collisions not yet supported`);n[e]=[],Object.entries(t).forEach(([t,n])=>{i(t,n,e)}),o||r(a).push({name:e,type:e})}else{let n;switch(typeof t){case`string`:n=`string`;break;case`number`:n=`int256`;break;case`boolean`:n=`bool`;break;case`bigint`:case`symbol`:case`undefined`:case`function`:case`object`:throw Error(`Unsupported type, ${typeof t}, value: ${Object.prototype.toString.call(t)}`)}if(o)return n;r(a).push({name:e,type:n})}}return Object.entries(t).forEach(([t,n])=>{i(t,n,e)}),n}
|
|
4
|
-
|
|
3
|
+
if(!t)throw Error(`Missing EIP-712 type definition for ${e}`);return t}function i(e,t,a,o=!1){if(Array.isArray(t)){let n=t.length>0?i(e,t[0],a,!0):`string`;o||r(a).push({name:e,type:(n??e)+`[]`})}else if(typeof t==`object`&&t){if(n[e])throw Error(`Name collisions not yet supported`);n[e]=[],Object.entries(t).forEach(([t,n])=>{i(t,n,e)}),o||r(a).push({name:e,type:e})}else{let n;switch(typeof t){case`string`:n=`string`;break;case`number`:n=`int256`;break;case`boolean`:n=`bool`;break;case`bigint`:case`symbol`:case`undefined`:case`function`:case`object`:throw Error(`Unsupported type, ${typeof t}, value: ${Object.prototype.toString.call(t)}`)}if(o)return n;r(a).push({name:e,type:n})}}return Object.entries(t).forEach(([t,n])=>{i(t,n,e)}),n}function pn(e){let t=typeof e==`string`&&/^0x[0-9a-fA-F]+$/u.test(e)?Number(e):typeof e==`number`?e:NaN;if(!Number.isSafeInteger(t)||t<=0)throw new m(`Wallet returned an invalid chain id.`,`INVALID_CHAIN_ID`,{chainId:e});return{name:`ethereum`,chainId:t}}const mn=/* @__PURE__ */ new Set([`RequestTrade`,`AddLiquidity`,`RemoveLiquidity`,`CollectPositionFees`]);function J(e,t){return typeof e[t]==`number`?e[t]:0}function hn(e){return{...e,amount0Desired:J(e,`amount0Desired`),amount0Min:J(e,`amount0Min`),amount1Desired:J(e,`amount1Desired`),amount1Min:J(e,`amount1Min`),positionId:e.positionId??``}}function gn(e){return{...e,amount:J(e,`amount`),amount0Min:J(e,`amount0Min`),amount1Min:J(e,`amount1Min`),positionId:e.positionId??``}}function _n(e){return{...e,amount0Requested:J(e,`amount0Requested`),amount1Requested:J(e,`amount1Requested`),positionId:e.positionId??``}}const vn={AddLiquidity:hn,RemoveLiquidity:gn,CollectPositionFees:_n};function yn(e,t){let n=vn[e],r=n?n(t):t;return{completedDto:r,types:fn(e,r)}}const bn=new TextEncoder;function xn(e){if(e==null)return e;if(e instanceof RegExp)return e.toString();let t=e;return typeof t.toJSON==`function`?Reflect.apply(t.toJSON,e,[]):e}function Sn(e){let t=xn(e);if(t===void 0)return;if(typeof t!=`object`||!t)return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(e=>Sn(e)??`null`).join(`,`)}]`;let n=t,r=[];for(let e of Object.keys(n).sort()){let t=Sn(n[e]);t!==void 0&&r.push(`${JSON.stringify(e)}:${t}`)}return`{${r.join(`,`)}}`}function Y(e){JSON.stringify(e);let t=Sn(e);if(t===void 0)throw TypeError(`Cannot serialize a value with no JSON representation.`);return t}function Cn(e){let{prefix:t,...n}=e;return delete n.signature,delete n.multisig,delete n.trace,(typeof t==`string`?t:``)+Y(n)}const wn=`Ethereum Signed Message:
|
|
4
|
+
`;function Tn(e){return wn+String(bn.encode(e).length)}function En(e){let t={...e};return delete t.prefix,Tn(Y(t))}function Dn(e){let t={...e};delete t.prefix;let n=bn.encode(Cn(t)).length,r=wn+String(n),i=-1;for(;n!==i;)i=n,r=wn+String(n),n=bn.encode(Cn({...t,prefix:r})).length;return r}function On(e){return new m(`Invalid private key: ${e}`,`VALIDATION_ERROR`,{type:`INVALID_PRIVATE_KEY`})}function kn(e){if(!/^[A-Za-z0-9+/]+={0,2}$/u.test(e)||e.length%4!=0)return;let t=e.replace(/=+$/u,``),n=[],r=0,i=0;for(let e of t)r=r<<6|`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.indexOf(e),i+=6,i>=8&&(i-=8,n.push(r>>i&255));return Uint8Array.from(n)}function An(e){let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n+=1)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}function jn(e){if(typeof e!=`string`){if(!(e instanceof Uint8Array)||e.length!==32)throw On(`expected exactly 32 bytes.`);if(!r.utils.isValidSecretKey(e))throw On(`not a valid secp256k1 scalar.`);return Uint8Array.from(e)}let t=e.startsWith(`0x`)?e.slice(2):e,n;if(/^[0-9a-fA-F]{63,64}$/u.test(t)?n=An(t.length===63?`0${t}`:t):t.length===44&&(n=kn(t)),n?.length!==32)throw On(`expected 64 hex characters or a 44-character base64 string.`);if(!r.utils.isValidSecretKey(n))throw On(`not a valid secp256k1 scalar.`);return n}function Mn(e,t){if(t.length!==32)throw new m(`secp256k1 can only sign a 32-byte hash (got ${t.length}).`,`VALIDATION_ERROR`);let n=r.sign(t,e,{prehash:!1,lowS:!0});return a(n.toBytes(`compact`))+(n.recovery===1?`1c`:`1b`)}function Nn(e){let t=r.getPublicKey(e,!1);return`0x${a(i(t.slice(1)).slice(-20))}`}function Pn(e){return i(bn.encode(e))}function Fn(e,t){return Mn(e,Pn(t))}function In(e,t){return Fn(e,Cn(t))}function Ln(e,t,n){return Mn(e,Pn(t+n))}function Rn(){let e=globalThis.window?.gala;if(!e)throw new m(`Gala wallet is not available. Please ensure the Gala wallet is connected.`,`GALA_WALLET_NOT_AVAILABLE`);return e}function zn(e){if(typeof e!=`string`)throw new m(`Wallet returned an invalid signature.`,`INVALID_SIGNATURE`);if(!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(e))throw new m(`Wallet returned an invalid native signature.`,`INVALID_SIGNATURE`);return e}function Bn(e){if(typeof e!=`string`||!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(e))throw new m(`Wallet returned an invalid personal-sign signature.`,`INVALID_SIGNATURE`);return e}function Vn(e,t){let n=t&&e.startsWith(`eth|`)?e.slice(4):e;if(!/^0x[0-9a-fA-F]{40}$/u.test(n))throw new m(`Wallet address must be the selected Ethereum account in 0x-prefixed form.`,`VALIDATION_ERROR`,{type:`INVALID_WALLET_ADDRESS`,value:e});return n}function Hn(e){let t=/^eth\|(?:0x)?([0-9a-fA-F]{40})$/u.exec(e);if(t?.[1]!==void 0)return`0x${t[1]}`;if(/^0x[0-9a-fA-F]{40}$/u.test(e)||/^(?:client\|)?[0-9a-fA-F]{24}$/u.test(e))return e;throw new m(`Wallet address must be the selected Ethereum account (0x plus 40 hex digits, or eth|...) or a GalaChain id (client|... or 24 hex digits).`,`VALIDATION_ERROR`,{type:`INVALID_WALLET_ADDRESS`,value:e})}function Un(e){if(!/^(?:eth\|(?:0x)?[0-9a-fA-F]{40}|0x[0-9a-fA-F]{40}|(?:client\|)?[0-9a-fA-F]{24})$/u.test(e))throw new m(`selectAddress must be an eth| or client| identity, or an account in one of the accepted forms.`,`VALIDATION_ERROR`,{type:`INVALID_WALLET_ADDRESS`,value:e})}const Wn=/* @__PURE__ */ new WeakMap;function Gn(e,t,n){let{setAddress:r}=e;if(t===void 0||typeof r!=`function`)return n();let i=(Wn.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>(await r.call(e,t),n()));return Wn.set(e,i),i}function Kn(e,t,n,r){let i=En(t),a={...t,prefix:i},o=r===void 0?[Y(t),n]:[Y(a),n,r];return e.request({method:r===void 0?`personal_sign`:`gala_signChainDto`,params:o}).then(e=>({...a,signature:Bn(e)}))}async function qn(e,t,n,r){let{completedDto:i,types:a}=yn(t,n),o=pn(await e.request({method:`eth_chainId`,params:[]})),s=Dn(i),c={...i,prefix:s},l=[{name:`name`,type:`string`},{name:`chainId`,type:`uint256`}],u={domain:o,types:{...a,EIP712Domain:l},primaryType:t,message:c},d=await e.request({method:`eth_signTypedData_v4`,params:[r,JSON.stringify(u)]});return{...c,signature:Bn(d),types:a,domain:o}}var Jn=class{constructor(e){p(this,`privateKey`,void 0),this.privateKey=jn(e)}signObject(e,t){let n=In(this.privateKey,t);return Promise.resolve({...t,signature:n})}};function Yn(e,t={}){let n=t.expectedAddress;n!==void 0&&Vn(n,!0);let r=n?.replace(/^eth\|/u,``).toLowerCase();return{async signObject(t,n){let i=await e();if(typeof i!=`string`)throw new m(`Invalid private key: the provider returned no key.`,`VALIDATION_ERROR`,{type:`INVALID_PRIVATE_KEY`});let a=jn(i);try{if(r!==void 0&&Nn(a)!==r)throw new m(`The signing key does not belong to the expected account.`,`SIGNER_ADDRESS_MISMATCH`);return{...n,signature:In(a,n)}}finally{a.fill(0)}}}}var Xn=class{constructor(e,t={}){p(this,`walletAddress`,void 0),p(this,`scheme`,void 0),p(this,`selectAddress`,void 0),this.walletAddress=Hn(e),this.scheme=t.scheme??`native`,t.selectAddress!==void 0&&Un(t.selectAddress),this.selectAddress=t.selectAddress}async signObject(e,t){let n=Rn();return Gn(n,this.selectAddress,async()=>{if(this.scheme===`personal-sign`)return Kn(n,t,this.walletAddress,e);let r=await n.request({method:`gala_signChainDto`,params:[Y(t),this.walletAddress,e,`native`]});return{...t,signature:zn(r)}})}},Zn=class{constructor(e,t,n={}){this.provider=e,p(this,`walletAddress`,void 0),p(this,`scheme`,void 0),this.walletAddress=Vn(t,!1),this.scheme=n.scheme??`personal-sign`}signObject(e,t){return this.scheme===`eip712`&&mn.has(e)?qn(this.provider,e,t,this.walletAddress):Kn(this.provider,t,this.walletAddress)}};function X(e,t){let n=jn(e);try{return t(n)}finally{n.fill(0)}}function Qn(e,t){return X(e,e=>Fn(e,t))}function $n(e,t,n){return X(e,e=>Ln(e,t,n))}const er=/^(?:0|[1-9][0-9]*)$/u;function tr(e){return e.startsWith(`Ethereum Signed Message:
|
|
5
|
+
`)&&er.test(e.slice(26))}const nr=[`signature`,`multisig`,`trace`,`types`,`domain`,`stringsInstructions`];function Z(e,t){throw new m(e,`INVALID_PERSONAL_SIGN_DTO`,{type:t})}function rr(e){let t;try{t=JSON.parse(e)}catch{return Z(`Personal-sign DTO is not valid JSON`,`NOT_JSON`)}if(typeof t!=`object`||!t||Array.isArray(t))return Z(`Personal-sign DTO must be a JSON object`,`NOT_OBJECT`);let n=t;if(!Object.prototype.hasOwnProperty.call(n,`prefix`))return{prefix:``,message:e};let{prefix:r,...i}=n;if(typeof r!=`string`||!tr(r))return Z(`Personal-sign DTO prefix is not an EIP-191 "Ethereum Signed Message" header`,`BAD_PREFIX`);let a=nr.filter(e=>Object.prototype.hasOwnProperty.call(i,e));return a.length>0?Z(`Personal-sign DTO carries signing-envelope field(s): ${a.join(`, `)}`,`ENVELOPE_FIELDS`):Y(n)===e?{prefix:r,message:Y(i)}:Z(`Personal-sign DTO is not in canonical serialized form`,`NOT_CANONICAL`)}function ir(e,t){let{prefix:n,message:r}=rr(t);return $n(e,n,r)}function ar(e,t){let n={...t};return delete n.signature,{signature:Qn(e,Y(n)),...n}}function or(e){let t={};for(let n of Object.keys(e))n!==`EIP712Domain`&&(t[n]=e[n]);return t}function sr(e){let t=t=>{let n=e?.[t];return typeof n==`string`?n:``};return`${t(`collection`)}$${t(`category`)}$${t(`type`)}$${t(`additionalKey`)}`}function cr(t){let n=new e(NaN);try{n=new e(t)}catch{}if(!n.isFinite())throw new m(`Invalid decimal quantity: ${String(t)}`,`VALIDATION_ERROR`,{type:`INVALID_DECIMAL`});return n.toFixed()}const lr=new TextEncoder,ur=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,dr=/^([A-Za-z_$][A-Za-z0-9_$]*)((?:\[(?:0|[1-9][0-9]*)?\])*)$/u,fr=/^-?[0-9]+$/u,pr=/^-?0x[0-9a-fA-F]+$/u,mr=(1n<<256n)-1n,hr=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`},{name:`salt`,type:`bytes32`}];function Q(e,t){throw new m(`Invalid typed data: ${e}`,`INVALID_TYPED_DATA`,t)}function $(e){let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function gr(e){let t=/* @__PURE__ */ new Uint8Array(32),n=e<0n?e+(1n<<256n):e;if(n<0n||n>mr)return Q(`integer does not fit in 256 bits`);for(let e=31;e>=0;--e)t[e]=Number(n&255n),n>>=8n;return t}function _r(e){let t=e.slice(2),n=new Uint8Array(t.length/2);for(let e=0;e<n.length;e+=1)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}function vr(e,t){return e instanceof Uint8Array?e:typeof e==`string`&&/^0x(?:[0-9a-fA-F]{2})*$/u.test(e)?_r(e):Q(`${t} must be an even-length 0x hex string`)}function yr(e,t){if(typeof e==`bigint`)return e;if(typeof e==`number`)return Number.isSafeInteger(e)?BigInt(e):Q(`${t} must be a safe integer`);if(typeof e==`string`){if(fr.test(e))return BigInt(e);if(pr.test(e))return e.startsWith(`-`)?-BigInt(e.slice(1)):BigInt(e)}return Q(`${t} must be an integer`)}function br(e,t){if(typeof e!=`string`)return Q(`${t} must be a string`);for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r>=55296&&r<=56319){let r=e.charCodeAt(n+1);if(!(r>=56320&&r<=57343))return Q(`${t} has an unpaired surrogate`);n+=1}else if(r>=56320&&r<=57343)return Q(`${t} has an unpaired surrogate`)}return lr.encode(e)}function xr(e){if(typeof e!=`string`||!/^0x[0-9a-fA-F]{40}$/u.test(e))return Q(`address must be 0x followed by 40 hex digits`);let t=e.slice(2);if(/[A-F]/u.test(t)&&/[a-f]/u.test(t)){let e=i(lr.encode(t.toLowerCase()));for(let n=0;n<40;n+=1){let r=e[n>>1]>>(n%2==0?4:0)&15,i=t.charAt(n);if(i!==(r>=8?i.toUpperCase():i.toLowerCase()))return Q(`address has a bad checksum`)}}return _r(e)}function Sr(e){if(e===`string`)return e=>i(br(e,`string`));if(e===`bytes`)return e=>i(vr(e,`bytes`));if(e===`bool`)return e=>typeof e==`boolean`?gr(e?1n:0n):Q(`bool must be a boolean`);if(e===`address`)return e=>$([/* @__PURE__ */ new Uint8Array(12),xr(e)]);let t=/^bytes([1-9][0-9]?)$/u.exec(e);if(t!==null){let n=Number(t[1]);return n>32||String(n)!==t[1]?void 0:t=>{let r=vr(t,e);return r.length===n?$([r,new Uint8Array(32-n)]):Q(`${e} must be exactly ${n} bytes`)}}let n=/^(u?)int([1-9][0-9]*)$/u.exec(e);if(n!==null){let t=Number(n[2]);if(t%8!=0||t>256||String(t)!==n[2])return;let r=n[1]===``,i=r?-(1n<<BigInt(t-1)):0n,a=r?(1n<<BigInt(t-1))-1n:(1n<<BigInt(t))-1n;return t=>{let n=yr(t,e);return n<i||n>a?Q(`value out of bounds for ${e}`):gr(n)}}}function Cr(e){let t=dr.exec(e);if(t===null)return Q(`unsupported type "${e}"`);let n=[...(t[2]??``).matchAll(/\[([0-9]*)\]/gu)].map(e=>e[1]===``?-1:Number(e[1]));return{base:t[1],dimensions:n}}function wr(e,t){if(!Array.isArray(t))return Q(`type ${e} must be a list of fields`);let n=/* @__PURE__ */ new Set;return t.map(t=>{let r=t;if(typeof r?.name!=`string`||typeof r.type!=`string`)return Q(`type ${e} has a field without a string name and type`);if(!ur.test(r.name))return Q(`invalid field name "${r.name}"`);if(n.has(r.name))return Q(`duplicate field "${r.name}" in ${e}`);n.add(r.name);let i=Cr(r.type),a=i.base===`uint`||i.base===`int`?`${i.base}256`:i.base;return{name:r.name,type:a+r.type.slice(i.base.length)}})}function Tr(e){let t=Object.keys(e),n=/* @__PURE__ */ new Map;for(let r of t){if(!ur.test(r))return Q(`invalid type name "${r}"`);n.set(r,wr(r,e[r]))}let r=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map;for(let e of t)r.set(e,/* @__PURE__ */ new Set),a.set(e,/* @__PURE__ */ new Set);for(let[e,t]of n)for(let i of t){let{base:t}=Cr(i.type);if(t===e)return Q(`circular type reference in ${e}`);if(Sr(t)===void 0){if(!n.has(t))return Q(`unknown type "${t}" in ${e}`);r.get(e)?.add(t),a.get(t)?.add(e)}}let o=t.filter(e=>a.get(e)?.size===0);if(o.length===0)return Q(`missing primary type`);if(o.length>1)return Q(`ambiguous primary types or unused types`,{roots:o});let s=o[0],c=/* @__PURE__ */ new Set,l=/* @__PURE__ */ new Set,u=e=>{if(c.has(e))return Q(`circular type reference at ${e}`);if(!l.has(e)){c.add(e);for(let t of r.get(e)??[])u(t);c.delete(e),l.add(e)}};u(s);let d=(e,t)=>{for(let n of r.get(e)??[])t.has(n)||(t.add(n),d(n,t));return t},f=e=>`${e}(${(n.get(e)??[]).map(e=>`${e.type} ${e.name}`).join(`,`)})`,p=/* @__PURE__ */ new Map;for(let e of t){let t=[...d(e,/* @__PURE__ */ new Set)].filter(t=>t!==e).sort();p.set(e,i(lr.encode([e,...t].map(f).join(``))))}let m=(e,t,n)=>{let r=e.dimensions[e.dimensions.length-1-n];if(r!==void 0)return Array.isArray(t)?r!==-1&&r!==t.length?Q(`array length mismatch`):i($(t.map(t=>m(e,t,n+1)))):Q(`${e.base} array value must be an array`);let a=Sr(e.base);return a===void 0?h(e.base,t):a(t)};function h(e,t){let r=n.get(e),a=p.get(e);if(r===void 0||a===void 0)return Q(`unknown type "${e}"`);if(typeof t!=`object`||!t||Array.isArray(t))return Q(`${e} value must be an object`);let o=t,s=r.map(t=>Object.prototype.hasOwnProperty.call(o,t.name)?m(Cr(t.type),o[t.name],0):Q(`${e} value is missing field "${t.name}"`));return i($([a,...s]))}return{primaryType:s,hashStruct:h}}function Er(e){if(typeof e!=`object`||!e||Array.isArray(e))return Q(`domain must be an object`);for(let t of Object.keys(e))if(!hr.some(e=>e.name===t))return Q(`invalid typed-data domain key ${JSON.stringify(t)}`);return Tr({EIP712Domain:hr.filter(t=>Object.prototype.hasOwnProperty.call(e,t.name))}).hashStruct(`EIP712Domain`,e)}function Dr(e){let t=Er(e.domain),n=Tr(e.types),r=n.hashStruct(n.primaryType,e.message);return i($([Uint8Array.of(25,1),t,r]))}async function Or(e,t){let n=Dr(t);return X(e,e=>`0x${Mn(e,n)}`)}export{xe as ALL_FEE_TIERS,b as AppliedTradeError,Le as Assets,Zn as BrowserWalletSigner,ht as CanonicalSymbols,Xe as ChainGateway,wt as DEFAULT_UNIQUE_KEY_PREFIX,Be as DEX_FEE_METHODS,Ve as DRY_RUN_METHOD,He as DRY_RUN_UNIQUE_KEY_PREFIX,qe as DexFees,mn as EIP712_CAPABLE_METHODS,ye as FEE_TIER,S as GC_MAX_TICK,x as GC_MIN_TICK,et as GSWAP_ENVIRONMENTS,sn as GSwap,m as GSwapSDKError,Xn as GalaWalletSigner,M as GdexStreamError,ot as GdexStreamService,ln as PENDING_SWAPS_STORAGE_KEY,un as PENDING_SWAP_EXPIRY_MS,dn as PendingSwapStore,gt as Pools,Lt as Positions,Jn as PrivateKeySigner,Ut as Quoting,Ye as SubmittedTransaction,on as Swaps,ft as Symbols,be as TICK_SPACING_BY_FEE,Ee as alignTickDown,De as alignTickUp,O as assertCanonicalPair,K as assertCanonicalV2Dto,w as assertTickRange,V as assertUniqueKey,W as buildAddLiquidityDto,jt as buildCollectPositionFeesDto,Mt as buildCreatePoolDto,Ke as buildDryRunWrapper,yn as buildEIP712Payload,At as buildRemoveLiquidityDto,U as buildRequestTradeDto,Tn as calculatePersonalSignPrefix,cr as canonicalDecimalString,tn as classifyShadowSubmitError,en as classifyShadowSubmitStatus,I as compositeKeyOf,fe as confirmAppliedTrade,Yn as createLazyPrivateKeySigner,Ot as createUniqueKey,pn as eip712DomainFor,Nn as ethAddressOfPrivateKey,Dn as fixpointPrefixFor,ke as frameSlot0,fn as generateEIP712Types,g as getObjectProperty,Cn as getPayloadToSign,_ as getStringProperty,Dr as hashTypedData,We as isCurrentContractDexMessage,Ue as isDexFeeMethod,it as isGdexLiquidityEvent,D as isProposableTradingSymbol,jn as normalizePrivateKey,F as orderSymbols,ee as parseJson,L as parseTokenClassKey,En as personalSignPrefixFor,B as queryTokenOf,R as rawTokenOf,dt as readOrderedSymbols,nn as readShadowSubmitOutcome,rr as resolvePersonalSignChainDtoPayload,Et as resolveUniqueKeyPrefix,Y as serialize,$n as signChainDtoHash,Qn as signChainDtoNative,ir as signChainDtoPersonalSign,In as signNative,Ln as signPersonalMessage,ar as signRawObject,Fn as signSerializedNative,Or as signTypedDataPayload,we as sqrtPriceToTick,or as stripEip712DomainType,an as swapRouteFromQuote,Te as tickFromPrice,Ce as tickToSqrtPrice,Ge as toChainDto,sr as tokenClassDollarKey,z as tradingSymbolOf,E as validateFee,T as validateNumericAmount,Ae as validatePriceValues,Me as validateTickRange,Ne as validateTickSpacing,je as validateTokenDecimals,Pe as validateWalletAddress,X as withPrivateKey};
|
|
5
6
|
//# sourceMappingURL=index.js.map
|