@gala-chain/gswap-sdk 1.2.0-rc.2 → 1.2.0-rc.3
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/dist/browser/index.js +4 -4
- package/dist/browser/index.js.map +1 -1
- package/dist/index.cjs +1176 -399
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +920 -58
- package/dist/index.d.ts +920 -58
- package/dist/index.mjs +1173 -400
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -1
package/dist/browser/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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()}function y(e,t={}){let n=/* @__PURE__ */ new Map,r=(e,t=!1)=>{for(let[r,i]of Object.entries(e??{}))t&&n.delete(r.toLowerCase()),n.set(r.toLowerCase(),[r,i])};return e?.userAgent!==!1&&r({"User-Agent":e?.userAgent??`GalaChain-SDK/1.2.0-rc.2`}),r(t.defaults),r(e?.headers),t.json===!0&&!n.has(`content-type`)&&r({"Content-Type":`application/json`}),r(t.fixed,!0),Object.fromEntries(n.values())}async function b(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 x(e){let t=await e.text();return ee(t)??t}function S(e,t){let n=e.headers;if(n===void 0)return;if(ce(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 oe(e){let t=S(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 se(e,t=`x-block-number`){let n=S(e,t);if(n===void 0)return;let r=Number(n);return Number.isInteger(r)&&r>=0?r:void 0}function ce(e){return`get`in e&&typeof e.get==`function`}const le=/^[A-Za-z0-9._:-]{1,128}$/u;var C=class extends m{constructor(e,t,n={},r){super(e,t,n,r),this.name=`AppliedTradeError`}};async function ue(e,t,n){let{uniqueKey:r}=t;if(!le.test(r))throw new C(`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 C(`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 n,o;try{n=await b(i,u,{method:`GET`,headers:y(e.wire),...c===void 0?{}:{signal:c}},a),o=await x(n)}catch(e){if(s(c,l),f=e,!await d.waitForRead())break;continue}if(s(c,l),n.status===200)return de(t,n,o,u);if(n.status===404||n.status===429||me(n.status)){let e=n.status===429?oe(n):void 0;if(!await d.waitForRead(e))break;continue}throw new C(he(o),`CONFIRMATION_FAILED`,{uniqueKey:r,status:n.status,body:o,url:u})}throw new C(`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 de(e,t,n,r){let{uniqueKey:i}=e,a=ge(n),o=a?.uniqueKey??a?.UniqueKey;if(typeof o==`string`&&o!==i)throw fe(e,t,n,r,`Apply result key did not match the requested key.`);let s=a?.Status,c=S(t,`x-apply-transaction-id`)??null,l=se(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 C(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 fe(e,t,n,r);let u=pe(a?.Data);if(u===void 0)throw fe(e,t,n,r);return{uniqueKey:i,transactionId:c,blockNumber:l,requestTransactionId:e.requestTransactionId,result:u}}function fe(e,t,n,r,i=`Transaction confirmation returned a malformed body`){return new C(i,`CONFIRMATION_FAILED`,{uniqueKey:e.uniqueKey,status:t.status,body:n,url:r})}function pe(e){let t=ge(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 me(e){return e===500||e===502||e===503||e===504}function he(e){return _(e,`message`)??_(e,`Message`)??_(g(e,`error`),`message`)??_(g(e,`error`),`Message`)??`Transaction confirmation failed`}function ge(e){return typeof e==`object`&&e?e:void 0}let _e=/* @__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 ve={0:200,500:10,3e3:60,1e4:200},ye=[0,500,3e3,1e4],w=-887272,T=887272,be=e.clone({DECIMAL_PLACES:60,ROUNDING_MODE:e.ROUND_DOWN}),E=t.clone({precision:60});function xe(t){return new e(new E(1.0001).pow(t/2).toString())}function Se(e){let t;try{t=new be(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(T,Math.max(w,Math.floor(n)));for(;r<887272&&xe(r+1).isLessThanOrEqualTo(t);)r+=1;for(;r>-887272&&xe(r).isGreaterThan(t);)--r;return r}function Ce(t){let n=typeof t==`string`?t:typeof t==`number`||e.isBigNumber(t)?t.toString():`NaN`,r=new E(n);if(!r.isFinite()||r.lessThanOrEqualTo(0)||!Number.isFinite(r.toNumber()))return NaN;let i=r.ln().dividedBy(new E(1.0001).ln()).floor().toNumber();return Number.isFinite(i)?i:NaN}function we(e,t){return Ee(t),Math.floor(e/t)*t}function Te(e,t){return Ee(t),Math.ceil(e/t)*t}function D(e,t,n){let r=ve[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 ${w} <= lower < upper <= ${T}`);if(e%r!==0||t%r!==0)throw RangeError(`Ticks must be aligned to spacing ${r}`)}function Ee(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`Tick spacing must be positive`)}function De(e){if(e.flippedFromRequest!==!0)return{sqrtPrice:e.sqrtPrice,tick:e.tick};let t=new E(1).dividedBy(new E(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:Se(n)}}function O(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 Oe(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 ke(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 Ae(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 ${w} and ${T}`,`VALIDATION_ERROR`,{type:`INVALID_TICK_BOUNDS`,tickLower:e,tickUpper:t,minTick:w,maxTick:T})}function k(e){if(!ye.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 je(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 Me(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 Ne=/* @__PURE__ */ new Set([`Token`,`Unit`,`none`]),Pe=/^[A-Za-z0-9]+$/u;function A(e){return Pe.test(e)&&e.length<=32&&!Ne.has(e)}function j(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 Fe=class{constructor(e,t){this.dexBackendBaseUrl=e,this.httpClient=t}async getUserAssets(e,t=1,n=10){if(Me(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 Ie(await this.httpClient.sendGetRequest(this.dexBackendBaseUrl,`/user/assets`,``,{address:e,page:t.toString(),limit:n.toString()}))}};function Ie(e){let t=g(e,`data`),n=t?.token;if(!Array.isArray(n)||!n.every(Le))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 Le(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 Re=[`Swap`,`RequestTrade`,`AddLiquidity`,`RemoveLiquidity`,`CollectPositionFees`,`CreatePool`],ze=`DryRun`,Be=`galaconnect-operation-`;function Ve(e){return typeof e==`string`&&Re.includes(e)}function He(e,t){return Ve(t)&&typeof e?.token0==`string`&&typeof e.token1==`string`}function Ue(e){let t={...e};for(let e of[`signature`,`prefix`,`types`,`domain`,`trace`])delete t[e];return t}function We(e,t,n,r,i=Be){return e.signObject(ze,{callerPublicKey:t,method:n,dto:r,uniqueKey:`${i}${globalThis.crypto.randomUUID()}`})}var Ge=class{constructor(e,t){this.signer=t,p(this,`requestor`,void 0),p(this,`baseUrl`,void 0),p(this,`requestTimeoutMs`,void 0),p(this,`wire`,void 0),this.requestor=e.httpRequestor??fetch.bind(globalThis),this.baseUrl=e.dexBackendBaseUrl.replace(/\/$/u,``),this.requestTimeoutMs=e.requestTimeoutMs??3e4,this.wire=e.wire}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 We(this.signer,e,t,Ue(n)),s=`${this.baseUrl}/wallet/connect/galachain/api/${encodeURIComponent(i)}/${encodeURIComponent(a)}/${encodeURIComponent(t)}/fee`,c,l,u;try{let e=await b(this.requestor,s,{method:`POST`,headers:y(this.wire,{json:!0,defaults:{Accept:`application/json`}}),body:JSON.stringify(o)},this.requestTimeoutMs);c=e.status,l=e.ok,u=l?await x(e):void 0}catch{return null}return l?Ke(u):a===`dex-contract`&&(c===403||c===404)?{source:`default`,fees:[{feeInGala:`0`}]}:null}};function Ke(e){if(typeof e!=`object`||!e)return null;let t=e.fees;return!Array.isArray(t)||typeof t[0]?.feeInGala!=`string`?null:e}var qe=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,`status`,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,`wire`,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.status=e.mode===`queued`?`queued`:`executed`,this.result=e.result,this.envelope=e.envelope,this.backendBaseUrl=e.dexBackendBaseUrl.replace(/\/$/u,``),this.requestor=e.httpRequestor,this.requestTimeoutMs=e.requestTimeoutMs??3e4,this.wire=e.wire,this.positionConfirmation=e.positionConfirmation}async confirm(e){return this.method===`RequestTrade`?this.confirmApplied(e):this.confirmPosition(e)}confirmApplied(e){return ue({dexBackendBaseUrl:this.backendBaseUrl,httpRequestor:this.requestor,requestTimeoutMs:this.requestTimeoutMs,wire:this.wire},{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)}},Je=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=Ye(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=n?.walletAddress??this.walletAddress,a=y(this.wire,{json:!0,fixed:i===void 0?{}:{"X-Wallet-Address":i}}),o=await this.post(r,a,t),s=await x(o);if(!o.ok)throw Ze(o,s,r);let c=N(s);if(c?.error===!0)throw new m(_(c,`message`)||`The gateway reported an error for this write.`,`INVALID_GATEWAY_RESPONSE`,{status:o.status,body:s,url:r,type:`GATEWAY_REPORTED_ERROR`});let l=N(c?.data??c?.Data);if(l===void 0)throw M(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&&!Qe(p))throw M(o,s,r,h);if(e===`RequestTrade`&&d===`sync`)throw M(o,s,r,`The gateway executed RequestTrade synchronously, which this SDK refuses; RequestTrade must be queued.`);if(e===`RequestTrade`&&d===`queued`)Xe(o,s,r,l,t);else if(d===`queued`||!(`result`in l))throw M(o,s,r,h);if(d===`sync`){let e=N(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=S(o,`x-transaction-id`),v=u===void 0||u===``?ee:u,te=p==null?se(o):Qe(p)?p:void 0;return new qe({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,wire:this.wire,...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=y(this.wire,{json:!0,fixed:{"X-Wallet-Address":r,"X-Shadow":`true`}}),a=await this.post(this.writeUrl(e),i,t);return{httpStatus:a.status,body:await x(a)}}writeUrl(e){return`${this.dexBackendBaseUrl}/v1/chain/asset/dex-contract/${e}`}async post(e,t,n){try{return await b(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 Ye(e){return e.replace(/\/$/u,``)}function M(e,t,n,r){return new m(r,`INVALID_GATEWAY_RESPONSE`,{status:e.status,body:t,url:n})}function Xe(e,t,n,r,i){let a=_(i,`uniqueKey`)??``,o=r.uniqueKey;if(typeof o==`string`&&o!==``&&o===a)return;let s=o==null||o===``;throw new m(s?`The gateway acknowledged RequestTrade without echoing its uniqueKey, so it cannot be tied to the signed request.`:`Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey.`,`INVALID_GATEWAY_RESPONSE`,{status:e.status,body:t,url:n,type:s?`MISSING_UNIQUE_KEY`:`UNIQUE_KEY_MISMATCH`,uniqueKey:a})}function Ze(e,t,n){let r=N(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?oe(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 N(e){return typeof e==`object`&&e?e:void 0}function Qe(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}const $e={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`}},P=n(`GSWAP_SDK`);var et=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 tt=`gdex.jsonrpc.v1`,nt=[`add`,`remove`,`collect`];function rt(e){let{pool:t}=e;return(e.version===`v1`||e.version===`v2`)&&typeof t==`object`&&!!t&&typeof e.poolHash==`string`&&typeof e.transactionId==`string`&&nt.includes(e.action)&&typeof e.owner==`string`&&typeof e.amount0==`string`&&typeof e.amount1==`string`&&typeof e.blockNumber==`number`&&typeof e.timestamp==`string`}var F=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 it(e){let t=typeof e==`object`&&e?e.subscriptionId:void 0;if(typeof t!=`string`)throw new F(-32603,`GDEX subscribe response is missing its subscriptionId`);return t}var at=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??$e.prod.dexBackendWsUrl,this.requestTimeoutMs=e.requestTimeoutMs??15e3,this.backoff=new et({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=>{rt(t)?e(t):P(`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,tt):new this.webSocketConstructor(this.url,tt,{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(),P(`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`){P(`Ignoring non-text GDEX WebSocket frame`);return}let t;try{t=JSON.parse(e)}catch{P(`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 F(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){P(`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=it(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(),P(`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){P(`GDEX reconnect failed: ${e instanceof Error?e.message:String(e)}`)}}this.reconnecting=!1,this.intentionalClose||P(`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=it(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 F)||e.code!==-32003||n>=5)throw e;let t=this.readRetryAfterMs(e.data);P(`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)}},I=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}`;P(`Sending request to ${o} with body:`,i);let s=!!i,c=await b(this.httpRequestor,o,{method:e,headers:y(this.wire,{json:s}),...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 x(c);return P(`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 ot(e){return{ok:!0,value:e}}function L(e){return{ok:!1,reason:e}}function st(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 ct(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function lt(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 R(e,t){return e<t?[e,t]:[t,e]}function ut(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 z(e){return[e.collection,e.category,e.type,e.additionalKey].join(`$`)}function B(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 dt=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 I(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=>st(`symbols`,e.data,ft,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`?pt(e)?z(B(e)):void 0:z(e),r=t.find(t=>t.symbol===e||n!==void 0&&z(t)===n);if(r===void 0){t=await this.refresh();let r=t.find(t=>t.symbol===e||n!==void 0&&z(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=z(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(A(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]=R(n.symbol,r.symbol);return{token0:i===n.symbol?n:r,token1:a===r.symbol?r:n,flipped:i!==n.symbol}}};function ft(e){let t=ct(e);if(t===void 0)return L(`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?L(`symbol is empty`):typeof r==`string`?typeof i==`string`?typeof a==`string`?typeof o==`string`?typeof s!=`number`||!Number.isInteger(s)||s<0?L(`decimals is not a non-negative integer`):ot({symbol:n,collection:r,category:i,type:a,additionalKey:o,decimals:s}):L(`additionalKey is not a string`):L(`type is not a string`):L(`category is not a string`):L(`collection is not a string`):L(`symbol is not a string`)}function pt(e){return e.includes(`|`)||e.includes(`$`)}function V(e){return typeof e==`string`?e:z(e)}async function H(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 U(e,t){return e.passthrough===!0?V(t):H(e,t)}var mt=class{constructor(){p(this,`passthrough`,!0)}resolve(e){return typeof e==`string`&&!pt(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]=R(n.symbol,r.symbol),a=i!==n.symbol;return{token0:a?r:n,token1:a?n:r,flipped:a}}invalidate(){}},ht=class{constructor(e,t,n={}){this.gateway=e,this.symbols=t,this.options=n,p(this,`http`,void 0),this.http=new I(e.httpRequestor,e.requestTimeoutMs??3e4,e.wire)}async getPools(e){return st(`pools`,(await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,`/pools`,vt(e),e?.signal===void 0?void 0:{signal:e.signal})).data,St,e?.onInvalidEntry??this.options.onInvalidEntry)}async getPool(e,t,n){return k(n),this.getBackend(`/pool`,await this.backendParams(e,t,n))}async getSlot0(e,t,n){return k(n),this.getBackend(`/slot0`,await this.backendParams(e,t,n))}async getCompositePool(e,t,n){if(k(n),this.symbols.passthrough===!0)return this.getBackend(`/composite-pool`,{token0:V(e),token1:V(t),fee:String(n)});let r=ut(R(await H(this.symbols,e),await H(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 U(this.symbols,e),token1:await U(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 gt=[`tvl`,`volume1d`,`volume30d`],_t=1e3;function vt(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(!gt.includes(e.sortBy))throw new m(`sortBy must be one of ${gt.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>_t)throw new m(`limit must be an integer from 1 to ${_t}.`,`VALIDATION_ERROR`,{limit:e.limit});t.limit=String(e.limit)}return Object.keys(t).length===0?void 0:t}const yt=[`poolName`,`token0CompositeKey`,`token1CompositeKey`,`token0Image`,`token1Image`,`creator`,`price`,`sqrtPrice`,`token0Tvl`,`token1Tvl`],bt=[`tickSpacing`,`protocolFees`,`tradingFees`,`tick`,`volume1d`,`volume7d`,`volume30d`,`trades1d`,`fee24h`,`token0Price`,`token1Price`],xt=[`fee`,`tvlUsd`,`apr1d`];function St(e){let t=ct(e);if(t===void 0)return L(`the row is not an object`);for(let e of[`token0`,`token1`,`poolRef`])if(typeof t[e]!=`string`)return L(`${e} is not a string`);if(t.contractVersion!==void 0&&t.contractVersion!==`v2`)return L(`contractVersion is not v2`);let n={...t};for(let e of xt){let r=t[e];if(r===void 0&&e!==`fee`)continue;let i=lt(r);if(i===void 0)return L(`${e} is not a number`);n[e]=i}for(let e of yt)if(t[e]!==void 0&&typeof t[e]!=`string`)return L(`${e} is not a string`);for(let e of bt){let n=t[e];if(n!==void 0&&(typeof n!=`number`||!Number.isFinite(n)))return L(`${e} is not a number`)}return ot(n)}const Ct=`galaswap-operation-`,wt=/^[A-Za-z0-9._:-]*$/u;function Tt(e){if(e===void 0)return Ct;if(!wt.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 Et=/^[A-Za-z0-9._:-]{1,128}$/u;function W(e){if(typeof e!=`string`||!Et.test(e))throw new m(`uniqueKey must be 1-128 characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".`,`VALIDATION_ERROR`,{uniqueKey:e})}function Dt(e){return`${e}${globalThis.crypto.randomUUID()}`}const G=t=>new e(t).toFixed();function Ot(e){k(e.fee),j(e.token0,e.token1),W(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`);O(n,`exactIn`),t[e.tokenInIsToken0?`sell0Qty`:`sell1Qty`]=G(n),e.amountOutMinimum!==void 0&&(O(e.amountOutMinimum,`amountOutMinimum`,!0),t.amountOutMinimum=G(e.amountOutMinimum))}else{let n=e.exactOut;if(n===void 0)throw new m(`exactOut is required for an exact-output swap.`,`VALIDATION_ERROR`);O(n,`exactOut`),t[e.tokenInIsToken0?`buy1Qty`:`buy0Qty`]=G(n),e.amountInMaximum!==void 0&&(O(e.amountInMaximum,`amountInMaximum`,!0),t.amountInMaximum=G(e.amountInMaximum))}return e.priceLimit!==void 0&&(O(e.priceLimit,`priceLimit`),t.priceLimit=G(e.priceLimit)),t}function kt(e){k(e.fee),j(e.token0,e.token1),D(e.tickLower,e.tickUpper,e.fee),W(e.uniqueKey)}function At(e){kt(e);let t=Ft(e.depositQuantityToken0,e.depositQuantityToken1,`depositQuantityToken0`,`depositQuantityToken1`);if(t===void 0)throw new m(`Provide exactly one of depositQuantityToken0 or depositQuantityToken1.`,`VALIDATION_ERROR`);return O(t.amount,t.name),{token0:e.token0,token1:e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,uniqueKey:e.uniqueKey,[t.name]:G(t.amount)}}function jt(e){kt(e);let t=Ft(e.withdrawalQuantityToken0,e.withdrawalQuantityToken1,`withdrawalQuantityToken0`,`withdrawalQuantityToken1`,!0);return t!==void 0&&O(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]:G(t.amount)}}}function Mt(e){return kt(e),{token0:e.token0,token1:e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,uniqueKey:e.uniqueKey}}function Nt(t){k(t.fee),W(t.uniqueKey),j(t.token0Symbol,t.token1Symbol);for(let e of[t.token0Symbol,t.token1Symbol])if(!A(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])Pt(e);let n=Ft(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 Pt(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 Ft(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 K(e,t,n){return new m(`${e} DTO field ${t} must be ${n}.`,`VALIDATION_ERROR`,{type:`INVALID_DTO`,method:e,field:t})}function It(e,t){let n=n=>{let r=t[n];if(typeof r!=`string`)throw K(e,n,`a string`);return r},r=n=>{let r=t[n];if(typeof r!=`number`)throw K(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 K(e,n,`a class key`);let i=r,a=t=>{if(typeof i[t]!=`string`)throw K(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 K(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`)?Ot({...l,exactIn:n(a),amountOutMinimum:i(`amountOutMinimum`),priceLimit:u}):Ot({...l,exactOut:n(a),amountInMaximum:i(`amountInMaximum`),priceLimit:u})}case`AddLiquidity`:{let e=i(`depositQuantityToken0`),t=i(`depositQuantityToken1`);return At({...c(),...e===void 0?{depositQuantityToken1:t}:{depositQuantityToken0:e}})}case`RemoveLiquidity`:return jt({...c(),withdrawalQuantityToken0:i(`withdrawalQuantityToken0`),withdrawalQuantityToken1:i(`withdrawalQuantityToken1`)});case`CollectPositionFees`:return Mt(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 K(e,`privateAccess`,`an array of strings`);if(t.isPrivate!==void 0&&typeof t.isPrivate!=`boolean`)throw K(e,`isPrivate`,`a boolean`);return Nt({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 q(e,t){let n=It(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 Lt(e){return{token0:e.token0,token1:e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper}}var Rt=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 I(e.httpRequestor,e.requestTimeoutMs??3e4,e.wire),this.uniqueKeyPrefix=Tt(i.uniqueKeyPrefix),this.onInvalidEntry=i.onInvalidEntry}async getUserPositions(e){return st(`positions`,(await this.get(`/positions`,{user:e})).data,Ht,this.onInvalidEntry)}async getPosition(e,t){let n=await this.getNullable(`/position`,await this.positionParams(e),t);return n===null?null:Ut(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:V(e.token0),token1:V(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 O(t.amount,`amount`),(await this.get(`/add-liq-estimate`,{token0:V(t.token0),token1:V(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 O(t.liquidity,`liquidity`),(await this.get(`/remove-liq-estimate`,{token0:V(t.token0),token1:V(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){k(e.fee);let t=await this.symbols.orderPair(e.token0,e.token1),n=this.canonicalTicks(e.tickLower,e.tickUpper,t.flipped);D(n.tickLower,n.tickUpper,e.fee),O(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?At({...r,depositQuantityToken1:e.amount}):At({...r,depositQuantityToken0:e.amount})}async submitAddLiquidity(e){return q(`AddLiquidity`,e),this.submit(`AddLiquidity`,e,{kind:`add`,identity:Lt(e)})}async addLiquidityByPrice(t){k(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=we(Ce(n),i),o=Te(Ce(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){k(e.fee);let t=await this.symbols.orderPair(e.token0,e.token1),n=this.canonicalTicks(e.tickLower,e.tickUpper,t.flipped);if(D(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&&O(e.amount0,`amount0`),e.amount1!==void 0&&O(e.amount1,`amount1`);let[r,i]=t.flipped?[e.amount1,e.amount0]:[e.amount0,e.amount1];return jt({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){q(`RemoveLiquidity`,e);let t=e.withdrawalQuantityToken0===void 0&&e.withdrawalQuantityToken1===void 0;return this.submit(`RemoveLiquidity`,e,{kind:t?`removeFull`:`removePartial`,identity:Lt(e)})}async collectPositionFees(e){return this.submitCollectPositionFees(await this.buildCollectPositionFees(e))}async buildCollectPositionFees(e){k(e.fee);let t=await this.symbols.orderPair(e.token0,e.token1),n=this.canonicalTicks(e.tickLower,e.tickUpper,t.flipped);return D(n.tickLower,n.tickUpper,e.fee),Mt({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 q(`CollectPositionFees`,e),this.submit(`CollectPositionFees`,e,{kind:`collect`,identity:Lt(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`);k(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 Nt(n?{...d,startingPrice:u}:{...d,startingSqrtPrice:u})}async submitCreatePool(e){q(`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=ve[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?Dt(this.uniqueKeyPrefix):(W(e),e)}async resolveCreateToken(e,t){try{let n=typeof e==`object`?z(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??B({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=B(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(!A(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 B(e)}catch{return}}};const zt=[`token0Symbol`,`token1Symbol`,`owner`,`liquidity`,`amount0`,`amount1`],Bt=[`fee`,`tickLower`,`tickUpper`],Vt=[`token0CompositeKey`,`token1CompositeKey`,`token0Image`,`token1Image`,`sqrtPrice`,`fees0`,`fees1`];function Ht(e){let t=ct(e);if(t===void 0)return L(`the row is not an object`);for(let e of zt)if(typeof t[e]!=`string`)return L(`${e} is not a string`);for(let e of Bt){let n=t[e];if(typeof n!=`number`||!Number.isFinite(n))return L(`${e} is not a number`)}if(typeof t.inRange!=`boolean`)return L(`inRange is not a boolean`);for(let e of Vt)if(t[e]!==void 0&&typeof t[e]!=`string`)return L(`${e} is not a string`);let n=t.currentTick;if(n!==void 0&&(typeof n!=`number`||!Number.isFinite(n)))return L(`currentTick is not a number`);let r=t.poolRef??t.pool??``;if(typeof r!=`string`)return L(`pool is not a string`);let i=Object.fromEntries([...Vt,`currentTick`].flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]));return ot({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 Ut(e){let t=Ht(e);if(t.ok)return t.value;throw new m(`Backend returned an invalid position.`,`INVALID_CHAIN_RESPONSE`,{data:e,reason:t.reason})}var Wt=class{constructor(e,t){this.gateway=e,this.symbols=t,p(this,`http`,void 0),this.http=new I(e.httpRequestor,e.requestTimeoutMs??3e4,e.wire)}async quoteExactInput(e,t,n,r){return O(n,`amountIn`),this.quote(e,t,{amountIn:tn(n)},r)}async quoteExactOutput(e,t,n,r){return O(n,`amountOut`),this.quote(e,t,{amountOut:tn(n)},r)}async quote(e,t,n,r){en(r);let i={tokenIn:await U(this.symbols,e),tokenOut:await U(this.symbols,t),...n};r!==void 0&&(i.fee=String(r));try{return Gt((await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,`/quote`,i)).data)}catch(n){throw Zt(n,e,t,r)}}};function Gt(t){if(!Jt(t))throw new m(`Backend returned an invalid quote.`,`INVALID_CHAIN_RESPONSE`,{data:t});let n=t,r=n.currentPrice===void 0?qt(n.currentSqrtPrice,n.tokenInIsToken0):new e(n.currentPrice),i=n.newPrice===void 0?qt(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 Kt=e.clone({DECIMAL_PLACES:60});function qt(e,t){let n=new Kt(e).pow(2);return t?n:new Kt(1).dividedBy(n)}function Jt(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`&&Yt(t.currentSqrtPrice)&&Yt(t.newSqrtPrice)&&Yt(t.currentPrice)&&Yt(t.newPrice)&&(t.currentSqrtPrice!==void 0||t.currentPrice!==void 0)&&(t.newSqrtPrice!==void 0||t.newPrice!==void 0)}function Yt(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 Xt=/no pool|no pools|pool does not exist|has no trading symbol on the new DEX contract/iu;function Zt(e,t,n,r){if(e instanceof m){let i=Qt(e.details),a=$t(e.details)??e.message;return i===404||Xt.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 Qt(e){let t=e?.status;return typeof t==`number`?t:void 0}function $t(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 en(e){if(e!==void 0&&!ye.some(t=>Number(t)===Number(e)))throw new m(`Invalid fee tier: ${e}`,`VALIDATION_ERROR`,{fee:e})}function tn(t){return new e(t).toFixed()}function nn(e){return e===503?`unavailable`:e===400?`disabled`:`unknown`}function rn(e,t){return t===`SHADOW_UNAVAILABLE`?`unavailable`:t===`SHADOW_RELAY_REJECTED`?`rejected`:t===`SHADOW_DISABLED`||t===`SHADOW_UNSUPPORTED_TYPE`?`disabled`:nn(e)}function an(e,t,n){let{httpStatus:r,body:i}=n,a=on(i);if(r>=200&&r<300&&a?.error===!1){let n=on(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=rn(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 on(e){return typeof e==`object`&&e?e:void 0}function sn(e){k(e.fee),j(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 cn=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=Tt(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){k(n);let a=i?.uniqueKey??Dt(this.uniqueKeyPrefix);W(a);let o=await H(this.symbols,e),s=await H(this.symbols,t),c=this.orientPool(o,s,i?.pool);return Ot({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 an(`RequestTrade`,t,await this.gateway.submitShadow(`RequestTrade`,t,this.submitOptions()))}submitOptions(){return this.walletAddress===void 0?{}:{walletAddress:this.walletAddress}}async signRequestTrade(e){if(q(`RequestTrade`,e),this.signer===void 0)throw m.noSignerError();return this.signer.signObject(`RequestTrade`,e)}orientPool(e,t,n){if(n===void 0)return ut(R(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 W(e),new qe({method:`RequestTrade`,uniqueKey:e,transactionId:null,mode:`queued`,result:void 0,dexBackendBaseUrl:this.gateway.dexBackendBaseUrl,httpRequestor:this.gateway.httpRequestor,requestTimeoutMs:this.gateway.requestTimeoutMs,wire:this.gateway.wire}).confirm({initialDelayMs:0,...t})}},ln=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=$e[e?.env??`prod`];this.dexBackendBaseUrl=un(e?.dexBackendBaseUrl??t.dexBackendBaseUrl),this.chainCallTimeoutMs=e?.chainCallTimeoutMs??3e4,this.signer=e?.signer,this.walletAddress=e?.walletAddress;let n=new I(e?.httpRequestor,this.chainCallTimeoutMs,e?.wire);this.gateway=new Je({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 dt(this.gateway,r);let i=e?.symbolResolution===`canonical`?new mt:this.symbols;this.quoting=new Wt(this.gateway,i),this.pools=new ht(this.gateway,i,r);let a={uniqueKeyPrefix:e?.uniqueKeyPrefix,...r};this.positions=new Rt(this.gateway,i,this.signer,this.walletAddress,a),this.swaps=new cn(this.gateway,i,this.signer,this.walletAddress,a),this.assets=new Fe(this.dexBackendBaseUrl,n),this.fees=new Ge(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 at({url:this.dexBackendWsUrl,...this.webSocketImpl===void 0?{}:{webSocketImpl:this.webSocketImpl},...this.streamApiKey===void 0?{}:{apiKey:this.streamApiKey}})),this.streamClient}};function un(e){return e.replace(/\/$/u,``)}const dn=`pendingSwaps.v1`,fn=6048e5;var pn=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 mn(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)))}const u=`0,500,3000,10000`,d={HTTP_ERROR:{template:`Unexpected HTTP error {status} from {url}.`,params:{status:`number`,url:`string`}},REQUEST_TIMEOUT:{template:`Request to {url} timed out after {timeoutMs} ms.`,params:{url:`string`,timeoutMs:`number`}},TRANSPORT_ERROR:{template:`The request to {url} failed before the server answered.`,params:{url:`string`}},REQUEST_FAILED:{template:`The {operation} request failed.`,params:{operation:`string`}},INVALID_TIMEOUT:{template:`{field} must be a positive number of milliseconds, or Infinity for no timeout (got {value}).`,params:{field:`string`,value:`number`}},METHOD_NOT_SUPPORTED:{template:`The method {method} is not supported; swaps are queued through RequestTrade.`,params:{method:`string`}},SUBMISSION_OUTCOME_UNKNOWN:{template:`The submission outcome is unknown because the gateway request timed out. Confirm before retrying.`,params:{}},GATEWAY_REPORTED_ERROR:{template:`The gateway reported an error for this write: {serverMessage}`,params:{serverMessage:`string`}},GATEWAY_DATA_MISSING:{template:`The gateway response is missing its data object.`,params:{}},GATEWAY_MODE_INVALID:{template:`Gateway response must contain data.mode="sync" with data.result, or data.mode="queued".`,params:{}},GATEWAY_SYNC_REQUEST_TRADE:{template:`The gateway executed RequestTrade synchronously, which this SDK refuses; RequestTrade must be queued.`,params:{}},MISSING_UNIQUE_KEY:{template:`The gateway acknowledged RequestTrade without echoing its uniqueKey, so it cannot be tied to the signed request.`,params:{}},UNIQUE_KEY_MISMATCH:{template:`Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey.`,params:{}},SHADOW_NOT_QUEUED:{template:`The swap backend did not queue the shadow request.`,params:{}},SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS:{template:`A shadow submission needs a walletAddress (the X-Wallet-Address header): pass one to the GSwap constructor or to this call.`,params:{}},METHOD_NOT_ALLOWED:{template:`The gateway does not expose this contract method: {serverMessage}`,params:{serverMessage:`string`}},SIGNATURE_INVALID:{template:`The gateway could not verify the signature: {serverMessage}`,params:{serverMessage:`string`}},SIGNER_MISMATCH:{template:`The recovered signer does not match an actor named by the operation: {serverMessage}`,params:{serverMessage:`string`}},DTO_INVALID:{template:`The gateway rejected the DTO shape: {serverMessage}`,params:{serverMessage:`string`}},BOUNDS_VIOLATION:{template:`The gateway rejected a numeric, tick, symbol or range bound: {serverMessage}`,params:{serverMessage:`string`}},SYMBOL_CONFLICT:{template:`The CreatePool symbol is already owned by another class: {serverMessage}`,params:{serverMessage:`string`}},RATE_LIMITED:{template:`The gateway rate-limited this signer: {serverMessage}`,params:{serverMessage:`string`}},CHAIN_DISPATCH_FAILED:{template:`The chain dispatch failed: {serverMessage}`,params:{serverMessage:`string`}},GATEWAY_REJECTED:{template:`Gateway rejected {gatewayCode}: {serverMessage}`,params:{gatewayCode:`string`,serverMessage:`string`}},CHAIN_REJECTED:{template:`GalaChain error {errorKey}: {serverMessage}`,params:{errorKey:`string`,serverMessage:`string`}},INVALID_CHAIN_RESPONSE:{template:`Backend returned an invalid {resource}.`,params:{resource:`string`}},INVALID_POSITION_RESPONSE:{template:`Backend returned an invalid position ({reason}).`,params:{reason:`string`}},CONFIRMATION_TIMEOUT:{template:`Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.`,params:{}},CONFIRMATION_ABORTED:{template:`Transaction confirmation was aborted.`,params:{}},CONFIRMATION_FAILED:{template:`Transaction confirmation failed with HTTP {status}.`,params:{status:`number`}},CONFIRMATION_MALFORMED:{template:`Transaction confirmation returned a malformed body.`,params:{}},CONFIRMATION_KEY_MISMATCH:{template:`Apply result key did not match the requested key.`,params:{}},NO_SIGNER:{template:`This method requires a signer. Please provide a signer to the GSwap constructor.`,params:{}},NO_WALLET_ADDRESS:{template:`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.`,params:{}},NO_POOL_AVAILABLE:{template:`No pool is available for {tokenIn}/{tokenOut} (fee tier {fee}).`,params:{tokenIn:`string`,tokenOut:`string`,fee:`string`}},INSUFFICIENT_LIQUIDITY:{template:`The selected pool has insufficient liquidity for {tokenIn}/{tokenOut} (fee tier {fee}).`,params:{tokenIn:`string`,tokenOut:`string`,fee:`string`}},UNKNOWN_TOKEN:{template:`Token {token} has no trading symbol on the new DEX contract (no gcdex pool includes it yet).`,params:{token:`string`}},SYMBOL_NOT_FOUND:{template:`Token {token} could not be resolved to a trading symbol.`,params:{token:`string`}},STREAM_API_KEY_UNUSABLE:{template:`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.`,params:{}},STREAM_WEBSOCKET_UNAVAILABLE:{template:`GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the "ws" package).`,params:{}},STREAM_NOT_CONNECTED:{template:`GDEX stream is not connected. Call connect() first.`,params:{}},STREAM_DISCONNECTED:{template:`GDEX stream disconnected.`,params:{}},STREAM_REQUEST_TIMEOUT:{template:`GDEX request "{method}" timed out after {timeoutMs} ms.`,params:{method:`string`,timeoutMs:`number`}},STREAM_CONNECT_FAILED:{template:`Failed to connect to GDEX stream at {url}.`,params:{url:`string`}},STREAM_CLOSED_BEFORE_CONNECT:{template:`GDEX stream closed before connecting (code {closeCode}).`,params:{closeCode:`number`}},STREAM_CONNECTION_CLOSED:{template:`GDEX stream connection closed (code {closeCode}).`,params:{closeCode:`number`}},GALA_WALLET_NOT_AVAILABLE:{template:`Gala wallet is not available. Please ensure the Gala wallet is connected.`,params:{}},WALLET_UNAVAILABLE:{template:`No wallet is connected.`,params:{}},MALFORMED_WALLET_REQUEST:{template:`Wallet {method} request is malformed.`,params:{method:`string`}},UNSUPPORTED_WALLET_METHOD:{template:`Unsupported wallet method {method}.`,params:{method:`string`}},INVALID_SIGNATURE:{template:`Wallet returned an invalid {scheme} signature.`,params:{scheme:`string`}},INVALID_CHAIN_ID:{template:`Wallet returned an invalid chain id ({chainId}).`,params:{chainId:`string`}},SIGNER_ADDRESS_MISMATCH:{template:`The signing key does not belong to the expected account.`,params:{}},INVALID_PRIVATE_KEY:{template:`Invalid private key: {reason}.`,params:{reason:`string`}},INVALID_SIGNING_HASH_LENGTH:{template:`secp256k1 can only sign a 32-byte hash (got {length}).`,params:{length:`number`}},MISSING_WALLET_ADDRESS:{template:`Invalid wallet address: No wallet address provided. Either provide a wallet address to the function you are calling, or set one when instantiating GSwapSDK.`,params:{}},INVALID_WALLET_ADDRESS:{template:`Invalid {field}: "{value}" is not an accepted wallet address form.`,params:{field:`string`,value:`string`}},INVALID_DECIMAL:{template:`Invalid decimal quantity: {value}`,params:{value:`string`}},PERSONAL_SIGN_NOT_JSON:{template:`Personal-sign DTO is not valid JSON`,params:{}},PERSONAL_SIGN_NOT_OBJECT:{template:`Personal-sign DTO must be a JSON object`,params:{}},PERSONAL_SIGN_BAD_PREFIX:{template:`Personal-sign DTO prefix is not an EIP-191 "Ethereum Signed Message" header`,params:{}},PERSONAL_SIGN_ENVELOPE_FIELDS:{template:`Personal-sign DTO carries signing-envelope field(s): {fields}`,params:{fields:`string`}},PERSONAL_SIGN_NOT_CANONICAL:{template:`Personal-sign DTO is not in canonical serialized form`,params:{}},EIP712_NAME_COLLISION:{template:`Name collisions are not supported when deriving EIP-712 types ({name}).`,params:{name:`string`}},EIP712_UNSUPPORTED_VALUE:{template:`Unsupported EIP-712 value of type {valueType}.`,params:{valueType:`string`}},TYPED_DATA_NOT_STRING:{template:`Invalid typed data: {what} must be a string`,params:{what:`string`}},TYPED_DATA_UNPAIRED_SURROGATE:{template:`Invalid typed data: {what} has an unpaired surrogate`,params:{what:`string`}},TYPED_DATA_NOT_HEX_BYTES:{template:`Invalid typed data: {what} must be an even-length 0x hex string`,params:{what:`string`}},TYPED_DATA_NOT_SAFE_INTEGER:{template:`Invalid typed data: {what} must be a safe integer`,params:{what:`string`}},TYPED_DATA_NOT_INTEGER:{template:`Invalid typed data: {what} must be an integer`,params:{what:`string`}},TYPED_DATA_NOT_BOOLEAN:{template:`Invalid typed data: bool must be a boolean`,params:{}},TYPED_DATA_BAD_ADDRESS:{template:`Invalid typed data: address must be 0x followed by 40 hex digits`,params:{}},TYPED_DATA_BAD_CHECKSUM:{template:`Invalid typed data: address has a bad checksum`,params:{}},TYPED_DATA_BYTES_LENGTH:{template:`Invalid typed data: {type} must be exactly {width} bytes`,params:{type:`string`,width:`number`}},TYPED_DATA_OUT_OF_BOUNDS:{template:`Invalid typed data: value out of bounds for {type}`,params:{type:`string`}},TYPED_DATA_UNSUPPORTED_TYPE:{template:`Invalid typed data: unsupported type "{type}"`,params:{type:`string`}},TYPED_DATA_FIELDS_NOT_LIST:{template:`Invalid typed data: type {typeName} must be a list of fields`,params:{typeName:`string`}},TYPED_DATA_FIELD_MALFORMED:{template:`Invalid typed data: type {typeName} has a field without a string name and type`,params:{typeName:`string`}},TYPED_DATA_INVALID_FIELD_NAME:{template:`Invalid typed data: invalid field name "{name}"`,params:{name:`string`}},TYPED_DATA_DUPLICATE_FIELD:{template:`Invalid typed data: duplicate field "{name}" in {typeName}`,params:{name:`string`,typeName:`string`}},TYPED_DATA_INVALID_TYPE_NAME:{template:`Invalid typed data: invalid type name "{name}"`,params:{name:`string`}},TYPED_DATA_CIRCULAR_TYPE:{template:`Invalid typed data: circular type reference in {typeName}`,params:{typeName:`string`}},TYPED_DATA_UNKNOWN_FIELD_TYPE:{template:`Invalid typed data: unknown type "{type}" in {typeName}`,params:{type:`string`,typeName:`string`}},TYPED_DATA_NO_PRIMARY_TYPE:{template:`Invalid typed data: missing primary type`,params:{}},TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE:{template:`Invalid typed data: ambiguous primary types or unused types ({roots})`,params:{roots:`string`}},TYPED_DATA_ARRAY_EXPECTED:{template:`Invalid typed data: {type} array value must be an array`,params:{type:`string`}},TYPED_DATA_ARRAY_LENGTH_MISMATCH:{template:`Invalid typed data: array length mismatch`,params:{}},TYPED_DATA_STRUCT_NOT_OBJECT:{template:`Invalid typed data: {typeName} value must be an object`,params:{typeName:`string`}},TYPED_DATA_MISSING_FIELD:{template:`Invalid typed data: {typeName} value is missing field "{field}"`,params:{typeName:`string`,field:`string`}},TYPED_DATA_DOMAIN_NOT_OBJECT:{template:`Invalid typed data: domain must be an object`,params:{}},TYPED_DATA_INVALID_DOMAIN_KEY:{template:`Invalid typed data: invalid typed-data domain key {key}`,params:{key:`string`}},NON_CANONICAL_PAIR:{template:`The pair {token0}/{token1} is not in canonical order: token0 must sort before token1.`,params:{token0:`string`,token1:`string`}},UNORDERABLE_SYMBOLS:{template:`Unable to order trading symbols: expected a pair of symbols, got {received}.`,params:{received:`string`}},INVALID_TOKEN_CLASS_KEY:{template:`Invalid token class key "{tokenClassKey}": expected a collection followed by category, type and additionalKey`,params:{tokenClassKey:`string`}},INCOMPLETE_TOKEN_CLASS_KEY:{template:`Token class key "{compositeKey}" is missing {part}.`,params:{compositeKey:`string`,part:`string`}},INVALID_TRADING_SYMBOL:{template:`Invalid trading symbol "{symbol}": must be 1-32 ASCII letters and digits and not a reserved word (Token, Unit, none).`,params:{symbol:`string`}},NO_VALID_TRADING_SYMBOL:{template:`No valid trading symbol for token class {classKey}: "{displaySymbol}" is not an acceptable symbol and none is registered`,params:{classKey:`string`,displaySymbol:`string`}},TOKEN_SYMBOL_NOT_REGISTERED:{template:`Token {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.`,params:{token:`string`}},SYMBOL_DISAGREES_WITH_REGISTRY:{template:`Supplied symbol {suppliedSymbol} for {token} disagrees with the registered trading symbol {registeredSymbol}.`,params:{token:`string`,suppliedSymbol:`string`,registeredSymbol:`string`}},CREATE_POOL_NEEDS_CLASS_KEY:{template:`createPool needs each token as a class key; {token} is a bare trading symbol, which does not carry one.`,params:{token:`string`}},INVALID_UNIQUE_KEY:{template:`The uniqueKey "{uniqueKey}" must be 1-128 characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".`,params:{uniqueKey:`string`}},INVALID_UNIQUE_KEY_PREFIX:{template:`uniqueKeyPrefix "{uniqueKeyPrefix}" must be at most {maxLength} characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".`,params:{uniqueKeyPrefix:`string`,maxLength:`number`}},AMOUNT_IS_JS_NUMBER:{template:`Invalid {field}: use a decimal string or BigNumber, not a JavaScript number`,params:{field:`string`}},AMOUNT_NOT_FINITE:{template:`Invalid {field}: must be a finite number (got {value})`,params:{field:`string`,value:`string`}},AMOUNT_NOT_POSITIVE:{template:`Invalid {field}: must be positive (got {value})`,params:{field:`string`,value:`string`}},AMOUNT_NEGATIVE:{template:`Invalid {field}: must not be negative (got {value})`,params:{field:`string`,value:`string`}},PRICE_VALUES_IS_JS_NUMBER:{template:`Invalid price values: use decimal strings or BigNumber values, not JavaScript numbers`,params:{}},INVALID_PRICE_VALUES:{template:`Invalid price values: all prices must be finite and positive (spot {spotPrice}, lower {lowerPrice}, upper {upperPrice})`,params:{spotPrice:`string`,lowerPrice:`string`,upperPrice:`string`}},INVALID_PRICE_RANGE:{template:`Invalid price range: lower price {lowerPrice} must be less than or equal to upper price {upperPrice}`,params:{lowerPrice:`string`,upperPrice:`string`}},INVALID_PRICE_BOUNDS:{template:`Price bounds must be finite and positive (minPrice {minPrice}, maxPrice {maxPrice}).`,params:{minPrice:`string`,maxPrice:`string`}},PRICE_BOUNDS_ORDER:{template:`minPrice {minPrice} must be less than or equal to maxPrice {maxPrice}.`,params:{minPrice:`string`,maxPrice:`string`}},INVALID_STARTING_PRICE:{template:`Starting price must be finite and positive (got {value}).`,params:{value:`string`}},INVALID_SQRT_PRICE:{template:`Cannot invert a non-positive sqrt price ({sqrtPrice}).`,params:{sqrtPrice:`string`}},INVALID_TOKEN_DECIMALS:{template:`Invalid {field}: must be a non-negative integer (got {value})`,params:{field:`string`,value:`number`}},TICKS_NOT_INTEGERS:{template:`Invalid tick values: ticks must be integers (got {tickLower} and {tickUpper})`,params:{tickLower:`number`,tickUpper:`number`}},INVALID_TICK_RANGE:{template:`Invalid tick range: tickLower {tickLower} must be less than tickUpper {tickUpper}`,params:{tickLower:`number`,tickUpper:`number`}},TICKS_OUT_OF_BOUNDS:{template:`Invalid tick range: ticks {tickLower} and {tickUpper} must be between {minTick} and {maxTick}`,params:{tickLower:`number`,tickUpper:`number`,minTick:`number`,maxTick:`number`}},TICKS_NOT_ALIGNED:{template:`Ticks {tickLower} and {tickUpper} must be aligned to spacing {spacing}.`,params:{tickLower:`number`,tickUpper:`number`,spacing:`number`}},INVALID_TICK_SPACING:{template:`Invalid tick spacing: must be a positive integer (got {value})`,params:{value:`number`}},INVALID_FEE:{template:`Invalid {field}: {value} is not a supported fee tier; must be one of {allowed}.`,params:{field:`string`,value:`number`,allowed:`string`}},EXACT_AMOUNT_REQUIRED:{template:`{field} is required for this swap.`,params:{field:`string`}},EXACTLY_ONE_OF_REQUIRED:{template:`Provide exactly one of {first} or {second}.`,params:{first:`string`,second:`string`}},AT_MOST_ONE_OF_ALLOWED:{template:`Provide at most one of {first} or {second}.`,params:{first:`string`,second:`string`}},POOL_MISMATCH:{template:`tokenIn {tokenIn} and tokenOut {tokenOut} must be the two tokens of the pinned pool {poolToken0}/{poolToken1}.`,params:{tokenIn:`string`,tokenOut:`string`,poolToken0:`string`,poolToken1:`string`}},INVALID_DTO:{template:`{method} DTO field {field} is invalid (expected {expected}).`,params:{method:`string`,field:`string`,expected:`string`}},DTO_NOT_CANONICAL:{template:`The {method} DTO is not in the form the SDK builders produce; build it with the matching build function and submit that.`,params:{method:`string`}},SEARCH_TOO_LONG:{template:`search must be at most {maxLength} characters (got {length}).`,params:{length:`number`,maxLength:`number`}},INVALID_SORT_BY:{template:`sortBy "{value}" is not allowed; it must be one of {allowed}.`,params:{value:`string`,allowed:`string`}},INVALID_SORT_ORDER:{template:`sortOrder "{value}" is not allowed; it must be asc or desc.`,params:{value:`string`}},INVALID_PAGE:{template:`page must be an integer of at least 1 (got {value}).`,params:{value:`number`}},INVALID_LIMIT:{template:`limit must be an integer from {min} to {max} (got {value}).`,params:{value:`number`,min:`number`,max:`number`}}},f=Object.fromEntries(Object.entries(d).map(([e,t])=>[e,t.template])),p=/\{([A-Za-z0-9_]+)\}/gu;function m(e,t){return e.replace(p,(e,n)=>{let r=t[n];return r===void 0?e:String(r)})}function h(e){"@babel/helpers - typeof";return h=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},h(e)}function ee(e,t){if(h(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(h(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function te(e){var t=ee(e,`string`);return h(t)==`symbol`?t:t+``}function g(e,t,n){return(t=te(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var _=class e extends Error{constructor(e,t,n={}){super(m(d[e].template,t),n.cause===void 0?void 0:{cause:n.cause}),g(this,`code`,void 0),g(this,`params`,void 0),g(this,`retryAfterMs`,void 0),g(this,`status`,void 0),g(this,`body`,void 0),g(this,`bodyText`,void 0),g(this,`url`,void 0),g(this,`uniqueKey`,void 0),g(this,`requestTransactionId`,void 0),g(this,`applyTransactionId`,void 0),g(this,`blockNumber`,void 0),this.name=`GSwapSDKError`,this.code=e,this.params=t,this.retryAfterMs=n.retryAfterMs,this.status=n.status,this.body=typeof n.body==`string`?void 0:n.body,this.bodyText=typeof n.body==`string`?n.body:void 0,this.url=n.url,this.uniqueKey=n.uniqueKey,this.requestTransactionId=n.requestTransactionId,this.applyTransactionId=n.applyTransactionId,this.blockNumber=n.blockNumber}get notFound(){return this.status===404||this.code===`NO_POOL_AVAILABLE`||this.code===`UNKNOWN_TOKEN`}static noSignerError(){return new e(`NO_SIGNER`,{})}static noWalletAddressError(){return new e(`NO_WALLET_ADDRESS`,{})}static noPoolAvailableError(t,n,r,i){return new e(`NO_POOL_AVAILABLE`,{tokenIn:v(t),tokenOut:v(n),fee:ne(r)},re(i))}static insufficientLiquidityError(t,n,r,i){return new e(`INSUFFICIENT_LIQUIDITY`,{tokenIn:v(t),tokenOut:v(n),fee:ne(r)},re(i))}static fromGatewayBounce(t,n,r,i,a,o){let s={status:r,body:i,url:a,retryAfterMs:o},c={serverMessage:n};switch(t){case`METHOD_NOT_ALLOWED`:return new e(`METHOD_NOT_ALLOWED`,c,s);case`SIGNATURE_INVALID`:return new e(`SIGNATURE_INVALID`,c,s);case`SIGNER_MISMATCH`:return new e(`SIGNER_MISMATCH`,c,s);case`DTO_INVALID`:return new e(`DTO_INVALID`,c,s);case`BOUNDS_VIOLATION`:return new e(`BOUNDS_VIOLATION`,c,s);case`SYMBOL_CONFLICT`:return new e(`SYMBOL_CONFLICT`,c,s);case`RATE_LIMITED`:return new e(`RATE_LIMITED`,c,s);case`CHAIN_DISPATCH_FAILED`:return new e(`CHAIN_DISPATCH_FAILED`,c,s);default:return new e(`GATEWAY_REJECTED`,{gatewayCode:t,serverMessage:n},s)}}static fromChainError(t,n,r){return new e(`CHAIN_REJECTED`,{errorKey:t,serverMessage:n},r)}static unknownTokenError(t){return new e(`UNKNOWN_TOKEN`,{token:v(t)})}static confirmationTimeoutError(t,n){return new e(`CONFIRMATION_TIMEOUT`,{},{uniqueKey:t,cause:n})}static async fromErrorResponse(t,n){let r=await n.text(),i=ae(r),a=y(i,`error`),o=b(a,`ErrorKey`),s=b(a,`Message`),c={status:n.status,body:i??r,url:t};return o!==void 0&&s!==void 0?new e(`CHAIN_REJECTED`,{errorKey:o,serverMessage:s},c):new e(`HTTP_ERROR`,{status:n.status,url:t},c)}};function v(e){return typeof e==`string`?e:[e.collection,e.category,e.type,e.additionalKey].join(`$`)}function ne(e){return e===void 0?`any`:String(e)}function re(e){return e===void 0?{}:{status:e.status,body:e.body??e.bodyText,url:e.url}}function ie(e,t){return e instanceof _&&(t===void 0||e.code===t)}function y(e,t){if(typeof e!=`object`||!e||!(t in e))return;let n=e[t];return typeof n==`object`&&n?n:void 0}function b(e,t){if(typeof e!=`object`||!e||!(t in e))return;let n=e[t];return typeof n==`string`?n:void 0}function ae(e){try{return JSON.parse(e)}catch{return}}function oe(e,t){if(t===1/0)return()=>void 0;let n=setTimeout(()=>e.abort(),t);return()=>clearTimeout(n)}function se(e,t){if(e===1/0||Number.isFinite(e)&&e>0)return e;throw new _(`INVALID_TIMEOUT`,{field:t,value:e})}const ce=/[A-Za-z0-9\-._~!'()*$|:,]/u;function le(e){let t=``;for(let n of e)n===` `?t+=`+`:ce.test(n)?t+=n:t+=ue(n);return t}function ue(e){try{return encodeURIComponent(e)}catch{return`%EF%BF%BD`}}function de(e,t=`standard`){return t===`readable`?Object.entries(e).map(([e,t])=>`${le(e)}=${le(t)}`).join(`&`):new URLSearchParams(e).toString()}function x(e,t={}){let n=/* @__PURE__ */ new Map,r=(e,t=!1)=>{for(let[r,i]of Object.entries(e??{}))t&&n.delete(r.toLowerCase()),n.set(r.toLowerCase(),[r,i])};return e?.userAgent!==!1&&r({"User-Agent":e?.userAgent??`GalaChain-SDK/1.2.0-rc.3`}),r(t.defaults),r(e?.headers),t.json===!0&&!n.has(`content-type`)&&r({"Content-Type":`application/json`}),r(t.fixed,!0),Object.fromEntries(n.values())}const S=async(e,t)=>{try{return await fetch(e,t)}catch(n){throw t?.signal?.aborted===!0?n:new _(`TRANSPORT_ERROR`,{url:e},{url:e,cause:n})}};async function C(e,t,n,r){let i=new AbortController,a=oe(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 o?.aborted===!0?e:i.signal.aborted?new _(`REQUEST_TIMEOUT`,{url:t,timeoutMs:r},{url:t,cause:e}):e}finally{a(),o?.removeEventListener(`abort`,s)}}async function w(e){let t=await e.text();return ae(t)??t}function fe(e,t){let n=e.headers;if(n===void 0)return;if(he(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 pe(e){let t=fe(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 me(e,t=`x-block-number`){let n=fe(e,t);if(n===void 0)return;let r=Number(n);return Number.isInteger(r)&&r>=0?r:void 0}function he(e){return`get`in e&&typeof e.get==`function`}const ge=/^[A-Za-z0-9._:-]{1,128}$/u;var T=class extends _{constructor(e,t,n={}){super(e,t,n),this.name=`AppliedTradeError`}};async function _e(e,t,n){let{uniqueKey:r}=t;if(!ge.test(r))throw new T(`INVALID_UNIQUE_KEY`,{uniqueKey:String(r)},{uniqueKey:r});let i=e.httpRequestor??S,a=e.requestTimeoutMs??3e4,c=n?.signal,l=e=>new T(`CONFIRMATION_ABORTED`,{},{uniqueKey:r,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 n,o;try{n=await C(i,u,{method:`GET`,headers:x(e.wire),...c===void 0?{}:{signal:c}},a),o=await w(n)}catch(e){if(s(c,l),f=e,!await d.waitForRead())break;continue}if(s(c,l),n.status===200)return ve(t,n,o,u);if(n.status===404||n.status===429||xe(n.status)){let e=n.status===429?pe(n):void 0;if(!await d.waitForRead(e))break;continue}throw new T(`CONFIRMATION_FAILED`,{status:n.status},{uniqueKey:r,status:n.status,body:o,url:u})}throw new T(`CONFIRMATION_TIMEOUT`,{},{uniqueKey:r,requestTransactionId:t.requestTransactionId,url:u,cause:f})}function ve(e,t,n,r){let{uniqueKey:i}=e,a=Se(n),o=a?.uniqueKey??a?.UniqueKey;if(typeof o==`string`&&o!==i)throw new T(`CONFIRMATION_KEY_MISMATCH`,{},{uniqueKey:i,status:t.status,body:n,url:r});let s=a?.Status,c=fe(t,`x-apply-transaction-id`)??null,l=me(t,`x-apply-block-number`)??null;if(s===0)throw new T(`CHAIN_REJECTED`,{errorKey:b(a,`ErrorKey`)??`CHAIN_ERROR`,serverMessage:b(a,`Message`)??``},{uniqueKey:i,requestTransactionId:e.requestTransactionId,applyTransactionId:c,blockNumber:l,status:t.status,body:n,url:r});if(s!==1)throw ye(e,t,n,r);let u=be(a?.Data);if(u===void 0)throw ye(e,t,n,r);return{uniqueKey:i,transactionId:c,blockNumber:l,requestTransactionId:e.requestTransactionId,result:u}}function ye(e,t,n,r){return new T(`CONFIRMATION_MALFORMED`,{},{uniqueKey:e.uniqueKey,status:t.status,body:n,url:r})}function be(e){let t=Se(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 xe(e){return e===500||e===502||e===503||e===504}function Se(e){return typeof e==`object`&&e?e:void 0}let Ce=/* @__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 we={0:200,500:10,3e3:60,1e4:200},Te=[0,500,3e3,1e4],E=-887272,D=887272,Ee=e.clone({DECIMAL_PLACES:60,ROUNDING_MODE:e.ROUND_DOWN}),O=t.clone({precision:60});function De(t){return new e(new O(1.0001).pow(t/2).toString())}function Oe(e){let t;try{t=new Ee(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(D,Math.max(E,Math.floor(n)));for(;r<887272&&De(r+1).isLessThanOrEqualTo(t);)r+=1;for(;r>-887272&&De(r).isGreaterThan(t);)--r;return r}function ke(t){let n=typeof t==`string`?t:typeof t==`number`||e.isBigNumber(t)?t.toString():`NaN`,r=new O(n);if(!r.isFinite()||r.lessThanOrEqualTo(0)||!Number.isFinite(r.toNumber()))return NaN;let i=r.ln().dividedBy(new O(1.0001).ln()).floor().toNumber();return Number.isFinite(i)?i:NaN}function Ae(e,t){return Me(t),Math.floor(e/t)*t}function je(e,t){return Me(t),Math.ceil(e/t)*t}function k(e,t,n){let r=we[n];if(r===void 0)throw new _(`INVALID_FEE`,{field:`fee`,value:n,allowed:u});if(!Number.isInteger(e)||!Number.isInteger(t))throw new _(`TICKS_NOT_INTEGERS`,{tickLower:e,tickUpper:t});if(e>=t)throw new _(`INVALID_TICK_RANGE`,{tickLower:e,tickUpper:t});if(e<-887272||t>887272)throw new _(`TICKS_OUT_OF_BOUNDS`,{tickLower:e,tickUpper:t,minTick:E,maxTick:D});if(e%r!==0||t%r!==0)throw new _(`TICKS_NOT_ALIGNED`,{tickLower:e,tickUpper:t,spacing:r})}function Me(e){if(!Number.isInteger(e)||e<=0)throw new _(`INVALID_TICK_SPACING`,{value:e})}function Ne(e){if(e.flippedFromRequest!==!0)return{sqrtPrice:e.sqrtPrice,tick:e.tick};let t=new O(1).dividedBy(new O(e.sqrtPrice));if(!t.isFinite()||t.lessThanOrEqualTo(0))throw new _(`INVALID_SQRT_PRICE`,{sqrtPrice:e.sqrtPrice});let n=t.toString();return{sqrtPrice:n,tick:Oe(n)}}function A(t,n,r=!1){if(typeof t==`number`)throw new _(`AMOUNT_IS_JS_NUMBER`,{field:n});let i;try{i=e(t)}catch{i=e(NaN)}if(!i.isFinite())throw new _(`AMOUNT_NOT_FINITE`,{field:n,value:String(t)});if(!r&&i.isZero())throw new _(`AMOUNT_NOT_POSITIVE`,{field:n,value:String(t)});if(i.isNegative())throw new _(`AMOUNT_NEGATIVE`,{field:n,value:String(t)})}function Pe(t,n,r){if([t,n,r].some(e=>typeof e==`number`))throw new _(`PRICE_VALUES_IS_JS_NUMBER`,{});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 _(`INVALID_PRICE_VALUES`,{spotPrice:String(t),lowerPrice:String(n),upperPrice:String(r)});if(o.isGreaterThan(s))throw new _(`INVALID_PRICE_RANGE`,{lowerPrice:String(n),upperPrice:String(r)})}function Fe(e,t){if(e<0||!Number.isInteger(e))throw new _(`INVALID_TOKEN_DECIMALS`,{field:t,value:e})}function Ie(e,t){if(!Number.isInteger(e)||!Number.isInteger(t))throw new _(`TICKS_NOT_INTEGERS`,{tickLower:e,tickUpper:t});if(e>=t)throw new _(`INVALID_TICK_RANGE`,{tickLower:e,tickUpper:t});if(e<-887272||t>887272)throw new _(`TICKS_OUT_OF_BOUNDS`,{tickLower:e,tickUpper:t,minTick:E,maxTick:D})}function j(e){if(!Te.some(t=>Number(t)===e))throw new _(`INVALID_FEE`,{field:`fee`,value:e,allowed:u})}function Le(e){if(!Number.isInteger(e)||e<=0)throw new _(`INVALID_TICK_SPACING`,{value:e})}function Re(e){if(e===void 0)throw new _(`MISSING_WALLET_ADDRESS`,{});if(!e||typeof e!=`string`||e.trim().length===0)throw new _(`INVALID_WALLET_ADDRESS`,{field:`walletAddress`,value:String(e)})}const ze=/* @__PURE__ */ new Set([`Token`,`Unit`,`none`]),Be=/^[A-Za-z0-9]+$/u;function Ve(e){return Be.test(e)&&e.length<=32&&!ze.has(e)}function M(e,t){if(!(e<t))throw new _(`NON_CANONICAL_PAIR`,{token0:e,token1:t})}var He=class{constructor(e,t){this.dexBackendBaseUrl=e,this.httpClient=t}async getUserAssets(e,t=1,n=10){if(Re(e),!Number.isInteger(t)||t<1)throw new _(`INVALID_PAGE`,{value:t});if(!Number.isInteger(n)||n<1||n>100)throw new _(`INVALID_LIMIT`,{value:n,min:1,max:100});return Ue(await this.httpClient.sendGetRequest(this.dexBackendBaseUrl,`/user/assets`,``,{address:e,page:t.toString(),limit:n.toString()}))}};function Ue(e){let t=y(e,`data`),n=t?.token;if(!Array.isArray(n)||!n.every(We))throw new _(`INVALID_CHAIN_RESPONSE`,{resource:`user assets response`},{body:e});let r=t?.count;return{tokens:n.map(e=>({...e,decimals:parseInt(e.decimals,10)})),count:typeof r==`number`?r:0}}function We(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 Ge=[`Swap`,`RequestTrade`,`AddLiquidity`,`RemoveLiquidity`,`CollectPositionFees`,`CreatePool`],Ke=`DryRun`,qe=`galaconnect-operation-`;function Je(e){return typeof e==`string`&&Ge.includes(e)}function Ye(e,t){return Je(t)&&typeof e?.token0==`string`&&typeof e.token1==`string`}function Xe(e){let t={...e};for(let e of[`signature`,`prefix`,`types`,`domain`,`trace`])delete t[e];return t}function Ze(e,t,n,r,i=qe){return e.signObject(Ke,{callerPublicKey:t,method:n,dto:r,uniqueKey:`${i}${globalThis.crypto.randomUUID()}`})}var Qe=class{constructor(e,t){this.signer=t,g(this,`requestor`,void 0),g(this,`baseUrl`,void 0),g(this,`requestTimeoutMs`,void 0),g(this,`wire`,void 0),this.requestor=e.httpRequestor??S,this.baseUrl=e.dexBackendBaseUrl.replace(/\/$/u,``),this.requestTimeoutMs=e.requestTimeoutMs??3e4,this.wire=e.wire}async quote(e,t,n,r={}){if(this.signer===void 0)throw _.noSignerError();let i=r.channel??`asset`,a=r.contract??`dexv3-contract`,o=await Ze(this.signer,e,t,Xe(n)),s=`${this.baseUrl}/wallet/connect/galachain/api/${encodeURIComponent(i)}/${encodeURIComponent(a)}/${encodeURIComponent(t)}/fee`,c,l,u;try{let e=await C(this.requestor,s,{method:`POST`,headers:x(this.wire,{json:!0,defaults:{Accept:`application/json`}}),body:JSON.stringify(o)},this.requestTimeoutMs);c=e.status,l=e.ok,u=l?await w(e):void 0}catch{return null}return l?$e(u):a===`dex-contract`&&(c===403||c===404)?{source:`default`,fees:[{feeInGala:`0`}]}:null}};function $e(e){if(typeof e!=`object`||!e)return null;let t=e.fees;return!Array.isArray(t)||typeof t[0]?.feeInGala!=`string`?null:e}var et=class{constructor(e){g(this,`method`,void 0),g(this,`uniqueKey`,void 0),g(this,`transactionId`,void 0),g(this,`blockNumber`,void 0),g(this,`mode`,void 0),g(this,`status`,void 0),g(this,`result`,void 0),g(this,`envelope`,void 0),g(this,`backendBaseUrl`,void 0),g(this,`requestor`,void 0),g(this,`requestTimeoutMs`,void 0),g(this,`wire`,void 0),g(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.status=e.mode===`queued`?`queued`:`executed`,this.result=e.result,this.envelope=e.envelope,this.backendBaseUrl=e.dexBackendBaseUrl.replace(/\/$/u,``),this.requestor=e.httpRequestor,this.requestTimeoutMs=e.requestTimeoutMs??3e4,this.wire=e.wire,this.positionConfirmation=e.positionConfirmation}async confirm(e){return this.method===`RequestTrade`?this.confirmApplied(e):this.confirmPosition(e)}confirmApplied(e){return _e({dexBackendBaseUrl:this.backendBaseUrl,httpRequestor:this.requestor,requestTimeoutMs:this.requestTimeoutMs,wire:this.wire},{uniqueKey:this.uniqueKey,requestTransactionId:this.transactionId},e)}async confirmPosition(e){if(this.positionConfirmation===void 0)throw _.noWalletAddressError();let t=e?.signal,n=e=>new _(`CONFIRMATION_ABORTED`,{},{uniqueKey:this.uniqueKey,cause:e}),r=o(e,0,n);for(await r.waitForRead();;){let e=new AbortController,i=oe(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 _.confirmationTimeoutError(this.uniqueKey)}},tt=class{constructor(e){g(this,`requestor`,void 0),g(this,`walletAddress`,void 0),g(this,`chainCallTimeoutMs`,void 0),g(this,`requestTimeoutMs`,void 0),g(this,`dexBackendBaseUrl`,void 0),g(this,`wire`,void 0),this.dexBackendBaseUrl=nt(e.dexBackendBaseUrl),this.requestor=e.httpRequestor??S,this.walletAddress=e.walletAddress,this.chainCallTimeoutMs=se(e.chainCallTimeoutMs??3e4,`chainCallTimeoutMs`),this.requestTimeoutMs=this.chainCallTimeoutMs,this.wire=e.wire??{}}async submit(e,t,n){if(e===`Trade`)throw new _(`METHOD_NOT_SUPPORTED`,{method:e});let r=this.writeUrl(e),i=n?.walletAddress??this.walletAddress,a=x(this.wire,{json:!0,fixed:i===void 0?{}:{"X-Wallet-Address":i}}),o=await this.post(r,a,t),s=await w(o);if(!o.ok)throw it(o,s,r);let c=at(s);if(c?.error===!0)throw new _(`GATEWAY_REPORTED_ERROR`,{serverMessage:b(c,`message`)??``},{status:o.status,body:s,url:r});let l=at(c?.data??c?.Data);if(l===void 0)throw new _(`GATEWAY_DATA_MISSING`,{},N(o,s,r));let u=b(l,`transactionId`),d=b(l,`mode`),f=l.transactionId,p=l.blockNumber,m=()=>new _(`GATEWAY_MODE_INVALID`,{},N(o,s,r));if(d!==`sync`&&d!==`queued`||`transactionId`in l&&typeof f!=`string`||p!=null&&!ot(p))throw m();if(e===`RequestTrade`&&d===`sync`)throw new _(`GATEWAY_SYNC_REQUEST_TRADE`,{},N(o,s,r));if(e===`RequestTrade`&&d===`queued`)rt(o,s,r,l,t);else if(d===`queued`||!(`result`in l))throw m();if(d===`sync`){let e=at(l.result);if(e!==void 0){let t=e.Status;if(t!==void 0&&t!==1)throw _.fromChainError(b(e,`ErrorKey`)??`CHAIN_ERROR`,b(e,`Message`)??``,N(o,s,r))}}let h=b(t,`uniqueKey`)??``,ee=fe(o,`x-transaction-id`),te=u===void 0||u===``?ee:u,g=p==null?me(o):ot(p)?p:void 0;return new et({method:e,uniqueKey:h,transactionId:te===void 0||te===``?null:te,blockNumber:g??null,mode:d,result:d===`queued`?void 0:l.result,envelope:s,dexBackendBaseUrl:this.dexBackendBaseUrl,httpRequestor:this.requestor,requestTimeoutMs:this.chainCallTimeoutMs,wire:this.wire,...n?.positionConfirmation===void 0?{}:{positionConfirmation:n.positionConfirmation}})}async submitShadow(e,t,n){if(e===`Trade`)throw new _(`METHOD_NOT_SUPPORTED`,{method:e});let r=n?.walletAddress??this.walletAddress;if(r===void 0)throw new _(`SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS`,{});let i=x(this.wire,{json:!0,fixed:{"X-Wallet-Address":r,"X-Shadow":`true`}}),a=await this.post(this.writeUrl(e),i,t);return{httpStatus:a.status,body:await w(a)}}writeUrl(e){return`${this.dexBackendBaseUrl}/v1/chain/asset/dex-contract/${e}`}async post(e,t,n){try{return await C(this.requestor,e,{method:`POST`,headers:t,body:JSON.stringify(n)},this.chainCallTimeoutMs)}catch(t){throw ie(t,`REQUEST_TIMEOUT`)?new _(`SUBMISSION_OUTCOME_UNKNOWN`,{},{uniqueKey:b(n,`uniqueKey`)??``,url:e,cause:t}):t}}get httpRequestor(){return this.requestor}};function nt(e){return e.replace(/\/$/u,``)}function N(e,t,n){return{status:e.status,body:t,url:n}}function rt(e,t,n,r,i){let a=b(i,`uniqueKey`)??``,o=r.uniqueKey;if(typeof o==`string`&&o!==``&&o===a)return;let s=o==null||o===``,c={...N(e,t,n),uniqueKey:a};throw s?new _(`MISSING_UNIQUE_KEY`,{},c):new _(`UNIQUE_KEY_MISMATCH`,{},c)}function it(e,t,n){let r=at(t),i=y(t,`error`),a=b(r,`code`)??b(i,`code`)??b(i,`ErrorKey`)??`HTTP_ERROR`,o=b(r,`message`)??b(i,`message`)??b(i,`Message`)??``,s=e.status===429?pe(e):void 0;return a===`HTTP_ERROR`?new _(`HTTP_ERROR`,{status:e.status,url:n},N(e,t,n)):_.fromGatewayBounce(a,o,e.status,t,n,s)}function at(e){return typeof e==`object`&&e?e:void 0}function ot(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}const st={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`}},P=n(`GSWAP_SDK`);var ct=class{constructor(e){this.options=e,g(this,`attempts`,0),g(this,`delayMs`,void 0),g(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 lt=`gdex.jsonrpc.v1`,ut=[`add`,`remove`,`collect`];function dt(e){let{pool:t}=e;return(e.version===`v1`||e.version===`v2`)&&typeof t==`object`&&!!t&&typeof e.poolHash==`string`&&typeof e.transactionId==`string`&&ut.includes(e.action)&&typeof e.owner==`string`&&typeof e.amount0==`string`&&typeof e.amount1==`string`&&typeof e.blockNumber==`number`&&typeof e.timestamp==`string`}var F=class extends Error{constructor(e,t,n){super(t),g(this,`code`,void 0),g(this,`data`,void 0),this.name=`GdexStreamError`,this.code=e,n!==void 0&&(this.data=n)}};function ft(e){let t=typeof e==`object`&&e?e.subscriptionId:void 0;if(typeof t!=`string`)throw new F(-32603,`GDEX subscribe response is missing its subscriptionId`);return t}var pt=class{constructor(e={}){g(this,`url`,void 0),g(this,`requestTimeoutMs`,void 0),g(this,`apiKey`,void 0),g(this,`webSocketConstructor`,void 0),g(this,`backoff`,void 0),g(this,`socket`,void 0),g(this,`connectPromise`,void 0),g(this,`nextRequestId`,0),g(this,`pending`,/* @__PURE__ */ new Map),g(this,`subscriptionsByServerId`,/* @__PURE__ */ new Map),g(this,`activeSubscriptions`,/* @__PURE__ */ new Set),g(this,`intentionalClose`,!1),g(this,`reconnecting`,!1),g(this,`reconnectTimer`,void 0),g(this,`reconnectDelayResolve`,void 0),this.url=e.url??st.prod.dexBackendWsUrl,this.requestTimeoutMs=e.requestTimeoutMs??15e3,this.backoff=new ct({maxAttempts:e.reconnectAttempts??5,baseDelayMs:e.reconnectDelayMs??2e3});let t=e.webSocketImpl??globalThis.WebSocket;if(typeof t!=`function`)throw new _(`STREAM_WEBSOCKET_UNAVAILABLE`,{});if(this.webSocketConstructor=t,e.apiKey!==void 0){if(e.apiKey===``||e.webSocketImpl===void 0)throw new _(`STREAM_API_KEY_UNUSABLE`,{});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(new _(`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(new _(`STREAM_NOT_CONNECTED`,{}));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(new _(`STREAM_REQUEST_TIMEOUT`,{method:e,timeoutMs:this.requestTimeoutMs}))},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=>{dt(t)?e(t):P(`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,lt):new this.webSocketConstructor(this.url,lt,{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(),P(`Connected to GDEX stream`),e())},r.onmessage=e=>this.handleMessage(e.data),r.onerror=()=>{n||t(new _(`STREAM_CONNECT_FAILED`,{url:this.url}))},r.onclose=e=>{this.socket===r&&(this.socket=void 0,this.connectPromise=void 0,n||t(new _(`STREAM_CLOSED_BEFORE_CONNECT`,{closeCode:e.code??0})),this.rejectPending(new _(`STREAM_CONNECTION_CLOSED`,{closeCode:e.code??0})),!this.intentionalClose&&!this.reconnecting&&this.startReconnectLoop())}})}handleMessage(e){if(typeof e!=`string`){P(`Ignoring non-text GDEX WebSocket frame`);return}let t;try{t=JSON.parse(e)}catch{P(`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 F(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){P(`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=ft(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(),P(`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){P(`GDEX reconnect failed: ${e instanceof Error?e.message:String(e)}`)}}this.reconnecting=!1,this.intentionalClose||P(`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=ft(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 F)||e.code!==-32003||n>=5)throw e;let t=this.readRetryAfterMs(e.data);P(`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)}},I=class{constructor(e=S,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}`;P(`Sending request to ${o} with body:`,i);let s=!!i,c=await C(this.httpRequestor,o,{method:e,headers:x(this.wire,{json:s}),...s?{body:JSON.stringify(i)}:{},...a?.signal===void 0?{}:{signal:a.signal}},this.timeoutMs);if(!c.ok)throw await _.fromErrorResponse(o,c);let l=await w(c);return P(`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}?${de(r,this.wire.queryEncoding)}`:n;return this.sendRequest(`GET`,e,t,a,void 0,i)}};function mt(e){return{ok:!0,value:e}}function L(e){return{ok:!1,reason:e}}function ht(e,t,n,r){if(!Array.isArray(t))throw new _(`INVALID_CHAIN_RESPONSE`,{resource:`${e} list`},{body: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 gt(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function _t(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 R(e,t){return e<t?[e,t]:[t,e]}function vt(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 _(`UNORDERABLE_SYMBOLS`,{received:Array.isArray(e)?`array`:e===null?`null`:typeof e})}function z(e){return[e.collection,e.category,e.type,e.additionalKey].join(`$`)}function B(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 _(`INVALID_TOKEN_CLASS_KEY`,{tokenClassKey:e});let[a,o,s]=r;return{collection:i,category:a,type:o,additionalKey:s}}var yt=class{constructor(e,t={}){this.gateway=e,this.options=t,g(this,`cachedSymbols`,void 0),g(this,`cachedAt`,0),g(this,`refreshInFlight`,void 0),g(this,`http`,void 0),this.http=new I(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=>ht(`symbols`,e.data,bt,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`?xt(e)?z(B(e)):void 0:z(e),r=t.find(t=>t.symbol===e||n!==void 0&&z(t)===n);if(r===void 0){t=await this.refresh();let r=t.find(t=>t.symbol===e||n!==void 0&&z(t)===n);if(r===void 0)throw _.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=z(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(Ve(t))return t;throw new _(`NO_VALID_TRADING_SYMBOL`,{classKey:i,displaySymbol:t})}async orderPair(e,t){let[n,r]=await Promise.all([this.resolve(e),this.resolve(t)]),[i,a]=R(n.symbol,r.symbol);return{token0:i===n.symbol?n:r,token1:a===r.symbol?r:n,flipped:i!==n.symbol}}};function bt(e){let t=gt(e);if(t===void 0)return L(`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?L(`symbol is empty`):typeof r==`string`?typeof i==`string`?typeof a==`string`?typeof o==`string`?typeof s!=`number`||!Number.isInteger(s)||s<0?L(`decimals is not a non-negative integer`):mt({symbol:n,collection:r,category:i,type:a,additionalKey:o,decimals:s}):L(`additionalKey is not a string`):L(`type is not a string`):L(`category is not a string`):L(`collection is not a string`):L(`symbol is not a string`)}function xt(e){return e.includes(`|`)||e.includes(`$`)}function V(e){return typeof e==`string`?e:z(e)}async function H(e,t){let n=await e.resolve(t);if(n.symbol.length>0)return n.symbol;throw new _(`SYMBOL_NOT_FOUND`,{token:V(t)})}async function U(e,t){return e.passthrough===!0?V(t):H(e,t)}var St=class{constructor(){g(this,`passthrough`,!0)}resolve(e){return typeof e==`string`&&!xt(e)?Promise.resolve({symbol:e,collection:``,category:``,type:``,additionalKey:``,decimals:0}):Promise.reject(_.unknownTokenError(e))}async orderPair(e,t){let[n,r]=await Promise.all([this.resolve(e),this.resolve(t)]),[i]=R(n.symbol,r.symbol),a=i!==n.symbol;return{token0:a?r:n,token1:a?n:r,flipped:a}}invalidate(){}},Ct=class{constructor(e,t,n={}){this.gateway=e,this.symbols=t,this.options=n,g(this,`http`,void 0),this.http=new I(e.httpRequestor,e.requestTimeoutMs??3e4,e.wire)}async getPools(e){return ht(`pools`,(await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,`/pools`,Et(e),e?.signal===void 0?void 0:{signal:e.signal})).data,At,e?.onInvalidEntry??this.options.onInvalidEntry)}async getPool(e,t,n){return j(n),this.getBackend(`/pool`,await this.backendParams(e,t,n))}async getSlot0(e,t,n){return j(n),this.getBackend(`/slot0`,await this.backendParams(e,t,n))}async getCompositePool(e,t,n){if(j(n),this.symbols.passthrough===!0)return this.getBackend(`/composite-pool`,{token0:V(e),token1:V(t),fee:String(n)});let r=vt(R(await H(this.symbols,e),await H(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 U(this.symbols,e),token1:await U(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 _?e:new _(`REQUEST_FAILED`,{operation:`pool`},{cause:e})}}};const wt=[`tvl`,`volume1d`,`volume30d`],Tt=1e3;function Et(e){if(e===void 0)return;let t={};if(e.search!==void 0){if(e.search.length>64)throw new _(`SEARCH_TOO_LONG`,{length:e.search.length,maxLength:64});t.search=e.search}if(e.sortBy!==void 0){if(!wt.includes(e.sortBy))throw new _(`INVALID_SORT_BY`,{value:String(e.sortBy),allowed:wt.join(`,`)});t.sortBy=e.sortBy}if(e.sortOrder!==void 0){if(e.sortOrder!==`asc`&&e.sortOrder!==`desc`)throw new _(`INVALID_SORT_ORDER`,{value:String(e.sortOrder)});t.sortOrder=e.sortOrder}if(e.page!==void 0){if(!Number.isInteger(e.page)||e.page<1)throw new _(`INVALID_PAGE`,{value:e.page});t.page=String(e.page)}if(e.limit!==void 0){if(!Number.isInteger(e.limit)||e.limit<1||e.limit>Tt)throw new _(`INVALID_LIMIT`,{value:e.limit,min:1,max:Tt});t.limit=String(e.limit)}return Object.keys(t).length===0?void 0:t}const Dt=[`poolName`,`token0CompositeKey`,`token1CompositeKey`,`token0Image`,`token1Image`,`creator`,`price`,`sqrtPrice`,`token0Tvl`,`token1Tvl`],Ot=[`tickSpacing`,`protocolFees`,`tradingFees`,`tick`,`volume1d`,`volume7d`,`volume30d`,`trades1d`,`fee24h`,`token0Price`,`token1Price`],kt=[`fee`,`tvlUsd`,`apr1d`];function At(e){let t=gt(e);if(t===void 0)return L(`the row is not an object`);for(let e of[`token0`,`token1`,`poolRef`])if(typeof t[e]!=`string`)return L(`${e} is not a string`);if(t.contractVersion!==void 0&&t.contractVersion!==`v2`)return L(`contractVersion is not v2`);let n={...t};for(let e of kt){let r=t[e];if(r===void 0&&e!==`fee`)continue;let i=_t(r);if(i===void 0)return L(`${e} is not a number`);n[e]=i}for(let e of Dt)if(t[e]!==void 0&&typeof t[e]!=`string`)return L(`${e} is not a string`);for(let e of Ot){let n=t[e];if(n!==void 0&&(typeof n!=`number`||!Number.isFinite(n)))return L(`${e} is not a number`)}return mt(n)}const jt=`galaswap-operation-`,Mt=/^[A-Za-z0-9._:-]*$/u;function Nt(e){if(e===void 0)return jt;if(!Mt.test(e)||e.length>92)throw new _(`INVALID_UNIQUE_KEY_PREFIX`,{uniqueKeyPrefix:e,maxLength:92});return e}const Pt=/^[A-Za-z0-9._:-]{1,128}$/u;function W(e){if(typeof e!=`string`||!Pt.test(e))throw new _(`INVALID_UNIQUE_KEY`,{uniqueKey:String(e)})}function Ft(e){return`${e}${globalThis.crypto.randomUUID()}`}const G=t=>new e(t).toFixed();function K(e){j(e.fee),M(e.token0,e.token1),W(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 _(`EXACT_AMOUNT_REQUIRED`,{field:`exactIn`});A(n,`exactIn`),t[e.tokenInIsToken0?`sell0Qty`:`sell1Qty`]=G(n),e.amountOutMinimum!==void 0&&(A(e.amountOutMinimum,`amountOutMinimum`,!0),t.amountOutMinimum=G(e.amountOutMinimum))}else{let n=e.exactOut;if(n===void 0)throw new _(`EXACT_AMOUNT_REQUIRED`,{field:`exactOut`});A(n,`exactOut`),t[e.tokenInIsToken0?`buy1Qty`:`buy0Qty`]=G(n),e.amountInMaximum!==void 0&&(A(e.amountInMaximum,`amountInMaximum`,!0),t.amountInMaximum=G(e.amountInMaximum))}return e.priceLimit!==void 0&&(A(e.priceLimit,`priceLimit`),t.priceLimit=G(e.priceLimit)),t}function It(e){j(e.fee),M(e.token0,e.token1),k(e.tickLower,e.tickUpper,e.fee),W(e.uniqueKey)}function q(e){It(e);let t=Vt(e.depositQuantityToken0,e.depositQuantityToken1,`depositQuantityToken0`,`depositQuantityToken1`);if(t===void 0)throw new _(`EXACTLY_ONE_OF_REQUIRED`,{first:`depositQuantityToken0`,second:`depositQuantityToken1`});return A(t.amount,t.name),{token0:e.token0,token1:e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,uniqueKey:e.uniqueKey,[t.name]:G(t.amount)}}function Lt(e){It(e);let t=Vt(e.withdrawalQuantityToken0,e.withdrawalQuantityToken1,`withdrawalQuantityToken0`,`withdrawalQuantityToken1`,!0);return t!==void 0&&A(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]:G(t.amount)}}}function Rt(e){return It(e),{token0:e.token0,token1:e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,uniqueKey:e.uniqueKey}}function zt(t){j(t.fee),W(t.uniqueKey),M(t.token0Symbol,t.token1Symbol);for(let e of[t.token0Symbol,t.token1Symbol])if(!Ve(e))throw new _(`INVALID_TRADING_SYMBOL`,{symbol:e});for(let e of[t.token0Key,t.token1Key])Bt(e);let n=Vt(t.startingPrice,t.startingSqrtPrice,`startingPrice`,`startingSqrtPrice`);if(n===void 0)throw new _(`EXACTLY_ONE_OF_REQUIRED`,{first:`startingPrice`,second:`startingSqrtPrice`});if(typeof n.amount==`number`)throw new _(`AMOUNT_IS_JS_NUMBER`,{field:n.name});let r=new e(n.amount);if(!r.isFinite()||r.isLessThanOrEqualTo(0))throw new _(`INVALID_STARTING_PRICE`,{value:String(n.amount)});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 Bt(e){for(let t of[`collection`,`category`,`type`,`additionalKey`])if(typeof e[t]!=`string`||e[t].length===0)throw new _(`INCOMPLETE_TOKEN_CLASS_KEY`,{compositeKey:[e.collection,e.category,e.type,e.additionalKey].join(`$`),part:t})}function Vt(e,t,n,r,i=!1){if(e!==void 0&&t!==void 0)throw i?new _(`AT_MOST_ONE_OF_ALLOWED`,{first:n,second:r}):new _(`EXACTLY_ONE_OF_REQUIRED`,{first:n,second:r});if(e!==void 0)return{name:n,amount:e};if(t!==void 0)return{name:r,amount:t}}function J(e,t,n){return new _(`INVALID_DTO`,{method:e,field:t,expected:n})}function Ht(e,t){let n=n=>{let r=t[n];if(typeof r!=`string`)throw J(e,n,`string`);return r},r=n=>{let r=t[n];if(typeof r!=`number`)throw J(e,n,`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 J(e,n,`class_key`);let i=r,a=t=>{if(typeof i[t]!=`string`)throw J(e,`${n}.${t}`,`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 J(e,`sell0Qty|sell1Qty|buy0Qty|buy1Qty`,`exactly_once`);let c=a===`sell0Qty`||a===`buy1Qty`,l={...o(),uniqueKey:s,tokenInIsToken0:c},u=i(`priceLimit`);return a.startsWith(`sell`)?K({...l,exactIn:n(a),amountOutMinimum:i(`amountOutMinimum`),priceLimit:u}):K({...l,exactOut:n(a),amountInMaximum:i(`amountInMaximum`),priceLimit:u})}case`AddLiquidity`:{let e=i(`depositQuantityToken0`),t=i(`depositQuantityToken1`);return q({...c(),...e===void 0?{depositQuantityToken1:t}:{depositQuantityToken0:e}})}case`RemoveLiquidity`:return Lt({...c(),withdrawalQuantityToken0:i(`withdrawalQuantityToken0`),withdrawalQuantityToken1:i(`withdrawalQuantityToken1`)});case`CollectPositionFees`:return Rt(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 J(e,`privateAccess`,`string_array`);if(t.isPrivate!==void 0&&typeof t.isPrivate!=`boolean`)throw J(e,`isPrivate`,`boolean`);return zt({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 Y(e,t){let n=Ht(e,t);if(JSON.stringify(n)!==JSON.stringify(t))throw new _(`DTO_NOT_CANONICAL`,{method:e})}function Ut(e){return{token0:e.token0,token1:e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper}}var Wt=class{constructor(e,t,n,r,i={}){this.gateway=e,this.symbols=t,this.signer=n,this.walletAddress=r,g(this,`http`,void 0),g(this,`uniqueKeyPrefix`,void 0),g(this,`onInvalidEntry`,void 0),this.http=new I(e.httpRequestor,e.requestTimeoutMs??3e4,e.wire),this.uniqueKeyPrefix=Nt(i.uniqueKeyPrefix),this.onInvalidEntry=i.onInvalidEntry}async getUserPositions(e){return ht(`positions`,(await this.get(`/positions`,{user:e})).data,Jt,this.onInvalidEntry)}async getPosition(e,t){let n=await this.getNullable(`/position`,await this.positionParams(e),t);return n===null?null:Yt(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 _?e:new _(`REQUEST_FAILED`,{operation:`position`},{cause:e})}}}async positionParams(e){if(this.symbols.passthrough===!0)return{token0:V(e.token0),token1:V(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 A(t.amount,`amount`),(await this.get(`/add-liq-estimate`,{token0:V(t.token0),token1:V(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 A(t.liquidity,`liquidity`),(await this.get(`/remove-liq-estimate`,{token0:V(t.token0),token1:V(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){j(e.fee);let t=await this.symbols.orderPair(e.token0,e.token1),n=this.canonicalTicks(e.tickLower,e.tickUpper,t.flipped);k(n.tickLower,n.tickUpper,e.fee),A(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?q({...r,depositQuantityToken1:e.amount}):q({...r,depositQuantityToken0:e.amount})}async submitAddLiquidity(e){return Y(`AddLiquidity`,e),this.submit(`AddLiquidity`,e,{kind:`add`,identity:Ut(e)})}async addLiquidityByPrice(t){j(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 _(`INVALID_PRICE_BOUNDS`,{minPrice:String(t.minPrice),maxPrice:String(t.maxPrice)});if(n.isGreaterThan(r))throw new _(`PRICE_BOUNDS_ORDER`,{minPrice:String(t.minPrice),maxPrice:String(t.maxPrice)});let i=this.tickSpacing(t.fee),a=Ae(ke(n),i),o=je(ke(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){j(e.fee);let t=await this.symbols.orderPair(e.token0,e.token1),n=this.canonicalTicks(e.tickLower,e.tickUpper,t.flipped);if(k(n.tickLower,n.tickUpper,e.fee),e.amount0!==void 0&&e.amount1!==void 0)throw new _(`AT_MOST_ONE_OF_ALLOWED`,{first:`amount0`,second:`amount1`});e.amount0!==void 0&&A(e.amount0,`amount0`),e.amount1!==void 0&&A(e.amount1,`amount1`);let[r,i]=t.flipped?[e.amount1,e.amount0]:[e.amount0,e.amount1];return Lt({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){Y(`RemoveLiquidity`,e);let t=e.withdrawalQuantityToken0===void 0&&e.withdrawalQuantityToken1===void 0;return this.submit(`RemoveLiquidity`,e,{kind:t?`removeFull`:`removePartial`,identity:Ut(e)})}async collectPositionFees(e){return this.submitCollectPositionFees(await this.buildCollectPositionFees(e))}async buildCollectPositionFees(e){j(e.fee);let t=await this.symbols.orderPair(e.token0,e.token1),n=this.canonicalTicks(e.tickLower,e.tickUpper,t.flipped);return k(n.tickLower,n.tickUpper,e.fee),Rt({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 Y(`CollectPositionFees`,e),this.submit(`CollectPositionFees`,e,{kind:`collect`,identity:Ut(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 _(`EXACTLY_ONE_OF_REQUIRED`,{first:`startingPrice`,second:`startingSqrtPrice`});j(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 _(`INVALID_STARTING_PRICE`,{value:String(c)});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 zt(n?{...d,startingPrice:u}:{...d,startingSqrtPrice:u})}async submitCreatePool(e){Y(`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 _.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 _&&e.status===404}canonicalTicks(e,t,n){return n?{tickLower:-t,tickUpper:-e}:{tickLower:e,tickUpper:t}}tickSpacing(e){let t=we[e];if(t===void 0)throw new _(`INVALID_FEE`,{field:`fee`,value:e,allowed:u});return t}rejectNumber(e,t){if(typeof e==`number`)throw new _(`AMOUNT_IS_JS_NUMBER`,{field:t})}uniqueKeyFor(e){return e===void 0?Ft(this.uniqueKeyPrefix):(W(e),e)}async resolveCreateToken(e,t){try{let n=typeof e==`object`?z(e):e,r=await this.symbols.resolve(n);if(t!==void 0&&t!==``&&t!==r.symbol)throw new _(`SYMBOL_DISAGREES_WITH_REGISTRY`,{token:V(e),suppliedSymbol:t,registeredSymbol:r.symbol});let i=this.tryParseClassKey(e);if(i===void 0&&r.collection===``)throw new _(`CREATE_POOL_NEEDS_CLASS_KEY`,{token:V(e)});return{symbol:r.symbol,classKey:i??B({collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey})}}catch(n){if(!(n instanceof _)||n.code!==`UNKNOWN_TOKEN`)throw n;let r;try{r=B(e)}catch{throw n}if(t===void 0||t===``)throw new _(`TOKEN_SYMBOL_NOT_REGISTERED`,{token:V(e)});if(!Ve(t))throw new _(`INVALID_TRADING_SYMBOL`,{symbol:t});return{symbol:t,classKey:r}}}tryParseClassKey(e){try{return B(e)}catch{return}}};const Gt=[`token0Symbol`,`token1Symbol`,`owner`,`liquidity`,`amount0`,`amount1`],Kt=[`fee`,`tickLower`,`tickUpper`],qt=[`token0CompositeKey`,`token1CompositeKey`,`token0Image`,`token1Image`,`sqrtPrice`,`fees0`,`fees1`];function Jt(e){let t=gt(e);if(t===void 0)return L(`the row is not an object`);for(let e of Gt)if(typeof t[e]!=`string`)return L(`${e} is not a string`);for(let e of Kt){let n=t[e];if(typeof n!=`number`||!Number.isFinite(n))return L(`${e} is not a number`)}if(typeof t.inRange!=`boolean`)return L(`inRange is not a boolean`);for(let e of qt)if(t[e]!==void 0&&typeof t[e]!=`string`)return L(`${e} is not a string`);let n=t.currentTick;if(n!==void 0&&(typeof n!=`number`||!Number.isFinite(n)))return L(`currentTick is not a number`);let r=t.poolRef??t.pool??``;if(typeof r!=`string`)return L(`pool is not a string`);let i=Object.fromEntries([...qt,`currentTick`].flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]));return mt({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 Yt(e){let t=Jt(e);if(t.ok)return t.value;throw new _(`INVALID_POSITION_RESPONSE`,{reason:t.reason},{body:e})}function Xt(e){let t=e.params.serverMessage;if(typeof t==`string`&&t!==``)return t;let n=e.body;return b(n,`message`)??b(n,`Message`)??b(y(n,`error`),`Message`)}var Zt=class{constructor(e,t){this.gateway=e,this.symbols=t,g(this,`http`,void 0),this.http=new I(e.httpRequestor,e.requestTimeoutMs??3e4,e.wire)}async quoteExactInput(e,t,n,r){return A(n,`amountIn`),this.quote(e,t,{amountIn:sn(n)},r)}async quoteExactOutput(e,t,n,r){return A(n,`amountOut`),this.quote(e,t,{amountOut:sn(n)},r)}async quote(e,t,n,r){on(r);let i={tokenIn:await U(this.symbols,e),tokenOut:await U(this.symbols,t),...n};r!==void 0&&(i.fee=String(r));try{return Qt((await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,`/quote`,i)).data)}catch(n){throw an(n,e,t,r)}}};function Qt(t){if(!tn(t))throw new _(`INVALID_CHAIN_RESPONSE`,{resource:`quote`},{body:t});let n=t,r=n.currentPrice===void 0?en(n.currentSqrtPrice,n.tokenInIsToken0):new e(n.currentPrice),i=n.newPrice===void 0?en(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 $t=e.clone({DECIMAL_PLACES:60});function en(e,t){let n=new $t(e).pow(2);return t?n:new $t(1).dividedBy(n)}function tn(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`&&nn(t.currentSqrtPrice)&&nn(t.newSqrtPrice)&&nn(t.currentPrice)&&nn(t.newPrice)&&(t.currentSqrtPrice!==void 0||t.currentPrice!==void 0)&&(t.newSqrtPrice!==void 0||t.newPrice!==void 0)}function nn(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 rn=/no pool|no pools|pool does not exist|has no trading symbol on the new DEX contract/iu;function an(e,t,n,r){if(ie(e)){let i=Xt(e)??``;return e.status===404||rn.test(i)?_.noPoolAvailableError(t,n,r,e):e.status===400&&/insufficient liquidity/iu.test(i)?_.insufficientLiquidityError(t,n,r,e):e}return new _(`REQUEST_FAILED`,{operation:`quote`},{cause:e})}function on(e){if(e!==void 0&&!Te.some(t=>Number(t)===Number(e)))throw new _(`INVALID_FEE`,{field:`fee`,value:Number(e),allowed:u})}function sn(t){return new e(t).toFixed()}function cn(e){return e===503?`unavailable`:e===400?`disabled`:`unknown`}function ln(e,t){return t===`SHADOW_UNAVAILABLE`?`unavailable`:t===`SHADOW_RELAY_REJECTED`?`rejected`:t===`SHADOW_DISABLED`||t===`SHADOW_UNSUPPORTED_TYPE`?`disabled`:cn(e)}function un(e,t,n){let{httpStatus:r,body:i}=n,a=dn(i);if(r>=200&&r<300&&a?.error===!1){let n=dn(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 _(`SHADOW_NOT_QUEUED`,{},{status:r,body:i,...typeof e==`string`?{uniqueKey:e}:{}});return{ok:!0,bundleId:o??``,queued:{uniqueKey:e,requestTransactionId:o??null}}}if(n?.mode===`sync`)return{ok:!0,bundleId:o??``}}let o=ln(r,b(i,`code`));return o===`rejected`?{ok:!1,kind:`rejected`,retryable:!1,message:b(i,`message`)??``}:o===`unavailable`?{ok:!1,kind:o,retryable:!0}:{ok:!1,kind:o,retryable:!1}}function dn(e){return typeof e==`object`&&e?e:void 0}function fn(e){j(e.fee),M(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 pn=class{constructor(e,t,n,r,i={}){this.gateway=e,this.symbols=t,this.signer=n,this.walletAddress=r,g(this,`uniqueKeyPrefix`,void 0),this.uniqueKeyPrefix=Nt(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){j(n);let a=i?.uniqueKey??Ft(this.uniqueKeyPrefix);W(a);let o=await H(this.symbols,e),s=await H(this.symbols,t),c=this.orientPool(o,s,i?.pool);return K({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 un(`RequestTrade`,t,await this.gateway.submitShadow(`RequestTrade`,t,this.submitOptions()))}submitOptions(){return this.walletAddress===void 0?{}:{walletAddress:this.walletAddress}}async signRequestTrade(e){if(Y(`RequestTrade`,e),this.signer===void 0)throw _.noSignerError();return this.signer.signObject(`RequestTrade`,e)}orientPool(e,t,n){if(n===void 0)return vt(R(e,t));if(!(e===n.token0&&t===n.token1||e===n.token1&&t===n.token0))throw new _(`POOL_MISMATCH`,{tokenIn:e,tokenOut:t,poolToken0:n.token0,poolToken1:n.token1});return{token0:n.token0,token1:n.token1}}async confirmSwap(e,t){return W(e),new et({method:`RequestTrade`,uniqueKey:e,transactionId:null,mode:`queued`,result:void 0,dexBackendBaseUrl:this.gateway.dexBackendBaseUrl,httpRequestor:this.gateway.httpRequestor,requestTimeoutMs:this.gateway.requestTimeoutMs,wire:this.gateway.wire}).confirm({initialDelayMs:0,...t})}},mn=class{constructor(e){g(this,`dexBackendBaseUrl`,void 0),g(this,`chainCallTimeoutMs`,void 0),g(this,`signer`,void 0),g(this,`walletAddress`,void 0),g(this,`gateway`,void 0),g(this,`symbols`,void 0),g(this,`quoting`,void 0),g(this,`pools`,void 0),g(this,`positions`,void 0),g(this,`swaps`,void 0),g(this,`assets`,void 0),g(this,`fees`,void 0),g(this,`dexBackendWsUrl`,void 0),g(this,`webSocketImpl`,void 0),g(this,`streamApiKey`,void 0),g(this,`streamClient`,void 0);let t=st[e?.env??`prod`];this.dexBackendBaseUrl=hn(e?.dexBackendBaseUrl??t.dexBackendBaseUrl),this.chainCallTimeoutMs=e?.chainCallTimeoutMs??3e4,this.signer=e?.signer,this.walletAddress=e?.walletAddress;let n=new I(e?.httpRequestor,this.chainCallTimeoutMs,e?.wire);this.gateway=new tt({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 yt(this.gateway,r);let i=e?.symbolResolution===`canonical`?new St:this.symbols;this.quoting=new Zt(this.gateway,i),this.pools=new Ct(this.gateway,i,r);let a={uniqueKeyPrefix:e?.uniqueKeyPrefix,...r};this.positions=new Wt(this.gateway,i,this.signer,this.walletAddress,a),this.swaps=new pn(this.gateway,i,this.signer,this.walletAddress,a),this.assets=new He(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 pt({url:this.dexBackendWsUrl,...this.webSocketImpl===void 0?{}:{webSocketImpl:this.webSocketImpl},...this.streamApiKey===void 0?{}:{apiKey:this.streamApiKey}})),this.streamClient}};function hn(e){return e.replace(/\/$/u,``)}const gn=`pendingSwaps.v1`,_n=6048e5;var vn=class{constructor(e,t={}){this.storage=e,g(this,`storageKey`,void 0),g(this,`darkFlagField`,void 0),g(this,`insertAt`,void 0),g(this,`listOrder`,void 0),g(this,`now`,void 0),g(this,`queue`,Promise.resolve()),g(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 yn(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
|
|
4
|
-
`;function
|
|
5
|
-
`)&&ir.test(e.slice(26))}const or=[`signature`,`multisig`,`trace`,`types`,`domain`,`stringsInstructions`];function X(e,t){throw new m(e,`INVALID_PERSONAL_SIGN_DTO`,{type:t})}function sr(e){let t;try{t=JSON.parse(e)}catch{return X(`Personal-sign DTO is not valid JSON`,`NOT_JSON`)}if(typeof t!=`object`||!t||Array.isArray(t))return X(`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`||!ar(r))return X(`Personal-sign DTO prefix is not an EIP-191 "Ethereum Signed Message" header`,`BAD_PREFIX`);let a=or.filter(e=>Object.prototype.hasOwnProperty.call(i,e));return a.length>0?X(`Personal-sign DTO carries signing-envelope field(s): ${a.join(`, `)}`,`ENVELOPE_FIELDS`):Y(n)===e?{prefix:r,message:Y(i)}:X(`Personal-sign DTO is not in canonical serialized form`,`NOT_CANONICAL`)}function cr(e,t){let{prefix:n,message:r}=sr(t);return rr(e,n,r)}function lr(e,t){let n={...t};return delete n.signature,{signature:nr(e,Y(n)),...n}}function ur(e){let t={};for(let n of Object.keys(e))n!==`EIP712Domain`&&(t[n]=e[n]);return t}function dr(e){let t=t=>{let n=e?.[t];return typeof n==`string`?n:``};return`${t(`collection`)}$${t(`category`)}$${t(`type`)}$${t(`additionalKey`)}`}function fr(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 pr=new TextEncoder,mr=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,hr=/^([A-Za-z_$][A-Za-z0-9_$]*)((?:\[(?:0|[1-9][0-9]*)?\])*)$/u,gr=/^-?[0-9]+$/u,_r=/^-?0x[0-9a-fA-F]+$/u,vr=(1n<<256n)-1n,yr=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`},{name:`salt`,type:`bytes32`}];function Z(e,t){throw new m(`Invalid typed data: ${e}`,`INVALID_TYPED_DATA`,t)}function Q(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 br(e){let t=/* @__PURE__ */ new Uint8Array(32),n=e<0n?e+(1n<<256n):e;if(n<0n||n>vr)return Z(`integer does not fit in 256 bits`);for(let e=31;e>=0;--e)t[e]=Number(n&255n),n>>=8n;return t}function xr(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 Sr(e,t){return e instanceof Uint8Array?e:typeof e==`string`&&/^0x(?:[0-9a-fA-F]{2})*$/u.test(e)?xr(e):Z(`${t} must be an even-length 0x hex string`)}function Cr(e,t){if(typeof e==`bigint`)return e;if(typeof e==`number`)return Number.isSafeInteger(e)?BigInt(e):Z(`${t} must be a safe integer`);if(typeof e==`string`){if(gr.test(e))return BigInt(e);if(_r.test(e))return e.startsWith(`-`)?-BigInt(e.slice(1)):BigInt(e)}return Z(`${t} must be an integer`)}function wr(e,t){if(typeof e!=`string`)return Z(`${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 Z(`${t} has an unpaired surrogate`);n+=1}else if(r>=56320&&r<=57343)return Z(`${t} has an unpaired surrogate`)}return pr.encode(e)}function Tr(e){if(typeof e!=`string`||!/^0x[0-9a-fA-F]{40}$/u.test(e))return Z(`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(pr.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 Z(`address has a bad checksum`)}}return xr(e)}function Er(e){if(e===`string`)return e=>i(wr(e,`string`));if(e===`bytes`)return e=>i(Sr(e,`bytes`));if(e===`bool`)return e=>typeof e==`boolean`?br(e?1n:0n):Z(`bool must be a boolean`);if(e===`address`)return e=>Q([/* @__PURE__ */ new Uint8Array(12),Tr(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=Sr(t,e);return r.length===n?Q([r,new Uint8Array(32-n)]):Z(`${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=Cr(t,e);return n<i||n>a?Z(`value out of bounds for ${e}`):br(n)}}}function Dr(e){let t=hr.exec(e);if(t===null)return Z(`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 Or(e,t){if(!Array.isArray(t))return Z(`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 Z(`type ${e} has a field without a string name and type`);if(!mr.test(r.name))return Z(`invalid field name "${r.name}"`);if(n.has(r.name))return Z(`duplicate field "${r.name}" in ${e}`);n.add(r.name);let i=Dr(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 kr(e){let t=Object.keys(e),n=/* @__PURE__ */ new Map;for(let r of t){if(!mr.test(r))return Z(`invalid type name "${r}"`);n.set(r,Or(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}=Dr(i.type);if(t===e)return Z(`circular type reference in ${e}`);if(Er(t)===void 0){if(!n.has(t))return Z(`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 Z(`missing primary type`);if(o.length>1)return Z(`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 Z(`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(pr.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?Z(`array length mismatch`):i(Q(t.map(t=>m(e,t,n+1)))):Z(`${e.base} array value must be an array`);let a=Er(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 Z(`unknown type "${e}"`);if(typeof t!=`object`||!t||Array.isArray(t))return Z(`${e} value must be an object`);let o=t,s=r.map(t=>Object.prototype.hasOwnProperty.call(o,t.name)?m(Dr(t.type),o[t.name],0):Z(`${e} value is missing field "${t.name}"`));return i(Q([a,...s]))}return{primaryType:s,hashStruct:h}}function Ar(e){if(typeof e!=`object`||!e||Array.isArray(e))return Z(`domain must be an object`);for(let t of Object.keys(e))if(!yr.some(e=>e.name===t))return Z(`invalid typed-data domain key ${JSON.stringify(t)}`);return kr({EIP712Domain:yr.filter(t=>Object.prototype.hasOwnProperty.call(e,t.name))}).hashStruct(`EIP712Domain`,e)}function jr(e){let t=Ar(e.domain),n=kr(e.types),r=n.hashStruct(n.primaryType,e.message);return i(Q([Uint8Array.of(25,1),t,r]))}async function Mr(e,t){let n=jr(t);return tr(e,e=>`0x${Pn(e,n)}`)}function Nr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pr(e){return Nr(e)&&typeof e.status==`number`}function Fr(e,t){if(!Nr(e))return null;let n=e.get;if(typeof n==`function`){let r=n.call(e,t);return typeof r==`string`?r:null}let r=Object.entries(e).find(([e])=>e.toLowerCase()===t.toLowerCase());return typeof r?.[1]==`string`?r[1]:null}function Ir(e,t){if(!Pr(e))throw new m(`The request failed before the server answered.`,`TRANSPORT_ERROR`,{url:t});let{status:n,data:r,headers:i}=e;return{ok:n>=200&&n<300,status:n,json:()=>Promise.resolve(r),text:()=>Promise.resolve(typeof r==`string`?r:JSON.stringify(r)),headers:{get:e=>Fr(i,e)}}}function Lr(e,t){let n=new Set(t.map(e=>e.toLowerCase())),r=e?.headers,i=r===void 0?[]:r instanceof Headers?[...r.entries()]:Array.isArray(r)?r.map(([e,t])=>[String(e),String(t)]):Object.entries(r).map(([e,t])=>[e,String(t)]);return Object.fromEntries(i.filter(([e])=>!n.has(e.toLowerCase())))}function Rr(e,t){let n=t.omitHeaders??[`content-type`];return async(r,i)=>{let a=i?.signal??void 0,o={headers:Lr(i,n),...a?{signal:a}:{},...t.rejectOnHttpError?{}:{validateStatus:()=>!0}};if((i?.method??`GET`).toUpperCase()===`POST`){let t=typeof i?.body==`string`?JSON.parse(i.body):void 0;return Ir(await e.post(r,t,o),r)}return Ir(await e.get(r,o),r)}}function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zr(e){return $(e)&&Object.values(e).every(e=>Array.isArray(e)&&e.every(e=>$(e)&&typeof e.name==`string`&&typeof e.type==`string`))}function Br(e){return new m(`Wallet ${e} request is malformed.`,`MALFORMED_WALLET_REQUEST`,{method:e})}function Vr(e){let t=e?.[1],n;try{n=typeof t==`string`?JSON.parse(t):t}catch{throw Br(`eth_signTypedData_v4`)}if(!$(n))throw Br(`eth_signTypedData_v4`);let{domain:r,types:i,message:a}=n;if(!$(r)||!zr(i)||!$(a))throw Br(`eth_signTypedData_v4`);return{domain:r,types:ur(i),message:a}}function Hr(e,t={}){let n=()=>{if(e==null)throw new m(t.unavailableMessage??`No wallet is connected.`,`WALLET_UNAVAILABLE`);return e};return{request:async({method:e,params:r})=>{switch(e){case`eth_chainId`:return n().send(`eth_chainId`,[]);case`eth_signTypedData_v4`:{let e=n(),{domain:t,types:i,message:a}=Vr(r);return(await e.getSigner()).signTypedData(t,i,a)}case`personal_sign`:{let e=r?.[0];if(typeof e!=`string`)throw Br(`personal_sign`);return t.personalSign===void 0?(await n().getSigner()).signMessage(e):t.personalSign(e)}default:throw new m(`Unsupported wallet method ${e}.`,`UNSUPPORTED_WALLET_METHOD`,{method:e})}}}}function Ur(e){let t=e.data;return typeof t==`object`&&t?t.mode:void 0}function Wr(e){return typeof e==`object`&&e?e:void 0}function Gr(e){return!e||Wr(e)?.error===!0}function Kr(e){let t=Wr(e);return t?.error===!1&&Ur(t)===`sync`}function qr(e){let t=Wr(e);return t?.error!==!1||Ur(t)!==`queued`?!1:typeof Wr(t.data)?.uniqueKey==`string`}function Jr(e){return Gr(e)?`rejected`:Kr(e)?`executed`:qr(e)?`queued`:`unconfirmed`}export{ye as ALL_FEE_TIERS,C as AppliedTradeError,Fe as Assets,er as BrowserWalletSigner,mt as CanonicalSymbols,Je as ChainGateway,Ct as DEFAULT_UNIQUE_KEY_PREFIX,Re as DEX_FEE_METHODS,ze as DRY_RUN_METHOD,Be as DRY_RUN_UNIQUE_KEY_PREFIX,Ge as DexFees,gn as EIP712_CAPABLE_METHODS,_e as FEE_TIER,T as GC_MAX_TICK,w as GC_MIN_TICK,$e as GSWAP_ENVIRONMENTS,ln as GSwap,m as GSwapSDKError,$n as GalaWalletSigner,F as GdexStreamError,at as GdexStreamService,dn as PENDING_SWAPS_STORAGE_KEY,fn as PENDING_SWAP_EXPIRY_MS,pn as PendingSwapStore,ht as Pools,Rt as Positions,Zn as PrivateKeySigner,Wt as Quoting,qe as SubmittedTransaction,cn as Swaps,dt as Symbols,ve as TICK_SPACING_BY_FEE,we as alignTickDown,Te as alignTickUp,j as assertCanonicalPair,q as assertCanonicalV2Dto,D as assertTickRange,W as assertUniqueKey,At as buildAddLiquidityDto,Mt as buildCollectPositionFeesDto,Nt as buildCreatePoolDto,We as buildDryRunWrapper,xn as buildEIP712Payload,jt as buildRemoveLiquidityDto,Ot as buildRequestTradeDto,Dn as calculatePersonalSignPrefix,fr as canonicalDecimalString,rn as classifyShadowSubmitError,nn as classifyShadowSubmitStatus,Jr as classifySubmitEnvelope,z as compositeKeyOf,ue as confirmAppliedTrade,Qn as createLazyPrivateKeySigner,Dt as createUniqueKey,Hr as eip1193ProviderFromEthers,hn as eip712DomainFor,Fn as ethAddressOfPrivateKey,Un as ethereumAddressOfAccount,kn as fixpointPrefixFor,De as frameSlot0,mn as generateEIP712Types,g as getObjectProperty,Tn as getPayloadToSign,_ as getStringProperty,jr as hashTypedData,Rr as httpRequestorFromAxios,He as isCurrentContractDexMessage,Ve as isDexFeeMethod,rt as isGdexLiquidityEvent,A as isProposableTradingSymbol,Kr as isSubmitExecuted,qr as isSubmitQueued,Gr as isSubmitRejected,Nn as normalizePrivateKey,R as orderSymbols,ee as parseJson,B as parseTokenClassKey,On as personalSignPrefixFor,U as queryTokenOf,V as rawTokenOf,ut as readOrderedSymbols,an as readShadowSubmitOutcome,sr as resolvePersonalSignChainDtoPayload,Tt as resolveUniqueKeyPrefix,Y as serialize,rr as signChainDtoHash,nr as signChainDtoNative,cr as signChainDtoPersonalSign,Rn as signNative,zn as signPersonalMessage,lr as signRawObject,Ln as signSerializedNative,Mr as signTypedDataPayload,Se as sqrtPriceToTick,ur as stripEip712DomainType,sn as swapRouteFromQuote,Ce as tickFromPrice,xe as tickToSqrtPrice,Ue as toChainDto,dr as tokenClassDollarKey,H as tradingSymbolOf,k as validateFee,O as validateNumericAmount,Oe as validatePriceValues,Ae as validateTickRange,je as validateTickSpacing,ke as validateTokenDecimals,Me as validateWalletAddress,tr as withPrivateKey};
|
|
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 new _(`EIP712_NAME_COLLISION`,{name:e});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 new _(`EIP712_UNSUPPORTED_VALUE`,{valueType:typeof 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 bn(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 _(`INVALID_CHAIN_ID`,{chainId:typeof e==`string`||typeof e==`number`?String(e):typeof e});return{name:`ethereum`,chainId:t}}const xn=/* @__PURE__ */ new Set([`RequestTrade`,`AddLiquidity`,`RemoveLiquidity`,`CollectPositionFees`]);function X(e,t){return typeof e[t]==`number`?e[t]:0}function Sn(e){return{...e,amount0Desired:X(e,`amount0Desired`),amount0Min:X(e,`amount0Min`),amount1Desired:X(e,`amount1Desired`),amount1Min:X(e,`amount1Min`),positionId:e.positionId??``}}function Cn(e){return{...e,amount:X(e,`amount`),amount0Min:X(e,`amount0Min`),amount1Min:X(e,`amount1Min`),positionId:e.positionId??``}}function wn(e){return{...e,amount0Requested:X(e,`amount0Requested`),amount1Requested:X(e,`amount1Requested`),positionId:e.positionId??``}}const Tn={AddLiquidity:Sn,RemoveLiquidity:Cn,CollectPositionFees:wn};function En(e,t){let n=Tn[e],r=n?n(t):t;return{completedDto:r,types:yn(e,r)}}const Dn=new TextEncoder;function On(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 kn(e){let t=On(e);if(t===void 0)return;if(typeof t!=`object`||!t)return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(e=>kn(e)??`null`).join(`,`)}]`;let n=t,r=[];for(let e of Object.keys(n).sort()){let t=kn(n[e]);t!==void 0&&r.push(`${JSON.stringify(e)}:${t}`)}return`{${r.join(`,`)}}`}function Z(e){JSON.stringify(e);let t=kn(e);if(t===void 0)throw TypeError(`Cannot serialize a value with no JSON representation.`);return t}function An(e){let{prefix:t,...n}=e;return delete n.signature,delete n.multisig,delete n.trace,(typeof t==`string`?t:``)+Z(n)}const jn=`Ethereum Signed Message:
|
|
4
|
+
`;function Mn(e){return jn+String(Dn.encode(e).length)}function Nn(e){let t={...e};return delete t.prefix,Mn(Z(t))}function Pn(e){let t={...e};delete t.prefix;let n=Dn.encode(An(t)).length,r=jn+String(n),i=-1;for(;n!==i;)i=n,r=jn+String(n),n=Dn.encode(An({...t,prefix:r})).length;return r}function Fn(e){return new _(`INVALID_PRIVATE_KEY`,{reason:e})}function In(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 Ln(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 Rn(e){if(typeof e!=`string`){if(!(e instanceof Uint8Array)||e.length!==32)throw Fn(`wrong_length`);if(!r.utils.isValidSecretKey(e))throw Fn(`not_on_curve`);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=Ln(t.length===63?`0${t}`:t):t.length===44&&(n=In(t)),n?.length!==32)throw Fn(`bad_encoding`);if(!r.utils.isValidSecretKey(n))throw Fn(`not_on_curve`);return n}function zn(e,t){if(t.length!==32)throw new _(`INVALID_SIGNING_HASH_LENGTH`,{length:t.length});let n=r.sign(t,e,{prehash:!1,lowS:!0});return a(n.toBytes(`compact`))+(n.recovery===1?`1c`:`1b`)}function Bn(e){let t=r.getPublicKey(e,!1);return`0x${a(i(t.slice(1)).slice(-20))}`}function Vn(e){return i(Dn.encode(e))}function Hn(e,t){return zn(e,Vn(t))}function Un(e,t){return Hn(e,An(t))}function Wn(e,t,n){return zn(e,Vn(t+n))}function Gn(){let e=globalThis.window?.gala;if(!e)throw new _(`GALA_WALLET_NOT_AVAILABLE`,{});return e}function Kn(e){if(typeof e!=`string`||!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(e))throw new _(`INVALID_SIGNATURE`,{scheme:`native`});return e}function qn(e){if(typeof e!=`string`||!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(e))throw new _(`INVALID_SIGNATURE`,{scheme:`personal-sign`});return e}function Jn(e){let t=/^(?:eth\|(?:0x)?|0x)([0-9a-fA-F]{40})$/u.exec(e);return t?.[1]===void 0?void 0:`0x${t[1]}`}function Yn(e,t){let n=t?Jn(e)??e:e;if(!/^0x[0-9a-fA-F]{40}$/u.test(n))throw new _(`INVALID_WALLET_ADDRESS`,{field:`walletAddress`,value:e});return n}function Xn(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 _(`INVALID_WALLET_ADDRESS`,{field:`walletAddress`,value:e})}function Zn(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 _(`INVALID_WALLET_ADDRESS`,{field:`selectAddress`,value:e})}const Qn=/* @__PURE__ */ new WeakMap;function $n(e,t,n){let{setAddress:r}=e;if(t===void 0||typeof r!=`function`)return n();let i=(Qn.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>(await r.call(e,t),n()));return Qn.set(e,i),i}function er(e,t,n,r){let i=Nn(t),a={...t,prefix:i},o=r===void 0?[Z(t),n]:[Z(a),n,r];return e.request({method:r===void 0?`personal_sign`:`gala_signChainDto`,params:o}).then(e=>({...a,signature:qn(e)}))}async function tr(e,t,n,r){let{completedDto:i,types:a}=En(t,n),o=bn(await e.request({method:`eth_chainId`,params:[]})),s=Pn(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:qn(d),types:a,domain:o}}var nr=class{constructor(e){g(this,`privateKey`,void 0),this.privateKey=Rn(e)}signObject(e,t){let n=Un(this.privateKey,t);return Promise.resolve({...t,signature:n})}};function rr(e,t={}){let n=t.expectedAddress,r=n===void 0?void 0:Yn(n,!0).toLowerCase();return{async signObject(t,n){let i=await e();if(typeof i!=`string`)throw new _(`INVALID_PRIVATE_KEY`,{reason:`no_key_provided`});let a=Rn(i);try{if(r!==void 0&&Bn(a)!==r)throw new _(`SIGNER_ADDRESS_MISMATCH`,{});return{...n,signature:Un(a,n)}}finally{a.fill(0)}}}}var ir=class{constructor(e,t={}){g(this,`walletAddress`,void 0),g(this,`scheme`,void 0),g(this,`selectAddress`,void 0),this.walletAddress=Xn(e),this.scheme=t.scheme??`native`,t.selectAddress!==void 0&&Zn(t.selectAddress),this.selectAddress=t.selectAddress}async signObject(e,t){let n=Gn();return $n(n,this.selectAddress,async()=>{if(this.scheme===`personal-sign`)return er(n,t,this.walletAddress,e);let r=await n.request({method:`gala_signChainDto`,params:[Z(t),this.walletAddress,e,`native`]});return{...t,signature:Kn(r)}})}},ar=class{constructor(e,t,n={}){this.provider=e,g(this,`walletAddress`,void 0),g(this,`scheme`,void 0),this.walletAddress=Yn(t,!1),this.scheme=n.scheme??`personal-sign`}signObject(e,t){return this.scheme===`eip712`&&xn.has(e)?tr(this.provider,e,t,this.walletAddress):er(this.provider,t,this.walletAddress)}};function or(e,t){let n=Rn(e);try{return t(n)}finally{n.fill(0)}}function sr(e,t){return or(e,e=>Hn(e,t))}function cr(e,t,n){return or(e,e=>Wn(e,t,n))}const lr=/^(?:0|[1-9][0-9]*)$/u;function ur(e){return e.startsWith(`Ethereum Signed Message:
|
|
5
|
+
`)&&lr.test(e.slice(26))}const dr=[`signature`,`multisig`,`trace`,`types`,`domain`,`stringsInstructions`];function fr(e){let t;try{t=JSON.parse(e)}catch{throw new _(`PERSONAL_SIGN_NOT_JSON`,{})}if(typeof t!=`object`||!t||Array.isArray(t))throw new _(`PERSONAL_SIGN_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`||!ur(r))throw new _(`PERSONAL_SIGN_BAD_PREFIX`,{});let a=dr.filter(e=>Object.prototype.hasOwnProperty.call(i,e));if(a.length>0)throw new _(`PERSONAL_SIGN_ENVELOPE_FIELDS`,{fields:a.join(`, `)});if(Z(n)!==e)throw new _(`PERSONAL_SIGN_NOT_CANONICAL`,{});return{prefix:r,message:Z(i)}}function pr(e,t){let{prefix:n,message:r}=fr(t);return cr(e,n,r)}function mr(e,t){let n={...t};return delete n.signature,{signature:sr(e,Z(n)),...n}}function hr(e){let t={};for(let n of Object.keys(e))n!==`EIP712Domain`&&(t[n]=e[n]);return t}function gr(e){let t=t=>{let n=e?.[t];return typeof n==`string`?n:``};return`${t(`collection`)}$${t(`category`)}$${t(`type`)}$${t(`additionalKey`)}`}function _r(t){let n=new e(NaN);try{n=new e(t)}catch{}if(!n.isFinite())throw new _(`INVALID_DECIMAL`,{value:String(t)});return n.toFixed()}const vr=new TextEncoder,yr=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,br=/^([A-Za-z_$][A-Za-z0-9_$]*)((?:\[(?:0|[1-9][0-9]*)?\])*)$/u,xr=/^-?[0-9]+$/u,Sr=/^-?0x[0-9a-fA-F]+$/u,Cr=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`},{name:`salt`,type:`bytes32`}];function Q(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 wr(e){let t=/* @__PURE__ */ new Uint8Array(32),n=e<0n?e+(1n<<256n):e;for(let e=31;e>=0;--e)t[e]=Number(n&255n),n>>=8n;return t}function Tr(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 Er(e,t){if(e instanceof Uint8Array)return e;if(typeof e==`string`&&/^0x(?:[0-9a-fA-F]{2})*$/u.test(e))return Tr(e);throw new _(`TYPED_DATA_NOT_HEX_BYTES`,{what:t})}function Dr(e,t){if(typeof e==`bigint`)return e;if(typeof e==`number`){if(!Number.isSafeInteger(e))throw new _(`TYPED_DATA_NOT_SAFE_INTEGER`,{what:t});return BigInt(e)}if(typeof e==`string`){if(xr.test(e))return BigInt(e);if(Sr.test(e))return e.startsWith(`-`)?-BigInt(e.slice(1)):BigInt(e)}throw new _(`TYPED_DATA_NOT_INTEGER`,{what:t})}function Or(e,t){if(typeof e!=`string`)throw new _(`TYPED_DATA_NOT_STRING`,{what:t});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))throw new _(`TYPED_DATA_UNPAIRED_SURROGATE`,{what:t});n+=1}else if(r>=56320&&r<=57343)throw new _(`TYPED_DATA_UNPAIRED_SURROGATE`,{what:t})}return vr.encode(e)}function kr(e){if(typeof e!=`string`||!/^0x[0-9a-fA-F]{40}$/u.test(e))throw new _(`TYPED_DATA_BAD_ADDRESS`,{});let t=e.slice(2);if(/[A-F]/u.test(t)&&/[a-f]/u.test(t)){let e=i(vr.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()))throw new _(`TYPED_DATA_BAD_CHECKSUM`,{})}}return Tr(e)}function Ar(e){if(e===`string`)return e=>i(Or(e,`string`));if(e===`bytes`)return e=>i(Er(e,`bytes`));if(e===`bool`)return e=>{if(typeof e!=`boolean`)throw new _(`TYPED_DATA_NOT_BOOLEAN`,{});return wr(e?1n:0n)};if(e===`address`)return e=>Q([/* @__PURE__ */ new Uint8Array(12),kr(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=Er(t,e);if(r.length!==n)throw new _(`TYPED_DATA_BYTES_LENGTH`,{type:e,width:n});return Q([r,new Uint8Array(32-n)])}}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=Dr(t,e);if(n<i||n>a)throw new _(`TYPED_DATA_OUT_OF_BOUNDS`,{type:e});return wr(n)}}}function jr(e){let t=br.exec(e);if(t===null)throw new _(`TYPED_DATA_UNSUPPORTED_TYPE`,{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 Mr(e,t){if(!Array.isArray(t))throw new _(`TYPED_DATA_FIELDS_NOT_LIST`,{typeName:e});let n=/* @__PURE__ */ new Set;return t.map(t=>{let r=t;if(typeof r?.name!=`string`||typeof r.type!=`string`)throw new _(`TYPED_DATA_FIELD_MALFORMED`,{typeName:e});if(!yr.test(r.name))throw new _(`TYPED_DATA_INVALID_FIELD_NAME`,{name:r.name});if(n.has(r.name))throw new _(`TYPED_DATA_DUPLICATE_FIELD`,{name:r.name,typeName:e});n.add(r.name);let i=jr(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 Nr(e){let t=Object.keys(e),n=/* @__PURE__ */ new Map;for(let r of t){if(!yr.test(r))throw new _(`TYPED_DATA_INVALID_TYPE_NAME`,{name:r});n.set(r,Mr(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}=jr(i.type);if(t===e)throw new _(`TYPED_DATA_CIRCULAR_TYPE`,{typeName:e});if(Ar(t)===void 0){if(!n.has(t))throw new _(`TYPED_DATA_UNKNOWN_FIELD_TYPE`,{type:t,typeName: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)throw new _(`TYPED_DATA_NO_PRIMARY_TYPE`,{});if(o.length>1)throw new _(`TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE`,{roots:o.join(`, `)});let s=o[0],c=/* @__PURE__ */ new Set,l=/* @__PURE__ */ new Set,u=e=>{if(c.has(e))throw new _(`TYPED_DATA_CIRCULAR_TYPE`,{typeName: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(vr.encode([e,...t].map(f).join(``))))}let m=(e,t,n)=>{let r=e.dimensions[e.dimensions.length-1-n];if(r!==void 0){if(!Array.isArray(t))throw new _(`TYPED_DATA_ARRAY_EXPECTED`,{type:e.base});if(r!==-1&&r!==t.length)throw new _(`TYPED_DATA_ARRAY_LENGTH_MISMATCH`,{});return i(Q(t.map(t=>m(e,t,n+1))))}let a=Ar(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)throw Error(`Internal error: no encoder for struct ${e}`);if(typeof t!=`object`||!t||Array.isArray(t))throw new _(`TYPED_DATA_STRUCT_NOT_OBJECT`,{typeName:e});let o=t,s=r.map(t=>{if(!Object.prototype.hasOwnProperty.call(o,t.name))throw new _(`TYPED_DATA_MISSING_FIELD`,{typeName:e,field:t.name});return m(jr(t.type),o[t.name],0)});return i(Q([a,...s]))}return{primaryType:s,hashStruct:h}}function Pr(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new _(`TYPED_DATA_DOMAIN_NOT_OBJECT`,{});for(let t of Object.keys(e))if(!Cr.some(e=>e.name===t))throw new _(`TYPED_DATA_INVALID_DOMAIN_KEY`,{key:JSON.stringify(t)});return Nr({EIP712Domain:Cr.filter(t=>Object.prototype.hasOwnProperty.call(e,t.name))}).hashStruct(`EIP712Domain`,e)}function Fr(e){let t=Pr(e.domain),n=Nr(e.types),r=n.hashStruct(n.primaryType,e.message);return i(Q([Uint8Array.of(25,1),t,r]))}async function Ir(e,t){let n=Fr(t);return or(e,e=>`0x${zn(e,n)}`)}function Lr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rr(e){return Lr(e)&&typeof e.status==`number`}function zr(e,t){if(!Lr(e))return null;let n=e.get;if(typeof n==`function`){let r=n.call(e,t);return typeof r==`string`?r:null}let r=Object.entries(e).find(([e])=>e.toLowerCase()===t.toLowerCase());return typeof r?.[1]==`string`?r[1]:null}function Br(e,t){if(!Rr(e))throw new _(`TRANSPORT_ERROR`,{url:t},{url:t});let{status:n,data:r,headers:i}=e;return{ok:n>=200&&n<300,status:n,json:()=>Promise.resolve(r),text:()=>Promise.resolve(typeof r==`string`?r:JSON.stringify(r)),headers:{get:e=>zr(i,e)}}}function Vr(e,t){let n=new Set(t.map(e=>e.toLowerCase())),r=e?.headers,i=r===void 0?[]:r instanceof Headers?[...r.entries()]:Array.isArray(r)?r.map(([e,t])=>[String(e),String(t)]):Object.entries(r).map(([e,t])=>[e,String(t)]);return Object.fromEntries(i.filter(([e])=>!n.has(e.toLowerCase())))}function Hr(e,t){let n=t.omitHeaders??[`content-type`];return async(r,i)=>{let a=i?.signal??void 0,o={headers:Vr(i,n),...a?{signal:a}:{},...t.rejectOnHttpError?{}:{validateStatus:()=>!0}};if((i?.method??`GET`).toUpperCase()===`POST`){let t=typeof i?.body==`string`?JSON.parse(i.body):void 0;return Br(await e.post(r,t,o),r)}return Br(await e.get(r,o),r)}}function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ur(e){return $(e)&&Object.values(e).every(e=>Array.isArray(e)&&e.every(e=>$(e)&&typeof e.name==`string`&&typeof e.type==`string`))}function Wr(e){return new _(`MALFORMED_WALLET_REQUEST`,{method:e})}function Gr(e){let t=e?.[1],n;try{n=typeof t==`string`?JSON.parse(t):t}catch{throw Wr(`eth_signTypedData_v4`)}if(!$(n))throw Wr(`eth_signTypedData_v4`);let{domain:r,types:i,message:a}=n;if(!$(r)||!Ur(i)||!$(a))throw Wr(`eth_signTypedData_v4`);return{domain:r,types:hr(i),message:a}}function Kr(e,t={}){let n=()=>{if(e==null)throw new _(`WALLET_UNAVAILABLE`,{});return e};return{request:async({method:e,params:r})=>{switch(e){case`eth_chainId`:return n().send(`eth_chainId`,[]);case`eth_signTypedData_v4`:{let e=n(),{domain:t,types:i,message:a}=Gr(r);return(await e.getSigner()).signTypedData(t,i,a)}case`personal_sign`:{let e=r?.[0];if(typeof e!=`string`)throw Wr(`personal_sign`);return t.personalSign===void 0?(await n().getSigner()).signMessage(e):t.personalSign(e)}default:throw new _(`UNSUPPORTED_WALLET_METHOD`,{method:e})}}}}function qr(e){let t=e.data;return typeof t==`object`&&t?t.mode:void 0}function Jr(e){return typeof e==`object`&&e?e:void 0}function Yr(e){return!e||Jr(e)?.error===!0}function Xr(e){let t=Jr(e);return t?.error===!1&&qr(t)===`sync`}function Zr(e){let t=Jr(e);return t?.error!==!1||qr(t)!==`queued`?!1:typeof Jr(t.data)?.uniqueKey==`string`}function Qr(e){return Yr(e)?`rejected`:Xr(e)?`executed`:Zr(e)?`queued`:`unconfirmed`}export{Te as ALL_FEE_TIERS,T as AppliedTradeError,He as Assets,ar as BrowserWalletSigner,St as CanonicalSymbols,tt as ChainGateway,jt as DEFAULT_UNIQUE_KEY_PREFIX,Ge as DEX_FEE_METHODS,Ke as DRY_RUN_METHOD,qe as DRY_RUN_UNIQUE_KEY_PREFIX,Qe as DexFees,xn as EIP712_CAPABLE_METHODS,Ce as FEE_TIER,D as GC_MAX_TICK,E as GC_MIN_TICK,st as GSWAP_ENVIRONMENTS,d as GSWAP_ERROR_CATALOG,mn as GSwap,_ as GSwapSDKError,ir as GalaWalletSigner,F as GdexStreamError,pt as GdexStreamService,gn as PENDING_SWAPS_STORAGE_KEY,_n as PENDING_SWAP_EXPIRY_MS,vn as PendingSwapStore,Ct as Pools,Wt as Positions,nr as PrivateKeySigner,Zt as Quoting,et as SubmittedTransaction,pn as Swaps,yt as Symbols,we as TICK_SPACING_BY_FEE,Ae as alignTickDown,je as alignTickUp,M as assertCanonicalPair,Y as assertCanonicalV2Dto,k as assertTickRange,W as assertUniqueKey,q as buildAddLiquidityDto,Rt as buildCollectPositionFeesDto,zt as buildCreatePoolDto,Ze as buildDryRunWrapper,En as buildEIP712Payload,Lt as buildRemoveLiquidityDto,K as buildRequestTradeDto,Mn as calculatePersonalSignPrefix,_r as canonicalDecimalString,ln as classifyShadowSubmitError,cn as classifyShadowSubmitStatus,Qr as classifySubmitEnvelope,z as compositeKeyOf,_e as confirmAppliedTrade,rr as createLazyPrivateKeySigner,Ft as createUniqueKey,Kr as eip1193ProviderFromEthers,bn as eip712DomainFor,Bn as ethAddressOfPrivateKey,Jn as ethereumAddressOfAccount,Pn as fixpointPrefixFor,Ne as frameSlot0,yn as generateEIP712Types,y as getObjectProperty,An as getPayloadToSign,b as getStringProperty,f as gswapErrorTemplates,Fr as hashTypedData,Hr as httpRequestorFromAxios,Ye as isCurrentContractDexMessage,Je as isDexFeeMethod,ie as isGSwapError,dt as isGdexLiquidityEvent,Ve as isProposableTradingSymbol,Xr as isSubmitExecuted,Zr as isSubmitQueued,Yr as isSubmitRejected,Rn as normalizePrivateKey,R as orderSymbols,ae as parseJson,B as parseTokenClassKey,Nn as personalSignPrefixFor,U as queryTokenOf,V as rawTokenOf,vt as readOrderedSymbols,un as readShadowSubmitOutcome,m as renderGSwapErrorTemplate,fr as resolvePersonalSignChainDtoPayload,Nt as resolveUniqueKeyPrefix,Z as serialize,cr as signChainDtoHash,sr as signChainDtoNative,pr as signChainDtoPersonalSign,Un as signNative,Wn as signPersonalMessage,mr as signRawObject,Hn as signSerializedNative,Ir as signTypedDataPayload,Oe as sqrtPriceToTick,hr as stripEip712DomainType,fn as swapRouteFromQuote,ke as tickFromPrice,De as tickToSqrtPrice,Xe as toChainDto,gr as tokenClassDollarKey,H as tradingSymbolOf,j as validateFee,A as validateNumericAmount,Pe as validatePriceValues,Ie as validateTickRange,Le as validateTickSpacing,Fe as validateTokenDecimals,Re as validateWalletAddress,or as withPrivateKey};
|
|
6
6
|
//# sourceMappingURL=index.js.map
|