@gala-chain/gala-core-sdk 1.0.0 → 1.1.0-beta.1

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.
Files changed (68) hide show
  1. package/README.md +28 -7
  2. package/dist/bridge.cjs +6 -1
  3. package/dist/bridge.cjs.map +1 -1
  4. package/dist/bridge.mjs +7 -2
  5. package/dist/bridge.mjs.map +1 -1
  6. package/dist/browser/bridge.js +1 -1
  7. package/dist/browser/bridge.js.map +1 -1
  8. package/dist/browser/classes/error_catalog.js.map +1 -1
  9. package/dist/browser/classes/error_phase_table.js.map +1 -1
  10. package/dist/browser/classes/error_phases.js.map +1 -1
  11. package/dist/browser/classes/gala_sdk_error.js +1 -1
  12. package/dist/browser/classes/gala_sdk_error.js.map +1 -1
  13. package/dist/browser/classes/signers.js +1 -1
  14. package/dist/browser/classes/signers.js.map +1 -1
  15. package/dist/browser/config/environments.js.map +1 -1
  16. package/dist/browser/index.js +1 -1
  17. package/dist/browser/providers.js.map +1 -1
  18. package/dist/browser/react.js.map +1 -1
  19. package/dist/browser/reads/gateway_reads.js +1 -1
  20. package/dist/browser/reads/gateway_reads.js.map +1 -1
  21. package/dist/browser/reads/parse.js.map +1 -1
  22. package/dist/browser/reads/request.js.map +1 -1
  23. package/dist/browser/reads/types.js.map +1 -1
  24. package/dist/browser/utils/axios_requestor.js.map +1 -1
  25. package/dist/browser/utils/chain_dto_signing.js.map +1 -1
  26. package/dist/browser/utils/class_key.js.map +1 -1
  27. package/dist/browser/utils/dto_operation.js +2 -0
  28. package/dist/browser/utils/dto_operation.js.map +1 -0
  29. package/dist/browser/utils/eip712.js.map +1 -1
  30. package/dist/browser/utils/error_brand.js.map +1 -1
  31. package/dist/browser/utils/eth_address.js.map +1 -1
  32. package/dist/browser/utils/ethers_provider.js.map +1 -1
  33. package/dist/browser/utils/failure_outcomes.js.map +1 -1
  34. package/dist/browser/utils/failure_view.js.map +1 -1
  35. package/dist/browser/utils/fetch_failure.js.map +1 -1
  36. package/dist/browser/utils/pre_send.js +1 -1
  37. package/dist/browser/utils/pre_send.js.map +1 -1
  38. package/dist/browser/utils/signing.js.map +1 -1
  39. package/dist/browser/utils/transport.js +1 -1
  40. package/dist/browser/utils/transport.js.map +1 -1
  41. package/dist/browser/utils/typed_data.js.map +1 -1
  42. package/dist/browser/utils/unique_key.js.map +1 -1
  43. package/dist/browser/utils/unique_key_syntax.js.map +1 -1
  44. package/dist/browser/utils/wallet_keys.js.map +1 -1
  45. package/dist/browser/utils/wallet_rejection.js.map +1 -1
  46. package/dist/browser/version.js +1 -1
  47. package/dist/browser/version.js.map +1 -1
  48. package/dist/browser/wallet.js.map +1 -1
  49. package/dist/browser/writes/gateway_writes.js +1 -1
  50. package/dist/browser/writes/gateway_writes.js.map +1 -1
  51. package/dist/browser/writes/identity.js.map +1 -1
  52. package/dist/browser/writes/lock.js.map +1 -1
  53. package/dist/browser/writes/submit.js +1 -1
  54. package/dist/browser/writes/submit.js.map +1 -1
  55. package/dist/browser/writes/token_ref.js.map +1 -1
  56. package/dist/browser/writes/transfer.js.map +1 -1
  57. package/dist/browser/writes/types.js.map +1 -1
  58. package/dist/index.cjs +119 -8
  59. package/dist/index.cjs.map +1 -1
  60. package/dist/index.d.cts +95 -3
  61. package/dist/index.d.ts +95 -3
  62. package/dist/index.mjs +117 -9
  63. package/dist/index.mjs.map +1 -1
  64. package/package.json +30 -30
  65. /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/defineProperty.js +0 -0
  66. /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/toPrimitive.js +0 -0
  67. /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/toPropertyKey.js +0 -0
  68. /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/typeof.js +0 -0
