@gala-chain/gala-core-sdk 1.1.0-beta.1 → 1.1.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -2
- package/dist/bridge.cjs +32 -7
- package/dist/bridge.cjs.map +1 -1
- package/dist/bridge.d.cts +26 -0
- package/dist/bridge.d.ts +26 -0
- package/dist/bridge.mjs +32 -8
- package/dist/bridge.mjs.map +1 -1
- package/dist/browser/bridge.js +1 -1
- package/dist/browser/bridge.js.map +1 -1
- package/dist/browser/classes/signers.js +1 -1
- package/dist/browser/classes/signers.js.map +1 -1
- package/dist/browser/config/environments.js +1 -1
- package/dist/browser/config/environments.js.map +1 -1
- package/dist/browser/providers.js.map +1 -1
- package/dist/browser/utils/eip712.js +1 -1
- package/dist/browser/utils/eip712.js.map +1 -1
- package/dist/browser/utils/transport.js +1 -1
- package/dist/browser/version.js +1 -1
- package/dist/browser/version.js.map +1 -1
- package/dist/index.cjs +25 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -1
- package/dist/index.d.ts +25 -1
- package/dist/index.mjs +25 -8
- package/dist/index.mjs.map +1 -1
- package/dist/providers.cjs +2 -0
- package/dist/providers.cjs.map +1 -1
- package/dist/providers.d.cts +3 -0
- package/dist/providers.d.ts +3 -0
- package/dist/providers.mjs +2 -0
- package/dist/providers.mjs.map +1 -1
- package/package.json +1 -1
package/dist/browser/bridge.js
CHANGED
|
@@ -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 y={name:`GalaConnect`,chainId:1},he=[{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`}],ge=[{name:`collection`,type:`string`},{name:`category`,type:`string`},{name:`type`,type:`string`},{name:`additionalKey`,type:`string`}],b=[{name:`collection`,type:`string`},{name:`category`,type:`string`},{name:`type`,type:`string`},{name:`additionalKey`,type:`string`},{name:`instance`,type:`string`}],x=[{name:`name`,type:`string`},{name:`symbol`,type:`string`}],_e={GalaTransaction:he,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:ge,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:b,externalQuoteToken:x,tokenInstance:b},ve={GalaTransaction:he,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:ge,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:x,externalQuoteToken:x,externalCrossRateToken:x,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:b,tokenInstance:b};function ye(e){return e?ve:_e}function be(e){return e==null}function xe(e){return e==null||e===``}function S(e){return typeof e==`object`&&e?e:{}}function C(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function w(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`?C(r):typeof r===n)})}function T(e,t){if(be(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 Se(e,t=0){if(xe(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 Ce(e,t){if(xe(e))return t;try{return JSON.parse(e)}catch{return t}}function E(t,n=`0`){if(xe(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 we(e){return e instanceof Error}function Te(e){return we(e)||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`?e.message:typeof e==`string`?e:String(e)}function Ee(e){if(typeof e==`object`&&e&&`code`in e&&(typeof e.code==`string`||typeof e.code==`number`))return e.code}function D(e){return e.trim().toUpperCase()}function De(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}const O={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},k={ASSET:1,MUSIC:3};function Oe(e){return Object.values(k).includes(e)}const ke=12,Ae=15e3,je=27e5,Me={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},Ne=`https://ethereum.publicnode.com`,Pe=`https://api.mainnet-beta.solana.com`,Fe=`0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9`,Ie=`0x6a1734E09f3099a3675645D214ce547080ea67e0`,Le=`AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS`,Re=`https://dex-api-platform-dex-prod-gala.gala.com`,A=[{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}],ze=[{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 j(e){return e===`prod`?A:ze}function Be(e){return e===`prod`?Fe:Ie}const M=[{symbol:`GALA`,amount:`1`,mintAddress:`eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6`,isNative:!1,decimals:8},{symbol:`GSOL`,amount:`0.001`,mintAddress:`So11111111111111111111111111111111111111111`,isNative:!0,decimals:9}],N={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`}},Ve=[`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)`],He=[`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`],Ue={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 We(e){let t=D(e);return N[t]}function Ge(e){let t=D(e);return A.find(e=>D(e.symbol)===t)}function Ke(e){let t=D(e);return M.find(e=>D(e.symbol)===t)}function qe(e){return De(e)}function Je(e){if(e===void 0||e===``)throw new n(`INVALID_TOKEN_REFERENCE`,{field:`tokenSymbol`,reason:`missing`});return e}function Ye(e,t,r){let i=S(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 Xe(e){if(e===void 0||e===``)throw new n(`BRIDGE_RESPONSE_INVALID`,{method:`RequestTokenBridgeOut`,missing:`bridge request id`});return e}function Ze(e){let t=S(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 Qe(e,t){if(!le(e))throw new n(`INVALID_WALLET_ADDRESS`,{field:t??`address`,value:String(e)})}function $e(e,t){try{return new _(e)}catch{throw new n(`INVALID_WALLET_ADDRESS`,{field:t??`address`,value:String(e)})}}function et(e){return $e(e)}function P(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 tt(e,t){if(typeof e!=`string`||!le(e))throw new n(`INVALID_BRIDGE_OPTION`,{option:t});return e}function nt(e,t){try{if(typeof e==`string`&&e!==``)return new _(e)}catch{}throw new n(`INVALID_BRIDGE_OPTION`,{option:t})}function F(e){"@babel/helpers - typeof";return F=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},F(e)}function rt(e,t){if(F(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(F(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function it(e){var t=rt(e,`string`);return F(t)==`symbol`?t:t+``}function I(e,t,n){return(t=it(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var at=class{constructor(e){if(I(this,`minIntervalMs`,void 0),I(this,`lastTimestamp`,0),I(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 ot={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},st=/* @__PURE__ */ new Set([408,429,500,502,503,504]),ct=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function lt(e){if(typeof e==`object`&&e){let t=e;if(typeof t.status==`number`)return st.has(t.status);if(typeof t.statusCode==`number`)return st.has(t.statusCode);let n=Ee(e);if(typeof n==`string`&&(n===`ECONNRESET`||n===`ECONNREFUSED`||n===`ETIMEDOUT`||n===`ENOTFOUND`||n===`EAI_AGAIN`))return!0}let t=Te(e);return ct.some(e=>e.test(t))}function ut(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 dt(e,t={}){let n={...ot,...t},r=t.shouldRetry??(e=>lt(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=ut(a,n);t.onRetry&&t.onRetry(e,a,o),await new Promise(e=>setTimeout(e,o))}throw i}function ft(e){return new Promise(t=>setTimeout(t,e))}const L={baseUrl:Re,galachainBaseUrl:`https://galachain-gateway-chain-platform-galachain-mainnet.gala.com`,requestsPerSecond:12,requestTimeoutMs:3e4,enableRetry:!0,maxRetries:3,retryInitialDelayMs:1e3};function R(e){return e.uniqueKey===void 0?{write:e.write}:{write:!0,uniqueKey:e.uniqueKey}}function pt(e){let t=e.uniqueKey;return typeof t==`string`&&t!==``?t:void 0}function mt(e,t,r,i){let a=Ce(i,{rawBody:i.slice(0,500)});return new n(`GALACONNECT_HTTP_ERROR`,{method:e.path,status:r,serverMessage:i.slice(0,500)},{...R(e),status:r,body:a,url:t})}function ht(e,t,r){return e.write?new n(`BRIDGE_WRITE_OUTCOME_UNKNOWN`,{method:e.path},{...R(e),url:t,cause:r}):new n(`TRANSPORT_ERROR`,{url:t},{write:!1,url:t,cause:r})}function gt(e,t,r,i){let a=new n(`REQUEST_TIMEOUT`,{url:t,timeoutMs:r},{...R(e),url:t,cause:i});return e.write?ht(e,t,a):a}function _t(e,t){return e.write?new n(`BRIDGE_RESPONSE_INVALID`,{method:e.path,missing:`JSON answer`},{...R(e),url:t}):new n(`BRIDGE_READ_RESPONSE_INVALID`,{method:e.path},{write:!1,url:t})}function vt(e,t,n){if(!n.ok)throw mt(e,t,n.status,n.text);if(n.text!==``)try{return JSON.parse(n.text)}catch{throw _t(e,t)}}function yt(e,t){let n=e;return n.code===`GALACONNECT_HTTP_ERROR`?n.status===429||!t.write&<({status:n.status}):!t.write&<(n.cause)}var bt=class{constructor(e){I(this,`baseUrl`,void 0),I(this,`galachainBaseUrl`,void 0),I(this,`walletAddress`,void 0),I(this,`rateLimiter`,void 0),I(this,`defaultHeaders`,void 0),I(this,`retryOptions`,void 0),I(this,`requestor`,void 0),I(this,`requestTimeoutMs`,void 0),this.requestTimeoutMs=f(e.requestTimeoutMs??L.requestTimeoutMs,`requestTimeoutMs`),this.baseUrl=P(e.baseUrl??L.baseUrl,`baseUrl`),this.galachainBaseUrl=P(e.galachainBaseUrl??L.galachainBaseUrl,`galachainBaseUrl`),this.walletAddress=e.walletAddress===``?``:a(e.walletAddress,`walletAddress`),this.rateLimiter=new at(e.requestsPerSecond??L.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??L.enableRetry;this.retryOptions=t?{maxRetries:e.maxRetries??L.maxRetries,initialDelayMs:e.retryInitialDelayMs??L.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 mt(t,n.toString(),r.status,r.text);let i=Ce(r.text,null)?.data?.tokens;if(!Array.isArray(i))throw _t(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 vt(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:pt(e)},e)}async bridgeTokenOut(e){return this.postJson({path:`/v1/BridgeTokenOut`,write:!0,uniqueKey:pt(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:pt(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 vt(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?gt(n,e,this.requestTimeoutMs,t):ht(n,e,t)}finally{clearTimeout(o)}if(this.retryOptions&&!i.ok&&(i.status===429||i.status>=500))throw mt(n,e,i.status,i.text);return i});return this.retryOptions?dt(r,{...this.retryOptions,shouldRetry:e=>yt(e,n)}):r()}};function xt(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function St(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function Ct(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(D(n.symbol),n);return t}function wt(e,t){return e.get(D(t))}function z(e,t,r){let i=wt(e,t);if(!i)throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:r,symbol:t});return i}function Tt(e){if(e===void 0||!xt(e))throw new n(`INVALID_PRIVATE_KEY`,{reason:`bad_encoding`})}function Et(e){if(!St(e))throw new n(`INVALID_TRANSACTION_HASH`,{network:`Ethereum`,value:String(e)})}function B(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function Dt(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function Ot(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function kt(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 At(e,t){if(e===void 0)throw new n(`BRIDGE_NOT_CONFIGURED`,{network:t});return e}function jt(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 Mt(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 Nt(e){return{destinationChainId:e.destinationChainId,destinationChainTxFee:e.bridgeFee,quantity:e.amount,recipient:e.recipientAddress,tokenInstance:{...e.tokenDescriptor,instance:`0`}}}function Pt(e){let t={...e,galaDecimals:typeof e.galaDecimals==`string`?T(e.galaDecimals,0):e.galaDecimals,timestamp:typeof e.timestamp==`string`?T(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:typeof e.galaExchangeRate.timestamp==`string`?T(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){let n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:typeof n.timestamp==`string`?T(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:typeof n.baseTokenCrossRate.timestamp==`string`?T(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:typeof n.quoteTokenCrossRate.timestamp==`string`?T(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}function Ft(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r&&typeof r==`object`&&!Array.isArray(r)?Ft(r):r);return t}function It(e){let t=S(e);if(typeof t.Data==`string`)return t.Data;let n=t.data;if(typeof n==`string`)return n;let r=S(n).Data;return typeof r==`string`?r:void 0}function V(e){let t=Se(e,-1);if(t<=0)throw new n(`INVALID_BRIDGE_AMOUNT`,{value:String(e),reason:`not_positive`});return t}function Lt(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 Rt(e){let t=e;if(!C(t)||typeof t.estimatedTotalTxFeeInGala!=`string`||!(C(t.galaExchangeRate)||C(t.galaExchangeCrossRate)))throw Bt(`/v1/bridge/fee`);return e}function zt(e){if(!C(e))throw Bt(`/v1/bridge/status`);return e}function Bt(e){return new n(`BRIDGE_READ_RESPONSE_INVALID`,{method:e},{write:!1})}function Vt(e){let t=typeof e.timestamp==`string`?T(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 Ht(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 Ut=`RequestTokenBridgeOut`;async function Wt(e,t,r){let i;try{i=await e.signTypedData(y,t,r)}catch(e){throw o(e)?e:new n(`SIGNING_FAILED`,{method:Ut,reason:c(e)?`user_rejected`:`failed`},{cause:e,walletCode:p(e)})}if(typeof i!=`string`)throw new n(`SIGNING_FAILED`,{method:Ut,reason:`failed`},{cause:i});return i}async function Gt(e,t){let{wallet:n}=t,a=Ht(e.destinationChainId),o=e.uniqueKey??r(`galaconnect-operation-`),s=Pt(e.destinationChainTxFee),c=!!s.galaExchangeCrossRate,u={destinationChainId:a,destinationChainTxFee:Ft(c?{...s,galaExchangeRate:void 0}:{...s,galaExchangeCrossRate:void 0}),dtoOperation:i(`asset/bridge-contract`,Ut),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:o},d=ye(c),f=await Wt(n,d,u),p=`\u0019Ethereum Signed Message:\n${l({domain:y,message:u,primaryType:`GalaTransaction`,types:d}).length}`;return{...u,signature:f,prefix:p,types:d,domain:y}}async function Kt(e,t,r,i,a){let o=`request_id`,s=``;try{s=Xe(It(t)),o=`bridge_token_out`;let n=await e.bridgeTokenOut({bridgeFromChannel:i,bridgeRequestId:s});return Ye(`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 qt(e,t){let{amount:n,recipientAddress:r,tokenSymbol:i}=e,{galaConnectClient:a,tokenMetadataResolver:o,ethereumWallet:s,destinationChainId:c,destinationChain:l,validateRecipientAddress:u}=t,d=Je(i);V(n),u(r,`recipient`);let f=await o.getTokenMetadata(d),p=Rt(await a.fetchBridgeFee({chainId:l,bridgeToken:f.descriptor})),m=await Gt(Nt({destinationChainId:c,bridgeFee:p,amount:n,recipientAddress:r,tokenDescriptor:f.descriptor}),{wallet:s}),h=await a.requestBridgeOut(m);return Ye(`RequestTokenBridgeOut`,h,m.uniqueKey),jt({toChain:l,transactionHash:await Kt(a,h,m.uniqueKey,`asset`,Ze),tokenSymbol:d,amount:n,feePaid:p.estimatedTotalTxFeeInGala,baseUrl:a.getBaseUrl()})}const Jt={COMPLETED:5,FAILED:6,DELIVERY_FAILED:7};function Yt(e){let t=e.status,n=T(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(Jt.COMPLETED),isFailed:n===Number(Jt.FAILED)||n===Number(Jt.DELIVERY_FAILED)}}function H(e){return At(e.get(`Ethereum`),`Ethereum`)}function U(e){return At(e.get(`Solana`),`Solana`)}function W(e,t){return e??t.getWalletAddress()}async function Xt(e,t,n,r){let i=await t.getTokenMetadata(r);return Vt(Rt(await e.fetchBridgeFee({chainId:n,bridgeToken:i.descriptor})))}async function Zt(e,t){return Yt(zt(await e.getBridgeStatus(t)))}function Qt(e){return Array.from(e.keys())}function $t(e,t){return e.has(D(t))}function en(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 tn=class{constructor(e){I(this,`galaConnectClient`,void 0),I(this,`cache`,/* @__PURE__ */ new Map),this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){let t=D(e),n=this.cache.get(t);if(n)return n;let r=N[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`&&D(t.symbol)===D(e)&&t.verified===!0);if(!t)throw new n(`BRIDGE_TOKEN_NOT_FOUND`,{symbol:e},{write:!1});if(!en(t))throw new n(`BRIDGE_READ_RESPONSE_INVALID`,{method:`/v1/connect/bridge-configurations`},{write:!1});return Lt({collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey},t.decimals,t.channel)}};function nn(t){if(typeof t==`string`&&t!==``)try{let n=new e(t);return n.isFinite()?n:void 0}catch{return}}function rn(e,t){let r=nn(e);if(r===void 0)throw new n(`INVALID_BRIDGE_AMOUNT`,{value:String(e),reason:`not_a_number`});let i=r.multipliedBy(E(10).pow(t));if(!i.isInteger())throw new n(`INVALID_BRIDGE_AMOUNT`,{value:e,reason:`too_many_decimals`});return BigInt(i.toFixed(0))}function G(e,t){return an(E(e.toString()).dividedBy(E(10).pow(t)).toFixed(t))}function an(e){return e.includes(`.`)?e.replace(/\.?0+$/u,``):e}function on(e,t=6){let n=E(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 an(n.toFixed(r))}function sn(e,t){let n=E(e),r=E(t);return n.comparedTo(r)}const cn=/* @__PURE__ */ new Set([5,6,7]);var ln=class{constructor(e=ft){I(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),cn.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)}}},un=class extends ln{constructor(e,t,n){super(n),I(this,`galaConnectClient`,void 0),I(this,`tokenConfigs`,void 0),this.galaConnectClient=e,this.tokenConfigs=t}async getStatus(e){return Zt(this.galaConnectClient,e)}getSupportedTokens(){return Qt(this.tokenConfigs)}isTokenSupported(e){return $t(this.tokenConfigs,e)}};function dn(e,t){return new ae(e,Ve,t)}async function K(e,t){try{return await t()}catch(t){throw new n(`BRIDGE_CHAIN_READ_FAILED`,{network:`Ethereum`,call:e},{write:!1,cause:t})}}function fn(e,t,r){return new n(`BRIDGE_DEPOSIT_OUTCOME_UNKNOWN`,{network:`Ethereum`,step:e,transactionHash:t},{cause:r})}const pn=/^0x[0-9a-fA-F]{40}$/u;var mn=class e extends un{constructor(e){let t=e.tokenConfigs??A;super(e.galaConnectClient,Ct(t),e.sleep),I(this,`network`,`Ethereum`),I(this,`galaChainWalletAddress`,void 0),I(this,`ethereumProvider`,void 0),I(this,`ethereumWallet`,void 0),I(this,`ethereumBridgeContract`,void 0),I(this,`ethereumWalletAddress`,void 0),I(this,`tokenMetadataResolver`,void 0);for(let e of t)tt(e.contractAddress,`tokenConfigs`);this.galaChainWalletAddress=e.galaChainWalletAddress,Tt(e.ethereumPrivateKey);let n=tt(e.ethereumBridgeContract,`ethereumBridgeContract`),r=P(e.ethereumRpcUrl??`https://ethereum.publicnode.com`,`ethereumRpcUrl`);e.ethereumWalletAddress!==void 0&&tt(e.ethereumWalletAddress,`ethereumWalletAddress`),this.ethereumProvider=new oe(r),this.ethereumWallet=new ce(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=n,this.tokenMetadataResolver=new tn({galaConnectClient:this.galaConnectClient})}async estimateFee(e){return Xt(this.galaConnectClient,this.tokenMetadataResolver,`Ethereum`,e)}async bridgeOut(e){return qt(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:O.ETHEREUM,destinationChain:`Ethereum`,validateRecipientAddress:Qe})}async bridgeIn(e){let{amount:t,sourcePrivateKey:r,recipientAddress:i,tokenSymbol:o}=e,s=Je(o);V(t);let c=r!==void 0&&r!==``;c&&Tt(r);let l=a(i??this.galaChainWalletAddress,`address`),u=c?new ce(r,this.ethereumProvider):this.ethereumWallet,d=z(this.tokenConfigs,s,`Ethereum`),f=await this.tokenMetadataResolver.getTokenMetadata(s),p=dn(d.contractAddress,u),m=Number(await K(`decimals`,()=>p.decimals())),h=rn(t,m),g=await K(`balanceOf`,()=>p.balanceOf(u.address));if(g<h)throw new n(`INSUFFICIENT_BRIDGE_BALANCE`,{network:`Ethereum`,symbol:s,needed:G(h,m),available:G(g,m)});return Mt({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 pn.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,t){let n=z(this.tokenConfigs,e,`Ethereum`),r=t??this.ethereumWalletAddress;Qe(r);let i=dn(n.contractAddress,this.ethereumProvider);return G(await K(`balanceOf`,()=>i.balanceOf(r)),n.decimals??Number(await K(`decimals`,()=>i.decimals())))}async getEthereumNativeBalance(e){let t=e??this.ethereumWalletAddress;return Qe(t),G(await this.ethereumProvider.getBalance(t),18)}async getEthereumTransactionStatus(t){Et(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: ${Te(e)}`}}}async executeBridgeDeposit(e){let t=new ae(this.ethereumBridgeContract,He,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 fn(`send`,``,e)}try{await i.wait()}catch(e){throw fn(`confirmation`,i.hash,e)}try{await this.sleep(3e4),await this.galaConnectClient.registerBridgeTransaction({quantity:G(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 fn(`registration`,i.hash,e)}return i.hash}async prepareBridgeWithPermit(e,t,n,r,i,a){let o=await K(`chainId`,()=>this.ethereumProvider.getNetwork()),s=await K(`name`,()=>t.name()),c=await K(`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,O.GALA_CHAIN,a,l,d.v,d.r,d.s)}async prepareBridgeWithApproval(e,t,n,r,i,a){return await K(`allowance`,()=>t.allowance(e.address,this.ethereumBridgeContract))<i&&await(await t.approve(this.ethereumBridgeContract,i)).wait(),()=>n.bridgeOut(r.contractAddress,i,0,O.GALA_CHAIN,a)}};I(mn,`ETHEREUM_FINALITY_THRESHOLD`,12);function hn(...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 gn(e){let t=/* @__PURE__ */ new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!0),t}function _n(e){let t=/* @__PURE__ */ new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t}function q(e){return new TextEncoder().encode(e)}function vn(e,t,n,r){let[i]=_.findProgramAddressSync([t.toBytes(),n.toBytes(),e.toBytes()],r);return i}function J(e,t){return new n(`BRIDGE_CHAIN_READ_FAILED`,{network:`Solana`,call:e},{write:!1,cause:t})}async function yn(e,t,n){let r=await e.getAccountInfo(t);if(r){if(!r.owner.equals(n))throw J(`token account`);return de.decode(r.data).amount}}function bn(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 xn=/^[1-9A-HJ-NP-Za-km-z]{80,90}$/u;var Sn=class extends un{constructor(e){let t=e.tokenConfigs??M;super(e.galaConnectClient,Ct(t),e.sleep),I(this,`network`,`Solana`),I(this,`galaChainWalletAddress`,void 0),I(this,`ethereumWallet`,void 0),I(this,`solanaConnection`,void 0),I(this,`solanaKeypair`,void 0),I(this,`solanaBridgeProgramId`,void 0),I(this,`solanaBridgeTokenAuthority`,void 0),I(this,`solanaBridgeConfigPda`,void 0),I(this,`solanaNativeBridgePda`,void 0),I(this,`solanaBridgeAccountCache`,/* @__PURE__ */ new Map),I(this,`tokenMetadataResolver`,void 0);for(let e of t)nt(e.mintAddress,`tokenConfigs`);this.galaChainWalletAddress=e.galaChainWalletAddress,Tt(e.ethereumPrivateKey),this.ethereumWallet=new ce(e.ethereumPrivateKey);let n=P(e.solanaRpcUrl??`https://api.mainnet-beta.solana.com`,`solanaRpcUrl`);this.solanaConnection=e.solanaConnection??new h(n,`confirmed`),this.solanaKeypair=bn(e.solanaPrivateKeyBase58),this.solanaBridgeProgramId=nt(e.solanaBridgeProgram??`AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS`,`solanaBridgeProgram`),[this.solanaBridgeTokenAuthority]=_.findProgramAddressSync([q(`bridge_token_authority`)],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=_.findProgramAddressSync([q(`configv1`)],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=_.findProgramAddressSync([q(`native_sol_bridge`)],this.solanaBridgeProgramId),this.tokenMetadataResolver=new tn({galaConnectClient:this.galaConnectClient})}async estimateFee(e){return Xt(this.galaConnectClient,this.tokenMetadataResolver,`Solana`,e)}async bridgeOut(e){return qt(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:O.SOLANA,destinationChain:`Solana`,validateRecipientAddress:$e})}async bridgeIn(e){let{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:i}=e,o=Je(i);V(t);let s=n!==void 0&&n!==``?bn(n):this.solanaKeypair,c=a(r??this.galaChainWalletAddress,`address`),l=z(this.tokenConfigs,o,`Solana`),u=await this.tokenMetadataResolver.getTokenMetadata(o),d=rn(t,u.decimals);return Mt({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=z(this.tokenConfigs,e,`Solana`);if(r.isNative)return this.getSolanaNativeBalance(t);let i=et(t??this.solanaKeypair.publicKey.toBase58()),a=vn(new _(r.mintAddress),i,v,ue),o;try{o=await yn(this.solanaConnection,a,v)}catch(e){throw e instanceof n?e:J(`token account`,e)}let s=r.decimals??await this.mintDecimals(new _(r.mintAddress));return G(o??0n,s)}async mintDecimals(e){let t;try{t=await this.solanaConnection.getAccountInfo(e)}catch(e){throw J(`mint`,e)}if(!t?.owner.equals(v))throw J(`mint`);return fe.decode(t.data).decimals}async getSolanaNativeBalance(e){let t=et(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,`confirmed`);return G(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!==``?et(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`||!xn.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=q(e.recipient),i=[gn(e.amountBaseUnits),_n(r.length),r],a=e.tokenConfig.isNative?this.buildNativeBridgeInstruction(e.keypair.publicKey,i):this.buildTokenBridgeInstruction(e.keypair.publicKey,vn(t,e.keypair.publicKey,v,ue),t,await this.getSolanaBridgeAccounts(t,e.tokenConfig.symbol),i),o=new ne;o.add(m.setComputeUnitPrice({microLamports:Me.UNIT_PRICE_MICROLAMPORTS}),m.setComputeUnitLimit({units:Me.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 J(`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:hn(Ue.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:hn(Ue.BRIDGE_OUT,...i)})}async getSolanaBridgeAccounts(e,t){let r=e.toBase58(),i=this.solanaBridgeAccountCache.get(r);if(i)return i;let[a]=_.findProgramAddressSync([q(`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 J(`mint lookup`);let s={mintLookup:a,tokenBridge:new _(o.data.subarray(8,40)),bridgeTokenAccount:vn(e,this.solanaBridgeTokenAuthority,v,ue)};return this.solanaBridgeAccountCache.set(r,s),s}};function Cn(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 Y(e){return De(e)}function X(e){let t;if(typeof e==`string`)t=Cn(e);else if(s(e))t=e;else throw new n(`INVALID_TOKEN_REFERENCE`,{field:`tokenId`,reason:`bad_class_key`});let r=Y(t);return{tokenClassKey:t,stringified:r}}const wn={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`}},Tn={rateLimit:12,pollInterval:15e3,pollTimeout:27e5};function En(e,t){let r=N[e];if(r===void 0)throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:t,symbol:e});return{...r.descriptor}}var Dn=class{constructor(e){if(I(this,`environment`,void 0),I(this,`pollInterval`,void 0),I(this,`pollTimeout`,void 0),I(this,`galaConnectClient`,void 0),I(this,`strategies`,void 0),I(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=wn[this.environment];this.pollInterval=e.pollInterval??Tn.pollInterval,this.pollTimeout=e.pollTimeout??Tn.pollTimeout,this.galaConnectClient=new bt({baseUrl:e.galaConnectBaseUrl??i.dexApiBaseUrl,galachainBaseUrl:e.galaChainApiBaseUrl??i.gatewayBaseUrl,walletAddress:r,requestsPerSecond:e.rateLimit??Tn.rateLimit,...e.httpRequestor!==void 0&&{httpRequestor:e.httpRequestor}}),this.bridgeableTokenService=e.bridgeableTokenService;let s=e.sleep===void 0?{}:{sleep:e.sleep};this.strategies=/* @__PURE__ */ new Map([[`Ethereum`,new mn({galaConnectClient:this.galaConnectClient,galaChainWalletAddress:r,ethereumPrivateKey:e.ethereumPrivateKey,ethereumRpcUrl:e.ethereumRpcUrl??o.ethereum,ethereumBridgeContract:e.ethereumBridgeContract??Be(this.environment),tokenConfigs:j(this.environment),...s})]]),e.solanaPrivateKey!==void 0&&e.solanaPrivateKey!==``&&this.strategies.set(`Solana`,new Sn({galaConnectClient:this.galaConnectClient,galaChainWalletAddress:r,ethereumPrivateKey:e.ethereumPrivateKey,solanaPrivateKeyBase58:e.solanaPrivateKey,solanaRpcUrl:e.solanaRpcUrl??o.solana,solanaBridgeProgram:e.solanaBridgeProgram??`AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS`,tokenConfigs:M,...e.solanaConnection!==void 0&&{solanaConnection:e.solanaConnection},...s}))}async resolveTokenSymbol(e,t){let r=X(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)});V(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);V(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 Zt(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 j(this.environment))t.push({symbol:e.symbol,decimals:e.decimals,verified:!0,supportedChains:[`Ethereum`],galaChainDescriptor:En(e.symbol,`Ethereum`),externalAddresses:{ethereum:e.contractAddress}});if(e===void 0||e===`Solana`)for(let e of M){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:En(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 H(this.strategies).getEthereumTokenBalance(e,t)}async getEthereumNativeBalance(e){return H(this.strategies).getEthereumNativeBalance(e)}async getSolanaTokenBalance(e,t){return U(this.strategies).getSolanaTokenBalance(e,t)}async getSolanaNativeBalance(e){return U(this.strategies).getSolanaNativeBalance(e)}async fetchEthereumWalletTokenBalance(e,t){let n=H(this.strategies),r=kt(j(this.environment),e,`Ethereum`),i=W(t,n);return Dt(r,await n.getEthereumTokenBalance(e,i))}async fetchEthereumWalletNativeBalance(e){let t=H(this.strategies),n=W(e,t);return B(`ETH`,await t.getEthereumNativeBalance(n),18)}async fetchSolanaWalletTokenBalance(e,t){let n=U(this.strategies),r=kt(M,e,`Solana`),i=W(t,n);return Ot(r,await n.getSolanaTokenBalance(e,i))}async fetchSolanaWalletNativeBalance(e){let t=U(this.strategies),n=W(e,t);return B(`SOL`,await t.getSolanaNativeBalance(n),9)}async requestSolanaDevnetAirdrop(e,t){return U(this.strategies).requestDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return U(this.strategies).getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return H(this.strategies).getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){let t=H(this.strategies),n=W(e,t),[r,i]=await Promise.all([t.getEthereumNativeBalance(n),Promise.all(j(this.environment).map(async e=>Dt(e,await t.getEthereumTokenBalance(e.symbol,n))))]);return{address:n,native:B(`ETH`,r,18),tokens:i,timestamp:Date.now()}}async fetchSolanaWalletAllBalances(e){let t=U(this.strategies),n=W(e,t),[r,i]=await Promise.all([t.getSolanaNativeBalance(n),Promise.all(M.map(async e=>Ot(e,await t.getSolanaTokenBalance(e.symbol,n))))]);return{address:n,native:B(`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 Z=`/v1/tokens`,Q=1e3,On=1e4;function kn(e){return C(e)&&w(e,[`symbol`,`name`,`stringifiedTokenClassKey`,`collection`,`category`,`type`,`additionalKey`],{image:`string`,description:`string`})&&Number.isSafeInteger(e.decimals)&&e.decimals>=0&&typeof e.verified==`boolean`}function An(e){let t=S(e),n=t.status??t.statusCode;return typeof n==`number`?n:void 0}function jn(e){if(o(e))return e;let t=An(e);return t===void 0?new n(`TRANSPORT_ERROR`,{url:Z},{write:!1,cause:e}):new n(`GALACONNECT_HTTP_ERROR`,{method:Z,status:t,serverMessage:``},{write:!1,status:t,cause:e})}async function Mn(e,t,r,i,a){let o;try{o=await e.request({method:`GET`,url:Z,params:{...t,pageSize:Math.min(i,Q),offset:r}})}catch(e){throw jn(e)}let s=S(o).tokens;if(!Array.isArray(s))throw new n(`BRIDGE_READ_RESPONSE_INVALID`,{method:Z},{write:!1});return{items:a(s),rawCount:s.length}}async function Nn(e){let t=[];for(let n=0;n<On;n++){let r=await e(n*Q,Q);if(t.push(...r.items),r.rawCount!==1e3)return t}throw new n(`PAGINATION_LIMIT_EXCEEDED`,{method:Z,maxPages:On},{write:!1})}const Pn=[`ETHEREUM`,`SOLANA`];function Fn(e){if(!kn(e))return!1;let{canBridgeTo:t,otherNetworks:n}=e;return Array.isArray(t)&&t.every(e=>C(e)&&w(e,[`network`]))&&Array.isArray(n)&&n.every(e=>C(e)&&w(e,[`network`],{contractAddress:`string`,symbol:`string`,allowanceStorageSlot:`number`}))}function In(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 Ln=class{constructor(e){this.dexApi=e,I(this,`cache`,/* @__PURE__ */ new Map)}fetchPage(e,t,n){return Mn(this.dexApi,{canBridgeTo:e.toLowerCase()},t,n,e=>e.filter(Fn).map(In))}store(e,t){let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let e of t){let t=D(e.symbol);n.has(t)||n.set(t,e),r.set(Y(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=Q}=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 Nn((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=X(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(D(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(Pn.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 Rn(e){return kn(e)&&w(e,[`wrap`],{channel:`string`,trending:`boolean`,currentPrices:`object`})&&typeof e.swappable==`boolean`}function zn(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 Bn=class{constructor(e){this.dexApi=e,I(this,`byTokenId`,/* @__PURE__ */ new Map),I(this,`fetchedAt`,null)}fetchPage(e,t){return Mn(this.dexApi,{wrappable:!0},e,t,e=>e.filter(Rn).map(zn))}store(e){this.byTokenId.clear();for(let t of e)this.byTokenId.set(Y(t.galaChainDescriptor),t);this.fetchedAt=Date.now()}async lookup(e){let t=X(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=Q}=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 Nn((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 $=`asset`,Vn={[$]:k.ASSET,music:k.MUSIC};function Hn(e){if(e.channel===void 0||Vn[e.channel]===void 0)throw new n(`TOKEN_NOT_WRAPPABLE`,{tokenId:e.stringifiedTokenClassKey,reason:`unknown_channel`});return e.channel}var Un=class{constructor(e){I(this,`galaConnectClient`,void 0),I(this,`wrappableTokenService`,void 0),I(this,`signer`,void 0),I(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:De(e),reason:`not_listed`});let i=r.channel===$;if(t===`wrap`?i:!i)throw new n(`INVALID_WRAP_DIRECTION`,{symbol:r.symbol,direction:t});return r}async estimate(e,t,n){V(t);let r=await this.sourceToken(e,n);return{fee:`0`,feeToken:`GALA`,authorizationType:n===`wrap`?`cross_channel_authorization`:`automatic`,feeChannel:n===`wrap`?Hn(r):$}}async execute(e,t){let{amount:i}=e;if(V(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:Hn(c),destinationChannel:$,destinationChannelId:k.ASSET}:{sourceChannel:$,destinationChannel:Hn(l),destinationChannelId:Vn[Hn(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 Ye(`RequestTokenBridgeOut`,h,f),{success:!0,transactionId:await Kt(this.galaConnectClient,h,f,d.sourceChannel,Wn),fromToken:c.symbol,toToken:l.symbol,amount:i,fromChannel:d.sourceChannel,toChannel:d.destinationChannel,completedAt:Date.now()}}};function Wn(e,t){let r=S(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 Gn(){let e=g.generate(),t=e.publicKey.toBase58();return{privateKey:pe.encode(e.secretKey),publicKey:t,address:t}}function Kn(e){return e===``?``:e.startsWith(`0x`)?e.slice(2):e}export{He as BRIDGE_CONTRACT_ABI,ln as BaseBridgeStrategy,Dn as BridgeService,me as BridgeStatusCode,Ln as BridgeableTokenService,O as CHAIN_IDS,ve as CROSS_RATE_TYPED_DATA_TYPES,Fe as DEFAULT_ETHEREUM_BRIDGE_CONTRACT,Ne as DEFAULT_ETHEREUM_RPC_URL,Ae as DEFAULT_POLL_INTERVAL_MS,je as DEFAULT_POLL_TIMEOUT_MS,ke as DEFAULT_RATE_LIMIT_RPS,Le as DEFAULT_SOLANA_BRIDGE_PROGRAM,Pe as DEFAULT_SOLANA_RPC_URL,M as DEFAULT_SOLANA_TOKENS,Ve as ERC20_ABI,Ie as ETHEREUM_BRIDGE_CONTRACT_SEPOLIA,A as ETHEREUM_TOKENS_PROD,ze as ETHEREUM_TOKENS_STAGE,mn as EthereumBridgeStrategy,k as GALACHAIN_CHANNELS,Re as GALACONNECT_PRODUCTION_URL,y as GALA_BRIDGE_TYPED_DATA_DOMAIN,bt as GalaConnectClient,_e as LEGACY_TYPED_DATA_TYPES,at as RateLimiter,Me as SOLANA_COMPUTE,Ue as SOLANA_DISCRIMINATORS,N as STATIC_TOKEN_METADATA,Sn as SolanaBridgeStrategy,Un as WrapService,Bn as WrappableTokenService,Gt as buildBridgeOutPayload,sn as compareAmounts,Gn as createSolanaWallet,on as formatTokenAmount,qe as formatTokenDescriptor,G as fromBaseUnits,Be as getEthereumBridgeContractByEnvironment,Ge as getEthereumTokenConfig,j as getEthereumTokensByEnvironment,ye as getGalaBridgeTypedDataTypes,Ke as getSolanaTokenConfig,We as getStaticTokenMetadata,Oe as isValidGalaChainChannel,X as parseTokenId,Cn as parseTokenString,Y as stringifyTokenClassKey,Kn as stripHexPrefix,rn 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`;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};
|
|
2
2
|
//# sourceMappingURL=bridge.js.map
|