@gala-chain/gala-core-sdk 1.1.0-beta.2 → 1.1.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import e from"bignumber.js";import{GALA_CHAIN_ENVIRONMENTS as t,GalaSDKError as n,createUniqueKey as r,dtoOperationOf as i,galaChainUserRef as a,isGalaError as o,isTokenClassKey as s,isWalletUserRejection as c,serialize as l,signPreSend as u,splitClassKey as d,validateTimeoutMs as f,walletDeclineCode as p}from"@gala-chain/gala-core-sdk";import{ComputeBudgetProgram as m,Connection as h,Keypair as g,LAMPORTS_PER_SOL as ee,PublicKey as _,SystemProgram as te,Transaction as ne,TransactionExpiredBlockheightExceededError as re,TransactionInstruction as ie}from"@solana/web3.js";import{Contract as ae,JsonRpcProvider as oe,Signature as se,Wallet as ce,isAddress as le}from"ethers";import{ASSOCIATED_TOKEN_PROGRAM_ID as ue,AccountLayout as de,MintLayout as fe,TOKEN_PROGRAM_ID as v}from"@solana/spl-token";import{base58 as pe}from"@scure/base";let me=/* @__PURE__ */ function(e){return e[e.PENDING=0]=`PENDING`,e[e.SUBMITTED=1]=`SUBMITTED`,e[e.CONFIRMED=2]=`CONFIRMED`,e[e.PROCESSING=3]=`PROCESSING`,e[e.FINALIZING=4]=`FINALIZING`,e[e.COMPLETED=5]=`COMPLETED`,e[e.FAILED=6]=`FAILED`,e[e.DELIVERY_FAILED=7]=`DELIVERY_FAILED`,e}({});const he={name:`GalaConnect`,chainId:1};function ge(e){return e===void 0?he:{name:e,chainId:1}}const _e=[{name:`destinationChainId`,type:`uint256`},{name:`destinationChainTxFee`,type:`destinationChainTxFee`},{name:`dtoOperation`,type:`string`},{name:`quantity`,type:`string`},{name:`recipient`,type:`string`},{name:`tokenInstance`,type:`tokenInstance`},{name:`uniqueKey`,type:`string`}],ve=[{name:`collection`,type:`string`},{name:`category`,type:`string`},{name:`type`,type:`string`},{name:`additionalKey`,type:`string`}],y=[{name:`collection`,type:`string`},{name:`category`,type:`string`},{name:`type`,type:`string`},{name:`additionalKey`,type:`string`},{name:`instance`,type:`string`}],b=[{name:`name`,type:`string`},{name:`symbol`,type:`string`}],ye={GalaTransaction:_e,destinationChainTxFee:[{name:`bridgeToken`,type:`bridgeToken`},{name:`bridgeTokenIsNonFungible`,type:`bool`},{name:`estimatedPricePerTxFeeUnit`,type:`string`},{name:`estimatedTotalTxFeeInExternalToken`,type:`string`},{name:`estimatedTotalTxFeeInGala`,type:`string`},{name:`estimatedTxFeeUnitsTotal`,type:`string`},{name:`galaDecimals`,type:`uint256`},{name:`galaExchangeRate`,type:`galaExchangeRate`},{name:`timestamp`,type:`uint256`},{name:`signingIdentity`,type:`string`},{name:`signature`,type:`string`}],bridgeToken:ve,galaExchangeRate:[{name:`identity`,type:`string`},{name:`oracle`,type:`string`},{name:`source`,type:`string`},{name:`sourceUrl`,type:`string`},{name:`timestamp`,type:`uint256`},{name:`baseToken`,type:`baseToken`},{name:`exchangeRate`,type:`string`},{name:`externalQuoteToken`,type:`externalQuoteToken`}],baseToken:y,externalQuoteToken:b,tokenInstance:y},be={GalaTransaction:_e,destinationChainTxFee:[{name:`bridgeToken`,type:`bridgeToken`},{name:`bridgeTokenIsNonFungible`,type:`bool`},{name:`estimatedPricePerTxFeeUnit`,type:`string`},{name:`estimatedTotalTxFeeInExternalToken`,type:`string`},{name:`estimatedTotalTxFeeInGala`,type:`string`},{name:`estimatedTxFeeUnitsTotal`,type:`string`},{name:`galaDecimals`,type:`uint256`},{name:`galaExchangeCrossRate`,type:`galaExchangeCrossRate`},{name:`timestamp`,type:`uint256`},{name:`signingIdentity`,type:`string`},{name:`signature`,type:`string`}],bridgeToken:ve,galaExchangeCrossRate:[{name:`baseTokenCrossRate`,type:`baseTokenCrossRate`},{name:`crossRate`,type:`string`},{name:`externalCrossRateToken`,type:`externalCrossRateToken`},{name:`identity`,type:`string`},{name:`oracle`,type:`string`},{name:`quoteTokenCrossRate`,type:`quoteTokenCrossRate`},{name:`source`,type:`string`},{name:`timestamp`,type:`uint256`}],baseTokenCrossRate:[{name:`identity`,type:`string`},{name:`oracle`,type:`string`},{name:`source`,type:`string`},{name:`sourceUrl`,type:`string`},{name:`timestamp`,type:`uint256`},{name:`exchangeRate`,type:`string`},{name:`externalBaseToken`,type:`externalBaseToken`},{name:`externalQuoteToken`,type:`externalQuoteToken`},{name:`signature`,type:`string`}],externalBaseToken:b,externalQuoteToken:b,externalCrossRateToken:b,quoteTokenCrossRate:[{name:`identity`,type:`string`},{name:`oracle`,type:`string`},{name:`source`,type:`string`},{name:`sourceUrl`,type:`string`},{name:`timestamp`,type:`uint256`},{name:`baseToken`,type:`baseToken`},{name:`exchangeRate`,type:`string`},{name:`externalQuoteToken`,type:`externalQuoteToken`},{name:`signature`,type:`string`}],baseToken:y,tokenInstance:y};function xe(e){return e?be:ye}function Se(e){return e==null}function Ce(e){return e==null||e===``}function x(e){return typeof e==`object`&&e?e:{}}function S(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function C(e,t,n={}){return t.every(t=>typeof e[t]==`string`)&&Object.entries(n).every(([t,n])=>{let r=e[t];return r===void 0||(n===`object`?S(r):typeof r===n)})}function w(e,t){if(Se(e))return t;if(typeof e==`bigint`)return Number(e);if(typeof e==`number`)return isNaN(e)?t:Math.floor(e);let n=parseInt(String(e),10);return isNaN(n)?t:n}function we(e,t=0){if(Ce(e))return t;if(typeof e==`number`)return isNaN(e)||!isFinite(e)?t:e;let n=parseFloat(e);return isNaN(n)||!isFinite(n)?t:n}function Te(e,t){if(Ce(e))return t;try{return JSON.parse(e)}catch{return t}}function T(t,n=`0`){if(Ce(t))return new e(n);if(e.isBigNumber(t))return t.isNaN()?new e(n):t;try{let r=new e(t);return r.isNaN()||!r.isFinite()?new e(n):r}catch{return new e(n)}}function Ee(e){return e instanceof Error}function De(e){return Ee(e)||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`?e.message:typeof e==`string`?e:String(e)}function Oe(e){if(typeof e==`object`&&e&&`code`in e&&(typeof e.code==`string`||typeof e.code==`number`))return e.code}function E(e){return e.trim().toUpperCase()}function ke(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}const D={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},O={ASSET:1,MUSIC:3};function Ae(e){return Object.values(O).includes(e)}const je=12,Me=15e3,Ne=27e5,Pe={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},Fe=`https://ethereum.publicnode.com`,Ie=`https://api.mainnet-beta.solana.com`,Le=`0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9`,Re=`0x6a1734E09f3099a3675645D214ce547080ea67e0`,ze=`AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS`,Be=`https://dex-api-platform-dex-prod-gala.gala.com`,k=[{symbol:`GALA`,amount:`1`,contractAddress:`0xd1d2Eb1B1e90B638588728b4130137D262C87cae`,bridgeUsesPermit:!0,decimals:8},{symbol:`GWETH`,amount:`0.0001`,contractAddress:`0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2`,bridgeUsesPermit:!1,decimals:18},{symbol:`GUSDC`,amount:`1`,contractAddress:`0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48`,bridgeUsesPermit:!1,decimals:6},{symbol:`GUSDT`,amount:`1`,contractAddress:`0xdAC17F958D2ee523a2206206994597C13D831ec7`,bridgeUsesPermit:!1,decimals:6},{symbol:`GWTRX`,amount:`1`,contractAddress:`0x50327c6c5a14DCaDE707ABad2E27eB517df87AB5`,bridgeUsesPermit:!1,decimals:6},{symbol:`GWBTC`,amount:`0.00001`,contractAddress:`0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599`,bridgeUsesPermit:!1,decimals:8}],Ve=[{symbol:`GALA`,amount:`1`,contractAddress:`0x9fBFf09325C1967A135AC9b4860b1cf89aca52DA`,bridgeUsesPermit:!0,decimals:8},{symbol:`GWETH`,amount:`0.0001`,contractAddress:`0xC3F00B9CbC4221D85A66EEbe928551d0d8dD9158`,bridgeUsesPermit:!1,decimals:18},{symbol:`GUSDC`,amount:`1`,contractAddress:`0x081e78E33bfa612b23A99ef61e7c194649AA318E`,bridgeUsesPermit:!1,decimals:6},{symbol:`GUSDT`,amount:`1`,contractAddress:`0x461e3595f087bfb0E32B6e44BCbF4C74D99B0001`,bridgeUsesPermit:!1,decimals:6},{symbol:`GWBTC`,amount:`0.00001`,contractAddress:`0x5f69276935EF17e5aF5289b60aFBf6d48B344770`,bridgeUsesPermit:!1,decimals:8}];function A(e){return e===`prod`?k:Ve}function He(e){return e===`prod`?Le:Re}const j=[{symbol:`GALA`,amount:`1`,mintAddress:`eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6`,isNative:!1,decimals:8},{symbol:`GSOL`,amount:`0.001`,mintAddress:`So11111111111111111111111111111111111111111`,isNative:!0,decimals:9}],M={GALA:{descriptor:{collection:`GALA`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:8,channel:`asset`},GWETH:{descriptor:{collection:`GWETH`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:18,channel:`asset`},GUSDC:{descriptor:{collection:`GUSDC`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:6,channel:`asset`},GUSDT:{descriptor:{collection:`GUSDT`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:6,channel:`asset`},GWTRX:{descriptor:{collection:`GWTRX`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:6,channel:`asset`},GWBTC:{descriptor:{collection:`GWBTC`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:8,channel:`asset`},GSOL:{descriptor:{collection:`GSOL`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:9,channel:`asset`}},Ue=[`function decimals() view returns (uint8)`,`function balanceOf(address owner) view returns (uint256)`,`function approve(address spender, uint256 value) returns (bool)`,`function allowance(address owner, address spender) view returns (uint256)`,`function transfer(address to, uint256 value) returns (bool)`,`function name() view returns (string)`,`function nonces(address owner) view returns (uint256)`,`function permit(address owner,address spender,uint256 value,uint256 deadline,uint8 v,bytes32 r,bytes32 s)`],We=[`function bridgeOut(address token,uint256 amount,uint256 tokenId,uint16 destinationChainId,bytes recipient) external`,`function bridgeOutWithPermit(address token,uint256 amount,uint16 destinationChainId,bytes recipient,uint256 deadline,uint8 v,bytes32 r,bytes32 s) external`],Ge={BRIDGE_OUT:Uint8Array.from([27,194,57,119,215,165,247,150]),BRIDGE_OUT_NATIVE:Uint8Array.from([243,44,75,224,249,206,98,79])};function Ke(e){let t=E(e);return M[t]}function qe(e){let t=E(e);return k.find(e=>E(e.symbol)===t)}function Je(e){let t=E(e);return j.find(e=>E(e.symbol)===t)}function Ye(e){return ke(e)}function Xe(e){if(e===void 0||e===``)throw new n(`INVALID_TOKEN_REFERENCE`,{field:`tokenSymbol`,reason:`missing`});return e}function Ze(e,t,r){let i=x(t),a=i.Status;if(typeof a!=`number`||a===1)return;let o=e=>{let t=i[e];return typeof t==`string`?t:``},s=i.ErrorCode;throw new n(`BRIDGE_REQUEST_REJECTED`,{method:e,chainStatus:a,errorKey:o(`ErrorKey`),serverMessage:o(`Message`)},{write:!0,body:t,...typeof s==`number`&&{status:s},...r!==void 0&&{uniqueKey:r}})}function Qe(e){if(e===void 0||e===``)throw new n(`BRIDGE_RESPONSE_INVALID`,{method:`RequestTokenBridgeOut`,missing:`bridge request id`});return e}function $e(e){let t=x(e),r=[t.Hash,t.hash].find(e=>typeof e==`string`&&e!==``);if(r===void 0)throw new n(`BRIDGE_RESPONSE_INVALID`,{method:`BridgeTokenOut`,missing:`transaction hash`});return r}function et(e,t){if(!le(e))throw new n(`INVALID_WALLET_ADDRESS`,{field:t??`address`,value:String(e)})}function tt(e,t){try{return new _(e)}catch{throw new n(`INVALID_WALLET_ADDRESS`,{field:t??`address`,value:String(e)})}}function nt(e){return tt(e)}function N(e,t){let r=``;try{r=new URL(e).protocol}catch{}if(r!==`http:`&&r!==`https:`)throw new n(`INVALID_BRIDGE_OPTION`,{option:t});return e}function rt(e,t){if(typeof e!=`string`||!le(e))throw new n(`INVALID_BRIDGE_OPTION`,{option:t});return e}function it(e,t){try{if(typeof e==`string`&&e!==``)return new _(e)}catch{}throw new n(`INVALID_BRIDGE_OPTION`,{option:t})}function P(e){"@babel/helpers - typeof";return P=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},P(e)}function at(e,t){if(P(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(P(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ot(e){var t=at(e,`string`);return P(t)==`symbol`?t:t+``}function F(e,t,n){return(t=ot(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var st=class{constructor(e){if(F(this,`minIntervalMs`,void 0),F(this,`lastTimestamp`,0),F(this,`pendingPromise`,Promise.resolve()),!(e>0))throw new n(`INVALID_BRIDGE_OPTION`,{option:`requestsPerSecond`});this.minIntervalMs=1e3/e}schedule(e){let t=this.pendingPromise.then(async()=>{let t=this.minIntervalMs-(Date.now()-this.lastTimestamp);return t>0&&await new Promise(e=>setTimeout(e,t)),this.lastTimestamp=Date.now(),e()});return this.pendingPromise=t.then(()=>void 0,()=>void 0),t}};const ct={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},lt=/* @__PURE__ */ new Set([408,429,500,502,503,504]),ut=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function dt(e){if(typeof e==`object`&&e){let t=e;if(typeof t.status==`number`)return lt.has(t.status);if(typeof t.statusCode==`number`)return lt.has(t.statusCode);let n=Oe(e);if(typeof n==`string`&&(n===`ECONNRESET`||n===`ECONNREFUSED`||n===`ETIMEDOUT`||n===`ENOTFOUND`||n===`EAI_AGAIN`))return!0}let t=De(e);return ut.some(e=>e.test(t))}function ft(e,t){let n=t.initialDelayMs*t.backoffMultiplier**(e-1),r=Math.min(n,t.maxDelayMs),i=r*t.jitterFactor*Math.random();return Math.floor(r+i)}async function pt(e,t={}){let n={...ct,...t},r=t.shouldRetry??(e=>dt(e)),i;for(let a=1;a<=n.maxRetries+1;a++)try{return await e()}catch(e){if(i=e,a>n.maxRetries||!r(e,a))break;let o=ft(a,n);t.onRetry&&t.onRetry(e,a,o),await new Promise(e=>setTimeout(e,o))}throw i}function mt(e){return new Promise(t=>setTimeout(t,e))}const I={baseUrl:Be,galachainBaseUrl:`https://galachain-gateway-chain-platform-galachain-mainnet.gala.com`,requestsPerSecond:12,requestTimeoutMs:3e4,enableRetry:!0,maxRetries:3,retryInitialDelayMs:1e3};function L(e){return e.uniqueKey===void 0?{write:e.write}:{write:!0,uniqueKey:e.uniqueKey}}function ht(e){let t=e.uniqueKey;return typeof t==`string`&&t!==``?t:void 0}function gt(e,t,r,i){let a=Te(i,{rawBody:i.slice(0,500)});return new n(`GALACONNECT_HTTP_ERROR`,{method:e.path,status:r,serverMessage:i.slice(0,500)},{...L(e),status:r,body:a,url:t})}function _t(e,t,r){return e.write?new n(`BRIDGE_WRITE_OUTCOME_UNKNOWN`,{method:e.path},{...L(e),url:t,cause:r}):new n(`TRANSPORT_ERROR`,{url:t},{write:!1,url:t,cause:r})}function vt(e,t,r,i){let a=new n(`REQUEST_TIMEOUT`,{url:t,timeoutMs:r},{...L(e),url:t,cause:i});return e.write?_t(e,t,a):a}function yt(e,t){return e.write?new n(`BRIDGE_RESPONSE_INVALID`,{method:e.path,missing:`JSON answer`},{...L(e),url:t}):new n(`BRIDGE_READ_RESPONSE_INVALID`,{method:e.path},{write:!1,url:t})}function bt(e,t,n){if(!n.ok)throw gt(e,t,n.status,n.text);if(n.text!==``)try{return JSON.parse(n.text)}catch{throw yt(e,t)}}function xt(e,t){let n=e;return n.code===`GALACONNECT_HTTP_ERROR`?n.status===429||!t.write&&dt({status:n.status}):!t.write&&dt(n.cause)}var St=class{constructor(e){F(this,`baseUrl`,void 0),F(this,`galachainBaseUrl`,void 0),F(this,`walletAddress`,void 0),F(this,`rateLimiter`,void 0),F(this,`defaultHeaders`,void 0),F(this,`retryOptions`,void 0),F(this,`requestor`,void 0),F(this,`requestTimeoutMs`,void 0),this.requestTimeoutMs=f(e.requestTimeoutMs??I.requestTimeoutMs,`requestTimeoutMs`),this.baseUrl=N(e.baseUrl??I.baseUrl,`baseUrl`),this.galachainBaseUrl=N(e.galachainBaseUrl??I.galachainBaseUrl,`galachainBaseUrl`),this.walletAddress=e.walletAddress===``?``:a(e.walletAddress,`walletAddress`),this.rateLimiter=new st(e.requestsPerSecond??I.requestsPerSecond),this.requestor=e.httpRequestor??((e,t)=>globalThis.fetch(e,t)),this.defaultHeaders={"Content-Type":`application/json`,"X-Wallet-Address":this.walletAddress};let t=e.enableRetry??I.enableRetry;this.retryOptions=t?{maxRetries:e.maxRetries??I.maxRetries,initialDelayMs:e.retryInitialDelayMs??I.retryInitialDelayMs,...e.onRetry&&{onRetry:e.onRetry}}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){let t={path:`/v1/connect/bridge-configurations`,write:!1},n=new URL(t.path,this.baseUrl);n.searchParams.set(`searchprefix`,e);let r=await this.send(n.toString(),{method:`GET`},t);if(!r.ok)throw gt(t,n.toString(),r.status,r.text);let i=Te(r.text,null)?.data?.tokens;if(!Array.isArray(i))throw yt(t,n.toString());return i}async request(e){let t={path:e.url,write:!1},n=new URL(e.url,this.baseUrl);for(let[t,r]of Object.entries(e.params))n.searchParams.set(t,String(r));return bt(t,n.toString(),await this.send(n.toString(),{method:`GET`},t))}async fetchBridgeFee(e){return this.postJson({path:`/v1/bridge/fee`,write:!1},e,{skipWalletHeader:!0})}async requestBridgeOut(e){return this.postJson({path:`/v1/RequestTokenBridgeOut`,write:!0,uniqueKey:ht(e)},e)}async bridgeTokenOut(e){return this.postJson({path:`/v1/BridgeTokenOut`,write:!0,uniqueKey:ht(e)},e)}async getBridgeStatus(e){return this.postJson({path:`/v1/bridge/status`,write:!1},{hash:e})}async registerBridgeTransaction(e){return this.postJson({path:`/v1/bridge/transaction`,write:!0,uniqueKey:ht(e)},e)}async fetchBalances(e=`asset`){return this.postJson({path:`/v1/FetchBalances`,write:!1},{owner:this.walletAddress,channel:e},{baseUrl:this.galachainBaseUrl})}async postJson(e,t,n={}){let r=new URL(e.path,n.baseUrl??this.baseUrl).toString(),i=n.skipWalletHeader?{"Content-Type":`application/json`,"X-Wallet-Address":``}:this.defaultHeaders;return bt(e,r,await this.send(r,{method:`POST`,headers:i,body:JSON.stringify(t,(e,t)=>typeof t==`bigint`?t.toString():t)},e))}async send(e,t,n){let r=()=>this.rateLimiter.schedule(async()=>{let r={...this.defaultHeaders,...t.headers};r[`X-Wallet-Address`]===``&&delete r[`X-Wallet-Address`];let i,a=new AbortController,o=this.requestTimeoutMs===1/0?void 0:setTimeout(()=>a.abort(),this.requestTimeoutMs);try{let n=await this.requestor(e,{...t,headers:r,signal:a.signal});i={ok:n.ok,status:n.status,text:await n.text()}}catch(t){throw a.signal.aborted?vt(n,e,this.requestTimeoutMs,t):_t(n,e,t)}finally{clearTimeout(o)}if(this.retryOptions&&!i.ok&&(i.status===429||i.status>=500))throw gt(n,e,i.status,i.text);return i});return this.retryOptions?pt(r,{...this.retryOptions,shouldRetry:e=>xt(e,n)}):r()}};function Ct(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function wt(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function Tt(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(E(n.symbol),n);return t}function Et(e,t){return e.get(E(t))}function R(e,t,r){let i=Et(e,t);if(!i)throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:r,symbol:t});return i}function Dt(e){if(e===void 0||!Ct(e))throw new n(`INVALID_PRIVATE_KEY`,{reason:`bad_encoding`})}function Ot(e){if(!wt(e))throw new n(`INVALID_TRANSACTION_HASH`,{network:`Ethereum`,value:String(e)})}function z(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function kt(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function At(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function jt(e,t,r){let i=e.find(e=>e.symbol===t);if(!i)throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:r,symbol:t});return i}function Mt(e,t){if(e===void 0)throw new n(`BRIDGE_NOT_CONFIGURED`,{network:t});return e}function Nt(e){return{direction:`outbound`,fromChain:`GalaChain`,toChain:e.toChain,transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,feePaid:e.feePaid,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}function Pt(e){return{direction:`inbound`,fromChain:e.fromChain,toChain:`GalaChain`,transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}function Ft(e){return{destinationChainId:e.destinationChainId,destinationChainTxFee:e.bridgeFee,quantity:e.amount,recipient:e.recipientAddress,tokenInstance:{...e.tokenDescriptor,instance:`0`}}}function It(e){let t={...e,galaDecimals:typeof e.galaDecimals==`string`?w(e.galaDecimals,0):e.galaDecimals,timestamp:typeof e.timestamp==`string`?w(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:typeof e.galaExchangeRate.timestamp==`string`?w(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){let n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:typeof n.timestamp==`string`?w(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:typeof n.baseTokenCrossRate.timestamp==`string`?w(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:typeof n.quoteTokenCrossRate.timestamp==`string`?w(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}function Lt(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r&&typeof r==`object`&&!Array.isArray(r)?Lt(r):r);return t}function Rt(e){let t=x(e);if(typeof t.Data==`string`)return t.Data;let n=t.data;if(typeof n==`string`)return n;let r=x(n).Data;return typeof r==`string`?r:void 0}function B(e){let t=we(e,-1);if(t<=0)throw new n(`INVALID_BRIDGE_AMOUNT`,{value:String(e),reason:`not_positive`});return t}function zt(e,t,n){return{descriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},decimals:t,...n===void 0?{}:{channel:n}}}function Bt(e){let t=e;if(!S(t)||typeof t.estimatedTotalTxFeeInGala!=`string`||!(S(t.galaExchangeRate)||S(t.galaExchangeCrossRate)))throw Ht(`/v1/bridge/fee`);return e}function Vt(e){if(!S(e))throw Ht(`/v1/bridge/status`);return e}function Ht(e){return new n(`BRIDGE_READ_RESPONSE_INVALID`,{method:e},{write:!1})}function Ut(e){let t=typeof e.timestamp==`string`?w(e.timestamp,0):e.timestamp;return{estimatedFeeInGala:e.estimatedTotalTxFeeInGala,estimatedFeeInExternalToken:e.estimatedTotalTxFeeInExternalToken,feeToken:e.bridgeToken,pricePerUnit:e.estimatedPricePerTxFeeUnit,estimatedGasUnits:e.estimatedTxFeeUnitsTotal,exchangeRate:e.galaExchangeRate?.exchangeRate??`0`,timestamp:t,raw:e}}function Wt(e){let t=typeof e==`string`&&/^\d+$/u.test(e)?Number(e):e;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<=0)throw new n(`INVALID_BRIDGE_OPTION`,{option:`destinationChainId`});return t}const Gt=`RequestTokenBridgeOut`;async function Kt(e,t,r,i){let a;try{a=await e.signTypedData(t,r,i)}catch(e){throw o(e)?e:new n(`SIGNING_FAILED`,{method:Gt,reason:c(e)?`user_rejected`:`failed`},{cause:e,walletCode:p(e)})}if(typeof a!=`string`)throw new n(`SIGNING_FAILED`,{method:Gt,reason:`failed`},{cause:a});return a}async function qt(e,t){let{wallet:n}=t,a=Wt(e.destinationChainId),o=e.uniqueKey??r(`galaconnect-operation-`),s=It(e.destinationChainTxFee),c=!!s.galaExchangeCrossRate,u={destinationChainId:a,destinationChainTxFee:Lt(c?{...s,galaExchangeRate:void 0}:{...s,galaExchangeCrossRate:void 0}),dtoOperation:i(`asset/bridge-contract`,Gt),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:o},d=xe(c),f=ge(t.eip712DomainName),p=await Kt(n,f,d,u),m=`\u0019Ethereum Signed Message:\n${l({domain:f,message:u,primaryType:`GalaTransaction`,types:d}).length}`;return{...u,signature:p,prefix:m,types:d,domain:f}}async function Jt(e,t,r,i,a){let o=`request_id`,s=``;try{s=Qe(Rt(t)),o=`bridge_token_out`;let n=await e.bridgeTokenOut({bridgeFromChannel:i,bridgeRequestId:s});return Ze(`BridgeTokenOut`,n),o=`transaction_hash`,a(n,s)}catch(e){throw new n(`BRIDGE_OUT_OUTCOME_UNKNOWN`,{step:o,bridgeRequestId:s},{uniqueKey:r,cause:e})}}async function Yt(e,t){let{amount:n,recipientAddress:r,tokenSymbol:i}=e,{galaConnectClient:a,tokenMetadataResolver:o,ethereumWallet:s,eip712DomainName:c,destinationChainId:l,destinationChain:u,validateRecipientAddress:d}=t,f=Xe(i);B(n),d(r,`recipient`);let p=await o.getTokenMetadata(f),m=Bt(await a.fetchBridgeFee({chainId:u,bridgeToken:p.descriptor})),h=await qt(Ft({destinationChainId:l,bridgeFee:m,amount:n,recipientAddress:r,tokenDescriptor:p.descriptor}),{wallet:s,eip712DomainName:c}),g=await a.requestBridgeOut(h);return Ze(`RequestTokenBridgeOut`,g,h.uniqueKey),Nt({toChain:u,transactionHash:await Jt(a,g,h.uniqueKey,`asset`,$e),tokenSymbol:f,amount:n,feePaid:m.estimatedTotalTxFeeInGala,baseUrl:a.getBaseUrl()})}const Xt={COMPLETED:5,FAILED:6,DELIVERY_FAILED:7};function Zt(e){let t=e.status,n=w(t,0);return{status:n,statusDescription:e.statusDescription,fromChain:e.fromChain,toChain:e.toChain,quantity:e.quantity,transactionHash:e.emitterTransactionHash,tokenInstance:e.tokenInstance,isComplete:n===Number(Xt.COMPLETED),isFailed:n===Number(Xt.FAILED)||n===Number(Xt.DELIVERY_FAILED)}}function V(e){return Mt(e.get(`Ethereum`),`Ethereum`)}function H(e){return Mt(e.get(`Solana`),`Solana`)}function U(e,t){return e??t.getWalletAddress()}async function Qt(e,t,n,r){let i=await t.getTokenMetadata(r);return Ut(Bt(await e.fetchBridgeFee({chainId:n,bridgeToken:i.descriptor})))}async function $t(e,t){return Zt(Vt(await e.getBridgeStatus(t)))}function en(e){return Array.from(e.keys())}function tn(e,t){return e.has(E(t))}function nn(e){return[e.collection,e.category,e.type,e.additionalKey].every(e=>typeof e==`string`)&&Number.isSafeInteger(e.decimals)&&e.decimals>=0&&(e.channel===void 0||typeof e.channel==`string`)}var rn=class{constructor(e){F(this,`galaConnectClient`,void 0),F(this,`cache`,/* @__PURE__ */ new Map),this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){let t=E(e),n=this.cache.get(t);if(n)return n;let r=M[t];if(r!==void 0)return this.cache.set(t,r),r;let i=await this.fetchFromApi(e);return this.cache.set(t,i),i}async fetchFromApi(e){let t=(await this.galaConnectClient.getBridgeConfigurations(e)).find(t=>typeof t.symbol==`string`&&E(t.symbol)===E(e)&&t.verified===!0);if(!t)throw new n(`BRIDGE_TOKEN_NOT_FOUND`,{symbol:e},{write:!1});if(!nn(t))throw new n(`BRIDGE_READ_RESPONSE_INVALID`,{method:`/v1/connect/bridge-configurations`},{write:!1});return zt({collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey},t.decimals,t.channel)}};function an(t){if(typeof t==`string`&&t!==``)try{let n=new e(t);return n.isFinite()?n:void 0}catch{return}}function on(e,t){let r=an(e);if(r===void 0)throw new n(`INVALID_BRIDGE_AMOUNT`,{value:String(e),reason:`not_a_number`});let i=r.multipliedBy(T(10).pow(t));if(!i.isInteger())throw new n(`INVALID_BRIDGE_AMOUNT`,{value:e,reason:`too_many_decimals`});return BigInt(i.toFixed(0))}function W(e,t){return sn(T(e.toString()).dividedBy(T(10).pow(t)).toFixed(t))}function sn(e){return e.includes(`.`)?e.replace(/\.?0+$/u,``):e}function cn(e,t=6){let n=T(e);if(n.abs().lt(1e-6)&&!n.isZero())return n.toExponential(2);let r=Math.min(t,n.abs().lt(1)?t:n.abs().lt(100)?4:2);return sn(n.toFixed(r))}function ln(e,t){let n=T(e),r=T(t);return n.comparedTo(r)}const un=/* @__PURE__ */ new Set([5,6,7]);var dn=class{constructor(e=mt){F(this,`sleep`,void 0),this.sleep=e}async waitForCompletion(e,t={}){let{pollInterval:r=15e3,timeout:i=27e5,onStatusUpdate:a}=t;for(let[e,t]of[[`pollInterval`,r],[`timeout`,i]])if(!Number.isFinite(t)||t<0)throw new n(`INVALID_BRIDGE_OPTION`,{option:e});let o=Date.now();for(;;){let t=await this.getStatus(e);if(a&&a(t),un.has(t.status))return t;if(Date.now()-o>i)throw new n(`BRIDGE_STATUS_TIMEOUT`,{transactionHash:e,timeoutMs:i,lastStatus:t.status},{write:!1});await this.sleep(r)}}},fn=class extends dn{constructor(e,t,n){super(n),F(this,`galaConnectClient`,void 0),F(this,`tokenConfigs`,void 0),this.galaConnectClient=e,this.tokenConfigs=t}async getStatus(e){return $t(this.galaConnectClient,e)}getSupportedTokens(){return en(this.tokenConfigs)}isTokenSupported(e){return tn(this.tokenConfigs,e)}};function pn(e,t){return new ae(e,Ue,t)}async function G(e,t){try{return await t()}catch(t){throw new n(`BRIDGE_CHAIN_READ_FAILED`,{network:`Ethereum`,call:e},{write:!1,cause:t})}}function mn(e,t,r){return new n(`BRIDGE_DEPOSIT_OUTCOME_UNKNOWN`,{network:`Ethereum`,step:e,transactionHash:t},{cause:r})}const hn=/^0x[0-9a-fA-F]{40}$/u;var gn=class e extends fn{constructor(e){let t=e.tokenConfigs??k;super(e.galaConnectClient,Tt(t),e.sleep),F(this,`network`,`Ethereum`),F(this,`galaChainWalletAddress`,void 0),F(this,`ethereumProvider`,void 0),F(this,`ethereumWallet`,void 0),F(this,`ethereumBridgeContract`,void 0),F(this,`ethereumWalletAddress`,void 0),F(this,`tokenMetadataResolver`,void 0),F(this,`eip712DomainName`,void 0);for(let e of t)rt(e.contractAddress,`tokenConfigs`);this.galaChainWalletAddress=e.galaChainWalletAddress,Dt(e.ethereumPrivateKey);let n=rt(e.ethereumBridgeContract,`ethereumBridgeContract`),r=N(e.ethereumRpcUrl??`https://ethereum.publicnode.com`,`ethereumRpcUrl`);e.ethereumWalletAddress!==void 0&&rt(e.ethereumWalletAddress,`ethereumWalletAddress`),this.ethereumProvider=new oe(r),this.eip712DomainName=e.eip712DomainName,this.ethereumWallet=new ce(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=n,this.tokenMetadataResolver=new rn({galaConnectClient:this.galaConnectClient})}async estimateFee(e){return Qt(this.galaConnectClient,this.tokenMetadataResolver,`Ethereum`,e)}async bridgeOut(e){return Yt(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,eip712DomainName:this.eip712DomainName,destinationChainId:D.ETHEREUM,destinationChain:`Ethereum`,validateRecipientAddress:et})}async bridgeIn(e){let{amount:t,sourcePrivateKey:r,recipientAddress:i,tokenSymbol:o}=e,s=Xe(o);B(t);let c=r!==void 0&&r!==``;c&&Dt(r);let l=a(i??this.galaChainWalletAddress,`address`),u=c?new ce(r,this.ethereumProvider):this.ethereumWallet,d=R(this.tokenConfigs,s,`Ethereum`),f=await this.tokenMetadataResolver.getTokenMetadata(s),p=pn(d.contractAddress,u),m=Number(await G(`decimals`,()=>p.decimals())),h=on(t,m),g=await G(`balanceOf`,()=>p.balanceOf(u.address));if(g<h)throw new n(`INSUFFICIENT_BRIDGE_BALANCE`,{network:`Ethereum`,symbol:s,needed:W(h,m),available:W(g,m)});return Pt({fromChain:`Ethereum`,transactionHash:await this.executeBridgeDeposit({wallet:u,tokenContract:p,tokenConfig:d,amountBaseUnits:h,decimals:m,recipient:l,metadata:f}),tokenSymbol:s,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){return hn.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,t){let n=R(this.tokenConfigs,e,`Ethereum`),r=t??this.ethereumWalletAddress;et(r);let i=pn(n.contractAddress,this.ethereumProvider);return W(await G(`balanceOf`,()=>i.balanceOf(r)),n.decimals??Number(await G(`decimals`,()=>i.decimals())))}async getEthereumNativeBalance(e){let t=e??this.ethereumWalletAddress;return et(t),W(await this.ethereumProvider.getBalance(t),18)}async getEthereumTransactionStatus(t){Ot(t);let n=t.toLowerCase();try{let t=await this.ethereumProvider.getTransactionReceipt(n);if(t){let r=await this.ethereumProvider.getBlockNumber()-t.blockNumber+1;return t.status===1?{confirmed:!0,status:r>=e.ETHEREUM_FINALITY_THRESHOLD?`finalized`:`confirmed`,blockNumber:t.blockNumber,confirmations:r,transactionHash:n,gasUsed:t.gasUsed.toString(),effectiveGasPrice:t.gasPrice.toString()}:{confirmed:!1,status:`failed`,blockNumber:t.blockNumber,confirmations:r,transactionHash:n,gasUsed:t.gasUsed.toString(),effectiveGasPrice:t.gasPrice.toString(),error:`Transaction reverted during execution`}}return await this.ethereumProvider.getTransaction(n)?{confirmed:!1,status:`pending`,transactionHash:n}:{confirmed:!1,status:`not_found`,transactionHash:n,error:`Transaction not found on Ethereum network`}}catch(e){return{confirmed:!1,status:`not_found`,transactionHash:n,error:`Failed to query transaction status: ${De(e)}`}}}async executeBridgeDeposit(e){let t=new ae(this.ethereumBridgeContract,We,e.wallet),n=new TextEncoder().encode(e.recipient),r=e.tokenConfig.bridgeUsesPermit?await this.prepareBridgeWithPermit(e.wallet,e.tokenContract,e.tokenConfig,t,e.amountBaseUnits,n):await this.prepareBridgeWithApproval(e.wallet,e.tokenContract,t,e.tokenConfig,e.amountBaseUnits,n),i;try{i=await r()}catch(e){throw mn(`send`,``,e)}try{await i.wait()}catch(e){throw mn(`confirmation`,i.hash,e)}try{await this.sleep(3e4),await this.galaConnectClient.registerBridgeTransaction({quantity:W(e.amountBaseUnits,e.decimals),tokenInstance:{collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:`0`},fromChain:`Ethereum`,toChain:`GC`,hash:i.hash})}catch(e){throw mn(`registration`,i.hash,e)}return i.hash}async prepareBridgeWithPermit(e,t,n,r,i,a){let o=await G(`chainId`,()=>this.ethereumProvider.getNetwork()),s=await G(`name`,()=>t.name()),c=await G(`nonces`,()=>t.nonces(e.address)),l=BigInt(Math.floor(Date.now()/1e3)+3600),u=await e.signTypedData({name:s,version:`1`,chainId:Number(o.chainId),verifyingContract:n.contractAddress},{Permit:[{name:`owner`,type:`address`},{name:`spender`,type:`address`},{name:`value`,type:`uint256`},{name:`nonce`,type:`uint256`},{name:`deadline`,type:`uint256`}]},{owner:e.address,spender:this.ethereumBridgeContract,value:i,nonce:c,deadline:l}),d=se.from(u);return()=>r.bridgeOutWithPermit(n.contractAddress,i,D.GALA_CHAIN,a,l,d.v,d.r,d.s)}async prepareBridgeWithApproval(e,t,n,r,i,a){return await G(`allowance`,()=>t.allowance(e.address,this.ethereumBridgeContract))<i&&await(await t.approve(this.ethereumBridgeContract,i)).wait(),()=>n.bridgeOut(r.contractAddress,i,0,D.GALA_CHAIN,a)}};F(gn,`ETHEREUM_FINALITY_THRESHOLD`,12);function _n(...e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function vn(e){let t=/* @__PURE__ */ new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!0),t}function yn(e){let t=/* @__PURE__ */ new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t}function K(e){return new TextEncoder().encode(e)}function bn(e,t,n,r){let[i]=_.findProgramAddressSync([t.toBytes(),n.toBytes(),e.toBytes()],r);return i}function q(e,t){return new n(`BRIDGE_CHAIN_READ_FAILED`,{network:`Solana`,call:e},{write:!1,cause:t})}async function xn(e,t,n){let r=await e.getAccountInfo(t);if(r){if(!r.owner.equals(n))throw q(`token account`);return de.decode(r.data).amount}}function Sn(e){let t;try{t=pe.decode(e)}catch{throw new n(`INVALID_PRIVATE_KEY`,{reason:`bad_encoding`})}if(t.length!==64)throw new n(`INVALID_PRIVATE_KEY`,{reason:`wrong_length`});try{return g.fromSecretKey(t)}catch{throw new n(`INVALID_PRIVATE_KEY`,{reason:`bad_encoding`})}}const Cn=/^[1-9A-HJ-NP-Za-km-z]{80,90}$/u;var wn=class extends fn{constructor(e){let t=e.tokenConfigs??j;super(e.galaConnectClient,Tt(t),e.sleep),F(this,`network`,`Solana`),F(this,`galaChainWalletAddress`,void 0),F(this,`ethereumWallet`,void 0),F(this,`eip712DomainName`,void 0),F(this,`solanaConnection`,void 0),F(this,`solanaKeypair`,void 0),F(this,`solanaBridgeProgramId`,void 0),F(this,`solanaBridgeTokenAuthority`,void 0),F(this,`solanaBridgeConfigPda`,void 0),F(this,`solanaNativeBridgePda`,void 0),F(this,`solanaBridgeAccountCache`,/* @__PURE__ */ new Map),F(this,`tokenMetadataResolver`,void 0);for(let e of t)it(e.mintAddress,`tokenConfigs`);this.galaChainWalletAddress=e.galaChainWalletAddress,Dt(e.ethereumPrivateKey),this.ethereumWallet=new ce(e.ethereumPrivateKey),this.eip712DomainName=e.eip712DomainName;let n=N(e.solanaRpcUrl??`https://api.mainnet-beta.solana.com`,`solanaRpcUrl`);this.solanaConnection=e.solanaConnection??new h(n,`confirmed`),this.solanaKeypair=Sn(e.solanaPrivateKeyBase58),this.solanaBridgeProgramId=it(e.solanaBridgeProgram??`AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS`,`solanaBridgeProgram`),[this.solanaBridgeTokenAuthority]=_.findProgramAddressSync([K(`bridge_token_authority`)],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=_.findProgramAddressSync([K(`configv1`)],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=_.findProgramAddressSync([K(`native_sol_bridge`)],this.solanaBridgeProgramId),this.tokenMetadataResolver=new rn({galaConnectClient:this.galaConnectClient})}async estimateFee(e){return Qt(this.galaConnectClient,this.tokenMetadataResolver,`Solana`,e)}async bridgeOut(e){return Yt(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,eip712DomainName:this.eip712DomainName,destinationChainId:D.SOLANA,destinationChain:`Solana`,validateRecipientAddress:tt})}async bridgeIn(e){let{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:i}=e,o=Xe(i);B(t);let s=n!==void 0&&n!==``?Sn(n):this.solanaKeypair,c=a(r??this.galaChainWalletAddress,`address`),l=R(this.tokenConfigs,o,`Solana`),u=await this.tokenMetadataResolver.getTokenMetadata(o),d=on(t,u.decimals);return Pt({fromChain:`Solana`,transactionHash:await this.executeSolanaBridgeOut({keypair:s,tokenConfig:l,metadata:u,amountBaseUnits:d,recipient:c,amount:t}),tokenSymbol:o,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){try{return new _(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){let r=R(this.tokenConfigs,e,`Solana`);if(r.isNative)return this.getSolanaNativeBalance(t);let i=nt(t??this.solanaKeypair.publicKey.toBase58()),a=bn(new _(r.mintAddress),i,v,ue),o;try{o=await xn(this.solanaConnection,a,v)}catch(e){throw e instanceof n?e:q(`token account`,e)}let s=r.decimals??await this.mintDecimals(new _(r.mintAddress));return W(o??0n,s)}async mintDecimals(e){let t;try{t=await this.solanaConnection.getAccountInfo(e)}catch(e){throw q(`mint`,e)}if(!t?.owner.equals(v))throw q(`mint`);return fe.decode(t.data).decimals}async getSolanaNativeBalance(e){let t=nt(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,`confirmed`);return W(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){if(typeof e!=`number`||!Number.isFinite(e)||e<1e-5||e>2)throw new n(`INVALID_BRIDGE_OPTION`,{option:`airdropAmount`});let r=t!==void 0&&t!==``?nt(t):this.solanaKeypair.publicKey;if(!this.solanaConnection.rpcEndpoint.includes(`devnet`))throw new n(`INVALID_BRIDGE_OPTION`,{option:`solanaRpcUrl`});let i=Math.floor(e*ee);return this.solanaConnection.requestAirdrop(r,i)}async getSolanaTransactionStatus(e){if(typeof e!=`string`||!Cn.test(e))throw new n(`INVALID_TRANSACTION_HASH`,{network:`Solana`,value:String(e)});let t=(await this.solanaConnection.getSignatureStatuses([e])).value[0];return t?t.err!==null&&t.err!==void 0?{confirmed:!1,status:`failed`,slot:t.slot,error:JSON.stringify(t.err)}:{confirmed:!0,status:t.confirmationStatus??`processed`,slot:t.slot}:{confirmed:!1,status:`not_found`}}async executeSolanaBridgeOut(e){let t=new _(e.tokenConfig.mintAddress),r=K(e.recipient),i=[vn(e.amountBaseUnits),yn(r.length),r],a=e.tokenConfig.isNative?this.buildNativeBridgeInstruction(e.keypair.publicKey,i):this.buildTokenBridgeInstruction(e.keypair.publicKey,bn(t,e.keypair.publicKey,v,ue),t,await this.getSolanaBridgeAccounts(t,e.tokenConfig.symbol),i),o=new ne;o.add(m.setComputeUnitPrice({microLamports:Pe.UNIT_PRICE_MICROLAMPORTS}),m.setComputeUnitLimit({units:Pe.UNIT_LIMIT}),a),o.feePayer=e.keypair.publicKey;let s={sent:!1,step:`send`,signature:``};try{let t=await this.sendAndConfirm(o,e.keypair,s);return s.step=`registration`,await this.galaConnectClient.registerBridgeTransaction({quantity:e.amount,tokenInstance:{collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:`0`},fromChain:`Solana`,toChain:`GC`,hash:t}),t}catch(e){throw s.sent?new n(`BRIDGE_DEPOSIT_OUTCOME_UNKNOWN`,{network:`Solana`,step:s.step,transactionHash:s.signature},{cause:e}):e}}async sendAndConfirm(e,t,n,r=1){let i;try{i=await this.solanaConnection.getLatestBlockhash(`confirmed`)}catch(e){throw q(`latest blockhash`,e)}e.recentBlockhash=i.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t),n.signature=pe.encode(e.signature),n.step=`send`,n.sent=!0;let a=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:`confirmed`});n.step=`confirmation`;try{return await this.solanaConnection.confirmTransaction({signature:a,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},`confirmed`),a}catch(e){if(!(e instanceof re))throw e;let{value:[t]}=await this.solanaConnection.getSignatureStatuses([a],{searchTransactionHistory:!0});if(t){if(t.err===null&&(t.confirmationStatus===`confirmed`||t.confirmationStatus===`finalized`))return a;throw e}if(r>=3)throw e}return await this.sleep(Math.min(1e3*2**(r-1),5e3)),this.sendAndConfirm(e,t,n,r+1)}buildNativeBridgeInstruction(e,t){return new ie({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!0},{pubkey:this.solanaNativeBridgePda,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:te.programId,isSigner:!1,isWritable:!1}],data:_n(Ge.BRIDGE_OUT_NATIVE,...t)})}buildTokenBridgeInstruction(e,t,n,r,i){return new ie({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:r.mintLookup,isSigner:!1,isWritable:!1},{pubkey:r.tokenBridge,isSigner:!1,isWritable:!1},{pubkey:r.bridgeTokenAccount,isSigner:!1,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:te.programId,isSigner:!1,isWritable:!1},{pubkey:v,isSigner:!1,isWritable:!1}],data:_n(Ge.BRIDGE_OUT,...i)})}async getSolanaBridgeAccounts(e,t){let r=e.toBase58(),i=this.solanaBridgeAccountCache.get(r);if(i)return i;let[a]=_.findProgramAddressSync([K(`mint_lookup_v1`),e.toBytes()],this.solanaBridgeProgramId),o=await this.solanaConnection.getAccountInfo(a,`confirmed`);if(!o)throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:`Solana`,symbol:t});if(!o.owner.equals(this.solanaBridgeProgramId)||o.data.length<40)throw q(`mint lookup`);let s={mintLookup:a,tokenBridge:new _(o.data.subarray(8,40)),bridgeTokenAccount:bn(e,this.solanaBridgeTokenAuthority,v,ue)};return this.solanaBridgeAccountCache.set(r,s),s}};function Tn(e){let t=typeof e==`string`?d(e,`|`):void 0;if(t===void 0)throw new n(`INVALID_TOKEN_REFERENCE`,{field:`tokenId`,reason:`bad_class_key`});return t}function J(e){return ke(e)}function Y(e){let t;if(typeof e==`string`)t=Tn(e);else if(s(e))t=e;else throw new n(`INVALID_TOKEN_REFERENCE`,{field:`tokenId`,reason:`bad_class_key`});let r=J(t);return{tokenClassKey:t,stringified:r}}const En={prod:{ethereum:`https://eth.gala.games`,solana:`https://api.mainnet-beta.solana.com`},stage:{ethereum:`https://dev.eth.gala.games`,solana:`https://api.devnet.solana.com`}},Dn={rateLimit:12,pollInterval:15e3,pollTimeout:27e5};function On(e,t){let r=M[e];if(r===void 0)throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:t,symbol:e});return{...r.descriptor}}var kn=class{constructor(e){if(F(this,`environment`,void 0),F(this,`pollInterval`,void 0),F(this,`pollTimeout`,void 0),F(this,`galaConnectClient`,void 0),F(this,`strategies`,void 0),F(this,`bridgeableTokenService`,void 0),typeof e.bridgeableTokenService?.getTokenByTokenId!=`function`)throw new n(`INVALID_BRIDGE_OPTION`,{option:`bridgeableTokenService`});let r=a(e.galaChainWalletAddress,`galaChainWalletAddress`);this.environment=e.environment??`prod`;let i=t[this.environment],o=En[this.environment];this.pollInterval=e.pollInterval??Dn.pollInterval,this.pollTimeout=e.pollTimeout??Dn.pollTimeout,this.galaConnectClient=new St({baseUrl:e.galaConnectBaseUrl??i.dexApiBaseUrl,galachainBaseUrl:e.galaChainApiBaseUrl??i.gatewayBaseUrl,walletAddress:r,requestsPerSecond:e.rateLimit??Dn.rateLimit,...e.httpRequestor!==void 0&&{httpRequestor:e.httpRequestor}}),this.bridgeableTokenService=e.bridgeableTokenService;let s=e.sleep===void 0?{}:{sleep:e.sleep},c=e.eip712DomainName??i.eip712DomainName;this.strategies=/* @__PURE__ */ new Map([[`Ethereum`,new gn({galaConnectClient:this.galaConnectClient,galaChainWalletAddress:r,ethereumPrivateKey:e.ethereumPrivateKey,ethereumRpcUrl:e.ethereumRpcUrl??o.ethereum,ethereumBridgeContract:e.ethereumBridgeContract??He(this.environment),tokenConfigs:A(this.environment),eip712DomainName:c,...s})]]),e.solanaPrivateKey!==void 0&&e.solanaPrivateKey!==``&&this.strategies.set(`Solana`,new wn({galaConnectClient:this.galaConnectClient,galaChainWalletAddress:r,ethereumPrivateKey:e.ethereumPrivateKey,solanaPrivateKeyBase58:e.solanaPrivateKey,solanaRpcUrl:e.solanaRpcUrl??o.solana,solanaBridgeProgram:e.solanaBridgeProgram??`AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS`,tokenConfigs:j,eip712DomainName:c,...e.solanaConnection!==void 0&&{solanaConnection:e.solanaConnection},...s}))}async resolveTokenSymbol(e,t){let r=Y(e).stringified,i=t===`Ethereum`?`ETHEREUM`:`SOLANA`,a=await this.bridgeableTokenService.getTokenByTokenId(r,i);if(!a)throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:t,symbol:r});return a.symbol}async estimateBridgeFee(e){let t=this.getStrategy(e.destinationChain),n=await this.resolveTokenSymbol(e.tokenId,e.destinationChain);return t.estimateFee(n)}async bridgeOut(e){let t=this.getStrategy(e.destinationChain);if(!t.isValidAddress(e.recipientAddress))throw new n(`INVALID_WALLET_ADDRESS`,{field:`recipientAddress`,value:String(e.recipientAddress)});B(e.amount);let r=await this.resolveTokenSymbol(e.tokenId,e.destinationChain);return this.assertTokenSupported(t,r),t.bridgeOut({...e,tokenSymbol:r})}async bridgeIn(e){let t=this.getStrategy(e.sourceChain);B(e.amount);let n=await this.resolveTokenSymbol(e.tokenId,e.sourceChain);return this.assertTokenSupported(t,n),t.bridgeIn({...e,tokenSymbol:n})}async getBridgeStatus(e){return $t(this.galaConnectClient,e)}async waitForBridgeCompletion(e,t){let n={pollInterval:t?.pollInterval??this.pollInterval,timeout:t?.timeout??this.pollTimeout,...t?.onStatusUpdate&&{onStatusUpdate:t.onStatusUpdate}};return this.getStrategy(`Ethereum`).waitForCompletion(e,n)}getSupportedBridgeTokens(e){let t=[];if(e===void 0||e===`Ethereum`)for(let e of A(this.environment))t.push({symbol:e.symbol,decimals:e.decimals,verified:!0,supportedChains:[`Ethereum`],galaChainDescriptor:On(e.symbol,`Ethereum`),externalAddresses:{ethereum:e.contractAddress}});if(e===void 0||e===`Solana`)for(let e of j){let n=t.find(t=>t.symbol===e.symbol);n?(n.supportedChains.push(`Solana`),n.externalAddresses.solana=e.mintAddress):t.push({symbol:e.symbol,decimals:e.decimals,verified:!0,supportedChains:[`Solana`],galaChainDescriptor:On(e.symbol,`Solana`),externalAddresses:{solana:e.mintAddress}})}return t}getSupportedBridgeChains(){return Array.from(this.strategies.keys())}isTokenSupported(e,t){return(t===void 0?[...this.strategies.values()]:[this.strategies.get(t)]).some(t=>t?.isTokenSupported(e)===!0)}isValidAddress(e,t){return this.strategies.get(t)?.isValidAddress(e)??!1}async getEthereumTokenBalance(e,t){return V(this.strategies).getEthereumTokenBalance(e,t)}async getEthereumNativeBalance(e){return V(this.strategies).getEthereumNativeBalance(e)}async getSolanaTokenBalance(e,t){return H(this.strategies).getSolanaTokenBalance(e,t)}async getSolanaNativeBalance(e){return H(this.strategies).getSolanaNativeBalance(e)}async fetchEthereumWalletTokenBalance(e,t){let n=V(this.strategies),r=jt(A(this.environment),e,`Ethereum`),i=U(t,n);return kt(r,await n.getEthereumTokenBalance(e,i))}async fetchEthereumWalletNativeBalance(e){let t=V(this.strategies),n=U(e,t);return z(`ETH`,await t.getEthereumNativeBalance(n),18)}async fetchSolanaWalletTokenBalance(e,t){let n=H(this.strategies),r=jt(j,e,`Solana`),i=U(t,n);return At(r,await n.getSolanaTokenBalance(e,i))}async fetchSolanaWalletNativeBalance(e){let t=H(this.strategies),n=U(e,t);return z(`SOL`,await t.getSolanaNativeBalance(n),9)}async requestSolanaDevnetAirdrop(e,t){return H(this.strategies).requestDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return H(this.strategies).getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return V(this.strategies).getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){let t=V(this.strategies),n=U(e,t),[r,i]=await Promise.all([t.getEthereumNativeBalance(n),Promise.all(A(this.environment).map(async e=>kt(e,await t.getEthereumTokenBalance(e.symbol,n))))]);return{address:n,native:z(`ETH`,r,18),tokens:i,timestamp:Date.now()}}async fetchSolanaWalletAllBalances(e){let t=H(this.strategies),n=U(e,t),[r,i]=await Promise.all([t.getSolanaNativeBalance(n),Promise.all(j.map(async e=>At(e,await t.getSolanaTokenBalance(e.symbol,n))))]);return{address:n,native:z(`SOL`,r,9),tokens:i,timestamp:Date.now()}}getStrategy(e){let t=this.strategies.get(e);if(!t)throw new n(`BRIDGE_NOT_CONFIGURED`,{network:e});return t}assertTokenSupported(e,t){if(!e.isTokenSupported(t))throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:e.network,symbol:t})}};const X=`/v1/tokens`,Z=1e3,An=1e4;function jn(e){return S(e)&&C(e,[`symbol`,`name`,`stringifiedTokenClassKey`,`collection`,`category`,`type`,`additionalKey`],{image:`string`,description:`string`})&&Number.isSafeInteger(e.decimals)&&e.decimals>=0&&typeof e.verified==`boolean`}function Mn(e){let t=x(e),n=t.status??t.statusCode;return typeof n==`number`?n:void 0}function Nn(e){if(o(e))return e;let t=Mn(e);return t===void 0?new n(`TRANSPORT_ERROR`,{url:X},{write:!1,cause:e}):new n(`GALACONNECT_HTTP_ERROR`,{method:X,status:t,serverMessage:``},{write:!1,status:t,cause:e})}async function Pn(e,t,r,i,a){let o;try{o=await e.request({method:`GET`,url:X,params:{...t,pageSize:Math.min(i,Z),offset:r}})}catch(e){throw Nn(e)}let s=x(o).tokens;if(!Array.isArray(s))throw new n(`BRIDGE_READ_RESPONSE_INVALID`,{method:X},{write:!1});return{items:a(s),rawCount:s.length}}async function Fn(e){let t=[];for(let n=0;n<An;n++){let r=await e(n*Z,Z);if(t.push(...r.items),r.rawCount!==1e3)return t}throw new n(`PAGINATION_LIMIT_EXCEEDED`,{method:X,maxPages:An},{write:!1})}const In=[`ETHEREUM`,`SOLANA`];function Ln(e){if(!jn(e))return!1;let{canBridgeTo:t,otherNetworks:n}=e;return Array.isArray(t)&&t.every(e=>S(e)&&C(e,[`network`]))&&Array.isArray(n)&&n.every(e=>S(e)&&C(e,[`network`],{contractAddress:`string`,symbol:`string`,allowanceStorageSlot:`number`}))}function Rn(e){let t=e.otherNetworks.find(e=>e.network===`Ethereum`),n=e.otherNetworks.find(e=>e.network===`Solana`),r=e.canBridgeTo.map(e=>e.network).filter(e=>e===`Ethereum`||e===`Solana`),i={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,verified:e.verified,supportedChains:r};return t?.contractAddress!==void 0&&(i.ethereumContractAddress=t.contractAddress),t?.symbol!==void 0&&(i.ethereumSymbol=t.symbol),t?.allowanceStorageSlot!==void 0&&(i.ethereumAllowanceSlot=t.allowanceStorageSlot),n?.contractAddress!==void 0&&(i.solanaContractAddress=n.contractAddress),n?.symbol!==void 0&&(i.solanaSymbol=n.symbol),e.image!==void 0&&(i.image=e.image),e.description!==void 0&&(i.description=e.description),i}var zn=class{constructor(e){this.dexApi=e,F(this,`cache`,/* @__PURE__ */ new Map)}fetchPage(e,t,n){return Pn(this.dexApi,{canBridgeTo:e.toLowerCase()},t,n,e=>e.filter(Ln).map(Rn))}store(e,t){let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let e of t){let t=E(e.symbol);n.has(t)||n.set(t,e),r.set(J(e.galaChainDescriptor),e)}this.cache.set(e,{tokens:t,bySymbol:n,byTokenId:r,fetchedAt:Date.now()})}async tokensOf(e){let t=this.cache.get(e);return t!==void 0&&t.tokens.length>0?t:(await this.fetchAllBridgeableTokensByNetwork(e),this.cache.get(e))}async fetchBridgeableTokensByNetwork(e){let{network:t,offset:n=0,limit:r=Z}=e,{items:i}=await this.fetchPage(t,n,r);return{tokens:i,network:t,fetchedAt:Date.now(),tokenCount:i.length}}async fetchAllBridgeableTokensByNetwork(e){let t=this.cache.get(e);if(t!==void 0&&t.tokens.length>0){let n=[...t.tokens];return{tokens:n,network:e,fetchedAt:t.fetchedAt,tokenCount:n.length}}let n=await Fn((t,n)=>this.fetchPage(e,t,n));return this.store(e,n),{tokens:n,network:e,fetchedAt:Date.now(),tokenCount:n.length}}async fetchAllTokensBridgeableToEthereum(){return this.fetchAllBridgeableTokensByNetwork(`ETHEREUM`)}async fetchAllTokensBridgeableToSolana(){return this.fetchAllBridgeableTokensByNetwork(`SOLANA`)}async isTokenBridgeableToNetwork(e){let{tokenId:t,network:n}=e,r=Y(t).stringified,i=(await this.tokensOf(n)).byTokenId.get(r),a={isBridgeable:i!==void 0,network:n};if(i!==void 0){a.tokenSymbol=i.symbol;let e=n===`ETHEREUM`?i.ethereumContractAddress:i.solanaContractAddress;e!==void 0&&(a.contractAddress=e)}return a}async isTokenBridgeableToEthereum(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:`ETHEREUM`})}async isTokenBridgeableToSolana(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:`SOLANA`})}async getTokenBySymbol(e,t){return(await this.tokensOf(t)).bySymbol.get(E(e))}async getTokenByTokenId(e,t){return(await this.tokensOf(t)).byTokenId.get(e)}async getContractAddress(e,t){let n=await this.getTokenBySymbol(e,t);return t===`ETHEREUM`?n?.ethereumContractAddress:n?.solanaContractAddress}async getSupportedTokenSymbols(e){return(await this.tokensOf(e)).tokens.map(e=>e.symbol)}async preload(){await Promise.all(In.map(e=>this.fetchAllBridgeableTokensByNetwork(e)))}getCacheStats(){let e={ETHEREUM:0,SOLANA:0},t={};for(let[n,r]of this.cache)e[n]=r.tokens.length,t[n]=r.fetchedAt;let n=e.ETHEREUM+e.SOLANA;return{networks:[...this.cache.keys()],totalItems:n,itemsByNetwork:e,fetchTimestamps:t,totalTokens:n,tokensByNetwork:e}}clearCache(e){e===void 0?this.cache.clear():this.cache.delete(e)}};function Bn(e){return jn(e)&&C(e,[`wrap`],{channel:`string`,trending:`boolean`,currentPrices:`object`})&&typeof e.swappable==`boolean`}function Vn(e){let t={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,wrapCounterpart:e.wrap,swappable:e.swappable,verified:e.verified};return e.channel!==void 0&&e.channel!==``&&(t.channel=e.channel),e.trending!==void 0&&(t.trending=e.trending),e.image!==void 0&&e.image!==``&&(t.image=e.image),e.description!==void 0&&e.description!==``&&(t.description=e.description),e.currentPrices!==void 0&&(t.currentPrices=e.currentPrices),t}var Hn=class{constructor(e){this.dexApi=e,F(this,`byTokenId`,/* @__PURE__ */ new Map),F(this,`fetchedAt`,null)}fetchPage(e,t){return Pn(this.dexApi,{wrappable:!0},e,t,e=>e.filter(Bn).map(Vn))}store(e){this.byTokenId.clear();for(let t of e)this.byTokenId.set(J(t.galaChainDescriptor),t);this.fetchedAt=Date.now()}async lookup(e){let t=Y(e).stringified;this.byTokenId.size===0&&await this.fetchAllWrappableTokens();let n=this.byTokenId.get(t);return n===void 0?{key:t}:{key:t,token:n}}async fetchWrappableTokens(e={}){let{offset:t=0,limit:n=Z}=e,{items:r}=await this.fetchPage(t,n);return{tokens:r,fetchedAt:Date.now(),tokenCount:r.length}}async fetchAllWrappableTokens(){if(this.byTokenId.size>0){let e=[...this.byTokenId.values()];return{tokens:e,fetchedAt:this.fetchedAt,tokenCount:e.length}}let e=await Fn((e,t)=>this.fetchPage(e,t));return this.store(e),{tokens:e,fetchedAt:Date.now(),tokenCount:e.length}}async getWrappableToken(e){return(await this.lookup(e)).token}async getWrapCounterpart(e){let t=await this.getWrappableToken(e);return t===void 0?void 0:this.getWrappableToken(t.wrapCounterpart)}async isTokenWrappable(e){let{key:t,token:n}=await this.lookup(e),r={isWrappable:n!==void 0,tokenId:t};return n!==void 0&&(r.wrapCounterpart=n.wrapCounterpart),r}getCacheStats(){return{totalItems:this.byTokenId.size,tokenCount:this.byTokenId.size,isPopulated:this.byTokenId.size>0,lastFetchedAt:this.fetchedAt}}clearCache(){this.byTokenId.clear(),this.fetchedAt=null}};const Q=`asset`,Un={[Q]:O.ASSET,music:O.MUSIC};function $(e){if(e.channel===void 0||Un[e.channel]===void 0)throw new n(`TOKEN_NOT_WRAPPABLE`,{tokenId:e.stringifiedTokenClassKey,reason:`unknown_channel`});return e.channel}var Wn=class{constructor(e){F(this,`galaConnectClient`,void 0),F(this,`wrappableTokenService`,void 0),F(this,`signer`,void 0),F(this,`walletAddress`,void 0),this.galaConnectClient=e.galaConnectClient,this.wrappableTokenService=e.wrappableTokenService,this.signer=e.signer,this.walletAddress=e.walletAddress}async wrapToken(e){return this.execute(e,`wrap`)}async unwrapToken(e){return this.execute(e,`unwrap`)}async estimateWrapFee(e,t){return this.estimate(e,t,`wrap`)}async estimateUnwrapFee(e,t){return this.estimate(e,t,`unwrap`)}async sourceToken(e,t){let r=await this.wrappableTokenService.getWrappableToken(e);if(r===void 0)throw new n(`TOKEN_NOT_WRAPPABLE`,{tokenId:typeof e==`string`?e:ke(e),reason:`not_listed`});let i=r.channel===Q;if(t===`wrap`?i:!i)throw new n(`INVALID_WRAP_DIRECTION`,{symbol:r.symbol,direction:t});return r}async estimate(e,t,n){B(t);let r=await this.sourceToken(e,n);return{fee:`0`,feeToken:`GALA`,authorizationType:n===`wrap`?`cross_channel_authorization`:`automatic`,feeChannel:n===`wrap`?$(r):Q}}async execute(e,t){let{amount:i}=e;if(B(i),this.signer===void 0)throw new n(`INVALID_BRIDGE_OPTION`,{option:`signer`});if(this.walletAddress===void 0||this.walletAddress===``)throw new n(`INVALID_BRIDGE_OPTION`,{option:`walletAddress`});let o=a(this.walletAddress,`walletAddress`),s=e.recipient===void 0||e.recipient===``?o:a(e.recipient,`recipient`),c=await this.sourceToken(e.tokenId,t),l=await this.wrappableTokenService.getWrapCounterpart(e.tokenId);if(l===void 0)throw new n(`TOKEN_NOT_WRAPPABLE`,{tokenId:c.wrapCounterpart,reason:`no_counterpart`});let d=t===`wrap`?{sourceChannel:$(c),destinationChannel:Q,destinationChannelId:O.ASSET}:{sourceChannel:Q,destinationChannel:$(l),destinationChannelId:Un[$(l)]},f=r(`galaswap-operation-`),p={quantity:i,tokenInstance:{collection:c.galaChainDescriptor.collection,category:c.galaChainDescriptor.category,type:c.galaChainDescriptor.type,additionalKey:c.galaChainDescriptor.additionalKey,instance:`0`},destinationChainId:d.destinationChannelId,recipient:s,wrap:!0,uniqueKey:f},m=await u(this.signer,`asset/bridge-contract`,`RequestTokenBridgeOut`,p),h=await this.galaConnectClient.requestBridgeOut(m);return Ze(`RequestTokenBridgeOut`,h,f),{success:!0,transactionId:await Jt(this.galaConnectClient,h,f,d.sourceChannel,Gn),fromToken:c.symbol,toToken:l.symbol,amount:i,fromChannel:d.sourceChannel,toChannel:d.destinationChannel,completedAt:Date.now()}}};function Gn(e,t){let r=x(e);if(r.Status!==1)throw new n(`BRIDGE_RESPONSE_INVALID`,{method:`BridgeTokenOut`,missing:`Status 1`});let i=r.Hash;return typeof i==`string`&&i!==``?i:t}function Kn(){let e=g.generate(),t=e.publicKey.toBase58();return{privateKey:pe.encode(e.secretKey),publicKey:t,address:t}}function qn(e){return e===``?``:e.startsWith(`0x`)?e.slice(2):e}export{We as BRIDGE_CONTRACT_ABI,dn as BaseBridgeStrategy,kn as BridgeService,me as BridgeStatusCode,zn as BridgeableTokenService,D as CHAIN_IDS,be as CROSS_RATE_TYPED_DATA_TYPES,Le as DEFAULT_ETHEREUM_BRIDGE_CONTRACT,Fe as DEFAULT_ETHEREUM_RPC_URL,Me as DEFAULT_POLL_INTERVAL_MS,Ne as DEFAULT_POLL_TIMEOUT_MS,je as DEFAULT_RATE_LIMIT_RPS,ze as DEFAULT_SOLANA_BRIDGE_PROGRAM,Ie as DEFAULT_SOLANA_RPC_URL,j as DEFAULT_SOLANA_TOKENS,Ue as ERC20_ABI,Re as ETHEREUM_BRIDGE_CONTRACT_SEPOLIA,k as ETHEREUM_TOKENS_PROD,Ve as ETHEREUM_TOKENS_STAGE,gn as EthereumBridgeStrategy,O as GALACHAIN_CHANNELS,Be as GALACONNECT_PRODUCTION_URL,he as GALA_BRIDGE_TYPED_DATA_DOMAIN,St as GalaConnectClient,ye as LEGACY_TYPED_DATA_TYPES,st as RateLimiter,Pe as SOLANA_COMPUTE,Ge as SOLANA_DISCRIMINATORS,M as STATIC_TOKEN_METADATA,wn as SolanaBridgeStrategy,Wn as WrapService,Hn as WrappableTokenService,qt as buildBridgeOutPayload,ln as compareAmounts,Kn as createSolanaWallet,cn as formatTokenAmount,Ye as formatTokenDescriptor,W as fromBaseUnits,ge as galaBridgeTypedDataDomain,He as getEthereumBridgeContractByEnvironment,qe as getEthereumTokenConfig,A as getEthereumTokensByEnvironment,xe as getGalaBridgeTypedDataTypes,Je as getSolanaTokenConfig,Ke as getStaticTokenMetadata,Ae as isValidGalaChainChannel,Y as parseTokenId,Tn as parseTokenString,J as stringifyTokenClassKey,qn as stripHexPrefix,on as toBaseUnits};
1
+ import e from"bignumber.js";import{GALA_CHAIN_ENVIRONMENTS as t,GalaSDKError as n,createUniqueKey as r,dtoOperationOf as i,galaChainUserRef as a,isGalaError as o,isTokenClassKey as s,isWalletUserRejection as c,serialize as l,signPreSend as u,splitClassKey as d,validateTimeoutMs as f,walletDeclineCode as p}from"@gala-chain/gala-core-sdk";import{ComputeBudgetProgram as m,Connection as h,Keypair as g,LAMPORTS_PER_SOL as ee,PublicKey as _,SystemProgram as te,Transaction as ne,TransactionExpiredBlockheightExceededError as re,TransactionInstruction as ie}from"@solana/web3.js";import{Contract as ae,JsonRpcProvider as oe,Signature as se,Wallet as ce,isAddress as le}from"ethers";import{ASSOCIATED_TOKEN_PROGRAM_ID as ue,AccountLayout as de,MintLayout as fe,TOKEN_PROGRAM_ID as v}from"@solana/spl-token";import{base58 as pe}from"@scure/base";let me=/* @__PURE__ */ function(e){return e[e.PENDING=0]=`PENDING`,e[e.SUBMITTED=1]=`SUBMITTED`,e[e.CONFIRMED=2]=`CONFIRMED`,e[e.PROCESSING=3]=`PROCESSING`,e[e.FINALIZING=4]=`FINALIZING`,e[e.COMPLETED=5]=`COMPLETED`,e[e.FAILED=6]=`FAILED`,e[e.DELIVERY_FAILED=7]=`DELIVERY_FAILED`,e}({});const he={name:`GalaConnect`,chainId:1};function ge(e){return e===void 0?he:{name:e,chainId:1}}const _e=[{name:`destinationChainId`,type:`uint256`},{name:`destinationChainTxFee`,type:`destinationChainTxFee`},{name:`dtoOperation`,type:`string`},{name:`quantity`,type:`string`},{name:`recipient`,type:`string`},{name:`tokenInstance`,type:`tokenInstance`},{name:`uniqueKey`,type:`string`}],ve=[{name:`collection`,type:`string`},{name:`category`,type:`string`},{name:`type`,type:`string`},{name:`additionalKey`,type:`string`}],y=[{name:`collection`,type:`string`},{name:`category`,type:`string`},{name:`type`,type:`string`},{name:`additionalKey`,type:`string`},{name:`instance`,type:`string`}],b=[{name:`name`,type:`string`},{name:`symbol`,type:`string`}],ye={GalaTransaction:_e,destinationChainTxFee:[{name:`bridgeToken`,type:`bridgeToken`},{name:`bridgeTokenIsNonFungible`,type:`bool`},{name:`estimatedPricePerTxFeeUnit`,type:`string`},{name:`estimatedTotalTxFeeInExternalToken`,type:`string`},{name:`estimatedTotalTxFeeInGala`,type:`string`},{name:`estimatedTxFeeUnitsTotal`,type:`string`},{name:`galaDecimals`,type:`uint256`},{name:`galaExchangeRate`,type:`galaExchangeRate`},{name:`timestamp`,type:`uint256`},{name:`signingIdentity`,type:`string`},{name:`signature`,type:`string`}],bridgeToken:ve,galaExchangeRate:[{name:`identity`,type:`string`},{name:`oracle`,type:`string`},{name:`source`,type:`string`},{name:`sourceUrl`,type:`string`},{name:`timestamp`,type:`uint256`},{name:`baseToken`,type:`baseToken`},{name:`exchangeRate`,type:`string`},{name:`externalQuoteToken`,type:`externalQuoteToken`}],baseToken:y,externalQuoteToken:b,tokenInstance:y},be={GalaTransaction:_e,destinationChainTxFee:[{name:`bridgeToken`,type:`bridgeToken`},{name:`bridgeTokenIsNonFungible`,type:`bool`},{name:`estimatedPricePerTxFeeUnit`,type:`string`},{name:`estimatedTotalTxFeeInExternalToken`,type:`string`},{name:`estimatedTotalTxFeeInGala`,type:`string`},{name:`estimatedTxFeeUnitsTotal`,type:`string`},{name:`galaDecimals`,type:`uint256`},{name:`galaExchangeCrossRate`,type:`galaExchangeCrossRate`},{name:`timestamp`,type:`uint256`},{name:`signingIdentity`,type:`string`},{name:`signature`,type:`string`}],bridgeToken:ve,galaExchangeCrossRate:[{name:`baseTokenCrossRate`,type:`baseTokenCrossRate`},{name:`crossRate`,type:`string`},{name:`externalCrossRateToken`,type:`externalCrossRateToken`},{name:`identity`,type:`string`},{name:`oracle`,type:`string`},{name:`quoteTokenCrossRate`,type:`quoteTokenCrossRate`},{name:`source`,type:`string`},{name:`timestamp`,type:`uint256`}],baseTokenCrossRate:[{name:`identity`,type:`string`},{name:`oracle`,type:`string`},{name:`source`,type:`string`},{name:`sourceUrl`,type:`string`},{name:`timestamp`,type:`uint256`},{name:`exchangeRate`,type:`string`},{name:`externalBaseToken`,type:`externalBaseToken`},{name:`externalQuoteToken`,type:`externalQuoteToken`},{name:`signature`,type:`string`}],externalBaseToken:b,externalQuoteToken:b,externalCrossRateToken:b,quoteTokenCrossRate:[{name:`identity`,type:`string`},{name:`oracle`,type:`string`},{name:`source`,type:`string`},{name:`sourceUrl`,type:`string`},{name:`timestamp`,type:`uint256`},{name:`baseToken`,type:`baseToken`},{name:`exchangeRate`,type:`string`},{name:`externalQuoteToken`,type:`externalQuoteToken`},{name:`signature`,type:`string`}],baseToken:y,tokenInstance:y};function xe(e){return e?be:ye}function Se(e){return e==null}function Ce(e){return e==null||e===``}function x(e){return typeof e==`object`&&e?e:{}}function S(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function C(e,t,n={}){return t.every(t=>typeof e[t]==`string`)&&Object.entries(n).every(([t,n])=>{let r=e[t];return r===void 0||(n===`object`?S(r):typeof r===n)})}function w(e,t){if(Se(e))return t;if(typeof e==`bigint`)return Number(e);if(typeof e==`number`)return isNaN(e)?t:Math.floor(e);let n=parseInt(String(e),10);return isNaN(n)?t:n}function we(e,t=0){if(Ce(e))return t;if(typeof e==`number`)return isNaN(e)||!isFinite(e)?t:e;let n=parseFloat(e);return isNaN(n)||!isFinite(n)?t:n}function Te(e,t){if(Ce(e))return t;try{return JSON.parse(e)}catch{return t}}function T(t,n=`0`){if(Ce(t))return new e(n);if(e.isBigNumber(t))return t.isNaN()?new e(n):t;try{let r=new e(t);return r.isNaN()||!r.isFinite()?new e(n):r}catch{return new e(n)}}function Ee(e){return e instanceof Error}function De(e){return Ee(e)||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`?e.message:typeof e==`string`?e:String(e)}function Oe(e){if(typeof e==`object`&&e&&`code`in e&&(typeof e.code==`string`||typeof e.code==`number`))return e.code}function E(e){return e.trim().toUpperCase()}function ke(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}const D={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},O={ASSET:1,MUSIC:3};function Ae(e){return Object.values(O).includes(e)}const je=12,Me=15e3,Ne=27e5,Pe={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},Fe=`https://ethereum.publicnode.com`,Ie=`https://api.mainnet-beta.solana.com`,Le=`0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9`,Re=`0x6a1734E09f3099a3675645D214ce547080ea67e0`,ze=`AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS`,Be=`https://dex-api-platform-dex-prod-gala.gala.com`,k=[{symbol:`GALA`,amount:`1`,contractAddress:`0xd1d2Eb1B1e90B638588728b4130137D262C87cae`,bridgeUsesPermit:!0,decimals:8},{symbol:`GWETH`,amount:`0.0001`,contractAddress:`0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2`,bridgeUsesPermit:!1,decimals:18},{symbol:`GUSDC`,amount:`1`,contractAddress:`0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48`,bridgeUsesPermit:!1,decimals:6},{symbol:`GUSDT`,amount:`1`,contractAddress:`0xdAC17F958D2ee523a2206206994597C13D831ec7`,bridgeUsesPermit:!1,decimals:6},{symbol:`GWTRX`,amount:`1`,contractAddress:`0x50327c6c5a14DCaDE707ABad2E27eB517df87AB5`,bridgeUsesPermit:!1,decimals:6},{symbol:`GWBTC`,amount:`0.00001`,contractAddress:`0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599`,bridgeUsesPermit:!1,decimals:8}],Ve=[{symbol:`GALA`,amount:`1`,contractAddress:`0x9fBFf09325C1967A135AC9b4860b1cf89aca52DA`,bridgeUsesPermit:!0,decimals:8},{symbol:`GWETH`,amount:`0.0001`,contractAddress:`0xC3F00B9CbC4221D85A66EEbe928551d0d8dD9158`,bridgeUsesPermit:!1,decimals:18},{symbol:`GUSDC`,amount:`1`,contractAddress:`0x081e78E33bfa612b23A99ef61e7c194649AA318E`,bridgeUsesPermit:!1,decimals:6},{symbol:`GUSDT`,amount:`1`,contractAddress:`0x461e3595f087bfb0E32B6e44BCbF4C74D99B0001`,bridgeUsesPermit:!1,decimals:6},{symbol:`GWBTC`,amount:`0.00001`,contractAddress:`0x5f69276935EF17e5aF5289b60aFBf6d48B344770`,bridgeUsesPermit:!1,decimals:8}];function A(e){return e===`prod`?k:Ve}function He(e){return e===`prod`?Le:Re}const j=[{symbol:`GALA`,amount:`1`,mintAddress:`eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6`,isNative:!1,decimals:8},{symbol:`GSOL`,amount:`0.001`,mintAddress:`So11111111111111111111111111111111111111111`,isNative:!0,decimals:9}],M={GALA:{descriptor:{collection:`GALA`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:8,channel:`asset`},GWETH:{descriptor:{collection:`GWETH`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:18,channel:`asset`},GUSDC:{descriptor:{collection:`GUSDC`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:6,channel:`asset`},GUSDT:{descriptor:{collection:`GUSDT`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:6,channel:`asset`},GWTRX:{descriptor:{collection:`GWTRX`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:6,channel:`asset`},GWBTC:{descriptor:{collection:`GWBTC`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:8,channel:`asset`},GSOL:{descriptor:{collection:`GSOL`,category:`Unit`,type:`none`,additionalKey:`none`},decimals:9,channel:`asset`}},Ue=[`function decimals() view returns (uint8)`,`function balanceOf(address owner) view returns (uint256)`,`function approve(address spender, uint256 value) returns (bool)`,`function allowance(address owner, address spender) view returns (uint256)`,`function transfer(address to, uint256 value) returns (bool)`,`function name() view returns (string)`,`function nonces(address owner) view returns (uint256)`,`function permit(address owner,address spender,uint256 value,uint256 deadline,uint8 v,bytes32 r,bytes32 s)`],We=[`function bridgeOut(address token,uint256 amount,uint256 tokenId,uint16 destinationChainId,bytes recipient) external`,`function bridgeOutWithPermit(address token,uint256 amount,uint16 destinationChainId,bytes recipient,uint256 deadline,uint8 v,bytes32 r,bytes32 s) external`],Ge={BRIDGE_OUT:Uint8Array.from([27,194,57,119,215,165,247,150]),BRIDGE_OUT_NATIVE:Uint8Array.from([243,44,75,224,249,206,98,79])};function Ke(e){let t=E(e);return M[t]}function qe(e){let t=E(e);return k.find(e=>E(e.symbol)===t)}function Je(e){let t=E(e);return j.find(e=>E(e.symbol)===t)}function Ye(e){return ke(e)}function Xe(e){if(e===void 0||e===``)throw new n(`INVALID_TOKEN_REFERENCE`,{field:`tokenSymbol`,reason:`missing`});return e}function Ze(e,t,r){let i=x(t),a=i.Status;if(typeof a!=`number`||a===1)return;let o=e=>{let t=i[e];return typeof t==`string`?t:``},s=i.ErrorCode;throw new n(`BRIDGE_REQUEST_REJECTED`,{method:e,chainStatus:a,errorKey:o(`ErrorKey`),serverMessage:o(`Message`)},{write:!0,body:t,...typeof s==`number`&&{status:s},...r!==void 0&&{uniqueKey:r}})}function Qe(e){if(e===void 0||e===``)throw new n(`BRIDGE_RESPONSE_INVALID`,{method:`RequestTokenBridgeOut`,missing:`bridge request id`});return e}function $e(e){let t=x(e),r=[t.Hash,t.hash].find(e=>typeof e==`string`&&e!==``);if(r===void 0)throw new n(`BRIDGE_RESPONSE_INVALID`,{method:`BridgeTokenOut`,missing:`transaction hash`});return r}function et(e,t){if(!le(e))throw new n(`INVALID_WALLET_ADDRESS`,{field:t??`address`,value:String(e)})}function tt(e,t){try{return new _(e)}catch{throw new n(`INVALID_WALLET_ADDRESS`,{field:t??`address`,value:String(e)})}}function nt(e){return tt(e)}function N(e,t){let r=``;try{r=new URL(e).protocol}catch{}if(r!==`http:`&&r!==`https:`)throw new n(`INVALID_BRIDGE_OPTION`,{option:t});return e}function rt(e,t){if(typeof e!=`string`||!le(e))throw new n(`INVALID_BRIDGE_OPTION`,{option:t});return e}function it(e,t){try{if(typeof e==`string`&&e!==``)return new _(e)}catch{}throw new n(`INVALID_BRIDGE_OPTION`,{option:t})}function P(e){"@babel/helpers - typeof";return P=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},P(e)}function at(e,t){if(P(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(P(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ot(e){var t=at(e,`string`);return P(t)==`symbol`?t:t+``}function F(e,t,n){return(t=ot(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var st=class{constructor(e){if(F(this,`minIntervalMs`,void 0),F(this,`lastTimestamp`,0),F(this,`pendingPromise`,Promise.resolve()),!(e>0))throw new n(`INVALID_BRIDGE_OPTION`,{option:`requestsPerSecond`});this.minIntervalMs=1e3/e}schedule(e){let t=this.pendingPromise.then(async()=>{let t=this.minIntervalMs-(Date.now()-this.lastTimestamp);return t>0&&await new Promise(e=>setTimeout(e,t)),this.lastTimestamp=Date.now(),e()});return this.pendingPromise=t.then(()=>void 0,()=>void 0),t}};const ct={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},lt=/* @__PURE__ */ new Set([408,429,500,502,503,504]),ut=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function dt(e){if(typeof e==`object`&&e){let t=e;if(typeof t.status==`number`)return lt.has(t.status);if(typeof t.statusCode==`number`)return lt.has(t.statusCode);let n=Oe(e);if(typeof n==`string`&&(n===`ECONNRESET`||n===`ECONNREFUSED`||n===`ETIMEDOUT`||n===`ENOTFOUND`||n===`EAI_AGAIN`))return!0}let t=De(e);return ut.some(e=>e.test(t))}function ft(e,t){let n=t.initialDelayMs*t.backoffMultiplier**(e-1),r=Math.min(n,t.maxDelayMs),i=r*t.jitterFactor*Math.random();return Math.floor(r+i)}async function pt(e,t={}){let n={...ct,...t},r=t.shouldRetry??(e=>dt(e)),i;for(let a=1;a<=n.maxRetries+1;a++)try{return await e()}catch(e){if(i=e,a>n.maxRetries||!r(e,a))break;let o=ft(a,n);t.onRetry&&t.onRetry(e,a,o),await new Promise(e=>setTimeout(e,o))}throw i}function mt(e){return new Promise(t=>setTimeout(t,e))}const I={baseUrl:Be,galachainBaseUrl:`https://galachain-gateway-chain-platform-galachain-mainnet.gala.com`,requestsPerSecond:12,requestTimeoutMs:3e4,enableRetry:!0,maxRetries:3,retryInitialDelayMs:1e3};function L(e){return e.uniqueKey===void 0?{write:e.write}:{write:!0,uniqueKey:e.uniqueKey}}function ht(e){let t=e.uniqueKey;return typeof t==`string`&&t!==``?t:void 0}function gt(e,t,r,i){let a=Te(i,{rawBody:i.slice(0,500)});return new n(`GALACONNECT_HTTP_ERROR`,{method:e.path,status:r,serverMessage:i.slice(0,500)},{...L(e),status:r,body:a,url:t})}function _t(e,t,r){return e.write?new n(`BRIDGE_WRITE_OUTCOME_UNKNOWN`,{method:e.path},{...L(e),url:t,cause:r}):new n(`TRANSPORT_ERROR`,{url:t},{write:!1,url:t,cause:r})}function vt(e,t,r,i){let a=new n(`REQUEST_TIMEOUT`,{url:t,timeoutMs:r},{...L(e),url:t,cause:i});return e.write?_t(e,t,a):a}function yt(e,t){return e.write?new n(`BRIDGE_RESPONSE_INVALID`,{method:e.path,missing:`JSON answer`},{...L(e),url:t}):new n(`BRIDGE_READ_RESPONSE_INVALID`,{method:e.path},{write:!1,url:t})}function bt(e,t,n){if(!n.ok)throw gt(e,t,n.status,n.text);if(n.text!==``)try{return JSON.parse(n.text)}catch{throw yt(e,t)}}function xt(e,t){let n=e;return n.code===`GALACONNECT_HTTP_ERROR`?n.status===429||!t.write&&dt({status:n.status}):!t.write&&dt(n.cause)}var St=class{constructor(e){F(this,`baseUrl`,void 0),F(this,`galachainBaseUrl`,void 0),F(this,`walletAddress`,void 0),F(this,`rateLimiter`,void 0),F(this,`defaultHeaders`,void 0),F(this,`retryOptions`,void 0),F(this,`requestor`,void 0),F(this,`requestTimeoutMs`,void 0),this.requestTimeoutMs=f(e.requestTimeoutMs??I.requestTimeoutMs,`requestTimeoutMs`),this.baseUrl=N(e.baseUrl??I.baseUrl,`baseUrl`),this.galachainBaseUrl=N(e.galachainBaseUrl??I.galachainBaseUrl,`galachainBaseUrl`),this.walletAddress=e.walletAddress===``?``:a(e.walletAddress,`walletAddress`),this.rateLimiter=new st(e.requestsPerSecond??I.requestsPerSecond),this.requestor=e.httpRequestor??((e,t)=>globalThis.fetch(e,t)),this.defaultHeaders={"Content-Type":`application/json`,"X-Wallet-Address":this.walletAddress};let t=e.enableRetry??I.enableRetry;this.retryOptions=t?{maxRetries:e.maxRetries??I.maxRetries,initialDelayMs:e.retryInitialDelayMs??I.retryInitialDelayMs,...e.onRetry&&{onRetry:e.onRetry}}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){let t={path:`/v1/connect/bridge-configurations`,write:!1},n=new URL(t.path,this.baseUrl);n.searchParams.set(`searchprefix`,e);let r=await this.send(n.toString(),{method:`GET`},t);if(!r.ok)throw gt(t,n.toString(),r.status,r.text);let i=Te(r.text,null)?.data?.tokens;if(!Array.isArray(i))throw yt(t,n.toString());return i}async request(e){let t={path:e.url,write:!1},n=new URL(e.url,this.baseUrl);for(let[t,r]of Object.entries(e.params))n.searchParams.set(t,String(r));return bt(t,n.toString(),await this.send(n.toString(),{method:`GET`},t))}async fetchBridgeFee(e){return this.postJson({path:`/v1/bridge/fee`,write:!1},e,{skipWalletHeader:!0})}async requestBridgeOut(e){return this.postJson({path:`/v1/RequestTokenBridgeOut`,write:!0,uniqueKey:ht(e)},e)}async bridgeTokenOut(e){return this.postJson({path:`/v1/BridgeTokenOut`,write:!0,uniqueKey:ht(e)},e)}async getBridgeStatus(e){return this.postJson({path:`/v1/bridge/status`,write:!1},{hash:e})}async registerBridgeTransaction(e){return this.postJson({path:`/v1/bridge/transaction`,write:!0,uniqueKey:ht(e)},e)}async fetchBalances(e=`asset`){return this.postJson({path:`/v1/FetchBalances`,write:!1},{owner:this.walletAddress,channel:e},{baseUrl:this.galachainBaseUrl})}async postJson(e,t,n={}){let r=new URL(e.path,n.baseUrl??this.baseUrl).toString(),i=n.skipWalletHeader?{"Content-Type":`application/json`,"X-Wallet-Address":``}:this.defaultHeaders;return bt(e,r,await this.send(r,{method:`POST`,headers:i,body:JSON.stringify(t,(e,t)=>typeof t==`bigint`?t.toString():t)},e))}async send(e,t,n){let r=()=>this.rateLimiter.schedule(async()=>{let r={...this.defaultHeaders,...t.headers};r[`X-Wallet-Address`]===``&&delete r[`X-Wallet-Address`];let i,a=new AbortController,o=this.requestTimeoutMs===1/0?void 0:setTimeout(()=>a.abort(),this.requestTimeoutMs);try{let n=await this.requestor(e,{...t,headers:r,signal:a.signal});i={ok:n.ok,status:n.status,text:await n.text()}}catch(t){throw a.signal.aborted?vt(n,e,this.requestTimeoutMs,t):_t(n,e,t)}finally{clearTimeout(o)}if(this.retryOptions&&!i.ok&&(i.status===429||i.status>=500))throw gt(n,e,i.status,i.text);return i});return this.retryOptions?pt(r,{...this.retryOptions,shouldRetry:e=>xt(e,n)}):r()}};function Ct(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function wt(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function Tt(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(E(n.symbol),n);return t}function Et(e,t){return e.get(E(t))}function R(e,t,r){let i=Et(e,t);if(!i)throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:r,symbol:t});return i}function Dt(e){if(e===void 0||!Ct(e))throw new n(`INVALID_PRIVATE_KEY`,{reason:`bad_encoding`})}function Ot(e){if(!wt(e))throw new n(`INVALID_TRANSACTION_HASH`,{network:`Ethereum`,value:String(e)})}function z(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function kt(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function At(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function jt(e,t,r){let i=e.find(e=>e.symbol===t);if(!i)throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:r,symbol:t});return i}function Mt(e,t){if(e===void 0)throw new n(`BRIDGE_NOT_CONFIGURED`,{network:t});return e}function Nt(e){return{direction:`outbound`,fromChain:`GalaChain`,toChain:e.toChain,transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,feePaid:e.feePaid,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}function Pt(e){return{direction:`inbound`,fromChain:e.fromChain,toChain:`GalaChain`,transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}function Ft(e){return{destinationChainId:e.destinationChainId,destinationChainTxFee:e.bridgeFee,quantity:e.amount,recipient:e.recipientAddress,tokenInstance:{...e.tokenDescriptor,instance:`0`}}}function It(e){let t={...e,galaDecimals:typeof e.galaDecimals==`string`?w(e.galaDecimals,0):e.galaDecimals,timestamp:typeof e.timestamp==`string`?w(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:typeof e.galaExchangeRate.timestamp==`string`?w(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){let n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:typeof n.timestamp==`string`?w(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:typeof n.baseTokenCrossRate.timestamp==`string`?w(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:typeof n.quoteTokenCrossRate.timestamp==`string`?w(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}function Lt(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r&&typeof r==`object`&&!Array.isArray(r)?Lt(r):r);return t}function Rt(e){let t=x(e);if(typeof t.Data==`string`)return t.Data;let n=t.data;if(typeof n==`string`)return n;let r=x(n).Data;return typeof r==`string`?r:void 0}function B(e){let t=we(e,-1);if(t<=0)throw new n(`INVALID_BRIDGE_AMOUNT`,{value:String(e),reason:`not_positive`});return t}function zt(e,t,n){return{descriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},decimals:t,...n===void 0?{}:{channel:n}}}function Bt(e){let t=e;if(!S(t)||typeof t.estimatedTotalTxFeeInGala!=`string`||!(S(t.galaExchangeRate)||S(t.galaExchangeCrossRate)))throw Ht(`/v1/bridge/fee`);return e}function Vt(e){if(!S(e))throw Ht(`/v1/bridge/status`);return e}function Ht(e){return new n(`BRIDGE_READ_RESPONSE_INVALID`,{method:e},{write:!1})}function Ut(e){let t=typeof e.timestamp==`string`?w(e.timestamp,0):e.timestamp;return{estimatedFeeInGala:e.estimatedTotalTxFeeInGala,estimatedFeeInExternalToken:e.estimatedTotalTxFeeInExternalToken,feeToken:e.bridgeToken,pricePerUnit:e.estimatedPricePerTxFeeUnit,estimatedGasUnits:e.estimatedTxFeeUnitsTotal,exchangeRate:e.galaExchangeRate?.exchangeRate??`0`,timestamp:t,raw:e}}function Wt(e){let t=typeof e==`string`&&/^\d+$/u.test(e)?Number(e):e;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<=0)throw new n(`INVALID_BRIDGE_OPTION`,{option:`destinationChainId`});return t}const Gt=`RequestTokenBridgeOut`,Kt=`asset/token-contract`;async function qt(e,t,r,i){let a;try{a=await e.signTypedData(t,r,i)}catch(e){throw o(e)?e:new n(`SIGNING_FAILED`,{method:Gt,reason:c(e)?`user_rejected`:`failed`},{cause:e,walletCode:p(e)})}if(typeof a!=`string`)throw new n(`SIGNING_FAILED`,{method:Gt,reason:`failed`},{cause:a});return a}async function Jt(e,t){let{wallet:n}=t,a=Wt(e.destinationChainId),o=e.uniqueKey??r(`galaconnect-operation-`),s=It(e.destinationChainTxFee),c=!!s.galaExchangeCrossRate,u={destinationChainId:a,destinationChainTxFee:Lt(c?{...s,galaExchangeRate:void 0}:{...s,galaExchangeCrossRate:void 0}),dtoOperation:i(Kt,Gt),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:o},d=xe(c),f=ge(t.eip712DomainName),p=await qt(n,f,d,u),m=`\u0019Ethereum Signed Message:\n${l({domain:f,message:u,primaryType:`GalaTransaction`,types:d}).length}`;return{...u,signature:p,prefix:m,types:d,domain:f}}async function Yt(e,t,r,i,a){let o=`request_id`,s=``;try{s=Qe(Rt(t)),o=`bridge_token_out`;let n=await e.bridgeTokenOut({bridgeFromChannel:i,bridgeRequestId:s});return Ze(`BridgeTokenOut`,n),o=`transaction_hash`,a(n,s)}catch(e){throw new n(`BRIDGE_OUT_OUTCOME_UNKNOWN`,{step:o,bridgeRequestId:s},{uniqueKey:r,cause:e})}}async function Xt(e,t){let{amount:n,recipientAddress:r,tokenSymbol:i}=e,{galaConnectClient:a,tokenMetadataResolver:o,ethereumWallet:s,eip712DomainName:c,destinationChainId:l,destinationChain:u,validateRecipientAddress:d}=t,f=Xe(i);B(n),d(r,`recipient`);let p=await o.getTokenMetadata(f),m=Bt(await a.fetchBridgeFee({chainId:u,bridgeToken:p.descriptor})),h=await Jt(Ft({destinationChainId:l,bridgeFee:m,amount:n,recipientAddress:r,tokenDescriptor:p.descriptor}),{wallet:s,eip712DomainName:c}),g=await a.requestBridgeOut(h);return Ze(`RequestTokenBridgeOut`,g,h.uniqueKey),Nt({toChain:u,transactionHash:await Yt(a,g,h.uniqueKey,`asset`,$e),tokenSymbol:f,amount:n,feePaid:m.estimatedTotalTxFeeInGala,baseUrl:a.getBaseUrl()})}const Zt={COMPLETED:5,FAILED:6,DELIVERY_FAILED:7};function Qt(e){let t=e.status,n=w(t,0);return{status:n,statusDescription:e.statusDescription,fromChain:e.fromChain,toChain:e.toChain,quantity:e.quantity,transactionHash:e.emitterTransactionHash,tokenInstance:e.tokenInstance,isComplete:n===Number(Zt.COMPLETED),isFailed:n===Number(Zt.FAILED)||n===Number(Zt.DELIVERY_FAILED)}}function V(e){return Mt(e.get(`Ethereum`),`Ethereum`)}function H(e){return Mt(e.get(`Solana`),`Solana`)}function U(e,t){return e??t.getWalletAddress()}async function $t(e,t,n,r){let i=await t.getTokenMetadata(r);return Ut(Bt(await e.fetchBridgeFee({chainId:n,bridgeToken:i.descriptor})))}async function en(e,t){return Qt(Vt(await e.getBridgeStatus(t)))}function tn(e){return Array.from(e.keys())}function nn(e,t){return e.has(E(t))}function rn(e){return[e.collection,e.category,e.type,e.additionalKey].every(e=>typeof e==`string`)&&Number.isSafeInteger(e.decimals)&&e.decimals>=0&&(e.channel===void 0||typeof e.channel==`string`)}var an=class{constructor(e){F(this,`galaConnectClient`,void 0),F(this,`cache`,/* @__PURE__ */ new Map),this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){let t=E(e),n=this.cache.get(t);if(n)return n;let r=M[t];if(r!==void 0)return this.cache.set(t,r),r;let i=await this.fetchFromApi(e);return this.cache.set(t,i),i}async fetchFromApi(e){let t=(await this.galaConnectClient.getBridgeConfigurations(e)).find(t=>typeof t.symbol==`string`&&E(t.symbol)===E(e)&&t.verified===!0);if(!t)throw new n(`BRIDGE_TOKEN_NOT_FOUND`,{symbol:e},{write:!1});if(!rn(t))throw new n(`BRIDGE_READ_RESPONSE_INVALID`,{method:`/v1/connect/bridge-configurations`},{write:!1});return zt({collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey},t.decimals,t.channel)}};function on(t){if(typeof t==`string`&&t!==``)try{let n=new e(t);return n.isFinite()?n:void 0}catch{return}}function sn(e,t){let r=on(e);if(r===void 0)throw new n(`INVALID_BRIDGE_AMOUNT`,{value:String(e),reason:`not_a_number`});let i=r.multipliedBy(T(10).pow(t));if(!i.isInteger())throw new n(`INVALID_BRIDGE_AMOUNT`,{value:e,reason:`too_many_decimals`});return BigInt(i.toFixed(0))}function W(e,t){return cn(T(e.toString()).dividedBy(T(10).pow(t)).toFixed(t))}function cn(e){return e.includes(`.`)?e.replace(/\.?0+$/u,``):e}function ln(e,t=6){let n=T(e);if(n.abs().lt(1e-6)&&!n.isZero())return n.toExponential(2);let r=Math.min(t,n.abs().lt(1)?t:n.abs().lt(100)?4:2);return cn(n.toFixed(r))}function un(e,t){let n=T(e),r=T(t);return n.comparedTo(r)}const dn=/* @__PURE__ */ new Set([5,6,7]);var fn=class{constructor(e=mt){F(this,`sleep`,void 0),this.sleep=e}async waitForCompletion(e,t={}){let{pollInterval:r=15e3,timeout:i=27e5,onStatusUpdate:a}=t;for(let[e,t]of[[`pollInterval`,r],[`timeout`,i]])if(!Number.isFinite(t)||t<0)throw new n(`INVALID_BRIDGE_OPTION`,{option:e});let o=Date.now();for(;;){let t=await this.getStatus(e);if(a&&a(t),dn.has(t.status))return t;if(Date.now()-o>i)throw new n(`BRIDGE_STATUS_TIMEOUT`,{transactionHash:e,timeoutMs:i,lastStatus:t.status},{write:!1});await this.sleep(r)}}},pn=class extends fn{constructor(e,t,n){super(n),F(this,`galaConnectClient`,void 0),F(this,`tokenConfigs`,void 0),this.galaConnectClient=e,this.tokenConfigs=t}async getStatus(e){return en(this.galaConnectClient,e)}getSupportedTokens(){return tn(this.tokenConfigs)}isTokenSupported(e){return nn(this.tokenConfigs,e)}};function mn(e,t){return new ae(e,Ue,t)}async function G(e,t){try{return await t()}catch(t){throw new n(`BRIDGE_CHAIN_READ_FAILED`,{network:`Ethereum`,call:e},{write:!1,cause:t})}}function hn(e,t,r){return new n(`BRIDGE_DEPOSIT_OUTCOME_UNKNOWN`,{network:`Ethereum`,step:e,transactionHash:t},{cause:r})}const gn=/^0x[0-9a-fA-F]{40}$/u;var _n=class e extends pn{constructor(e){let t=e.tokenConfigs??k;super(e.galaConnectClient,Tt(t),e.sleep),F(this,`network`,`Ethereum`),F(this,`galaChainWalletAddress`,void 0),F(this,`ethereumProvider`,void 0),F(this,`ethereumWallet`,void 0),F(this,`ethereumBridgeContract`,void 0),F(this,`ethereumWalletAddress`,void 0),F(this,`tokenMetadataResolver`,void 0),F(this,`eip712DomainName`,void 0);for(let e of t)rt(e.contractAddress,`tokenConfigs`);this.galaChainWalletAddress=e.galaChainWalletAddress,Dt(e.ethereumPrivateKey);let n=rt(e.ethereumBridgeContract,`ethereumBridgeContract`),r=N(e.ethereumRpcUrl??`https://ethereum.publicnode.com`,`ethereumRpcUrl`);e.ethereumWalletAddress!==void 0&&rt(e.ethereumWalletAddress,`ethereumWalletAddress`),this.ethereumProvider=new oe(r),this.eip712DomainName=e.eip712DomainName,this.ethereumWallet=new ce(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=n,this.tokenMetadataResolver=new an({galaConnectClient:this.galaConnectClient})}async estimateFee(e){return $t(this.galaConnectClient,this.tokenMetadataResolver,`Ethereum`,e)}async bridgeOut(e){return Xt(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,eip712DomainName:this.eip712DomainName,destinationChainId:D.ETHEREUM,destinationChain:`Ethereum`,validateRecipientAddress:et})}async bridgeIn(e){let{amount:t,sourcePrivateKey:r,recipientAddress:i,tokenSymbol:o}=e,s=Xe(o);B(t);let c=r!==void 0&&r!==``;c&&Dt(r);let l=a(i??this.galaChainWalletAddress,`address`),u=c?new ce(r,this.ethereumProvider):this.ethereumWallet,d=R(this.tokenConfigs,s,`Ethereum`),f=await this.tokenMetadataResolver.getTokenMetadata(s),p=mn(d.contractAddress,u),m=Number(await G(`decimals`,()=>p.decimals())),h=sn(t,m),g=await G(`balanceOf`,()=>p.balanceOf(u.address));if(g<h)throw new n(`INSUFFICIENT_BRIDGE_BALANCE`,{network:`Ethereum`,symbol:s,needed:W(h,m),available:W(g,m)});return Pt({fromChain:`Ethereum`,transactionHash:await this.executeBridgeDeposit({wallet:u,tokenContract:p,tokenConfig:d,amountBaseUnits:h,decimals:m,recipient:l,metadata:f}),tokenSymbol:s,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){return gn.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,t){let n=R(this.tokenConfigs,e,`Ethereum`),r=t??this.ethereumWalletAddress;et(r);let i=mn(n.contractAddress,this.ethereumProvider);return W(await G(`balanceOf`,()=>i.balanceOf(r)),n.decimals??Number(await G(`decimals`,()=>i.decimals())))}async getEthereumNativeBalance(e){let t=e??this.ethereumWalletAddress;return et(t),W(await this.ethereumProvider.getBalance(t),18)}async getEthereumTransactionStatus(t){Ot(t);let n=t.toLowerCase();try{let t=await this.ethereumProvider.getTransactionReceipt(n);if(t){let r=await this.ethereumProvider.getBlockNumber()-t.blockNumber+1;return t.status===1?{confirmed:!0,status:r>=e.ETHEREUM_FINALITY_THRESHOLD?`finalized`:`confirmed`,blockNumber:t.blockNumber,confirmations:r,transactionHash:n,gasUsed:t.gasUsed.toString(),effectiveGasPrice:t.gasPrice.toString()}:{confirmed:!1,status:`failed`,blockNumber:t.blockNumber,confirmations:r,transactionHash:n,gasUsed:t.gasUsed.toString(),effectiveGasPrice:t.gasPrice.toString(),error:`Transaction reverted during execution`}}return await this.ethereumProvider.getTransaction(n)?{confirmed:!1,status:`pending`,transactionHash:n}:{confirmed:!1,status:`not_found`,transactionHash:n,error:`Transaction not found on Ethereum network`}}catch(e){return{confirmed:!1,status:`not_found`,transactionHash:n,error:`Failed to query transaction status: ${De(e)}`}}}async executeBridgeDeposit(e){let t=new ae(this.ethereumBridgeContract,We,e.wallet),n=new TextEncoder().encode(e.recipient),r=e.tokenConfig.bridgeUsesPermit?await this.prepareBridgeWithPermit(e.wallet,e.tokenContract,e.tokenConfig,t,e.amountBaseUnits,n):await this.prepareBridgeWithApproval(e.wallet,e.tokenContract,t,e.tokenConfig,e.amountBaseUnits,n),i;try{i=await r()}catch(e){throw hn(`send`,``,e)}try{await i.wait()}catch(e){throw hn(`confirmation`,i.hash,e)}try{await this.sleep(3e4),await this.galaConnectClient.registerBridgeTransaction({quantity:W(e.amountBaseUnits,e.decimals),tokenInstance:{collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:`0`},fromChain:`Ethereum`,toChain:`GC`,hash:i.hash})}catch(e){throw hn(`registration`,i.hash,e)}return i.hash}async prepareBridgeWithPermit(e,t,n,r,i,a){let o=await G(`chainId`,()=>this.ethereumProvider.getNetwork()),s=await G(`name`,()=>t.name()),c=await G(`nonces`,()=>t.nonces(e.address)),l=BigInt(Math.floor(Date.now()/1e3)+3600),u=await e.signTypedData({name:s,version:`1`,chainId:Number(o.chainId),verifyingContract:n.contractAddress},{Permit:[{name:`owner`,type:`address`},{name:`spender`,type:`address`},{name:`value`,type:`uint256`},{name:`nonce`,type:`uint256`},{name:`deadline`,type:`uint256`}]},{owner:e.address,spender:this.ethereumBridgeContract,value:i,nonce:c,deadline:l}),d=se.from(u);return()=>r.bridgeOutWithPermit(n.contractAddress,i,D.GALA_CHAIN,a,l,d.v,d.r,d.s)}async prepareBridgeWithApproval(e,t,n,r,i,a){return await G(`allowance`,()=>t.allowance(e.address,this.ethereumBridgeContract))<i&&await(await t.approve(this.ethereumBridgeContract,i)).wait(),()=>n.bridgeOut(r.contractAddress,i,0,D.GALA_CHAIN,a)}};F(_n,`ETHEREUM_FINALITY_THRESHOLD`,12);function vn(...e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function yn(e){let t=/* @__PURE__ */ new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!0),t}function bn(e){let t=/* @__PURE__ */ new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t}function K(e){return new TextEncoder().encode(e)}function xn(e,t,n,r){let[i]=_.findProgramAddressSync([t.toBytes(),n.toBytes(),e.toBytes()],r);return i}function q(e,t){return new n(`BRIDGE_CHAIN_READ_FAILED`,{network:`Solana`,call:e},{write:!1,cause:t})}async function Sn(e,t,n){let r=await e.getAccountInfo(t);if(r){if(!r.owner.equals(n))throw q(`token account`);return de.decode(r.data).amount}}function Cn(e){let t;try{t=pe.decode(e)}catch{throw new n(`INVALID_PRIVATE_KEY`,{reason:`bad_encoding`})}if(t.length!==64)throw new n(`INVALID_PRIVATE_KEY`,{reason:`wrong_length`});try{return g.fromSecretKey(t)}catch{throw new n(`INVALID_PRIVATE_KEY`,{reason:`bad_encoding`})}}const wn=/^[1-9A-HJ-NP-Za-km-z]{80,90}$/u;var Tn=class extends pn{constructor(e){let t=e.tokenConfigs??j;super(e.galaConnectClient,Tt(t),e.sleep),F(this,`network`,`Solana`),F(this,`galaChainWalletAddress`,void 0),F(this,`ethereumWallet`,void 0),F(this,`eip712DomainName`,void 0),F(this,`solanaConnection`,void 0),F(this,`solanaKeypair`,void 0),F(this,`solanaBridgeProgramId`,void 0),F(this,`solanaBridgeTokenAuthority`,void 0),F(this,`solanaBridgeConfigPda`,void 0),F(this,`solanaNativeBridgePda`,void 0),F(this,`solanaBridgeAccountCache`,/* @__PURE__ */ new Map),F(this,`tokenMetadataResolver`,void 0);for(let e of t)it(e.mintAddress,`tokenConfigs`);this.galaChainWalletAddress=e.galaChainWalletAddress,Dt(e.ethereumPrivateKey),this.ethereumWallet=new ce(e.ethereumPrivateKey),this.eip712DomainName=e.eip712DomainName;let n=N(e.solanaRpcUrl??`https://api.mainnet-beta.solana.com`,`solanaRpcUrl`);this.solanaConnection=e.solanaConnection??new h(n,`confirmed`),this.solanaKeypair=Cn(e.solanaPrivateKeyBase58),this.solanaBridgeProgramId=it(e.solanaBridgeProgram??`AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS`,`solanaBridgeProgram`),[this.solanaBridgeTokenAuthority]=_.findProgramAddressSync([K(`bridge_token_authority`)],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=_.findProgramAddressSync([K(`configv1`)],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=_.findProgramAddressSync([K(`native_sol_bridge`)],this.solanaBridgeProgramId),this.tokenMetadataResolver=new an({galaConnectClient:this.galaConnectClient})}async estimateFee(e){return $t(this.galaConnectClient,this.tokenMetadataResolver,`Solana`,e)}async bridgeOut(e){return Xt(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,eip712DomainName:this.eip712DomainName,destinationChainId:D.SOLANA,destinationChain:`Solana`,validateRecipientAddress:tt})}async bridgeIn(e){let{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:i}=e,o=Xe(i);B(t);let s=n!==void 0&&n!==``?Cn(n):this.solanaKeypair,c=a(r??this.galaChainWalletAddress,`address`),l=R(this.tokenConfigs,o,`Solana`),u=await this.tokenMetadataResolver.getTokenMetadata(o),d=sn(t,u.decimals);return Pt({fromChain:`Solana`,transactionHash:await this.executeSolanaBridgeOut({keypair:s,tokenConfig:l,metadata:u,amountBaseUnits:d,recipient:c,amount:t}),tokenSymbol:o,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){try{return new _(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){let r=R(this.tokenConfigs,e,`Solana`);if(r.isNative)return this.getSolanaNativeBalance(t);let i=nt(t??this.solanaKeypair.publicKey.toBase58()),a=xn(new _(r.mintAddress),i,v,ue),o;try{o=await Sn(this.solanaConnection,a,v)}catch(e){throw e instanceof n?e:q(`token account`,e)}let s=r.decimals??await this.mintDecimals(new _(r.mintAddress));return W(o??0n,s)}async mintDecimals(e){let t;try{t=await this.solanaConnection.getAccountInfo(e)}catch(e){throw q(`mint`,e)}if(!t?.owner.equals(v))throw q(`mint`);return fe.decode(t.data).decimals}async getSolanaNativeBalance(e){let t=nt(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,`confirmed`);return W(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){if(typeof e!=`number`||!Number.isFinite(e)||e<1e-5||e>2)throw new n(`INVALID_BRIDGE_OPTION`,{option:`airdropAmount`});let r=t!==void 0&&t!==``?nt(t):this.solanaKeypair.publicKey;if(!this.solanaConnection.rpcEndpoint.includes(`devnet`))throw new n(`INVALID_BRIDGE_OPTION`,{option:`solanaRpcUrl`});let i=Math.floor(e*ee);return this.solanaConnection.requestAirdrop(r,i)}async getSolanaTransactionStatus(e){if(typeof e!=`string`||!wn.test(e))throw new n(`INVALID_TRANSACTION_HASH`,{network:`Solana`,value:String(e)});let t=(await this.solanaConnection.getSignatureStatuses([e])).value[0];return t?t.err!==null&&t.err!==void 0?{confirmed:!1,status:`failed`,slot:t.slot,error:JSON.stringify(t.err)}:{confirmed:!0,status:t.confirmationStatus??`processed`,slot:t.slot}:{confirmed:!1,status:`not_found`}}async executeSolanaBridgeOut(e){let t=new _(e.tokenConfig.mintAddress),r=K(e.recipient),i=[yn(e.amountBaseUnits),bn(r.length),r],a=e.tokenConfig.isNative?this.buildNativeBridgeInstruction(e.keypair.publicKey,i):this.buildTokenBridgeInstruction(e.keypair.publicKey,xn(t,e.keypair.publicKey,v,ue),t,await this.getSolanaBridgeAccounts(t,e.tokenConfig.symbol),i),o=new ne;o.add(m.setComputeUnitPrice({microLamports:Pe.UNIT_PRICE_MICROLAMPORTS}),m.setComputeUnitLimit({units:Pe.UNIT_LIMIT}),a),o.feePayer=e.keypair.publicKey;let s={sent:!1,step:`send`,signature:``};try{let t=await this.sendAndConfirm(o,e.keypair,s);return s.step=`registration`,await this.galaConnectClient.registerBridgeTransaction({quantity:e.amount,tokenInstance:{collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:`0`},fromChain:`Solana`,toChain:`GC`,hash:t}),t}catch(e){throw s.sent?new n(`BRIDGE_DEPOSIT_OUTCOME_UNKNOWN`,{network:`Solana`,step:s.step,transactionHash:s.signature},{cause:e}):e}}async sendAndConfirm(e,t,n,r=1){let i;try{i=await this.solanaConnection.getLatestBlockhash(`confirmed`)}catch(e){throw q(`latest blockhash`,e)}e.recentBlockhash=i.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t),n.signature=pe.encode(e.signature),n.step=`send`,n.sent=!0;let a=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:`confirmed`});n.step=`confirmation`;try{return await this.solanaConnection.confirmTransaction({signature:a,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},`confirmed`),a}catch(e){if(!(e instanceof re))throw e;let{value:[t]}=await this.solanaConnection.getSignatureStatuses([a],{searchTransactionHistory:!0});if(t){if(t.err===null&&(t.confirmationStatus===`confirmed`||t.confirmationStatus===`finalized`))return a;throw e}if(r>=3)throw e}return await this.sleep(Math.min(1e3*2**(r-1),5e3)),this.sendAndConfirm(e,t,n,r+1)}buildNativeBridgeInstruction(e,t){return new ie({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!0},{pubkey:this.solanaNativeBridgePda,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:te.programId,isSigner:!1,isWritable:!1}],data:vn(Ge.BRIDGE_OUT_NATIVE,...t)})}buildTokenBridgeInstruction(e,t,n,r,i){return new ie({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:r.mintLookup,isSigner:!1,isWritable:!1},{pubkey:r.tokenBridge,isSigner:!1,isWritable:!1},{pubkey:r.bridgeTokenAccount,isSigner:!1,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:te.programId,isSigner:!1,isWritable:!1},{pubkey:v,isSigner:!1,isWritable:!1}],data:vn(Ge.BRIDGE_OUT,...i)})}async getSolanaBridgeAccounts(e,t){let r=e.toBase58(),i=this.solanaBridgeAccountCache.get(r);if(i)return i;let[a]=_.findProgramAddressSync([K(`mint_lookup_v1`),e.toBytes()],this.solanaBridgeProgramId),o=await this.solanaConnection.getAccountInfo(a,`confirmed`);if(!o)throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:`Solana`,symbol:t});if(!o.owner.equals(this.solanaBridgeProgramId)||o.data.length<40)throw q(`mint lookup`);let s={mintLookup:a,tokenBridge:new _(o.data.subarray(8,40)),bridgeTokenAccount:xn(e,this.solanaBridgeTokenAuthority,v,ue)};return this.solanaBridgeAccountCache.set(r,s),s}};function En(e){let t=typeof e==`string`?d(e,`|`):void 0;if(t===void 0)throw new n(`INVALID_TOKEN_REFERENCE`,{field:`tokenId`,reason:`bad_class_key`});return t}function J(e){return ke(e)}function Y(e){let t;if(typeof e==`string`)t=En(e);else if(s(e))t=e;else throw new n(`INVALID_TOKEN_REFERENCE`,{field:`tokenId`,reason:`bad_class_key`});let r=J(t);return{tokenClassKey:t,stringified:r}}const Dn={prod:{ethereum:`https://eth.gala.games`,solana:`https://api.mainnet-beta.solana.com`},stage:{ethereum:`https://dev.eth.gala.games`,solana:`https://api.devnet.solana.com`}},On={rateLimit:12,pollInterval:15e3,pollTimeout:27e5};function kn(e,t){let r=M[e];if(r===void 0)throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:t,symbol:e});return{...r.descriptor}}var An=class{constructor(e){if(F(this,`environment`,void 0),F(this,`pollInterval`,void 0),F(this,`pollTimeout`,void 0),F(this,`galaConnectClient`,void 0),F(this,`strategies`,void 0),F(this,`bridgeableTokenService`,void 0),typeof e.bridgeableTokenService?.getTokenByTokenId!=`function`)throw new n(`INVALID_BRIDGE_OPTION`,{option:`bridgeableTokenService`});let r=a(e.galaChainWalletAddress,`galaChainWalletAddress`);this.environment=e.environment??`prod`;let i=t[this.environment],o=Dn[this.environment];this.pollInterval=e.pollInterval??On.pollInterval,this.pollTimeout=e.pollTimeout??On.pollTimeout,this.galaConnectClient=new St({baseUrl:e.galaConnectBaseUrl??i.dexApiBaseUrl,galachainBaseUrl:e.galaChainApiBaseUrl??i.gatewayBaseUrl,walletAddress:r,requestsPerSecond:e.rateLimit??On.rateLimit,...e.httpRequestor!==void 0&&{httpRequestor:e.httpRequestor}}),this.bridgeableTokenService=e.bridgeableTokenService;let s=e.sleep===void 0?{}:{sleep:e.sleep},c=e.eip712DomainName??i.eip712DomainName;this.strategies=/* @__PURE__ */ new Map([[`Ethereum`,new _n({galaConnectClient:this.galaConnectClient,galaChainWalletAddress:r,ethereumPrivateKey:e.ethereumPrivateKey,ethereumRpcUrl:e.ethereumRpcUrl??o.ethereum,ethereumBridgeContract:e.ethereumBridgeContract??He(this.environment),tokenConfigs:A(this.environment),eip712DomainName:c,...s})]]),e.solanaPrivateKey!==void 0&&e.solanaPrivateKey!==``&&this.strategies.set(`Solana`,new Tn({galaConnectClient:this.galaConnectClient,galaChainWalletAddress:r,ethereumPrivateKey:e.ethereumPrivateKey,solanaPrivateKeyBase58:e.solanaPrivateKey,solanaRpcUrl:e.solanaRpcUrl??o.solana,solanaBridgeProgram:e.solanaBridgeProgram??`AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS`,tokenConfigs:j,eip712DomainName:c,...e.solanaConnection!==void 0&&{solanaConnection:e.solanaConnection},...s}))}async resolveTokenSymbol(e,t){let r=Y(e).stringified,i=t===`Ethereum`?`ETHEREUM`:`SOLANA`,a=await this.bridgeableTokenService.getTokenByTokenId(r,i);if(!a)throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:t,symbol:r});return a.symbol}async estimateBridgeFee(e){let t=this.getStrategy(e.destinationChain),n=await this.resolveTokenSymbol(e.tokenId,e.destinationChain);return t.estimateFee(n)}async bridgeOut(e){let t=this.getStrategy(e.destinationChain);if(!t.isValidAddress(e.recipientAddress))throw new n(`INVALID_WALLET_ADDRESS`,{field:`recipientAddress`,value:String(e.recipientAddress)});B(e.amount);let r=await this.resolveTokenSymbol(e.tokenId,e.destinationChain);return this.assertTokenSupported(t,r),t.bridgeOut({...e,tokenSymbol:r})}async bridgeIn(e){let t=this.getStrategy(e.sourceChain);B(e.amount);let n=await this.resolveTokenSymbol(e.tokenId,e.sourceChain);return this.assertTokenSupported(t,n),t.bridgeIn({...e,tokenSymbol:n})}async getBridgeStatus(e){return en(this.galaConnectClient,e)}async waitForBridgeCompletion(e,t){let n={pollInterval:t?.pollInterval??this.pollInterval,timeout:t?.timeout??this.pollTimeout,...t?.onStatusUpdate&&{onStatusUpdate:t.onStatusUpdate}};return this.getStrategy(`Ethereum`).waitForCompletion(e,n)}getSupportedBridgeTokens(e){let t=[];if(e===void 0||e===`Ethereum`)for(let e of A(this.environment))t.push({symbol:e.symbol,decimals:e.decimals,verified:!0,supportedChains:[`Ethereum`],galaChainDescriptor:kn(e.symbol,`Ethereum`),externalAddresses:{ethereum:e.contractAddress}});if(e===void 0||e===`Solana`)for(let e of j){let n=t.find(t=>t.symbol===e.symbol);n?(n.supportedChains.push(`Solana`),n.externalAddresses.solana=e.mintAddress):t.push({symbol:e.symbol,decimals:e.decimals,verified:!0,supportedChains:[`Solana`],galaChainDescriptor:kn(e.symbol,`Solana`),externalAddresses:{solana:e.mintAddress}})}return t}getSupportedBridgeChains(){return Array.from(this.strategies.keys())}isTokenSupported(e,t){return(t===void 0?[...this.strategies.values()]:[this.strategies.get(t)]).some(t=>t?.isTokenSupported(e)===!0)}isValidAddress(e,t){return this.strategies.get(t)?.isValidAddress(e)??!1}async getEthereumTokenBalance(e,t){return V(this.strategies).getEthereumTokenBalance(e,t)}async getEthereumNativeBalance(e){return V(this.strategies).getEthereumNativeBalance(e)}async getSolanaTokenBalance(e,t){return H(this.strategies).getSolanaTokenBalance(e,t)}async getSolanaNativeBalance(e){return H(this.strategies).getSolanaNativeBalance(e)}async fetchEthereumWalletTokenBalance(e,t){let n=V(this.strategies),r=jt(A(this.environment),e,`Ethereum`),i=U(t,n);return kt(r,await n.getEthereumTokenBalance(e,i))}async fetchEthereumWalletNativeBalance(e){let t=V(this.strategies),n=U(e,t);return z(`ETH`,await t.getEthereumNativeBalance(n),18)}async fetchSolanaWalletTokenBalance(e,t){let n=H(this.strategies),r=jt(j,e,`Solana`),i=U(t,n);return At(r,await n.getSolanaTokenBalance(e,i))}async fetchSolanaWalletNativeBalance(e){let t=H(this.strategies),n=U(e,t);return z(`SOL`,await t.getSolanaNativeBalance(n),9)}async requestSolanaDevnetAirdrop(e,t){return H(this.strategies).requestDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return H(this.strategies).getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return V(this.strategies).getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){let t=V(this.strategies),n=U(e,t),[r,i]=await Promise.all([t.getEthereumNativeBalance(n),Promise.all(A(this.environment).map(async e=>kt(e,await t.getEthereumTokenBalance(e.symbol,n))))]);return{address:n,native:z(`ETH`,r,18),tokens:i,timestamp:Date.now()}}async fetchSolanaWalletAllBalances(e){let t=H(this.strategies),n=U(e,t),[r,i]=await Promise.all([t.getSolanaNativeBalance(n),Promise.all(j.map(async e=>At(e,await t.getSolanaTokenBalance(e.symbol,n))))]);return{address:n,native:z(`SOL`,r,9),tokens:i,timestamp:Date.now()}}getStrategy(e){let t=this.strategies.get(e);if(!t)throw new n(`BRIDGE_NOT_CONFIGURED`,{network:e});return t}assertTokenSupported(e,t){if(!e.isTokenSupported(t))throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:e.network,symbol:t})}};const X=`/v1/tokens`,Z=1e3,jn=1e4;function Mn(e){return S(e)&&C(e,[`symbol`,`name`,`stringifiedTokenClassKey`,`collection`,`category`,`type`,`additionalKey`],{image:`string`,description:`string`})&&Number.isSafeInteger(e.decimals)&&e.decimals>=0&&typeof e.verified==`boolean`}function Nn(e){let t=x(e),n=t.status??t.statusCode;return typeof n==`number`?n:void 0}function Pn(e){if(o(e))return e;let t=Nn(e);return t===void 0?new n(`TRANSPORT_ERROR`,{url:X},{write:!1,cause:e}):new n(`GALACONNECT_HTTP_ERROR`,{method:X,status:t,serverMessage:``},{write:!1,status:t,cause:e})}async function Fn(e,t,r,i,a){let o;try{o=await e.request({method:`GET`,url:X,params:{...t,pageSize:Math.min(i,Z),offset:r}})}catch(e){throw Pn(e)}let s=x(o).tokens;if(!Array.isArray(s))throw new n(`BRIDGE_READ_RESPONSE_INVALID`,{method:X},{write:!1});return{items:a(s),rawCount:s.length}}async function In(e){let t=[];for(let n=0;n<jn;n++){let r=await e(n*Z,Z);if(t.push(...r.items),r.rawCount!==1e3)return t}throw new n(`PAGINATION_LIMIT_EXCEEDED`,{method:X,maxPages:jn},{write:!1})}const Ln=[`ETHEREUM`,`SOLANA`];function Rn(e){if(!Mn(e))return!1;let{canBridgeTo:t,otherNetworks:n}=e;return Array.isArray(t)&&t.every(e=>S(e)&&C(e,[`network`]))&&Array.isArray(n)&&n.every(e=>S(e)&&C(e,[`network`],{contractAddress:`string`,symbol:`string`,allowanceStorageSlot:`number`}))}function zn(e){let t=e.otherNetworks.find(e=>e.network===`Ethereum`),n=e.otherNetworks.find(e=>e.network===`Solana`),r=e.canBridgeTo.map(e=>e.network).filter(e=>e===`Ethereum`||e===`Solana`),i={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,verified:e.verified,supportedChains:r};return t?.contractAddress!==void 0&&(i.ethereumContractAddress=t.contractAddress),t?.symbol!==void 0&&(i.ethereumSymbol=t.symbol),t?.allowanceStorageSlot!==void 0&&(i.ethereumAllowanceSlot=t.allowanceStorageSlot),n?.contractAddress!==void 0&&(i.solanaContractAddress=n.contractAddress),n?.symbol!==void 0&&(i.solanaSymbol=n.symbol),e.image!==void 0&&(i.image=e.image),e.description!==void 0&&(i.description=e.description),i}var Bn=class{constructor(e){this.dexApi=e,F(this,`cache`,/* @__PURE__ */ new Map)}fetchPage(e,t,n){return Fn(this.dexApi,{canBridgeTo:e.toLowerCase()},t,n,e=>e.filter(Rn).map(zn))}store(e,t){let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let e of t){let t=E(e.symbol);n.has(t)||n.set(t,e),r.set(J(e.galaChainDescriptor),e)}this.cache.set(e,{tokens:t,bySymbol:n,byTokenId:r,fetchedAt:Date.now()})}async tokensOf(e){let t=this.cache.get(e);return t!==void 0&&t.tokens.length>0?t:(await this.fetchAllBridgeableTokensByNetwork(e),this.cache.get(e))}async fetchBridgeableTokensByNetwork(e){let{network:t,offset:n=0,limit:r=Z}=e,{items:i}=await this.fetchPage(t,n,r);return{tokens:i,network:t,fetchedAt:Date.now(),tokenCount:i.length}}async fetchAllBridgeableTokensByNetwork(e){let t=this.cache.get(e);if(t!==void 0&&t.tokens.length>0){let n=[...t.tokens];return{tokens:n,network:e,fetchedAt:t.fetchedAt,tokenCount:n.length}}let n=await In((t,n)=>this.fetchPage(e,t,n));return this.store(e,n),{tokens:n,network:e,fetchedAt:Date.now(),tokenCount:n.length}}async fetchAllTokensBridgeableToEthereum(){return this.fetchAllBridgeableTokensByNetwork(`ETHEREUM`)}async fetchAllTokensBridgeableToSolana(){return this.fetchAllBridgeableTokensByNetwork(`SOLANA`)}async isTokenBridgeableToNetwork(e){let{tokenId:t,network:n}=e,r=Y(t).stringified,i=(await this.tokensOf(n)).byTokenId.get(r),a={isBridgeable:i!==void 0,network:n};if(i!==void 0){a.tokenSymbol=i.symbol;let e=n===`ETHEREUM`?i.ethereumContractAddress:i.solanaContractAddress;e!==void 0&&(a.contractAddress=e)}return a}async isTokenBridgeableToEthereum(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:`ETHEREUM`})}async isTokenBridgeableToSolana(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:`SOLANA`})}async getTokenBySymbol(e,t){return(await this.tokensOf(t)).bySymbol.get(E(e))}async getTokenByTokenId(e,t){return(await this.tokensOf(t)).byTokenId.get(e)}async getContractAddress(e,t){let n=await this.getTokenBySymbol(e,t);return t===`ETHEREUM`?n?.ethereumContractAddress:n?.solanaContractAddress}async getSupportedTokenSymbols(e){return(await this.tokensOf(e)).tokens.map(e=>e.symbol)}async preload(){await Promise.all(Ln.map(e=>this.fetchAllBridgeableTokensByNetwork(e)))}getCacheStats(){let e={ETHEREUM:0,SOLANA:0},t={};for(let[n,r]of this.cache)e[n]=r.tokens.length,t[n]=r.fetchedAt;let n=e.ETHEREUM+e.SOLANA;return{networks:[...this.cache.keys()],totalItems:n,itemsByNetwork:e,fetchTimestamps:t,totalTokens:n,tokensByNetwork:e}}clearCache(e){e===void 0?this.cache.clear():this.cache.delete(e)}};function Vn(e){return Mn(e)&&C(e,[`wrap`],{channel:`string`,trending:`boolean`,currentPrices:`object`})&&typeof e.swappable==`boolean`}function Hn(e){let t={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,wrapCounterpart:e.wrap,swappable:e.swappable,verified:e.verified};return e.channel!==void 0&&e.channel!==``&&(t.channel=e.channel),e.trending!==void 0&&(t.trending=e.trending),e.image!==void 0&&e.image!==``&&(t.image=e.image),e.description!==void 0&&e.description!==``&&(t.description=e.description),e.currentPrices!==void 0&&(t.currentPrices=e.currentPrices),t}var Un=class{constructor(e){this.dexApi=e,F(this,`byTokenId`,/* @__PURE__ */ new Map),F(this,`fetchedAt`,null)}fetchPage(e,t){return Fn(this.dexApi,{wrappable:!0},e,t,e=>e.filter(Vn).map(Hn))}store(e){this.byTokenId.clear();for(let t of e)this.byTokenId.set(J(t.galaChainDescriptor),t);this.fetchedAt=Date.now()}async lookup(e){let t=Y(e).stringified;this.byTokenId.size===0&&await this.fetchAllWrappableTokens();let n=this.byTokenId.get(t);return n===void 0?{key:t}:{key:t,token:n}}async fetchWrappableTokens(e={}){let{offset:t=0,limit:n=Z}=e,{items:r}=await this.fetchPage(t,n);return{tokens:r,fetchedAt:Date.now(),tokenCount:r.length}}async fetchAllWrappableTokens(){if(this.byTokenId.size>0){let e=[...this.byTokenId.values()];return{tokens:e,fetchedAt:this.fetchedAt,tokenCount:e.length}}let e=await In((e,t)=>this.fetchPage(e,t));return this.store(e),{tokens:e,fetchedAt:Date.now(),tokenCount:e.length}}async getWrappableToken(e){return(await this.lookup(e)).token}async getWrapCounterpart(e){let t=await this.getWrappableToken(e);return t===void 0?void 0:this.getWrappableToken(t.wrapCounterpart)}async isTokenWrappable(e){let{key:t,token:n}=await this.lookup(e),r={isWrappable:n!==void 0,tokenId:t};return n!==void 0&&(r.wrapCounterpart=n.wrapCounterpart),r}getCacheStats(){return{totalItems:this.byTokenId.size,tokenCount:this.byTokenId.size,isPopulated:this.byTokenId.size>0,lastFetchedAt:this.fetchedAt}}clearCache(){this.byTokenId.clear(),this.fetchedAt=null}};const Q=`asset`,Wn={[Q]:O.ASSET,music:O.MUSIC};function $(e){if(e.channel===void 0||Wn[e.channel]===void 0)throw new n(`TOKEN_NOT_WRAPPABLE`,{tokenId:e.stringifiedTokenClassKey,reason:`unknown_channel`});return e.channel}var Gn=class{constructor(e){F(this,`galaConnectClient`,void 0),F(this,`wrappableTokenService`,void 0),F(this,`signer`,void 0),F(this,`walletAddress`,void 0),this.galaConnectClient=e.galaConnectClient,this.wrappableTokenService=e.wrappableTokenService,this.signer=e.signer,this.walletAddress=e.walletAddress}async wrapToken(e){return this.execute(e,`wrap`)}async unwrapToken(e){return this.execute(e,`unwrap`)}async estimateWrapFee(e,t){return this.estimate(e,t,`wrap`)}async estimateUnwrapFee(e,t){return this.estimate(e,t,`unwrap`)}async sourceToken(e,t){let r=await this.wrappableTokenService.getWrappableToken(e);if(r===void 0)throw new n(`TOKEN_NOT_WRAPPABLE`,{tokenId:typeof e==`string`?e:ke(e),reason:`not_listed`});let i=r.channel===Q;if(t===`wrap`?i:!i)throw new n(`INVALID_WRAP_DIRECTION`,{symbol:r.symbol,direction:t});return r}async estimate(e,t,n){B(t);let r=await this.sourceToken(e,n);return{fee:`0`,feeToken:`GALA`,authorizationType:n===`wrap`?`cross_channel_authorization`:`automatic`,feeChannel:n===`wrap`?$(r):Q}}async execute(e,t){let{amount:i}=e;if(B(i),this.signer===void 0)throw new n(`INVALID_BRIDGE_OPTION`,{option:`signer`});if(this.walletAddress===void 0||this.walletAddress===``)throw new n(`INVALID_BRIDGE_OPTION`,{option:`walletAddress`});let o=a(this.walletAddress,`walletAddress`),s=e.recipient===void 0||e.recipient===``?o:a(e.recipient,`recipient`),c=await this.sourceToken(e.tokenId,t),l=await this.wrappableTokenService.getWrapCounterpart(e.tokenId);if(l===void 0)throw new n(`TOKEN_NOT_WRAPPABLE`,{tokenId:c.wrapCounterpart,reason:`no_counterpart`});let d=t===`wrap`?{sourceChannel:$(c),destinationChannel:Q,destinationChannelId:O.ASSET}:{sourceChannel:Q,destinationChannel:$(l),destinationChannelId:Wn[$(l)]},f=r(`galaswap-operation-`),p={quantity:i,tokenInstance:{collection:c.galaChainDescriptor.collection,category:c.galaChainDescriptor.category,type:c.galaChainDescriptor.type,additionalKey:c.galaChainDescriptor.additionalKey,instance:`0`},destinationChainId:d.destinationChannelId,recipient:s,wrap:!0,uniqueKey:f},m=await u(this.signer,Kt,`RequestTokenBridgeOut`,p),h=await this.galaConnectClient.requestBridgeOut(m);return Ze(`RequestTokenBridgeOut`,h,f),{success:!0,transactionId:await Yt(this.galaConnectClient,h,f,d.sourceChannel,Kn),fromToken:c.symbol,toToken:l.symbol,amount:i,fromChannel:d.sourceChannel,toChannel:d.destinationChannel,completedAt:Date.now()}}};function Kn(e,t){let r=x(e);if(r.Status!==1)throw new n(`BRIDGE_RESPONSE_INVALID`,{method:`BridgeTokenOut`,missing:`Status 1`});let i=r.Hash;return typeof i==`string`&&i!==``?i:t}function qn(){let e=g.generate(),t=e.publicKey.toBase58();return{privateKey:pe.encode(e.secretKey),publicKey:t,address:t}}function Jn(e){return e===``?``:e.startsWith(`0x`)?e.slice(2):e}export{We as BRIDGE_CONTRACT_ABI,fn as BaseBridgeStrategy,An as BridgeService,me as BridgeStatusCode,Bn as BridgeableTokenService,D as CHAIN_IDS,be as CROSS_RATE_TYPED_DATA_TYPES,Le as DEFAULT_ETHEREUM_BRIDGE_CONTRACT,Fe as DEFAULT_ETHEREUM_RPC_URL,Me as DEFAULT_POLL_INTERVAL_MS,Ne as DEFAULT_POLL_TIMEOUT_MS,je as DEFAULT_RATE_LIMIT_RPS,ze as DEFAULT_SOLANA_BRIDGE_PROGRAM,Ie as DEFAULT_SOLANA_RPC_URL,j as DEFAULT_SOLANA_TOKENS,Ue as ERC20_ABI,Re as ETHEREUM_BRIDGE_CONTRACT_SEPOLIA,k as ETHEREUM_TOKENS_PROD,Ve as ETHEREUM_TOKENS_STAGE,_n as EthereumBridgeStrategy,O as GALACHAIN_CHANNELS,Be as GALACONNECT_PRODUCTION_URL,he as GALA_BRIDGE_TYPED_DATA_DOMAIN,St as GalaConnectClient,ye as LEGACY_TYPED_DATA_TYPES,st as RateLimiter,Pe as SOLANA_COMPUTE,Ge as SOLANA_DISCRIMINATORS,M as STATIC_TOKEN_METADATA,Tn as SolanaBridgeStrategy,Gn as WrapService,Un as WrappableTokenService,Jt as buildBridgeOutPayload,un as compareAmounts,qn as createSolanaWallet,ln as formatTokenAmount,Ye as formatTokenDescriptor,W as fromBaseUnits,ge as galaBridgeTypedDataDomain,He as getEthereumBridgeContractByEnvironment,qe as getEthereumTokenConfig,A as getEthereumTokensByEnvironment,xe as getGalaBridgeTypedDataTypes,Je as getSolanaTokenConfig,Ke as getStaticTokenMetadata,Ae as isValidGalaChainChannel,Y as parseTokenId,En as parseTokenString,J as stringifyTokenClassKey,Jn as stripHexPrefix,sn as toBaseUnits};
2
2
  //# sourceMappingURL=bridge.js.map