@@ -1,2 +1,2 @@
1
- import e from"bignumber.js";import{GALA_CHAIN_ENVIRONMENTS as t,GalaSDKError as n,createUniqueKey as r,galaChainUserRef as i,isGalaError as a,isTokenClassKey as o,isWalletUserRejection as s,serialize as c,signPreSend as l,splitClassKey as u,validateTimeoutMs as d,walletDeclineCode as f}from"@gala-chain/gala-core-sdk";import{ComputeBudgetProgram as p,Connection as m,Keypair as h,LAMPORTS_PER_SOL as ee,PublicKey as g,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 _}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 v={name:`GalaConnect`,chainId:1},he=[{name:`destinationChainId`,type:`uint256`},{name:`destinationChainTxFee`,type:`destinationChainTxFee`},{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`}],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`}],_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:y,externalQuoteToken:b,tokenInstance:y},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: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 ye(e){return e?ve:_e}function be(e){return e==null}function xe(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(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 T(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 E(e){return e.trim().toUpperCase()}function De(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 Oe(e){return Object.values(O).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`,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}],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 A(e){return e===`prod`?k:ze}function Be(e){return e===`prod`?Fe:Ie}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`}},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=E(e);return M[t]}function Ge(e){let t=E(e);return k.find(e=>E(e.symbol)===t)}function Ke(e){let t=E(e);return j.find(e=>E(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=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 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=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 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 g(e)}catch{throw new n(`INVALID_WALLET_ADDRESS`,{field:t??`address`,value:String(e)})}}function et(e){return $e(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 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 g(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 rt(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 it(e){var t=rt(e,`string`);return P(t)==`symbol`?t:t+``}function F(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(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 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 I={baseUrl:Re,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 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)},{...L(e),status:r,body:a,url:t})}function ht(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 gt(e,t,r,i){let a=new n(`REQUEST_TIMEOUT`,{url:t,timeoutMs:r},{...L(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`},{...L(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&&lt({status:n.status}):!t.write&&lt(n.cause)}var bt=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=d(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===``?``:i(e.walletAddress,`walletAddress`),this.rateLimiter=new at(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 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(E(n.symbol),n);return t}function wt(e,t){return e.get(E(t))}function R(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 z(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`?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 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=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=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(!S(t)||typeof t.estimatedTotalTxFeeInGala!=`string`||!(S(t.galaExchangeRate)||S(t.galaExchangeCrossRate)))throw Bt(`/v1/bridge/fee`);return e}function zt(e){if(!S(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`?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 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(v,t,r)}catch(e){throw a(e)?e:new n(`SIGNING_FAILED`,{method:Ut,reason:s(e)?`user_rejected`:`failed`},{cause:e,walletCode:f(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,i=Ht(e.destinationChainId),a=e.uniqueKey??r(`galaconnect-operation-`),o=Pt(e.destinationChainTxFee),s=!!o.galaExchangeCrossRate,l={destinationChainId:i,destinationChainTxFee:Ft(s?{...o,galaExchangeRate:void 0}:{...o,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:a},u=ye(s),d=await Wt(n,u,l),f=`\u0019Ethereum Signed Message:\n${c({domain:v,message:l,primaryType:`GalaTransaction`,types:u}).length}`;return{...l,signature:d,prefix:f,types:u,domain:v}}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);B(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=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(Jt.COMPLETED),isFailed:n===Number(Jt.FAILED)||n===Number(Jt.DELIVERY_FAILED)}}function V(e){return At(e.get(`Ethereum`),`Ethereum`)}function H(e){return At(e.get(`Solana`),`Solana`)}function U(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(E(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){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(!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(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 an(T(e.toString()).dividedBy(T(10).pow(t)).toFixed(t))}function an(e){return e.includes(`.`)?e.replace(/\.?0+$/u,``):e}function on(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 an(n.toFixed(r))}function sn(e,t){let n=T(e),r=T(t);return n.comparedTo(r)}const cn=/* @__PURE__ */ new Set([5,6,7]);var ln=class{constructor(e=ft){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),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),F(this,`galaConnectClient`,void 0),F(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 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 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??k;super(e.galaConnectClient,Ct(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);for(let e of t)tt(e.contractAddress,`tokenConfigs`);this.galaChainWalletAddress=e.galaChainWalletAddress,Tt(e.ethereumPrivateKey);let n=tt(e.ethereumBridgeContract,`ethereumBridgeContract`),r=N(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:D.ETHEREUM,destinationChain:`Ethereum`,validateRecipientAddress:Qe})}async bridgeIn(e){let{amount:t,sourcePrivateKey:r,recipientAddress:a,tokenSymbol:o}=e,s=Je(o);B(t);let c=r!==void 0&&r!==``;c&&Tt(r);let l=i(a??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=dn(d.contractAddress,u),m=Number(await G(`decimals`,()=>p.decimals())),h=rn(t,m),ee=await G(`balanceOf`,()=>p.balanceOf(u.address));if(ee<h)throw new n(`INSUFFICIENT_BRIDGE_BALANCE`,{network:`Ethereum`,symbol:s,needed:W(h,m),available:W(ee,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=R(this.tokenConfigs,e,`Ethereum`),r=t??this.ethereumWalletAddress;Qe(r);let i=dn(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 Qe(t),W(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: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 fn(`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(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 K(e){return new TextEncoder().encode(e)}function vn(e,t,n,r){let[i]=g.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 yn(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 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 h.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??j;super(e.galaConnectClient,Ct(t),e.sleep),F(this,`network`,`Solana`),F(this,`galaChainWalletAddress`,void 0),F(this,`ethereumWallet`,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)nt(e.mintAddress,`tokenConfigs`);this.galaChainWalletAddress=e.galaChainWalletAddress,Tt(e.ethereumPrivateKey),this.ethereumWallet=new ce(e.ethereumPrivateKey);let n=N(e.solanaRpcUrl??`https://api.mainnet-beta.solana.com`,`solanaRpcUrl`);this.solanaConnection=e.solanaConnection??new m(n,`confirmed`),this.solanaKeypair=bn(e.solanaPrivateKeyBase58),this.solanaBridgeProgramId=nt(e.solanaBridgeProgram??`AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS`,`solanaBridgeProgram`),[this.solanaBridgeTokenAuthority]=g.findProgramAddressSync([K(`bridge_token_authority`)],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=g.findProgramAddressSync([K(`configv1`)],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=g.findProgramAddressSync([K(`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:D.SOLANA,destinationChain:`Solana`,validateRecipientAddress:$e})}async bridgeIn(e){let{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:a}=e,o=Je(a);B(t);let s=n!==void 0&&n!==``?bn(n):this.solanaKeypair,c=i(r??this.galaChainWalletAddress,`address`),l=R(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 g(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=et(t??this.solanaKeypair.publicKey.toBase58()),a=vn(new g(r.mintAddress),i,_,ue),o;try{o=await yn(this.solanaConnection,a,_)}catch(e){throw e instanceof n?e:q(`token account`,e)}let s=r.decimals??await this.mintDecimals(new g(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(_))throw q(`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 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!==``?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 g(e.tokenConfig.mintAddress),r=K(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,_,ue),t,await this.getSolanaBridgeAccounts(t,e.tokenConfig.symbol),i),o=new ne;o.add(p.setComputeUnitPrice({microLamports:Me.UNIT_PRICE_MICROLAMPORTS}),p.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 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: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:_,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]=g.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 g(o.data.subarray(8,40)),bridgeTokenAccount:vn(e,this.solanaBridgeTokenAuthority,_,ue)};return this.solanaBridgeAccountCache.set(r,s),s}};function Cn(e){let t=typeof e==`string`?u(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 De(e)}function Y(e){let t;if(typeof e==`string`)t=Cn(e);else if(o(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 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=M[e];if(r===void 0)throw new n(`UNSUPPORTED_BRIDGE_TOKEN`,{network:t,symbol:e});return{...r.descriptor}}var Dn=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=i(e.galaChainWalletAddress,`galaChainWalletAddress`);this.environment=e.environment??`prod`;let a=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??a.dexApiBaseUrl,galachainBaseUrl:e.galaChainApiBaseUrl??a.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:A(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:j,...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 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 A(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 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: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 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=kt(A(this.environment),e,`Ethereum`),i=U(t,n);return Dt(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=kt(j,e,`Solana`),i=U(t,n);return Ot(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=>Dt(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=>Ot(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,On=1e4;function kn(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 An(e){let t=x(e),n=t.status??t.statusCode;return typeof n==`number`?n:void 0}function jn(e){if(a(e))return e;let t=An(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 Mn(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 jn(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 Nn(e){let t=[];for(let n=0;n<On;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: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=>S(e)&&C(e,[`network`]))&&Array.isArray(n)&&n.every(e=>S(e)&&C(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,F(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=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 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=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(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)&&C(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,F(this,`byTokenId`,/* @__PURE__ */ new Map),F(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(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 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 Q=`asset`,Vn={[Q]:O.ASSET,music:O.MUSIC};function $(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 Hn=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:De(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:a}=e;if(B(a),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=i(this.walletAddress,`walletAddress`),s=e.recipient===void 0||e.recipient===``?o:i(e.recipient,`recipient`),c=await this.sourceToken(e.tokenId,t),u=await this.wrappableTokenService.getWrapCounterpart(e.tokenId);if(u===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:$(u),destinationChannelId:Vn[$(u)]},f=r(`galaswap-operation-`),p={quantity:a,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 l(this.signer,`RequestTokenBridgeOut`,p),h=await this.galaConnectClient.requestBridgeOut(m);return Ye(`RequestTokenBridgeOut`,h,f),{success:!0,transactionId:await Kt(this.galaConnectClient,h,f,d.sourceChannel,Un),fromToken:c.symbol,toToken:u.symbol,amount:a,fromChannel:d.sourceChannel,toChannel:d.destinationChannel,completedAt:Date.now()}}};function Un(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 Wn(){let e=h.generate(),t=e.publicKey.toBase58();return{privateKey:pe.encode(e.secretKey),publicKey:t,address:t}}function Gn(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,D 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,j as DEFAULT_SOLANA_TOKENS,Ve as ERC20_ABI,Ie as ETHEREUM_BRIDGE_CONTRACT_SEPOLIA,k as ETHEREUM_TOKENS_PROD,ze as ETHEREUM_TOKENS_STAGE,mn as EthereumBridgeStrategy,O as GALACHAIN_CHANNELS,Re as GALACONNECT_PRODUCTION_URL,v 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,M as STATIC_TOKEN_METADATA,Sn as SolanaBridgeStrategy,Hn as WrapService,Bn as WrappableTokenService,Gt as buildBridgeOutPayload,sn as compareAmounts,Wn as createSolanaWallet,on as formatTokenAmount,qe as formatTokenDescriptor,W as fromBaseUnits,Be as getEthereumBridgeContractByEnvironment,Ge as getEthereumTokenConfig,A as getEthereumTokensByEnvironment,ye as getGalaBridgeTypedDataTypes,Ke as getSolanaTokenConfig,We as getStaticTokenMetadata,Oe as isValidGalaChainChannel,Y as parseTokenId,Cn as parseTokenString,J as stringifyTokenClassKey,Gn 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 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&&lt({status:n.status}):!t.write&&lt(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};
2
2
  //# sourceMappingURL=bridge.js.map