@gala-chain/gswap-sdk 1.0.0-rc.3 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,5 @@
1
- var Ke=Object.defineProperty;var je=(t,e,n)=>e in t?Ke(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var d=(t,e,n)=>je(t,typeof e!="symbol"?e+"":e,n);import x from"bignumber.js";var u=class t extends Error{constructor(n,i,r,o,a){super(n);d(this,"code",i);d(this,"details",r);d(this,"chainMessage");d(this,"retryAfterMs");this.name="GSwapSDKError",this.chainMessage=o,this.retryAfterMs=a}static noSignerError(){return new t("This method requires a signer. Please provide a signer to the GSwap constructor.","NO_SIGNER")}static noWalletAddressError(){return new t("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(n,i,r){return new t("No pool is available for the requested pair.","NO_POOL_AVAILABLE",{tokenIn:n,tokenOut:i,...r===void 0?{}:{fee:r}})}static insufficientLiquidityError(n,i,r){return new t("The selected pool has insufficient liquidity for the requested quote.","INSUFFICIENT_LIQUIDITY",{tokenIn:n,tokenOut:i,...r===void 0?{}:{fee:r}})}static fromGatewayBounce(n,i,r,o){let a={status:r,chainMessage:i};o!==void 0&&(a.retryAfterMs=o);let s=n==="CHAIN_DISPATCH_FAILED"?i:`Gateway rejected ${n}: ${i}`;return new t(s,n,a,i,o)}static fromChainError(n,i,r){return new t(`GalaChain error ${n}: ${i}`,n,{...r,errorKey:n,message:i},i)}static unknownTokenError(n){let i=typeof n=="string"?n:JSON.stringify(n);return new t(`Token ${i} has no trading symbol on the new DEX contract (no gcdex pool includes it yet).`,"UNKNOWN_TOKEN",{token:n})}static confirmationTimeoutError(n,i){return new t("Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.","CONFIRMATION_TIMEOUT",{uniqueKey:n,...i===void 0?{}:{cause:i}})}static async fromErrorResponse(n,i){let r=await i.text(),o=re(r),a=R(o,"error"),s=p(a,"ErrorKey"),c=p(a,"Message");return s!==void 0&&c!==void 0?new t(`GalaChain Error ${s} from ${n}: ${c}`,s,{message:c,errorKey:s,status:i.status,body:o,url:n},c):new t(`Unexpected HTTP Error ${i.status} from ${n}`,"HTTP_ERROR",{status:i.status,body:o??r,url:n})}};function R(t,e){if(typeof t!="object"||t===null||!(e in t))return;let n=t[e];return typeof n=="object"&&n!==null?n:void 0}function p(t,e){if(typeof t!="object"||t===null||!(e in t))return;let n=t[e];return typeof n=="string"?n:void 0}function re(t){try{return JSON.parse(t)}catch{return}}var He=(r=>(r[r.PERCENT_00_00=0]="PERCENT_00_00",r[r.PERCENT_00_05=500]="PERCENT_00_05",r[r.PERCENT_00_30=3e3]="PERCENT_00_30",r[r.PERCENT_01_00=1e4]="PERCENT_01_00",r))(He||{}),L={0:200,500:10,3e3:60,1e4:200},B=[0,500,3e3,1e4];import M from"bignumber.js";import{Decimal as $e}from"decimal.js";var E=-887272,I=887272,Ve=M.clone({DECIMAL_PLACES:60,ROUNDING_MODE:M.ROUND_DOWN}),oe=$e.clone({precision:60});function le(t){return new M(new oe(1.0001).pow(t/2).toString())}function Bt(t){let e;try{e=new Ve(t)}catch{return Number.NaN}if(!e.isFinite()||e.isLessThanOrEqualTo(0))return Number.NaN;let n=Math.log(e.toNumber()**2)/Math.log(1.0001);if(!Number.isFinite(n))return Number.NaN;let i=Math.min(I,Math.max(E,Math.floor(n)));for(;i<I&&le(i+1).isLessThanOrEqualTo(e);)i+=1;for(;i>E&&le(i).isGreaterThan(e);)i-=1;return i}function se(t){let e=typeof t=="string"?t:typeof t=="number"||M.isBigNumber(t)?t.toString():"NaN",n=new oe(e);if(!n.isFinite()||n.lessThanOrEqualTo(0)||!Number.isFinite(n.toNumber()))return Number.NaN;let i=n.ln().dividedBy(new oe(1.0001).ln()).floor().toNumber();return Number.isFinite(i)?i:Number.NaN}function me(t,e){return fe(e),Math.floor(t/e)*e}function pe(t,e){return fe(e),Math.ceil(t/e)*e}function F(t,e,n){let i=L[n];if(i===void 0)throw new RangeError(`Unsupported fee tier: ${n}`);if(!Number.isInteger(t)||!Number.isInteger(e))throw new RangeError("Ticks must be integers");if(t<E||e>I||t>=e)throw new RangeError(`Tick range must satisfy ${E} <= lower < upper <= ${I}`);if(t%i!==0||e%i!==0)throw new RangeError(`Ticks must be aligned to spacing ${i}`)}function fe(t){if(!Number.isInteger(t)||t<=0)throw new RangeError("Tick spacing must be positive")}function y(t,e,n=!1){if(typeof t=="number")throw new u(`Invalid ${e}: use a decimal string or BigNumber, not a JavaScript number`,"VALIDATION_ERROR",{type:"INVALID_NUMERIC_AMOUNT",parameterName:e,value:t,reason:"number_input"});let i;try{i=x(t)}catch{i=x(NaN)}if(!i.isFinite())throw new u(`Invalid ${e}: must be a finite number`,"VALIDATION_ERROR",{type:"INVALID_NUMERIC_AMOUNT",parameterName:e,value:t,reason:"not_finite"});if(!n&&i.isZero())throw new u(`Invalid ${e}: must be positive`,"VALIDATION_ERROR",{type:"INVALID_NUMERIC_AMOUNT",parameterName:e,value:t,reason:"zero_not_allowed"});if(i.isNegative())throw new u(`Invalid ${e}: must be ${n?"non-negative":"positive"}`,"VALIDATION_ERROR",{type:"INVALID_NUMERIC_AMOUNT",parameterName:e,value:t,reason:"negative"})}function jt(t,e,n){if([t,e,n].some(s=>typeof s=="number"))throw new u("Invalid price values: use decimal strings or BigNumber values, not JavaScript numbers","VALIDATION_ERROR",{type:"INVALID_NUMERIC_AMOUNT",reason:"number_input"});let i=s=>{try{return x(s)}catch{return x(NaN)}},r=i(t),o=i(e),a=i(n);if(a=a.isFinite()?a:x(1e18),!r.isFinite()||!o.isFinite()||!a.isFinite()||!r.isPositive()||!o.isPositive()||!a.isPositive())throw new u("Invalid price values: all prices must be finite and positive","VALIDATION_ERROR",{type:"INVALID_PRICE_VALUES",spotPrice:t,lowerPrice:e,upperPrice:n});if(o.isGreaterThan(a))throw new u("Invalid price range: lower price must be less than or equal to upper price","VALIDATION_ERROR",{type:"INVALID_PRICE_RANGE",lowerPrice:e,upperPrice:n})}function Ht(t,e){if(t<0||!Number.isInteger(t))throw new u(`Invalid ${e}: must be a non-negative integer`,"VALIDATION_ERROR",{type:"INVALID_TOKEN_DECIMALS",parameterName:e,value:t})}function $t(t,e){if(!Number.isInteger(t)||!Number.isInteger(e))throw new u("Invalid tick values: ticks must be integers","VALIDATION_ERROR",{type:"INVALID_TICK_VALUES",tickLower:t,tickUpper:e});if(t>=e)throw new u("Invalid tick range: tickLower must be less than tickUpper","VALIDATION_ERROR",{type:"INVALID_TICK_RANGE",tickLower:t,tickUpper:e});if(t<E||e>I)throw new u(`Invalid tick range: ticks must be between ${E} and ${I}`,"VALIDATION_ERROR",{type:"INVALID_TICK_BOUNDS",tickLower:t,tickUpper:e,minTick:E,maxTick:I})}function w(t){if(!B.some(e=>Number(e)===t))throw new u("Invalid fee tier: must be one of 0, 500, 3000, or 10000","VALIDATION_ERROR",{type:"INVALID_FEE",value:t})}function Vt(t){if(!Number.isInteger(t)||t<=0)throw new u("Invalid tick spacing: must be a positive integer","VALIDATION_ERROR",{type:"INVALID_TICK_SPACING",value:t})}function ye(t){if(t===void 0)throw new u("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(!t||typeof t!="string"||t.trim().length===0)throw new u("Invalid wallet address: must be a non-empty string","VALIDATION_ERROR",{type:"INVALID_WALLET_ADDRESS",value:t})}var G=class{constructor(e,n){d(this,"dexBackendBaseUrl",e);d(this,"httpClient",n)}async getUserAssets(e,n=1,i=10){if(ye(e),!Number.isInteger(n)||n<1)throw new u("Invalid page: must be a positive integer","VALIDATION_ERROR",{page:n});if(!Number.isInteger(i)||i<1||i>100)throw new u("Invalid limit: must be an integer between 1 and 100","VALIDATION_ERROR",{limit:i});let r=await this.httpClient.sendGetRequest(this.dexBackendBaseUrl,"/user/assets","",{address:e,page:n.toString(),limit:i.toString()});return We(r)}};function We(t){let e=R(t,"data"),n=e?.token;if(!Array.isArray(n)||!n.every(Qe))throw new u("Backend returned an invalid user assets response.","INVALID_CHAIN_RESPONSE",{data:t});let i=e?.count;return{tokens:n.map(r=>({...r,decimals:parseInt(r.decimals,10)})),count:typeof i=="number"?i:0}}function Qe(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.image=="string"&&typeof e.name=="string"&&typeof e.decimals=="string"&&/^\d+$/u.test(e.decimals)&&typeof e.verify=="boolean"&&typeof e.symbol=="string"&&typeof e.quantity=="string"}async function A(t,e,n,i){let r=new AbortController,o=setTimeout(()=>r.abort(),i),a=n.signal,s=()=>r.abort();a?.addEventListener("abort",s,{once:!0});try{return await t(e,{...n,signal:r.signal})}catch(c){throw r.signal.aborted?new u(`Request timed out after ${i} ms.`,"REQUEST_TIMEOUT",{url:e,timeoutMs:i,cause:c}):c}finally{clearTimeout(o),a?.removeEventListener("abort",s)}}async function N(t){let e=await t.text();return re(e)??e}function v(t,e){let n=t.headers;if(n===void 0)return;if(Je(n)){let r=n.get(e);return r===null||r===""?void 0:r}let i=Object.entries(n).find(([r])=>r.toLowerCase()===e.toLowerCase())?.[1];return i===void 0||i===""?void 0:i}function U(t){let e=v(t,"retry-after");if(e===void 0)return;let n=Number(e);return Number.isFinite(n)&&n>=0?n*1e3:void 0}function K(t,e="x-block-number"){let n=v(t,e);if(n===void 0)return;let i=Number(n);return Number.isInteger(i)&&i>=0?i:void 0}function Je(t){return"get"in t&&typeof t.get=="function"}var q=class{constructor(e){d(this,"method");d(this,"uniqueKey");d(this,"transactionId");d(this,"blockNumber");d(this,"mode");d(this,"result");d(this,"backendBaseUrl");d(this,"requestor");d(this,"requestTimeoutMs");d(this,"positionConfirmation");this.method=e.method,this.uniqueKey=e.uniqueKey,this.transactionId=e.transactionId,this.blockNumber=e.blockNumber??null,this.mode=e.mode,this.result=e.result,this.backendBaseUrl=e.dexBackendBaseUrl.replace(/\/$/u,""),this.requestor=e.httpRequestor,this.requestTimeoutMs=e.requestTimeoutMs??3e4,this.positionConfirmation=e.positionConfirmation}async confirm(e){return this.method==="RequestTrade"?this.confirmApplied(e):this.confirmPosition(e)}async confirmApplied(e){let n=we(e,3e3);await n.waitForRead();let i=`${this.backendBaseUrl}/v1/chain/apply-results/${encodeURIComponent(this.uniqueKey)}?channel=asset&contract=dex-contract`,r;for(;;){let o,a;try{o=await A(this.requestor,i,{method:"GET"},this.requestTimeoutMs),a=await N(o)}catch(s){if(r=s,!await n.waitForRead())break;continue}if(o.status===200)return this.readAppliedResult(o,a,i);if(o.status===404||o.status===429||ze(o.status)){if(o.status===429){let s=U(o);if(s!==void 0){if(!await n.waitForRead(s))break;continue}}}else throw new u(Xe(a),"CONFIRMATION_FAILED",{status:o.status,body:a,url:i});if(!await n.waitForRead())break}throw u.confirmationTimeoutError(this.uniqueKey,r)}readAppliedResult(e,n,i){let r=ke(n),o=r?.Status,a=v(e,"x-apply-transaction-id")??null,s=K(e,"x-apply-block-number")??null;if(o===0)throw u.fromChainError(p(r,"ErrorKey")??"CHAIN_ERROR",p(r,"Message")??"The chain rejected this trade.",{uniqueKey:this.uniqueKey,applyTransactionId:a,blockNumber:s,status:e.status,body:n,url:i});if(o!==1)throw he(e,n,i);let c=Ye(r?.Data);if(c===void 0)throw he(e,n,i);return{uniqueKey:this.uniqueKey,transactionId:a,blockNumber:s,requestTransactionId:this.transactionId,result:c}}async confirmPosition(e){if(this.positionConfirmation===void 0)throw u.noWalletAddressError();let n=we(e,0);for(await n.waitForRead();;){let i=new AbortController,r=setTimeout(()=>i.abort(),this.requestTimeoutMs);try{let o=await this.positionConfirmation(i.signal);if(o.confirmed)return o.position}finally{clearTimeout(r)}if(!await n.waitForRead())break}throw u.confirmationTimeoutError(this.uniqueKey)}};function we(t,e){let n=Math.max(0,t?.timeoutMs??6e4),i=Math.max(500,t?.pollIntervalMs??2e3),r=Math.max(0,t?.initialDelayMs??e),o=Date.now()+n,a=!0,s=0;return{async waitForRead(c){if(a){a=!1;let T=Math.max(0,o-Date.now());return await ge(Math.min(r,T)),!0}let m=Math.min(8e3,i*2**Math.min(s,5));s+=1;let l=c===void 0?Ze(m):c;return Date.now()+l>o?!1:(await ge(l),!0)}}}function Ye(t){let e=ke(t);if(e===void 0||typeof e.token0!="string"||typeof e.token1!="string"||typeof e.fee!="number")return;let n=["sell0Qty","sell1Qty","buy0Qty","buy1Qty","tradingFees","protocolFees","totalFees"];for(let i of n)if(i in e&&typeof e[i]!="string")return;return{token0:e.token0,token1:e.token1,fee:e.fee,...Object.fromEntries(n.flatMap(i=>typeof e[i]=="string"?[[i,e[i]]]:[]))}}function he(t,e,n){return new u("Transaction confirmation returned a malformed body","CONFIRMATION_FAILED",{status:t.status,body:e,url:n})}function ze(t){return t===500||t===502||t===503||t===504}function Xe(t){return p(t,"message")??p(t,"Message")??p(R(t,"error"),"message")??p(R(t,"error"),"Message")??(typeof t=="string"?t:"Transaction confirmation failed")}function ke(t){return typeof t=="object"&&t!==null?t:void 0}function ge(t){return new Promise(e=>setTimeout(e,t))}function Ze(t){return Math.max(0,Math.round(t*(.9+Math.random()*.2)))}var H=class{constructor(e){d(this,"requestor");d(this,"walletAddress");d(this,"chainCallTimeoutMs");d(this,"requestTimeoutMs");d(this,"dexBackendBaseUrl");this.dexBackendBaseUrl=et(e.dexBackendBaseUrl),this.requestor=e.httpRequestor??fetch.bind(globalThis),this.walletAddress=e.walletAddress,this.chainCallTimeoutMs=e.chainCallTimeoutMs??3e4,this.requestTimeoutMs=this.chainCallTimeoutMs}async submit(e,n,i){if(e==="Trade")throw new u("The synchronous Trade method was removed; swaps are queued through RequestTrade.","METHOD_NOT_SUPPORTED",{method:e});let r=`${this.dexBackendBaseUrl}/v1/chain/asset/dex-contract/${e}`,o={"content-type":"application/json"},a=i?.walletAddress??this.walletAddress;a!==void 0&&(o["X-Wallet-Address"]=a);let s;try{s=await A(this.requestor,r,{method:"POST",headers:o,body:JSON.stringify(n)},this.chainCallTimeoutMs)}catch(h){throw h instanceof u&&h.code==="REQUEST_TIMEOUT"?new u("The submission outcome is unknown because the gateway request timed out. Confirm before retrying.","SUBMISSION_OUTCOME_UNKNOWN",{uniqueKey:p(n,"uniqueKey")??"",cause:h}):h}let c=await N(s);if(!s.ok)throw tt(s,c,r);let m=j(c),l=j(m?.data??m?.Data);if(l===void 0)throw _(s,c,r,"Expected a data object.");let T=p(l,"transactionId"),g=p(l,"mode"),te=l.transactionId,P=l.blockNumber,ne='Gateway response must contain data.mode="sync" with data.result, or data.mode="queued".';if(g!=="sync"&&g!=="queued"||"transactionId"in l&&typeof te!="string"||P!=null&&!be(P))throw _(s,c,r,ne);if(e==="RequestTrade"&&g==="sync")throw _(s,c,r,"The gateway executed RequestTrade synchronously, which this SDK refuses; RequestTrade must be queued.");if(e==="RequestTrade"&&g==="queued"){let h=p(n,"uniqueKey");if("uniqueKey"in l&&(typeof l.uniqueKey!="string"||l.uniqueKey!==h))throw _(s,c,r,"Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey.")}else if(g==="queued"||!("result"in l))throw _(s,c,r,ne);if(g==="sync"){let h=j(l.result);if(h!==void 0){let ce=h.Status;if(ce!==void 0&&ce!==1)throw u.fromChainError(p(h,"ErrorKey")??"CHAIN_ERROR",p(h,"Message")??"The chain rejected this write.",{status:s.status,body:c,url:r})}}let Fe=p(n,"uniqueKey")??"",Ge=v(s,"x-transaction-id"),ie=T===void 0||T===""?Ge:T,Ue=P==null?K(s):be(P)?P:void 0;return new q({method:e,uniqueKey:Fe,transactionId:ie===void 0||ie===""?null:ie,blockNumber:Ue??null,mode:g,result:g==="queued"?void 0:l.result,dexBackendBaseUrl:this.dexBackendBaseUrl,httpRequestor:this.requestor,requestTimeoutMs:this.chainCallTimeoutMs,...i?.positionConfirmation===void 0?{}:{positionConfirmation:i.positionConfirmation}})}get httpRequestor(){return this.requestor}};function et(t){return t.replace(/\/$/u,"")}function _(t,e,n,i){return new u(i,"INVALID_GATEWAY_RESPONSE",{status:t.status,body:e,url:n})}function tt(t,e,n){let i=j(e),r=R(e,"error"),o=p(i,"code")??p(r,"code")??p(r,"ErrorKey")??"HTTP_ERROR",a=p(i,"message")??p(r,"message")??p(r,"Message")??(typeof e=="string"?e:`Gateway request failed with HTTP ${t.status}`),s=t.status===429?U(t):void 0;return o==="HTTP_ERROR"?new u(a,o,{status:t.status,body:e,url:n}):u.fromGatewayBounce(o,a,t.status,s)}function j(t){return typeof t=="object"&&t!==null?t:void 0}function be(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}import nt from"debug";var ae=nt("GSWAP_SDK");var Te="1.0.0-rc.3";var k=class{constructor(e=fetch,n=3e4){d(this,"httpRequestor",e);d(this,"timeoutMs",n)}async sendRequest(e,n,i,r,o,a){let s=`${n}${i}${r}`;ae(`Sending request to ${s} with body:`,o);let c=await A(this.httpRequestor,s,{method:e,headers:{"Content-Type":"application/json","User-Agent":`GalaChain-SDK/${Te}`},...o?{body:JSON.stringify(o)}:{},...a?.signal===void 0?{}:{signal:a.signal}},this.timeoutMs);if(!c.ok)throw await u.fromErrorResponse(s,c);let m=await N(c);return ae(`Response from ${n}${i}${r}:`,m),m}async sendPostRequest(e,n,i,r){return this.sendRequest("POST",e,n,i,r)}async sendGetRequest(e,n,i,r,o){let a=r?new URLSearchParams(r):void 0,s=a?`${i}?${a.toString()}`:i;return this.sendRequest("GET",e,n,s,void 0,o)}};function C(t,e){return t<e?[t,e]:[e,t]}function $(t){if(Array.isArray(t)&&t.length>=2){let e=t[0],n=t[1];if(typeof e=="string"&&typeof n=="string")return{token0:e,token1:n}}if(typeof t=="object"&&t!==null){let e=t,n=e.token0,i=e.token1;if(typeof n=="string"&&typeof i=="string")return{token0:n,token1:i}}throw new u("Unable to order trading symbols.","VALIDATION_ERROR",{value:t})}function S(t){return[t.collection,t.category,t.type,t.additionalKey].join("$")}function O(t){if(typeof t=="object")return{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey};let e=t.includes("|")?t.split("|"):t.split("$");if(e.length!==4||e.some(a=>a.length===0))throw new u("Invalid token class key: expected four non-empty parts","VALIDATION_ERROR",{tokenClassKey:t});let[n,i,r,o]=e;return{collection:n,category:i,type:r,additionalKey:o}}var W=class{constructor(e,n){d(this,"gateway",e);d(this,"symbols",n);d(this,"http");this.http=new k(e.httpRequestor,e.requestTimeoutMs??3e4)}async getPools(e){let n=await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,"/v2/trade","/pools",void 0,e?.signal===void 0?void 0:{signal:e.signal});if(!Array.isArray(n.data)||!n.data.every(it))throw new u("Backend returned an invalid pool list.","INVALID_CHAIN_RESPONSE",{data:n.data});return n.data}async getPool(e,n,i){return w(i),this.getBackend("/pool",await this.backendParams(e,n,i))}async getSlot0(e,n,i){return w(i),this.getBackend("/slot0",await this.backendParams(e,n,i))}async getCompositePool(e,n,i){w(i);let r=await V(this.symbols,e),o=await V(this.symbols,n),a=$(C(r,o));return this.getBackend("/composite-pool",{token0:a.token0,token1:a.token1,fee:String(i)})}async backendParams(e,n,i){return{token0:await V(this.symbols,e),token1:await V(this.symbols,n),fee:String(i)}}async getBackend(e,n){try{return(await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,"/v2/trade",e,n)).data}catch(i){throw i instanceof u?i:new u("Pool request failed.","HTTP_ERROR",{cause:i})}}};async function V(t,e){let n=await t.resolve(e);if(n.symbol.length>0)return n.symbol;throw new u("Token could not be resolved to a trading symbol.","SYMBOL_NOT_FOUND",{token:e})}function it(t){if(typeof t!="object"||t===null)return!1;let e=t,n=["fee","tickSpacing","protocolFees","tradingFees"],i=["token0CompositeKey","token1CompositeKey","creator","price","sqrtPrice","token0Tvl","token1Tvl"],r=["tick","tvlUsd","volume1d","volume7d","volume30d","trades1d","fee24h","apr1d","token0Price","token1Price"];return e.contractVersion==="v2"&&typeof e.token0=="string"&&typeof e.token1=="string"&&typeof e.poolName=="string"&&typeof e.poolRef=="string"&&n.every(o=>Re(e[o]))&&i.every(o=>rt(e[o]))&&r.every(o=>ot(e[o]))}function Re(t){return typeof t=="number"&&Number.isFinite(t)}function rt(t){return t===void 0||typeof t=="string"}function ot(t){return t===void 0||Re(t)}import f from"bignumber.js";var Q=class{constructor(e,n,i,r){d(this,"gateway",e);d(this,"symbols",n);d(this,"signer",i);d(this,"walletAddress",r);d(this,"http");this.http=new k(e.httpRequestor,e.requestTimeoutMs??3e4)}async getUserPositions(e){return(await this.get("/positions",{user:e})).data.map(i=>this.mapPosition(i))}async getPosition(e,n){let i=await this.symbols.orderPair(e.token0,e.token1),r=this.canonicalTicks(e.tickLower,e.tickUpper,i.flipped),o=await this.getNullable("/position",{token0:i.token0.symbol,token1:i.token1.symbol,fee:`${e.fee}`,owner:e.owner,tickLower:`${r.tickLower}`,tickUpper:`${r.tickUpper}`},n);return o===null?null:this.mapPosition(o.data)}async estimateAddLiquidity(e){return y(e.amount,"amount"),(await this.get("/add-liq-estimate",{token0:this.requestToken(e.token0),token1:this.requestToken(e.token1),fee:`${e.fee}`,tickLower:`${e.tickLower}`,tickUpper:`${e.tickUpper}`,amount:new f(e.amount).toFixed(),amountIsToken0:String(e.amountIsToken0)})).data}async estimateRemoveLiquidity(e){return y(e.liquidity,"liquidity"),(await this.get("/remove-liq-estimate",{token0:this.requestToken(e.token0),token1:this.requestToken(e.token1),fee:`${e.fee}`,tickLower:`${e.tickLower}`,tickUpper:`${e.tickUpper}`,liquidity:new f(e.liquidity).toFixed()})).data}async addLiquidityByTicks(e){w(e.fee);let n=await this.symbols.orderPair(e.token0,e.token1),i=this.canonicalTicks(e.tickLower,e.tickUpper,n.flipped);F(i.tickLower,i.tickUpper,e.fee),y(e.amount,"amount");let r=new f(e.amount).toFixed(),o={token0:n.token0.symbol,token1:n.token1.symbol,fee:e.fee,tickLower:i.tickLower,tickUpper:i.tickUpper,uniqueKey:this.uniqueKey(),...n.flipped!==e.amountIsToken0?{depositQuantityToken0:r}:{depositQuantityToken1:r}};return this.submit("AddLiquidity",o,{kind:"add",identity:{token0:n.token0.symbol,token1:n.token1.symbol,fee:e.fee,tickLower:i.tickLower,tickUpper:i.tickUpper}})}async addLiquidityByPrice(e){w(e.fee),this.rejectNumber(e.minPrice,"minPrice"),this.rejectNumber(e.maxPrice,"maxPrice");let n=new f(e.minPrice),i=new f(e.maxPrice);if(!n.isFinite()||!i.isFinite()||n.isLessThanOrEqualTo(0)||i.isLessThanOrEqualTo(0))throw new u("Price bounds must be finite and positive.","VALIDATION_ERROR");if(n.isGreaterThan(i))throw new u("minPrice must be less than or equal to maxPrice.","VALIDATION_ERROR");let r=this.tickSpacing(e.fee),o=me(se(n),r),a=pe(se(i),r);return this.addLiquidityByTicks({token0:e.token0,token1:e.token1,fee:e.fee,tickLower:o,tickUpper:a,amount:e.amount,amountIsToken0:e.amountIsToken0})}async removeLiquidity(e){w(e.fee);let n=await this.symbols.orderPair(e.token0,e.token1),i=this.canonicalTicks(e.tickLower,e.tickUpper,n.flipped);if(F(i.tickLower,i.tickUpper,e.fee),e.amount0!==void 0&&e.amount1!==void 0)throw new u("Provide at most one of amount0 or amount1.","VALIDATION_ERROR");e.amount0!==void 0&&y(e.amount0,"amount0"),e.amount1!==void 0&&y(e.amount1,"amount1");let r=e.amount0!==void 0?n.flipped?{withdrawalQuantityToken1:new f(e.amount0).toFixed()}:{withdrawalQuantityToken0:new f(e.amount0).toFixed()}:e.amount1!==void 0?n.flipped?{withdrawalQuantityToken0:new f(e.amount1).toFixed()}:{withdrawalQuantityToken1:new f(e.amount1).toFixed()}:{},o={token0:n.token0.symbol,token1:n.token1.symbol,fee:e.fee,tickLower:i.tickLower,tickUpper:i.tickUpper,uniqueKey:this.uniqueKey(),...r},a=e.amount0===void 0&&e.amount1===void 0;return this.submit("RemoveLiquidity",o,{kind:a?"removeFull":"removePartial",identity:{token0:n.token0.symbol,token1:n.token1.symbol,fee:e.fee,tickLower:i.tickLower,tickUpper:i.tickUpper}})}async collectPositionFees(e){w(e.fee);let n=await this.symbols.orderPair(e.token0,e.token1),i=this.canonicalTicks(e.tickLower,e.tickUpper,n.flipped);F(i.tickLower,i.tickUpper,e.fee);let r={token0:n.token0.symbol,token1:n.token1.symbol,fee:e.fee,tickLower:i.tickLower,tickUpper:i.tickUpper,uniqueKey:this.uniqueKey()};return this.submit("CollectPositionFees",r,{kind:"collect",identity:{token0:n.token0.symbol,token1:n.token1.symbol,fee:e.fee,tickLower:i.tickLower,tickUpper:i.tickUpper}})}async createPool(e){let n=e.startingPrice!==void 0,i=e.startingSqrtPrice!==void 0;if(n===i)throw new u("Provide exactly one of startingPrice or startingSqrtPrice.","VALIDATION_ERROR");w(e.fee);let[r,o]=await Promise.all([this.resolveCreateToken(e.token0),this.resolveCreateToken(e.token1)]),a=r.symbol>o.symbol,[s,c]=a?[o,r]:[r,o],m=n?e.startingPrice:e.startingSqrtPrice;this.rejectNumber(m,n?"startingPrice":"startingSqrtPrice");let l=new f(m);if(!l.isFinite()||l.isLessThanOrEqualTo(0))throw new u("Starting price must be finite and positive.","VALIDATION_ERROR");let T=a?new f(1).dividedBy(l):l,g={token0Key:s.classKey,token1Key:c.classKey,token0Symbol:s.symbol,token1Symbol:c.symbol,fee:e.fee,uniqueKey:this.uniqueKey(),...n?{startingPrice:T.toFixed()}:{startingSqrtPrice:T.toFixed()},...e.isPrivate===void 0?{}:{isPrivate:e.isPrivate},...e.privateAccess===void 0?{}:{privateAccess:e.privateAccess}},te=await this.submit("CreatePool",g,{kind:"createPool",token0:s.symbol,token1:c.symbol,fee:e.fee});return this.symbols.invalidate?.(),te}async submit(e,n,i){if(this.signer===void 0)throw u.noSignerError();let r=await this.signer.signObject(e,n),o=this.walletAddress===void 0?{}:{walletAddress:this.walletAddress},a=this.walletAddress,s=this.buildPositionConfirmation(i,a),c={...o,...s===void 0?{}:{positionConfirmation:s}};return this.gateway.submit(e,r,c)}buildPositionConfirmation(e,n){if(e===void 0)return;if(e.kind==="createPool"){let{token0:a,token1:s,fee:c}=e;return async m=>await this.getNullable("/pool",{token0:a,token1:s,fee:`${c}`},m)===null?{confirmed:!1}:{confirmed:!0,position:null}}if(n===void 0)return;let{kind:i,identity:r}=e,o;return async a=>{let s=await this.getPosition({...r,owner:n},a);if(o===void 0)return o={liquidity:new f(s?.liquidity??0),fees:new f(s?.fees0??0).plus(new f(s?.fees1??0))},i==="removeFull"&&s===null?{confirmed:!0,position:null}:{confirmed:!1};switch(i){case"add":return s!==null&&new f(s.liquidity).isGreaterThan(o.liquidity)?{confirmed:!0,position:s}:{confirmed:!1};case"removePartial":return s!==null&&new f(s.liquidity).isLessThan(o.liquidity)?{confirmed:!0,position:s}:{confirmed:!1};case"removeFull":return s===null?{confirmed:!0,position:null}:{confirmed:!1};case"collect":{if(s===null)return{confirmed:!1};let c=new f(s.fees0??0).plus(new f(s.fees1??0));return c.isLessThan(o.fees)?{confirmed:!0,position:s}:o.fees.isZero()&&c.isZero()?{confirmed:!0,position:s}:{confirmed:!1}}}}}async get(e,n,i){return this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,"/v2/trade",e,n,i===void 0?void 0:{signal:i})}async getNullable(e,n,i){try{return await this.get(e,n,i)}catch(r){if(this.isNotFound(r))return null;throw r}}isNotFound(e){return!(e instanceof u)||e.details===void 0?!1:e.details.status===404}mapPosition(e){return{token0Symbol:e.token0Symbol,token1Symbol:e.token1Symbol,...e.token0CompositeKey===void 0?{}:{token0CompositeKey:e.token0CompositeKey},...e.token1CompositeKey===void 0?{}:{token1CompositeKey:e.token1CompositeKey},fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,liquidity:e.liquidity,amount0:e.amount0,amount1:e.amount1,inRange:e.inRange,...e.currentTick===void 0?{}:{currentTick:e.currentTick},...e.sqrtPrice===void 0?{}:{sqrtPrice:e.sqrtPrice},pool:e.poolRef??e.pool??"",owner:e.owner,...e.fees0===void 0?{}:{fees0:e.fees0},...e.fees1===void 0?{}:{fees1:e.fees1}}}requestToken(e){return typeof e=="string"?e:S(e)}canonicalTicks(e,n,i){return i?{tickLower:-n,tickUpper:-e}:{tickLower:e,tickUpper:n}}tickSpacing(e){let n=L[e];if(n===void 0)throw new u(`Unsupported fee tier: ${e}.`,"VALIDATION_ERROR");return n}rejectNumber(e,n){if(typeof e=="number")throw new u(`Invalid ${n}: use a decimal string or BigNumber, not a JavaScript number`,"VALIDATION_ERROR")}uniqueKey(){return`gswap-sdk-${globalThis.crypto.randomUUID()}`}async resolveCreateToken(e){try{let n=typeof e=="object"?S(e):e,i=await this.symbols.resolve(n),r=this.tryParseClassKey(e);return{symbol:i.symbol,classKey:r??O({collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey})}}catch(n){if(!(n instanceof u)||n.code!=="UNKNOWN_TOKEN")throw n;let i;try{i=O(e)}catch{throw n}return{symbol:i.collection,classKey:i}}}tryParseClassKey(e){try{return O(e)}catch{return}}};import D from"bignumber.js";var Y=class{constructor(e,n,i){d(this,"dexBackendBaseUrl",e);d(this,"http",n);d(this,"symbols",i)}async quoteExactInput(e,n,i,r){return y(i,"amountIn"),this.quote(e,n,{amountIn:Se(i)},r)}async quoteExactOutput(e,n,i,r){return y(i,"amountOut"),this.quote(e,n,{amountOut:Se(i)},r)}async quote(e,n,i,r){lt(r);let o=await Pe(this.symbols,e),a=await Pe(this.symbols,n),s={tokenIn:o,tokenOut:a,...i};r!==void 0&&(s.fee=String(r));try{let c=await this.http.sendGetRequest(this.dexBackendBaseUrl,"/v2/trade","/quote",s);return st(c.data)}catch(c){throw ut(c,e,n,r)}}};function st(t){if(!at(t))throw new u("Backend returned an invalid quote.","INVALID_CHAIN_RESPONSE",{data:t});let e=t,n=e.currentPrice!==void 0?new D(e.currentPrice):Ie(e.currentSqrtPrice,e.tokenInIsToken0),i=e.newPrice!==void 0?new D(e.newPrice):Ie(e.newSqrtPrice,e.tokenInIsToken0),r=i.minus(n).dividedBy(n);return{contractVersion:e.contractVersion,fee:e.fee,amountIn:e.amountIn,amountOut:e.amountOut,...e.currentSqrtPrice===void 0?{}:{currentSqrtPrice:e.currentSqrtPrice},...e.newSqrtPrice===void 0?{}:{newSqrtPrice:e.newSqrtPrice},feeTier:e.fee,newTick:e.newTick,tradingFees:e.tradingFees,protocolFees:e.protocolFees,totalFees:e.totalFees,feeTokenSymbol:e.feeTokenSymbol,token0Symbol:e.token0Symbol,token1Symbol:e.token1Symbol,tokenInIsToken0:e.tokenInIsToken0,currentPrice:n,newPrice:i,priceImpact:r}}var Ee=D.clone({DECIMAL_PLACES:60});function Ie(t,e){let n=new Ee(t).pow(2);return e?n:new Ee(1).dividedBy(n)}function at(t){if(typeof t!="object"||t===null)return!1;let e=t,n=["amountIn","amountOut","tradingFees","protocolFees","totalFees","feeTokenSymbol","token0Symbol","token1Symbol"];return e.contractVersion==="v2"&&typeof e.fee=="number"&&Number.isFinite(e.fee)&&n.every(i=>typeof e[i]=="string")&&typeof e.newTick=="number"&&Number.isInteger(e.newTick)&&typeof e.tokenInIsToken0=="boolean"&&J(e.currentSqrtPrice)&&J(e.newSqrtPrice)&&J(e.currentPrice)&&J(e.newPrice)&&(e.currentSqrtPrice!==void 0||e.currentPrice!==void 0)&&(e.newSqrtPrice!==void 0||e.newPrice!==void 0)}function J(t){if(t===void 0)return!0;if(typeof t!="string")return!1;try{let e=new D(t);return e.isFinite()&&e.isGreaterThan(0)}catch{return!1}}function ut(t,e,n,i){if(t instanceof u){let r=dt(t.details),o=ct(t.details)??t.message;return r===404||/no pool|no pools|pool does not exist/iu.test(o)?u.noPoolAvailableError(e,n,i):r===400&&/insufficient liquidity/iu.test(o)?u.insufficientLiquidityError(e,n,i):t}return new u("Quote request failed.","HTTP_ERROR",{cause:t,tokenIn:e,tokenOut:n,fee:i})}function dt(t){let e=t?.status;return typeof e=="number"?e:void 0}function ct(t){let e=t?.message;if(typeof e=="string")return e;let n=t?.body;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=n.message;return typeof i=="string"?i:void 0}function lt(t){if(t!==void 0&&!B.some(e=>Number(e)===Number(t)))throw new u(`Invalid fee tier: ${t}`,"VALIDATION_ERROR",{fee:t})}function Se(t){return new D(t).toFixed()}async function Pe(t,e){let n=await t.resolve(e);if(n.symbol.length>0)return n.symbol;throw new u("Token could not be resolved to a trading symbol.","SYMBOL_NOT_FOUND",{token:e})}var mt=6e4,z=class{constructor(e){d(this,"gateway",e);d(this,"cachedSymbols");d(this,"cachedAt",0);d(this,"refreshInFlight");d(this,"http");this.http=new k(e.httpRequestor,e.requestTimeoutMs)}async list(){return this.cachedSymbols!==void 0&&Date.now()-this.cachedAt<mt?this.cachedSymbols:this.refreshInFlight!==void 0?this.refreshInFlight:(this.refreshInFlight=this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,"/v2/trade","/symbols").then(e=>pt(e.data)).then(e=>(this.cachedSymbols=e,this.cachedAt=Date.now(),e)).finally(()=>{this.refreshInFlight=void 0}),this.refreshInFlight)}invalidate(){this.cachedSymbols=void 0,this.cachedAt=0}async refresh(){return this.invalidate(),this.refreshInFlight=void 0,this.list()}async resolve(e){let n=await this.list(),i=typeof e=="string"?yt(e)?S(O(e)):void 0:S(e),r=n.find(o=>o.symbol===e||i!==void 0&&S(o)===i);if(r===void 0){n=await this.refresh();let o=n.find(a=>a.symbol===e||i!==void 0&&S(a)===i);if(o===void 0)throw u.unknownTokenError(e);return o}return r}async orderPair(e,n){let[i,r]=await Promise.all([this.resolve(e),this.resolve(n)]),[o,a]=C(i.symbol,r.symbol);return{token0:o===i.symbol?i:r,token1:a===r.symbol?r:i,flipped:o!==i.symbol}}};function pt(t){if(!Array.isArray(t)||!t.every(ft))throw new u("Backend returned an invalid symbol list.","INVALID_CHAIN_RESPONSE",{data:t});return t}function ft(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.symbol=="string"&&typeof e.collection=="string"&&typeof e.category=="string"&&typeof e.type=="string"&&typeof e.additionalKey=="string"&&typeof e.decimals=="number"&&Number.isInteger(e.decimals)&&e.decimals>=0}function yt(t){return t.includes("|")||t.includes("$")}import wt from"bignumber.js";var ht=/^[A-Za-z0-9._:-]{1,128}$/u,Z=class{constructor(e,n,i,r){d(this,"gateway",e);d(this,"symbols",n);d(this,"signer",i);d(this,"walletAddress",r)}async swap(e,n,i,r){w(i);let o=await this.buildRequestTradeDto(e,n,i,r);if(this.signer===void 0)throw u.noSignerError();let a=await this.signer.signObject("RequestTrade",o),s=this.walletAddress===void 0?{}:{walletAddress:this.walletAddress};return this.gateway.submit("RequestTrade",a,s)}async confirmSwap(e,n){if(!ht.test(e))throw new u('uniqueKey must be 1-128 characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".',"VALIDATION_ERROR",{uniqueKey:e});return new q({method:"RequestTrade",uniqueKey:e,transactionId:null,mode:"queued",result:void 0,dexBackendBaseUrl:this.gateway.dexBackendBaseUrl,httpRequestor:this.gateway.httpRequestor,requestTimeoutMs:this.gateway.requestTimeoutMs}).confirm({initialDelayMs:0,...n})}async buildRequestTradeDto(e,n,i,r){let o=await Ae(this.symbols,e),a=await Ae(this.symbols,n),s=$(C(o,a)),c=o===s.token0,m={token0:s.token0,token1:s.token1,fee:i,uniqueKey:`gswap-sdk-${globalThis.crypto.randomUUID()}`};if("exactIn"in r){let l=r.exactIn;if(l===void 0)throw new u("exactIn is required for an exact-input swap.","VALIDATION_ERROR");y(l,"exactIn"),m[c?"sell0Qty":"sell1Qty"]=X(l),r.amountOutMinimum!==void 0&&(y(r.amountOutMinimum,"amountOutMinimum",!0),m.amountOutMinimum=X(r.amountOutMinimum))}else{let l=r.exactOut;if(l===void 0)throw new u("exactOut is required for an exact-output swap.","VALIDATION_ERROR");y(l,"exactOut"),m[c?"buy1Qty":"buy0Qty"]=X(l),r.amountInMaximum!==void 0&&(y(r.amountInMaximum,"amountInMaximum",!0),m.amountInMaximum=X(r.amountInMaximum))}return m}};function X(t){return new wt(t).toFixed()}async function Ae(t,e){let n=await t.resolve(e);if(n.symbol.length>0)return n.symbol;throw new u("Token could not be resolved to a trading symbol.","SYMBOL_NOT_FOUND",{token:e})}var Ne={prod:{dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com"},stage:{dexBackendBaseUrl:"https://swap-backend.stage.defi.ovh.gala.com"}};var ve=class{constructor(e){d(this,"dexBackendBaseUrl");d(this,"chainCallTimeoutMs");d(this,"signer");d(this,"walletAddress");d(this,"gateway");d(this,"symbols");d(this,"quoting");d(this,"pools");d(this,"positions");d(this,"swaps");d(this,"assets");let n=Ne[e?.env??"prod"];this.dexBackendBaseUrl=gt(e?.dexBackendBaseUrl??n.dexBackendBaseUrl),this.chainCallTimeoutMs=e?.chainCallTimeoutMs??3e4,this.signer=e?.signer,this.walletAddress=e?.walletAddress;let i=new k(e?.httpRequestor,this.chainCallTimeoutMs);this.gateway=new H({dexBackendBaseUrl:this.dexBackendBaseUrl,chainCallTimeoutMs:this.chainCallTimeoutMs,...e?.httpRequestor===void 0?{}:{httpRequestor:e.httpRequestor},...this.walletAddress===void 0?{}:{walletAddress:this.walletAddress}}),this.symbols=new z(this.gateway),this.quoting=new Y(this.dexBackendBaseUrl,i,this.symbols),this.pools=new W(this.gateway,this.symbols),this.positions=new Q(this.gateway,this.symbols,this.signer,this.walletAddress),this.swaps=new Z(this.gateway,this.symbols,this.signer,this.walletAddress),this.assets=new G(this.dexBackendBaseUrl,i)}};function gt(t){return t.replace(/\/$/u,"")}import{serialize as ee,signatures as Ce}from"@gala-chain/api";function kt(t,e){let n={};n[t]=[];function i(o){let a=n[o];if(!a)throw new Error(`Missing EIP-712 type definition for ${o}`);return a}function r(o,a,s,c=!1){if(Array.isArray(a)){let m=a.length>0?r(o,a[0],s,!0):"string";c||i(s).push({name:o,type:(m??o)+"[]"})}else if(typeof a=="object"&&a!==null){if(n[o])throw new Error("Name collisions not yet supported");n[o]=[],Object.entries(a).forEach(([m,l])=>{r(m,l,o)}),c||i(s).push({name:o,type:o})}else{let m;switch(typeof a){case"string":m="string";break;case"number":m="int256";break;case"boolean":m="bool";break;case"bigint":case"symbol":case"undefined":case"function":case"object":throw new Error(`Unsupported type, ${typeof a}, value: ${Object.prototype.toString.call(a)}`)}if(c)return m;i(s).push({name:o,type:m})}}return Object.entries(e).forEach(([o,a])=>{r(o,a,t)}),n}var ue={name:"ethereum",chainId:1},qe=new Set(["RequestTrade","AddLiquidity","RemoveLiquidity","CollectPositionFees"]);function b(t,e){return typeof t[e]=="number"?t[e]:0}function bt(t){return{...t,amount0Desired:b(t,"amount0Desired"),amount0Min:b(t,"amount0Min"),amount1Desired:b(t,"amount1Desired"),amount1Min:b(t,"amount1Min"),positionId:t.positionId??""}}function Tt(t){return{...t,amount:b(t,"amount"),amount0Min:b(t,"amount0Min"),amount1Min:b(t,"amount1Min"),positionId:t.positionId??""}}function Rt(t){return{...t,amount0Requested:b(t,"amount0Requested"),amount1Requested:b(t,"amount1Requested"),positionId:t.positionId??""}}var Et={AddLiquidity:bt,RemoveLiquidity:Tt,CollectPositionFees:Rt};function _e(t,e){let n=Et[t],i=n?n(e):e,r=kt(t,i);return{completedDto:i,types:r}}var It=`Ethereum Signed Message:
2
- `;function Le(t){let e={...t};delete e.prefix;let n=ee(e);return It+String(new TextEncoder().encode(n).length)}function St(){let e=globalThis.window?.gala;if(!e)throw new u("Gala wallet is not available. Please ensure the Gala wallet is connected.","GALA_WALLET_NOT_AVAILABLE");return e}function Pt(t){if(typeof t!="string")throw new u("Wallet returned an invalid signature.","INVALID_SIGNATURE");if(!/^[0-9a-fA-F]{130}$/u.test(t))throw new u("Wallet returned an invalid native signature.","INVALID_SIGNATURE");return t}function Be(t){if(typeof t!="string"||!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(t))throw new u("Wallet returned an invalid personal-sign signature.","INVALID_SIGNATURE");return t}function Me(t,e){let n=e&&t.startsWith("eth|")?t.slice(4):t;if(!/^0x[0-9a-fA-F]{40}$/u.test(n))throw new u("Wallet address must be the selected Ethereum account in 0x-prefixed form.","VALIDATION_ERROR",{type:"INVALID_WALLET_ADDRESS",value:t});return`0x${n.slice(2).toLowerCase()}`}function At(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;if(typeof t=="object"&&t!==null&&"message"in t){let e=t.message;return typeof e=="string"?e:""}return""}function Nt(t){return/unsupported|unknown scheme/i.test(At(t))}function de(t,e,n,i){let r=Le(e),o={...e,prefix:r},a=i!==void 0?[ee(o),n,i]:[ee(e),n];return t.request({method:i!==void 0?"gala_signChainDto":"personal_sign",params:a}).then(s=>({...o,signature:Be(s)}))}function vt(t,e,n,i){let{completedDto:r,types:o}=_e(e,n),a=Le(r),s={...r,prefix:a},m={domain:ue,types:{...o,EIP712Domain:[{name:"name",type:"string"},{name:"chainId",type:"uint256"}]},primaryType:e,message:s};return t.request({method:"eth_signTypedData_v4",params:[i,JSON.stringify(m)]}).then(l=>({...s,types:o,domain:ue,signature:Be(l)}))}var Oe=class{constructor(e){d(this,"keyBuffer");this.keyBuffer=Ce.normalizePrivateKey(e)}signObject(e,n){let i=Ce.getSignature(n,this.keyBuffer);return Promise.resolve({...n,signature:i})}},xe=class{constructor(e,n={}){d(this,"walletAddress");d(this,"effectiveScheme");this.walletAddress=Me(e,!0),this.effectiveScheme=n.scheme??"native"}async signObject(e,n){let i=St();if(this.effectiveScheme==="personal-sign")return de(i,n,this.walletAddress,e);try{let r=await i.request({method:"gala_signChainDto",params:[ee(n),this.walletAddress,e,"native"]});return{...n,signature:Pt(r)}}catch(r){if(!Nt(r))throw r;return this.effectiveScheme="personal-sign",de(i,n,this.walletAddress,e)}}},De=class{constructor(e,n,i={}){d(this,"provider",e);d(this,"walletAddress");d(this,"scheme");this.walletAddress=Me(n,!1),this.scheme=i.scheme??"personal-sign"}signObject(e,n){return this.scheme==="eip712"&&qe.has(e)?vt(this.provider,e,n,this.walletAddress):de(this.provider,n,this.walletAddress)}};export{B as ALL_FEE_TIERS,G as Assets,De as BrowserWalletSigner,H as ChainGateway,He as FEE_TIER,I as GC_MAX_TICK,E as GC_MIN_TICK,Ne as GSWAP_ENVIRONMENTS,ve as GSwap,u as GSwapSDKError,xe as GalaWalletSigner,W as Pools,Q as Positions,Oe as PrivateKeySigner,Y as Quoting,q as SubmittedTransaction,Z as Swaps,z as Symbols,L as TICK_SPACING_BY_FEE,me as alignTickDown,pe as alignTickUp,F as assertTickRange,S as compositeKeyOf,R as getObjectProperty,p as getStringProperty,C as orderSymbols,re as parseJson,O as parseTokenClassKey,$ as readOrderedSymbols,Bt as sqrtPriceToTick,se as tickFromPrice,le as tickToSqrtPrice,w as validateFee,y as validateNumericAmount,jt as validatePriceValues,$t as validateTickRange,Vt as validateTickSpacing,Ht as validateTokenDecimals,ye as validateWalletAddress};
1
+ import e from"bignumber.js";import{Decimal as t}from"decimal.js";import n from"debug";import{serialize as r,signatures as i}from"@gala-chain/api";function a(e){"@babel/helpers - typeof";return a=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},a(e)}function o(e,t){if(a(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(a(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function s(e){var t=o(e,`string`);return a(t)==`symbol`?t:t+``}function c(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var l=class e extends Error{constructor(e,t,n,r,i){super(e),this.code=t,this.details=n,c(this,`chainMessage`,void 0),c(this,`retryAfterMs`,void 0),this.name=`GSwapSDKError`,this.chainMessage=r,this.retryAfterMs=i}static noSignerError(){return new e(`This method requires a signer. Please provide a signer to the GSwap constructor.`,`NO_SIGNER`)}static noWalletAddressError(){return new e(`Cannot confirm this write: no walletAddress was provided to the GSwap constructor, so the resulting position cannot be looked up to confirm it landed on chain.`,`NO_WALLET_ADDRESS`)}static noPoolAvailableError(t,n,r){return new e(`No pool is available for the requested pair.`,`NO_POOL_AVAILABLE`,{tokenIn:t,tokenOut:n,...r===void 0?{}:{fee:r}})}static insufficientLiquidityError(t,n,r){return new e(`The selected pool has insufficient liquidity for the requested quote.`,`INSUFFICIENT_LIQUIDITY`,{tokenIn:t,tokenOut:n,...r===void 0?{}:{fee:r}})}static fromGatewayBounce(t,n,r,i){let a={status:r,chainMessage:n};i!==void 0&&(a.retryAfterMs=i);let o=t===`CHAIN_DISPATCH_FAILED`?n:`Gateway rejected ${t}: ${n}`;return new e(o,t,a,n,i)}static fromChainError(t,n,r){return new e(`GalaChain error ${t}: ${n}`,t,{...r,errorKey:t,message:n},n)}static unknownTokenError(t){let n=typeof t==`string`?t:JSON.stringify(t);return new e(`Token ${n} has no trading symbol on the new DEX contract (no gcdex pool includes it yet).`,`UNKNOWN_TOKEN`,{token:t})}static confirmationTimeoutError(t,n){return new e(`Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.`,`CONFIRMATION_TIMEOUT`,{uniqueKey:t,...n===void 0?{}:{cause:n}})}static async fromErrorResponse(t,n){let r=await n.text(),i=f(r),a=u(i,`error`),o=d(a,`ErrorKey`),s=d(a,`Message`);return o!==void 0&&s!==void 0?new e(`GalaChain Error ${o} from ${t}: ${s}`,o,{message:s,errorKey:o,status:n.status,body:i,url:t},s):new e(`Unexpected HTTP Error ${n.status} from ${t}`,`HTTP_ERROR`,{status:n.status,body:i??r,url:t})}};function u(e,t){if(typeof e!=`object`||!e||!(t in e))return;let n=e[t];return typeof n==`object`&&n?n:void 0}function d(e,t){if(typeof e!=`object`||!e||!(t in e))return;let n=e[t];return typeof n==`string`?n:void 0}function f(e){try{return JSON.parse(e)}catch{return}}let p=/* @__PURE__ */ function(e){return e[e.PERCENT_00_00=0]=`PERCENT_00_00`,e[e.PERCENT_00_05=500]=`PERCENT_00_05`,e[e.PERCENT_00_30=3e3]=`PERCENT_00_30`,e[e.PERCENT_01_00=1e4]=`PERCENT_01_00`,e}({});const m={0:200,500:10,3e3:60,1e4:200},h=[0,500,3e3,1e4],g=-887272,_=887272,v=e.clone({DECIMAL_PLACES:60,ROUNDING_MODE:e.ROUND_DOWN}),y=t.clone({precision:60});function b(t){return new e(new y(1.0001).pow(t/2).toString())}function ee(e){let t;try{t=new v(e)}catch{return NaN}if(!t.isFinite()||t.isLessThanOrEqualTo(0))return NaN;let n=Math.log(t.toNumber()**2)/Math.log(1.0001);if(!Number.isFinite(n))return NaN;let r=Math.min(_,Math.max(g,Math.floor(n)));for(;r<887272&&b(r+1).isLessThanOrEqualTo(t);)r+=1;for(;r>-887272&&b(r).isGreaterThan(t);)--r;return r}function x(t){let n=typeof t==`string`?t:typeof t==`number`||e.isBigNumber(t)?t.toString():`NaN`,r=new y(n);if(!r.isFinite()||r.lessThanOrEqualTo(0)||!Number.isFinite(r.toNumber()))return NaN;let i=r.ln().dividedBy(new y(1.0001).ln()).floor().toNumber();return Number.isFinite(i)?i:NaN}function S(e,t){return ne(t),Math.floor(e/t)*t}function te(e,t){return ne(t),Math.ceil(e/t)*t}function C(e,t,n){let r=m[n];if(r===void 0)throw RangeError(`Unsupported fee tier: ${n}`);if(!Number.isInteger(e)||!Number.isInteger(t))throw RangeError(`Ticks must be integers`);if(e<-887272||t>887272||e>=t)throw RangeError(`Tick range must satisfy ${g} <= lower < upper <= ${_}`);if(e%r!==0||t%r!==0)throw RangeError(`Ticks must be aligned to spacing ${r}`)}function ne(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`Tick spacing must be positive`)}function w(t,n,r=!1){if(typeof t==`number`)throw new l(`Invalid ${n}: use a decimal string or BigNumber, not a JavaScript number`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,parameterName:n,value:t,reason:`number_input`});let i;try{i=e(t)}catch{i=e(NaN)}if(!i.isFinite())throw new l(`Invalid ${n}: must be a finite number`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,parameterName:n,value:t,reason:`not_finite`});if(!r&&i.isZero())throw new l(`Invalid ${n}: must be positive`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,parameterName:n,value:t,reason:`zero_not_allowed`});if(i.isNegative())throw new l(`Invalid ${n}: must be ${r?`non-negative`:`positive`}`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,parameterName:n,value:t,reason:`negative`})}function re(t,n,r){if([t,n,r].some(e=>typeof e==`number`))throw new l(`Invalid price values: use decimal strings or BigNumber values, not JavaScript numbers`,`VALIDATION_ERROR`,{type:`INVALID_NUMERIC_AMOUNT`,reason:`number_input`});let i=t=>{try{return e(t)}catch{return e(NaN)}},a=i(t),o=i(n),s=i(r);if(s=s.isFinite()?s:e(0xde0b6b3a7640000),!a.isFinite()||!o.isFinite()||!s.isFinite()||!a.isPositive()||!o.isPositive()||!s.isPositive())throw new l(`Invalid price values: all prices must be finite and positive`,`VALIDATION_ERROR`,{type:`INVALID_PRICE_VALUES`,spotPrice:t,lowerPrice:n,upperPrice:r});if(o.isGreaterThan(s))throw new l(`Invalid price range: lower price must be less than or equal to upper price`,`VALIDATION_ERROR`,{type:`INVALID_PRICE_RANGE`,lowerPrice:n,upperPrice:r})}function ie(e,t){if(e<0||!Number.isInteger(e))throw new l(`Invalid ${t}: must be a non-negative integer`,`VALIDATION_ERROR`,{type:`INVALID_TOKEN_DECIMALS`,parameterName:t,value:e})}function ae(e,t){if(!Number.isInteger(e)||!Number.isInteger(t))throw new l(`Invalid tick values: ticks must be integers`,`VALIDATION_ERROR`,{type:`INVALID_TICK_VALUES`,tickLower:e,tickUpper:t});if(e>=t)throw new l(`Invalid tick range: tickLower must be less than tickUpper`,`VALIDATION_ERROR`,{type:`INVALID_TICK_RANGE`,tickLower:e,tickUpper:t});if(e<-887272||t>887272)throw new l(`Invalid tick range: ticks must be between ${g} and ${_}`,`VALIDATION_ERROR`,{type:`INVALID_TICK_BOUNDS`,tickLower:e,tickUpper:t,minTick:g,maxTick:_})}function T(e){if(!h.some(t=>Number(t)===e))throw new l(`Invalid fee tier: must be one of 0, 500, 3000, or 10000`,`VALIDATION_ERROR`,{type:`INVALID_FEE`,value:e})}function oe(e){if(!Number.isInteger(e)||e<=0)throw new l(`Invalid tick spacing: must be a positive integer`,`VALIDATION_ERROR`,{type:`INVALID_TICK_SPACING`,value:e})}function se(e){if(e===void 0)throw new l(`Invalid wallet address: No wallet address provided`,`VALIDATION_ERROR`,{type:`MISSING_WALLET_ADDRESS`,hint:`Either provide a wallet address to the function you are calling, or set one when instantiating GSwapSDK`});if(!e||typeof e!=`string`||e.trim().length===0)throw new l(`Invalid wallet address: must be a non-empty string`,`VALIDATION_ERROR`,{type:`INVALID_WALLET_ADDRESS`,value:e})}var E=class{constructor(e,t){this.dexBackendBaseUrl=e,this.httpClient=t}async getUserAssets(e,t=1,n=10){if(se(e),!Number.isInteger(t)||t<1)throw new l(`Invalid page: must be a positive integer`,`VALIDATION_ERROR`,{page:t});if(!Number.isInteger(n)||n<1||n>100)throw new l(`Invalid limit: must be an integer between 1 and 100`,`VALIDATION_ERROR`,{limit:n});return ce(await this.httpClient.sendGetRequest(this.dexBackendBaseUrl,`/user/assets`,``,{address:e,page:t.toString(),limit:n.toString()}))}};function ce(e){let t=u(e,`data`),n=t?.token;if(!Array.isArray(n)||!n.every(le))throw new l(`Backend returned an invalid user assets response.`,`INVALID_CHAIN_RESPONSE`,{data:e});let r=t?.count;return{tokens:n.map(e=>({...e,decimals:parseInt(e.decimals,10)})),count:typeof r==`number`?r:0}}function 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`}async function D(e,t,n,r){let i=new AbortController,a=setTimeout(()=>i.abort(),r),o=n.signal,s=()=>i.abort();o?.addEventListener(`abort`,s,{once:!0});try{return await e(t,{...n,signal:i.signal})}catch(e){throw i.signal.aborted?new l(`Request timed out after ${r} ms.`,`REQUEST_TIMEOUT`,{url:t,timeoutMs:r,cause:e}):e}finally{clearTimeout(a),o?.removeEventListener(`abort`,s)}}async function O(e){let t=await e.text();return f(t)??t}function k(e,t){let n=e.headers;if(n===void 0)return;if(ue(n)){let e=n.get(t);return e===null||e===``?void 0:e}let r=Object.entries(n).find(([e])=>e.toLowerCase()===t.toLowerCase())?.[1];return r===void 0||r===``?void 0:r}function A(e){let t=k(e,`retry-after`);if(t===void 0)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n*1e3:void 0}function j(e,t=`x-block-number`){let n=k(e,t);if(n===void 0)return;let r=Number(n);return Number.isInteger(r)&&r>=0?r:void 0}function ue(e){return`get`in e&&typeof e.get==`function`}var M=class{constructor(e){c(this,`method`,void 0),c(this,`uniqueKey`,void 0),c(this,`transactionId`,void 0),c(this,`blockNumber`,void 0),c(this,`mode`,void 0),c(this,`result`,void 0),c(this,`backendBaseUrl`,void 0),c(this,`requestor`,void 0),c(this,`requestTimeoutMs`,void 0),c(this,`positionConfirmation`,void 0),this.method=e.method,this.uniqueKey=e.uniqueKey,this.transactionId=e.transactionId,this.blockNumber=e.blockNumber??null,this.mode=e.mode,this.result=e.result,this.backendBaseUrl=e.dexBackendBaseUrl.replace(/\/$/u,``),this.requestor=e.httpRequestor,this.requestTimeoutMs=e.requestTimeoutMs??3e4,this.positionConfirmation=e.positionConfirmation}async confirm(e){return this.method===`RequestTrade`?this.confirmApplied(e):this.confirmPosition(e)}async confirmApplied(e){let t=N(e,3e3);await t.waitForRead();let n=`${this.backendBaseUrl}/v1/chain/apply-results/${encodeURIComponent(this.uniqueKey)}?channel=asset&contract=dex-contract`,r;for(;;){let e,i;try{e=await D(this.requestor,n,{method:`GET`},this.requestTimeoutMs),i=await O(e)}catch(e){if(r=e,!await t.waitForRead())break;continue}if(e.status===200)return this.readAppliedResult(e,i,n);if(e.status===404||e.status===429||fe(e.status)){if(e.status===429){let n=A(e);if(n!==void 0){if(!await t.waitForRead(n))break;continue}}}else throw new l(pe(i),`CONFIRMATION_FAILED`,{status:e.status,body:i,url:n});if(!await t.waitForRead())break}throw l.confirmationTimeoutError(this.uniqueKey,r)}readAppliedResult(e,t,n){let r=me(t),i=r?.Status,a=k(e,`x-apply-transaction-id`)??null,o=j(e,`x-apply-block-number`)??null;if(i===0)throw l.fromChainError(d(r,`ErrorKey`)??`CHAIN_ERROR`,d(r,`Message`)??`The chain rejected this trade.`,{uniqueKey:this.uniqueKey,applyTransactionId:a,blockNumber:o,status:e.status,body:t,url:n});if(i!==1)throw P(e,t,n);let s=de(r?.Data);if(s===void 0)throw P(e,t,n);return{uniqueKey:this.uniqueKey,transactionId:a,blockNumber:o,requestTransactionId:this.transactionId,result:s}}async confirmPosition(e){if(this.positionConfirmation===void 0)throw l.noWalletAddressError();let t=N(e,0);for(await t.waitForRead();;){let e=new AbortController,n=setTimeout(()=>e.abort(),this.requestTimeoutMs);try{let t=await this.positionConfirmation(e.signal);if(t.confirmed)return t.position}finally{clearTimeout(n)}if(!await t.waitForRead())break}throw l.confirmationTimeoutError(this.uniqueKey)}};function N(e,t){let n=Math.max(0,e?.timeoutMs??6e4),r=Math.max(500,e?.pollIntervalMs??2e3),i=Math.max(0,e?.initialDelayMs??t),a=Date.now()+n,o=!0,s=0;return{async waitForRead(e){if(o){o=!1;let e=Math.max(0,a-Date.now());return await he(Math.min(i,e)),!0}let t=Math.min(8e3,r*2**Math.min(s,5));s+=1;let n=e===void 0?ge(t):e;return Date.now()+n>a?!1:(await he(n),!0)}}}function de(e){let t=me(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 P(e,t,n){return new l(`Transaction confirmation returned a malformed body`,`CONFIRMATION_FAILED`,{status:e.status,body:t,url:n})}function fe(e){return e===500||e===502||e===503||e===504}function pe(e){return d(e,`message`)??d(e,`Message`)??d(u(e,`error`),`message`)??d(u(e,`error`),`Message`)??(typeof e==`string`?e:`Transaction confirmation failed`)}function me(e){return typeof e==`object`&&e?e:void 0}function he(e){return new Promise(t=>setTimeout(t,e))}function ge(e){return Math.max(0,Math.round(e*(.9+Math.random()*.2)))}var _e=class{constructor(e){c(this,`requestor`,void 0),c(this,`walletAddress`,void 0),c(this,`chainCallTimeoutMs`,void 0),c(this,`requestTimeoutMs`,void 0),c(this,`dexBackendBaseUrl`,void 0),this.dexBackendBaseUrl=ve(e.dexBackendBaseUrl),this.requestor=e.httpRequestor??fetch.bind(globalThis),this.walletAddress=e.walletAddress,this.chainCallTimeoutMs=e.chainCallTimeoutMs??3e4,this.requestTimeoutMs=this.chainCallTimeoutMs}async submit(e,t,n){if(e===`Trade`)throw new l(`The synchronous Trade method was removed; swaps are queued through RequestTrade.`,`METHOD_NOT_SUPPORTED`,{method:e});let r=`${this.dexBackendBaseUrl}/v1/chain/asset/dex-contract/${e}`,i={"content-type":`application/json`},a=n?.walletAddress??this.walletAddress;a!==void 0&&(i[`X-Wallet-Address`]=a);let o;try{o=await D(this.requestor,r,{method:`POST`,headers:i,body:JSON.stringify(t)},this.chainCallTimeoutMs)}catch(e){throw e instanceof l&&e.code===`REQUEST_TIMEOUT`?new l(`The submission outcome is unknown because the gateway request timed out. Confirm before retrying.`,`SUBMISSION_OUTCOME_UNKNOWN`,{uniqueKey:d(t,`uniqueKey`)??``,cause:e}):e}let s=await O(o);if(!o.ok)throw ye(o,s,r);let c=I(s),u=I(c?.data??c?.Data);if(u===void 0)throw F(o,s,r,`Expected a data object.`);let f=d(u,`transactionId`),p=d(u,`mode`),m=u.transactionId,h=u.blockNumber,g=`Gateway response must contain data.mode="sync" with data.result, or data.mode="queued".`;if(p!==`sync`&&p!==`queued`||`transactionId`in u&&typeof m!=`string`||h!=null&&!L(h))throw F(o,s,r,g);if(e===`RequestTrade`&&p===`sync`)throw F(o,s,r,`The gateway executed RequestTrade synchronously, which this SDK refuses; RequestTrade must be queued.`);if(e===`RequestTrade`&&p===`queued`){let e=d(t,`uniqueKey`);if(`uniqueKey`in u&&(typeof u.uniqueKey!=`string`||u.uniqueKey!==e))throw F(o,s,r,`Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey.`)}else if(p===`queued`||!(`result`in u))throw F(o,s,r,g);if(p===`sync`){let e=I(u.result);if(e!==void 0){let t=e.Status;if(t!==void 0&&t!==1)throw l.fromChainError(d(e,`ErrorKey`)??`CHAIN_ERROR`,d(e,`Message`)??`The chain rejected this write.`,{status:o.status,body:s,url:r})}}let _=d(t,`uniqueKey`)??``,v=k(o,`x-transaction-id`),y=f===void 0||f===``?v:f,b=h==null?j(o):L(h)?h:void 0;return new M({method:e,uniqueKey:_,transactionId:y===void 0||y===``?null:y,blockNumber:b??null,mode:p,result:p===`queued`?void 0:u.result,dexBackendBaseUrl:this.dexBackendBaseUrl,httpRequestor:this.requestor,requestTimeoutMs:this.chainCallTimeoutMs,...n?.positionConfirmation===void 0?{}:{positionConfirmation:n.positionConfirmation}})}get httpRequestor(){return this.requestor}};function ve(e){return e.replace(/\/$/u,``)}function F(e,t,n,r){return new l(r,`INVALID_GATEWAY_RESPONSE`,{status:e.status,body:t,url:n})}function ye(e,t,n){let r=I(t),i=u(t,`error`),a=d(r,`code`)??d(i,`code`)??d(i,`ErrorKey`)??`HTTP_ERROR`,o=d(r,`message`)??d(i,`message`)??d(i,`Message`)??(typeof t==`string`?t:`Gateway request failed with HTTP ${e.status}`),s=e.status===429?A(e):void 0;return a===`HTTP_ERROR`?new l(o,a,{status:e.status,body:t,url:n}):l.fromGatewayBounce(a,o,e.status,s)}function I(e){return typeof e==`object`&&e?e:void 0}function L(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}const R=n(`GSWAP_SDK`);var z=class{constructor(e=fetch,t=3e4){this.httpRequestor=e,this.timeoutMs=t}async sendRequest(e,t,n,r,i,a){let o=`${t}${n}${r}`;R(`Sending request to ${o} with body:`,i);let s=await D(this.httpRequestor,o,{method:e,headers:{"Content-Type":`application/json`,"User-Agent":`GalaChain-SDK/1.0.0`},...i?{body:JSON.stringify(i)}:{},...a?.signal===void 0?{}:{signal:a.signal}},this.timeoutMs);if(!s.ok)throw await l.fromErrorResponse(o,s);let c=await O(s);return R(`Response from ${t}${n}${r}:`,c),c}async sendPostRequest(e,t,n,r){return this.sendRequest(`POST`,e,t,n,r)}async sendGetRequest(e,t,n,r,i){let a=r?new URLSearchParams(r):void 0,o=a?`${n}?${a.toString()}`:n;return this.sendRequest(`GET`,e,t,o,void 0,i)}};function B(e,t){return e<t?[e,t]:[t,e]}function V(e){if(Array.isArray(e)&&e.length>=2){let t=e[0],n=e[1];if(typeof t==`string`&&typeof n==`string`)return{token0:t,token1:n}}if(typeof e==`object`&&e){let t=e,n=t.token0,r=t.token1;if(typeof n==`string`&&typeof r==`string`)return{token0:n,token1:r}}throw new l(`Unable to order trading symbols.`,`VALIDATION_ERROR`,{value:e})}function H(e){return[e.collection,e.category,e.type,e.additionalKey].join(`$`)}function U(e){if(typeof e==`object`)return{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey};let t=e.includes(`|`)?`|`:`$`,n=e.split(t),r=n.slice(-3),i=n.slice(0,-3).join(t);if(n.length<4||i.length===0||r.some(e=>e.length===0))throw new l(`Invalid token class key: expected a collection followed by category, type and additionalKey`,`VALIDATION_ERROR`,{tokenClassKey:e});let[a,o,s]=r;return{collection:i,category:a,type:o,additionalKey:s}}var W=class{constructor(e,t){this.gateway=e,this.symbols=t,c(this,`http`,void 0),this.http=new z(e.httpRequestor,e.requestTimeoutMs??3e4)}async getPools(e){let t=await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,`/pools`,void 0,e?.signal===void 0?void 0:{signal:e.signal});if(!Array.isArray(t.data)||!t.data.every(be))throw new l(`Backend returned an invalid pool list.`,`INVALID_CHAIN_RESPONSE`,{data:t.data});return t.data}async getPool(e,t,n){return T(n),this.getBackend(`/pool`,await this.backendParams(e,t,n))}async getSlot0(e,t,n){return T(n),this.getBackend(`/slot0`,await this.backendParams(e,t,n))}async getCompositePool(e,t,n){T(n);let r=V(B(await G(this.symbols,e),await G(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 G(this.symbols,e),token1:await G(this.symbols,t),fee:String(n)}}async getBackend(e,t){try{return(await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,e,t)).data}catch(e){throw e instanceof l?e:new l(`Pool request failed.`,`HTTP_ERROR`,{cause:e})}}};async function G(e,t){let n=await e.resolve(t);if(n.symbol.length>0)return n.symbol;throw new l(`Token could not be resolved to a trading symbol.`,`SYMBOL_NOT_FOUND`,{token:t})}function be(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.contractVersion===`v2`&&typeof t.token0==`string`&&typeof t.token1==`string`&&typeof t.poolName==`string`&&typeof t.poolRef==`string`&&[`fee`,`tickSpacing`,`protocolFees`,`tradingFees`].every(e=>K(t[e]))&&[`token0CompositeKey`,`token1CompositeKey`,`creator`,`price`,`sqrtPrice`,`token0Tvl`,`token1Tvl`].every(e=>xe(t[e]))&&[`tick`,`tvlUsd`,`volume1d`,`volume7d`,`volume30d`,`trades1d`,`fee24h`,`apr1d`,`token0Price`,`token1Price`].every(e=>Se(t[e]))}function K(e){return typeof e==`number`&&Number.isFinite(e)}function xe(e){return e===void 0||typeof e==`string`}function Se(e){return e===void 0||K(e)}var q=class{constructor(e,t,n,r){this.gateway=e,this.symbols=t,this.signer=n,this.walletAddress=r,c(this,`http`,void 0),this.http=new z(e.httpRequestor,e.requestTimeoutMs??3e4)}async getUserPositions(e){return(await this.get(`/positions`,{user:e})).data.map(e=>this.mapPosition(e))}async getPosition(e,t){let n=await this.symbols.orderPair(e.token0,e.token1),r=this.canonicalTicks(e.tickLower,e.tickUpper,n.flipped),i=await this.getNullable(`/position`,{token0:n.token0.symbol,token1:n.token1.symbol,fee:`${e.fee}`,owner:e.owner,tickLower:`${r.tickLower}`,tickUpper:`${r.tickUpper}`},t);return i===null?null:this.mapPosition(i.data)}async estimateAddLiquidity(t){return w(t.amount,`amount`),(await this.get(`/add-liq-estimate`,{token0:this.requestToken(t.token0),token1:this.requestToken(t.token1),fee:`${t.fee}`,tickLower:`${t.tickLower}`,tickUpper:`${t.tickUpper}`,amount:new e(t.amount).toFixed(),amountIsToken0:String(t.amountIsToken0)})).data}async estimateRemoveLiquidity(t){return w(t.liquidity,`liquidity`),(await this.get(`/remove-liq-estimate`,{token0:this.requestToken(t.token0),token1:this.requestToken(t.token1),fee:`${t.fee}`,tickLower:`${t.tickLower}`,tickUpper:`${t.tickUpper}`,liquidity:new e(t.liquidity).toFixed()})).data}async addLiquidityByTicks(t){T(t.fee);let n=await this.symbols.orderPair(t.token0,t.token1),r=this.canonicalTicks(t.tickLower,t.tickUpper,n.flipped);C(r.tickLower,r.tickUpper,t.fee),w(t.amount,`amount`);let i=new e(t.amount).toFixed(),a={token0:n.token0.symbol,token1:n.token1.symbol,fee:t.fee,tickLower:r.tickLower,tickUpper:r.tickUpper,uniqueKey:this.uniqueKey(),...n.flipped===t.amountIsToken0?{depositQuantityToken1:i}:{depositQuantityToken0:i}};return this.submit(`AddLiquidity`,a,{kind:`add`,identity:{token0:n.token0.symbol,token1:n.token1.symbol,fee:t.fee,tickLower:r.tickLower,tickUpper:r.tickUpper}})}async addLiquidityByPrice(t){T(t.fee),this.rejectNumber(t.minPrice,`minPrice`),this.rejectNumber(t.maxPrice,`maxPrice`);let n=new e(t.minPrice),r=new e(t.maxPrice);if(!n.isFinite()||!r.isFinite()||n.isLessThanOrEqualTo(0)||r.isLessThanOrEqualTo(0))throw new l(`Price bounds must be finite and positive.`,`VALIDATION_ERROR`);if(n.isGreaterThan(r))throw new l(`minPrice must be less than or equal to maxPrice.`,`VALIDATION_ERROR`);let i=this.tickSpacing(t.fee),a=S(x(n),i),o=te(x(r),i);return this.addLiquidityByTicks({token0:t.token0,token1:t.token1,fee:t.fee,tickLower:a,tickUpper:o,amount:t.amount,amountIsToken0:t.amountIsToken0})}async removeLiquidity(t){T(t.fee);let n=await this.symbols.orderPair(t.token0,t.token1),r=this.canonicalTicks(t.tickLower,t.tickUpper,n.flipped);if(C(r.tickLower,r.tickUpper,t.fee),t.amount0!==void 0&&t.amount1!==void 0)throw new l(`Provide at most one of amount0 or amount1.`,`VALIDATION_ERROR`);t.amount0!==void 0&&w(t.amount0,`amount0`),t.amount1!==void 0&&w(t.amount1,`amount1`);let i=t.amount0===void 0?t.amount1===void 0?{}:n.flipped?{withdrawalQuantityToken0:new e(t.amount1).toFixed()}:{withdrawalQuantityToken1:new e(t.amount1).toFixed()}:n.flipped?{withdrawalQuantityToken1:new e(t.amount0).toFixed()}:{withdrawalQuantityToken0:new e(t.amount0).toFixed()},a={token0:n.token0.symbol,token1:n.token1.symbol,fee:t.fee,tickLower:r.tickLower,tickUpper:r.tickUpper,uniqueKey:this.uniqueKey(),...i},o=t.amount0===void 0&&t.amount1===void 0;return this.submit(`RemoveLiquidity`,a,{kind:o?`removeFull`:`removePartial`,identity:{token0:n.token0.symbol,token1:n.token1.symbol,fee:t.fee,tickLower:r.tickLower,tickUpper:r.tickUpper}})}async collectPositionFees(e){T(e.fee);let t=await this.symbols.orderPair(e.token0,e.token1),n=this.canonicalTicks(e.tickLower,e.tickUpper,t.flipped);C(n.tickLower,n.tickUpper,e.fee);let r={token0:t.token0.symbol,token1:t.token1.symbol,fee:e.fee,tickLower:n.tickLower,tickUpper:n.tickUpper,uniqueKey:this.uniqueKey()};return this.submit(`CollectPositionFees`,r,{kind:`collect`,identity:{token0:t.token0.symbol,token1:t.token1.symbol,fee:e.fee,tickLower:n.tickLower,tickUpper:n.tickUpper}})}async createPool(t){let n=t.startingPrice!==void 0;if(n===(t.startingSqrtPrice!==void 0))throw new l(`Provide exactly one of startingPrice or startingSqrtPrice.`,`VALIDATION_ERROR`);T(t.fee);let[r,i]=await Promise.all([this.resolveCreateToken(t.token0,t.token0Symbol),this.resolveCreateToken(t.token1,t.token1Symbol)]),a=r.symbol>i.symbol,[o,s]=a?[i,r]:[r,i],c=n?t.startingPrice:t.startingSqrtPrice;this.rejectNumber(c,n?`startingPrice`:`startingSqrtPrice`);let u=new e(c);if(!u.isFinite()||u.isLessThanOrEqualTo(0))throw new l(`Starting price must be finite and positive.`,`VALIDATION_ERROR`);let d=a?new e(1).dividedBy(u):u,f={token0Key:o.classKey,token1Key:s.classKey,token0Symbol:o.symbol,token1Symbol:s.symbol,fee:t.fee,uniqueKey:this.uniqueKey(),...n?{startingPrice:d.toFixed()}:{startingSqrtPrice:d.toFixed()},...t.isPrivate===void 0?{}:{isPrivate:t.isPrivate},...t.privateAccess===void 0?{}:{privateAccess:t.privateAccess}},p=await this.submit(`CreatePool`,f,{kind:`createPool`,token0:o.symbol,token1:s.symbol,fee:t.fee});return this.symbols.invalidate?.(),p}async submit(e,t,n){if(this.signer===void 0)throw l.noSignerError();let r=await this.signer.signObject(e,t),i=this.walletAddress===void 0?{}:{walletAddress:this.walletAddress},a=this.walletAddress,o=this.buildPositionConfirmation(n,a),s={...i,...o===void 0?{}:{positionConfirmation:o}};return this.gateway.submit(e,r,s)}buildPositionConfirmation(t,n){if(t===void 0)return;if(t.kind===`createPool`){let{token0:e,token1:n,fee:r}=t;return async t=>await this.getNullable(`/pool`,{token0:e,token1:n,fee:`${r}`},t)===null?{confirmed:!1}:{confirmed:!0,position:null}}if(n===void 0)return;let{kind:r,identity:i}=t,a;return async t=>{let o=await this.getPosition({...i,owner:n},t);if(a===void 0)return a={liquidity:new e(o?.liquidity??0),fees:new e(o?.fees0??0).plus(new e(o?.fees1??0))},r===`removeFull`&&o===null?{confirmed:!0,position:null}:{confirmed:!1};switch(r){case`add`:return o!==null&&new e(o.liquidity).isGreaterThan(a.liquidity)?{confirmed:!0,position:o}:{confirmed:!1};case`removePartial`:return o!==null&&new e(o.liquidity).isLessThan(a.liquidity)?{confirmed:!0,position:o}:{confirmed:!1};case`removeFull`:return o===null?{confirmed:!0,position:null}:{confirmed:!1};case`collect`:{if(o===null)return{confirmed:!1};let t=new e(o.fees0??0).plus(new e(o.fees1??0));return t.isLessThan(a.fees)||a.fees.isZero()&&t.isZero()?{confirmed:!0,position:o}:{confirmed:!1}}}}}async get(e,t,n){return this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,e,t,n===void 0?void 0:{signal:n})}async getNullable(e,t,n){try{return await this.get(e,t,n)}catch(e){if(this.isNotFound(e))return null;throw e}}isNotFound(e){return!(e instanceof l)||e.details===void 0?!1:e.details.status===404}mapPosition(e){return{token0Symbol:e.token0Symbol,token1Symbol:e.token1Symbol,...e.token0CompositeKey===void 0?{}:{token0CompositeKey:e.token0CompositeKey},...e.token1CompositeKey===void 0?{}:{token1CompositeKey:e.token1CompositeKey},fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,liquidity:e.liquidity,amount0:e.amount0,amount1:e.amount1,inRange:e.inRange,...e.currentTick===void 0?{}:{currentTick:e.currentTick},...e.sqrtPrice===void 0?{}:{sqrtPrice:e.sqrtPrice},pool:e.poolRef??e.pool??``,owner:e.owner,...e.fees0===void 0?{}:{fees0:e.fees0},...e.fees1===void 0?{}:{fees1:e.fees1}}}requestToken(e){return typeof e==`string`?e:H(e)}canonicalTicks(e,t,n){return n?{tickLower:-t,tickUpper:-e}:{tickLower:e,tickUpper:t}}tickSpacing(e){let t=m[e];if(t===void 0)throw new l(`Unsupported fee tier: ${e}.`,`VALIDATION_ERROR`);return t}rejectNumber(e,t){if(typeof e==`number`)throw new l(`Invalid ${t}: use a decimal string or BigNumber, not a JavaScript number`,`VALIDATION_ERROR`)}uniqueKey(){return`gswap-sdk-${globalThis.crypto.randomUUID()}`}async resolveCreateToken(e,t){try{let n=typeof e==`object`?H(e):e,r=await this.symbols.resolve(n);if(t!==void 0&&t!==``&&t!==r.symbol)throw new l(`Supplied symbol ${t} disagrees with the registered trading symbol ${r.symbol}.`,`VALIDATION_ERROR`,{token:e,suppliedSymbol:t,registeredSymbol:r.symbol});let i=this.tryParseClassKey(e);return{symbol:r.symbol,classKey:i??U({collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey})}}catch(n){if(!(n instanceof l)||n.code!==`UNKNOWN_TOKEN`)throw n;let r;try{r=U(e)}catch{throw n}if(t===void 0||t===``)throw new l(`Token is not registered in the trading-symbol registry yet; pass token0Symbol/token1Symbol (the token class symbol) to propose one. A symbol cannot be derived from a class key.`,`VALIDATION_ERROR`,{token:e});if(!/^[A-Za-z0-9]+$/u.test(t))throw new l(`Invalid trading symbol: must be ASCII letters and digits only.`,`VALIDATION_ERROR`,{symbol:t});return{symbol:t,classKey:r}}}tryParseClassKey(e){try{return U(e)}catch{return}}},J=class{constructor(e,t,n){this.dexBackendBaseUrl=e,this.http=t,this.symbols=n}async quoteExactInput(e,t,n,r){return w(n,`amountIn`),this.quote(e,t,{amountIn:je(n)},r)}async quoteExactOutput(e,t,n,r){return w(n,`amountOut`),this.quote(e,t,{amountOut:je(n)},r)}async quote(e,t,n,r){Ae(r);let i={tokenIn:await Me(this.symbols,e),tokenOut:await Me(this.symbols,t),...n};r!==void 0&&(i.fee=String(r));try{return Ce((await this.http.sendGetRequest(this.dexBackendBaseUrl,`/v2/trade`,`/quote`,i)).data)}catch(n){throw De(n,e,t,r)}}};function Ce(t){if(!Ee(t))throw new l(`Backend returned an invalid quote.`,`INVALID_CHAIN_RESPONSE`,{data:t});let n=t,r=n.currentPrice===void 0?Te(n.currentSqrtPrice,n.tokenInIsToken0):new e(n.currentPrice),i=n.newPrice===void 0?Te(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 we=e.clone({DECIMAL_PLACES:60});function Te(e,t){let n=new we(e).pow(2);return t?n:new we(1).dividedBy(n)}function Ee(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`&&Y(t.currentSqrtPrice)&&Y(t.newSqrtPrice)&&Y(t.currentPrice)&&Y(t.newPrice)&&(t.currentSqrtPrice!==void 0||t.currentPrice!==void 0)&&(t.newSqrtPrice!==void 0||t.newPrice!==void 0)}function Y(t){if(t===void 0)return!0;if(typeof t!=`string`)return!1;try{let n=new e(t);return n.isFinite()&&n.isGreaterThan(0)}catch{return!1}}function De(e,t,n,r){if(e instanceof l){let i=Oe(e.details),a=ke(e.details)??e.message;return i===404||/no pool|no pools|pool does not exist/iu.test(a)?l.noPoolAvailableError(t,n,r):i===400&&/insufficient liquidity/iu.test(a)?l.insufficientLiquidityError(t,n,r):e}return new l(`Quote request failed.`,`HTTP_ERROR`,{cause:e,tokenIn:t,tokenOut:n,fee:r})}function Oe(e){let t=e?.status;return typeof t==`number`?t:void 0}function ke(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 Ae(e){if(e!==void 0&&!h.some(t=>Number(t)===Number(e)))throw new l(`Invalid fee tier: ${e}`,`VALIDATION_ERROR`,{fee:e})}function je(t){return new e(t).toFixed()}async function Me(e,t){let n=await e.resolve(t);if(n.symbol.length>0)return n.symbol;throw new l(`Token could not be resolved to a trading symbol.`,`SYMBOL_NOT_FOUND`,{token:t})}var Ne=class{constructor(e){this.gateway=e,c(this,`cachedSymbols`,void 0),c(this,`cachedAt`,0),c(this,`refreshInFlight`,void 0),c(this,`http`,void 0),this.http=new z(e.httpRequestor,e.requestTimeoutMs)}async list(){return this.cachedSymbols!==void 0&&Date.now()-this.cachedAt<6e4?this.cachedSymbols:(this.refreshInFlight===void 0&&(this.refreshInFlight=this.http.sendGetRequest(this.gateway.dexBackendBaseUrl,`/v2/trade`,`/symbols`).then(e=>Pe(e.data)).then(e=>(this.cachedSymbols=e,this.cachedAt=Date.now(),e)).finally(()=>{this.refreshInFlight=void 0})),this.refreshInFlight)}invalidate(){this.cachedSymbols=void 0,this.cachedAt=0}async refresh(){return this.invalidate(),this.refreshInFlight=void 0,this.list()}async resolve(e){let t=await this.list(),n=typeof e==`string`?Ie(e)?H(U(e)):void 0:H(e),r=t.find(t=>t.symbol===e||n!==void 0&&H(t)===n);if(r===void 0){t=await this.refresh();let r=t.find(t=>t.symbol===e||n!==void 0&&H(t)===n);if(r===void 0)throw l.unknownTokenError(e);return r}return r}async orderPair(e,t){let[n,r]=await Promise.all([this.resolve(e),this.resolve(t)]),[i,a]=B(n.symbol,r.symbol);return{token0:i===n.symbol?n:r,token1:a===r.symbol?r:n,flipped:i!==n.symbol}}};function Pe(e){if(!Array.isArray(e)||!e.every(Fe))throw new l(`Backend returned an invalid symbol list.`,`INVALID_CHAIN_RESPONSE`,{data:e});return e}function Fe(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.symbol==`string`&&typeof t.collection==`string`&&typeof t.category==`string`&&typeof t.type==`string`&&typeof t.additionalKey==`string`&&typeof t.decimals==`number`&&Number.isInteger(t.decimals)&&t.decimals>=0}function Ie(e){return e.includes(`|`)||e.includes(`$`)}const Le=/^[A-Za-z0-9._:-]{1,128}$/u;var X=class{constructor(e,t,n,r){this.gateway=e,this.symbols=t,this.signer=n,this.walletAddress=r}async swap(e,t,n,r){T(n);let i=await this.buildRequestTradeDto(e,t,n,r);if(this.signer===void 0)throw l.noSignerError();let a=await this.signer.signObject(`RequestTrade`,i),o=this.walletAddress===void 0?{}:{walletAddress:this.walletAddress};return this.gateway.submit(`RequestTrade`,a,o)}async confirmSwap(e,t){if(!Le.test(e))throw new l(`uniqueKey must be 1-128 characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".`,`VALIDATION_ERROR`,{uniqueKey:e});return new M({method:`RequestTrade`,uniqueKey:e,transactionId:null,mode:`queued`,result:void 0,dexBackendBaseUrl:this.gateway.dexBackendBaseUrl,httpRequestor:this.gateway.httpRequestor,requestTimeoutMs:this.gateway.requestTimeoutMs}).confirm({initialDelayMs:0,...t})}async buildRequestTradeDto(e,t,n,r){let i=await Re(this.symbols,e),a=V(B(i,await Re(this.symbols,t))),o=i===a.token0,s={token0:a.token0,token1:a.token1,fee:n,uniqueKey:`gswap-sdk-${globalThis.crypto.randomUUID()}`};if(`exactIn`in r){let e=r.exactIn;if(e===void 0)throw new l(`exactIn is required for an exact-input swap.`,`VALIDATION_ERROR`);w(e,`exactIn`),s[o?`sell0Qty`:`sell1Qty`]=Z(e),r.amountOutMinimum!==void 0&&(w(r.amountOutMinimum,`amountOutMinimum`,!0),s.amountOutMinimum=Z(r.amountOutMinimum))}else{let e=r.exactOut;if(e===void 0)throw new l(`exactOut is required for an exact-output swap.`,`VALIDATION_ERROR`);w(e,`exactOut`),s[o?`buy1Qty`:`buy0Qty`]=Z(e),r.amountInMaximum!==void 0&&(w(r.amountInMaximum,`amountInMaximum`,!0),s.amountInMaximum=Z(r.amountInMaximum))}return s}};function Z(t){return new e(t).toFixed()}async function Re(e,t){let n=await e.resolve(t);if(n.symbol.length>0)return n.symbol;throw new l(`Token could not be resolved to a trading symbol.`,`SYMBOL_NOT_FOUND`,{token:t})}const ze={prod:{dexBackendBaseUrl:`https://dex-backend-prod1.defi.gala.com`},stage:{dexBackendBaseUrl:`https://swap-backend.stage.defi.ovh.gala.com`}};var Be=class{constructor(e){c(this,`dexBackendBaseUrl`,void 0),c(this,`chainCallTimeoutMs`,void 0),c(this,`signer`,void 0),c(this,`walletAddress`,void 0),c(this,`gateway`,void 0),c(this,`symbols`,void 0),c(this,`quoting`,void 0),c(this,`pools`,void 0),c(this,`positions`,void 0),c(this,`swaps`,void 0),c(this,`assets`,void 0);let t=ze[e?.env??`prod`];this.dexBackendBaseUrl=Ve(e?.dexBackendBaseUrl??t.dexBackendBaseUrl),this.chainCallTimeoutMs=e?.chainCallTimeoutMs??3e4,this.signer=e?.signer,this.walletAddress=e?.walletAddress;let n=new z(e?.httpRequestor,this.chainCallTimeoutMs);this.gateway=new _e({dexBackendBaseUrl:this.dexBackendBaseUrl,chainCallTimeoutMs:this.chainCallTimeoutMs,...e?.httpRequestor===void 0?{}:{httpRequestor:e.httpRequestor},...this.walletAddress===void 0?{}:{walletAddress:this.walletAddress}}),this.symbols=new Ne(this.gateway),this.quoting=new J(this.dexBackendBaseUrl,n,this.symbols),this.pools=new W(this.gateway,this.symbols),this.positions=new q(this.gateway,this.symbols,this.signer,this.walletAddress),this.swaps=new X(this.gateway,this.symbols,this.signer,this.walletAddress),this.assets=new E(this.dexBackendBaseUrl,n)}};function Ve(e){return e.replace(/\/$/u,``)}function He(e,t){let n={};n[e]=[];function r(e){let t=n[e];
2
+ /* c8 ignore next */
3
+ if(!t)throw Error(`Missing EIP-712 type definition for ${e}`);return t}function i(e,t,a,o=!1){if(Array.isArray(t)){let n=t.length>0?i(e,t[0],a,!0):`string`;o||r(a).push({name:e,type:(n??e)+`[]`})}else if(typeof t==`object`&&t){if(n[e])throw Error(`Name collisions not yet supported`);n[e]=[],Object.entries(t).forEach(([t,n])=>{i(t,n,e)}),o||r(a).push({name:e,type:e})}else{let n;switch(typeof t){case`string`:n=`string`;break;case`number`:n=`int256`;break;case`boolean`:n=`bool`;break;case`bigint`:case`symbol`:case`undefined`:case`function`:case`object`:throw Error(`Unsupported type, ${typeof t}, value: ${Object.prototype.toString.call(t)}`)}if(o)return n;r(a).push({name:e,type:n})}}return Object.entries(t).forEach(([t,n])=>{i(t,n,e)}),n}const Ue={name:`ethereum`,chainId:1},We=/* @__PURE__ */ new Set([`RequestTrade`,`AddLiquidity`,`RemoveLiquidity`,`CollectPositionFees`]);function Q(e,t){return typeof e[t]==`number`?e[t]:0}function Ge(e){return{...e,amount0Desired:Q(e,`amount0Desired`),amount0Min:Q(e,`amount0Min`),amount1Desired:Q(e,`amount1Desired`),amount1Min:Q(e,`amount1Min`),positionId:e.positionId??``}}function Ke(e){return{...e,amount:Q(e,`amount`),amount0Min:Q(e,`amount0Min`),amount1Min:Q(e,`amount1Min`),positionId:e.positionId??``}}function qe(e){return{...e,amount0Requested:Q(e,`amount0Requested`),amount1Requested:Q(e,`amount1Requested`),positionId:e.positionId??``}}const Je={AddLiquidity:Ge,RemoveLiquidity:Ke,CollectPositionFees:qe};function Ye(e,t){let n=Je[e],r=n?n(t):t;return{completedDto:r,types:He(e,r)}}function Xe(e){let t={...e};delete t.prefix;let n=r(t);return`Ethereum Signed Message:
4
+ `+String(new TextEncoder().encode(n).length)}function Ze(){let e=globalThis.window?.gala;if(!e)throw new l(`Gala wallet is not available. Please ensure the Gala wallet is connected.`,`GALA_WALLET_NOT_AVAILABLE`);return e}function Qe(e){if(typeof e!=`string`)throw new l(`Wallet returned an invalid signature.`,`INVALID_SIGNATURE`);if(!/^[0-9a-fA-F]{130}$/u.test(e))throw new l(`Wallet returned an invalid native signature.`,`INVALID_SIGNATURE`);return e}function $e(e){if(typeof e!=`string`||!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(e))throw new l(`Wallet returned an invalid personal-sign signature.`,`INVALID_SIGNATURE`);return e}function et(e,t){let n=t&&e.startsWith(`eth|`)?e.slice(4):e;if(!/^0x[0-9a-fA-F]{40}$/u.test(n))throw new l(`Wallet address must be the selected Ethereum account in 0x-prefixed form.`,`VALIDATION_ERROR`,{type:`INVALID_WALLET_ADDRESS`,value:e});return`0x${n.slice(2).toLowerCase()}`}function tt(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(typeof e==`object`&&e&&`message`in e){let t=e.message;return typeof t==`string`?t:``}return``}function nt(e){return/unsupported|unknown scheme/i.test(tt(e))}function $(e,t,n,i){let a=Xe(t),o={...t,prefix:a},s=i===void 0?[r(t),n]:[r(o),n,i];return e.request({method:i===void 0?`personal_sign`:`gala_signChainDto`,params:s}).then(e=>({...o,signature:$e(e)}))}function rt(e,t,n,r){let{completedDto:i,types:a}=Ye(t,n),o=Xe(i),s={...i,prefix:o},c=[{name:`name`,type:`string`},{name:`chainId`,type:`uint256`}],l={domain:Ue,types:{...a,EIP712Domain:c},primaryType:t,message:s};return e.request({method:`eth_signTypedData_v4`,params:[r,JSON.stringify(l)]}).then(e=>({...s,types:a,domain:Ue,signature:$e(e)}))}var it=class{constructor(e){c(this,`keyBuffer`,void 0),this.keyBuffer=i.normalizePrivateKey(e)}signObject(e,t){let n=i.getSignature(t,this.keyBuffer);return Promise.resolve({...t,signature:n})}},at=class{constructor(e,t={}){c(this,`walletAddress`,void 0),c(this,`effectiveScheme`,void 0),this.walletAddress=et(e,!0),this.effectiveScheme=t.scheme??`native`}async signObject(e,t){let n=Ze();if(this.effectiveScheme===`personal-sign`)return $(n,t,this.walletAddress,e);try{let i=await n.request({method:`gala_signChainDto`,params:[r(t),this.walletAddress,e,`native`]});return{...t,signature:Qe(i)}}catch(r){if(!nt(r))throw r;return this.effectiveScheme=`personal-sign`,$(n,t,this.walletAddress,e)}}},ot=class{constructor(e,t,n={}){this.provider=e,c(this,`walletAddress`,void 0),c(this,`scheme`,void 0),this.walletAddress=et(t,!1),this.scheme=n.scheme??`personal-sign`}signObject(e,t){return this.scheme===`eip712`&&We.has(e)?rt(this.provider,e,t,this.walletAddress):$(this.provider,t,this.walletAddress)}};export{h as ALL_FEE_TIERS,E as Assets,ot as BrowserWalletSigner,_e as ChainGateway,p as FEE_TIER,_ as GC_MAX_TICK,g as GC_MIN_TICK,ze as GSWAP_ENVIRONMENTS,Be as GSwap,l as GSwapSDKError,at as GalaWalletSigner,W as Pools,q as Positions,it as PrivateKeySigner,J as Quoting,M as SubmittedTransaction,X as Swaps,Ne as Symbols,m as TICK_SPACING_BY_FEE,S as alignTickDown,te as alignTickUp,C as assertTickRange,H as compositeKeyOf,u as getObjectProperty,d as getStringProperty,B as orderSymbols,f as parseJson,U as parseTokenClassKey,V as readOrderedSymbols,ee as sqrtPriceToTick,x as tickFromPrice,b as tickToSqrtPrice,T as validateFee,w as validateNumericAmount,re as validatePriceValues,ae as validateTickRange,oe as validateTickSpacing,ie as validateTokenDecimals,se as validateWalletAddress};
3
5
  //# sourceMappingURL=index.js.map