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