@galacticcouncil/xc-sdk 1.1.2 → 1.2.0-pr337-94e58a8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.cjs +4 -4
- package/build/index.mjs +4 -4
- package/build/platforms/adapter.d.ts +2 -5
- package/build/platforms/evm/EvmPlatform.d.ts +2 -5
- package/build/platforms/solana/SolanaPlatform.d.ts +2 -5
- package/build/platforms/substrate/SubstratePlatform.d.ts +2 -5
- package/build/platforms/substrate/SubstrateService.d.ts +1 -2
- package/build/platforms/sui/SuiPlatform.d.ts +2 -5
- package/build/platforms/types.d.ts +2 -5
- package/build/transfer/DataDestinationProcessor.d.ts +10 -0
- package/build/transfer/DataOriginProcessor.d.ts +7 -0
- package/build/transfer/DataProcessor.d.ts +11 -4
- package/build/transfer/index.d.ts +1 -1
- package/build/transfer/utils.d.ts +10 -1
- package/build/types.d.ts +3 -0
- package/package.json +2 -2
- package/build/platforms/evm/balance/Erc20.d.ts +0 -8
- package/build/platforms/evm/balance/EvmBalance.d.ts +0 -10
- package/build/platforms/evm/balance/EvmBalanceFactory.d.ts +0 -5
- package/build/platforms/evm/balance/Native.d.ts +0 -5
- package/build/platforms/evm/balance/index.d.ts +0 -2
- package/build/platforms/solana/balance/Native.d.ts +0 -5
- package/build/platforms/solana/balance/SolanaBalance.d.ts +0 -11
- package/build/platforms/solana/balance/SolanaBalanceFactory.d.ts +0 -6
- package/build/platforms/solana/balance/Token.d.ts +0 -9
- package/build/platforms/solana/balance/index.d.ts +0 -2
- package/build/platforms/sui/balance/Native.d.ts +0 -5
- package/build/platforms/sui/balance/SuiBalance.d.ts +0 -11
- package/build/platforms/sui/balance/SuiBalanceFactory.d.ts +0 -6
- package/build/platforms/sui/balance/index.d.ts +0 -2
- package/build/transfer/DataReverseProcessor.d.ts +0 -6
package/build/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`,s.message):console.log(s),0n}}async getGasPrice(){return this.client.getProvider().getGasPrice()}async getNonce(t){return this.client.getProvider().getTransactionCount({address:t})}async simulateCall(t){let{address:e,args:s,value:n,func:a}=this.config,r=this.client.getProvider(),
|
|
3
|
-
`,o.details),{error:o}}}decodeEvents(t){let e=[];return t&&t.forEach(s=>{try{let{eventName:n,args:a}=(0,Nt.decodeEventLog)({abi:this.abi,data:s.data,topics:s.topics});e.push({eventName:n,args:a})}catch{}}),e}};var pt=class{static get(t,e){return new Mt(t,e)}};var Be=require("@galacticcouncil/xc-core"),Ee=require("viem");function ie(u){return u.module==="Snowbridge"&&u.func==="v2_sendMessage"}function Ie(u){if(!ie(u))return;let t=u.args[1];if(!t||t.length===0)return;let[e,s]=(0,Ee.decodeAbiParameters)([{type:"uint8"},{type:"address"},{type:"uint128"}],t[0]);return s}function Fe(u){let t=u.module==="Snowbridge"&&u.func==="v2_sendMessage"&&Array.isArray(u.args[1])&&u.args[1].length===0,e=u.module==="Snowbridge"&&u.func==="sendToken"&&u.args[0]==="0x0000000000000000000000000000000000000000";return u.module==="TokenBridge"&&["wrapAndTransferETHWithPayload","wrapAndTransferETH"].includes(u.func)||t||e}function De(u){return Object.entries(Be.Precompile).map(([e,s])=>s).includes(u.address)}var ft=class{#t;constructor(t){this.#t=t.evmClient}async buildCall(t,e,s,n){let a=pt.get(this.#t,n),{abi:r,asset:i,calldata:o}=a,c={abi:JSON.stringify(r),data:o,from:t,to:n.address,type:R.CallType.Evm,value:n.value,dryRun:async()=>{let{error:p,logs:f}=await a.simulateCall(t),h=a.decodeEvents(f);return{call:n.module+"."+n.func,error:p?.shortMessage,events:h}}};if(De(n)||Fe(n))return c;let l=ie(n)?Ie(n):i,m=new R.Erc20Client(this.#t,l),d=await m.allowance(t,n.address);if(d>=e)return c;let g=m.approve(n.address,e);return{abi:JSON.stringify(R.Abi.Erc20),allowance:d,data:g,from:t,to:l,type:R.CallType.Evm,dryRun:()=>{}}}async estimateFee(t,e,s,n){let r=await pt.get(this.#t,n).estimateFee(t,e);return s.copyWith({amount:r})}async getBalance(t,e){let s=_t.get(this.#t,e),[n,a]=await Promise.all([s.getBalance(),s.getDecimals()]);return R.AssetAmount.fromAsset(t,{amount:n,decimals:a})}async subscribeBalance(t,e){let s=new _.Subject,n=s.pipe((0,_.shareReplay)(1)),a=this.#t.getProvider(),r=async()=>{let o=async()=>{let l=await this.getBalance(t,e);s.next(l)};await o();let c=a.watchBlocks({onBlock:()=>o()});return()=>c()},i;return r().then(o=>i=o),n.pipe((0,_.finalize)(()=>i?.()),(0,_.distinctUntilChanged)((o,c)=>o.amount===c.amount))}};var Re=require("@galacticcouncil/xc-core"),ke=require("@galacticcouncil/common"),Ve=require("polkadot-api"),oe="0x0000000000000000000000000000000000000401",{H160:kn}=ke.h160,ce=class{#t;#e;#n;constructor(t,e){this.#t=t,this.#e=t.evmClient,this.#n=e}async signAndSend(t,e){let s=kn.fromAny(t.from),n=this.#e.getProvider(),a=!1;if(this.#t instanceof Re.EvmParachain)try{let i=this.#t.client,o=Ve.Binary.fromHex(t.data);await i.getUnsafeApi().txFromCallData(o),a=!0}catch{}let r;if(a){let[i,o]=await Promise.all([n.estimateGas({account:s,data:t.data,to:oe}),n.getGasPrice()]),c=o+o/100n*10n;r=await this.#n.sendTransaction({account:s,chain:this.#e.chain,data:t.data,maxPriorityFeePerGas:c,maxFeePerGas:c,gas:i*11n/10n,to:oe})}else{let{data:i,to:o,value:c}=t;r=await this.#n.sendTransaction({account:s,chain:this.#e.chain,data:i,to:o,value:c})}e.onTransactionSend(r),n.waitForTransactionReceipt({hash:r}).then(i=>e.onTransactionReceipt(i)).catch(i=>e.onError(i))}};var Ht=require("@galacticcouncil/xc-core"),je=require("@solana/web3.js"),Ke=require("buffer"),N=require("rxjs");var tt=class{connection;config;constructor(t,e){this.validateConnection(t),this.validateConfig(e),this.connection=t,this.config=e}validateConnection(t){if(!t)throw new Error("No connection found")}validateConfig(t){if(!t.address)throw new Error("Solana address is required")}};var Oe=require("@wormhole-foundation/sdk-solana");var Vn=9,Wt=class extends tt{async getBalance(){let{address:t}=this.config,e=new Oe.SolanaAddress(t).unwrap(),s=await this.connection.getBalance(e);return BigInt(s)}async getDecimals(){return Vn}};var Ut=require("@wormhole-foundation/sdk-solana");var jt=class extends tt{constructor(t,e){super(t,e),this.validateToken(e)}async getBalance(){let{address:t,token:e}=this.config,s=new Ut.SolanaAddress(t).unwrap(),n=new Ut.SolanaAddress(e).unwrap();return(await this.connection.getParsedTokenAccountsByOwner(s,{mint:n})).value.reduce((r,{account:i})=>{let o=i.data.parsed.info.tokenAmount;return r+=BigInt(o.amount),r},0n)}async getDecimals(){let{token:t}=this.config,e=new Ut.SolanaAddress(t).unwrap();return(await this.connection.getTokenSupply(e)).value.decimals}validateToken(t){if(!t.token)throw new Error("Token address is required")}};var Kt=class{static get(t,e){switch(e.module){case"Native":return new Wt(t,e);case"Token":return new jt(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};var D=require("@solana/web3.js"),_e=.5,Me=2,Ne=1,We=1e6,On=25e4,zt=class{connection;config;constructor(t,e){this.validateConnection(t),this.connection=t,this.config=e}validateConnection(t){if(!t)throw new Error("No connection found")}async getPriorityMessage(t){let{instructions:e}=this.config,s=await this.getV0Message(t,e),n=await this.createPriorityFeeInstructions(s);return this.getV0Message(t,[...e,...n])}async estimateFee(t,e){if(e===0n)return 0n;let{instructions:s}=this.config,n=await this.getV0Message(t,s),a=await this.determineComputeBudget(n);return BigInt(a)}async getV0Message(t,e){let s=new D.PublicKey(t),{blockhash:n}=await this.connection.getLatestBlockhash("finalized");return new D.TransactionMessage({payerKey:s,recentBlockhash:n,instructions:e}).compileToV0Message()}async createPriorityFeeInstructions(t,e=_e,s=Me,n=Ne,a=We){let[r,i]=await Promise.all([this.determineComputeBudget(t),this.determinePriorityFee(t,e,s,n,a)]);return[D.ComputeBudgetProgram.setComputeUnitLimit({units:r}),D.ComputeBudgetProgram.setComputeUnitPrice({microLamports:i})]}async simulateTransaction(t,e){let s=new D.VersionedTransaction(e);return(await this.connection.simulateTransaction(s,{accounts:{encoding:"base64",addresses:[t]}})).value}async determineComputeBudget(t){let e=new D.VersionedTransaction(t),s=await this.connection.simulateTransaction(e),{err:n,unitsConsumed:a}=s.value;return a&&!n?Math.round(a*1.2):On}async determinePriorityFee(t,e=_e,s=Me,n=Ne,a=We){let r=n,i=await this.getTxAccounts(t),o=await this.connection.getRecentPrioritizationFees({lockedWritableAccounts:i});if(o){let c=o.map(m=>m.prioritizationFee).filter(m=>m>0).sort((m,d)=>m-d),l=Math.ceil(c.length*e);if(c.length>l){let d=c[l]*s;r=Math.max(r,d)}}return Math.min(Math.max(r,n),a)}async getTxAccounts(t){let e=(await Promise.all(t.addressTableLookups.map(n=>this.connection.getAddressLookupTable(n.accountKey)))).map(n=>n.value).filter(n=>n!==null),s=t.getAccountKeys({addressLookupTableAccounts:e??void 0});return t.compiledInstructions.flatMap(n=>n.accountKeyIndexes).map(n=>t.isAccountWritable(n)?s.get(n):null).filter(n=>n!==null)}};var ht=class{static get(t,e){return new zt(t,e)}};var Ue=require("@solana/web3.js");function M(u){return u.map(t=>({program:t.programId.toBase58(),data:t.data.toString("hex"),keys:t.keys.map(e=>e.pubkey.toBase58())}))}function ue(u,t=1e3){let e=[],s=[],n=0;for(let a of u){let r=a.data?.length??0;s.length&&n+r>t&&(e.push(s),s=[],n=0),s.push(a),n+=r}return s.length&&e.push(s),e}function et(u){let t=u.serialize();return Buffer.from(t).toString("hex")}function _n(u){let t=Buffer.from(u,"hex"),e=Uint8Array.from(t);return Ue.MessageV0.deserialize(e)}var yt=class{#t;constructor(t){this.#t=t.connection}async buildCall(t,e,s,n){let a=ht.get(this.#t,n),r=await a.getPriorityMessage(t),i=r.serialize(),o=Ke.Buffer.from(i).toString("hex");return{from:t,data:o,ix:M(n.instructions),signers:n.signers,type:Ht.CallType.Solana,dryRun:async()=>{let{err:c,logs:l}=await a.simulateTransaction(t,r);return{call:n.module+"."+n.func,error:c,events:l}}}}async estimateFee(t,e,s,n){let a=ht.get(this.#t,n),r=await a.estimateFee(t,e),i=await a.getPriorityMessage(t),{accounts:o}=await a.simulateTransaction(t,i),l=(o&&o[0])?.lamports;if(l){let m=n.module==="TokenBridge"&&n.func==="TransferNativeWithPayload";return s.copyWith({amount:s.amount-BigInt(l)-(m?e:0n)+n.rentReserve})}return s.copyWith({amount:r+n.rentReserve})}async getBalance(t,e){let s=Kt.get(this.#t,e),[n,a]=await Promise.all([s.getBalance(),s.getDecimals()]);return Ht.AssetAmount.fromAsset(t,{amount:n,decimals:a})}async subscribeBalance(t,e){let s=new N.Subject,n=s.pipe((0,N.shareReplay)(1)),a=async()=>{let i=async()=>{let l=await this.getBalance(t,e);s.next(l)};await i();let o=new je.PublicKey(e.address),c=this.#t.onAccountChange(o,()=>i());return()=>{this.#t.removeAccountChangeListener(c)}},r;return a().then(i=>r=i),n.pipe((0,N.finalize)(()=>r?.()),(0,N.distinctUntilChanged)((i,o)=>i.amount===o.amount))}};var X=require("@galacticcouncil/xc-core"),P=require("@solana/web3.js"),C=require("@solana/spl-token"),ze=require("@wormhole-foundation/sdk-solana"),le=require("@wormhole-foundation/sdk-solana-core"),He=require("@wormhole-foundation/sdk-base"),me=require("@wormhole-foundation/sdk-definitions"),Ct=require("@wormhole-foundation/sdk-solana-tokenbridge");var q=class{#t;constructor(t){this.#t=t.connection}async sendBundle(t){let{result:e}=await this.#t._rpcRequest("sendBundle",[t]);return e}async simulateBundle(t){return(await this.#t._rpcRequest("simulateBundle",[[t]])).result}async getInflightBundleStatuses(t){let{result:e}=await this.#t._rpcRequest("getInflightBundleStatuses",[t]);return e}async getRegion(){let{result:t}=await this.#t._rpcRequest("getRegions",[]);return t}async getTipAccount(){let{result:t}=await this.#t._rpcRequest("getTipAccounts",[]);return t}};var At=class{#t;#e;#n;constructor(t){this.#t=t,this.#e=t.connection,this.#n=new q(t)}async redeem(t,e,s){let n=X.Wormhole.fromChain(this.#t),a=He.encoding.b64.decode(e),r=(0,me.deserialize)("TokenBridge:Transfer",a),i=(0,me.deserialize)("Uint8Array",a),o=this.derivePostedVaaKey(n.getCoreBridge(),Buffer.from(r.hash)),c=new P.PublicKey(t),l=s?new P.PublicKey(s):c,m=c.equals(l),d=[];if(!await this.#e.getAccountInfo(o)){let y=P.Keypair.generate(),I=await le.utils.createVerifySignaturesInstructions(this.#t.connection,n.getCoreBridge(),c,i,y.publicKey),k=ue(I,1e3);for(let F=0;F<k.length;F++){let w=k[F],V=await this.getV0Message(c,w),O=et(V);d.push({from:t,data:O,ix:M(w),signers:[y],type:X.CallType.Solana})}let L=le.utils.createPostVaaInstruction(this.#e,n.getCoreBridge(),c,i,y.publicKey),mt=await this.getV0Message(c,[L]),A=et(mt);d.push({from:t,data:A,ix:M([L]),type:X.CallType.Solana})}let p=r.payload.token.chain==="Solana",f=new P.PublicKey(r.payload.token.address.toUint8Array()),h=p&&f.equals(C.NATIVE_MINT),T=await this.#n.getTipAccount(),b=P.SystemProgram.transfer({fromPubkey:c,toPubkey:new P.PublicKey(T[0]),lamports:1e3});if(h&&m){let y=await this.redeemAndUnwrap(n,c,r,b);d.push(y)}else{let y=await this.redeemToken(n,c,l,f,p,r,b);d.push(y)}return d}async redeemToken(t,e,s,n,a,r,i){let c=(a?Ct.createCompleteTransferNativeInstruction:Ct.createCompleteTransferWrappedInstruction)(this.#e,t.getTokenBridge(),t.getCoreBridge(),e,r),l=(0,C.getAssociatedTokenAddressSync)(n,s),m=(0,C.createAssociatedTokenAccountIdempotentInstruction)(e,l,s,n),d=await this.getV0Message(e,[m,c,i]),g=et(d);return{from:e.toBase58(),data:g,ix:M([m,c]),type:X.CallType.Solana}}async redeemAndUnwrap(t,e,s,n){let a=new P.PublicKey(s.payload.to.address.toUint8Array()),r=await(0,C.getMint)(this.#e,C.NATIVE_MINT),i=s.payload.token.amount*BigInt(Math.pow(10,r.decimals-8)),o=await(0,C.getMinimumBalanceForRentExemptAccount)(this.#e),c=P.Keypair.generate(),l=(0,C.createAssociatedTokenAccountIdempotentInstruction)(e,a,e,C.NATIVE_MINT),m=(0,Ct.createCompleteTransferNativeInstruction)(this.#e,t.getTokenBridge(),t.getCoreBridge(),e,s),d=P.SystemProgram.createAccount({fromPubkey:e,newAccountPubkey:c.publicKey,lamports:o,space:C.ACCOUNT_SIZE,programId:C.TOKEN_PROGRAM_ID}),g=(0,C.createInitializeAccountInstruction)(c.publicKey,C.NATIVE_MINT,e),p=(0,C.createTransferInstruction)(a,c.publicKey,e,i),f=(0,C.createCloseAccountInstruction)(c.publicKey,e,e),h=[l,m,d,g,p,f,n],T=await this.getV0Message(e,h),b=et(T);return{from:e.toBase58(),data:b,ix:M(h),signers:[c],type:X.CallType.Solana}}derivePostedVaaKey(t,e){return ze.utils.deriveAddress([Buffer.from("PostedVAA"),e],t)}async getV0Message(t,e){let{blockhash:s}=await this.#e.getLatestBlockhash("finalized");return new P.TransactionMessage({payerKey:t,recentBlockhash:s,instructions:e}).compileToV0Message()}};var J=require("@solana/web3.js"),Lt=require("buffer");var de=class{#t;#e;#n;constructor(t,e){this.#t=t,this.#e=e,this.#n=new q(t)}async signAndSend(t,e){let{data:s,signers:n}=t,a=this.toVersioned(s,n);try{if(this.#e instanceof J.Keypair){a.sign([this.#e]);let c=await this.#t.connection.sendTransaction(a);e.onTransactionSend(c);let l=await this.#t.connection.getSignatureStatus(c);e.onStatus?.(l);return}let r=this.#e;await r.connect(),n&&a.sign(n);let{signature:i}=await r.signAndSendTransaction(a);e.onTransactionSend(i);let o=await this.#t.connection.getSignatureStatus(i);e.onStatus?.(o)}catch(r){e.onError(r)}}async signAndSendAll(t,e){let s=t.map(n=>{let{data:a,signers:r}=n;return this.toVersioned(a,r)});try{let n;if(this.#e instanceof J.Keypair)s.forEach(o=>o.sign([this.#e])),n=s.map(o=>Lt.Buffer.from(o.serialize()).toString("base64"));else{let o=this.#e;await o.connect(),n=(await o.signAllTransactions(s)).map(l=>Lt.Buffer.from(l.serialize()).toString("base64"))}let a=await this.#n.simulateBundle(n);if(a.value.summary!=="succeeded")throw new Error("Bundle simulation failed! "+JSON.stringify(a,null,2));let r=await this.#n.sendBundle(n);e.onTransactionSend(r);let i=await this.#n.getInflightBundleStatuses([r]);e.onBundleStatus?.(i.value)}catch(n){e.onError(n)}}toVersioned(t,e){let s=Lt.Buffer.from(t,"hex"),n=Uint8Array.from(s),a=J.MessageV0.deserialize(n),r=new J.VersionedTransaction(a);return e&&r.sign(e),r}};var W=require("@galacticcouncil/xc-core"),ge=require("@wormhole-foundation/sdk-base"),Le=require("viem"),pe=require("polkadot-api"),bt=class{#t;constructor(t){this.#t=t,W.Wormhole.fromChain(this.#t)}redeemMrl(t,e){let s=ge.encoding.b64.decode(e),n=ge.encoding.hex.encode(s),a=W.Abi.Gmp,r=(0,Le.encodeFunctionData)({abi:a,functionName:"wormholeTransferERC20",args:["0x"+n]});return{abi:JSON.stringify(a),data:r,from:t,to:W.Precompile.Bridge}}async redeemMrlViaXcm(t,e){let n=this.#t.client.getUnsafeApi(),a=this.redeemMrl(t,e),i=await n.tx.EthereumXcm.transact({xcm_transaction:{type:"V2",value:{gas_limit:[5000000n,0n,0n,0n],action:{type:"Call",value:a.to},value:[0n,0n,0n,0n],input:pe.Binary.fromHex(a.data),access_list:void 0}}}).getEncodedData();return{data:pe.Binary.toHex(i),from:t,type:W.CallType.Substrate,dryRun:async()=>{},txOptions:void 0}}};var Qt=require("@galacticcouncil/xc-core"),wt=require("polkadot-api");var $e=require("@galacticcouncil/common");async function fe(u,t,e){let s=await e.getDecimals(),n=e.chain.getAssetDecimals(t)??s,a=e.chain.usesChainDecimals?s:n;return{amount:$e.big.convertDecimals(u,a,n),decimals:n}}var Qe=require("@galacticcouncil/common"),qe=u=>{let t=[];for(let e of u)if(["PolkadotXcm"].includes(e.type)&&e.value.type==="FeesPaid"){let n=e.value.value.fees;for(let a of n)if(a.fun.type==="Fungible"){let r=BigInt(a.fun.value);t.push(r)}}return t.reduce((e,s)=>e+s,0n)},nt=u=>{let t=u.value.error;return t.type==="Module"?Qe.enums.enumPath(t.value):JSON.stringify(t.value)};var $t=require("@galacticcouncil/common");function Mn(u){return{parents:0,interior:{type:"X1",value:u.startsWith("0x")?$t.xcm.toAccountKey20(u):$t.xcm.toAccountId32(u)}}}function Xe(u){return{type:"V4",value:{parents:1,interior:{type:"X1",value:{type:"Parachain",value:u.parachainId}}}}}var Nn=(u,t)=>({id:$t.xcm.transform(u),fun:{type:"Fungible",value:t}}),Je=(u,t,e,s,n,a)=>{console.log(a);let r=Mn(u),i=Nn(t,e.amount);return{type:"V4",value:[{type:"WithdrawAsset",value:[i]},{type:"BuyExecution",value:{fees:i,weight_limit:{type:"Unlimited"}}},{type:"Transact",value:{origin_kind:{type:"SovereignAccount"},require_weight_at_most:{ref_time:s,proof_size:n},call:a}},{type:"RefundSurplus",value:void 0},{type:"DepositAsset",value:{assets:{type:"Wild",value:{type:"AllCounted",value:1}},beneficiary:r}}]}};var vt=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}async remoteExec(t,e,s,n,a={}){let r=this.#t.api,i=await this.#t.getAsset(),o=this.#e.api,c=this.#e.chain,l=await c.getCurrency(),m=l.asset,d=l.decimals,g=c.getAssetXcmLocation(m),p=wt.Binary.fromHex(s.data),h=await(await o.txFromCallData(p)).getPaymentInfo(e),T=BigInt(h.partial_fee)*120n/100n,b=Qt.AssetAmount.fromAsset(m,{amount:T,decimals:d}),y=h.weight.ref_time,I=h.weight.proof_size,k=Xe(c),L=Je(e,g,b,y,I,p),mt=r.tx.PolkadotXcm.send({dest:k,message:L}),A=[];try{let x=await this.#t.chain.dex.getCalldata(t,a.srcFeeAsset||i,m,b,10),Dt=wt.Binary.fromHex(x),dt=await r.txFromCallData(Dt);A.push(dt)}catch{}let F=await n(b),w=wt.Binary.fromHex(F.data),V=await r.txFromCallData(w);A.push(V),A.push(mt);let O=A.map(x=>x.decodedCall),Ft=r.tx.Utility.batch_all({calls:O}),ae=await Ft.getEncodedData();return{from:t,data:wt.Binary.toHex(ae),type:Qt.CallType.Substrate,dryRun:this.#t.isDryRunSupported()?async()=>{try{let x=await this.#t.dryRun(t,Ft);return{call:"polkadotXcm.send",error:x.execution_result&&x.execution_result.success?void 0:nt(x.execution_result),events:x.emitted_events||[],xcm:x.forwarded_xcms||[]}}catch(x){return{call:"polkadotXcm.send",error:x instanceof Error?x.message:"unknown"}}}:()=>{}}}};var G=require("@galacticcouncil/xc-core"),Ye=require("polkadot-api"),E=require("rxjs");var U=require("@galacticcouncil/xc-core"),qt=require("@galacticcouncil/common"),Xt=require("@polkadot-api/substrate-bindings"),xt=require("@polkadot-api/utils"),he=require("polkadot-api");var{Ss58Addr:Ge}=U.addr,B=class u{chain;_currency;constructor(t){this.chain=t}static async create(t){return new u(t)}get client(){return this.chain.client}get api(){return this.client.getUnsafeApi()}async getCurrency(){return this._currency||(this._currency=this.chain.getCurrency()),this._currency}async getAsset(){return(await this.getCurrency()).asset}async getDecimals(){return(await this.getCurrency()).decimals}async getExistentialDeposit(){let t;try{let n=await this.api.constants.Balances.ExistentialDeposit();t=typeof n=="bigint"?n:BigInt(String(n))}catch{t=0n}let{asset:e,decimals:s}=await this.getCurrency();return U.AssetAmount.fromAsset(e,{amount:t,decimals:s})}isDryRunSupported(){return this.api.apis?.DryRunApi!==void 0}async buildMessageId(t,e,s,n){let a=await this.client._request("system_accountNextIndex",[t]),r=Xt.u32.enc(a),i=l=>new TextEncoder().encode(l),o=new Uint8Array([...i(this.chain.parachainId.toString()),...(0,xt.fromHex)(t.startsWith("0x")?t.slice(2):t),...r,...(0,xt.fromHex)(s.startsWith("0x")?s.slice(2):s),...i(n),...i(e.toString())]),c=(0,Xt.Blake2256)(o);return(0,xt.toHex)(c)}async dryRun(t,e){let s=(0,he.Enum)("Signed",t),n=(0,he.Enum)("system",s),a=await this.api.apis.DryRunApi.dry_run_call(n,e.decodedCall,4);if(!a.success)throw new Error("DryRun call failed");let r=a.value;if("type"in r&&"value"in r)throw new Error("DryRun call error: "+qt.enums.enumPath(r.value));return r}async estimateNetworkFee(t,e){let s=e.getTx(this.client);try{let n=await s.getPaymentInfo(t);return BigInt(n.partial_fee)}catch{console.warn("Can't estimate network fee.")}return 0n}async estimateDeliveryFee(t,e){if(this.chain.usesDeliveryFee){let s=await this.estimateDeliveryFeeWith(t,e);try{let n=e.getTx(this.client),a=await this.dryRun(s,n);if(a.execution_result?.success)return qe(a.emitted_events||[]);{let r=nt(a.execution_result);console.warn(`Can't estimate delivery fee. Reason:
|
|
4
|
-
${r}`)}}catch{}}return 0n}async estimateDeliveryFeeWith(t,e){if(["PolkadotXcm"].includes(e.module)){let n=e.getTx(this.client).decodedCall.value.value,a="dest"in n?n.dest:void 0;if(!a)return t;let r=U.multiloc.findNestedKey(a,"interior"),i=U.multiloc.findParachain(a);if(U.multiloc.findGlobalConsensus(a))return t;if(i){let c=qt.acc.getSovereignAccounts(i);return this.chain.parachainId===0?Ge.encodePubKey(c.relay):Ge.encodePubKey(c.generic)}if(r&&r.interior==="Here")return this.chain.treasury||t}return t}};var St=class{#t;constructor(t){this.#t=B.create(t)}async useSignerFee(t){let e=await this.#t,s=await e.getAsset();return e.chain.usesSignerFee&&!s.isEqual(t)}async buildCall(t,e,s,n){let a=await this.#t,i=await this.useSignerFee(s)?{asset:new G.Asset(s)}:void 0,o=n.getTx(a.client),c=n.module+"."+n.func,l=await o.getEncodedData();return{from:t,data:Ye.Binary.toHex(l),type:G.CallType.Substrate,txOptions:i,dryRun:a.isDryRunSupported()?async()=>{try{let m=n.getTx(a.client),d=await a.dryRun(t,m),g=d.execution_result&&d.execution_result.success?void 0:nt(d.execution_result);return{call:c,error:g,events:d.emitted_events||[],xcm:d.forwarded_xcms||[]}}catch(m){return{call:c,error:m instanceof Error?m.message:"unknown"}}}:()=>{}}}async estimateFee(t,e,s,n){let a=await this.#t,r=await a.estimateNetworkFee(t,n),i=await a.estimateDeliveryFee(t,n),o=await this.exchangeFee(r+i,s),c=await fe(o,s,a);return s.copyWith(c)}async getBalance(t,e){let s=await this.subscribeBalance(t,e);return(0,E.firstValueFrom)(s)}async subscribeBalance(t,e){let s=await this.#t,{module:n,func:a,args:r,transform:i}=e;return s.client.getUnsafeApi().query[n][a].watchValue(...r,{at:"best"}).pipe((0,E.map)(({value:l})=>l)).pipe((0,E.concatMap)(l=>i(l)),(0,E.distinctUntilChanged)((l,m)=>l===m),(0,E.concatMap)(async l=>{let m=await fe(l,t,s);return G.AssetAmount.fromAsset(t,m)}),(0,E.catchError)(l=>(console.error("subscribe fails for:",t),(0,E.throwError)(()=>l))))}async exchangeFee(t,e){let s=await this.#t,n=await s.getAsset(),a=await s.getDecimals();if(n.isEqual(e))return t;try{let r=s.chain.dex,i=G.AssetAmount.fromAsset(n,{amount:t,decimals:a});return(await r.getQuote(e,n,i,!0)).amount}catch{}return t}};var ye=require("@galacticcouncil/xc-core"),st=require("polkadot-api"),Ce=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}signAndSend(t,e){let n=this.#t.client.getUnsafeApi(),a=st.Binary.fromHex(t.data),r={};t.txOptions?.asset&&(r={asset:this.getFeeAsset(t.txOptions.asset)}),n.txFromCallData(a).then(i=>{i.signSubmitAndWatch(this.#e,r).subscribe({next:o=>{o.type==="broadcasted"&&e.onTransactionSend(o.txHash),o.type==="finalized"&&e.onFinalized(o)},error:o=>{e.onError(o)}})})}getFeeAsset(t){let e=this.#t.getAssetXcmLocation(t);if(e){let s=ye.multiloc.findPalletInstance(e),n=ye.multiloc.findGeneralIndex(e);return{parents:0,interior:(0,st.Enum)("X2",[(0,st.Enum)("PalletInstance",Number(s)),(0,st.Enum)("GeneralIndex",BigInt(n))])}}throw new Error("Asset location not found")}};var Gt=require("@galacticcouncil/xc-core"),tn=require("@mysten/sui/transactions"),en=require("@mysten/sui/utils"),nn=require("@mysten/bcs"),at=require("@wormhole-foundation/sdk-connect"),sn=require("@wormhole-foundation/sdk-definitions"),Ae=require("@wormhole-foundation/sdk-sui"),an=require("@wormhole-foundation/sdk-sui-tokenbridge");var Ze=require("@mysten/bcs");function Jt(u,t={}){let e=u.inputs??[],s=u.commands??[],n=t.numbers??"string",a=t.decode32As??"address",r=l=>n==="bigint"?l:n==="number"?Number(l):l.toString(),i=l=>{let m=(0,Ze.fromBase64)(l),d=g=>{let p=0n;for(let f=0;f<g;f++)p|=BigInt(m[f])<<8n*BigInt(f);return p};return m.length===1?{type:"pure",valueType:"u8",value:Number(m[0])}:m.length===2?{type:"pure",valueType:"u16",value:r(d(2))}:m.length===4?{type:"pure",valueType:"u32",value:Number(d(4))}:m.length===8?{type:"pure",valueType:"u64",value:r(d(8))}:m.length===32&&a==="address"?{type:"pure",valueType:"address",value:"0x"+[...m].map(p=>p.toString(16).padStart(2,"0")).join("")}:{type:"pure",valueType:"vector<u8>",value:Array.from(m)}},o=l=>{let m=e[l];if(!m)return{Input:l};if(m.Pure?.bytes)return i(m.Pure.bytes);let d=m.Object?.SharedObject;if(d)return{type:"object",objectType:"sharedObject",objectId:d.objectId,initialSharedVersion:String(d.initialSharedVersion),mutable:!!d.mutable};let g=m.Object?.ImmOrOwnedObject;return g?{type:"object",objectType:"immOrOwnedObject",objectId:g.objectId,version:String(g.version),digest:g.digest??void 0}:{Input:l}},c=l=>l?.GasCoin?"GasCoin":Array.isArray(l?.NestedResult)?l:typeof l?.Input=="number"?o(l.Input):l;return s.map(l=>{if(l.MoveCall){let m=l.MoveCall;return{MoveCall:{...m,arguments:(m.arguments??[]).map(c)}}}if(l.SplitCoins){let m=l.SplitCoins,d=m.coin?.GasCoin?"GasCoin":c(m.coin),g=(m.amounts??[]).map(c);return{SplitCoins:[d,g]}}if(l.MergeCoins){let m=l.MergeCoins;return{MergeCoins:{...m,destination:c(m.destination),sources:(m.sources??[]).map(c)}}}if(l.TransferObjects){let m=l.TransferObjects;return{TransferObjects:{...m,objects:(m.objects??[]).map(c),address:c(m.address)}}}return l})}var be=class{#t;constructor(t){this.#t=t}async redeem(t,e){let s=Gt.Wormhole.fromChain(this.#t),n=this.#t.client,a=at.encoding.b64.decode(e),r=(0,sn.deserialize)("TokenBridge:Transfer",a),i=s.getCoreBridge(),o=s.getTokenBridge(),c=await(0,an.getTokenCoinType)(n,o,r.payload.token.address.toUint8Array(),(0,at.toChainId)(r.payload.token.chain));if(!c)throw new Error("Unable to fetch token coinType");let[l,m]=await Promise.all([(0,Ae.getPackageId)(n,i),(0,Ae.getPackageId)(n,o)]),d=new tn.Transaction;d.setSender(t);let[g]=d.moveCall({target:`${l}::vaa::parse_and_verify`,arguments:[d.object(i),d.pure.vector("u8",(0,at.serialize)(r)),d.object(en.SUI_CLOCK_OBJECT_ID)]}),[p]=d.moveCall({target:`${m}::vaa::verify_only_once`,arguments:[d.object(o),g]}),[f]=d.moveCall({target:`${m}::complete_transfer::authorize_transfer`,arguments:[d.object(o),p],typeArguments:[c]}),[h]=d.moveCall({target:`${m}::complete_transfer::redeem_relayer_payout`,arguments:[f],typeArguments:[c]});d.moveCall({target:`${m}::coin_utils::return_nonzero`,arguments:[h],typeArguments:[c]});let T=await d.build({client:n}),b=await d.toJSON(),y=Jt(JSON.parse(b));return{from:t,commands:y,data:(0,nn.toBase64)(T),type:Gt.CallType.Sui}}};var ee=require("@galacticcouncil/xc-core"),on=require("@mysten/bcs"),j=require("rxjs");var Yt=class{client;config;constructor(t,e){this.validateClient(t),this.validateConfig(e),this.client=t,this.config=e}validateClient(t){if(!t)throw new Error("No client found")}validateConfig(t){if(!t.address)throw new Error("Sui address is required")}};var rn=require("@mysten/sui/utils");var Wn=9,Zt=class extends Yt{async getBalance(){let{address:t}=this.config,e=await this.client.getBalance({owner:t,coinType:rn.SUI_TYPE_ARG});return BigInt(e.totalBalance)}async getDecimals(){return Wn}};var te=class{static get(t,e){switch(e.module){case"Native":return new Zt(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};var Pt=class{#t;constructor(t){this.#t=t.client}async buildCall(t,e,s,n){let{transaction:a}=n;a.setSender(t);let r=await a.build({client:this.#t}),i=await a.toJSON(),o=Jt(JSON.parse(i));return{from:t,commands:o,data:(0,on.toBase64)(r),type:ee.CallType.Sui,dryRun:async()=>{let c=await this.#t.dryRunTransactionBlock({transactionBlock:r});return{call:n.module+"."+n.func,error:c.executionErrorSource}}}}async estimateFee(t,e,s,n){let{transaction:a}=n;a.setSender(t);let r=await a.build({client:this.#t}),o=(await this.#t.dryRunTransactionBlock({transactionBlock:r})).effects.gasUsed,c=BigInt(o.computationCost),l=BigInt(o.storageCost),m=c+l;return s.copyWith({amount:m})}async getBalance(t,e){let s=te.get(this.#t,e),[n,a]=await Promise.all([s.getBalance(),s.getDecimals()]);return ee.AssetAmount.fromAsset(t,{amount:n,decimals:a})}async subscribeBalance(t,e){let s=new j.Subject,n=s.pipe((0,j.shareReplay)(1)),a=async()=>{await(async()=>{let c=await this.getBalance(t,e);s.next(c)})();let o=setInterval(()=>{},3e3);return()=>clearInterval(o)},r;return a().then(i=>r=i),n.pipe((0,j.finalize)(()=>r?.()),(0,j.distinctUntilChanged)((i,o)=>i.amount===o.amount))}};var cn=require("@mysten/sui/keypairs/ed25519"),un=require("@mysten/sui/transactions"),we=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}async signAndSend(t,e){let{from:s,data:n}=t,a=this.#t.client;try{if(this.#e instanceof cn.Ed25519Keypair){let o=un.Transaction.from(n),c=await a.signAndExecuteTransaction({signer:this.#e,transaction:o,options:{showEffects:!0,showEvents:!0,showObjectChanges:!0,showBalanceChanges:!0}});e.onTransactionSend(c.digest);return}let r=await this.#e.signTransaction({transaction:n,address:s,networkID:"sui:mainnet"}),i=await a.executeTransactionBlock({transactionBlock:r.transaction,signature:r.signature,options:{showEffects:!0,showEvents:!0,showObjectChanges:!0,showBalanceChanges:!0}});e.onTransactionSend(i.digest)}catch(r){e.onError(r)}}};var K=class{platform={};constructor(t){switch(t.getType()){case rt.ChainType.EvmChain:this.registerEvm(t);break;case rt.ChainType.EvmParachain:this.registerEvm(t),this.registerSubstrate(t);break;case rt.ChainType.Parachain:this.registerSubstrate(t);break;case rt.ChainType.SolanaChain:this.registerSolana(t);break;case rt.ChainType.SuiChain:this.registerSui(t);break;default:throw new Error("Unsupported platform: "+t.getType())}}registerEvm(t){let e=t;this.platform.Evm=new ft(e)}registerSolana(t){let e=t;this.platform.Solana=new yt(e)}registerSui(t){let e=t;this.platform.Sui=new Pt(e)}registerSubstrate(t){let e=t;this.platform.Substrate=new St(e)}async buildCall(t,e,s,n){return this.platform[n.type].buildCall(t,e,s,n)}async estimateFee(t,e,s,n){return this.platform[n.type].estimateFee(t,e,s,n)}async getBalance(t,e){return this.platform[e.type].getBalance(t,e)}async subscribeBalance(t,e){return this.platform[e.type].subscribeBalance(t,e)}};var H=require("@galacticcouncil/xc-core"),Tt=require("@galacticcouncil/common");var ln=require("@galacticcouncil/common"),it=Dn(require("big.js"),1);function mn(u,t,e,s){let n=u.toBig().minus(e.toBig()).minus(u.isSame(t)?t.toBig():new it.default(0));return s&&(n=n.minus(u.isSame(s)?s.toBig():new it.default(0))),u.copyWith({amount:n.lt(0)?0n:BigInt(n.toFixed())})}function dn(u,t,e,s){let a=u.copyWith({amount:0n}).toBig().plus(u.isSame(t)?t.toBig():new it.default(0)).plus(u.toBig().lt(e.toBig())?e.toBig():new it.default(0));return s&&(a=a.plus(u.isSame(s)&&u.toBig().lt(s.toBig())?s.toBig():new it.default(0))),u.copyWith({amount:BigInt(a.toFixed())})}async function z(u,t){return t.isEvmParachain()?t.getDerivatedAddress(u):u}function gn(u,t){return t?ln.big.toBigInt(t,u):0n}var Y=require("@galacticcouncil/xc-core"),pn=require("@galacticcouncil/common");var{EvmAddr:Un}=Y.addr,ot=class{adapter;config;constructor(t,e){this.adapter=t,this.config=e}async getEd(){let{chain:t}=this.config;if(t instanceof Y.Parachain)return(await B.create(t)).getExistentialDeposit()}async getBalance(t){let{chain:e,route:s}=this.config,{source:n}=s,a=n.asset,r=e.getBalanceAssetId(a),i=Un.isValid(r.toString())?await z(t,e):t,o=s.source.balance.build({address:i,asset:a,chain:e});return this.adapter.getBalance(a,o)}async getMin(){let{chain:t,route:e}=this.config,{source:s}=e,n=s.asset,a=s.min;if(t instanceof Y.Parachain&&a){let r=t.getMinAssetId(n),i=a.build({asset:r});return this.adapter.getBalance(n,i)}return this.getAssetMin()}async getAssetMin(){let{chain:t,route:e}=this.config,{source:s}=e,n=s.asset,a=t.getAssetMin(n),r=await this.getDecimals(n),i=0n;return a&&(i=pn.big.toBigInt(a,r)),Y.AssetAmount.fromAsset(n,{amount:i,decimals:r})}async getDecimals(t){let{chain:e}=this.config,s=e.getAssetDecimals(t);return s||(await e.getCurrency()).decimals}};var{EvmAddr:fn}=H.addr,Bt=class extends ot{constructor(t,e){super(t,e)}async getCall(t){let{amount:e,sender:s,source:n}=t,a=await this.getTransfer(t);return this.adapter.buildCall(s,e,n.feeBalance,a)}async getDestinationFee(t){let{chain:e,route:s}=this.config,{source:n,destination:a,transact:r}=s,i=a.fee.amount,o=n.destinationFee.asset||a.fee.asset,c=await this.getDecimals(o);if(Number.isFinite(i))return{fee:H.AssetAmount.fromAsset(o,{amount:Tt.big.toBigInt(i,c),decimals:c}),feeBreakdown:{}};let l=i,{amount:m,breakdown:d}=await l.build({feeAsset:o,transferAsset:n.asset,source:r?r.chain:e,destination:a.chain,amount:t});return{fee:H.AssetAmount.fromAsset(o,{amount:m,decimals:c}),feeBreakdown:d}}async getDestinationFeeBalance(t){let{chain:e,route:s}=this.config,{source:n,destination:a}=s,r=n.asset,i=n.destinationFee.asset||a.fee.asset;if(r.isEqual(i))return this.getBalance(t);let o=e.getBalanceAssetId(i),c=fn.isValid(o.toString())?await z(t,e):t,l=n.destinationFee.balance.build({address:c,asset:i,chain:e});return this.adapter.getBalance(i,l)}async getFee(t){let{chain:e,route:s}=this.config,{amount:n,sender:a,source:r}=t,i=await this.getTransfer(t),o=s.contract?await z(a,e):a,c=await this.adapter.estimateFee(o,n,r.feeBalance,i),{fee:l}=s.source,m=l?gn(c.decimals,l.extra):0n,d=c.amount+m;return c.copyWith({amount:d})}async getFeeBalance(t){let{chain:e,route:s}=this.config,{source:n}=s;if(!n.fee)return this.getBalance(t);let a=await this.getFeeAsset(t),r=e.getBalanceAssetId(a),i=fn.isValid(r.toString())?await z(t,e):t,o=n.fee.balance.build({address:i,asset:a,chain:e});return this.adapter.getBalance(a,o)}async getFeeAsset(t){let{chain:e,route:s}=this.config,{source:n}=s,a=n.fee,r=n.asset;if(!a)return r;let i=a.asset;return e instanceof H.Parachain&&"build"in i?await i.build({chain:e,address:t}):i}async getTransfer(t){let{chain:e,route:s}=this.config,{contract:n,extrinsic:a,program:r,move:i}=s;if(a){let{address:c,amount:l,asset:m,sender:d}=t,p=await(await B.create(e)).buildMessageId(d,l,m.originSymbol,c);return a.build({...t,messageId:p})}let o=n||r||i;if(o)return o.build({...t});throw new Error("AssetRoute transfer config is invalid! Specify contract, extrinsic, move or program instructions.")}async getTransact(t){let{route:e}=this.config,{transact:s}=e;if(s){let n=Object.assign({transact:{chain:s.chain}}),a={...t,...n};return{...await this.getTransactData(s,a),chain:s.chain}}}async getTransactData(t,e){let{chain:s,extrinsic:n}=t,a=await n.build(e),r=await B.create(s),i=a.getTx(r.client),o=e.source.chain,c=e.sender,l=Tt.acc.getMultilocationDerivatedAccount(o.parachainId,c,s.parachainId===0?0:1,s.usesH160Acc),m=await i.getPaymentInfo(l),d=await i.getEncodedData(),[g,p]=await Promise.all([this.getTransactFee(t),this.getTransactFeeBalance(t,e)]);return{call:d,chain:s,fee:g,feeBalance:p,weight:{refTime:m.weight.ref_time,proofSize:m.weight.proof_size}}}async getTransactFee(t){let{fee:e}=t,s=await this.getDecimals(e.asset),n=Tt.big.toBigInt(e.amount,s);return H.AssetAmount.fromAsset(e.asset,{amount:n,decimals:s})}async getTransactFeeBalance(t,e){let{chain:s}=this.config,{fee:n}=t,a=n.balance.build({address:e.sender,asset:n.asset,chain:s});return this.adapter.getBalance(n.asset,a)}};var Et=class extends ot{constructor(t,e){super(t,e)}};var hn=require("@galacticcouncil/xc-core"),ct=class{ctx;constructor(t){this.ctx=t}get asset(){let{source:t}=this.ctx;return t.balance}get dex(){let{source:t}=this.ctx;return t.chain.dex}get destFee(){let{source:t,transact:e}=this.ctx;return e?e.fee:t.destinationFee}get destFeeBalance(){let{source:t,transact:e}=this.ctx;return e?e.feeBalance:t.destinationFeeBalance}get feeBalance(){let{source:t}=this.ctx;return t.feeBalance}async getSwap(t){let{asset:e,decimals:s}=await this.dex.chain.getCurrency(),{amount:n}=await this.dex.getQuote(e,t,t);return{aIn:t,aOut:hn.AssetAmount.fromAsset(e,{amount:n,decimals:s}),enabled:!0}}isSwapSupported(t){try{this.dex}catch{return!1}return!!(t&&t.swap)}async getDestinationSwap(t){let{amount:e,route:s}=await this.dex.getQuote(t,this.destFee,this.destFee),n=this.destFeeBalance.amount<this.destFee.amount,a=this.feeBalance.amount-t.amount>e*2n;return{aIn:t.copyWith({amount:e}),aOut:this.destFee,enabled:n&&a,route:s}}isDestinationSwapSupported(t){try{this.dex}catch{return!1}let e=!t.isSame(this.destFee),s=this.asset.isSame(this.destFee);return e&&!s}};var{EvmAddr:jn}=lt.addr,ne=class{config;validations;constructor({configService:t,transferValidations:e}){this.config=t,this.validations=e||[]}async transfer(t,e,s,n,a){let r=(0,lt.ConfigBuilder)(this.config).assets().asset(t).source(s).destination(a).build();return this.getTransferData(r,e,n)}async remoteXcm(t,e,s,n,a={}){let r=this.config.getChain(e),i=this.config.getChain(s);if(!(r.isSubstrate()&&i.isSubstrate()))throw Error("RemoteXcm is supported only between parachains");let[c,l]=await Promise.all([B.create(r),B.create(i)]),m=new vt(c,l),d=ut.acc.getMultilocationDerivatedAccount(r.parachainId,t,1,i.usesH160Acc),g=await l.getAsset(),p=await this.transfer(g,t,e,d,s);return m.remoteExec(t,d,n,f=>{let h=f.toDecimal();return p.buildCall(h)},a)}async getTransferData(t,e,s){let n=t.origin,a=t.reverse,r=new K(n.chain),i=new K(a.chain),o=new Bt(r,n),c=new Et(i,a),l=new lt.TransferValidator(...this.validations),[m,d,g,p,f,h,T]=await Promise.all([o.getBalance(e),o.getFeeBalance(e),o.getDestinationFee(),o.getDestinationFeeBalance(e),o.getMin(),c.getBalance(s),c.getMin()]),{source:b,destination:y}=n.route,I=g.fee.copyWith(y.fee.asset),k=g.feeBreakdown,mt=b.asset.isEqual(I)&&I.amount>10n?I.amount+1n:10n,A={address:s,amount:mt,asset:b.asset,destination:{balance:h,chain:a.chain,fee:I,feeBreakdown:k},sender:e,source:{balance:m,chain:n.chain,fee:d.copyWith({amount:0n}),feeBalance:d,destinationFee:g.fee,destinationFeeBalance:p}};A.transact=await o.getTransact(A);let F=new ct(A),w=await o.getFee(A),V;F.isSwapSupported(b.fee)&&(V=await F.getSwap(w),A.source.feeSwap=V);let O;F.isDestinationSwapSupported(w)&&(O=await F.getDestinationSwap(w),A.source.destinationFeeSwap=O),(V||O)&&(w=await o.getFee(A),w=w.padByPct(5n));let Ft=await c.getEd(),ae=dn(h,I,T,Ft),x=await o.getEd(),Dt=mn(m,w,f,x);A.amount=0n,A.source.fee=w;let dt={source:{balance:m,destinationFee:g.fee,destinationFeeBalance:p,destinationFeeSwap:O,fee:w,feeBalance:d,feeSwap:V,max:Dt,min:m.copyWith({amount:ae.amount})},destination:{balance:h,fee:I},async buildCall($){let S=Object.assign({},A);return S.amount=ut.big.toBigInt($,m.decimals),S.transact=await o.getTransact(S),o.getCall(S)},async estimateFee($){let S=Object.assign({},A);return S.amount=ut.big.toBigInt($,m.decimals),S.transact=await o.getTransact(S),o.getFee(S)},async estimateDestinationFee($){let S=ut.big.toBigInt($,m.decimals),{fee:Q,feeBreakdown:Sn}=await o.getDestinationFee(S);return A.destination.fee=Q,A.destination.feeBreakdown=Sn,A.source.destinationFee=Q,dt.destination.fee=Q,dt.source.destinationFee=Q,Q},async validate($){let S=Object.assign({},A),Q=$||w.amount;return S.source.fee=w.copyWith({amount:Q}),l.validate(S)}};return dt}async subscribeBalance(t,e,s){let n=this.config.getChainRoutes(e),a=new K(n.chain),r=n.getUniqueRoutes().map(async({source:c})=>{let{asset:l,balance:m}=c,d=n.chain.getBalanceAssetId(l),g=jn.isValid(d.toString())?await z(t,n.chain):t,p=m.build({address:g,asset:l,chain:n.chain});return a.subscribeBalance(l,p)}),i=await Promise.all(r);return(0,se.combineLatest)(i).pipe((0,se.debounceTime)(500)).subscribe(s)}};var yn=require("@galacticcouncil/xc-core");function Cn(u){let t=(0,yn.ConfigBuilder)(u.config).assets();return{assets:t,withAsset(e){let s=t.asset(e);return{sources:s,withSource(n){let a=s.source(n);return{destinations:a,withDestination(r){let{routes:i,destinationAssets:o,isAssetSelect:c,isTagSelect:l,build:m}=a.destination(r);return{routes:i,destinationAssets:o,isAssetSelect:c,isTagSelect:l,build({srcAddress:d,dstAddress:g,dstAsset:p,tag:f}){let h=m(p,f);return u.getTransferData(h,d,g)}}}}}}}}}var An=require("@galacticcouncil/xc-core"),Kn="https://api.wormholescan.io",It=class{_baseUrl;constructor(t){this._baseUrl=t||Kn}buildApi(t,e){return[this._baseUrl,t,"?"].join("")+new URLSearchParams(e).toString()}async getVaaBytes(t){let e=this.buildApi("/v1/signed_vaa/"+t,{});return await(await fetch(e)).json()}async getVaa(t){let e=this.buildApi("/api/v1/vaas/"+t,{});return(await(await fetch(e)).json()).data}async getVaaByTxHash(t){let e=this.buildApi("/api/v1/vaas/",{txHash:t}),n=await(await fetch(e)).json();if(n.data.length>0)return n.data[0];throw Error("Can't find VAA for given txHash: "+t)}async getOperations(t){let e=this.buildApi("/api/v1/operations/",t);return(await(await fetch(e)).json()).operations}async getOperation(t){let e=this.buildApi("/api/v1/operations/"+t,{});return await(await fetch(e)).json()}isMrlTransfer(t){let{payloadType:e,toAddress:s,toChain:n}=t,a="0x"+s.substring(26);return e===3&&n===16&&a===An.Precompile.Bridge}};var bn=require("@galacticcouncil/common"),v=require("@galacticcouncil/xc-core"),wn=require("@wormhole-foundation/sdk-base"),vn=require("@wormhole-foundation/sdk-connect"),xn=require("@wormhole-foundation/sdk-definitions");var ve=(s=>(s[s.WaitingForVaa=0]="WaitingForVaa",s[s.VaaEmitted=1]="VaaEmitted",s[s.Completed=2]="Completed",s))(ve||{});var zn=300*1e3,xe=class{parachainId;config;whScan;constructor(t,e){this.config=t,this.parachainId=e,this.whScan=new It}get chains(){let t=this.config.chains.values();return Array.from(t)}get filters(){let t=new Date,e=new Date;e.setDate(t.getDate()-6);let s=t.toISOString();return{page:"0",pageSize:"50",includeEndDate:"true",from:e.toISOString(),to:s}}async getWithdraws(t){let e=bn.acc.getMultilocationDerivatedAccount(this.parachainId,t,1,!0),n=(await this.whScan.getOperations({...this.filters,address:e})).map(async a=>{let{content:r}=a,{payload:i,standarizedProperties:o}=r,c=this.getStatus(a),l=this.chains.find(f=>f instanceof v.Parachain&&f.parachainId===this.parachainId),{toAddress:m,tokenAddress:d}=o,g=this.chains.find(f=>v.Wormhole.isKnown(f)&&v.Wormhole.fromChain(f).getWormholeId()===i.tokenChain),p;if(c===1&&a.vaa){let{timestamp:f}=this.getVaaHeader(a.vaa.raw),h=a.vaa.raw;if(this.isStuck(f))switch(g.getType()){case v.ChainType.EvmChain:let T=new gt(g);p=async y=>T.redeem(y,h);break;case v.ChainType.SolanaChain:let b=new At(g);p=async y=>b.redeem(y,h);break}}return{asset:d,assetSymbol:a.data.symbol,amount:a.data.tokenAmount,from:t,fromChain:l,to:m,toChain:g,status:c,redeem:p,operation:a}});return Promise.all(n)}async getDeposits(t,e="hydration"){let s=await this.whScan.getOperations({...this.filters,address:v.Precompile.Bridge,pageSize:"100"}),n=this.config.chains.get(e);if(!n)return[];let a=n,i=(await v.mrl.createPayload(a,t)).toHex(),o=s.filter(c=>{let{content:l}=c,{payload:m}=l;return m.payloadType===3&&m.toChain===16&&"0x"+m.payload===i}).map(async c=>{let{content:l,sourceChain:m}=c,{payload:d,standarizedProperties:g}=l,p=this.getStatus(c),{tokenAddress:f}=g,h=this.chains.find(y=>v.Wormhole.isKnown(y)&&v.Wormhole.fromChain(y).getWormholeId()===d.tokenChain),T=this.chains.find(y=>v.Wormhole.isKnown(y)&&v.Wormhole.fromChain(y).getWormholeId()===d.toChain),b;if(p===1&&c.vaa){let{timestamp:y}=this.getVaaHeader(c.vaa.raw),I=c.vaa.raw;if(this.isStuck(y)){let k=new bt(T);b=async L=>k.redeemMrlViaXcm(L,I)}}return{asset:f,assetSymbol:c.data.symbol,amount:c.data.tokenAmount,from:m.from,fromChain:h,to:t,toChain:n,status:p,redeem:b,operation:c}});return Promise.all(o)}isStuck(t){return Date.now()>=t*1e3+zn}getVaaHeader(t){let e=wn.encoding.b64.decode(t),s=(0,xn.deserialize)("Uint8Array",e);return{timestamp:s.timestamp,emitterChain:s.emitterChain,emitterAddress:s.emitterAddress.toString(),sequence:s.sequence,payload:s.payload,hash:s.hash,id:(0,vn.keccak256)(s.hash)}}getStatus(t){return t.vaa?t.targetChain&&t.targetChain.status==="completed"?2:1:0}};0&&(module.exports={DISPATCH_ADDRESS,EvmClaim,EvmPlatform,EvmSigner,FeeSwap,PlatformAdapter,SolanaClaim,SolanaLilJit,SolanaPlatform,SolanaSigner,SubstrateClaim,SubstrateExec,SubstratePlatform,SubstrateService,SubstrateSigner,SuiClaim,SuiPlatform,SuiSigner,TransferBuilder,Wallet,WhStatus,WormholeScan,WormholeTransfer,chunkBySize,deserializeV0,ixToHuman,serializeV0});
|
|
1
|
+
"use strict";var sn=Object.create;var vt=Object.defineProperty;var an=Object.getOwnPropertyDescriptor;var rn=Object.getOwnPropertyNames;var on=Object.getPrototypeOf,cn=Object.prototype.hasOwnProperty;var un=(o,t)=>{for(var e in t)vt(o,e,{get:t[e],enumerable:!0})},re=(o,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of rn(t))!cn.call(o,n)&&n!==e&&vt(o,n,{get:()=>t[n],enumerable:!(s=an(t,n))||s.enumerable});return o};var mn=(o,t,e)=>(e=o!=null?sn(on(o)):{},re(t||!o||!o.__esModule?vt(e,"default",{value:o,enumerable:!0}):e,o)),ln=o=>re(vt({},"__esModule",{value:!0}),o);var An={};un(An,{DISPATCH_ADDRESS:()=>Ut,EvmClaim:()=>st,EvmPlatform:()=>rt,EvmSigner:()=>zt,FeeSwap:()=>et,PlatformAdapter:()=>j,SolanaClaim:()=>ut,SolanaLilJit:()=>H,SolanaPlatform:()=>ot,SolanaSigner:()=>Gt,SubstrateClaim:()=>mt,SubstrateExec:()=>dt,SubstratePlatform:()=>pt,SubstrateService:()=>E,SubstrateSigner:()=>Yt,SuiClaim:()=>te,SuiPlatform:()=>ft,SuiSigner:()=>ee,TransferBuilder:()=>qe,Wallet:()=>Vt,WhStatus:()=>se,WormholeScan:()=>xt,WormholeTransfer:()=>ae,chunkBySize:()=>jt,deserializeV0:()=>pn,ixToHuman:()=>_,serializeV0:()=>L});module.exports=ln(An);var nt=require("@galacticcouncil/common"),Ot=require("@galacticcouncil/xc-core");var Q=require("@galacticcouncil/xc-core");var St=require("@galacticcouncil/xc-core"),ie=require("viem"),Kt=require("@wormhole-foundation/sdk-base"),st=class{#t;constructor(t){this.#t=t}redeem(t,e){let s=St.Wormhole.fromChain(this.#t),n=Kt.encoding.b64.decode(e),a=Kt.encoding.hex.encode(n),r=St.Abi.TokenBridge,c=(0,ie.encodeFunctionData)({abi:r,functionName:"completeTransfer",args:["0x"+a]});return{abi:JSON.stringify(r),data:c,from:t,to:s.getTokenBridge()}}};var K=require("@galacticcouncil/xc-core");var Tt=require("viem"),Pt=class{client;config;constructor(t,e){this.validateClient(t),this.client=t,this.config=e}validateClient(t){if(!t)throw new Error("No EVM client found")}get abi(){return this.config.abi}get asset(){let t=this.config.args,[e]=t;return e}get calldata(){return this.config.encodeFunctionData()}async estimateGas(t){let{address:e,args:s,value:n,func:a}=this.config;return await this.client.getProvider().estimateContractGas({address:e,abi:this.abi,functionName:a,args:s,value:n,account:t})}async estimateFee(t,e){if(e===0n)return 0n;try{let s=await this.estimateGas(t),n=await this.getGasPrice();return s*n}catch(s){return s instanceof Tt.ContractFunctionExecutionError?console.log(`Can't estimate fees!
|
|
2
|
+
`,s.message):console.log(s),0n}}async getGasPrice(){return this.client.getProvider().getGasPrice()}async getNonce(t){return this.client.getProvider().getTransactionCount({address:t})}async simulateCall(t){let{address:e,args:s,value:n,func:a}=this.config,r=this.client.getProvider(),c=await this.getNonce(t);try{let{results:m}=await r.simulateCalls({account:t,calls:[{to:e,abi:this.abi,functionName:a,args:s,value:n}],stateOverrides:[{address:t,nonce:c}]}),[i]=m;return i}catch(m){return console.log(`Can't simulate call!
|
|
3
|
+
`,m.details),{error:m}}}decodeEvents(t){let e=[];return t&&t.forEach(s=>{try{let{eventName:n,args:a}=(0,Tt.decodeEventLog)({abi:this.abi,data:s.data,topics:s.topics});e.push({eventName:n,args:a})}catch{}}),e}};var at=class{static get(t,e){return new Pt(t,e)}};var oe=require("@galacticcouncil/xc-core"),ce=require("viem");function Ht(o){return o.module==="Snowbridge"&&o.func==="v2_sendMessage"}function ue(o){if(!Ht(o))return;let t=o.args[1];if(!t||t.length===0)return;let[e,s]=(0,ce.decodeAbiParameters)([{type:"uint8"},{type:"address"},{type:"uint128"}],t[0]);return s}function me(o){let t=o.module==="Snowbridge"&&o.func==="v2_sendMessage"&&Array.isArray(o.args[1])&&o.args[1].length===0,e=o.module==="Snowbridge"&&o.func==="sendToken"&&o.args[0]==="0x0000000000000000000000000000000000000000";return o.module==="TokenBridge"&&["wrapAndTransferETHWithPayload","wrapAndTransferETH"].includes(o.func)||t||e}function le(o){return Object.entries(oe.Precompile).map(([e,s])=>s).includes(o.address)}var rt=class{#t;constructor(t){this.#t=t.evmClient}async buildCall(t,e,s,n){let a=at.get(this.#t,n),{abi:r,asset:c,calldata:m}=a,i={abi:JSON.stringify(r),data:m,from:t,to:n.address,type:K.CallType.Evm,value:n.value,dryRun:async()=>{let{error:p,logs:f}=await a.simulateCall(t),C=a.decodeEvents(f);return{call:n.module+"."+n.func,error:p?.shortMessage,events:C}}};if(le(n)||me(n))return i;let l=Ht(n)?ue(n):c,u=new K.Erc20Client(this.#t,l),d=await u.allowance(t,n.address);if(d>=e)return i;let g=u.approve(n.address,e);return{abi:JSON.stringify(K.Abi.Erc20),allowance:d,data:g,from:t,to:l,type:K.CallType.Evm,dryRun:()=>{}}}async estimateFee(t,e,s,n){let r=await at.get(this.#t,n).estimateFee(t,e);return s.copyWith({amount:r})}};var de=require("@galacticcouncil/xc-core"),ge=require("@galacticcouncil/common"),pe=require("polkadot-api"),Ut="0x0000000000000000000000000000000000000401",{H160:dn}=ge.h160,zt=class{#t;#e;#n;constructor(t,e){this.#t=t,this.#e=t.evmClient,this.#n=e}async signAndSend(t,e){let s=dn.fromAny(t.from),n=this.#e.getProvider(),a=!1;if(this.#t instanceof de.EvmParachain)try{let c=this.#t.client,m=pe.Binary.fromHex(t.data);await c.getUnsafeApi().txFromCallData(m),a=!0}catch{}let r;if(a){let[c,m]=await Promise.all([n.estimateGas({account:s,data:t.data,to:Ut}),n.getGasPrice()]),i=m+m/100n*10n;r=await this.#n.sendTransaction({account:s,chain:this.#e.chain,data:t.data,maxPriorityFeePerGas:i,maxFeePerGas:i,gas:c*11n/10n,to:Ut})}else{let{data:c,to:m,value:i}=t,[l,u]=await Promise.all([n.estimateGas({account:s,data:c,to:m,value:i}),n.getGasPrice()]),d=u+u*5n/100n,g=l+l*30n/100n;r=await this.#n.sendTransaction({account:s,chain:this.#e.chain,data:c,to:m,value:i,gas:g,maxFeePerGas:d,maxPriorityFeePerGas:d})}e.onTransactionSend(r),n.waitForTransactionReceipt({hash:r}).then(c=>e.onTransactionReceipt(c)).catch(c=>e.onError(c))}};var xe=require("@galacticcouncil/xc-core"),be=require("buffer");var F=require("@solana/web3.js"),fe=.5,he=2,ye=1,Ce=1e6,gn=25e4,Bt=class{connection;config;constructor(t,e){this.validateConnection(t),this.connection=t,this.config=e}validateConnection(t){if(!t)throw new Error("No connection found")}async getPriorityMessage(t){let{instructions:e}=this.config,s=await this.getV0Message(t,e),n=await this.createPriorityFeeInstructions(s);return this.getV0Message(t,[...e,...n])}async estimateFee(t,e){if(e===0n)return 0n;let{instructions:s}=this.config,n=await this.getV0Message(t,s),a=await this.determineComputeBudget(n);return BigInt(a)}async getV0Message(t,e){let s=new F.PublicKey(t),{blockhash:n}=await this.connection.getLatestBlockhash("finalized");return new F.TransactionMessage({payerKey:s,recentBlockhash:n,instructions:e}).compileToV0Message()}async createPriorityFeeInstructions(t,e=fe,s=he,n=ye,a=Ce){let[r,c]=await Promise.all([this.determineComputeBudget(t),this.determinePriorityFee(t,e,s,n,a)]);return[F.ComputeBudgetProgram.setComputeUnitLimit({units:r}),F.ComputeBudgetProgram.setComputeUnitPrice({microLamports:c})]}async simulateTransaction(t,e){let s=new F.VersionedTransaction(e);return(await this.connection.simulateTransaction(s,{accounts:{encoding:"base64",addresses:[t]}})).value}async determineComputeBudget(t){let e=new F.VersionedTransaction(t),s=await this.connection.simulateTransaction(e),{err:n,unitsConsumed:a}=s.value;return a&&!n?Math.round(a*1.2):gn}async determinePriorityFee(t,e=fe,s=he,n=ye,a=Ce){let r=n,c=await this.getTxAccounts(t),m=await this.connection.getRecentPrioritizationFees({lockedWritableAccounts:c});if(m){let i=m.map(u=>u.prioritizationFee).filter(u=>u>0).sort((u,d)=>u-d),l=Math.ceil(i.length*e);if(i.length>l){let d=i[l]*s;r=Math.max(r,d)}}return Math.min(Math.max(r,n),a)}async getTxAccounts(t){let e=(await Promise.all(t.addressTableLookups.map(n=>this.connection.getAddressLookupTable(n.accountKey)))).map(n=>n.value).filter(n=>n!==null),s=t.getAccountKeys({addressLookupTableAccounts:e??void 0});return t.compiledInstructions.flatMap(n=>n.accountKeyIndexes).map(n=>t.isAccountWritable(n)?s.get(n):null).filter(n=>n!==null)}};var it=class{static get(t,e){return new Bt(t,e)}};var Ae=require("@solana/web3.js");function _(o){return o.map(t=>({program:t.programId.toBase58(),data:t.data.toString("hex"),keys:t.keys.map(e=>e.pubkey.toBase58())}))}function jt(o,t=1e3){let e=[],s=[],n=0;for(let a of o){let r=a.data?.length??0;s.length&&n+r>t&&(e.push(s),s=[],n=0),s.push(a),n+=r}return s.length&&e.push(s),e}function L(o){let t=o.serialize();return Buffer.from(t).toString("hex")}function pn(o){let t=Buffer.from(o,"hex"),e=Uint8Array.from(t);return Ae.MessageV0.deserialize(e)}var ot=class{#t;constructor(t){this.#t=t.connection}async buildCall(t,e,s,n){let a=it.get(this.#t,n),r=await a.getPriorityMessage(t),c=r.serialize(),m=be.Buffer.from(c).toString("hex");return{from:t,data:m,ix:_(n.instructions),signers:n.signers,type:xe.CallType.Solana,dryRun:async()=>{let{err:i,logs:l}=await a.simulateTransaction(t,r);return{call:n.module+"."+n.func,error:i,events:l}}}}async estimateFee(t,e,s,n){let a=it.get(this.#t,n),r=await a.estimateFee(t,e),c=await a.getPriorityMessage(t),{accounts:m}=await a.simulateTransaction(t,c),l=(m&&m[0])?.lamports;if(l){let u=n.module==="TokenBridge"&&n.func==="TransferNativeWithPayload";return s.copyWith({amount:s.amount-BigInt(l)-(u?e:0n)+n.rentReserve})}return s.copyWith({amount:r+n.rentReserve})}};var U=require("@galacticcouncil/xc-core"),T=require("@solana/web3.js"),y=require("@solana/spl-token"),we=require("@wormhole-foundation/sdk-solana"),Lt=require("@wormhole-foundation/sdk-solana-core"),ve=require("@wormhole-foundation/sdk-base"),$t=require("@wormhole-foundation/sdk-definitions"),ct=require("@wormhole-foundation/sdk-solana-tokenbridge");var H=class{#t;constructor(t){this.#t=t.connection}async sendBundle(t){let{result:e}=await this.#t._rpcRequest("sendBundle",[t]);return e}async simulateBundle(t){return(await this.#t._rpcRequest("simulateBundle",[[t]])).result}async getInflightBundleStatuses(t){let{result:e}=await this.#t._rpcRequest("getInflightBundleStatuses",[t]);return e}async getRegion(){let{result:t}=await this.#t._rpcRequest("getRegions",[]);return t}async getTipAccount(){let{result:t}=await this.#t._rpcRequest("getTipAccounts",[]);return t}};var ut=class{#t;#e;#n;constructor(t){this.#t=t,this.#e=t.connection,this.#n=new H(t)}async redeem(t,e,s){let n=U.Wormhole.fromChain(this.#t),a=ve.encoding.b64.decode(e),r=(0,$t.deserialize)("TokenBridge:Transfer",a),c=(0,$t.deserialize)("Uint8Array",a),m=this.derivePostedVaaKey(n.getCoreBridge(),Buffer.from(r.hash)),i=new T.PublicKey(t),l=s?new T.PublicKey(s):i,u=i.equals(l),d=[];if(!await this.#e.getAccountInfo(m)){let h=T.Keypair.generate(),O=await Lt.utils.createVerifySignaturesInstructions(this.#t.connection,n.getCoreBridge(),i,c,h.publicKey),B=jt(O,1e3);for(let A=0;A<B.length;A++){let I=B[A],v=await this.getV0Message(i,I),k=L(v);d.push({from:t,data:k,ix:_(I),signers:[h],type:U.CallType.Solana})}let D=Lt.utils.createPostVaaInstruction(this.#e,n.getCoreBridge(),i,c,h.publicKey),bt=await this.getV0Message(i,[D]),R=L(bt);d.push({from:t,data:R,ix:_([D]),type:U.CallType.Solana})}let p=r.payload.token.chain==="Solana",f=new T.PublicKey(r.payload.token.address.toUint8Array()),C=p&&f.equals(y.NATIVE_MINT),w=await this.#n.getTipAccount(),x=T.SystemProgram.transfer({fromPubkey:i,toPubkey:new T.PublicKey(w[0]),lamports:1e3});if(C&&u){let h=await this.redeemAndUnwrap(n,i,r,x);d.push(h)}else{let h=await this.redeemToken(n,i,l,f,p,r,x);d.push(h)}return d}async redeemToken(t,e,s,n,a,r,c){let i=(a?ct.createCompleteTransferNativeInstruction:ct.createCompleteTransferWrappedInstruction)(this.#e,t.getTokenBridge(),t.getCoreBridge(),e,r),l=(0,y.getAssociatedTokenAddressSync)(n,s),u=(0,y.createAssociatedTokenAccountIdempotentInstruction)(e,l,s,n),d=await this.getV0Message(e,[u,i,c]),g=L(d);return{from:e.toBase58(),data:g,ix:_([u,i]),type:U.CallType.Solana}}async redeemAndUnwrap(t,e,s,n){let a=new T.PublicKey(s.payload.to.address.toUint8Array()),r=await(0,y.getMint)(this.#e,y.NATIVE_MINT),c=s.payload.token.amount*BigInt(Math.pow(10,r.decimals-8)),m=await(0,y.getMinimumBalanceForRentExemptAccount)(this.#e),i=T.Keypair.generate(),l=(0,y.createAssociatedTokenAccountIdempotentInstruction)(e,a,e,y.NATIVE_MINT),u=(0,ct.createCompleteTransferNativeInstruction)(this.#e,t.getTokenBridge(),t.getCoreBridge(),e,s),d=T.SystemProgram.createAccount({fromPubkey:e,newAccountPubkey:i.publicKey,lamports:m,space:y.ACCOUNT_SIZE,programId:y.TOKEN_PROGRAM_ID}),g=(0,y.createInitializeAccountInstruction)(i.publicKey,y.NATIVE_MINT,e),p=(0,y.createTransferInstruction)(a,i.publicKey,e,c),f=(0,y.createCloseAccountInstruction)(i.publicKey,e,e),C=[l,u,d,g,p,f,n],w=await this.getV0Message(e,C),x=L(w);return{from:e.toBase58(),data:x,ix:_(C),signers:[i],type:U.CallType.Solana}}derivePostedVaaKey(t,e){return we.utils.deriveAddress([Buffer.from("PostedVAA"),e],t)}async getV0Message(t,e){let{blockhash:s}=await this.#e.getLatestBlockhash("finalized");return new T.TransactionMessage({payerKey:t,recentBlockhash:s,instructions:e}).compileToV0Message()}};var z=require("@solana/web3.js"),Et=require("buffer");var Gt=class{#t;#e;#n;constructor(t,e){this.#t=t,this.#e=e,this.#n=new H(t)}async signAndSend(t,e){let{data:s,signers:n}=t,a=this.toVersioned(s,n);try{if(this.#e instanceof z.Keypair){a.sign([this.#e]);let i=await this.#t.connection.sendTransaction(a);e.onTransactionSend(i);let l=await this.#t.connection.getSignatureStatus(i);e.onStatus?.(l);return}let r=this.#e;await r.connect(),n&&a.sign(n);let{signature:c}=await r.signAndSendTransaction(a);e.onTransactionSend(c);let m=await this.#t.connection.getSignatureStatus(c);e.onStatus?.(m)}catch(r){e.onError(r)}}async signAndSendAll(t,e){let s=t.map(n=>{let{data:a,signers:r}=n;return this.toVersioned(a,r)});try{let n;if(this.#e instanceof z.Keypair)s.forEach(m=>m.sign([this.#e])),n=s.map(m=>Et.Buffer.from(m.serialize()).toString("base64"));else{let m=this.#e;await m.connect(),n=(await m.signAllTransactions(s)).map(l=>Et.Buffer.from(l.serialize()).toString("base64"))}let a=await this.#n.simulateBundle(n);if(a.value.summary!=="succeeded")throw new Error("Bundle simulation failed! "+JSON.stringify(a,null,2));let r=await this.#n.sendBundle(n);e.onTransactionSend(r);let c=await this.#n.getInflightBundleStatuses([r]);e.onBundleStatus?.(c.value)}catch(n){e.onError(n)}}toVersioned(t,e){let s=Et.Buffer.from(t,"hex"),n=Uint8Array.from(s),a=z.MessageV0.deserialize(n),r=new z.VersionedTransaction(a);return e&&r.sign(e),r}};var V=require("@galacticcouncil/xc-core"),Xt=require("@wormhole-foundation/sdk-base"),Se=require("viem"),Jt=require("polkadot-api"),mt=class{#t;constructor(t){this.#t=t,V.Wormhole.fromChain(this.#t)}redeemMrl(t,e){let s=Xt.encoding.b64.decode(e),n=Xt.encoding.hex.encode(s),a=V.Abi.Gmp,r=(0,Se.encodeFunctionData)({abi:a,functionName:"wormholeTransferERC20",args:["0x"+n]});return{abi:JSON.stringify(a),data:r,from:t,to:V.Precompile.Bridge}}async redeemMrlViaXcm(t,e){let n=this.#t.client.getUnsafeApi(),a=this.redeemMrl(t,e),c=await n.tx.EthereumXcm.transact({xcm_transaction:{type:"V2",value:{gas_limit:[5000000n,0n,0n,0n],action:{type:"Call",value:a.to},value:[0n,0n,0n,0n],input:Jt.Binary.fromHex(a.data),access_list:void 0}}}).getEncodedData();return{data:Jt.Binary.toHex(c),from:t,type:V.CallType.Substrate,dryRun:async()=>{},txOptions:void 0}}};var It=require("@galacticcouncil/xc-core"),lt=require("polkadot-api");var Pe=require("@galacticcouncil/common");async function Te(o,t,e){let s=await e.getDecimals(),n=e.chain.getAssetDecimals(t)??s,a=e.chain.usesChainDecimals?s:n;return{amount:Pe.big.convertDecimals(o,a,n),decimals:n}}var Be=require("@galacticcouncil/common"),Ee=o=>{let t=[];for(let e of o)if(["PolkadotXcm"].includes(e.type)&&e.value.type==="FeesPaid"){let n=e.value.value.fees;for(let a of n)if(a.fun.type==="Fungible"){let r=BigInt(a.fun.value);t.push(r)}}return t.reduce((e,s)=>e+s,0n)},$=o=>{let t=o.value.error;return t.type==="Module"?Be.enums.enumPath(t.value):JSON.stringify(t.value)};var Ft=require("@galacticcouncil/common");function fn(o){return{parents:0,interior:{type:"X1",value:o.startsWith("0x")?Ft.xcm.toAccountKey20(o):Ft.xcm.toAccountId32(o)}}}function Fe(o){return{type:"V4",value:{parents:1,interior:{type:"X1",value:{type:"Parachain",value:o.parachainId}}}}}var hn=(o,t)=>({id:Ft.xcm.transform(o),fun:{type:"Fungible",value:t}}),Ie=(o,t,e,s,n,a)=>{console.log(a);let r=fn(o),c=hn(t,e.amount);return{type:"V4",value:[{type:"WithdrawAsset",value:[c]},{type:"BuyExecution",value:{fees:c,weight_limit:{type:"Unlimited"}}},{type:"Transact",value:{origin_kind:{type:"SovereignAccount"},require_weight_at_most:{ref_time:s,proof_size:n},call:a}},{type:"RefundSurplus",value:void 0},{type:"DepositAsset",value:{assets:{type:"Wild",value:{type:"AllCounted",value:1}},beneficiary:r}}]}};var dt=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}async remoteExec(t,e,s,n,a={}){let r=this.#t.api,c=await this.#t.getAsset(),m=this.#e.api,i=this.#e.chain,l=await i.getCurrency(),u=l.asset,d=l.decimals,g=i.getAssetXcmLocation(u),p=lt.Binary.fromHex(s.data),C=await(await m.txFromCallData(p)).getPaymentInfo(e),w=BigInt(C.partial_fee)*120n/100n,x=It.AssetAmount.fromAsset(u,{amount:w,decimals:d}),h=C.weight.ref_time,O=C.weight.proof_size,B=Fe(i),D=Ie(e,g,x,h,O,p),bt=r.tx.PolkadotXcm.send({dest:B,message:D}),R=[];try{let S=await this.#t.chain.dex.getCalldata(t,a.srcFeeAsset||c,u,x,10),wt=lt.Binary.fromHex(S),Wt=await r.txFromCallData(wt);R.push(Wt)}catch{}let A=await n(x),I=lt.Binary.fromHex(A.data),v=await r.txFromCallData(I);R.push(v),R.push(bt);let k=R.map(S=>S.decodedCall),M=r.tx.Utility.batch_all({calls:k}),Mt=await M.getEncodedData();return{from:t,data:lt.Binary.toHex(Mt),type:It.CallType.Substrate,dryRun:this.#t.isDryRunSupported()?async()=>{try{let S=await this.#t.dryRun(t,M);return{call:"polkadotXcm.send",error:S.execution_result&&S.execution_result.success?void 0:$(S.execution_result),events:S.emitted_events||[],xcm:S.forwarded_xcms||[]}}catch(S){return{call:"polkadotXcm.send",error:S instanceof Error?S.message:"unknown"}}}:()=>{}}}};var X=require("@galacticcouncil/xc-core"),Re=require("polkadot-api");var G=require("@galacticcouncil/xc-core"),Dt=require("@galacticcouncil/common"),Rt=require("@polkadot-api/substrate-bindings"),gt=require("@polkadot-api/utils"),qt=require("polkadot-api");var{Ss58Addr:De}=G.addr,E=class o{chain;_currency;constructor(t){this.chain=t}static async create(t){return new o(t)}get client(){return this.chain.client}get api(){return this.client.getUnsafeApi()}async getCurrency(){return this._currency||(this._currency=this.chain.getCurrency()),this._currency}async getAsset(){return(await this.getCurrency()).asset}async getDecimals(){return(await this.getCurrency()).decimals}isDryRunSupported(){return this.api.apis?.DryRunApi!==void 0}async buildMessageId(t,e,s,n){let a=await this.client._request("system_accountNextIndex",[t]),r=Rt.u32.enc(a),c=l=>new TextEncoder().encode(l),m=new Uint8Array([...c(this.chain.parachainId.toString()),...(0,gt.fromHex)(t.startsWith("0x")?t.slice(2):t),...r,...(0,gt.fromHex)(s.startsWith("0x")?s.slice(2):s),...c(n),...c(e.toString())]),i=(0,Rt.Blake2256)(m);return(0,gt.toHex)(i)}async dryRun(t,e){let s=(0,qt.Enum)("Signed",t),n=(0,qt.Enum)("system",s),a=await this.api.apis.DryRunApi.dry_run_call(n,e.decodedCall,4);if(!a.success)throw new Error("DryRun call failed");let r=a.value;if("type"in r&&"value"in r)throw new Error("DryRun call error: "+Dt.enums.enumPath(r.value));return r}async estimateNetworkFee(t,e){let s=e.getTx(this.client);try{let n=await s.getPaymentInfo(t);return BigInt(n.partial_fee)}catch{console.warn("Can't estimate network fee.")}return 0n}async estimateDeliveryFee(t,e){if(this.chain.usesDeliveryFee){let s=await this.estimateDeliveryFeeWith(t,e);try{let n=e.getTx(this.client),a=await this.dryRun(s,n);if(a.execution_result?.success)return Ee(a.emitted_events||[]);{let r=$(a.execution_result);console.warn(`Can't estimate delivery fee. Reason:
|
|
4
|
+
${r}`)}}catch{}}return 0n}async estimateDeliveryFeeWith(t,e){if(["PolkadotXcm"].includes(e.module)){let n=e.getTx(this.client).decodedCall.value.value,a="dest"in n?n.dest:void 0;if(!a)return t;let r=G.multiloc.findNestedKey(a,"interior"),c=G.multiloc.findParachain(a);if(G.multiloc.findGlobalConsensus(a))return t;if(c){let i=Dt.acc.getSovereignAccounts(c);return this.chain.parachainId===0?De.encodePubKey(i.relay):De.encodePubKey(i.generic)}if(r&&r.interior==="Here")return this.chain.treasury||t}return t}};var pt=class{#t;constructor(t){this.#t=E.create(t)}async useSignerFee(t){let e=await this.#t,s=await e.getAsset();return e.chain.usesSignerFee&&!s.isEqual(t)}async buildCall(t,e,s,n){let a=await this.#t,c=await this.useSignerFee(s)?{asset:new X.Asset(s)}:void 0,m=n.getTx(a.client),i=n.module+"."+n.func,l=await m.getEncodedData();return{from:t,data:Re.Binary.toHex(l),type:X.CallType.Substrate,txOptions:c,dryRun:a.isDryRunSupported()?async()=>{try{let u=n.getTx(a.client),d=await a.dryRun(t,u),g=d.execution_result&&d.execution_result.success?void 0:$(d.execution_result);return{call:i,error:g,events:d.emitted_events||[],xcm:d.forwarded_xcms||[]}}catch(u){return{call:i,error:u instanceof Error?u.message:"unknown"}}}:()=>{}}}async estimateFee(t,e,s,n){let a=await this.#t,r=await a.estimateNetworkFee(t,n),c=await a.estimateDeliveryFee(t,n),m=await this.exchangeFee(r+c,s),i=await Te(m,s,a);return s.copyWith(i)}async exchangeFee(t,e){let s=await this.#t,n=await s.getAsset(),a=await s.getDecimals();if(n.isEqual(e))return t;try{let r=s.chain.dex,c=X.AssetAmount.fromAsset(n,{amount:t,decimals:a});return(await r.getQuote(e,n,c,!0)).amount}catch{}return t}};var Qt=require("@galacticcouncil/xc-core"),J=require("polkadot-api"),Yt=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}signAndSend(t,e){let n=this.#t.client.getUnsafeApi(),a=J.Binary.fromHex(t.data),r={};t.txOptions?.asset&&(r={asset:this.getFeeAsset(t.txOptions.asset)}),n.txFromCallData(a).then(c=>{c.signSubmitAndWatch(this.#e,r).subscribe({next:m=>{m.type==="broadcasted"&&e.onTransactionSend(m.txHash),m.type==="finalized"&&e.onFinalized(m)},error:m=>{e.onError(m)}})})}getFeeAsset(t){let e=this.#t.getAssetXcmLocation(t);if(e){let s=Qt.multiloc.findPalletInstance(e),n=Qt.multiloc.findGeneralIndex(e);return{parents:0,interior:(0,J.Enum)("X2",[(0,J.Enum)("PalletInstance",Number(s)),(0,J.Enum)("GeneralIndex",BigInt(n))])}}throw new Error("Asset location not found")}};var _t=require("@galacticcouncil/xc-core"),_e=require("@mysten/sui/transactions"),Ve=require("@mysten/sui/utils"),Oe=require("@mysten/bcs"),q=require("@wormhole-foundation/sdk-connect"),Me=require("@wormhole-foundation/sdk-definitions"),Zt=require("@wormhole-foundation/sdk-sui"),We=require("@wormhole-foundation/sdk-sui-tokenbridge");var ke=require("@mysten/bcs");function kt(o,t={}){let e=o.inputs??[],s=o.commands??[],n=t.numbers??"string",a=t.decode32As??"address",r=l=>n==="bigint"?l:n==="number"?Number(l):l.toString(),c=l=>{let u=(0,ke.fromBase64)(l),d=g=>{let p=0n;for(let f=0;f<g;f++)p|=BigInt(u[f])<<8n*BigInt(f);return p};return u.length===1?{type:"pure",valueType:"u8",value:Number(u[0])}:u.length===2?{type:"pure",valueType:"u16",value:r(d(2))}:u.length===4?{type:"pure",valueType:"u32",value:Number(d(4))}:u.length===8?{type:"pure",valueType:"u64",value:r(d(8))}:u.length===32&&a==="address"?{type:"pure",valueType:"address",value:"0x"+[...u].map(p=>p.toString(16).padStart(2,"0")).join("")}:{type:"pure",valueType:"vector<u8>",value:Array.from(u)}},m=l=>{let u=e[l];if(!u)return{Input:l};if(u.Pure?.bytes)return c(u.Pure.bytes);let d=u.Object?.SharedObject;if(d)return{type:"object",objectType:"sharedObject",objectId:d.objectId,initialSharedVersion:String(d.initialSharedVersion),mutable:!!d.mutable};let g=u.Object?.ImmOrOwnedObject;return g?{type:"object",objectType:"immOrOwnedObject",objectId:g.objectId,version:String(g.version),digest:g.digest??void 0}:{Input:l}},i=l=>l?.GasCoin?"GasCoin":Array.isArray(l?.NestedResult)?l:typeof l?.Input=="number"?m(l.Input):l;return s.map(l=>{if(l.MoveCall){let u=l.MoveCall;return{MoveCall:{...u,arguments:(u.arguments??[]).map(i)}}}if(l.SplitCoins){let u=l.SplitCoins,d=u.coin?.GasCoin?"GasCoin":i(u.coin),g=(u.amounts??[]).map(i);return{SplitCoins:[d,g]}}if(l.MergeCoins){let u=l.MergeCoins;return{MergeCoins:{...u,destination:i(u.destination),sources:(u.sources??[]).map(i)}}}if(l.TransferObjects){let u=l.TransferObjects;return{TransferObjects:{...u,objects:(u.objects??[]).map(i),address:i(u.address)}}}return l})}var te=class{#t;constructor(t){this.#t=t}async redeem(t,e){let s=_t.Wormhole.fromChain(this.#t),n=this.#t.client,a=q.encoding.b64.decode(e),r=(0,Me.deserialize)("TokenBridge:Transfer",a),c=s.getCoreBridge(),m=s.getTokenBridge(),i=await(0,We.getTokenCoinType)(n,m,r.payload.token.address.toUint8Array(),(0,q.toChainId)(r.payload.token.chain));if(!i)throw new Error("Unable to fetch token coinType");let[l,u]=await Promise.all([(0,Zt.getPackageId)(n,c),(0,Zt.getPackageId)(n,m)]),d=new _e.Transaction;d.setSender(t);let[g]=d.moveCall({target:`${l}::vaa::parse_and_verify`,arguments:[d.object(c),d.pure.vector("u8",(0,q.serialize)(r)),d.object(Ve.SUI_CLOCK_OBJECT_ID)]}),[p]=d.moveCall({target:`${u}::vaa::verify_only_once`,arguments:[d.object(m),g]}),[f]=d.moveCall({target:`${u}::complete_transfer::authorize_transfer`,arguments:[d.object(m),p],typeArguments:[i]}),[C]=d.moveCall({target:`${u}::complete_transfer::redeem_relayer_payout`,arguments:[f],typeArguments:[i]});d.moveCall({target:`${u}::coin_utils::return_nonzero`,arguments:[C],typeArguments:[i]});let w=await d.build({client:n}),x=await d.toJSON(),h=kt(JSON.parse(x));return{from:t,commands:h,data:(0,Oe.toBase64)(w),type:_t.CallType.Sui}}};var Ne=require("@galacticcouncil/xc-core"),Ke=require("@mysten/bcs");var ft=class{#t;constructor(t){this.#t=t.client}async buildCall(t,e,s,n){let{transaction:a}=n;a.setSender(t);let r=await a.build({client:this.#t}),c=await a.toJSON(),m=kt(JSON.parse(c));return{from:t,commands:m,data:(0,Ke.toBase64)(r),type:Ne.CallType.Sui,dryRun:async()=>{let i=await this.#t.dryRunTransactionBlock({transactionBlock:r});return{call:n.module+"."+n.func,error:i.executionErrorSource}}}}async estimateFee(t,e,s,n){let{transaction:a}=n;a.setSender(t);let r=await a.build({client:this.#t}),m=(await this.#t.dryRunTransactionBlock({transactionBlock:r})).effects.gasUsed,i=BigInt(m.computationCost),l=BigInt(m.storageCost),u=i+l;return s.copyWith({amount:u})}};var He=require("@mysten/sui/keypairs/ed25519"),Ue=require("@mysten/sui/transactions"),ee=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}async signAndSend(t,e){let{from:s,data:n}=t,a=this.#t.client;try{if(this.#e instanceof He.Ed25519Keypair){let m=Ue.Transaction.from(n),i=await a.signAndExecuteTransaction({signer:this.#e,transaction:m,options:{showEffects:!0,showEvents:!0,showObjectChanges:!0,showBalanceChanges:!0}});e.onTransactionSend(i.digest);return}let r=await this.#e.signTransaction({transaction:n,address:s,networkID:"sui:mainnet"}),c=await a.executeTransactionBlock({transactionBlock:r.transaction,signature:r.signature,options:{showEffects:!0,showEvents:!0,showObjectChanges:!0,showBalanceChanges:!0}});e.onTransactionSend(c.digest)}catch(r){e.onError(r)}}};var j=class{platform={};constructor(t){switch(t.getType()){case Q.ChainType.EvmChain:this.registerEvm(t);break;case Q.ChainType.EvmParachain:this.registerEvm(t),this.registerSubstrate(t);break;case Q.ChainType.Parachain:this.registerSubstrate(t);break;case Q.ChainType.SolanaChain:this.registerSolana(t);break;case Q.ChainType.SuiChain:this.registerSui(t);break;default:throw new Error("Unsupported platform: "+t.getType())}}registerEvm(t){let e=t;this.platform.Evm=new rt(e)}registerSolana(t){let e=t;this.platform.Solana=new ot(e)}registerSui(t){let e=t;this.platform.Sui=new ft(e)}registerSubstrate(t){let e=t;this.platform.Substrate=new pt(e)}async buildCall(t,e,s,n){return this.platform[n.type].buildCall(t,e,s,n)}async estimateFee(t,e,s,n){return this.platform[n.type].estimateFee(t,e,s,n)}};var tt=require("@galacticcouncil/xc-core"),yt=require("@galacticcouncil/common");var ze=require("@galacticcouncil/common"),Y=mn(require("big.js"),1);function je(o,t,e,s){let n=o.toBig().minus(e.toBig()).minus(o.isSame(t)?t.toBig():new Y.default(0));return s&&(n=n.minus(o.isSame(s)?s.toBig():new Y.default(0))),o.copyWith({amount:n.lt(0)?0n:BigInt(n.toFixed())})}function Le(o,t,e,s){let a=o.copyWith({amount:0n}).toBig().plus(o.isSame(t)?t.toBig():new Y.default(0)).plus(o.toBig().lt(e.toBig())?e.toBig():new Y.default(0));return s&&(a=a.plus(o.isSame(s)&&o.toBig().lt(s.toBig())?s.toBig():new Y.default(0))),o.copyWith({amount:BigInt(a.toFixed())})}async function $e(o,t){return t.isEvmParachain()?t.getDerivatedAddress(o):o}function Ge(o,t){return t?ze.big.toBigInt(t,o):0n}async function ne(o,t){let e=o.getAssetDecimals(t);return e||(await o.getCurrency()).decimals}var ht=require("@galacticcouncil/xc-core");var Z=class{adapter;chain;asset;constructor(t,e,s){this.adapter=t,this.chain=e,this.asset=s}async getEd(){return this.chain instanceof ht.Parachain?this.chain.getEd():void 0}async getBalance(t){return this.chain.getBalance(this.asset,t)}async getMin(){if(this.chain instanceof ht.Parachain)return this.chain.getMin(this.asset);let t=await ne(this.chain,this.asset);return ht.AssetAmount.fromAsset(this.asset,{amount:0n,decimals:t})}async getDecimals(t){return ne(this.chain,t)}};var Ct=class extends Z{config;constructor(t,e){super(t,e.chain,e.route.source.asset),this.config=e}async getCall(t){let{amount:e,sender:s,source:n}=t,a=await this.getTransfer(t);return this.adapter.buildCall(s,e,n.feeBalance,a)}async getDestinationFee(t){let{chain:e,route:s}=this.config,{source:n,destination:a,transact:r}=s,c=a.fee.amount,m=n.destinationFee??a.fee.asset,i=await this.getDecimals(m);if(Number.isFinite(c))return{fee:tt.AssetAmount.fromAsset(m,{amount:yt.big.toBigInt(c,i),decimals:i}),feeBreakdown:{}};let l=c,{amount:u,breakdown:d}=await l.build({feeAsset:m,transferAsset:n.asset,source:r?r.chain:e,destination:a.chain,amount:t});return{fee:tt.AssetAmount.fromAsset(m,{amount:u,decimals:i}),feeBreakdown:d}}async getDestinationFeeBalance(t){let{source:e,destination:s}=this.config.route,n=e.asset,a=e.destinationFee??s.fee.asset;return n.isEqual(a)?this.getBalance(t):this.config.chain.getBalance(a,t)}async getFee(t){let{chain:e,route:s}=this.config,{amount:n,sender:a,source:r}=t,c=await this.getTransfer(t),m=s.contract?await $e(a,e):a,i=await this.adapter.estimateFee(m,n,r.feeBalance,c),{fee:l}=s.source,u=l?Ge(i.decimals,l.extra):0n,d=i.amount+u;return i.copyWith({amount:d})}async getFeeBalance(t){let{source:e}=this.config.route;if(!e.fee)return this.getBalance(t);let s=await this.getFeeAsset(t);return this.config.chain.getBalance(s,t)}async getFeeAsset(t){let{chain:e,route:s}=this.config,{source:n}=s,a=n.fee,r=n.asset;if(!a)return r;let c=a.asset;return e instanceof tt.Parachain&&"build"in c?await c.build({chain:e,address:t}):c}async getTransfer(t){let{chain:e,route:s}=this.config,{contract:n,extrinsic:a,program:r,move:c}=s;if(a){let{address:i,amount:l,asset:u,sender:d}=t,p=await(await E.create(e)).buildMessageId(d,l,u.originSymbol,i);return a.build({...t,messageId:p})}let m=n||r||c;if(m)return m.build({...t});throw new Error("AssetRoute transfer config is invalid! Specify contract, extrinsic, move or program instructions.")}async getTransact(t){let{route:e}=this.config,{transact:s}=e;if(s){let n=Object.assign({transact:{chain:s.chain}}),a={...t,...n};return{...await this.getTransactData(s,a),chain:s.chain}}}async getTransactData(t,e){let{chain:s,extrinsic:n}=t,a=await n.build(e),r=await E.create(s),c=a.getTx(r.client),m=e.source.chain,i=e.sender,l=yt.acc.getMultilocationDerivatedAccount(m.parachainId,i,s.parachainId===0?0:1,s.usesH160Acc),u=await c.getPaymentInfo(l),d=await c.getEncodedData(),[g,p]=await Promise.all([this.getTransactFee(t),this.getTransactFeeBalance(t,e)]);return{call:d,chain:s,fee:g,feeBalance:p,weight:{refTime:u.weight.ref_time,proofSize:u.weight.proof_size}}}async getTransactFee(t){let{fee:e}=t,s=await this.getDecimals(e.asset),n=yt.big.toBigInt(e.amount,s);return tt.AssetAmount.fromAsset(e.asset,{amount:n,decimals:s})}async getTransactFeeBalance(t,e){return this.config.chain.getBalance(t.fee.asset,e.sender)}};var At=class extends Z{};var Xe=require("@galacticcouncil/xc-core"),et=class{ctx;constructor(t){this.ctx=t}get asset(){let{source:t}=this.ctx;return t.balance}get dex(){let{source:t}=this.ctx;return t.chain.dex}get destFee(){let{source:t,transact:e}=this.ctx;return e?e.fee:t.destinationFee}get destFeeBalance(){let{source:t,transact:e}=this.ctx;return e?e.feeBalance:t.destinationFeeBalance}get feeBalance(){let{source:t}=this.ctx;return t.feeBalance}async getSwap(t){let{asset:e,decimals:s}=await this.dex.chain.getCurrency(),{amount:n}=await this.dex.getQuote(e,t,t);return{aIn:t,aOut:Xe.AssetAmount.fromAsset(e,{amount:n,decimals:s}),enabled:!0}}isSwapSupported(t){try{this.dex}catch{return!1}return!!(t&&t.swap)}async getDestinationSwap(t){let{amount:e,route:s}=await this.dex.getQuote(t,this.destFee,this.destFee),n=this.destFeeBalance.amount<this.destFee.amount,a=this.feeBalance.amount-t.amount>e*2n;return{aIn:t.copyWith({amount:e}),aOut:this.destFee,enabled:n&&a,route:s}}isDestinationSwapSupported(t){try{this.dex}catch{return!1}let e=!t.isSame(this.destFee),s=this.asset.isSame(this.destFee);return e&&!s}};var Vt=class{config;validations;constructor({configService:t,transferValidations:e}){this.config=t,this.validations=e||[]}async transfer(t,e,s,n,a){let r=(0,Ot.ConfigBuilder)(this.config).assets().asset(t).source(s).destination(a).build();return this.getTransferData(r,e,n)}async remoteXcm(t,e,s,n,a={}){let r=this.config.getChain(e),c=this.config.getChain(s);if(!(r.isSubstrate()&&c.isSubstrate()))throw Error("RemoteXcm is supported only between parachains");let[i,l]=await Promise.all([E.create(r),E.create(c)]),u=new dt(i,l),d=nt.acc.getMultilocationDerivatedAccount(r.parachainId,t,1,c.usesH160Acc),g=await l.getAsset(),p=await this.transfer(g,t,e,d,s);return u.remoteExec(t,d,n,f=>{let C=f.toDecimal();return p.buildCall(C)},a)}async getTransferData(t,e,s){let n=t.origin,{chain:a,asset:r}=n.route.destination,c=new j(n.chain),m=new j(a),i=new Ct(c,n),l=new At(m,a,r),u=new Ot.TransferValidator(...this.validations),[d,g,p,f,C,w,x]=await Promise.all([i.getBalance(e),i.getFeeBalance(e),i.getDestinationFee(),i.getDestinationFeeBalance(e),i.getMin(),l.getBalance(s),l.getMin()]),{source:h,destination:O}=n.route,B=p.fee.copyWith(O.fee.asset),D=p.feeBreakdown,R=h.asset.isEqual(B)&&B.amount>10n?B.amount+1n:10n,A={address:s,amount:R,asset:h.asset,destination:{balance:w,chain:a,fee:B,feeBreakdown:D},sender:e,source:{balance:d,chain:n.chain,fee:g.copyWith({amount:0n}),feeBalance:g,destinationFee:p.fee,destinationFeeBalance:f}};A.transact=await i.getTransact(A);let I=new et(A),v=await i.getFee(A),k;I.isSwapSupported(h.fee)&&(k=await I.getSwap(v),A.source.feeSwap=k);let M;I.isDestinationSwapSupported(v)&&(M=await I.getDestinationSwap(v),A.source.destinationFeeSwap=M),(k||M)&&(v=await i.getFee(A),v=v.padByPct(5n));let Mt=await l.getEd(),S=Le(w,B,x,Mt),wt=await i.getEd(),Wt=je(d,v,C,wt);A.amount=0n,A.source.fee=v;let Nt={source:{balance:d,destinationFee:p.fee,destinationFeeBalance:f,destinationFeeSwap:M,fee:v,feeBalance:g,feeSwap:k,max:Wt,min:d.copyWith({amount:S.amount})},destination:{balance:w,fee:B},reversible:t.reversible,async buildCall(W){let P=Object.assign({},A);return P.amount=nt.big.toBigInt(W,d.decimals),P.transact=await i.getTransact(P),i.getCall(P)},async estimateFee(W){let P=Object.assign({},A);return P.amount=nt.big.toBigInt(W,d.decimals),P.transact=await i.getTransact(P),i.getFee(P)},async estimateDestinationFee(W){let P=nt.big.toBigInt(W,d.decimals),{fee:N,feeBreakdown:nn}=await i.getDestinationFee(P);return A.destination.fee=N,A.destination.feeBreakdown=nn,A.source.destinationFee=N,Nt.destination.fee=N,Nt.source.destinationFee=N,N},async validate(W){let P=Object.assign({},A),N=W||v.amount;return P.source.fee=v.copyWith({amount:N}),u.validate(P)}};return Nt}async subscribeBalance(t,e,s){let n=this.config.getChainRoutes(e),a=n.getUniqueRoutes().map(r=>r.source.asset);return n.chain.subscribeBalances(a,t).subscribe(s)}};var Je=require("@galacticcouncil/xc-core");function qe(o){let t=(0,Je.ConfigBuilder)(o.config).assets();return{assets:t,withAsset(e){let s=t.asset(e);return{sources:s,withSource(n){let a=s.source(n);return{destinations:a,withDestination(r){let{routes:c,destinationAssets:m,isAssetSelect:i,isTagSelect:l,build:u}=a.destination(r);return{routes:c,destinationAssets:m,isAssetSelect:i,isTagSelect:l,build({srcAddress:d,dstAddress:g,dstAsset:p,tag:f}){let C=u(p,f);return o.getTransferData(C,d,g)}}}}}}}}}var Qe=require("@galacticcouncil/xc-core"),yn="https://api.wormholescan.io",xt=class{_baseUrl;constructor(t){this._baseUrl=t||yn}buildApi(t,e){return[this._baseUrl,t,"?"].join("")+new URLSearchParams(e).toString()}async getVaaBytes(t){let e=this.buildApi("/v1/signed_vaa/"+t,{});return await(await fetch(e)).json()}async getVaa(t){let e=this.buildApi("/api/v1/vaas/"+t,{});return(await(await fetch(e)).json()).data}async getVaaByTxHash(t){let e=this.buildApi("/api/v1/vaas/",{txHash:t}),n=await(await fetch(e)).json();if(n.data.length>0)return n.data[0];throw Error("Can't find VAA for given txHash: "+t)}async getOperations(t){let e=this.buildApi("/api/v1/operations/",t);return(await(await fetch(e)).json()).operations}async getOperation(t){let e=this.buildApi("/api/v1/operations/"+t,{});return await(await fetch(e)).json()}isMrlTransfer(t){let{payloadType:e,toAddress:s,toChain:n}=t,a="0x"+s.substring(26);return e===3&&n===16&&a===Qe.Precompile.Bridge}};var Ye=require("@galacticcouncil/common"),b=require("@galacticcouncil/xc-core"),Ze=require("@wormhole-foundation/sdk-base"),tn=require("@wormhole-foundation/sdk-connect"),en=require("@wormhole-foundation/sdk-definitions");var se=(s=>(s[s.WaitingForVaa=0]="WaitingForVaa",s[s.VaaEmitted=1]="VaaEmitted",s[s.Completed=2]="Completed",s))(se||{});var Cn=300*1e3,ae=class{parachainId;config;whScan;constructor(t,e){this.config=t,this.parachainId=e,this.whScan=new xt}get chains(){let t=this.config.chains.values();return Array.from(t)}get filters(){let t=new Date,e=new Date;e.setDate(t.getDate()-6);let s=t.toISOString();return{page:"0",pageSize:"50",includeEndDate:"true",from:e.toISOString(),to:s}}async getWithdraws(t){let e=Ye.acc.getMultilocationDerivatedAccount(this.parachainId,t,1,!0),n=(await this.whScan.getOperations({...this.filters,address:e})).map(async a=>{let{content:r}=a,{payload:c,standarizedProperties:m}=r,i=this.getStatus(a),l=this.chains.find(f=>f instanceof b.Parachain&&f.parachainId===this.parachainId),{toAddress:u,tokenAddress:d}=m,g=this.chains.find(f=>b.Wormhole.isKnown(f)&&b.Wormhole.fromChain(f).getWormholeId()===c.tokenChain),p;if(i===1&&a.vaa){let{timestamp:f}=this.getVaaHeader(a.vaa.raw),C=a.vaa.raw;if(this.isStuck(f))switch(g.getType()){case b.ChainType.EvmChain:let w=new st(g);p=async h=>w.redeem(h,C);break;case b.ChainType.SolanaChain:let x=new ut(g);p=async h=>x.redeem(h,C);break}}return{asset:d,assetSymbol:a.data.symbol,amount:a.data.tokenAmount,from:t,fromChain:l,to:u,toChain:g,status:i,redeem:p,operation:a}});return Promise.all(n)}async getDeposits(t,e="hydration"){let s=await this.whScan.getOperations({...this.filters,address:b.Precompile.Bridge,pageSize:"100"}),n=this.config.chains.get(e);if(!n)return[];let a=n,c=(await b.mrl.createPayload(a,t)).toHex(),m=s.filter(i=>{let{content:l}=i,{payload:u}=l;return u.payloadType===3&&u.toChain===16&&"0x"+u.payload===c}).map(async i=>{let{content:l,sourceChain:u}=i,{payload:d,standarizedProperties:g}=l,p=this.getStatus(i),{tokenAddress:f}=g,C=this.chains.find(h=>b.Wormhole.isKnown(h)&&b.Wormhole.fromChain(h).getWormholeId()===d.tokenChain),w=this.chains.find(h=>b.Wormhole.isKnown(h)&&b.Wormhole.fromChain(h).getWormholeId()===d.toChain),x;if(p===1&&i.vaa){let{timestamp:h}=this.getVaaHeader(i.vaa.raw),O=i.vaa.raw;if(this.isStuck(h)){let B=new mt(w);x=async D=>B.redeemMrlViaXcm(D,O)}}return{asset:f,assetSymbol:i.data.symbol,amount:i.data.tokenAmount,from:u.from,fromChain:C,to:t,toChain:n,status:p,redeem:x,operation:i}});return Promise.all(m)}isStuck(t){return Date.now()>=t*1e3+Cn}getVaaHeader(t){let e=Ze.encoding.b64.decode(t),s=(0,en.deserialize)("Uint8Array",e);return{timestamp:s.timestamp,emitterChain:s.emitterChain,emitterAddress:s.emitterAddress.toString(),sequence:s.sequence,payload:s.payload,hash:s.hash,id:(0,tn.keccak256)(s.hash)}}getStatus(t){return t.vaa?t.targetChain&&t.targetChain.status==="completed"?2:1:0}};0&&(module.exports={DISPATCH_ADDRESS,EvmClaim,EvmPlatform,EvmSigner,FeeSwap,PlatformAdapter,SolanaClaim,SolanaLilJit,SolanaPlatform,SolanaSigner,SubstrateClaim,SubstrateExec,SubstratePlatform,SubstrateService,SubstrateSigner,SuiClaim,SuiPlatform,SuiSigner,TransferBuilder,Wallet,WhStatus,WormholeScan,WormholeTransfer,chunkBySize,deserializeV0,ixToHuman,serializeV0});
|
package/build/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{acc as
|
|
2
|
-
`,s.message):console.log(s),0n}}async getGasPrice(){return this.client.getProvider().getGasPrice()}async getNonce(t){return this.client.getProvider().getTransactionCount({address:t})}async simulateCall(t){let{address:e,args:s,value:n,func:a}=this.config,r=this.client.getProvider(),
|
|
3
|
-
`,o.details),{error:o}}}decodeEvents(t){let e=[];return t&&t.forEach(s=>{try{let{eventName:n,args:a}=Ve({abi:this.abi,data:s.data,topics:s.topics});e.push({eventName:n,args:a})}catch{}}),e}};var H=class{static get(t,e){return new rt(t,e)}};import{Precompile as Oe}from"@galacticcouncil/xc-core";import{decodeAbiParameters as _e}from"viem";function Tt(u){return u.module==="Snowbridge"&&u.func==="v2_sendMessage"}function Mt(u){if(!Tt(u))return;let t=u.args[1];if(!t||t.length===0)return;let[e,s]=_e([{type:"uint8"},{type:"address"},{type:"uint128"}],t[0]);return s}function Nt(u){let t=u.module==="Snowbridge"&&u.func==="v2_sendMessage"&&Array.isArray(u.args[1])&&u.args[1].length===0,e=u.module==="Snowbridge"&&u.func==="sendToken"&&u.args[0]==="0x0000000000000000000000000000000000000000";return u.module==="TokenBridge"&&["wrapAndTransferETHWithPayload","wrapAndTransferETH"].includes(u.func)||t||e}function Wt(u){return Object.entries(Oe).map(([e,s])=>s).includes(u.address)}var it=class{#t;constructor(t){this.#t=t.evmClient}async buildCall(t,e,s,n){let a=H.get(this.#t,n),{abi:r,asset:i,calldata:o}=a,c={abi:JSON.stringify(r),data:o,from:t,to:n.address,type:Ut.Evm,value:n.value,dryRun:async()=>{let{error:p,logs:f}=await a.simulateCall(t),h=a.decodeEvents(f);return{call:n.module+"."+n.func,error:p?.shortMessage,events:h}}};if(Wt(n)||Nt(n))return c;let l=Tt(n)?Mt(n):i,m=new We(this.#t,l),d=await m.allowance(t,n.address);if(d>=e)return c;let g=m.approve(n.address,e);return{abi:JSON.stringify(Me.Erc20),allowance:d,data:g,from:t,to:l,type:Ut.Evm,dryRun:()=>{}}}async estimateFee(t,e,s,n){let r=await H.get(this.#t,n).estimateFee(t,e);return s.copyWith({amount:r})}async getBalance(t,e){let s=at.get(this.#t,e),[n,a]=await Promise.all([s.getBalance(),s.getDecimals()]);return Ne.fromAsset(t,{amount:n,decimals:a})}async subscribeBalance(t,e){let s=new ze,n=s.pipe(Ke(1)),a=this.#t.getProvider(),r=async()=>{let o=async()=>{let l=await this.getBalance(t,e);s.next(l)};await o();let c=a.watchBlocks({onBlock:()=>o()});return()=>c()},i;return r().then(o=>i=o),n.pipe(je(()=>i?.()),Ue((o,c)=>o.amount===c.amount))}};import{EvmParachain as He}from"@galacticcouncil/xc-core";import{h160 as Le}from"@galacticcouncil/common";import{Binary as $e}from"polkadot-api";var jt="0x0000000000000000000000000000000000000401",{H160:Qe}=Le,Kt=class{#t;#e;#n;constructor(t,e){this.#t=t,this.#e=t.evmClient,this.#n=e}async signAndSend(t,e){let s=Qe.fromAny(t.from),n=this.#e.getProvider(),a=!1;if(this.#t instanceof He)try{let i=this.#t.client,o=$e.fromHex(t.data);await i.getUnsafeApi().txFromCallData(o),a=!0}catch{}let r;if(a){let[i,o]=await Promise.all([n.estimateGas({account:s,data:t.data,to:jt}),n.getGasPrice()]),c=o+o/100n*10n;r=await this.#n.sendTransaction({account:s,chain:this.#e.chain,data:t.data,maxPriorityFeePerGas:c,maxFeePerGas:c,gas:i*11n/10n,to:jt})}else{let{data:i,to:o,value:c}=t;r=await this.#n.sendTransaction({account:s,chain:this.#e.chain,data:i,to:o,value:c})}e.onTransactionSend(r),n.waitForTransactionReceipt({hash:r}).then(i=>e.onTransactionReceipt(i)).catch(i=>e.onError(i))}};import{AssetAmount as tn,CallType as en}from"@galacticcouncil/xc-core";import{PublicKey as nn}from"@solana/web3.js";import{Buffer as sn}from"buffer";import{distinctUntilChanged as an,finalize as rn,shareReplay as on,Subject as cn}from"rxjs";var M=class{connection;config;constructor(t,e){this.validateConnection(t),this.validateConfig(e),this.connection=t,this.config=e}validateConnection(t){if(!t)throw new Error("No connection found")}validateConfig(t){if(!t.address)throw new Error("Solana address is required")}};import{SolanaAddress as qe}from"@wormhole-foundation/sdk-solana";var Xe=9,ot=class extends M{async getBalance(){let{address:t}=this.config,e=new qe(t).unwrap(),s=await this.connection.getBalance(e);return BigInt(s)}async getDecimals(){return Xe}};import{SolanaAddress as Bt}from"@wormhole-foundation/sdk-solana";var ct=class extends M{constructor(t,e){super(t,e),this.validateToken(e)}async getBalance(){let{address:t,token:e}=this.config,s=new Bt(t).unwrap(),n=new Bt(e).unwrap();return(await this.connection.getParsedTokenAccountsByOwner(s,{mint:n})).value.reduce((r,{account:i})=>{let o=i.data.parsed.info.tokenAmount;return r+=BigInt(o.amount),r},0n)}async getDecimals(){let{token:t}=this.config,e=new Bt(t).unwrap();return(await this.connection.getTokenSupply(e)).value.decimals}validateToken(t){if(!t.token)throw new Error("Token address is required")}};var ut=class{static get(t,e){switch(e.module){case"Native":return new ot(t,e);case"Token":return new ct(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};import{ComputeBudgetProgram as zt,PublicKey as Je,TransactionMessage as Ge,VersionedTransaction as Ht}from"@solana/web3.js";var Lt=.5,$t=2,Qt=1,qt=1e6,Ye=25e4,lt=class{connection;config;constructor(t,e){this.validateConnection(t),this.connection=t,this.config=e}validateConnection(t){if(!t)throw new Error("No connection found")}async getPriorityMessage(t){let{instructions:e}=this.config,s=await this.getV0Message(t,e),n=await this.createPriorityFeeInstructions(s);return this.getV0Message(t,[...e,...n])}async estimateFee(t,e){if(e===0n)return 0n;let{instructions:s}=this.config,n=await this.getV0Message(t,s),a=await this.determineComputeBudget(n);return BigInt(a)}async getV0Message(t,e){let s=new Je(t),{blockhash:n}=await this.connection.getLatestBlockhash("finalized");return new Ge({payerKey:s,recentBlockhash:n,instructions:e}).compileToV0Message()}async createPriorityFeeInstructions(t,e=Lt,s=$t,n=Qt,a=qt){let[r,i]=await Promise.all([this.determineComputeBudget(t),this.determinePriorityFee(t,e,s,n,a)]);return[zt.setComputeUnitLimit({units:r}),zt.setComputeUnitPrice({microLamports:i})]}async simulateTransaction(t,e){let s=new Ht(e);return(await this.connection.simulateTransaction(s,{accounts:{encoding:"base64",addresses:[t]}})).value}async determineComputeBudget(t){let e=new Ht(t),s=await this.connection.simulateTransaction(e),{err:n,unitsConsumed:a}=s.value;return a&&!n?Math.round(a*1.2):Ye}async determinePriorityFee(t,e=Lt,s=$t,n=Qt,a=qt){let r=n,i=await this.getTxAccounts(t),o=await this.connection.getRecentPrioritizationFees({lockedWritableAccounts:i});if(o){let c=o.map(m=>m.prioritizationFee).filter(m=>m>0).sort((m,d)=>m-d),l=Math.ceil(c.length*e);if(c.length>l){let d=c[l]*s;r=Math.max(r,d)}}return Math.min(Math.max(r,n),a)}async getTxAccounts(t){let e=(await Promise.all(t.addressTableLookups.map(n=>this.connection.getAddressLookupTable(n.accountKey)))).map(n=>n.value).filter(n=>n!==null),s=t.getAccountKeys({addressLookupTableAccounts:e??void 0});return t.compiledInstructions.flatMap(n=>n.accountKeyIndexes).map(n=>t.isAccountWritable(n)?s.get(n):null).filter(n=>n!==null)}};var L=class{static get(t,e){return new lt(t,e)}};import{MessageV0 as Ze}from"@solana/web3.js";function V(u){return u.map(t=>({program:t.programId.toBase58(),data:t.data.toString("hex"),keys:t.keys.map(e=>e.pubkey.toBase58())}))}function Xt(u,t=1e3){let e=[],s=[],n=0;for(let a of u){let r=a.data?.length??0;s.length&&n+r>t&&(e.push(s),s=[],n=0),s.push(a),n+=r}return s.length&&e.push(s),e}function $(u){let t=u.serialize();return Buffer.from(t).toString("hex")}function wr(u){let t=Buffer.from(u,"hex"),e=Uint8Array.from(t);return Ze.deserialize(e)}var mt=class{#t;constructor(t){this.#t=t.connection}async buildCall(t,e,s,n){let a=L.get(this.#t,n),r=await a.getPriorityMessage(t),i=r.serialize(),o=sn.from(i).toString("hex");return{from:t,data:o,ix:V(n.instructions),signers:n.signers,type:en.Solana,dryRun:async()=>{let{err:c,logs:l}=await a.simulateTransaction(t,r);return{call:n.module+"."+n.func,error:c,events:l}}}}async estimateFee(t,e,s,n){let a=L.get(this.#t,n),r=await a.estimateFee(t,e),i=await a.getPriorityMessage(t),{accounts:o}=await a.simulateTransaction(t,i),l=(o&&o[0])?.lamports;if(l){let m=n.module==="TokenBridge"&&n.func==="TransferNativeWithPayload";return s.copyWith({amount:s.amount-BigInt(l)-(m?e:0n)+n.rentReserve})}return s.copyWith({amount:r+n.rentReserve})}async getBalance(t,e){let s=ut.get(this.#t,e),[n,a]=await Promise.all([s.getBalance(),s.getDecimals()]);return tn.fromAsset(t,{amount:n,decimals:a})}async subscribeBalance(t,e){let s=new cn,n=s.pipe(on(1)),a=async()=>{let i=async()=>{let l=await this.getBalance(t,e);s.next(l)};await i();let o=new nn(e.address),c=this.#t.onAccountChange(o,()=>i());return()=>{this.#t.removeAccountChangeListener(c)}},r;return a().then(i=>r=i),n.pipe(rn(()=>r?.()),an((i,o)=>i.amount===o.amount))}};import{CallType as dt,Wormhole as un}from"@galacticcouncil/xc-core";import{Keypair as Jt,PublicKey as Q,SystemProgram as Gt,TransactionMessage as ln}from"@solana/web3.js";import{ACCOUNT_SIZE as mn,NATIVE_MINT as gt,TOKEN_PROGRAM_ID as dn,createAssociatedTokenAccountIdempotentInstruction as Yt,createCloseAccountInstruction as gn,createInitializeAccountInstruction as pn,createTransferInstruction as fn,getAssociatedTokenAddressSync as hn,getMinimumBalanceForRentExemptAccount as yn,getMint as Cn}from"@solana/spl-token";import{utils as An}from"@wormhole-foundation/sdk-solana";import{utils as Zt}from"@wormhole-foundation/sdk-solana-core";import{encoding as bn}from"@wormhole-foundation/sdk-base";import{deserialize as te}from"@wormhole-foundation/sdk-definitions";import{createCompleteTransferNativeInstruction as ee,createCompleteTransferWrappedInstruction as wn}from"@wormhole-foundation/sdk-solana-tokenbridge";var N=class{#t;constructor(t){this.#t=t.connection}async sendBundle(t){let{result:e}=await this.#t._rpcRequest("sendBundle",[t]);return e}async simulateBundle(t){return(await this.#t._rpcRequest("simulateBundle",[[t]])).result}async getInflightBundleStatuses(t){let{result:e}=await this.#t._rpcRequest("getInflightBundleStatuses",[t]);return e}async getRegion(){let{result:t}=await this.#t._rpcRequest("getRegions",[]);return t}async getTipAccount(){let{result:t}=await this.#t._rpcRequest("getTipAccounts",[]);return t}};var pt=class{#t;#e;#n;constructor(t){this.#t=t,this.#e=t.connection,this.#n=new N(t)}async redeem(t,e,s){let n=un.fromChain(this.#t),a=bn.b64.decode(e),r=te("TokenBridge:Transfer",a),i=te("Uint8Array",a),o=this.derivePostedVaaKey(n.getCoreBridge(),Buffer.from(r.hash)),c=new Q(t),l=s?new Q(s):c,m=c.equals(l),d=[];if(!await this.#e.getAccountInfo(o)){let y=Jt.generate(),S=await Zt.createVerifySignaturesInstructions(this.#t.connection,n.getCoreBridge(),c,i,y.publicKey),B=Xt(S,1e3);for(let T=0;T<B.length;T++){let b=B[T],E=await this.getV0Message(c,b),I=$(E);d.push({from:t,data:I,ix:V(b),signers:[y],type:dt.Solana})}let D=Zt.createPostVaaInstruction(this.#e,n.getCoreBridge(),c,i,y.publicKey),K=await this.getV0Message(c,[D]),C=$(K);d.push({from:t,data:C,ix:V([D]),type:dt.Solana})}let p=r.payload.token.chain==="Solana",f=new Q(r.payload.token.address.toUint8Array()),h=p&&f.equals(gt),x=await this.#n.getTipAccount(),A=Gt.transfer({fromPubkey:c,toPubkey:new Q(x[0]),lamports:1e3});if(h&&m){let y=await this.redeemAndUnwrap(n,c,r,A);d.push(y)}else{let y=await this.redeemToken(n,c,l,f,p,r,A);d.push(y)}return d}async redeemToken(t,e,s,n,a,r,i){let c=(a?ee:wn)(this.#e,t.getTokenBridge(),t.getCoreBridge(),e,r),l=hn(n,s),m=Yt(e,l,s,n),d=await this.getV0Message(e,[m,c,i]),g=$(d);return{from:e.toBase58(),data:g,ix:V([m,c]),type:dt.Solana}}async redeemAndUnwrap(t,e,s,n){let a=new Q(s.payload.to.address.toUint8Array()),r=await Cn(this.#e,gt),i=s.payload.token.amount*BigInt(Math.pow(10,r.decimals-8)),o=await yn(this.#e),c=Jt.generate(),l=Yt(e,a,e,gt),m=ee(this.#e,t.getTokenBridge(),t.getCoreBridge(),e,s),d=Gt.createAccount({fromPubkey:e,newAccountPubkey:c.publicKey,lamports:o,space:mn,programId:dn}),g=pn(c.publicKey,gt,e),p=fn(a,c.publicKey,e,i),f=gn(c.publicKey,e,e),h=[l,m,d,g,p,f,n],x=await this.getV0Message(e,h),A=$(x);return{from:e.toBase58(),data:A,ix:V(h),signers:[c],type:dt.Solana}}derivePostedVaaKey(t,e){return An.deriveAddress([Buffer.from("PostedVAA"),e],t)}async getV0Message(t,e){let{blockhash:s}=await this.#e.getLatestBlockhash("finalized");return new ln({payerKey:t,recentBlockhash:s,instructions:e}).compileToV0Message()}};import{Keypair as ne,MessageV0 as vn,VersionedTransaction as xn}from"@solana/web3.js";import{Buffer as Et}from"buffer";var se=class{#t;#e;#n;constructor(t,e){this.#t=t,this.#e=e,this.#n=new N(t)}async signAndSend(t,e){let{data:s,signers:n}=t,a=this.toVersioned(s,n);try{if(this.#e instanceof ne){a.sign([this.#e]);let c=await this.#t.connection.sendTransaction(a);e.onTransactionSend(c);let l=await this.#t.connection.getSignatureStatus(c);e.onStatus?.(l);return}let r=this.#e;await r.connect(),n&&a.sign(n);let{signature:i}=await r.signAndSendTransaction(a);e.onTransactionSend(i);let o=await this.#t.connection.getSignatureStatus(i);e.onStatus?.(o)}catch(r){e.onError(r)}}async signAndSendAll(t,e){let s=t.map(n=>{let{data:a,signers:r}=n;return this.toVersioned(a,r)});try{let n;if(this.#e instanceof ne)s.forEach(o=>o.sign([this.#e])),n=s.map(o=>Et.from(o.serialize()).toString("base64"));else{let o=this.#e;await o.connect(),n=(await o.signAllTransactions(s)).map(l=>Et.from(l.serialize()).toString("base64"))}let a=await this.#n.simulateBundle(n);if(a.value.summary!=="succeeded")throw new Error("Bundle simulation failed! "+JSON.stringify(a,null,2));let r=await this.#n.sendBundle(n);e.onTransactionSend(r);let i=await this.#n.getInflightBundleStatuses([r]);e.onBundleStatus?.(i.value)}catch(n){e.onError(n)}}toVersioned(t,e){let s=Et.from(t,"hex"),n=Uint8Array.from(s),a=vn.deserialize(n),r=new xn(a);return e&&r.sign(e),r}};import{Abi as Sn,CallType as Pn,Precompile as Tn,Wormhole as Bn}from"@galacticcouncil/xc-core";import{encoding as ae}from"@wormhole-foundation/sdk-base";import{encodeFunctionData as En}from"viem";import{Binary as re}from"polkadot-api";var ft=class{#t;constructor(t){this.#t=t,Bn.fromChain(this.#t)}redeemMrl(t,e){let s=ae.b64.decode(e),n=ae.hex.encode(s),a=Sn.Gmp,r=En({abi:a,functionName:"wormholeTransferERC20",args:["0x"+n]});return{abi:JSON.stringify(a),data:r,from:t,to:Tn.Bridge}}async redeemMrlViaXcm(t,e){let n=this.#t.client.getUnsafeApi(),a=this.redeemMrl(t,e),i=await n.tx.EthereumXcm.transact({xcm_transaction:{type:"V2",value:{gas_limit:[5000000n,0n,0n,0n],action:{type:"Call",value:a.to},value:[0n,0n,0n,0n],input:re.fromHex(a.data),access_list:void 0}}}).getEncodedData();return{data:re.toHex(i),from:t,type:Pn.Substrate,dryRun:async()=>{},txOptions:void 0}}};import{AssetAmount as kn,CallType as Vn}from"@galacticcouncil/xc-core";import{Binary as ht}from"polkadot-api";import{big as In}from"@galacticcouncil/common";async function It(u,t,e){let s=await e.getDecimals(),n=e.chain.getAssetDecimals(t)??s,a=e.chain.usesChainDecimals?s:n;return{amount:In.convertDecimals(u,a,n),decimals:n}}import{enums as Fn}from"@galacticcouncil/common";var ie=u=>{let t=[];for(let e of u)if(["PolkadotXcm"].includes(e.type)&&e.value.type==="FeesPaid"){let n=e.value.value.fees;for(let a of n)if(a.fun.type==="Fungible"){let r=BigInt(a.fun.value);t.push(r)}}return t.reduce((e,s)=>e+s,0n)},W=u=>{let t=u.value.error;return t.type==="Module"?Fn.enumPath(t.value):JSON.stringify(t.value)};import{xcm as Ft}from"@galacticcouncil/common";function Dn(u){return{parents:0,interior:{type:"X1",value:u.startsWith("0x")?Ft.toAccountKey20(u):Ft.toAccountId32(u)}}}function oe(u){return{type:"V4",value:{parents:1,interior:{type:"X1",value:{type:"Parachain",value:u.parachainId}}}}}var Rn=(u,t)=>({id:Ft.transform(u),fun:{type:"Fungible",value:t}}),ce=(u,t,e,s,n,a)=>{console.log(a);let r=Dn(u),i=Rn(t,e.amount);return{type:"V4",value:[{type:"WithdrawAsset",value:[i]},{type:"BuyExecution",value:{fees:i,weight_limit:{type:"Unlimited"}}},{type:"Transact",value:{origin_kind:{type:"SovereignAccount"},require_weight_at_most:{ref_time:s,proof_size:n},call:a}},{type:"RefundSurplus",value:void 0},{type:"DepositAsset",value:{assets:{type:"Wild",value:{type:"AllCounted",value:1}},beneficiary:r}}]}};var yt=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}async remoteExec(t,e,s,n,a={}){let r=this.#t.api,i=await this.#t.getAsset(),o=this.#e.api,c=this.#e.chain,l=await c.getCurrency(),m=l.asset,d=l.decimals,g=c.getAssetXcmLocation(m),p=ht.fromHex(s.data),h=await(await o.txFromCallData(p)).getPaymentInfo(e),x=BigInt(h.partial_fee)*120n/100n,A=kn.fromAsset(m,{amount:x,decimals:d}),y=h.weight.ref_time,S=h.weight.proof_size,B=oe(c),D=ce(e,g,A,y,S,p),K=r.tx.PolkadotXcm.send({dest:B,message:D}),C=[];try{let w=await this.#t.chain.dex.getCalldata(t,a.srcFeeAsset||i,m,A,10),tt=ht.fromHex(w),z=await r.txFromCallData(tt);C.push(z)}catch{}let T=await n(A),b=ht.fromHex(T.data),E=await r.txFromCallData(b);C.push(E),C.push(K);let I=C.map(w=>w.decodedCall),Z=r.tx.Utility.batch_all({calls:I}),Pt=await Z.getEncodedData();return{from:t,data:ht.toHex(Pt),type:Vn.Substrate,dryRun:this.#t.isDryRunSupported()?async()=>{try{let w=await this.#t.dryRun(t,Z);return{call:"polkadotXcm.send",error:w.execution_result&&w.execution_result.success?void 0:W(w.execution_result),events:w.emitted_events||[],xcm:w.forwarded_xcms||[]}}catch(w){return{call:"polkadotXcm.send",error:w instanceof Error?w.message:"unknown"}}}:()=>{}}}};import{Asset as Kn,AssetAmount as de,CallType as zn}from"@galacticcouncil/xc-core";import{Binary as Hn}from"polkadot-api";import{concatMap as ge,catchError as Ln,distinctUntilChanged as $n,firstValueFrom as Qn,map as qn,throwError as Xn}from"rxjs";import{addr as On,multiloc as Dt,AssetAmount as _n}from"@galacticcouncil/xc-core";import{acc as Mn,enums as Nn}from"@galacticcouncil/common";import{Blake2256 as Wn,u32 as Un}from"@polkadot-api/substrate-bindings";import{toHex as jn,fromHex as ue}from"@polkadot-api/utils";import{Enum as le}from"polkadot-api";var{Ss58Addr:me}=On,P=class u{chain;_currency;constructor(t){this.chain=t}static async create(t){return new u(t)}get client(){return this.chain.client}get api(){return this.client.getUnsafeApi()}async getCurrency(){return this._currency||(this._currency=this.chain.getCurrency()),this._currency}async getAsset(){return(await this.getCurrency()).asset}async getDecimals(){return(await this.getCurrency()).decimals}async getExistentialDeposit(){let t;try{let n=await this.api.constants.Balances.ExistentialDeposit();t=typeof n=="bigint"?n:BigInt(String(n))}catch{t=0n}let{asset:e,decimals:s}=await this.getCurrency();return _n.fromAsset(e,{amount:t,decimals:s})}isDryRunSupported(){return this.api.apis?.DryRunApi!==void 0}async buildMessageId(t,e,s,n){let a=await this.client._request("system_accountNextIndex",[t]),r=Un.enc(a),i=l=>new TextEncoder().encode(l),o=new Uint8Array([...i(this.chain.parachainId.toString()),...ue(t.startsWith("0x")?t.slice(2):t),...r,...ue(s.startsWith("0x")?s.slice(2):s),...i(n),...i(e.toString())]),c=Wn(o);return jn(c)}async dryRun(t,e){let s=le("Signed",t),n=le("system",s),a=await this.api.apis.DryRunApi.dry_run_call(n,e.decodedCall,4);if(!a.success)throw new Error("DryRun call failed");let r=a.value;if("type"in r&&"value"in r)throw new Error("DryRun call error: "+Nn.enumPath(r.value));return r}async estimateNetworkFee(t,e){let s=e.getTx(this.client);try{let n=await s.getPaymentInfo(t);return BigInt(n.partial_fee)}catch{console.warn("Can't estimate network fee.")}return 0n}async estimateDeliveryFee(t,e){if(this.chain.usesDeliveryFee){let s=await this.estimateDeliveryFeeWith(t,e);try{let n=e.getTx(this.client),a=await this.dryRun(s,n);if(a.execution_result?.success)return ie(a.emitted_events||[]);{let r=W(a.execution_result);console.warn(`Can't estimate delivery fee. Reason:
|
|
4
|
-
${r}`)}}catch{}}return 0n}async estimateDeliveryFeeWith(t,e){if(["PolkadotXcm"].includes(e.module)){let n=e.getTx(this.client).decodedCall.value.value,a="dest"in n?n.dest:void 0;if(!a)return t;let r=Dt.findNestedKey(a,"interior"),i=Dt.findParachain(a);if(Dt.findGlobalConsensus(a))return t;if(i){let c=Mn.getSovereignAccounts(i);return this.chain.parachainId===0?me.encodePubKey(c.relay):me.encodePubKey(c.generic)}if(r&&r.interior==="Here")return this.chain.treasury||t}return t}};var Ct=class{#t;constructor(t){this.#t=P.create(t)}async useSignerFee(t){let e=await this.#t,s=await e.getAsset();return e.chain.usesSignerFee&&!s.isEqual(t)}async buildCall(t,e,s,n){let a=await this.#t,i=await this.useSignerFee(s)?{asset:new Kn(s)}:void 0,o=n.getTx(a.client),c=n.module+"."+n.func,l=await o.getEncodedData();return{from:t,data:Hn.toHex(l),type:zn.Substrate,txOptions:i,dryRun:a.isDryRunSupported()?async()=>{try{let m=n.getTx(a.client),d=await a.dryRun(t,m),g=d.execution_result&&d.execution_result.success?void 0:W(d.execution_result);return{call:c,error:g,events:d.emitted_events||[],xcm:d.forwarded_xcms||[]}}catch(m){return{call:c,error:m instanceof Error?m.message:"unknown"}}}:()=>{}}}async estimateFee(t,e,s,n){let a=await this.#t,r=await a.estimateNetworkFee(t,n),i=await a.estimateDeliveryFee(t,n),o=await this.exchangeFee(r+i,s),c=await It(o,s,a);return s.copyWith(c)}async getBalance(t,e){let s=await this.subscribeBalance(t,e);return Qn(s)}async subscribeBalance(t,e){let s=await this.#t,{module:n,func:a,args:r,transform:i}=e;return s.client.getUnsafeApi().query[n][a].watchValue(...r,{at:"best"}).pipe(qn(({value:l})=>l)).pipe(ge(l=>i(l)),$n((l,m)=>l===m),ge(async l=>{let m=await It(l,t,s);return de.fromAsset(t,m)}),Ln(l=>(console.error("subscribe fails for:",t),Xn(()=>l))))}async exchangeFee(t,e){let s=await this.#t,n=await s.getAsset(),a=await s.getDecimals();if(n.isEqual(e))return t;try{let r=s.chain.dex,i=de.fromAsset(n,{amount:t,decimals:a});return(await r.getQuote(e,n,i,!0)).amount}catch{}return t}};import{multiloc as pe}from"@galacticcouncil/xc-core";import{Binary as Jn,Enum as Rt}from"polkadot-api";var fe=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}signAndSend(t,e){let n=this.#t.client.getUnsafeApi(),a=Jn.fromHex(t.data),r={};t.txOptions?.asset&&(r={asset:this.getFeeAsset(t.txOptions.asset)}),n.txFromCallData(a).then(i=>{i.signSubmitAndWatch(this.#e,r).subscribe({next:o=>{o.type==="broadcasted"&&e.onTransactionSend(o.txHash),o.type==="finalized"&&e.onFinalized(o)},error:o=>{e.onError(o)}})})}getFeeAsset(t){let e=this.#t.getAssetXcmLocation(t);if(e){let s=pe.findPalletInstance(e),n=pe.findGeneralIndex(e);return{parents:0,interior:Rt("X2",[Rt("PalletInstance",Number(s)),Rt("GeneralIndex",BigInt(n))])}}throw new Error("Asset location not found")}};import{CallType as Yn,Wormhole as Zn}from"@galacticcouncil/xc-core";import{Transaction as ts}from"@mysten/sui/transactions";import{SUI_CLOCK_OBJECT_ID as es}from"@mysten/sui/utils";import{toBase64 as ns}from"@mysten/bcs";import{encoding as ss,serialize as as,toChainId as rs}from"@wormhole-foundation/sdk-connect";import{deserialize as is}from"@wormhole-foundation/sdk-definitions";import{getPackageId as he}from"@wormhole-foundation/sdk-sui";import{getTokenCoinType as os}from"@wormhole-foundation/sdk-sui-tokenbridge";import{fromBase64 as Gn}from"@mysten/bcs";function At(u,t={}){let e=u.inputs??[],s=u.commands??[],n=t.numbers??"string",a=t.decode32As??"address",r=l=>n==="bigint"?l:n==="number"?Number(l):l.toString(),i=l=>{let m=Gn(l),d=g=>{let p=0n;for(let f=0;f<g;f++)p|=BigInt(m[f])<<8n*BigInt(f);return p};return m.length===1?{type:"pure",valueType:"u8",value:Number(m[0])}:m.length===2?{type:"pure",valueType:"u16",value:r(d(2))}:m.length===4?{type:"pure",valueType:"u32",value:Number(d(4))}:m.length===8?{type:"pure",valueType:"u64",value:r(d(8))}:m.length===32&&a==="address"?{type:"pure",valueType:"address",value:"0x"+[...m].map(p=>p.toString(16).padStart(2,"0")).join("")}:{type:"pure",valueType:"vector<u8>",value:Array.from(m)}},o=l=>{let m=e[l];if(!m)return{Input:l};if(m.Pure?.bytes)return i(m.Pure.bytes);let d=m.Object?.SharedObject;if(d)return{type:"object",objectType:"sharedObject",objectId:d.objectId,initialSharedVersion:String(d.initialSharedVersion),mutable:!!d.mutable};let g=m.Object?.ImmOrOwnedObject;return g?{type:"object",objectType:"immOrOwnedObject",objectId:g.objectId,version:String(g.version),digest:g.digest??void 0}:{Input:l}},c=l=>l?.GasCoin?"GasCoin":Array.isArray(l?.NestedResult)?l:typeof l?.Input=="number"?o(l.Input):l;return s.map(l=>{if(l.MoveCall){let m=l.MoveCall;return{MoveCall:{...m,arguments:(m.arguments??[]).map(c)}}}if(l.SplitCoins){let m=l.SplitCoins,d=m.coin?.GasCoin?"GasCoin":c(m.coin),g=(m.amounts??[]).map(c);return{SplitCoins:[d,g]}}if(l.MergeCoins){let m=l.MergeCoins;return{MergeCoins:{...m,destination:c(m.destination),sources:(m.sources??[]).map(c)}}}if(l.TransferObjects){let m=l.TransferObjects;return{TransferObjects:{...m,objects:(m.objects??[]).map(c),address:c(m.address)}}}return l})}var ye=class{#t;constructor(t){this.#t=t}async redeem(t,e){let s=Zn.fromChain(this.#t),n=this.#t.client,a=ss.b64.decode(e),r=is("TokenBridge:Transfer",a),i=s.getCoreBridge(),o=s.getTokenBridge(),c=await os(n,o,r.payload.token.address.toUint8Array(),rs(r.payload.token.chain));if(!c)throw new Error("Unable to fetch token coinType");let[l,m]=await Promise.all([he(n,i),he(n,o)]),d=new ts;d.setSender(t);let[g]=d.moveCall({target:`${l}::vaa::parse_and_verify`,arguments:[d.object(i),d.pure.vector("u8",as(r)),d.object(es)]}),[p]=d.moveCall({target:`${m}::vaa::verify_only_once`,arguments:[d.object(o),g]}),[f]=d.moveCall({target:`${m}::complete_transfer::authorize_transfer`,arguments:[d.object(o),p],typeArguments:[c]}),[h]=d.moveCall({target:`${m}::complete_transfer::redeem_relayer_payout`,arguments:[f],typeArguments:[c]});d.moveCall({target:`${m}::coin_utils::return_nonzero`,arguments:[h],typeArguments:[c]});let x=await d.build({client:n}),A=await d.toJSON(),y=At(JSON.parse(A));return{from:t,commands:y,data:ns(x),type:Yn.Sui}}};import{AssetAmount as ls,CallType as ms}from"@galacticcouncil/xc-core";import{toBase64 as ds}from"@mysten/bcs";import{distinctUntilChanged as gs,finalize as ps,shareReplay as fs,Subject as hs}from"rxjs";var bt=class{client;config;constructor(t,e){this.validateClient(t),this.validateConfig(e),this.client=t,this.config=e}validateClient(t){if(!t)throw new Error("No client found")}validateConfig(t){if(!t.address)throw new Error("Sui address is required")}};import{SUI_TYPE_ARG as cs}from"@mysten/sui/utils";var us=9,wt=class extends bt{async getBalance(){let{address:t}=this.config,e=await this.client.getBalance({owner:t,coinType:cs});return BigInt(e.totalBalance)}async getDecimals(){return us}};var vt=class{static get(t,e){switch(e.module){case"Native":return new wt(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};var xt=class{#t;constructor(t){this.#t=t.client}async buildCall(t,e,s,n){let{transaction:a}=n;a.setSender(t);let r=await a.build({client:this.#t}),i=await a.toJSON(),o=At(JSON.parse(i));return{from:t,commands:o,data:ds(r),type:ms.Sui,dryRun:async()=>{let c=await this.#t.dryRunTransactionBlock({transactionBlock:r});return{call:n.module+"."+n.func,error:c.executionErrorSource}}}}async estimateFee(t,e,s,n){let{transaction:a}=n;a.setSender(t);let r=await a.build({client:this.#t}),o=(await this.#t.dryRunTransactionBlock({transactionBlock:r})).effects.gasUsed,c=BigInt(o.computationCost),l=BigInt(o.storageCost),m=c+l;return s.copyWith({amount:m})}async getBalance(t,e){let s=vt.get(this.#t,e),[n,a]=await Promise.all([s.getBalance(),s.getDecimals()]);return ls.fromAsset(t,{amount:n,decimals:a})}async subscribeBalance(t,e){let s=new hs,n=s.pipe(fs(1)),a=async()=>{await(async()=>{let c=await this.getBalance(t,e);s.next(c)})();let o=setInterval(()=>{},3e3);return()=>clearInterval(o)},r;return a().then(i=>r=i),n.pipe(ps(()=>r?.()),gs((i,o)=>i.amount===o.amount))}};import{Ed25519Keypair as ys}from"@mysten/sui/keypairs/ed25519";import{Transaction as Cs}from"@mysten/sui/transactions";var Ce=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}async signAndSend(t,e){let{from:s,data:n}=t,a=this.#t.client;try{if(this.#e instanceof ys){let o=Cs.from(n),c=await a.signAndExecuteTransaction({signer:this.#e,transaction:o,options:{showEffects:!0,showEvents:!0,showObjectChanges:!0,showBalanceChanges:!0}});e.onTransactionSend(c.digest);return}let r=await this.#e.signTransaction({transaction:n,address:s,networkID:"sui:mainnet"}),i=await a.executeTransactionBlock({transactionBlock:r.transaction,signature:r.signature,options:{showEffects:!0,showEvents:!0,showObjectChanges:!0,showBalanceChanges:!0}});e.onTransactionSend(i.digest)}catch(r){e.onError(r)}}};var O=class{platform={};constructor(t){switch(t.getType()){case q.EvmChain:this.registerEvm(t);break;case q.EvmParachain:this.registerEvm(t),this.registerSubstrate(t);break;case q.Parachain:this.registerSubstrate(t);break;case q.SolanaChain:this.registerSolana(t);break;case q.SuiChain:this.registerSui(t);break;default:throw new Error("Unsupported platform: "+t.getType())}}registerEvm(t){let e=t;this.platform.Evm=new it(e)}registerSolana(t){let e=t;this.platform.Solana=new mt(e)}registerSui(t){let e=t;this.platform.Sui=new xt(e)}registerSubstrate(t){let e=t;this.platform.Substrate=new Ct(e)}async buildCall(t,e,s,n){return this.platform[n.type].buildCall(t,e,s,n)}async estimateFee(t,e,s,n){return this.platform[n.type].estimateFee(t,e,s,n)}async getBalance(t,e){return this.platform[e.type].getBalance(t,e)}async subscribeBalance(t,e){return this.platform[e.type].subscribeBalance(t,e)}};import{addr as Ss,AssetAmount as kt,Parachain as Ps}from"@galacticcouncil/xc-core";import{acc as Ts,big as xe}from"@galacticcouncil/common";import{big as As}from"@galacticcouncil/common";import X from"big.js";function Ae(u,t,e,s){let n=u.toBig().minus(e.toBig()).minus(u.isSame(t)?t.toBig():new X(0));return s&&(n=n.minus(u.isSame(s)?s.toBig():new X(0))),u.copyWith({amount:n.lt(0)?0n:BigInt(n.toFixed())})}function be(u,t,e,s){let a=u.copyWith({amount:0n}).toBig().plus(u.isSame(t)?t.toBig():new X(0)).plus(u.toBig().lt(e.toBig())?e.toBig():new X(0));return s&&(a=a.plus(u.isSame(s)&&u.toBig().lt(s.toBig())?s.toBig():new X(0))),u.copyWith({amount:BigInt(a.toFixed())})}async function F(u,t){return t.isEvmParachain()?t.getDerivatedAddress(u):u}function we(u,t){return t?As.toBigInt(t,u):0n}import{addr as bs,AssetAmount as ws,Parachain as ve}from"@galacticcouncil/xc-core";import{big as vs}from"@galacticcouncil/common";var{EvmAddr:xs}=bs,U=class{adapter;config;constructor(t,e){this.adapter=t,this.config=e}async getEd(){let{chain:t}=this.config;if(t instanceof ve)return(await P.create(t)).getExistentialDeposit()}async getBalance(t){let{chain:e,route:s}=this.config,{source:n}=s,a=n.asset,r=e.getBalanceAssetId(a),i=xs.isValid(r.toString())?await F(t,e):t,o=s.source.balance.build({address:i,asset:a,chain:e});return this.adapter.getBalance(a,o)}async getMin(){let{chain:t,route:e}=this.config,{source:s}=e,n=s.asset,a=s.min;if(t instanceof ve&&a){let r=t.getMinAssetId(n),i=a.build({asset:r});return this.adapter.getBalance(n,i)}return this.getAssetMin()}async getAssetMin(){let{chain:t,route:e}=this.config,{source:s}=e,n=s.asset,a=t.getAssetMin(n),r=await this.getDecimals(n),i=0n;return a&&(i=vs.toBigInt(a,r)),ws.fromAsset(n,{amount:i,decimals:r})}async getDecimals(t){let{chain:e}=this.config,s=e.getAssetDecimals(t);return s||(await e.getCurrency()).decimals}};var{EvmAddr:Se}=Ss,J=class extends U{constructor(t,e){super(t,e)}async getCall(t){let{amount:e,sender:s,source:n}=t,a=await this.getTransfer(t);return this.adapter.buildCall(s,e,n.feeBalance,a)}async getDestinationFee(t){let{chain:e,route:s}=this.config,{source:n,destination:a,transact:r}=s,i=a.fee.amount,o=n.destinationFee.asset||a.fee.asset,c=await this.getDecimals(o);if(Number.isFinite(i))return{fee:kt.fromAsset(o,{amount:xe.toBigInt(i,c),decimals:c}),feeBreakdown:{}};let l=i,{amount:m,breakdown:d}=await l.build({feeAsset:o,transferAsset:n.asset,source:r?r.chain:e,destination:a.chain,amount:t});return{fee:kt.fromAsset(o,{amount:m,decimals:c}),feeBreakdown:d}}async getDestinationFeeBalance(t){let{chain:e,route:s}=this.config,{source:n,destination:a}=s,r=n.asset,i=n.destinationFee.asset||a.fee.asset;if(r.isEqual(i))return this.getBalance(t);let o=e.getBalanceAssetId(i),c=Se.isValid(o.toString())?await F(t,e):t,l=n.destinationFee.balance.build({address:c,asset:i,chain:e});return this.adapter.getBalance(i,l)}async getFee(t){let{chain:e,route:s}=this.config,{amount:n,sender:a,source:r}=t,i=await this.getTransfer(t),o=s.contract?await F(a,e):a,c=await this.adapter.estimateFee(o,n,r.feeBalance,i),{fee:l}=s.source,m=l?we(c.decimals,l.extra):0n,d=c.amount+m;return c.copyWith({amount:d})}async getFeeBalance(t){let{chain:e,route:s}=this.config,{source:n}=s;if(!n.fee)return this.getBalance(t);let a=await this.getFeeAsset(t),r=e.getBalanceAssetId(a),i=Se.isValid(r.toString())?await F(t,e):t,o=n.fee.balance.build({address:i,asset:a,chain:e});return this.adapter.getBalance(a,o)}async getFeeAsset(t){let{chain:e,route:s}=this.config,{source:n}=s,a=n.fee,r=n.asset;if(!a)return r;let i=a.asset;return e instanceof Ps&&"build"in i?await i.build({chain:e,address:t}):i}async getTransfer(t){let{chain:e,route:s}=this.config,{contract:n,extrinsic:a,program:r,move:i}=s;if(a){let{address:c,amount:l,asset:m,sender:d}=t,p=await(await P.create(e)).buildMessageId(d,l,m.originSymbol,c);return a.build({...t,messageId:p})}let o=n||r||i;if(o)return o.build({...t});throw new Error("AssetRoute transfer config is invalid! Specify contract, extrinsic, move or program instructions.")}async getTransact(t){let{route:e}=this.config,{transact:s}=e;if(s){let n=Object.assign({transact:{chain:s.chain}}),a={...t,...n};return{...await this.getTransactData(s,a),chain:s.chain}}}async getTransactData(t,e){let{chain:s,extrinsic:n}=t,a=await n.build(e),r=await P.create(s),i=a.getTx(r.client),o=e.source.chain,c=e.sender,l=Ts.getMultilocationDerivatedAccount(o.parachainId,c,s.parachainId===0?0:1,s.usesH160Acc),m=await i.getPaymentInfo(l),d=await i.getEncodedData(),[g,p]=await Promise.all([this.getTransactFee(t),this.getTransactFeeBalance(t,e)]);return{call:d,chain:s,fee:g,feeBalance:p,weight:{refTime:m.weight.ref_time,proofSize:m.weight.proof_size}}}async getTransactFee(t){let{fee:e}=t,s=await this.getDecimals(e.asset),n=xe.toBigInt(e.amount,s);return kt.fromAsset(e.asset,{amount:n,decimals:s})}async getTransactFeeBalance(t,e){let{chain:s}=this.config,{fee:n}=t,a=n.balance.build({address:e.sender,asset:n.asset,chain:s});return this.adapter.getBalance(n.asset,a)}};var G=class extends U{constructor(t,e){super(t,e)}};import{AssetAmount as Bs}from"@galacticcouncil/xc-core";var Y=class{ctx;constructor(t){this.ctx=t}get asset(){let{source:t}=this.ctx;return t.balance}get dex(){let{source:t}=this.ctx;return t.chain.dex}get destFee(){let{source:t,transact:e}=this.ctx;return e?e.fee:t.destinationFee}get destFeeBalance(){let{source:t,transact:e}=this.ctx;return e?e.feeBalance:t.destinationFeeBalance}get feeBalance(){let{source:t}=this.ctx;return t.feeBalance}async getSwap(t){let{asset:e,decimals:s}=await this.dex.chain.getCurrency(),{amount:n}=await this.dex.getQuote(e,t,t);return{aIn:t,aOut:Bs.fromAsset(e,{amount:n,decimals:s}),enabled:!0}}isSwapSupported(t){try{this.dex}catch{return!1}return!!(t&&t.swap)}async getDestinationSwap(t){let{amount:e,route:s}=await this.dex.getQuote(t,this.destFee,this.destFee),n=this.destFeeBalance.amount<this.destFee.amount,a=this.feeBalance.amount-t.amount>e*2n;return{aIn:t.copyWith({amount:e}),aOut:this.destFee,enabled:n&&a,route:s}}isDestinationSwapSupported(t){try{this.dex}catch{return!1}let e=!t.isSame(this.destFee),s=this.asset.isSame(this.destFee);return e&&!s}};var{EvmAddr:Vs}=Is,Ot=class{config;validations;constructor({configService:t,transferValidations:e}){this.config=t,this.validations=e||[]}async transfer(t,e,s,n,a){let r=Fs(this.config).assets().asset(t).source(s).destination(a).build();return this.getTransferData(r,e,n)}async remoteXcm(t,e,s,n,a={}){let r=this.config.getChain(e),i=this.config.getChain(s);if(!(r.isSubstrate()&&i.isSubstrate()))throw Error("RemoteXcm is supported only between parachains");let[c,l]=await Promise.all([P.create(r),P.create(i)]),m=new yt(c,l),d=Es.getMultilocationDerivatedAccount(r.parachainId,t,1,i.usesH160Acc),g=await l.getAsset(),p=await this.transfer(g,t,e,d,s);return m.remoteExec(t,d,n,f=>{let h=f.toDecimal();return p.buildCall(h)},a)}async getTransferData(t,e,s){let n=t.origin,a=t.reverse,r=new O(n.chain),i=new O(a.chain),o=new J(r,n),c=new G(i,a),l=new Ds(...this.validations),[m,d,g,p,f,h,x]=await Promise.all([o.getBalance(e),o.getFeeBalance(e),o.getDestinationFee(),o.getDestinationFeeBalance(e),o.getMin(),c.getBalance(s),c.getMin()]),{source:A,destination:y}=n.route,S=g.fee.copyWith(y.fee.asset),B=g.feeBreakdown,K=A.asset.isEqual(S)&&S.amount>10n?S.amount+1n:10n,C={address:s,amount:K,asset:A.asset,destination:{balance:h,chain:a.chain,fee:S,feeBreakdown:B},sender:e,source:{balance:m,chain:n.chain,fee:d.copyWith({amount:0n}),feeBalance:d,destinationFee:g.fee,destinationFeeBalance:p}};C.transact=await o.getTransact(C);let T=new Y(C),b=await o.getFee(C),E;T.isSwapSupported(A.fee)&&(E=await T.getSwap(b),C.source.feeSwap=E);let I;T.isDestinationSwapSupported(b)&&(I=await T.getDestinationSwap(b),C.source.destinationFeeSwap=I),(E||I)&&(b=await o.getFee(C),b=b.padByPct(5n));let Z=await c.getEd(),Pt=be(h,S,x,Z),w=await o.getEd(),tt=Ae(m,b,f,w);C.amount=0n,C.source.fee=b;let z={source:{balance:m,destinationFee:g.fee,destinationFeeBalance:p,destinationFeeSwap:I,fee:b,feeBalance:d,feeSwap:E,max:tt,min:m.copyWith({amount:Pt.amount})},destination:{balance:h,fee:S},async buildCall(R){let v=Object.assign({},C);return v.amount=Vt.toBigInt(R,m.decimals),v.transact=await o.getTransact(v),o.getCall(v)},async estimateFee(R){let v=Object.assign({},C);return v.amount=Vt.toBigInt(R,m.decimals),v.transact=await o.getTransact(v),o.getFee(v)},async estimateDestinationFee(R){let v=Vt.toBigInt(R,m.decimals),{fee:k,feeBreakdown:Ee}=await o.getDestinationFee(v);return C.destination.fee=k,C.destination.feeBreakdown=Ee,C.source.destinationFee=k,z.destination.fee=k,z.source.destinationFee=k,k},async validate(R){let v=Object.assign({},C),k=R||b.amount;return v.source.fee=b.copyWith({amount:k}),l.validate(v)}};return z}async subscribeBalance(t,e,s){let n=this.config.getChainRoutes(e),a=new O(n.chain),r=n.getUniqueRoutes().map(async({source:c})=>{let{asset:l,balance:m}=c,d=n.chain.getBalanceAssetId(l),g=Vs.isValid(d.toString())?await F(t,n.chain):t,p=m.build({address:g,asset:l,chain:n.chain});return a.subscribeBalance(l,p)}),i=await Promise.all(r);return Rs(i).pipe(ks(500)).subscribe(s)}};import{ConfigBuilder as Os}from"@galacticcouncil/xc-core";function _s(u){let t=Os(u.config).assets();return{assets:t,withAsset(e){let s=t.asset(e);return{sources:s,withSource(n){let a=s.source(n);return{destinations:a,withDestination(r){let{routes:i,destinationAssets:o,isAssetSelect:c,isTagSelect:l,build:m}=a.destination(r);return{routes:i,destinationAssets:o,isAssetSelect:c,isTagSelect:l,build({srcAddress:d,dstAddress:g,dstAsset:p,tag:f}){let h=m(p,f);return u.getTransferData(h,d,g)}}}}}}}}}import{Precompile as Ms}from"@galacticcouncil/xc-core";var Ns="https://api.wormholescan.io",St=class{_baseUrl;constructor(t){this._baseUrl=t||Ns}buildApi(t,e){return[this._baseUrl,t,"?"].join("")+new URLSearchParams(e).toString()}async getVaaBytes(t){let e=this.buildApi("/v1/signed_vaa/"+t,{});return await(await fetch(e)).json()}async getVaa(t){let e=this.buildApi("/api/v1/vaas/"+t,{});return(await(await fetch(e)).json()).data}async getVaaByTxHash(t){let e=this.buildApi("/api/v1/vaas/",{txHash:t}),n=await(await fetch(e)).json();if(n.data.length>0)return n.data[0];throw Error("Can't find VAA for given txHash: "+t)}async getOperations(t){let e=this.buildApi("/api/v1/operations/",t);return(await(await fetch(e)).json()).operations}async getOperation(t){let e=this.buildApi("/api/v1/operations/"+t,{});return await(await fetch(e)).json()}isMrlTransfer(t){let{payloadType:e,toAddress:s,toChain:n}=t,a="0x"+s.substring(26);return e===3&&n===16&&a===Ms.Bridge}};import{acc as Ws}from"@galacticcouncil/common";import{mrl as Us,ChainType as Te,Parachain as js,Precompile as Ks,Wormhole as j}from"@galacticcouncil/xc-core";import{encoding as zs}from"@wormhole-foundation/sdk-base";import{keccak256 as Hs}from"@wormhole-foundation/sdk-connect";import{deserialize as Ls}from"@wormhole-foundation/sdk-definitions";var Pe=(s=>(s[s.WaitingForVaa=0]="WaitingForVaa",s[s.VaaEmitted=1]="VaaEmitted",s[s.Completed=2]="Completed",s))(Pe||{});var $s=300*1e3,Be=class{parachainId;config;whScan;constructor(t,e){this.config=t,this.parachainId=e,this.whScan=new St}get chains(){let t=this.config.chains.values();return Array.from(t)}get filters(){let t=new Date,e=new Date;e.setDate(t.getDate()-6);let s=t.toISOString();return{page:"0",pageSize:"50",includeEndDate:"true",from:e.toISOString(),to:s}}async getWithdraws(t){let e=Ws.getMultilocationDerivatedAccount(this.parachainId,t,1,!0),n=(await this.whScan.getOperations({...this.filters,address:e})).map(async a=>{let{content:r}=a,{payload:i,standarizedProperties:o}=r,c=this.getStatus(a),l=this.chains.find(f=>f instanceof js&&f.parachainId===this.parachainId),{toAddress:m,tokenAddress:d}=o,g=this.chains.find(f=>j.isKnown(f)&&j.fromChain(f).getWormholeId()===i.tokenChain),p;if(c===1&&a.vaa){let{timestamp:f}=this.getVaaHeader(a.vaa.raw),h=a.vaa.raw;if(this.isStuck(f))switch(g.getType()){case Te.EvmChain:let x=new et(g);p=async y=>x.redeem(y,h);break;case Te.SolanaChain:let A=new pt(g);p=async y=>A.redeem(y,h);break}}return{asset:d,assetSymbol:a.data.symbol,amount:a.data.tokenAmount,from:t,fromChain:l,to:m,toChain:g,status:c,redeem:p,operation:a}});return Promise.all(n)}async getDeposits(t,e="hydration"){let s=await this.whScan.getOperations({...this.filters,address:Ks.Bridge,pageSize:"100"}),n=this.config.chains.get(e);if(!n)return[];let a=n,i=(await Us.createPayload(a,t)).toHex(),o=s.filter(c=>{let{content:l}=c,{payload:m}=l;return m.payloadType===3&&m.toChain===16&&"0x"+m.payload===i}).map(async c=>{let{content:l,sourceChain:m}=c,{payload:d,standarizedProperties:g}=l,p=this.getStatus(c),{tokenAddress:f}=g,h=this.chains.find(y=>j.isKnown(y)&&j.fromChain(y).getWormholeId()===d.tokenChain),x=this.chains.find(y=>j.isKnown(y)&&j.fromChain(y).getWormholeId()===d.toChain),A;if(p===1&&c.vaa){let{timestamp:y}=this.getVaaHeader(c.vaa.raw),S=c.vaa.raw;if(this.isStuck(y)){let B=new ft(x);A=async D=>B.redeemMrlViaXcm(D,S)}}return{asset:f,assetSymbol:c.data.symbol,amount:c.data.tokenAmount,from:m.from,fromChain:h,to:t,toChain:n,status:p,redeem:A,operation:c}});return Promise.all(o)}isStuck(t){return Date.now()>=t*1e3+$s}getVaaHeader(t){let e=zs.b64.decode(t),s=Ls("Uint8Array",e);return{timestamp:s.timestamp,emitterChain:s.emitterChain,emitterAddress:s.emitterAddress.toString(),sequence:s.sequence,payload:s.payload,hash:s.hash,id:Hs(s.hash)}}getStatus(t){return t.vaa?t.targetChain&&t.targetChain.status==="completed"?2:1:0}};export{jt as DISPATCH_ADDRESS,et as EvmClaim,it as EvmPlatform,Kt as EvmSigner,Y as FeeSwap,O as PlatformAdapter,pt as SolanaClaim,N as SolanaLilJit,mt as SolanaPlatform,se as SolanaSigner,ft as SubstrateClaim,yt as SubstrateExec,Ct as SubstratePlatform,P as SubstrateService,fe as SubstrateSigner,ye as SuiClaim,xt as SuiPlatform,Ce as SuiSigner,_s as TransferBuilder,Ot as Wallet,Pe as WhStatus,St as WormholeScan,Be as WormholeTransfer,Xt as chunkBySize,wr as deserializeV0,V as ixToHuman,$ as serializeV0};
|
|
1
|
+
import{acc as Nn,big as wt}from"@galacticcouncil/common";import{ConfigBuilder as Kn,TransferValidator as Hn}from"@galacticcouncil/xc-core";import{ChainType as j}from"@galacticcouncil/xc-core";import{Abi as he,Wormhole as ye}from"@galacticcouncil/xc-core";import{encodeFunctionData as Ce}from"viem";import{encoding as St}from"@wormhole-foundation/sdk-base";var Q=class{#t;constructor(t){this.#t=t}redeem(t,e){let s=ye.fromChain(this.#t),n=St.b64.decode(e),a=St.hex.encode(n),r=he.TokenBridge,o=Ce({abi:r,functionName:"completeTransfer",args:["0x"+a]});return{abi:JSON.stringify(r),data:o,from:t,to:s.getTokenBridge()}}};import{Abi as ve,CallType as Et,Erc20Client as Se}from"@galacticcouncil/xc-core";import{ContractFunctionExecutionError as Ae,decodeEventLog as xe}from"viem";var Y=class{client;config;constructor(t,e){this.validateClient(t),this.client=t,this.config=e}validateClient(t){if(!t)throw new Error("No EVM client found")}get abi(){return this.config.abi}get asset(){let t=this.config.args,[e]=t;return e}get calldata(){return this.config.encodeFunctionData()}async estimateGas(t){let{address:e,args:s,value:n,func:a}=this.config;return await this.client.getProvider().estimateContractGas({address:e,abi:this.abi,functionName:a,args:s,value:n,account:t})}async estimateFee(t,e){if(e===0n)return 0n;try{let s=await this.estimateGas(t),n=await this.getGasPrice();return s*n}catch(s){return s instanceof Ae?console.log(`Can't estimate fees!
|
|
2
|
+
`,s.message):console.log(s),0n}}async getGasPrice(){return this.client.getProvider().getGasPrice()}async getNonce(t){return this.client.getProvider().getTransactionCount({address:t})}async simulateCall(t){let{address:e,args:s,value:n,func:a}=this.config,r=this.client.getProvider(),o=await this.getNonce(t);try{let{results:m}=await r.simulateCalls({account:t,calls:[{to:e,abi:this.abi,functionName:a,args:s,value:n}],stateOverrides:[{address:t,nonce:o}]}),[i]=m;return i}catch(m){return console.log(`Can't simulate call!
|
|
3
|
+
`,m.details),{error:m}}}decodeEvents(t){let e=[];return t&&t.forEach(s=>{try{let{eventName:n,args:a}=xe({abi:this.abi,data:s.data,topics:s.topics});e.push({eventName:n,args:a})}catch{}}),e}};var K=class{static get(t,e){return new Y(t,e)}};import{Precompile as be}from"@galacticcouncil/xc-core";import{decodeAbiParameters as we}from"viem";function ft(c){return c.module==="Snowbridge"&&c.func==="v2_sendMessage"}function Pt(c){if(!ft(c))return;let t=c.args[1];if(!t||t.length===0)return;let[e,s]=we([{type:"uint8"},{type:"address"},{type:"uint128"}],t[0]);return s}function Tt(c){let t=c.module==="Snowbridge"&&c.func==="v2_sendMessage"&&Array.isArray(c.args[1])&&c.args[1].length===0,e=c.module==="Snowbridge"&&c.func==="sendToken"&&c.args[0]==="0x0000000000000000000000000000000000000000";return c.module==="TokenBridge"&&["wrapAndTransferETHWithPayload","wrapAndTransferETH"].includes(c.func)||t||e}function Bt(c){return Object.entries(be).map(([e,s])=>s).includes(c.address)}var Z=class{#t;constructor(t){this.#t=t.evmClient}async buildCall(t,e,s,n){let a=K.get(this.#t,n),{abi:r,asset:o,calldata:m}=a,i={abi:JSON.stringify(r),data:m,from:t,to:n.address,type:Et.Evm,value:n.value,dryRun:async()=>{let{error:p,logs:f}=await a.simulateCall(t),y=a.decodeEvents(f);return{call:n.module+"."+n.func,error:p?.shortMessage,events:y}}};if(Bt(n)||Tt(n))return i;let l=ft(n)?Pt(n):o,u=new Se(this.#t,l),d=await u.allowance(t,n.address);if(d>=e)return i;let g=u.approve(n.address,e);return{abi:JSON.stringify(ve.Erc20),allowance:d,data:g,from:t,to:l,type:Et.Evm,dryRun:()=>{}}}async estimateFee(t,e,s,n){let r=await K.get(this.#t,n).estimateFee(t,e);return s.copyWith({amount:r})}};import{EvmParachain as Pe}from"@galacticcouncil/xc-core";import{h160 as Te}from"@galacticcouncil/common";import{Binary as Be}from"polkadot-api";var Ft="0x0000000000000000000000000000000000000401",{H160:Ee}=Te,It=class{#t;#e;#n;constructor(t,e){this.#t=t,this.#e=t.evmClient,this.#n=e}async signAndSend(t,e){let s=Ee.fromAny(t.from),n=this.#e.getProvider(),a=!1;if(this.#t instanceof Pe)try{let o=this.#t.client,m=Be.fromHex(t.data);await o.getUnsafeApi().txFromCallData(m),a=!0}catch{}let r;if(a){let[o,m]=await Promise.all([n.estimateGas({account:s,data:t.data,to:Ft}),n.getGasPrice()]),i=m+m/100n*10n;r=await this.#n.sendTransaction({account:s,chain:this.#e.chain,data:t.data,maxPriorityFeePerGas:i,maxFeePerGas:i,gas:o*11n/10n,to:Ft})}else{let{data:o,to:m,value:i}=t,[l,u]=await Promise.all([n.estimateGas({account:s,data:o,to:m,value:i}),n.getGasPrice()]),d=u+u*5n/100n,g=l+l*30n/100n;r=await this.#n.sendTransaction({account:s,chain:this.#e.chain,data:o,to:m,value:i,gas:g,maxFeePerGas:d,maxPriorityFeePerGas:d})}e.onTransactionSend(r),n.waitForTransactionReceipt({hash:r}).then(o=>e.onTransactionReceipt(o)).catch(o=>e.onError(o))}};import{CallType as ke}from"@galacticcouncil/xc-core";import{Buffer as _e}from"buffer";import{ComputeBudgetProgram as Dt,PublicKey as Fe,TransactionMessage as Ie,VersionedTransaction as Rt}from"@solana/web3.js";var kt=.5,_t=2,Vt=1,Ot=1e6,De=25e4,tt=class{connection;config;constructor(t,e){this.validateConnection(t),this.connection=t,this.config=e}validateConnection(t){if(!t)throw new Error("No connection found")}async getPriorityMessage(t){let{instructions:e}=this.config,s=await this.getV0Message(t,e),n=await this.createPriorityFeeInstructions(s);return this.getV0Message(t,[...e,...n])}async estimateFee(t,e){if(e===0n)return 0n;let{instructions:s}=this.config,n=await this.getV0Message(t,s),a=await this.determineComputeBudget(n);return BigInt(a)}async getV0Message(t,e){let s=new Fe(t),{blockhash:n}=await this.connection.getLatestBlockhash("finalized");return new Ie({payerKey:s,recentBlockhash:n,instructions:e}).compileToV0Message()}async createPriorityFeeInstructions(t,e=kt,s=_t,n=Vt,a=Ot){let[r,o]=await Promise.all([this.determineComputeBudget(t),this.determinePriorityFee(t,e,s,n,a)]);return[Dt.setComputeUnitLimit({units:r}),Dt.setComputeUnitPrice({microLamports:o})]}async simulateTransaction(t,e){let s=new Rt(e);return(await this.connection.simulateTransaction(s,{accounts:{encoding:"base64",addresses:[t]}})).value}async determineComputeBudget(t){let e=new Rt(t),s=await this.connection.simulateTransaction(e),{err:n,unitsConsumed:a}=s.value;return a&&!n?Math.round(a*1.2):De}async determinePriorityFee(t,e=kt,s=_t,n=Vt,a=Ot){let r=n,o=await this.getTxAccounts(t),m=await this.connection.getRecentPrioritizationFees({lockedWritableAccounts:o});if(m){let i=m.map(u=>u.prioritizationFee).filter(u=>u>0).sort((u,d)=>u-d),l=Math.ceil(i.length*e);if(i.length>l){let d=i[l]*s;r=Math.max(r,d)}}return Math.min(Math.max(r,n),a)}async getTxAccounts(t){let e=(await Promise.all(t.addressTableLookups.map(n=>this.connection.getAddressLookupTable(n.accountKey)))).map(n=>n.value).filter(n=>n!==null),s=t.getAccountKeys({addressLookupTableAccounts:e??void 0});return t.compiledInstructions.flatMap(n=>n.accountKeyIndexes).map(n=>t.isAccountWritable(n)?s.get(n):null).filter(n=>n!==null)}};var H=class{static get(t,e){return new tt(t,e)}};import{MessageV0 as Re}from"@solana/web3.js";function _(c){return c.map(t=>({program:t.programId.toBase58(),data:t.data.toString("hex"),keys:t.keys.map(e=>e.pubkey.toBase58())}))}function Mt(c,t=1e3){let e=[],s=[],n=0;for(let a of c){let r=a.data?.length??0;s.length&&n+r>t&&(e.push(s),s=[],n=0),s.push(a),n+=r}return s.length&&e.push(s),e}function U(c){let t=c.serialize();return Buffer.from(t).toString("hex")}function Ys(c){let t=Buffer.from(c,"hex"),e=Uint8Array.from(t);return Re.deserialize(e)}var et=class{#t;constructor(t){this.#t=t.connection}async buildCall(t,e,s,n){let a=H.get(this.#t,n),r=await a.getPriorityMessage(t),o=r.serialize(),m=_e.from(o).toString("hex");return{from:t,data:m,ix:_(n.instructions),signers:n.signers,type:ke.Solana,dryRun:async()=>{let{err:i,logs:l}=await a.simulateTransaction(t,r);return{call:n.module+"."+n.func,error:i,events:l}}}}async estimateFee(t,e,s,n){let a=H.get(this.#t,n),r=await a.estimateFee(t,e),o=await a.getPriorityMessage(t),{accounts:m}=await a.simulateTransaction(t,o),l=(m&&m[0])?.lamports;if(l){let u=n.module==="TokenBridge"&&n.func==="TransferNativeWithPayload";return s.copyWith({amount:s.amount-BigInt(l)-(u?e:0n)+n.rentReserve})}return s.copyWith({amount:r+n.rentReserve})}};import{CallType as nt,Wormhole as Ve}from"@galacticcouncil/xc-core";import{Keypair as Wt,PublicKey as z,SystemProgram as Nt,TransactionMessage as Oe}from"@solana/web3.js";import{ACCOUNT_SIZE as Me,NATIVE_MINT as st,TOKEN_PROGRAM_ID as We,createAssociatedTokenAccountIdempotentInstruction as Kt,createCloseAccountInstruction as Ne,createInitializeAccountInstruction as Ke,createTransferInstruction as He,getAssociatedTokenAddressSync as Ue,getMinimumBalanceForRentExemptAccount as ze,getMint as je}from"@solana/spl-token";import{utils as Le}from"@wormhole-foundation/sdk-solana";import{utils as Ht}from"@wormhole-foundation/sdk-solana-core";import{encoding as $e}from"@wormhole-foundation/sdk-base";import{deserialize as Ut}from"@wormhole-foundation/sdk-definitions";import{createCompleteTransferNativeInstruction as zt,createCompleteTransferWrappedInstruction as Ge}from"@wormhole-foundation/sdk-solana-tokenbridge";var V=class{#t;constructor(t){this.#t=t.connection}async sendBundle(t){let{result:e}=await this.#t._rpcRequest("sendBundle",[t]);return e}async simulateBundle(t){return(await this.#t._rpcRequest("simulateBundle",[[t]])).result}async getInflightBundleStatuses(t){let{result:e}=await this.#t._rpcRequest("getInflightBundleStatuses",[t]);return e}async getRegion(){let{result:t}=await this.#t._rpcRequest("getRegions",[]);return t}async getTipAccount(){let{result:t}=await this.#t._rpcRequest("getTipAccounts",[]);return t}};var at=class{#t;#e;#n;constructor(t){this.#t=t,this.#e=t.connection,this.#n=new V(t)}async redeem(t,e,s){let n=Ve.fromChain(this.#t),a=$e.b64.decode(e),r=Ut("TokenBridge:Transfer",a),o=Ut("Uint8Array",a),m=this.derivePostedVaaKey(n.getCoreBridge(),Buffer.from(r.hash)),i=new z(t),l=s?new z(s):i,u=i.equals(l),d=[];if(!await this.#e.getAccountInfo(m)){let h=Wt.generate(),I=await Ht.createVerifySignaturesInstructions(this.#t.connection,n.getCoreBridge(),i,o,h.publicKey),S=Mt(I,1e3);for(let C=0;C<S.length;C++){let T=S[C],b=await this.getV0Message(i,T),F=U(b);d.push({from:t,data:F,ix:_(T),signers:[h],type:nt.Solana})}let B=Ht.createPostVaaInstruction(this.#e,n.getCoreBridge(),i,o,h.publicKey),J=await this.getV0Message(i,[B]),E=U(J);d.push({from:t,data:E,ix:_([B]),type:nt.Solana})}let p=r.payload.token.chain==="Solana",f=new z(r.payload.token.address.toUint8Array()),y=p&&f.equals(st),x=await this.#n.getTipAccount(),A=Nt.transfer({fromPubkey:i,toPubkey:new z(x[0]),lamports:1e3});if(y&&u){let h=await this.redeemAndUnwrap(n,i,r,A);d.push(h)}else{let h=await this.redeemToken(n,i,l,f,p,r,A);d.push(h)}return d}async redeemToken(t,e,s,n,a,r,o){let i=(a?zt:Ge)(this.#e,t.getTokenBridge(),t.getCoreBridge(),e,r),l=Ue(n,s),u=Kt(e,l,s,n),d=await this.getV0Message(e,[u,i,o]),g=U(d);return{from:e.toBase58(),data:g,ix:_([u,i]),type:nt.Solana}}async redeemAndUnwrap(t,e,s,n){let a=new z(s.payload.to.address.toUint8Array()),r=await je(this.#e,st),o=s.payload.token.amount*BigInt(Math.pow(10,r.decimals-8)),m=await ze(this.#e),i=Wt.generate(),l=Kt(e,a,e,st),u=zt(this.#e,t.getTokenBridge(),t.getCoreBridge(),e,s),d=Nt.createAccount({fromPubkey:e,newAccountPubkey:i.publicKey,lamports:m,space:Me,programId:We}),g=Ke(i.publicKey,st,e),p=He(a,i.publicKey,e,o),f=Ne(i.publicKey,e,e),y=[l,u,d,g,p,f,n],x=await this.getV0Message(e,y),A=U(x);return{from:e.toBase58(),data:A,ix:_(y),signers:[i],type:nt.Solana}}derivePostedVaaKey(t,e){return Le.deriveAddress([Buffer.from("PostedVAA"),e],t)}async getV0Message(t,e){let{blockhash:s}=await this.#e.getLatestBlockhash("finalized");return new Oe({payerKey:t,recentBlockhash:s,instructions:e}).compileToV0Message()}};import{Keypair as jt,MessageV0 as Xe,VersionedTransaction as Je}from"@solana/web3.js";import{Buffer as ht}from"buffer";var Lt=class{#t;#e;#n;constructor(t,e){this.#t=t,this.#e=e,this.#n=new V(t)}async signAndSend(t,e){let{data:s,signers:n}=t,a=this.toVersioned(s,n);try{if(this.#e instanceof jt){a.sign([this.#e]);let i=await this.#t.connection.sendTransaction(a);e.onTransactionSend(i);let l=await this.#t.connection.getSignatureStatus(i);e.onStatus?.(l);return}let r=this.#e;await r.connect(),n&&a.sign(n);let{signature:o}=await r.signAndSendTransaction(a);e.onTransactionSend(o);let m=await this.#t.connection.getSignatureStatus(o);e.onStatus?.(m)}catch(r){e.onError(r)}}async signAndSendAll(t,e){let s=t.map(n=>{let{data:a,signers:r}=n;return this.toVersioned(a,r)});try{let n;if(this.#e instanceof jt)s.forEach(m=>m.sign([this.#e])),n=s.map(m=>ht.from(m.serialize()).toString("base64"));else{let m=this.#e;await m.connect(),n=(await m.signAllTransactions(s)).map(l=>ht.from(l.serialize()).toString("base64"))}let a=await this.#n.simulateBundle(n);if(a.value.summary!=="succeeded")throw new Error("Bundle simulation failed! "+JSON.stringify(a,null,2));let r=await this.#n.sendBundle(n);e.onTransactionSend(r);let o=await this.#n.getInflightBundleStatuses([r]);e.onBundleStatus?.(o.value)}catch(n){e.onError(n)}}toVersioned(t,e){let s=ht.from(t,"hex"),n=Uint8Array.from(s),a=Xe.deserialize(n),r=new Je(a);return e&&r.sign(e),r}};import{Abi as qe,CallType as Qe,Precompile as Ye,Wormhole as Ze}from"@galacticcouncil/xc-core";import{encoding as $t}from"@wormhole-foundation/sdk-base";import{encodeFunctionData as tn}from"viem";import{Binary as Gt}from"polkadot-api";var rt=class{#t;constructor(t){this.#t=t,Ze.fromChain(this.#t)}redeemMrl(t,e){let s=$t.b64.decode(e),n=$t.hex.encode(s),a=qe.Gmp,r=tn({abi:a,functionName:"wormholeTransferERC20",args:["0x"+n]});return{abi:JSON.stringify(a),data:r,from:t,to:Ye.Bridge}}async redeemMrlViaXcm(t,e){let n=this.#t.client.getUnsafeApi(),a=this.redeemMrl(t,e),o=await n.tx.EthereumXcm.transact({xcm_transaction:{type:"V2",value:{gas_limit:[5000000n,0n,0n,0n],action:{type:"Call",value:a.to},value:[0n,0n,0n,0n],input:Gt.fromHex(a.data),access_list:void 0}}}).getEncodedData();return{data:Gt.toHex(o),from:t,type:Qe.Substrate,dryRun:async()=>{},txOptions:void 0}}};import{AssetAmount as rn,CallType as on}from"@galacticcouncil/xc-core";import{Binary as it}from"polkadot-api";import{big as en}from"@galacticcouncil/common";async function Xt(c,t,e){let s=await e.getDecimals(),n=e.chain.getAssetDecimals(t)??s,a=e.chain.usesChainDecimals?s:n;return{amount:en.convertDecimals(c,a,n),decimals:n}}import{enums as nn}from"@galacticcouncil/common";var Jt=c=>{let t=[];for(let e of c)if(["PolkadotXcm"].includes(e.type)&&e.value.type==="FeesPaid"){let n=e.value.value.fees;for(let a of n)if(a.fun.type==="Fungible"){let r=BigInt(a.fun.value);t.push(r)}}return t.reduce((e,s)=>e+s,0n)},O=c=>{let t=c.value.error;return t.type==="Module"?nn.enumPath(t.value):JSON.stringify(t.value)};import{xcm as yt}from"@galacticcouncil/common";function sn(c){return{parents:0,interior:{type:"X1",value:c.startsWith("0x")?yt.toAccountKey20(c):yt.toAccountId32(c)}}}function qt(c){return{type:"V4",value:{parents:1,interior:{type:"X1",value:{type:"Parachain",value:c.parachainId}}}}}var an=(c,t)=>({id:yt.transform(c),fun:{type:"Fungible",value:t}}),Qt=(c,t,e,s,n,a)=>{console.log(a);let r=sn(c),o=an(t,e.amount);return{type:"V4",value:[{type:"WithdrawAsset",value:[o]},{type:"BuyExecution",value:{fees:o,weight_limit:{type:"Unlimited"}}},{type:"Transact",value:{origin_kind:{type:"SovereignAccount"},require_weight_at_most:{ref_time:s,proof_size:n},call:a}},{type:"RefundSurplus",value:void 0},{type:"DepositAsset",value:{assets:{type:"Wild",value:{type:"AllCounted",value:1}},beneficiary:r}}]}};var ot=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}async remoteExec(t,e,s,n,a={}){let r=this.#t.api,o=await this.#t.getAsset(),m=this.#e.api,i=this.#e.chain,l=await i.getCurrency(),u=l.asset,d=l.decimals,g=i.getAssetXcmLocation(u),p=it.fromHex(s.data),y=await(await m.txFromCallData(p)).getPaymentInfo(e),x=BigInt(y.partial_fee)*120n/100n,A=rn.fromAsset(u,{amount:x,decimals:d}),h=y.weight.ref_time,I=y.weight.proof_size,S=qt(i),B=Qt(e,g,A,h,I,p),J=r.tx.PolkadotXcm.send({dest:S,message:B}),E=[];try{let w=await this.#t.chain.dex.getCalldata(t,a.srcFeeAsset||o,u,A,10),q=it.fromHex(w),gt=await r.txFromCallData(q);E.push(gt)}catch{}let C=await n(A),T=it.fromHex(C.data),b=await r.txFromCallData(T);E.push(b),E.push(J);let F=E.map(w=>w.decodedCall),D=r.tx.Utility.batch_all({calls:F}),dt=await D.getEncodedData();return{from:t,data:it.toHex(dt),type:on.Substrate,dryRun:this.#t.isDryRunSupported()?async()=>{try{let w=await this.#t.dryRun(t,D);return{call:"polkadotXcm.send",error:w.execution_result&&w.execution_result.success?void 0:O(w.execution_result),events:w.emitted_events||[],xcm:w.forwarded_xcms||[]}}catch(w){return{call:"polkadotXcm.send",error:w instanceof Error?w.message:"unknown"}}}:()=>{}}}};import{Asset as pn,AssetAmount as fn,CallType as hn}from"@galacticcouncil/xc-core";import{Binary as yn}from"polkadot-api";import{addr as cn,multiloc as Ct}from"@galacticcouncil/xc-core";import{acc as un,enums as mn}from"@galacticcouncil/common";import{Blake2256 as ln,u32 as dn}from"@polkadot-api/substrate-bindings";import{toHex as gn,fromHex as Yt}from"@polkadot-api/utils";import{Enum as Zt}from"polkadot-api";var{Ss58Addr:te}=cn,P=class c{chain;_currency;constructor(t){this.chain=t}static async create(t){return new c(t)}get client(){return this.chain.client}get api(){return this.client.getUnsafeApi()}async getCurrency(){return this._currency||(this._currency=this.chain.getCurrency()),this._currency}async getAsset(){return(await this.getCurrency()).asset}async getDecimals(){return(await this.getCurrency()).decimals}isDryRunSupported(){return this.api.apis?.DryRunApi!==void 0}async buildMessageId(t,e,s,n){let a=await this.client._request("system_accountNextIndex",[t]),r=dn.enc(a),o=l=>new TextEncoder().encode(l),m=new Uint8Array([...o(this.chain.parachainId.toString()),...Yt(t.startsWith("0x")?t.slice(2):t),...r,...Yt(s.startsWith("0x")?s.slice(2):s),...o(n),...o(e.toString())]),i=ln(m);return gn(i)}async dryRun(t,e){let s=Zt("Signed",t),n=Zt("system",s),a=await this.api.apis.DryRunApi.dry_run_call(n,e.decodedCall,4);if(!a.success)throw new Error("DryRun call failed");let r=a.value;if("type"in r&&"value"in r)throw new Error("DryRun call error: "+mn.enumPath(r.value));return r}async estimateNetworkFee(t,e){let s=e.getTx(this.client);try{let n=await s.getPaymentInfo(t);return BigInt(n.partial_fee)}catch{console.warn("Can't estimate network fee.")}return 0n}async estimateDeliveryFee(t,e){if(this.chain.usesDeliveryFee){let s=await this.estimateDeliveryFeeWith(t,e);try{let n=e.getTx(this.client),a=await this.dryRun(s,n);if(a.execution_result?.success)return Jt(a.emitted_events||[]);{let r=O(a.execution_result);console.warn(`Can't estimate delivery fee. Reason:
|
|
4
|
+
${r}`)}}catch{}}return 0n}async estimateDeliveryFeeWith(t,e){if(["PolkadotXcm"].includes(e.module)){let n=e.getTx(this.client).decodedCall.value.value,a="dest"in n?n.dest:void 0;if(!a)return t;let r=Ct.findNestedKey(a,"interior"),o=Ct.findParachain(a);if(Ct.findGlobalConsensus(a))return t;if(o){let i=un.getSovereignAccounts(o);return this.chain.parachainId===0?te.encodePubKey(i.relay):te.encodePubKey(i.generic)}if(r&&r.interior==="Here")return this.chain.treasury||t}return t}};var ct=class{#t;constructor(t){this.#t=P.create(t)}async useSignerFee(t){let e=await this.#t,s=await e.getAsset();return e.chain.usesSignerFee&&!s.isEqual(t)}async buildCall(t,e,s,n){let a=await this.#t,o=await this.useSignerFee(s)?{asset:new pn(s)}:void 0,m=n.getTx(a.client),i=n.module+"."+n.func,l=await m.getEncodedData();return{from:t,data:yn.toHex(l),type:hn.Substrate,txOptions:o,dryRun:a.isDryRunSupported()?async()=>{try{let u=n.getTx(a.client),d=await a.dryRun(t,u),g=d.execution_result&&d.execution_result.success?void 0:O(d.execution_result);return{call:i,error:g,events:d.emitted_events||[],xcm:d.forwarded_xcms||[]}}catch(u){return{call:i,error:u instanceof Error?u.message:"unknown"}}}:()=>{}}}async estimateFee(t,e,s,n){let a=await this.#t,r=await a.estimateNetworkFee(t,n),o=await a.estimateDeliveryFee(t,n),m=await this.exchangeFee(r+o,s),i=await Xt(m,s,a);return s.copyWith(i)}async exchangeFee(t,e){let s=await this.#t,n=await s.getAsset(),a=await s.getDecimals();if(n.isEqual(e))return t;try{let r=s.chain.dex,o=fn.fromAsset(n,{amount:t,decimals:a});return(await r.getQuote(e,n,o,!0)).amount}catch{}return t}};import{multiloc as ee}from"@galacticcouncil/xc-core";import{Binary as Cn,Enum as At}from"polkadot-api";var ne=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}signAndSend(t,e){let n=this.#t.client.getUnsafeApi(),a=Cn.fromHex(t.data),r={};t.txOptions?.asset&&(r={asset:this.getFeeAsset(t.txOptions.asset)}),n.txFromCallData(a).then(o=>{o.signSubmitAndWatch(this.#e,r).subscribe({next:m=>{m.type==="broadcasted"&&e.onTransactionSend(m.txHash),m.type==="finalized"&&e.onFinalized(m)},error:m=>{e.onError(m)}})})}getFeeAsset(t){let e=this.#t.getAssetXcmLocation(t);if(e){let s=ee.findPalletInstance(e),n=ee.findGeneralIndex(e);return{parents:0,interior:At("X2",[At("PalletInstance",Number(s)),At("GeneralIndex",BigInt(n))])}}throw new Error("Asset location not found")}};import{CallType as xn,Wormhole as bn}from"@galacticcouncil/xc-core";import{Transaction as wn}from"@mysten/sui/transactions";import{SUI_CLOCK_OBJECT_ID as vn}from"@mysten/sui/utils";import{toBase64 as Sn}from"@mysten/bcs";import{encoding as Pn,serialize as Tn,toChainId as Bn}from"@wormhole-foundation/sdk-connect";import{deserialize as En}from"@wormhole-foundation/sdk-definitions";import{getPackageId as se}from"@wormhole-foundation/sdk-sui";import{getTokenCoinType as Fn}from"@wormhole-foundation/sdk-sui-tokenbridge";import{fromBase64 as An}from"@mysten/bcs";function ut(c,t={}){let e=c.inputs??[],s=c.commands??[],n=t.numbers??"string",a=t.decode32As??"address",r=l=>n==="bigint"?l:n==="number"?Number(l):l.toString(),o=l=>{let u=An(l),d=g=>{let p=0n;for(let f=0;f<g;f++)p|=BigInt(u[f])<<8n*BigInt(f);return p};return u.length===1?{type:"pure",valueType:"u8",value:Number(u[0])}:u.length===2?{type:"pure",valueType:"u16",value:r(d(2))}:u.length===4?{type:"pure",valueType:"u32",value:Number(d(4))}:u.length===8?{type:"pure",valueType:"u64",value:r(d(8))}:u.length===32&&a==="address"?{type:"pure",valueType:"address",value:"0x"+[...u].map(p=>p.toString(16).padStart(2,"0")).join("")}:{type:"pure",valueType:"vector<u8>",value:Array.from(u)}},m=l=>{let u=e[l];if(!u)return{Input:l};if(u.Pure?.bytes)return o(u.Pure.bytes);let d=u.Object?.SharedObject;if(d)return{type:"object",objectType:"sharedObject",objectId:d.objectId,initialSharedVersion:String(d.initialSharedVersion),mutable:!!d.mutable};let g=u.Object?.ImmOrOwnedObject;return g?{type:"object",objectType:"immOrOwnedObject",objectId:g.objectId,version:String(g.version),digest:g.digest??void 0}:{Input:l}},i=l=>l?.GasCoin?"GasCoin":Array.isArray(l?.NestedResult)?l:typeof l?.Input=="number"?m(l.Input):l;return s.map(l=>{if(l.MoveCall){let u=l.MoveCall;return{MoveCall:{...u,arguments:(u.arguments??[]).map(i)}}}if(l.SplitCoins){let u=l.SplitCoins,d=u.coin?.GasCoin?"GasCoin":i(u.coin),g=(u.amounts??[]).map(i);return{SplitCoins:[d,g]}}if(l.MergeCoins){let u=l.MergeCoins;return{MergeCoins:{...u,destination:i(u.destination),sources:(u.sources??[]).map(i)}}}if(l.TransferObjects){let u=l.TransferObjects;return{TransferObjects:{...u,objects:(u.objects??[]).map(i),address:i(u.address)}}}return l})}var ae=class{#t;constructor(t){this.#t=t}async redeem(t,e){let s=bn.fromChain(this.#t),n=this.#t.client,a=Pn.b64.decode(e),r=En("TokenBridge:Transfer",a),o=s.getCoreBridge(),m=s.getTokenBridge(),i=await Fn(n,m,r.payload.token.address.toUint8Array(),Bn(r.payload.token.chain));if(!i)throw new Error("Unable to fetch token coinType");let[l,u]=await Promise.all([se(n,o),se(n,m)]),d=new wn;d.setSender(t);let[g]=d.moveCall({target:`${l}::vaa::parse_and_verify`,arguments:[d.object(o),d.pure.vector("u8",Tn(r)),d.object(vn)]}),[p]=d.moveCall({target:`${u}::vaa::verify_only_once`,arguments:[d.object(m),g]}),[f]=d.moveCall({target:`${u}::complete_transfer::authorize_transfer`,arguments:[d.object(m),p],typeArguments:[i]}),[y]=d.moveCall({target:`${u}::complete_transfer::redeem_relayer_payout`,arguments:[f],typeArguments:[i]});d.moveCall({target:`${u}::coin_utils::return_nonzero`,arguments:[y],typeArguments:[i]});let x=await d.build({client:n}),A=await d.toJSON(),h=ut(JSON.parse(A));return{from:t,commands:h,data:Sn(x),type:xn.Sui}}};import{CallType as In}from"@galacticcouncil/xc-core";import{toBase64 as Dn}from"@mysten/bcs";var mt=class{#t;constructor(t){this.#t=t.client}async buildCall(t,e,s,n){let{transaction:a}=n;a.setSender(t);let r=await a.build({client:this.#t}),o=await a.toJSON(),m=ut(JSON.parse(o));return{from:t,commands:m,data:Dn(r),type:In.Sui,dryRun:async()=>{let i=await this.#t.dryRunTransactionBlock({transactionBlock:r});return{call:n.module+"."+n.func,error:i.executionErrorSource}}}}async estimateFee(t,e,s,n){let{transaction:a}=n;a.setSender(t);let r=await a.build({client:this.#t}),m=(await this.#t.dryRunTransactionBlock({transactionBlock:r})).effects.gasUsed,i=BigInt(m.computationCost),l=BigInt(m.storageCost),u=i+l;return s.copyWith({amount:u})}};import{Ed25519Keypair as Rn}from"@mysten/sui/keypairs/ed25519";import{Transaction as kn}from"@mysten/sui/transactions";var re=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}async signAndSend(t,e){let{from:s,data:n}=t,a=this.#t.client;try{if(this.#e instanceof Rn){let m=kn.from(n),i=await a.signAndExecuteTransaction({signer:this.#e,transaction:m,options:{showEffects:!0,showEvents:!0,showObjectChanges:!0,showBalanceChanges:!0}});e.onTransactionSend(i.digest);return}let r=await this.#e.signTransaction({transaction:n,address:s,networkID:"sui:mainnet"}),o=await a.executeTransactionBlock({transactionBlock:r.transaction,signature:r.signature,options:{showEffects:!0,showEvents:!0,showObjectChanges:!0,showBalanceChanges:!0}});e.onTransactionSend(o.digest)}catch(r){e.onError(r)}}};var M=class{platform={};constructor(t){switch(t.getType()){case j.EvmChain:this.registerEvm(t);break;case j.EvmParachain:this.registerEvm(t),this.registerSubstrate(t);break;case j.Parachain:this.registerSubstrate(t);break;case j.SolanaChain:this.registerSolana(t);break;case j.SuiChain:this.registerSui(t);break;default:throw new Error("Unsupported platform: "+t.getType())}}registerEvm(t){let e=t;this.platform.Evm=new Z(e)}registerSolana(t){let e=t;this.platform.Solana=new et(e)}registerSui(t){let e=t;this.platform.Sui=new mt(e)}registerSubstrate(t){let e=t;this.platform.Substrate=new ct(e)}async buildCall(t,e,s,n){return this.platform[n.type].buildCall(t,e,s,n)}async estimateFee(t,e,s,n){return this.platform[n.type].estimateFee(t,e,s,n)}};import{AssetAmount as bt,Parachain as On}from"@galacticcouncil/xc-core";import{acc as Mn,big as le}from"@galacticcouncil/common";import{big as _n}from"@galacticcouncil/common";import L from"big.js";function ie(c,t,e,s){let n=c.toBig().minus(e.toBig()).minus(c.isSame(t)?t.toBig():new L(0));return s&&(n=n.minus(c.isSame(s)?s.toBig():new L(0))),c.copyWith({amount:n.lt(0)?0n:BigInt(n.toFixed())})}function oe(c,t,e,s){let a=c.copyWith({amount:0n}).toBig().plus(c.isSame(t)?t.toBig():new L(0)).plus(c.toBig().lt(e.toBig())?e.toBig():new L(0));return s&&(a=a.plus(c.isSame(s)&&c.toBig().lt(s.toBig())?s.toBig():new L(0))),c.copyWith({amount:BigInt(a.toFixed())})}async function ce(c,t){return t.isEvmParachain()?t.getDerivatedAddress(c):c}function ue(c,t){return t?_n.toBigInt(t,c):0n}async function xt(c,t){let e=c.getAssetDecimals(t);return e||(await c.getCurrency()).decimals}import{AssetAmount as Vn,Parachain as me}from"@galacticcouncil/xc-core";var W=class{adapter;chain;asset;constructor(t,e,s){this.adapter=t,this.chain=e,this.asset=s}async getEd(){return this.chain instanceof me?this.chain.getEd():void 0}async getBalance(t){return this.chain.getBalance(this.asset,t)}async getMin(){if(this.chain instanceof me)return this.chain.getMin(this.asset);let t=await xt(this.chain,this.asset);return Vn.fromAsset(this.asset,{amount:0n,decimals:t})}async getDecimals(t){return xt(this.chain,t)}};var $=class extends W{config;constructor(t,e){super(t,e.chain,e.route.source.asset),this.config=e}async getCall(t){let{amount:e,sender:s,source:n}=t,a=await this.getTransfer(t);return this.adapter.buildCall(s,e,n.feeBalance,a)}async getDestinationFee(t){let{chain:e,route:s}=this.config,{source:n,destination:a,transact:r}=s,o=a.fee.amount,m=n.destinationFee??a.fee.asset,i=await this.getDecimals(m);if(Number.isFinite(o))return{fee:bt.fromAsset(m,{amount:le.toBigInt(o,i),decimals:i}),feeBreakdown:{}};let l=o,{amount:u,breakdown:d}=await l.build({feeAsset:m,transferAsset:n.asset,source:r?r.chain:e,destination:a.chain,amount:t});return{fee:bt.fromAsset(m,{amount:u,decimals:i}),feeBreakdown:d}}async getDestinationFeeBalance(t){let{source:e,destination:s}=this.config.route,n=e.asset,a=e.destinationFee??s.fee.asset;return n.isEqual(a)?this.getBalance(t):this.config.chain.getBalance(a,t)}async getFee(t){let{chain:e,route:s}=this.config,{amount:n,sender:a,source:r}=t,o=await this.getTransfer(t),m=s.contract?await ce(a,e):a,i=await this.adapter.estimateFee(m,n,r.feeBalance,o),{fee:l}=s.source,u=l?ue(i.decimals,l.extra):0n,d=i.amount+u;return i.copyWith({amount:d})}async getFeeBalance(t){let{source:e}=this.config.route;if(!e.fee)return this.getBalance(t);let s=await this.getFeeAsset(t);return this.config.chain.getBalance(s,t)}async getFeeAsset(t){let{chain:e,route:s}=this.config,{source:n}=s,a=n.fee,r=n.asset;if(!a)return r;let o=a.asset;return e instanceof On&&"build"in o?await o.build({chain:e,address:t}):o}async getTransfer(t){let{chain:e,route:s}=this.config,{contract:n,extrinsic:a,program:r,move:o}=s;if(a){let{address:i,amount:l,asset:u,sender:d}=t,p=await(await P.create(e)).buildMessageId(d,l,u.originSymbol,i);return a.build({...t,messageId:p})}let m=n||r||o;if(m)return m.build({...t});throw new Error("AssetRoute transfer config is invalid! Specify contract, extrinsic, move or program instructions.")}async getTransact(t){let{route:e}=this.config,{transact:s}=e;if(s){let n=Object.assign({transact:{chain:s.chain}}),a={...t,...n};return{...await this.getTransactData(s,a),chain:s.chain}}}async getTransactData(t,e){let{chain:s,extrinsic:n}=t,a=await n.build(e),r=await P.create(s),o=a.getTx(r.client),m=e.source.chain,i=e.sender,l=Mn.getMultilocationDerivatedAccount(m.parachainId,i,s.parachainId===0?0:1,s.usesH160Acc),u=await o.getPaymentInfo(l),d=await o.getEncodedData(),[g,p]=await Promise.all([this.getTransactFee(t),this.getTransactFeeBalance(t,e)]);return{call:d,chain:s,fee:g,feeBalance:p,weight:{refTime:u.weight.ref_time,proofSize:u.weight.proof_size}}}async getTransactFee(t){let{fee:e}=t,s=await this.getDecimals(e.asset),n=le.toBigInt(e.amount,s);return bt.fromAsset(e.asset,{amount:n,decimals:s})}async getTransactFeeBalance(t,e){return this.config.chain.getBalance(t.fee.asset,e.sender)}};var G=class extends W{};import{AssetAmount as Wn}from"@galacticcouncil/xc-core";var X=class{ctx;constructor(t){this.ctx=t}get asset(){let{source:t}=this.ctx;return t.balance}get dex(){let{source:t}=this.ctx;return t.chain.dex}get destFee(){let{source:t,transact:e}=this.ctx;return e?e.fee:t.destinationFee}get destFeeBalance(){let{source:t,transact:e}=this.ctx;return e?e.feeBalance:t.destinationFeeBalance}get feeBalance(){let{source:t}=this.ctx;return t.feeBalance}async getSwap(t){let{asset:e,decimals:s}=await this.dex.chain.getCurrency(),{amount:n}=await this.dex.getQuote(e,t,t);return{aIn:t,aOut:Wn.fromAsset(e,{amount:n,decimals:s}),enabled:!0}}isSwapSupported(t){try{this.dex}catch{return!1}return!!(t&&t.swap)}async getDestinationSwap(t){let{amount:e,route:s}=await this.dex.getQuote(t,this.destFee,this.destFee),n=this.destFeeBalance.amount<this.destFee.amount,a=this.feeBalance.amount-t.amount>e*2n;return{aIn:t.copyWith({amount:e}),aOut:this.destFee,enabled:n&&a,route:s}}isDestinationSwapSupported(t){try{this.dex}catch{return!1}let e=!t.isSame(this.destFee),s=this.asset.isSame(this.destFee);return e&&!s}};var vt=class{config;validations;constructor({configService:t,transferValidations:e}){this.config=t,this.validations=e||[]}async transfer(t,e,s,n,a){let r=Kn(this.config).assets().asset(t).source(s).destination(a).build();return this.getTransferData(r,e,n)}async remoteXcm(t,e,s,n,a={}){let r=this.config.getChain(e),o=this.config.getChain(s);if(!(r.isSubstrate()&&o.isSubstrate()))throw Error("RemoteXcm is supported only between parachains");let[i,l]=await Promise.all([P.create(r),P.create(o)]),u=new ot(i,l),d=Nn.getMultilocationDerivatedAccount(r.parachainId,t,1,o.usesH160Acc),g=await l.getAsset(),p=await this.transfer(g,t,e,d,s);return u.remoteExec(t,d,n,f=>{let y=f.toDecimal();return p.buildCall(y)},a)}async getTransferData(t,e,s){let n=t.origin,{chain:a,asset:r}=n.route.destination,o=new M(n.chain),m=new M(a),i=new $(o,n),l=new G(m,a,r),u=new Hn(...this.validations),[d,g,p,f,y,x,A]=await Promise.all([i.getBalance(e),i.getFeeBalance(e),i.getDestinationFee(),i.getDestinationFeeBalance(e),i.getMin(),l.getBalance(s),l.getMin()]),{source:h,destination:I}=n.route,S=p.fee.copyWith(I.fee.asset),B=p.feeBreakdown,E=h.asset.isEqual(S)&&S.amount>10n?S.amount+1n:10n,C={address:s,amount:E,asset:h.asset,destination:{balance:x,chain:a,fee:S,feeBreakdown:B},sender:e,source:{balance:d,chain:n.chain,fee:g.copyWith({amount:0n}),feeBalance:g,destinationFee:p.fee,destinationFeeBalance:f}};C.transact=await i.getTransact(C);let T=new X(C),b=await i.getFee(C),F;T.isSwapSupported(h.fee)&&(F=await T.getSwap(b),C.source.feeSwap=F);let D;T.isDestinationSwapSupported(b)&&(D=await T.getDestinationSwap(b),C.source.destinationFeeSwap=D),(F||D)&&(b=await i.getFee(C),b=b.padByPct(5n));let dt=await l.getEd(),w=oe(x,S,A,dt),q=await i.getEd(),gt=ie(d,b,y,q);C.amount=0n,C.source.fee=b;let pt={source:{balance:d,destinationFee:p.fee,destinationFeeBalance:f,destinationFeeSwap:D,fee:b,feeBalance:g,feeSwap:F,max:gt,min:d.copyWith({amount:w.amount})},destination:{balance:x,fee:S},reversible:t.reversible,async buildCall(R){let v=Object.assign({},C);return v.amount=wt.toBigInt(R,d.decimals),v.transact=await i.getTransact(v),i.getCall(v)},async estimateFee(R){let v=Object.assign({},C);return v.amount=wt.toBigInt(R,d.decimals),v.transact=await i.getTransact(v),i.getFee(v)},async estimateDestinationFee(R){let v=wt.toBigInt(R,d.decimals),{fee:k,feeBreakdown:fe}=await i.getDestinationFee(v);return C.destination.fee=k,C.destination.feeBreakdown=fe,C.source.destinationFee=k,pt.destination.fee=k,pt.source.destinationFee=k,k},async validate(R){let v=Object.assign({},C),k=R||b.amount;return v.source.fee=b.copyWith({amount:k}),u.validate(v)}};return pt}async subscribeBalance(t,e,s){let n=this.config.getChainRoutes(e),a=n.getUniqueRoutes().map(r=>r.source.asset);return n.chain.subscribeBalances(a,t).subscribe(s)}};import{ConfigBuilder as Un}from"@galacticcouncil/xc-core";function zn(c){let t=Un(c.config).assets();return{assets:t,withAsset(e){let s=t.asset(e);return{sources:s,withSource(n){let a=s.source(n);return{destinations:a,withDestination(r){let{routes:o,destinationAssets:m,isAssetSelect:i,isTagSelect:l,build:u}=a.destination(r);return{routes:o,destinationAssets:m,isAssetSelect:i,isTagSelect:l,build({srcAddress:d,dstAddress:g,dstAsset:p,tag:f}){let y=u(p,f);return c.getTransferData(y,d,g)}}}}}}}}}import{Precompile as jn}from"@galacticcouncil/xc-core";var Ln="https://api.wormholescan.io",lt=class{_baseUrl;constructor(t){this._baseUrl=t||Ln}buildApi(t,e){return[this._baseUrl,t,"?"].join("")+new URLSearchParams(e).toString()}async getVaaBytes(t){let e=this.buildApi("/v1/signed_vaa/"+t,{});return await(await fetch(e)).json()}async getVaa(t){let e=this.buildApi("/api/v1/vaas/"+t,{});return(await(await fetch(e)).json()).data}async getVaaByTxHash(t){let e=this.buildApi("/api/v1/vaas/",{txHash:t}),n=await(await fetch(e)).json();if(n.data.length>0)return n.data[0];throw Error("Can't find VAA for given txHash: "+t)}async getOperations(t){let e=this.buildApi("/api/v1/operations/",t);return(await(await fetch(e)).json()).operations}async getOperation(t){let e=this.buildApi("/api/v1/operations/"+t,{});return await(await fetch(e)).json()}isMrlTransfer(t){let{payloadType:e,toAddress:s,toChain:n}=t,a="0x"+s.substring(26);return e===3&&n===16&&a===jn.Bridge}};import{acc as $n}from"@galacticcouncil/common";import{mrl as Gn,ChainType as ge,Parachain as Xn,Precompile as Jn,Wormhole as N}from"@galacticcouncil/xc-core";import{encoding as qn}from"@wormhole-foundation/sdk-base";import{keccak256 as Qn}from"@wormhole-foundation/sdk-connect";import{deserialize as Yn}from"@wormhole-foundation/sdk-definitions";var de=(s=>(s[s.WaitingForVaa=0]="WaitingForVaa",s[s.VaaEmitted=1]="VaaEmitted",s[s.Completed=2]="Completed",s))(de||{});var Zn=300*1e3,pe=class{parachainId;config;whScan;constructor(t,e){this.config=t,this.parachainId=e,this.whScan=new lt}get chains(){let t=this.config.chains.values();return Array.from(t)}get filters(){let t=new Date,e=new Date;e.setDate(t.getDate()-6);let s=t.toISOString();return{page:"0",pageSize:"50",includeEndDate:"true",from:e.toISOString(),to:s}}async getWithdraws(t){let e=$n.getMultilocationDerivatedAccount(this.parachainId,t,1,!0),n=(await this.whScan.getOperations({...this.filters,address:e})).map(async a=>{let{content:r}=a,{payload:o,standarizedProperties:m}=r,i=this.getStatus(a),l=this.chains.find(f=>f instanceof Xn&&f.parachainId===this.parachainId),{toAddress:u,tokenAddress:d}=m,g=this.chains.find(f=>N.isKnown(f)&&N.fromChain(f).getWormholeId()===o.tokenChain),p;if(i===1&&a.vaa){let{timestamp:f}=this.getVaaHeader(a.vaa.raw),y=a.vaa.raw;if(this.isStuck(f))switch(g.getType()){case ge.EvmChain:let x=new Q(g);p=async h=>x.redeem(h,y);break;case ge.SolanaChain:let A=new at(g);p=async h=>A.redeem(h,y);break}}return{asset:d,assetSymbol:a.data.symbol,amount:a.data.tokenAmount,from:t,fromChain:l,to:u,toChain:g,status:i,redeem:p,operation:a}});return Promise.all(n)}async getDeposits(t,e="hydration"){let s=await this.whScan.getOperations({...this.filters,address:Jn.Bridge,pageSize:"100"}),n=this.config.chains.get(e);if(!n)return[];let a=n,o=(await Gn.createPayload(a,t)).toHex(),m=s.filter(i=>{let{content:l}=i,{payload:u}=l;return u.payloadType===3&&u.toChain===16&&"0x"+u.payload===o}).map(async i=>{let{content:l,sourceChain:u}=i,{payload:d,standarizedProperties:g}=l,p=this.getStatus(i),{tokenAddress:f}=g,y=this.chains.find(h=>N.isKnown(h)&&N.fromChain(h).getWormholeId()===d.tokenChain),x=this.chains.find(h=>N.isKnown(h)&&N.fromChain(h).getWormholeId()===d.toChain),A;if(p===1&&i.vaa){let{timestamp:h}=this.getVaaHeader(i.vaa.raw),I=i.vaa.raw;if(this.isStuck(h)){let S=new rt(x);A=async B=>S.redeemMrlViaXcm(B,I)}}return{asset:f,assetSymbol:i.data.symbol,amount:i.data.tokenAmount,from:u.from,fromChain:y,to:t,toChain:n,status:p,redeem:A,operation:i}});return Promise.all(m)}isStuck(t){return Date.now()>=t*1e3+Zn}getVaaHeader(t){let e=qn.b64.decode(t),s=Yn("Uint8Array",e);return{timestamp:s.timestamp,emitterChain:s.emitterChain,emitterAddress:s.emitterAddress.toString(),sequence:s.sequence,payload:s.payload,hash:s.hash,id:Qn(s.hash)}}getStatus(t){return t.vaa?t.targetChain&&t.targetChain.status==="completed"?2:1:0}};export{Ft as DISPATCH_ADDRESS,Q as EvmClaim,Z as EvmPlatform,It as EvmSigner,X as FeeSwap,M as PlatformAdapter,at as SolanaClaim,V as SolanaLilJit,et as SolanaPlatform,Lt as SolanaSigner,rt as SubstrateClaim,ot as SubstrateExec,ct as SubstratePlatform,P as SubstrateService,ne as SubstrateSigner,ae as SuiClaim,mt as SuiPlatform,re as SuiSigner,zn as TransferBuilder,vt as Wallet,de as WhStatus,lt as WormholeScan,pe as WormholeTransfer,Mt as chunkBySize,Ys as deserializeV0,_ as ixToHuman,U as serializeV0};
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { AnyChain,
|
|
2
|
-
import { Observable } from 'rxjs';
|
|
1
|
+
import { AnyChain, AssetAmount, BaseConfig } from '@galacticcouncil/xc-core';
|
|
3
2
|
import { Call, Platform } from './types';
|
|
4
3
|
export declare class PlatformAdapter {
|
|
5
|
-
readonly platform: Record<string, Platform<BaseConfig
|
|
4
|
+
readonly platform: Record<string, Platform<BaseConfig>>;
|
|
6
5
|
constructor(chain: AnyChain);
|
|
7
6
|
private registerEvm;
|
|
8
7
|
private registerSolana;
|
|
@@ -10,6 +9,4 @@ export declare class PlatformAdapter {
|
|
|
10
9
|
private registerSubstrate;
|
|
11
10
|
buildCall(account: string, amount: bigint, feeBalance: AssetAmount, config: BaseConfig): Promise<Call>;
|
|
12
11
|
estimateFee(account: string, amount: bigint, feeBalance: AssetAmount, config: BaseConfig): Promise<AssetAmount>;
|
|
13
|
-
getBalance(asset: Asset, config: BaseConfig): Promise<AssetAmount>;
|
|
14
|
-
subscribeBalance(asset: Asset, config: BaseConfig): Promise<Observable<AssetAmount>>;
|
|
15
12
|
}
|
|
@@ -1,12 +1,9 @@
|
|
|
1
|
-
import { AnyEvmChain,
|
|
2
|
-
import { Observable } from 'rxjs';
|
|
1
|
+
import { AnyEvmChain, AssetAmount, ContractConfig } from '@galacticcouncil/xc-core';
|
|
3
2
|
import { EvmCall } from './types';
|
|
4
3
|
import { Platform } from '../types';
|
|
5
|
-
export declare class EvmPlatform implements Platform<ContractConfig
|
|
4
|
+
export declare class EvmPlatform implements Platform<ContractConfig> {
|
|
6
5
|
#private;
|
|
7
6
|
constructor(chain: AnyEvmChain);
|
|
8
7
|
buildCall(account: string, amount: bigint, _feeBalance: AssetAmount, config: ContractConfig): Promise<EvmCall>;
|
|
9
8
|
estimateFee(account: string, amount: bigint, feeBalance: AssetAmount, config: ContractConfig): Promise<AssetAmount>;
|
|
10
|
-
getBalance(asset: Asset, config: ContractConfig): Promise<AssetAmount>;
|
|
11
|
-
subscribeBalance(asset: Asset, config: ContractConfig): Promise<Observable<AssetAmount>>;
|
|
12
9
|
}
|
|
@@ -1,12 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { Observable } from 'rxjs';
|
|
1
|
+
import { AssetAmount, ProgramConfig, SolanaChain } from '@galacticcouncil/xc-core';
|
|
3
2
|
import { SolanaCall } from './types';
|
|
4
3
|
import { Platform } from '../types';
|
|
5
|
-
export declare class SolanaPlatform implements Platform<ProgramConfig
|
|
4
|
+
export declare class SolanaPlatform implements Platform<ProgramConfig> {
|
|
6
5
|
#private;
|
|
7
6
|
constructor(chain: SolanaChain);
|
|
8
7
|
buildCall(account: string, _amount: bigint, _feeBalance: AssetAmount, config: ProgramConfig): Promise<SolanaCall>;
|
|
9
8
|
estimateFee(account: string, amount: bigint, feeBalance: AssetAmount, config: ProgramConfig): Promise<AssetAmount>;
|
|
10
|
-
getBalance(asset: Asset, config: SolanaQueryConfig): Promise<AssetAmount>;
|
|
11
|
-
subscribeBalance(asset: Asset, config: SolanaQueryConfig): Promise<Observable<AssetAmount>>;
|
|
12
9
|
}
|
|
@@ -1,15 +1,12 @@
|
|
|
1
|
-
import { AnyParachain,
|
|
2
|
-
import { Observable } from 'rxjs';
|
|
1
|
+
import { AnyParachain, AssetAmount, ExtrinsicConfig } from '@galacticcouncil/xc-core';
|
|
3
2
|
import { SubstrateCall } from './types';
|
|
4
3
|
import { Platform } from '../types';
|
|
5
|
-
export declare class SubstratePlatform implements Platform<ExtrinsicConfig
|
|
4
|
+
export declare class SubstratePlatform implements Platform<ExtrinsicConfig> {
|
|
6
5
|
#private;
|
|
7
6
|
constructor(chain: AnyParachain);
|
|
8
7
|
private useSignerFee;
|
|
9
8
|
buildCall(account: string, _amount: bigint, feeBalance: AssetAmount, config: ExtrinsicConfig): Promise<SubstrateCall>;
|
|
10
9
|
estimateFee(account: string, _amount: bigint, feeBalance: AssetAmount, config: ExtrinsicConfig): Promise<AssetAmount>;
|
|
11
|
-
getBalance(asset: Asset, config: SubstrateQueryConfig): Promise<AssetAmount>;
|
|
12
|
-
subscribeBalance(asset: Asset, config: SubstrateQueryConfig): Promise<Observable<AssetAmount>>;
|
|
13
10
|
/**
|
|
14
11
|
* Display native fee in user preferred fee payment asset
|
|
15
12
|
*
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AnyParachain, Asset,
|
|
1
|
+
import { AnyParachain, Asset, ChainCurrency, Extrinsic, ExtrinsicConfig } from '@galacticcouncil/xc-core';
|
|
2
2
|
import { HubApis } from '@galacticcouncil/descriptors';
|
|
3
3
|
type TRawDryRun = HubApis['DryRunApi']['dry_run_call']['Value']['value'];
|
|
4
4
|
type TDryRun = Extract<TRawDryRun, {
|
|
@@ -14,7 +14,6 @@ export declare class SubstrateService {
|
|
|
14
14
|
getCurrency(): Promise<ChainCurrency>;
|
|
15
15
|
getAsset(): Promise<Asset>;
|
|
16
16
|
getDecimals(): Promise<number>;
|
|
17
|
-
getExistentialDeposit(): Promise<AssetAmount>;
|
|
18
17
|
isDryRunSupported(): boolean;
|
|
19
18
|
buildMessageId(account: string, amount: bigint, asset: string, beneficiary: string): Promise<string>;
|
|
20
19
|
dryRun(account: string, tx: Extrinsic): Promise<TDryRun>;
|
|
@@ -1,12 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { Observable } from 'rxjs';
|
|
1
|
+
import { AssetAmount, MoveConfig, SuiChain } from '@galacticcouncil/xc-core';
|
|
3
2
|
import { SuiCall } from './types';
|
|
4
3
|
import { Platform } from '../types';
|
|
5
|
-
export declare class SuiPlatform implements Platform<MoveConfig
|
|
4
|
+
export declare class SuiPlatform implements Platform<MoveConfig> {
|
|
6
5
|
#private;
|
|
7
6
|
constructor(chain: SuiChain);
|
|
8
7
|
buildCall(account: string, _amount: bigint, _feeBalance: AssetAmount, config: MoveConfig): Promise<SuiCall>;
|
|
9
8
|
estimateFee(account: string, _amount: bigint, feeBalance: AssetAmount, config: MoveConfig): Promise<AssetAmount>;
|
|
10
|
-
getBalance(asset: Asset, config: SuiQueryConfig): Promise<AssetAmount>;
|
|
11
|
-
subscribeBalance(asset: Asset, config: SuiQueryConfig): Promise<Observable<AssetAmount>>;
|
|
12
9
|
}
|
|
@@ -1,10 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
export interface Platform<T extends BaseConfig, B extends BaseConfig> {
|
|
1
|
+
import { AssetAmount, BaseConfig, CallType } from '@galacticcouncil/xc-core';
|
|
2
|
+
export interface Platform<T extends BaseConfig> {
|
|
4
3
|
buildCall(account: string, amount: bigint, feeBalance: AssetAmount, config: T): Promise<Call>;
|
|
5
4
|
estimateFee(account: string, amount: bigint, feeBalance: AssetAmount, config: T): Promise<AssetAmount>;
|
|
6
|
-
getBalance(asset: Asset, config: B): Promise<AssetAmount>;
|
|
7
|
-
subscribeBalance(asset: Asset, config: B): Promise<Observable<AssetAmount>>;
|
|
8
5
|
}
|
|
9
6
|
export interface Call {
|
|
10
7
|
/** Owner of transation. */
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { DataProcessor } from './DataProcessor';
|
|
2
|
+
/**
|
|
3
|
+
* Resolves destination-side transfer data (received balance, minimum,
|
|
4
|
+
* existential deposit) directly from the destination chain.
|
|
5
|
+
*
|
|
6
|
+
* Thin {@link DataProcessor} — its `(chain, asset)` are supplied directly so
|
|
7
|
+
* one-way routes resolve destination data without a reverse `TransferConfig`.
|
|
8
|
+
*/
|
|
9
|
+
export declare class DataDestinationProcessor extends DataProcessor {
|
|
10
|
+
}
|
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
import { Asset, AssetAmount, TransferCtx, TransferConfig, TransactCtx } from '@galacticcouncil/xc-core';
|
|
2
2
|
import { Call, PlatformAdapter } from '../platforms';
|
|
3
3
|
import { DataProcessor } from './DataProcessor';
|
|
4
|
+
/**
|
|
5
|
+
* Resolves origin-side transfer data — balance, minimum and existential
|
|
6
|
+
* deposit (via {@link DataProcessor}) plus the source/destination fee
|
|
7
|
+
* estimates and the transfer {@link Call} — sourcing `(chain, asset)` and the
|
|
8
|
+
* route from its `TransferConfig`.
|
|
9
|
+
*/
|
|
4
10
|
export declare class DataOriginProcessor extends DataProcessor {
|
|
11
|
+
readonly config: TransferConfig;
|
|
5
12
|
constructor(adapter: PlatformAdapter, config: TransferConfig);
|
|
6
13
|
getCall(ctx: TransferCtx): Promise<Call>;
|
|
7
14
|
getDestinationFee(transferAmount?: bigint): Promise<{
|
|
@@ -1,12 +1,19 @@
|
|
|
1
|
-
import { Asset, AssetAmount
|
|
1
|
+
import { AnyChain, Asset, AssetAmount } from '@galacticcouncil/xc-core';
|
|
2
2
|
import { PlatformAdapter } from '../platforms';
|
|
3
|
+
/**
|
|
4
|
+
* Resolves chain-side transfer data (balance, minimum, existential deposit)
|
|
5
|
+
* for a given `(chain, asset)` directly from the chain. Shared by the origin
|
|
6
|
+
* and destination processors — the origin sources `(chain, asset)` from its
|
|
7
|
+
* `TransferConfig`, the destination receives them directly (one-way routes
|
|
8
|
+
* have no reverse config).
|
|
9
|
+
*/
|
|
3
10
|
export declare abstract class DataProcessor {
|
|
4
11
|
readonly adapter: PlatformAdapter;
|
|
5
|
-
readonly
|
|
6
|
-
|
|
12
|
+
readonly chain: AnyChain;
|
|
13
|
+
readonly asset: Asset;
|
|
14
|
+
constructor(adapter: PlatformAdapter, chain: AnyChain, asset: Asset);
|
|
7
15
|
getEd(): Promise<AssetAmount | undefined>;
|
|
8
16
|
getBalance(address: string): Promise<AssetAmount>;
|
|
9
17
|
getMin(): Promise<AssetAmount>;
|
|
10
|
-
private getAssetMin;
|
|
11
18
|
protected getDecimals(asset: Asset): Promise<number>;
|
|
12
19
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AnyChain, AssetAmount } from '@galacticcouncil/xc-core';
|
|
1
|
+
import { AnyChain, Asset, AssetAmount } from '@galacticcouncil/xc-core';
|
|
2
2
|
/**
|
|
3
3
|
* Calculate maximum allowed amount of asset to send from source to
|
|
4
4
|
* destination chain.
|
|
@@ -39,3 +39,12 @@ export declare function formatEvmAddress(address: string, chain: AnyChain): Prom
|
|
|
39
39
|
* @returns formatted amount or 0
|
|
40
40
|
*/
|
|
41
41
|
export declare function formatAmount(decimals: number, amount?: number): bigint;
|
|
42
|
+
/**
|
|
43
|
+
* Resolve decimals for an asset on a given chain, falling back to the chain
|
|
44
|
+
* native currency decimals when the asset has no chain-specific override.
|
|
45
|
+
*
|
|
46
|
+
* @param chain - chain the asset is read on
|
|
47
|
+
* @param asset - asset to resolve decimals for
|
|
48
|
+
* @returns asset decimals
|
|
49
|
+
*/
|
|
50
|
+
export declare function getDecimals(chain: AnyChain, asset: Asset): Promise<number>;
|
package/build/types.d.ts
CHANGED
|
@@ -41,10 +41,13 @@ export interface TransferDestinationData {
|
|
|
41
41
|
* @interface Transfer
|
|
42
42
|
* @member {TransferSourceData} source Source chain data
|
|
43
43
|
* @member {TransferDestinationData} destination Destination chain data
|
|
44
|
+
* @member {boolean} reversible True if a return-trip route is registered.
|
|
45
|
+
* Consumers may use this to gate UI affordances (swap-direction button, etc.).
|
|
44
46
|
*/
|
|
45
47
|
export interface Transfer {
|
|
46
48
|
source: TransferSourceData;
|
|
47
49
|
destination: TransferDestinationData;
|
|
50
|
+
reversible: boolean;
|
|
48
51
|
buildCall(amount: bigint | number | string): Promise<Call>;
|
|
49
52
|
estimateFee(amount: bigint | number | string): Promise<AssetAmount>;
|
|
50
53
|
estimateDestinationFee(amount: bigint | number | string): Promise<AssetAmount>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@galacticcouncil/xc-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0-pr337-94e58a8",
|
|
4
4
|
"description": "Cross-chain sdk",
|
|
5
5
|
"author": "GalacticCouncil",
|
|
6
6
|
"type": "module",
|
|
@@ -33,6 +33,6 @@
|
|
|
33
33
|
"link": "npm ln"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@galacticcouncil/xc-core": "
|
|
36
|
+
"@galacticcouncil/xc-core": "1.2.0-pr337-94e58a8"
|
|
37
37
|
}
|
|
38
38
|
}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { ContractConfig, Erc20Client, EvmClient } from '@galacticcouncil/xc-core';
|
|
2
|
-
import { EvmBalance } from './EvmBalance';
|
|
3
|
-
export declare class Erc20 extends EvmBalance {
|
|
4
|
-
readonly erc20: Erc20Client;
|
|
5
|
-
constructor(client: EvmClient, config: ContractConfig);
|
|
6
|
-
getBalance(): Promise<bigint>;
|
|
7
|
-
getDecimals(): Promise<number>;
|
|
8
|
-
}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { ContractConfig, EvmClient } from '@galacticcouncil/xc-core';
|
|
2
|
-
export declare abstract class EvmBalance {
|
|
3
|
-
readonly client: EvmClient;
|
|
4
|
-
readonly config: ContractConfig;
|
|
5
|
-
constructor(client: EvmClient, config: ContractConfig);
|
|
6
|
-
private validateClient;
|
|
7
|
-
private validateConfig;
|
|
8
|
-
abstract getBalance(): Promise<bigint>;
|
|
9
|
-
abstract getDecimals(): Promise<number>;
|
|
10
|
-
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { SolanaQueryConfig } from '@galacticcouncil/xc-core';
|
|
2
|
-
import { Connection } from '@solana/web3.js';
|
|
3
|
-
export declare abstract class SolanaBalance {
|
|
4
|
-
readonly connection: Connection;
|
|
5
|
-
readonly config: SolanaQueryConfig;
|
|
6
|
-
constructor(connection: Connection, config: SolanaQueryConfig);
|
|
7
|
-
private validateConnection;
|
|
8
|
-
private validateConfig;
|
|
9
|
-
abstract getBalance(): Promise<bigint>;
|
|
10
|
-
abstract getDecimals(): Promise<number>;
|
|
11
|
-
}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { SolanaQueryConfig } from '@galacticcouncil/xc-core';
|
|
2
|
-
import { Connection } from '@solana/web3.js';
|
|
3
|
-
import { SolanaBalance } from './SolanaBalance';
|
|
4
|
-
export declare class SolanaBalanceFactory {
|
|
5
|
-
static get(connection: Connection, config: SolanaQueryConfig): SolanaBalance;
|
|
6
|
-
}
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { SolanaQueryConfig } from '@galacticcouncil/xc-core';
|
|
2
|
-
import { Connection } from '@solana/web3.js';
|
|
3
|
-
import { SolanaBalance } from './SolanaBalance';
|
|
4
|
-
export declare class Token extends SolanaBalance {
|
|
5
|
-
constructor(connection: Connection, config: SolanaQueryConfig);
|
|
6
|
-
getBalance(): Promise<bigint>;
|
|
7
|
-
getDecimals(): Promise<number>;
|
|
8
|
-
private validateToken;
|
|
9
|
-
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { SuiQueryConfig } from '@galacticcouncil/xc-core';
|
|
2
|
-
import { SuiClient } from '@mysten/sui/client';
|
|
3
|
-
export declare abstract class SuiBalance {
|
|
4
|
-
readonly client: SuiClient;
|
|
5
|
-
readonly config: SuiQueryConfig;
|
|
6
|
-
constructor(client: SuiClient, config: SuiQueryConfig);
|
|
7
|
-
private validateClient;
|
|
8
|
-
private validateConfig;
|
|
9
|
-
abstract getBalance(): Promise<bigint>;
|
|
10
|
-
abstract getDecimals(): Promise<number>;
|
|
11
|
-
}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { TransferConfig } from '@galacticcouncil/xc-core';
|
|
2
|
-
import { PlatformAdapter } from '../platforms';
|
|
3
|
-
import { DataProcessor } from './DataProcessor';
|
|
4
|
-
export declare class DataReverseProcessor extends DataProcessor {
|
|
5
|
-
constructor(adapter: PlatformAdapter, config: TransferConfig);
|
|
6
|
-
}
|