@galacticcouncil/xc-sdk 0.1.0 → 0.3.0
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/types/FeeSwap.d.ts +1 -1
- package/build/types/platforms/substrate/SubstrateService.d.ts +13 -20
- package/build/types/platforms/substrate/utils/dryRun.d.ts +1 -1
- package/build/types/platforms/substrate/utils/index.d.ts +0 -1
- package/build/types/platforms/substrate/utils/xcm.d.ts +76 -66
- package/package.json +2 -2
- package/build/types/platforms/substrate/utils/naming.d.ts +0 -24
package/build/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`,
|
|
3
|
-
`,o.details),{error:o}}}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 Bt(t,e)}};var ne=require("@galacticcouncil/xc-core");function se(i){let t=i.module==="Snowbridge"&&i.func==="sendToken"&&i.args[0]==="0x0000000000000000000000000000000000000000";return i.module==="TokenBridge"&&["wrapAndTransferETHWithPayload","wrapAndTransferETH"].includes(i.func)||t}function ae(i){return Object.entries(ne.Precompile).map(([e,s])=>s).includes(i.address)}var rt=class{#t;constructor(t){this.#t=t.client}async buildCall(t,e,s,n){let a=at.get(this.#t,n),{abi:r,asset:c,calldata:o}=a,u={abi:JSON.stringify(r),data:o,from:t,to:n.address,type:k.CallType.Evm,value:n.value,dryRun:async()=>{let{error:g,logs:f}=await a.simulateCall(t),p=a.decodeEvents(f);return{call:n.module+"."+n.func,error:g?.shortMessage,events:p}}};if(ae(n)||se(n))return u;let l=new k.Erc20Client(this.#t,c),m=await l.allowance(t,n.address);if(m>=e)return u;let d=l.approve(n.address,e);return{abi:JSON.stringify(k.Abi.Erc20),allowance:m,data:d,from:t,to:c,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})}async getBalance(t,e){let s=Pt.get(this.#t,e),[n,a]=await Promise.all([s.getBalance(),s.getDecimals()]);return k.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 u=a.watchBlocks({onBlock:()=>o()});return()=>u()},c;return r().then(o=>c=o),n.pipe((0,_.finalize)(()=>c?.()),(0,_.distinctUntilChanged)((o,u)=>o.amount===u.amount))}};var kt=require("@galacticcouncil/xc-core"),le=require("@solana/web3.js"),de=require("buffer"),N=require("rxjs");var q=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 re=require("@wormhole-foundation/sdk-solana");var Ge=9,Et=class extends q{async getBalance(){let{address:t}=this.config,e=new re.SolanaAddress(t).unwrap(),s=await this.connection.getBalance(e);return BigInt(s)}async getDecimals(){return Ge}};var Ft=require("@wormhole-foundation/sdk-solana");var Dt=class extends q{constructor(t,e){super(t,e),this.validateToken(e)}async getBalance(){let{address:t,token:e}=this.config,s=new Ft.SolanaAddress(t).unwrap(),n=new Ft.SolanaAddress(e).unwrap();return(await this.connection.getParsedTokenAccountsByOwner(s,{mint:n})).value.reduce((r,{account:c})=>{let o=c.data.parsed.info.tokenAmount;return r+=BigInt(o.amount),r},0n)}async getDecimals(){let{token:t}=this.config,e=new Ft.SolanaAddress(t).unwrap();return(await this.connection.getTokenSupply(e)).value.decimals}validateToken(t){if(!t.token)throw new Error("Token address is required")}};var It=class{static get(t,e){switch(e.module){case"Native":return new Et(t,e);case"Token":return new Dt(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};var F=require("@solana/web3.js"),ie=.5,oe=2,ce=1,ue=1e6,Je=25e4,Rt=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=ie,s=oe,n=ce,a=ue){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):Je}async determinePriorityFee(t,e=ie,s=oe,n=ce,a=ue){let r=n,c=await this.getTxAccounts(t),o=await this.connection.getRecentPrioritizationFees({lockedWritableAccounts:c});if(o){let u=o.map(m=>m.prioritizationFee).filter(m=>m>0).sort((m,d)=>m-d),l=Math.ceil(u.length*e);if(u.length>l){let d=u[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 Rt(t,e)}};var me=require("@solana/web3.js");function Q(i){return i.map(t=>({program:t.programId.toBase58(),data:t.data.toString("hex"),keys:t.keys.map(e=>e.pubkey.toBase58())}))}function Qt(i,t=1e3){let e=[],s=[],n=0;for(let a of i){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 ot(i){let t=i.serialize();return Buffer.from(t).toString("hex")}function Ye(i){let t=Buffer.from(i,"hex"),e=Uint8Array.from(t);return me.MessageV0.deserialize(e)}var ct=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(),o=de.Buffer.from(c).toString("hex");return{from:t,data:o,ix:Q(n.instructions),signers:n.signers,type:kt.CallType.Solana,dryRun:async()=>{let{err:u,logs:l}=await a.simulateTransaction(t,r);return{call:n.module+"."+n.func,error:u,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:o}=await a.simulateTransaction(t,c),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)})}return s.copyWith({amount:r})}async getBalance(t,e){let s=It.get(this.#t,e),[n,a]=await Promise.all([s.getBalance(),s.getDecimals()]);return kt.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 c=async()=>{let l=await this.getBalance(t,e);s.next(l)};await c();let o=new le.PublicKey(e.address),u=this.#t.onAccountChange(o,()=>c());return()=>{this.#t.removeAccountChangeListener(u)}},r;return a().then(c=>r=c),n.pipe((0,N.finalize)(()=>r?.()),(0,N.distinctUntilChanged)((c,o)=>c.amount===o.amount))}};var X=require("@galacticcouncil/xc-core"),M=require("@solana/web3.js"),ge=require("@wormhole-foundation/sdk-solana"),Ht=require("@wormhole-foundation/sdk-solana-core"),fe=require("@wormhole-foundation/sdk-base"),$t=require("@wormhole-foundation/sdk-definitions"),Mt=require("@wormhole-foundation/sdk-solana-tokenbridge");var ut=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){let{result:e}=await this.#t._rpcRequest("simulateBundle",[[t]]);return e}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 mt=class{#t;#e;#n;constructor(t){this.#t=t,this.#e=t.connection,this.#n=new ut(t)}async redeem(t,e){let s=X.Wormhole.fromChain(this.#t),n=fe.encoding.b64.decode(e),a=(0,$t.deserialize)("TokenBridge:Transfer",n),r=(0,$t.deserialize)("Uint8Array",n),c=this.derivePostedVaaKey(s.getCoreBridge(),Buffer.from(a.hash)),o=new M.PublicKey(t),u=[];if(!await this.#e.getAccountInfo(c)){let B=M.Keypair.generate(),T=await Ht.utils.createVerifySignaturesInstructions(this.#t.connection,s.getCoreBridge(),o,r,B.publicKey),h=Qt(T,1e3);for(let w=0;w<h.length;w++){let A=h[w],O=await this.getV0Message(o,A),R=ot(O);u.push({from:t,data:R,ix:Q(A),signers:[B],type:X.CallType.Solana})}let E=Ht.utils.createPostVaaInstruction(this.#e,s.getCoreBridge(),o,r,B.publicKey),z=await this.getV0Message(o,[E]),y=ot(z);u.push({from:t,data:y,ix:Q([E]),type:X.CallType.Solana})}let d=(a.payload.token.chain==="Solana"?Mt.createCompleteTransferNativeInstruction:Mt.createCompleteTransferWrappedInstruction)(this.#e,s.getTokenBridge(),s.getCoreBridge(),o,a),g=await this.#n.getTipAccount(),f=M.SystemProgram.transfer({fromPubkey:o,toPubkey:new M.PublicKey(g[0]),lamports:1e3}),p=await this.getV0Message(o,[d,f]),b=ot(p);return u.push({from:t,data:b,ix:Q([d]),type:X.CallType.Solana}),u}derivePostedVaaKey(t,e){return ge.utils.deriveAddress([Buffer.from("PostedVAA"),e],t)}async getV0Message(t,e){let{blockhash:s}=await this.#e.getLatestBlockhash("finalized");return new M.TransactionMessage({payerKey:t,recentBlockhash:s,instructions:e}).compileToV0Message()}};var W=require("@galacticcouncil/xc-core"),Kt=require("@wormhole-foundation/sdk-base"),pe=require("viem"),lt=class{#t;constructor(t){this.#t=t,W.Wormhole.fromChain(this.#t)}redeemMrl(t,e){let s=Kt.encoding.b64.decode(e),n=Kt.encoding.hex.encode(s),a=W.Abi.Gmp,r=(0,pe.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.api.getUnsafeApi(),a=this.redeemMrl(t,e);return{data:n.tx.EthereumXcm.transact({V2:{gas_limit:5000000n,action:{Call:a.to},value:0n,input:a.data}}).decodedCall,from:t,type:W.CallType.Substrate,dryRun:async()=>{},txOptions:void 0}}};var J=require("@galacticcouncil/xc-core"),Vt=require("polkadot-api");var he=require("@galacticcouncil/common");async function qt(i,t,e){let s=await e.getDecimals(),n=e.chain.getAssetDecimals(t)??s,a=e.chain.usesChainDecimals?s:n;return{amount:he.big.convertDecimals(i,a,n),decimals:n}}var ye=i=>{let t=[];for(let e of i)if((e.type==="XcmPallet.FeesPaid"||e.type==="PolkadotXcm.FeesPaid")&&e.value?.fees){let n=Array.isArray(e.value.fees)?e.value.fees:[e.value.fees];for(let a of n)if(a.fun?.Fungible){let r=BigInt(a.fun.Fungible);t.push(r)}}return t.reduce((e,s)=>e+s,0n)},G=i=>{if(i.type==="Module"){let{index:t,error:e}=i.value;return`Module error: ${t}:${e}`}return JSON.stringify(i)};function dt(i){return i.charAt(0).toUpperCase()+i.slice(1)}function Ce(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Ze(i){return i.startsWith("0x")?{parents:0,interior:{X1:[{AccountKey20:{key:i}}]}}:{parents:0,interior:{X1:[{AccountId32:{id:i}}]}}}function be(i){return{V4:{parents:1,interior:{X1:[{Parachain:i.parachainId}]}}}}function Ae(i,t,e,s,n,a){let r=Ze(i);return{V4:[{WithdrawAsset:[{id:t,fun:{Fungible:e.amount}}]},{BuyExecution:{fees:{id:t,fun:{Fungible:e.amount}},weightLimit:"Unlimited"}},{Transact:{originKind:"SovereignAccount",requireWeightAtMost:{refTime:s,proofSize:n},call:{encoded:a}}},{RefundSurplus:{}},{DepositAsset:{assets:{Wild:{AllCounted:1}},beneficiary:r}}]}}var gt=class{#t;#e;#n;constructor(t,e){this.#t=t,this.#e=e,this.#n=J.DexFactory.getInstance().get(t.chain.key)}async remoteExec(t,e,s,n,a={}){let r=this.#t.api,c=await this.#t.getAsset(),o=this.#e.api,u=await this.#e.getAsset(),l=this.#e.chain,m=await this.#e.getDecimals(),d=l.getAssetXcmLocation(u),f=await(await o.txFromCallData(Vt.Binary.fromHex(s.data))).getPaymentInfo(e),p=BigInt(f.partial_fee)*120n/100n,b=J.AssetAmount.fromAsset(u,{amount:p,decimals:m}),B=Number(f.weight.ref_time),T=String(f.weight.proof_size),h=s.data,E=be(l),z=Ae(e,d,b,B,T,h),y=r.tx.PolkadotXcm.send({dest:E,message:z}),w=[];if(this.#n){let v=await this.#n.getCalldata(t,a.srcFeeAsset||c,u,b,10),At=await r.txFromCallData(Vt.Binary.fromHex(v));w.push(At)}let A=await n(b),O=await r.txFromCallData(Vt.Binary.fromHex(A.data));w.push(O),w.push(y);let R=r.tx.Utility.batch_all({calls:w});return{from:t,data:R.decodedCall,type:J.CallType.Substrate,dryRun:this.#t.isDryRunSupported()?async()=>{try{let v=await this.#t.dryRun(t,R);return console.log(v.execution_result),{call:"polkadotXcm.send",error:v.execution_result&&!v.execution_result.success?G(v.execution_result.value):void 0,events:v.emitted_events||[],xcm:v.forwarded_xcms||[]}}catch(v){return{call:"polkadotXcm.send",error:v instanceof Error?v.message:"unknown"}}}:()=>{}}}};var V=require("@galacticcouncil/xc-core"),H=require("rxjs");var x=require("@galacticcouncil/xc-core"),ve=require("@polkadot-api/substrate-bindings"),ft=require("@polkadot-api/utils");var{Ss58Addr:we}=x.addr,S=class i{client;api;chain;_chainSpec;_asset;_decimals;constructor(t,e){this.client=t,this.api=t.getUnsafeApi(),this.chain=e}static async create(t){return new i(t.api,t)}async getChainSpec(){return this._chainSpec||(this._chainSpec=await this.client.getChainSpecData()),this._chainSpec}async getAsset(){if(!this._asset){let e=(await this.getChainSpec()).properties?.tokenSymbol,n=(Array.isArray(e)?e[0]:e).toLowerCase(),a=this.chain.getAsset(n);if(!a)throw new Error(`No asset found for key "${n}"`);this._asset=a}return this._asset}async getDecimals(){if(this._decimals===void 0){let s=((await this.getChainSpec()).properties?.tokenDecimals||[])[0]||12;return this._decimals=s,s}return this._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 e=await this.getAsset(),s=await this.getDecimals();return x.AssetAmount.fromAsset(e,{amount:t,decimals:s})}isDryRunSupported(){return this.api.apis?.DryRunApi!==void 0}async getDecimalsForAsset(t){let e=await this.getDecimals();return this.chain.getAssetDecimals(t)??e}getExtrinsic(t){let e=dt(t.module),s=Ce(t.func),n=this.api.tx[e];if(!n)throw new Error(`Pallet "${t.module}" (${e}) not found in runtime`);let a=n[s];if(!a||typeof a!="function")throw new Error(`Extrinsic "${t.func}" (${s}) not found in pallet "${e}"`);let r=t.getArgs();return this.isBatchCall(t.func)?this.buildBatchCall(a,r):a(r)}isBatchCall(t){return["batch","batchAll","forceBatch"].includes(t)}buildBatchCall(t,e){if(!e||typeof e!="object")throw new Error("Batch call requires transaction data");if(Array.isArray(e)){let s=e.map(n=>n instanceof x.ExtrinsicConfig?this.getExtrinsic(n):n);return t({calls:s})}if("calls"in e&&Array.isArray(e.calls)){let s=e.calls.map(n=>n instanceof x.ExtrinsicConfig?this.getExtrinsic(n):n);return t({...e,calls:s})}return t(e)}async buildMessageId(t,e,s,n){let a=await this.client._request("system_accountNextIndex",[t]),r=new Uint8Array(4);new DataView(r.buffer).setUint32(0,a,!0);let c=l=>new TextEncoder().encode(l),o=new Uint8Array([...c(this.chain.parachainId.toString()),...(0,ft.fromHex)(t.startsWith("0x")?t.slice(2):t),...r,...(0,ft.fromHex)(s.startsWith("0x")?s.slice(2):s),...c(n),...c(e.toString())]),u=(0,ve.Blake2256)(o);return(0,ft.toHex)(u)}async dryRun(t,e){if(!this.api.apis?.DryRunApi)throw new Error("DryRunApi not available on this chain");let s={System:{Signed:t}},n=e.decodedCall,a=await this.api.apis.DryRunApi.dry_run_call(s,n);if(!a.success)throw new Error("DryRun call failed");return a.value}async estimateNetworkFee(t,e){let s=await this.getExtrinsic(e);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=this.getExtrinsic(e),a=await this.dryRun(s,n);if(a.execution_result?.success)return ye(a.emitted_events||[]);{let r=G(a.execution_result?.value);console.warn(`Can't estimate delivery fee. Reason:
|
|
4
|
-
${r}`)}}catch{}}return 0n}async estimateDeliveryFeeWith(t,e){if(["xcmPallet","polkadotXcm"].includes(e.module)){let s=e.getArgs();if(!s||typeof s!="object")return t;let n="dest"in s?s.dest:void 0;if(!n)return t;let a=x.multiloc.findNestedKey(n,"interior"),r=x.multiloc.findParachain(n);if(x.multiloc.findGlobalConsensus(n))return t;if(r){let o=x.acc.getSovereignAccounts(r);return this.chain.parachainId===0?we.encodePubKey(o.relay):we.encodePubKey(o.generic)}if(a&&a.interior==="Here")return this.chain.treasury||t}return t}};var pt=class{#t;#e;constructor(t){this.#t=S.create(t),this.#e=V.DexFactory.getInstance().get(t.key)}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 V.Asset(s)}:void 0,o=await a.getExtrinsic(n),u=n.module+"."+n.func,l=await o.getEncodedData();return{from:t,data:l.asHex(),type:V.CallType.Substrate,txOptions:c,dryRun:a.isDryRunSupported()?async()=>{try{let m=a.getExtrinsic(n),d=await a.dryRun(t,m),g=d.execution_result&&!d.execution_result.success?G(d.execution_result.value):void 0;return{call:u,error:g,events:d.emitted_events||[],xcm:d.forwarded_xcms||[]}}catch(m){return{call:u,error:m instanceof Error?m.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),o=await this.exchangeFee(r+c,s),u=await qt(o,s,a);return s.copyWith(u)}async getBalance(t,e){let s=await this.subscribeBalance(t,e);return(0,H.firstValueFrom)(s)}async subscribeBalance(t,e){let s=await this.#t,{module:n,func:a,args:r,transform:c}=e,o=dt(n),u=dt(a),m=s.client.getUnsafeApi().query[o];if(!m)throw new Error(`Query module "${n}" (${o}) not found in runtime`);let d=m[u];if(!d)throw new Error(`Query function "${a}" (${u}) not found in module "${o}"`);return d.watchValue(...r).pipe((0,H.concatMap)(f=>c(f)),(0,H.distinctUntilChanged)((f,p)=>f===p),(0,H.concatMap)(async f=>{let p=await qt(f,t,s);return V.AssetAmount.fromAsset(t,p)}))}async exchangeFee(t,e){let s=await this.#t,n=await s.getAsset(),a=await s.getDecimals();if(n.isEqual(e))return t;if(this.#e){let r=V.AssetAmount.fromAsset(n,{amount:t,decimals:a});return(await this.#e.getQuote(e,n,r,!0)).amount}return t}};var Wt=require("@galacticcouncil/xc-core"),Be=require("@mysten/bcs"),L=require("rxjs");var Ot=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 xe=require("@mysten/sui/utils");var tn=9,_t=class extends Ot{async getBalance(){let{address:t}=this.config,e=await this.client.getBalance({owner:t,coinType:xe.SUI_TYPE_ARG});return BigInt(e.totalBalance)}async getDecimals(){return tn}};var Nt=class{static get(t,e){switch(e.module){case"Native":return new _t(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};var Se=require("@mysten/bcs");function Pe(i,t={}){let e=i.inputs??[],s=i.commands??[],n=t.numbers??"string",a=t.decode32As??"address",r=l=>n==="bigint"?l:n==="number"?Number(l):l.toString(),c=l=>{let m=(0,Se.fromBase64)(l),d=g=>{let f=0n;for(let p=0;p<g;p++)f|=BigInt(m[p])<<8n*BigInt(p);return f};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(f=>f.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 c(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}},u=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(u)}}}if(l.SplitCoins){let m=l.SplitCoins,d=m.coin?.GasCoin?"GasCoin":u(m.coin),g=(m.amounts??[]).map(u);return{SplitCoins:[d,g]}}if(l.MergeCoins){let m=l.MergeCoins;return{MergeCoins:{...m,destination:u(m.destination),sources:(m.sources??[]).map(u)}}}if(l.TransferObjects){let m=l.TransferObjects;return{TransferObjects:{...m,objects:(m.objects??[]).map(u),address:u(m.address)}}}return l})}var ht=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(),o=Pe(JSON.parse(c));return{from:t,commands:o,data:(0,Be.toBase64)(r),type:Wt.CallType.Sui,dryRun:async()=>{let u=await this.#t.dryRunTransactionBlock({transactionBlock:r});return{call:n.module+"."+n.func,error:u.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,u=BigInt(o.computationCost),l=BigInt(o.storageCost),m=BigInt(o.storageRebate),d=u+l-m;return s.copyWith({amount:d})}async getBalance(t,e){let s=Nt.get(this.#t,e),[n,a]=await Promise.all([s.getBalance(),s.getDecimals()]);return Wt.AssetAmount.fromAsset(t,{amount:n,decimals:a})}async subscribeBalance(t,e){let s=new L.Subject,n=s.pipe((0,L.shareReplay)(1)),a=async()=>{await(async()=>{let u=await this.getBalance(t,e);s.next(u)})();let o=setInterval(()=>{},3e3);return()=>clearInterval(o)},r;return a().then(c=>r=c),n.pipe((0,L.finalize)(()=>r?.()),(0,L.distinctUntilChanged)((c,o)=>c.amount===o.amount))}};var U=class{platform={};constructor(t){switch(t.getType()){case Y.ChainType.EvmChain:this.registerEvm(t);break;case Y.ChainType.EvmParachain:this.registerEvm(t),this.registerSubstrate(t);break;case Y.ChainType.Parachain:this.registerSubstrate(t);break;case Y.ChainType.SolanaChain:this.registerSolana(t);break;case Y.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 ct(e)}registerSui(t){let e=t;this.platform.Sui=new ht(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)}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 D=require("@galacticcouncil/xc-core"),Xt=require("@galacticcouncil/common");var Te=require("@galacticcouncil/common"),Z=qe(require("big.js"),1);function Ee(i,t,e,s){let n=i.toBig().minus(e.toBig()).minus(i.isSame(t)?t.toBig():new Z.default(0));return s&&(n=n.minus(i.isSame(s)?s.toBig():new Z.default(0))),i.copyWith({amount:n.lt(0)?0n:BigInt(n.toFixed())})}function Fe(i,t,e,s){let a=i.copyWith({amount:0n}).toBig().plus(i.isSame(t)?t.toBig():new Z.default(0)).plus(i.toBig().lt(e.toBig())?e.toBig():new Z.default(0));return s&&(a=a.plus(i.isSame(s)&&i.toBig().lt(s.toBig())?s.toBig():new Z.default(0))),i.copyWith({amount:BigInt(a.toFixed())})}async function j(i,t){return t.isEvmParachain()?t.getDerivatedAddress(i):i}function De(i,t){return t?Te.big.toBigInt(t,i):0n}var $=require("@galacticcouncil/xc-core"),Ie=require("@galacticcouncil/common");var{EvmAddr:en}=$.addr,tt=class{adapter;config;constructor(t,e){this.adapter=t,this.config=e}async getEd(){let{chain:t}=this.config;if(t instanceof $.Parachain)return(await S.create(t)).getExistentialDeposit()}async getBalance(t){let{chain:e,route:s}=this.config,{source:n}=s,a=n.asset,r=e.getBalanceAssetId(a),c=en.isValid(r.toString())?await j(t,e):t,o=s.source.balance.build({address:c,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 $.Parachain&&a){let r=t.getMinAssetId(n),c=a.build({asset:r});return this.adapter.getBalance(n,c)}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),c=0n;return a&&(c=Ie.big.toBigInt(a,r)),$.AssetAmount.fromAsset(n,{amount:c,decimals:r})}async getDecimals(t){let{chain:e}=this.config,s=e.getAssetDecimals(t);return s||(await e.getCurrency()).decimals}};var{EvmAddr:Re}=D.addr,yt=class extends tt{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(){let{chain:t,route:e}=this.config,{source:s,destination:n,transact:a}=e,r=n.fee.amount,c=s.destinationFee.asset||n.fee.asset,o=await this.getDecimals(c);if(Number.isFinite(r))return{fee:D.AssetAmount.fromAsset(c,{amount:Xt.big.toBigInt(r,o),decimals:o}),feeBreakdown:{}};let u=r,{amount:l,breakdown:m}=await u.build({feeAsset:c,transferAsset:s.asset,source:a?a.chain:t,destination:n.chain});return{fee:D.AssetAmount.fromAsset(c,{amount:l,decimals:o}),feeBreakdown:m}}async getDestinationFeeBalance(t){let{chain:e,route:s}=this.config,{source:n,destination:a}=s,r=n.asset,c=n.destinationFee.asset||a.fee.asset;if(r.isEqual(c))return this.getBalance(t);let o=e.getBalanceAssetId(c),u=Re.isValid(o.toString())?await j(t,e):t,l=n.destinationFee.balance.build({address:u,asset:c,chain:e});return this.adapter.getBalance(c,l)}async getFee(t){let{chain:e,route:s}=this.config,{amount:n,sender:a,source:r}=t,c=await this.getTransfer(t),o=s.contract?await j(a,e):a,u=await this.adapter.estimateFee(o,n,r.feeBalance,c),{fee:l}=s.source,m=l?De(u.decimals,l.extra):0n,d=u.amount+m;return u.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),c=Re.isValid(r.toString())?await j(t,e):t,o=n.fee.balance.build({address:c,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 c=a.asset;return e instanceof D.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:u,amount:l,asset:m,sender:d}=t,f=await(await S.create(e)).buildMessageId(d,l,m.originSymbol,u);return a.build({...t,messageId:f})}let o=n||r||c;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=n.build(e),c=await(await S.create(s)).getExtrinsic(a),o=e.source.chain,u=e.sender,l=D.acc.getMultilocationDerivatedAccount(o.parachainId,u,s.parachainId===0?0:1,s.usesH160Acc),m=await c.getPaymentInfo(l),[d,g]=await Promise.all([this.getTransactFee(t),this.getTransactFeeBalance(t,e)]);return{call:c.decodedCall,chain:s,fee:d,feeBalance:g,weight:{refTime:Number(m.weight.ref_time),proofSize:String(m.weight.proof_size)}}}async getTransactFee(t){let{fee:e}=t,s=await this.getDecimals(e.asset),n=Xt.big.toBigInt(e.amount,s);return D.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 Ct=class extends tt{constructor(t,e){super(t,e)}};var Lt=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 Lt.DexFactory.getInstance().get(t.chain.key)}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:Lt.AssetAmount.fromAsset(e,{amount:n,decimals:s}),enabled:!0}}isSwapSupported(t){let e=!!this.dex,s=t&&t.swap;return e&&!!s}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){let e=!!this.dex,s=!t.isSame(this.destFee),n=this.asset.isSame(this.destFee);return e&&s&&!n}};var{EvmAddr:nn}=I.addr,Ut=class{config;validations;constructor({configService:t,transferValidations:e}){this.config=t,this.validations=e||[]}registerDex(...t){t.forEach(e=>I.DexFactory.getInstance().register(e))}async transfer(t,e,s,n,a){let r=(0,I.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[u,l]=await Promise.all([S.create(r),S.create(c)]),m=new gt(u,l),d=I.acc.getMultilocationDerivatedAccount(r.parachainId,t,1,c.usesH160Acc),g=await l.getAsset(),f=await this.transfer(g,t,e,d,s);return m.remoteExec(t,d,n,p=>{let b=p.toDecimal(p.decimals);return f.buildCall(b)},a)}async getTransferData(t,e,s){let n=t.origin,a=t.reverse,r=new U(n.chain),c=new U(a.chain),o=new yt(r,n),u=new Ct(c,a),l=new I.TransferValidator(...this.validations),[m,d,g,f,p,b,B]=await Promise.all([o.getBalance(e),o.getFeeBalance(e),o.getDestinationFee(),o.getDestinationFeeBalance(e),o.getMin(),u.getBalance(s),u.getMin()]),{source:T,destination:h}=n.route,E=g.fee.copyWith(h.fee.asset),z=g.feeBreakdown,y={address:s,amount:1n,asset:T.asset,destination:{balance:b,chain:a.chain,fee:E,feeBreakdown:z},sender:e,source:{balance:m,chain:n.chain,fee:d.copyWith({amount:0n}),feeBalance:d,destinationFee:g.fee,destinationFeeBalance:f}};y.transact=await o.getTransact(y);let w=new et(y),A=await o.getFee(y),O;w.isSwapSupported(T.fee)&&(O=await w.getSwap(A),y.source.feeSwap=O);let R;w.isDestinationSwapSupported(A)&&(R=await w.getDestinationSwap(A),y.source.destinationFeeSwap=R),(O||R)&&(A=await o.getFee(y),A=A.padByPct(5n));let v=await u.getEd(),At=Fe(b,E,B,v),We=await o.getEd(),Le=Ee(m,A,p,We);return y.amount=0n,y.source.fee=A,{source:{balance:m,destinationFee:g.fee,destinationFeeBalance:f,destinationFeeSwap:R,fee:A,feeBalance:d,feeSwap:O,max:Le,min:m.copyWith({amount:At.amount})},destination:{balance:b,fee:E},async buildCall(nt){let P=Object.assign({},y);return P.amount=Gt.big.toBigInt(nt,m.decimals),P.transact=await o.getTransact(P),o.getCall(P)},async estimateFee(nt){let P=Object.assign({},y);return P.amount=Gt.big.toBigInt(nt,m.decimals),P.transact=await o.getTransact(P),o.getFee(P)},async validate(nt){let P=Object.assign({},y),Ue=nt||A.amount;return P.source.fee=A.copyWith({amount:Ue}),l.validate(P)}}}async subscribeBalance(t,e,s){let n=this.config.getChainRoutes(e),a=new U(n.chain),r=n.getUniqueRoutes().map(async({source:u})=>{let{asset:l,balance:m}=u,d=n.chain.getBalanceAssetId(l),g=nn.isValid(d.toString())?await j(t,n.chain):t,f=m.build({address:g,asset:l,chain:n.chain});return a.subscribeBalance(l,f)}),c=await Promise.all(r);return(0,jt.combineLatest)(c).pipe((0,jt.debounceTime)(500)).subscribe(s)}};var ke=require("@galacticcouncil/xc-core");function Me(i){let t=(0,ke.ConfigBuilder)(i.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,build:o}=a.destination(r);return{routes:c,build({srcAddress:u,dstAddress:l,dstAsset:m}){let d=o(m);return i.getTransferData(d,u,l)}}}}}}}}}var Ve=require("@galacticcouncil/xc-core"),sn="https://api.wormholescan.io",bt=class{_baseUrl;constructor(t){this._baseUrl=t||sn}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===Ve.Precompile.Bridge}};var C=require("@galacticcouncil/xc-core"),Oe=require("@wormhole-foundation/sdk-base"),_e=require("@wormhole-foundation/sdk-connect"),Ne=require("@wormhole-foundation/sdk-definitions");var Jt=(s=>(s[s.WaitingForVaa=0]="WaitingForVaa",s[s.VaaEmitted=1]="VaaEmitted",s[s.Completed=2]="Completed",s))(Jt||{});var an=300*1e3,Yt=class{parachainId;config;whScan;constructor(t,e){this.config=t,this.parachainId=e,this.whScan=new bt}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=C.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:o}=r,u=this.getStatus(a),l=this.chains.find(p=>p instanceof C.Parachain&&p.parachainId===this.parachainId),{toAddress:m,tokenAddress:d}=o,g=this.chains.find(p=>C.Wormhole.isKnown(p)&&C.Wormhole.fromChain(p).getWormholeId()===c.tokenChain),f;if(u===1&&a.vaa){let{timestamp:p}=this.getVaaHeader(a.vaa.raw),b=a.vaa.raw;if(this.isStuck(p))switch(g.getType()){case C.ChainType.EvmChain:let B=new st(g);f=async h=>B.redeem(h,b);break;case C.ChainType.SolanaChain:let T=new mt(g);f=async h=>T.redeem(h,b);break}}return{asset:d,assetSymbol:a.data.symbol,amount:a.data.tokenAmount,from:t,fromChain:l,to:m,toChain:g,status:u,redeem:f,operation:a}});return Promise.all(n)}async getDeposits(t,e="hydration"){let s=await this.whScan.getOperations({...this.filters,address:C.Precompile.Bridge,pageSize:"100"}),n=this.config.chains.get(e);if(!n)return[];let a=n,c=(await C.mrl.createPayload(a,t)).toHex(),o=s.filter(u=>{let{content:l}=u,{payload:m}=l;return m.payloadType===3&&m.toChain===16&&"0x"+m.payload===c}).map(async u=>{let{content:l,sourceChain:m}=u,{payload:d,standarizedProperties:g}=l,f=this.getStatus(u),{tokenAddress:p}=g,b=this.chains.find(h=>C.Wormhole.isKnown(h)&&C.Wormhole.fromChain(h).getWormholeId()===d.tokenChain),B=this.chains.find(h=>C.Wormhole.isKnown(h)&&C.Wormhole.fromChain(h).getWormholeId()===d.toChain),T;if(f===1&&u.vaa){let{timestamp:h}=this.getVaaHeader(u.vaa.raw),E=u.vaa.raw;if(this.isStuck(h)){let z=new lt(B);T=async y=>z.redeemMrlViaXcm(y,E)}}return{asset:p,assetSymbol:u.data.symbol,amount:u.data.tokenAmount,from:m.from,fromChain:b,to:t,toChain:n,status:f,redeem:T,operation:u}});return Promise.all(o)}isStuck(t){return Date.now()>=t*1e3+an}getVaaHeader(t){let e=Oe.encoding.b64.decode(t),s=(0,Ne.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,_e.keccak256)(s.hash)}}getStatus(t){return t.vaa?t.targetChain&&t.targetChain.status==="completed"?2:1:0}};0&&(module.exports={EvmClaim,EvmPlatform,FeeSwap,PlatformAdapter,SolanaClaim,SolanaLilJit,SolanaPlatform,SubstrateClaim,SubstrateExec,SubstratePlatform,SubstrateService,SuiPlatform,TransferBuilder,Wallet,WhStatus,WormholeScan,WormholeTransfer,chunkBySize,deserializeV0,ixToHuman,serializeV0});
|
|
1
|
+
"use strict";var Qe=Object.create;var Ct=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var Xe=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Ge=(i,t)=>{for(var e in t)Ct(i,e,{get:t[e],enumerable:!0})},se=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qe(t))!$e.call(i,s)&&s!==e&&Ct(i,s,{get:()=>t[s],enumerable:!(n=Ke(t,s))||n.enumerable});return i};var Je=(i,t,e)=>(e=i!=null?Qe(Xe(i)):{},se(t||!i||!i.__esModule?Ct(e,"default",{value:i,enumerable:!0}):e,i)),Ye=i=>se(Ct({},"__esModule",{value:!0}),i);var un={};Ge(un,{EvmClaim:()=>et,EvmPlatform:()=>st,FeeSwap:()=>tt,PlatformAdapter:()=>L,SolanaClaim:()=>ct,SolanaLilJit:()=>ot,SolanaPlatform:()=>it,SubstrateClaim:()=>ut,SubstrateExec:()=>mt,SubstratePlatform:()=>dt,SubstrateService:()=>S,SuiPlatform:()=>gt,TransferBuilder:()=>je,Wallet:()=>jt,WhStatus:()=>ee,WormholeScan:()=>ht,WormholeTransfer:()=>ne,chunkBySize:()=>qt,deserializeV0:()=>en,ixToHuman:()=>H,serializeV0:()=>rt});module.exports=Ye(un);var te=require("@galacticcouncil/common"),R=require("@galacticcouncil/xc-core"),Lt=require("rxjs");var J=require("@galacticcouncil/xc-core");var bt=require("@galacticcouncil/xc-core"),ae=require("viem"),Kt=require("@wormhole-foundation/sdk-base"),et=class{#t;constructor(t){this.#t=t}redeem(t,e){let n=bt.Wormhole.fromChain(this.#t),s=Kt.encoding.b64.decode(e),a=Kt.encoding.hex.encode(s),r=bt.Abi.TokenBridge,o=(0,ae.encodeFunctionData)({abi:r,functionName:"completeTransfer",args:["0x"+a]});return{abi:JSON.stringify(r),data:o,from:t,to:n.getTokenBridge()}}};var k=require("@galacticcouncil/xc-core"),_=require("rxjs");var q=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 EVM client found")}validateConfig(t){if(!t.address)throw new Error("Contract address is required")}};var re=require("@galacticcouncil/xc-core");var At=class extends q{erc20;constructor(t,e){super(t,e),this.erc20=new re.Erc20Client(t,e.address)}async getBalance(){let{args:t}=this.config,[e]=t;return this.erc20.balanceOf(e)}async getDecimals(){return this.erc20.decimals()}};var vt=class extends q{async getBalance(){let t=this.client.getProvider(),{address:e}=this.config;return t.getBalance({address:e})}async getDecimals(){return this.client.chain.nativeCurrency.decimals}};var wt=class{static get(t,e){switch(e.module){case"Erc20":return new At(t,e);case"Native":return new vt(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};var St=require("viem"),xt=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:n,value:s,func:a}=this.config;return await this.client.getProvider().estimateContractGas({address:e,abi:this.abi,functionName:a,args:n,value:s,account:t})}async estimateFee(t,e){if(e===0n)return 0n;try{let n=await this.estimateGas(t),s=await this.getGasPrice();return n*s}catch(n){return n instanceof St.ContractFunctionExecutionError?console.log(`Can't estimate fees!
|
|
2
|
+
`,n.message):console.log(n),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:n,value:s,func:a}=this.config,r=this.client.getProvider(),o=await this.getNonce(t);try{let{results:c}=await r.simulateCalls({account:t,calls:[{to:e,abi:this.abi,functionName:a,args:n,value:s}],stateOverrides:[{address:t,nonce:o}]}),[u]=c;return u}catch(c){return console.log(`Can't simulate call!
|
|
3
|
+
`,c.details),{error:c}}}decodeEvents(t){let e=[];return t&&t.forEach(n=>{try{let{eventName:s,args:a}=(0,St.decodeEventLog)({abi:this.abi,data:n.data,topics:n.topics});e.push({eventName:s,args:a})}catch{}}),e}};var nt=class{static get(t,e){return new xt(t,e)}};var ie=require("@galacticcouncil/xc-core");function oe(i){let t=i.module==="Snowbridge"&&i.func==="sendToken"&&i.args[0]==="0x0000000000000000000000000000000000000000";return i.module==="TokenBridge"&&["wrapAndTransferETHWithPayload","wrapAndTransferETH"].includes(i.func)||t}function ce(i){return Object.entries(ie.Precompile).map(([e,n])=>n).includes(i.address)}var st=class{#t;constructor(t){this.#t=t.evmClient}async buildCall(t,e,n,s){let a=nt.get(this.#t,s),{abi:r,asset:o,calldata:c}=a,u={abi:JSON.stringify(r),data:c,from:t,to:s.address,type:k.CallType.Evm,value:s.value,dryRun:async()=>{let{error:g,logs:p}=await a.simulateCall(t),f=a.decodeEvents(p);return{call:s.module+"."+s.func,error:g?.shortMessage,events:f}}};if(ce(s)||oe(s))return u;let l=new k.Erc20Client(this.#t,o),m=await l.allowance(t,s.address);if(m>=e)return u;let d=l.approve(s.address,e);return{abi:JSON.stringify(k.Abi.Erc20),allowance:m,data:d,from:t,to:o,type:k.CallType.Evm,dryRun:()=>{}}}async estimateFee(t,e,n,s){let r=await nt.get(this.#t,s).estimateFee(t,e);return n.copyWith({amount:r})}async getBalance(t,e){let n=wt.get(this.#t,e),[s,a]=await Promise.all([n.getBalance(),n.getDecimals()]);return k.AssetAmount.fromAsset(t,{amount:s,decimals:a})}async subscribeBalance(t,e){let n=new _.Subject,s=n.pipe((0,_.shareReplay)(1)),a=this.#t.getProvider(),r=async()=>{let c=async()=>{let l=await this.getBalance(t,e);n.next(l)};await c();let u=a.watchBlocks({onBlock:()=>c()});return()=>u()},o;return r().then(c=>o=c),s.pipe((0,_.finalize)(()=>o?.()),(0,_.distinctUntilChanged)((c,u)=>c.amount===u.amount))}};var Dt=require("@galacticcouncil/xc-core"),fe=require("@solana/web3.js"),he=require("buffer"),N=require("rxjs");var X=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 ue=require("@wormhole-foundation/sdk-solana");var Ze=9,Pt=class extends X{async getBalance(){let{address:t}=this.config,e=new ue.SolanaAddress(t).unwrap(),n=await this.connection.getBalance(e);return BigInt(n)}async getDecimals(){return Ze}};var Bt=require("@wormhole-foundation/sdk-solana");var Tt=class extends X{constructor(t,e){super(t,e),this.validateToken(e)}async getBalance(){let{address:t,token:e}=this.config,n=new Bt.SolanaAddress(t).unwrap(),s=new Bt.SolanaAddress(e).unwrap();return(await this.connection.getParsedTokenAccountsByOwner(n,{mint:s})).value.reduce((r,{account:o})=>{let c=o.data.parsed.info.tokenAmount;return r+=BigInt(c.amount),r},0n)}async getDecimals(){let{token:t}=this.config,e=new Bt.SolanaAddress(t).unwrap();return(await this.connection.getTokenSupply(e)).value.decimals}validateToken(t){if(!t.token)throw new Error("Token address is required")}};var Et=class{static get(t,e){switch(e.module){case"Native":return new Pt(t,e);case"Token":return new Tt(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};var F=require("@solana/web3.js"),me=.5,le=2,de=1,ge=1e6,tn=25e4,Ft=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,n=await this.getV0Message(t,e),s=await this.createPriorityFeeInstructions(n);return this.getV0Message(t,[...e,...s])}async estimateFee(t,e){if(e===0n)return 0n;let{instructions:n}=this.config,s=await this.getV0Message(t,n),a=await this.determineComputeBudget(s);return BigInt(a)}async getV0Message(t,e){let n=new F.PublicKey(t),{blockhash:s}=await this.connection.getLatestBlockhash("finalized");return new F.TransactionMessage({payerKey:n,recentBlockhash:s,instructions:e}).compileToV0Message()}async createPriorityFeeInstructions(t,e=me,n=le,s=de,a=ge){let[r,o]=await Promise.all([this.determineComputeBudget(t),this.determinePriorityFee(t,e,n,s,a)]);return[F.ComputeBudgetProgram.setComputeUnitLimit({units:r}),F.ComputeBudgetProgram.setComputeUnitPrice({microLamports:o})]}async simulateTransaction(t,e){let n=new F.VersionedTransaction(e);return(await this.connection.simulateTransaction(n,{accounts:{encoding:"base64",addresses:[t]}})).value}async determineComputeBudget(t){let e=new F.VersionedTransaction(t),n=await this.connection.simulateTransaction(e),{err:s,unitsConsumed:a}=n.value;return a&&!s?Math.round(a*1.2):tn}async determinePriorityFee(t,e=me,n=le,s=de,a=ge){let r=s,o=await this.getTxAccounts(t),c=await this.connection.getRecentPrioritizationFees({lockedWritableAccounts:o});if(c){let u=c.map(m=>m.prioritizationFee).filter(m=>m>0).sort((m,d)=>m-d),l=Math.ceil(u.length*e);if(u.length>l){let d=u[l]*n;r=Math.max(r,d)}}return Math.min(Math.max(r,s),a)}async getTxAccounts(t){let e=(await Promise.all(t.addressTableLookups.map(s=>this.connection.getAddressLookupTable(s.accountKey)))).map(s=>s.value).filter(s=>s!==null),n=t.getAccountKeys({addressLookupTableAccounts:e??void 0});return t.compiledInstructions.flatMap(s=>s.accountKeyIndexes).map(s=>t.isAccountWritable(s)?n.get(s):null).filter(s=>s!==null)}};var at=class{static get(t,e){return new Ft(t,e)}};var pe=require("@solana/web3.js");function H(i){return i.map(t=>({program:t.programId.toBase58(),data:t.data.toString("hex"),keys:t.keys.map(e=>e.pubkey.toBase58())}))}function qt(i,t=1e3){let e=[],n=[],s=0;for(let a of i){let r=a.data?.length??0;n.length&&s+r>t&&(e.push(n),n=[],s=0),n.push(a),s+=r}return n.length&&e.push(n),e}function rt(i){let t=i.serialize();return Buffer.from(t).toString("hex")}function en(i){let t=Buffer.from(i,"hex"),e=Uint8Array.from(t);return pe.MessageV0.deserialize(e)}var it=class{#t;constructor(t){this.#t=t.connection}async buildCall(t,e,n,s){let a=at.get(this.#t,s),r=await a.getPriorityMessage(t),o=r.serialize(),c=he.Buffer.from(o).toString("hex");return{from:t,data:c,ix:H(s.instructions),signers:s.signers,type:Dt.CallType.Solana,dryRun:async()=>{let{err:u,logs:l}=await a.simulateTransaction(t,r);return{call:s.module+"."+s.func,error:u,events:l}}}}async estimateFee(t,e,n,s){let a=at.get(this.#t,s),r=await a.estimateFee(t,e),o=await a.getPriorityMessage(t),{accounts:c}=await a.simulateTransaction(t,o),l=(c&&c[0])?.lamports;if(l){let m=s.module==="TokenBridge"&&s.func==="TransferNativeWithPayload";return n.copyWith({amount:n.amount-BigInt(l)-(m?e:0n)})}return n.copyWith({amount:r})}async getBalance(t,e){let n=Et.get(this.#t,e),[s,a]=await Promise.all([n.getBalance(),n.getDecimals()]);return Dt.AssetAmount.fromAsset(t,{amount:s,decimals:a})}async subscribeBalance(t,e){let n=new N.Subject,s=n.pipe((0,N.shareReplay)(1)),a=async()=>{let o=async()=>{let l=await this.getBalance(t,e);n.next(l)};await o();let c=new fe.PublicKey(e.address),u=this.#t.onAccountChange(c,()=>o());return()=>{this.#t.removeAccountChangeListener(u)}},r;return a().then(o=>r=o),s.pipe((0,N.finalize)(()=>r?.()),(0,N.distinctUntilChanged)((o,c)=>o.amount===c.amount))}};var $=require("@galacticcouncil/xc-core"),V=require("@solana/web3.js"),ye=require("@wormhole-foundation/sdk-solana"),Xt=require("@wormhole-foundation/sdk-solana-core"),Ce=require("@wormhole-foundation/sdk-base"),$t=require("@wormhole-foundation/sdk-definitions"),It=require("@wormhole-foundation/sdk-solana-tokenbridge");var ot=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){let{result:e}=await this.#t._rpcRequest("simulateBundle",[[t]]);return e}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 ct=class{#t;#e;#n;constructor(t){this.#t=t,this.#e=t.connection,this.#n=new ot(t)}async redeem(t,e){let n=$.Wormhole.fromChain(this.#t),s=Ce.encoding.b64.decode(e),a=(0,$t.deserialize)("TokenBridge:Transfer",s),r=(0,$t.deserialize)("Uint8Array",s),o=this.derivePostedVaaKey(n.getCoreBridge(),Buffer.from(a.hash)),c=new V.PublicKey(t),u=[];if(!await this.#e.getAccountInfo(o)){let P=V.Keypair.generate(),x=await Xt.utils.createVerifySignaturesInstructions(this.#t.connection,n.getCoreBridge(),c,r,P.publicKey),y=qt(x,1e3);for(let E=0;E<y.length;E++){let h=y[E],M=await this.getV0Message(c,h),O=rt(M);u.push({from:t,data:O,ix:H(h),signers:[P],type:$.CallType.Solana})}let T=Xt.utils.createPostVaaInstruction(this.#e,n.getCoreBridge(),c,r,P.publicKey),z=await this.getV0Message(c,[T]),C=rt(z);u.push({from:t,data:C,ix:H([T]),type:$.CallType.Solana})}let d=(a.payload.token.chain==="Solana"?It.createCompleteTransferNativeInstruction:It.createCompleteTransferWrappedInstruction)(this.#e,n.getTokenBridge(),n.getCoreBridge(),c,a),g=await this.#n.getTipAccount(),p=V.SystemProgram.transfer({fromPubkey:c,toPubkey:new V.PublicKey(g[0]),lamports:1e3}),f=await this.getV0Message(c,[d,p]),v=rt(f);return u.push({from:t,data:v,ix:H([d]),type:$.CallType.Solana}),u}derivePostedVaaKey(t,e){return ye.utils.deriveAddress([Buffer.from("PostedVAA"),e],t)}async getV0Message(t,e){let{blockhash:n}=await this.#e.getLatestBlockhash("finalized");return new V.TransactionMessage({payerKey:t,recentBlockhash:n,instructions:e}).compileToV0Message()}};var W=require("@galacticcouncil/xc-core"),Gt=require("@wormhole-foundation/sdk-base"),be=require("viem"),ut=class{#t;constructor(t){this.#t=t,W.Wormhole.fromChain(this.#t)}redeemMrl(t,e){let n=Gt.encoding.b64.decode(e),s=Gt.encoding.hex.encode(n),a=W.Abi.Gmp,r=(0,be.encodeFunctionData)({abi:a,functionName:"wormholeTransferERC20",args:["0x"+s]});return{abi:JSON.stringify(a),data:r,from:t,to:W.Precompile.Bridge}}async redeemMrlViaXcm(t,e){let s=this.#t.client.getUnsafeApi(),a=this.redeemMrl(t,e);return{data:s.tx.EthereumXcm.transact({V2:{gas_limit:5000000n,action:{Call:a.to},value:0n,input:a.data}}).decodedCall,from:t,type:W.CallType.Substrate,dryRun:async()=>{},txOptions:void 0}}};var Vt=require("@galacticcouncil/xc-core"),kt=require("polkadot-api");var Ae=require("@galacticcouncil/common");async function Jt(i,t,e){let n=await e.getDecimals(),s=e.chain.getAssetDecimals(t)??n,a=e.chain.usesChainDecimals?n:s;return{amount:Ae.big.convertDecimals(i,a,s),decimals:s}}var ve=require("@galacticcouncil/common"),we=i=>{let t=[];for(let e of i)if(["PolkadotXcm"].includes(e.type)&&e.value.type==="FeesPaid"){let s=e.value.value.fees;for(let a of s)if(a.fun.type==="Fungible"){let r=BigInt(a.fun.value);t.push(r)}}return t.reduce((e,n)=>e+n,0n)},G=i=>{let t=i.value.error;return t.type==="Module"?ve.enums.enumPath(t.value):JSON.stringify(t.value)};var Rt=require("@galacticcouncil/common");function nn(i){return{parents:0,interior:{type:"X1",value:[i.startsWith("0x")?Rt.xcm.toAccountKey20(i):Rt.xcm.toAccountId32(i)]}}}function Se(i){return{type:"V4",value:{parents:1,interior:{type:"X1",value:[{type:"Parachain",value:i.parachainId}]}}}}var xe=(i,t)=>({id:Rt.xcm.transform(i),fun:{type:"Fungible",value:t}}),Pe=(i,t,e,n,s,a)=>{console.log(a);let r=nn(i);return{type:"V4",value:[{type:"WithdrawAsset",value:xe(t,e.amount)},{type:"BuyExecution",value:{fees:xe(t,e.amount),weight_limit:{type:"Unlimited"}}},{type:"Transact",value:{origin_kind:{type:"SovereignAccount"},require_weight_at_most:{ref_time:n,proof_size:s},call:a}},{type:"RefundSurplus"},{type:"DepositAsset",value:{assets:{type:"Wild",value:{type:"AllCounted",value:1}},beneficiary:r}}]}};var mt=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}async remoteExec(t,e,n,s,a={}){let r=this.#t.api,o=await this.#t.getAsset(),c=this.#e.api,u=this.#e.chain,l=await u.getCurrency(),m=l.asset,d=l.decimals,g=u.getAssetXcmLocation(m),p=kt.Binary.fromHex(n.data),v=await(await c.txFromCallData(p)).getPaymentInfo(e),P=BigInt(v.partial_fee)*120n/100n,x=Vt.AssetAmount.fromAsset(m,{amount:P,decimals:d}),y=v.weight.ref_time,T=v.weight.proof_size,z=Se(u),C=Pe(e,g,x,y,T,p),E=r.tx.PolkadotXcm.send({dest:z,message:C}),h=[];try{let b=await this.#t.chain.dex.getCalldata(t,a.srcFeeAsset||o,m,x,10),w=kt.Binary.fromHex(b),Qt=await r.txFromCallData(w);h.push(Qt)}catch{}let M=await s(x),O=kt.Binary.fromHex(M.data),Ut=await r.txFromCallData(O);h.push(Ut),h.push(E);let zt=h.map(b=>b.decodedCall),yt=r.tx.Utility.batch_all({calls:zt}),Ht=await yt.getEncodedData();return{from:t,data:Ht.asHex(),type:Vt.CallType.Substrate,dryRun:this.#t.isDryRunSupported()?async()=>{try{let b=await this.#t.dryRun(t,yt);return{call:"polkadotXcm.send",error:b.execution_result&&b.execution_result.success?void 0:G(b.execution_result),events:b.emitted_events||[],xcm:b.forwarded_xcms||[]}}catch(b){return{call:"polkadotXcm.send",error:b instanceof Error?b.message:"unknown"}}}:()=>{}}}};var Q=require("@galacticcouncil/xc-core"),B=require("rxjs");var D=require("@galacticcouncil/xc-core"),Te=require("@galacticcouncil/common"),Mt=require("@polkadot-api/substrate-bindings"),lt=require("@polkadot-api/utils"),Yt=require("polkadot-api");var{Ss58Addr:Be}=D.addr,S=class i{chain;_currency;constructor(t){this.chain=t}static async create(t){return new i(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 s=await this.api.constants.Balances.ExistentialDeposit();t=typeof s=="bigint"?s:BigInt(String(s))}catch{t=0n}let{asset:e,decimals:n}=await this.getCurrency();return D.AssetAmount.fromAsset(e,{amount:t,decimals:n})}isDryRunSupported(){return this.api.apis?.DryRunApi!==void 0}async buildMessageId(t,e,n,s){let a=await this.client._request("system_accountNextIndex",[t]),r=Mt.u32.enc(a),o=l=>new TextEncoder().encode(l),c=new Uint8Array([...o(this.chain.parachainId.toString()),...(0,lt.fromHex)(t.startsWith("0x")?t.slice(2):t),...r,...(0,lt.fromHex)(n.startsWith("0x")?n.slice(2):n),...o(s),...o(e.toString())]),u=(0,Mt.Blake2256)(c);return(0,lt.toHex)(u)}async dryRun(t,e){let n=(0,Yt.Enum)("Signed",t),s=(0,Yt.Enum)("system",n),a=await this.api.apis.DryRunApi.dry_run_call(s,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: "+Te.enums.enumPath(r.value));return r}async estimateNetworkFee(t,e){let n=e.getTx(this.client);try{let s=await n.getPaymentInfo(t);return BigInt(s.partial_fee)}catch{console.warn("Can't estimate network fee.")}return 0n}async estimateDeliveryFee(t,e){if(this.chain.usesDeliveryFee){let n=await this.estimateDeliveryFeeWith(t,e);try{let s=e.getTx(this.client),a=await this.dryRun(n,s);if(a.execution_result?.success)return we(a.emitted_events||[]);{let r=G(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 s=e.getTx(this.client).decodedCall.value.value,a="dest"in s?s.dest:void 0;if(!a)return t;let r=D.multiloc.findNestedKey(a,"interior"),o=D.multiloc.findParachain(a);if(D.multiloc.findGlobalConsensus(a))return t;if(o){let u=D.acc.getSovereignAccounts(o);return this.chain.parachainId===0?Be.encodePubKey(u.relay):Be.encodePubKey(u.generic)}if(r&&r.interior==="Here")return this.chain.treasury||t}return t}};var dt=class{#t;constructor(t){this.#t=S.create(t)}async useSignerFee(t){let e=await this.#t,n=await e.getAsset();return e.chain.usesSignerFee&&!n.isEqual(t)}async buildCall(t,e,n,s){let a=await this.#t,o=await this.useSignerFee(n)?{asset:new Q.Asset(n)}:void 0,c=s.getTx(a.client),u=s.module+"."+s.func,l=await c.getEncodedData();return{from:t,data:l.asHex(),type:Q.CallType.Substrate,txOptions:o,dryRun:a.isDryRunSupported()?async()=>{try{let m=s.getTx(a.client),d=await a.dryRun(t,m),g=d.execution_result&&d.execution_result.success?void 0:G(d.execution_result);return{call:u,error:g,events:d.emitted_events||[],xcm:d.forwarded_xcms||[]}}catch(m){return{call:u,error:m instanceof Error?m.message:"unknown"}}}:()=>{}}}async estimateFee(t,e,n,s){let a=await this.#t,r=await a.estimateNetworkFee(t,s),o=await a.estimateDeliveryFee(t,s),c=await this.exchangeFee(r+o,n),u=await Jt(c,n,a);return n.copyWith(u)}async getBalance(t,e){let n=await this.subscribeBalance(t,e);return(0,B.firstValueFrom)(n)}async subscribeBalance(t,e){let n=await this.#t,{module:s,func:a,args:r,transform:o}=e;return n.client.getUnsafeApi().query[s][a].watchValue(...r).pipe((0,B.concatMap)(l=>o(l)),(0,B.distinctUntilChanged)((l,m)=>l===m),(0,B.concatMap)(async l=>{let m=await Jt(l,t,n);return Q.AssetAmount.fromAsset(t,m)}),(0,B.catchError)(l=>(console.error("subscribe fails for:",t),(0,B.throwError)(()=>l))))}async exchangeFee(t,e){let n=await this.#t,s=await n.getAsset(),a=await n.getDecimals();if(s.isEqual(e))return t;try{let r=n.chain.dex,o=Q.AssetAmount.fromAsset(s,{amount:t,decimals:a});return(await r.getQuote(e,s,o,!0)).amount}catch{}return t}};var Wt=require("@galacticcouncil/xc-core"),Ie=require("@mysten/bcs"),j=require("rxjs");var Ot=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 Ee=require("@mysten/sui/utils");var sn=9,_t=class extends Ot{async getBalance(){let{address:t}=this.config,e=await this.client.getBalance({owner:t,coinType:Ee.SUI_TYPE_ARG});return BigInt(e.totalBalance)}async getDecimals(){return sn}};var Nt=class{static get(t,e){switch(e.module){case"Native":return new _t(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};var Fe=require("@mysten/bcs");function De(i,t={}){let e=i.inputs??[],n=i.commands??[],s=t.numbers??"string",a=t.decode32As??"address",r=l=>s==="bigint"?l:s==="number"?Number(l):l.toString(),o=l=>{let m=(0,Fe.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)}},c=l=>{let m=e[l];if(!m)return{Input:l};if(m.Pure?.bytes)return o(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}},u=l=>l?.GasCoin?"GasCoin":Array.isArray(l?.NestedResult)?l:typeof l?.Input=="number"?c(l.Input):l;return n.map(l=>{if(l.MoveCall){let m=l.MoveCall;return{MoveCall:{...m,arguments:(m.arguments??[]).map(u)}}}if(l.SplitCoins){let m=l.SplitCoins,d=m.coin?.GasCoin?"GasCoin":u(m.coin),g=(m.amounts??[]).map(u);return{SplitCoins:[d,g]}}if(l.MergeCoins){let m=l.MergeCoins;return{MergeCoins:{...m,destination:u(m.destination),sources:(m.sources??[]).map(u)}}}if(l.TransferObjects){let m=l.TransferObjects;return{TransferObjects:{...m,objects:(m.objects??[]).map(u),address:u(m.address)}}}return l})}var gt=class{#t;constructor(t){this.#t=t.client}async buildCall(t,e,n,s){let{transaction:a}=s;a.setSender(t);let r=await a.build({client:this.#t}),o=await a.toJSON(),c=De(JSON.parse(o));return{from:t,commands:c,data:(0,Ie.toBase64)(r),type:Wt.CallType.Sui,dryRun:async()=>{let u=await this.#t.dryRunTransactionBlock({transactionBlock:r});return{call:s.module+"."+s.func,error:u.executionErrorSource}}}}async estimateFee(t,e,n,s){let{transaction:a}=s;a.setSender(t);let r=await a.build({client:this.#t}),c=(await this.#t.dryRunTransactionBlock({transactionBlock:r})).effects.gasUsed,u=BigInt(c.computationCost),l=BigInt(c.storageCost),m=BigInt(c.storageRebate),d=u+l-m;return n.copyWith({amount:d})}async getBalance(t,e){let n=Nt.get(this.#t,e),[s,a]=await Promise.all([n.getBalance(),n.getDecimals()]);return Wt.AssetAmount.fromAsset(t,{amount:s,decimals:a})}async subscribeBalance(t,e){let n=new j.Subject,s=n.pipe((0,j.shareReplay)(1)),a=async()=>{await(async()=>{let u=await this.getBalance(t,e);n.next(u)})();let c=setInterval(()=>{},3e3);return()=>clearInterval(c)},r;return a().then(o=>r=o),s.pipe((0,j.finalize)(()=>r?.()),(0,j.distinctUntilChanged)((o,c)=>o.amount===c.amount))}};var L=class{platform={};constructor(t){switch(t.getType()){case J.ChainType.EvmChain:this.registerEvm(t);break;case J.ChainType.EvmParachain:this.registerEvm(t),this.registerSubstrate(t);break;case J.ChainType.Parachain:this.registerSubstrate(t);break;case J.ChainType.SolanaChain:this.registerSolana(t);break;case J.ChainType.SuiChain:this.registerSui(t);break;default:throw new Error("Unsupported platform: "+t.getType())}}registerEvm(t){let e=t;this.platform.Evm=new st(e)}registerSolana(t){let e=t;this.platform.Solana=new it(e)}registerSui(t){let e=t;this.platform.Sui=new gt(e)}registerSubstrate(t){let e=t;this.platform.Substrate=new dt(e)}async buildCall(t,e,n,s){return this.platform[s.type].buildCall(t,e,n,s)}async estimateFee(t,e,n,s){return this.platform[s.type].estimateFee(t,e,n,s)}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 I=require("@galacticcouncil/xc-core"),Zt=require("@galacticcouncil/common");var Re=require("@galacticcouncil/common"),Y=Je(require("big.js"),1);function ke(i,t,e,n){let s=i.toBig().minus(e.toBig()).minus(i.isSame(t)?t.toBig():new Y.default(0));return n&&(s=s.minus(i.isSame(n)?n.toBig():new Y.default(0))),i.copyWith({amount:s.lt(0)?0n:BigInt(s.toFixed())})}function Ve(i,t,e,n){let a=i.copyWith({amount:0n}).toBig().plus(i.isSame(t)?t.toBig():new Y.default(0)).plus(i.toBig().lt(e.toBig())?e.toBig():new Y.default(0));return n&&(a=a.plus(i.isSame(n)&&i.toBig().lt(n.toBig())?n.toBig():new Y.default(0))),i.copyWith({amount:BigInt(a.toFixed())})}async function U(i,t){return t.isEvmParachain()?t.getDerivatedAddress(i):i}function Me(i,t){return t?Re.big.toBigInt(t,i):0n}var K=require("@galacticcouncil/xc-core"),Oe=require("@galacticcouncil/common");var{EvmAddr:an}=K.addr,Z=class{adapter;config;constructor(t,e){this.adapter=t,this.config=e}async getEd(){let{chain:t}=this.config;if(t instanceof K.Parachain)return(await S.create(t)).getExistentialDeposit()}async getBalance(t){let{chain:e,route:n}=this.config,{source:s}=n,a=s.asset,r=e.getBalanceAssetId(a),o=an.isValid(r.toString())?await U(t,e):t,c=n.source.balance.build({address:o,asset:a,chain:e});return this.adapter.getBalance(a,c)}async getMin(){let{chain:t,route:e}=this.config,{source:n}=e,s=n.asset,a=n.min;if(t instanceof K.Parachain&&a){let r=t.getMinAssetId(s),o=a.build({asset:r});return this.adapter.getBalance(s,o)}return this.getAssetMin()}async getAssetMin(){let{chain:t,route:e}=this.config,{source:n}=e,s=n.asset,a=t.getAssetMin(s),r=await this.getDecimals(s),o=0n;return a&&(o=Oe.big.toBigInt(a,r)),K.AssetAmount.fromAsset(s,{amount:o,decimals:r})}async getDecimals(t){let{chain:e}=this.config,n=e.getAssetDecimals(t);return n||(await e.getCurrency()).decimals}};var{EvmAddr:_e}=I.addr,pt=class extends Z{constructor(t,e){super(t,e)}async getCall(t){let{amount:e,sender:n,source:s}=t,a=await this.getTransfer(t);return this.adapter.buildCall(n,e,s.feeBalance,a)}async getDestinationFee(){let{chain:t,route:e}=this.config,{source:n,destination:s,transact:a}=e,r=s.fee.amount,o=n.destinationFee.asset||s.fee.asset,c=await this.getDecimals(o);if(Number.isFinite(r))return{fee:I.AssetAmount.fromAsset(o,{amount:Zt.big.toBigInt(r,c),decimals:c}),feeBreakdown:{}};let u=r,{amount:l,breakdown:m}=await u.build({feeAsset:o,transferAsset:n.asset,source:a?a.chain:t,destination:s.chain});return{fee:I.AssetAmount.fromAsset(o,{amount:l,decimals:c}),feeBreakdown:m}}async getDestinationFeeBalance(t){let{chain:e,route:n}=this.config,{source:s,destination:a}=n,r=s.asset,o=s.destinationFee.asset||a.fee.asset;if(r.isEqual(o))return this.getBalance(t);let c=e.getBalanceAssetId(o),u=_e.isValid(c.toString())?await U(t,e):t,l=s.destinationFee.balance.build({address:u,asset:o,chain:e});return this.adapter.getBalance(o,l)}async getFee(t){let{chain:e,route:n}=this.config,{amount:s,sender:a,source:r}=t,o=await this.getTransfer(t),c=n.contract?await U(a,e):a,u=await this.adapter.estimateFee(c,s,r.feeBalance,o),{fee:l}=n.source,m=l?Me(u.decimals,l.extra):0n,d=u.amount+m;return u.copyWith({amount:d})}async getFeeBalance(t){let{chain:e,route:n}=this.config,{source:s}=n;if(!s.fee)return this.getBalance(t);let a=await this.getFeeAsset(t),r=e.getBalanceAssetId(a),o=_e.isValid(r.toString())?await U(t,e):t,c=s.fee.balance.build({address:o,asset:a,chain:e});return this.adapter.getBalance(a,c)}async getFeeAsset(t){let{chain:e,route:n}=this.config,{source:s}=n,a=s.fee,r=s.asset;if(!a)return r;let o=a.asset;return e instanceof I.Parachain&&"build"in o?await o.build({chain:e,address:t}):o}async getTransfer(t){let{chain:e,route:n}=this.config,{contract:s,extrinsic:a,program:r,move:o}=n;if(a){let{address:u,amount:l,asset:m,sender:d}=t,p=await(await S.create(e)).buildMessageId(d,l,m.originSymbol,u);return a.build({...t,messageId:p})}let c=s||r||o;if(c)return c.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:n}=e;if(n){let s=Object.assign({transact:{chain:n.chain}}),a={...t,...s};return{...await this.getTransactData(n,a),chain:n.chain}}}async getTransactData(t,e){let{chain:n,extrinsic:s}=t,a=await s.build(e),r=await S.create(n),o=a.getTx(r.client),c=e.source.chain,u=e.sender,l=I.acc.getMultilocationDerivatedAccount(c.parachainId,u,n.parachainId===0?0:1,n.usesH160Acc),m=await o.getPaymentInfo(l),d=await o.getEncodedData(),[g,p]=await Promise.all([this.getTransactFee(t),this.getTransactFeeBalance(t,e)]);return{call:d,chain:n,fee:g,feeBalance:p,weight:{refTime:m.weight.ref_time,proofSize:m.weight.proof_size}}}async getTransactFee(t){let{fee:e}=t,n=await this.getDecimals(e.asset),s=Zt.big.toBigInt(e.amount,n);return I.AssetAmount.fromAsset(e.asset,{amount:s,decimals:n})}async getTransactFeeBalance(t,e){let{chain:n}=this.config,{fee:s}=t,a=s.balance.build({address:e.sender,asset:s.asset,chain:n});return this.adapter.getBalance(s.asset,a)}};var ft=class extends Z{constructor(t,e){super(t,e)}};var Ne=require("@galacticcouncil/xc-core"),tt=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:n}=await this.dex.chain.getCurrency(),{amount:s}=await this.dex.getQuote(e,t,t);return{aIn:t,aOut:Ne.AssetAmount.fromAsset(e,{amount:s,decimals:n}),enabled:!0}}isSwapSupported(t){try{this.dex}catch{return!1}return!!(t&&t.swap)}async getDestinationSwap(t){let{amount:e,route:n}=await this.dex.getQuote(t,this.destFee,this.destFee),s=this.destFeeBalance.amount<this.destFee.amount,a=this.feeBalance.amount-t.amount>e*2n;return{aIn:t.copyWith({amount:e}),aOut:this.destFee,enabled:s&&a,route:n}}isDestinationSwapSupported(t){try{this.dex}catch{return!1}let e=!t.isSame(this.destFee),n=this.asset.isSame(this.destFee);return e&&!n}};var{EvmAddr:rn}=R.addr,jt=class{config;validations;constructor({configService:t,transferValidations:e}){this.config=t,this.validations=e||[]}registerDex(...t){t.forEach(e=>R.DexFactory.getInstance().register(e))}async transfer(t,e,n,s,a){let r=(0,R.ConfigBuilder)(this.config).assets().asset(t).source(n).destination(a).build();return this.getTransferData(r,e,s)}async remoteXcm(t,e,n,s,a={}){let r=this.config.getChain(e),o=this.config.getChain(n);if(!(r.isSubstrate()&&o.isSubstrate()))throw Error("RemoteXcm is supported only between parachains");let[u,l]=await Promise.all([S.create(r),S.create(o)]),m=new mt(u,l),d=R.acc.getMultilocationDerivatedAccount(r.parachainId,t,1,o.usesH160Acc),g=await l.getAsset(),p=await this.transfer(g,t,e,d,n);return m.remoteExec(t,d,s,f=>{let v=f.toDecimal(f.decimals);return p.buildCall(v)},a)}async getTransferData(t,e,n){let s=t.origin,a=t.reverse,r=new L(s.chain),o=new L(a.chain),c=new pt(r,s),u=new ft(o,a),l=new R.TransferValidator(...this.validations),[m,d,g,p,f,v,P]=await Promise.all([c.getBalance(e),c.getFeeBalance(e),c.getDestinationFee(),c.getDestinationFeeBalance(e),c.getMin(),u.getBalance(n),u.getMin()]),{source:x,destination:y}=s.route,T=g.fee.copyWith(y.fee.asset),z=g.feeBreakdown,C={address:n,amount:1n,asset:x.asset,destination:{balance:v,chain:a.chain,fee:T,feeBreakdown:z},sender:e,source:{balance:m,chain:s.chain,fee:d.copyWith({amount:0n}),feeBalance:d,destinationFee:g.fee,destinationFeeBalance:p}};C.transact=await c.getTransact(C);let E=new tt(C),h=await c.getFee(C),M;E.isSwapSupported(x.fee)&&(M=await E.getSwap(h),C.source.feeSwap=M);let O;E.isDestinationSwapSupported(h)&&(O=await E.getDestinationSwap(h),C.source.destinationFeeSwap=O),(M||O)&&(h=await c.getFee(C),h=h.padByPct(5n));let Ut=await u.getEd(),zt=Ve(v,T,P,Ut),yt=await c.getEd(),Ht=ke(m,h,f,yt);return C.amount=0n,C.source.fee=h,{source:{balance:m,destinationFee:g.fee,destinationFeeBalance:p,destinationFeeSwap:O,fee:h,feeBalance:d,feeSwap:M,max:Ht,min:m.copyWith({amount:zt.amount})},destination:{balance:v,fee:T},async buildCall(b){let w=Object.assign({},C);return w.amount=te.big.toBigInt(b,m.decimals),w.transact=await c.getTransact(w),c.getCall(w)},async estimateFee(b){let w=Object.assign({},C);return w.amount=te.big.toBigInt(b,m.decimals),w.transact=await c.getTransact(w),c.getFee(w)},async validate(b){let w=Object.assign({},C),Qt=b||h.amount;return w.source.fee=h.copyWith({amount:Qt}),l.validate(w)}}}async subscribeBalance(t,e,n){let s=this.config.getChainRoutes(e),a=new L(s.chain),r=s.getUniqueRoutes().map(async({source:u})=>{let{asset:l,balance:m}=u,d=s.chain.getBalanceAssetId(l),g=rn.isValid(d.toString())?await U(t,s.chain):t,p=m.build({address:g,asset:l,chain:s.chain});return a.subscribeBalance(l,p)}),o=await Promise.all(r);return(0,Lt.combineLatest)(o).pipe((0,Lt.debounceTime)(500)).subscribe(n)}};var We=require("@galacticcouncil/xc-core");function je(i){let t=(0,We.ConfigBuilder)(i.config).assets();return{assets:t,withAsset(e){let n=t.asset(e);return{sources:n,withSource(s){let a=n.source(s);return{destinations:a,withDestination(r){let{routes:o,build:c}=a.destination(r);return{routes:o,build({srcAddress:u,dstAddress:l,dstAsset:m}){let d=c(m);return i.getTransferData(d,u,l)}}}}}}}}}var Le=require("@galacticcouncil/xc-core"),on="https://api.wormholescan.io",ht=class{_baseUrl;constructor(t){this._baseUrl=t||on}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}),s=await(await fetch(e)).json();if(s.data.length>0)return s.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:n,toChain:s}=t,a="0x"+n.substring(26);return e===3&&s===16&&a===Le.Precompile.Bridge}};var A=require("@galacticcouncil/xc-core"),Ue=require("@wormhole-foundation/sdk-base"),ze=require("@wormhole-foundation/sdk-connect"),He=require("@wormhole-foundation/sdk-definitions");var ee=(n=>(n[n.WaitingForVaa=0]="WaitingForVaa",n[n.VaaEmitted=1]="VaaEmitted",n[n.Completed=2]="Completed",n))(ee||{});var cn=300*1e3,ne=class{parachainId;config;whScan;constructor(t,e){this.config=t,this.parachainId=e,this.whScan=new ht}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 n=t.toISOString();return{page:"0",pageSize:"50",includeEndDate:"true",from:e.toISOString(),to:n}}async getWithdraws(t){let e=A.acc.getMultilocationDerivatedAccount(this.parachainId,t,1,!0),s=(await this.whScan.getOperations({...this.filters,address:e})).map(async a=>{let{content:r}=a,{payload:o,standarizedProperties:c}=r,u=this.getStatus(a),l=this.chains.find(f=>f instanceof A.Parachain&&f.parachainId===this.parachainId),{toAddress:m,tokenAddress:d}=c,g=this.chains.find(f=>A.Wormhole.isKnown(f)&&A.Wormhole.fromChain(f).getWormholeId()===o.tokenChain),p;if(u===1&&a.vaa){let{timestamp:f}=this.getVaaHeader(a.vaa.raw),v=a.vaa.raw;if(this.isStuck(f))switch(g.getType()){case A.ChainType.EvmChain:let P=new et(g);p=async y=>P.redeem(y,v);break;case A.ChainType.SolanaChain:let x=new ct(g);p=async y=>x.redeem(y,v);break}}return{asset:d,assetSymbol:a.data.symbol,amount:a.data.tokenAmount,from:t,fromChain:l,to:m,toChain:g,status:u,redeem:p,operation:a}});return Promise.all(s)}async getDeposits(t,e="hydration"){let n=await this.whScan.getOperations({...this.filters,address:A.Precompile.Bridge,pageSize:"100"}),s=this.config.chains.get(e);if(!s)return[];let a=s,o=(await A.mrl.createPayload(a,t)).toHex(),c=n.filter(u=>{let{content:l}=u,{payload:m}=l;return m.payloadType===3&&m.toChain===16&&"0x"+m.payload===o}).map(async u=>{let{content:l,sourceChain:m}=u,{payload:d,standarizedProperties:g}=l,p=this.getStatus(u),{tokenAddress:f}=g,v=this.chains.find(y=>A.Wormhole.isKnown(y)&&A.Wormhole.fromChain(y).getWormholeId()===d.tokenChain),P=this.chains.find(y=>A.Wormhole.isKnown(y)&&A.Wormhole.fromChain(y).getWormholeId()===d.toChain),x;if(p===1&&u.vaa){let{timestamp:y}=this.getVaaHeader(u.vaa.raw),T=u.vaa.raw;if(this.isStuck(y)){let z=new ut(P);x=async C=>z.redeemMrlViaXcm(C,T)}}return{asset:f,assetSymbol:u.data.symbol,amount:u.data.tokenAmount,from:m.from,fromChain:v,to:t,toChain:s,status:p,redeem:x,operation:u}});return Promise.all(c)}isStuck(t){return Date.now()>=t*1e3+cn}getVaaHeader(t){let e=Ue.encoding.b64.decode(t),n=(0,He.deserialize)("Uint8Array",e);return{timestamp:n.timestamp,emitterChain:n.emitterChain,emitterAddress:n.emitterAddress.toString(),sequence:n.sequence,payload:n.payload,hash:n.hash,id:(0,ze.keccak256)(n.hash)}}getStatus(t){return t.vaa?t.targetChain&&t.targetChain.status==="completed"?2:1:0}};0&&(module.exports={EvmClaim,EvmPlatform,FeeSwap,PlatformAdapter,SolanaClaim,SolanaLilJit,SolanaPlatform,SubstrateClaim,SubstrateExec,SubstratePlatform,SubstrateService,SuiPlatform,TransferBuilder,Wallet,WhStatus,WormholeScan,WormholeTransfer,chunkBySize,deserializeV0,ixToHuman,serializeV0});
|
package/build/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{acc as
|
|
2
|
-
`,n.message):console.log(n),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:n,value:s,func:a}=this.config,r=this.client.getProvider(),
|
|
3
|
-
`,i.details),{error:i}}}decodeEvents(t){let e=[];return t&&t.forEach(n=>{try{let{eventName:s,args:a}=de({abi:this.abi,data:n.data,topics:n.topics});e.push({eventName:s,args:a})}catch{}}),e}};var W=class{static get(t,e){return new Y(t,e)}};import{Precompile as ge}from"@galacticcouncil/xc-core";function St(c){let t=c.module==="Snowbridge"&&c.func==="sendToken"&&c.args[0]==="0x0000000000000000000000000000000000000000";return c.module==="TokenBridge"&&["wrapAndTransferETHWithPayload","wrapAndTransferETH"].includes(c.func)||t}function Pt(c){return Object.entries(ge).map(([e,n])=>n).includes(c.address)}var Z=class{#t;constructor(t){this.#t=t.client}async buildCall(t,e,n,s){let a=W.get(this.#t,s),{abi:r,asset:o,calldata:i}=a,u={abi:JSON.stringify(r),data:i,from:t,to:s.address,type:Bt.Evm,value:s.value,dryRun:async()=>{let{error:g,logs:f}=await a.simulateCall(t),p=a.decodeEvents(f);return{call:s.module+"."+s.func,error:g?.shortMessage,events:p}}};if(Pt(s)||St(s))return u;let l=new he(this.#t,o),m=await l.allowance(t,s.address);if(m>=e)return u;let d=l.approve(s.address,e);return{abi:JSON.stringify(fe.Erc20),allowance:m,data:d,from:t,to:o,type:Bt.Evm,dryRun:()=>{}}}async estimateFee(t,e,n,s){let r=await W.get(this.#t,s).estimateFee(t,e);return n.copyWith({amount:r})}async getBalance(t,e){let n=J.get(this.#t,e),[s,a]=await Promise.all([n.getBalance(),n.getDecimals()]);return pe.fromAsset(t,{amount:s,decimals:a})}async subscribeBalance(t,e){let n=new Ae,s=n.pipe(be(1)),a=this.#t.getProvider(),r=async()=>{let i=async()=>{let l=await this.getBalance(t,e);n.next(l)};await i();let u=a.watchBlocks({onBlock:()=>i()});return()=>u()},o;return r().then(i=>o=i),s.pipe(Ce(()=>o?.()),ye((i,u)=>i.amount===u.amount))}};import{AssetAmount as Te,CallType as Ee}from"@galacticcouncil/xc-core";import{PublicKey as Fe}from"@solana/web3.js";import{Buffer as De}from"buffer";import{distinctUntilChanged as Ie,finalize as Re,shareReplay as ke,Subject as Me}from"rxjs";var k=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 we}from"@wormhole-foundation/sdk-solana";var ve=9,tt=class extends k{async getBalance(){let{address:t}=this.config,e=new we(t).unwrap(),n=await this.connection.getBalance(e);return BigInt(n)}async getDecimals(){return ve}};import{SolanaAddress as ht}from"@wormhole-foundation/sdk-solana";var et=class extends k{constructor(t,e){super(t,e),this.validateToken(e)}async getBalance(){let{address:t,token:e}=this.config,n=new ht(t).unwrap(),s=new ht(e).unwrap();return(await this.connection.getParsedTokenAccountsByOwner(n,{mint:s})).value.reduce((r,{account:o})=>{let i=o.data.parsed.info.tokenAmount;return r+=BigInt(i.amount),r},0n)}async getDecimals(){let{token:t}=this.config,e=new ht(t).unwrap();return(await this.connection.getTokenSupply(e)).value.decimals}validateToken(t){if(!t.token)throw new Error("Token address is required")}};var nt=class{static get(t,e){switch(e.module){case"Native":return new tt(t,e);case"Token":return new et(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};import{ComputeBudgetProgram as Tt,PublicKey as xe,TransactionMessage as Se,VersionedTransaction as Et}from"@solana/web3.js";var Ft=.5,Dt=2,It=1,Rt=1e6,Pe=25e4,st=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,n=await this.getV0Message(t,e),s=await this.createPriorityFeeInstructions(n);return this.getV0Message(t,[...e,...s])}async estimateFee(t,e){if(e===0n)return 0n;let{instructions:n}=this.config,s=await this.getV0Message(t,n),a=await this.determineComputeBudget(s);return BigInt(a)}async getV0Message(t,e){let n=new xe(t),{blockhash:s}=await this.connection.getLatestBlockhash("finalized");return new Se({payerKey:n,recentBlockhash:s,instructions:e}).compileToV0Message()}async createPriorityFeeInstructions(t,e=Ft,n=Dt,s=It,a=Rt){let[r,o]=await Promise.all([this.determineComputeBudget(t),this.determinePriorityFee(t,e,n,s,a)]);return[Tt.setComputeUnitLimit({units:r}),Tt.setComputeUnitPrice({microLamports:o})]}async simulateTransaction(t,e){let n=new Et(e);return(await this.connection.simulateTransaction(n,{accounts:{encoding:"base64",addresses:[t]}})).value}async determineComputeBudget(t){let e=new Et(t),n=await this.connection.simulateTransaction(e),{err:s,unitsConsumed:a}=n.value;return a&&!s?Math.round(a*1.2):Pe}async determinePriorityFee(t,e=Ft,n=Dt,s=It,a=Rt){let r=s,o=await this.getTxAccounts(t),i=await this.connection.getRecentPrioritizationFees({lockedWritableAccounts:o});if(i){let u=i.map(m=>m.prioritizationFee).filter(m=>m>0).sort((m,d)=>m-d),l=Math.ceil(u.length*e);if(u.length>l){let d=u[l]*n;r=Math.max(r,d)}}return Math.min(Math.max(r,s),a)}async getTxAccounts(t){let e=(await Promise.all(t.addressTableLookups.map(s=>this.connection.getAddressLookupTable(s.accountKey)))).map(s=>s.value).filter(s=>s!==null),n=t.getAccountKeys({addressLookupTableAccounts:e??void 0});return t.compiledInstructions.flatMap(s=>s.accountKeyIndexes).map(s=>t.isAccountWritable(s)?n.get(s):null).filter(s=>s!==null)}};var L=class{static get(t,e){return new st(t,e)}};import{MessageV0 as Be}from"@solana/web3.js";function M(c){return c.map(t=>({program:t.programId.toBase58(),data:t.data.toString("hex"),keys:t.keys.map(e=>e.pubkey.toBase58())}))}function kt(c,t=1e3){let e=[],n=[],s=0;for(let a of c){let r=a.data?.length??0;n.length&&s+r>t&&(e.push(n),n=[],s=0),n.push(a),s+=r}return n.length&&e.push(n),e}function at(c){let t=c.serialize();return Buffer.from(t).toString("hex")}function ha(c){let t=Buffer.from(c,"hex"),e=Uint8Array.from(t);return Be.deserialize(e)}var rt=class{#t;constructor(t){this.#t=t.connection}async buildCall(t,e,n,s){let a=L.get(this.#t,s),r=await a.getPriorityMessage(t),o=r.serialize(),i=De.from(o).toString("hex");return{from:t,data:i,ix:M(s.instructions),signers:s.signers,type:Ee.Solana,dryRun:async()=>{let{err:u,logs:l}=await a.simulateTransaction(t,r);return{call:s.module+"."+s.func,error:u,events:l}}}}async estimateFee(t,e,n,s){let a=L.get(this.#t,s),r=await a.estimateFee(t,e),o=await a.getPriorityMessage(t),{accounts:i}=await a.simulateTransaction(t,o),l=(i&&i[0])?.lamports;if(l){let m=s.module==="TokenBridge"&&s.func==="TransferNativeWithPayload";return n.copyWith({amount:n.amount-BigInt(l)-(m?e:0n)})}return n.copyWith({amount:r})}async getBalance(t,e){let n=nt.get(this.#t,e),[s,a]=await Promise.all([n.getBalance(),n.getDecimals()]);return Te.fromAsset(t,{amount:s,decimals:a})}async subscribeBalance(t,e){let n=new Me,s=n.pipe(ke(1)),a=async()=>{let o=async()=>{let l=await this.getBalance(t,e);n.next(l)};await o();let i=new Fe(e.address),u=this.#t.onAccountChange(i,()=>o());return()=>{this.#t.removeAccountChangeListener(u)}},r;return a().then(o=>r=o),s.pipe(Re(()=>r?.()),Ie((o,i)=>o.amount===i.amount))}};import{CallType as yt,Wormhole as Ve}from"@galacticcouncil/xc-core";import{Keypair as Oe,PublicKey as Mt,SystemProgram as _e,TransactionMessage as Ne}from"@solana/web3.js";import{utils as We}from"@wormhole-foundation/sdk-solana";import{utils as Vt}from"@wormhole-foundation/sdk-solana-core";import{encoding as Le}from"@wormhole-foundation/sdk-base";import{deserialize as Ot}from"@wormhole-foundation/sdk-definitions";import{createCompleteTransferNativeInstruction as Ue,createCompleteTransferWrappedInstruction as je}from"@wormhole-foundation/sdk-solana-tokenbridge";var it=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){let{result:e}=await this.#t._rpcRequest("simulateBundle",[[t]]);return e}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 ot=class{#t;#e;#n;constructor(t){this.#t=t,this.#e=t.connection,this.#n=new it(t)}async redeem(t,e){let n=Ve.fromChain(this.#t),s=Le.b64.decode(e),a=Ot("TokenBridge:Transfer",s),r=Ot("Uint8Array",s),o=this.derivePostedVaaKey(n.getCoreBridge(),Buffer.from(a.hash)),i=new Mt(t),u=[];if(!await this.#e.getAccountInfo(o)){let S=Oe.generate(),P=await Vt.createVerifySignaturesInstructions(this.#t.connection,n.getCoreBridge(),i,r,S.publicKey),h=kt(P,1e3);for(let A=0;A<h.length;A++){let b=h[A],E=await this.getV0Message(i,b),T=at(E);u.push({from:t,data:T,ix:M(b),signers:[S],type:yt.Solana})}let B=Vt.createPostVaaInstruction(this.#e,n.getCoreBridge(),i,r,S.publicKey),D=await this.getV0Message(i,[B]),y=at(D);u.push({from:t,data:y,ix:M([B]),type:yt.Solana})}let d=(a.payload.token.chain==="Solana"?Ue:je)(this.#e,n.getTokenBridge(),n.getCoreBridge(),i,a),g=await this.#n.getTipAccount(),f=_e.transfer({fromPubkey:i,toPubkey:new Mt(g[0]),lamports:1e3}),p=await this.getV0Message(i,[d,f]),C=at(p);return u.push({from:t,data:C,ix:M([d]),type:yt.Solana}),u}derivePostedVaaKey(t,e){return We.deriveAddress([Buffer.from("PostedVAA"),e],t)}async getV0Message(t,e){let{blockhash:n}=await this.#e.getLatestBlockhash("finalized");return new Ne({payerKey:t,recentBlockhash:n,instructions:e}).compileToV0Message()}};import{Abi as ze,CallType as Qe,Precompile as He,Wormhole as $e}from"@galacticcouncil/xc-core";import{encoding as _t}from"@wormhole-foundation/sdk-base";import{encodeFunctionData as Ke}from"viem";var ct=class{#t;constructor(t){this.#t=t,$e.fromChain(this.#t)}redeemMrl(t,e){let n=_t.b64.decode(e),s=_t.hex.encode(n),a=ze.Gmp,r=Ke({abi:a,functionName:"wormholeTransferERC20",args:["0x"+s]});return{abi:JSON.stringify(a),data:r,from:t,to:He.Bridge}}async redeemMrlViaXcm(t,e){let s=this.#t.api.getUnsafeApi(),a=this.redeemMrl(t,e);return{data:s.tx.EthereumXcm.transact({V2:{gas_limit:5000000n,action:{Call:a.to},value:0n,input:a.data}}).decodedCall,from:t,type:Qe.Substrate,dryRun:async()=>{},txOptions:void 0}}};import{AssetAmount as Ge,CallType as Je,DexFactory as Ye}from"@galacticcouncil/xc-core";import{Binary as bt}from"polkadot-api";import{big as qe}from"@galacticcouncil/common";async function Ct(c,t,e){let n=await e.getDecimals(),s=e.chain.getAssetDecimals(t)??n,a=e.chain.usesChainDecimals?n:s;return{amount:qe.convertDecimals(c,a,s),decimals:s}}var Nt=c=>{let t=[];for(let e of c)if((e.type==="XcmPallet.FeesPaid"||e.type==="PolkadotXcm.FeesPaid")&&e.value?.fees){let s=Array.isArray(e.value.fees)?e.value.fees:[e.value.fees];for(let a of s)if(a.fun?.Fungible){let r=BigInt(a.fun.Fungible);t.push(r)}}return t.reduce((e,n)=>e+n,0n)},V=c=>{if(c.type==="Module"){let{index:t,error:e}=c.value;return`Module error: ${t}:${e}`}return JSON.stringify(c)};function U(c){return c.charAt(0).toUpperCase()+c.slice(1)}function Wt(c){return c.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Xe(c){return c.startsWith("0x")?{parents:0,interior:{X1:[{AccountKey20:{key:c}}]}}:{parents:0,interior:{X1:[{AccountId32:{id:c}}]}}}function Lt(c){return{V4:{parents:1,interior:{X1:[{Parachain:c.parachainId}]}}}}function Ut(c,t,e,n,s,a){let r=Xe(c);return{V4:[{WithdrawAsset:[{id:t,fun:{Fungible:e.amount}}]},{BuyExecution:{fees:{id:t,fun:{Fungible:e.amount}},weightLimit:"Unlimited"}},{Transact:{originKind:"SovereignAccount",requireWeightAtMost:{refTime:n,proofSize:s},call:{encoded:a}}},{RefundSurplus:{}},{DepositAsset:{assets:{Wild:{AllCounted:1}},beneficiary:r}}]}}var ut=class{#t;#e;#n;constructor(t,e){this.#t=t,this.#e=e,this.#n=Ye.getInstance().get(t.chain.key)}async remoteExec(t,e,n,s,a={}){let r=this.#t.api,o=await this.#t.getAsset(),i=this.#e.api,u=await this.#e.getAsset(),l=this.#e.chain,m=await this.#e.getDecimals(),d=l.getAssetXcmLocation(u),f=await(await i.txFromCallData(bt.fromHex(n.data))).getPaymentInfo(e),p=BigInt(f.partial_fee)*120n/100n,C=Ge.fromAsset(u,{amount:p,decimals:m}),S=Number(f.weight.ref_time),P=String(f.weight.proof_size),h=n.data,B=Lt(l),D=Ut(e,d,C,S,P,h),y=r.tx.PolkadotXcm.send({dest:B,message:D}),A=[];if(this.#n){let w=await this.#n.getCalldata(t,a.srcFeeAsset||o,u,C,10),K=await r.txFromCallData(bt.fromHex(w));A.push(K)}let b=await s(C),E=await r.txFromCallData(bt.fromHex(b.data));A.push(E),A.push(y);let T=r.tx.Utility.batch_all({calls:A});return{from:t,data:T.decodedCall,type:Je.Substrate,dryRun:this.#t.isDryRunSupported()?async()=>{try{let w=await this.#t.dryRun(t,T);return console.log(w.execution_result),{call:"polkadotXcm.send",error:w.execution_result&&!w.execution_result.success?V(w.execution_result.value):void 0,events:w.emitted_events||[],xcm:w.forwarded_xcms||[]}}catch(w){return{call:"polkadotXcm.send",error:w instanceof Error?w.message:"unknown"}}}:()=>{}}}};import{Asset as an,AssetAmount as Ht,CallType as rn,DexFactory as on}from"@galacticcouncil/xc-core";import{concatMap as $t,distinctUntilChanged as cn,firstValueFrom as un}from"rxjs";import{acc as Ze,addr as tn,multiloc as At,AssetAmount as en,ExtrinsicConfig as jt}from"@galacticcouncil/xc-core";import{Blake2256 as nn}from"@polkadot-api/substrate-bindings";import{toHex as sn,fromHex as zt}from"@polkadot-api/utils";var{Ss58Addr:Qt}=tn,x=class c{client;api;chain;_chainSpec;_asset;_decimals;constructor(t,e){this.client=t,this.api=t.getUnsafeApi(),this.chain=e}static async create(t){return new c(t.api,t)}async getChainSpec(){return this._chainSpec||(this._chainSpec=await this.client.getChainSpecData()),this._chainSpec}async getAsset(){if(!this._asset){let e=(await this.getChainSpec()).properties?.tokenSymbol,s=(Array.isArray(e)?e[0]:e).toLowerCase(),a=this.chain.getAsset(s);if(!a)throw new Error(`No asset found for key "${s}"`);this._asset=a}return this._asset}async getDecimals(){if(this._decimals===void 0){let n=((await this.getChainSpec()).properties?.tokenDecimals||[])[0]||12;return this._decimals=n,n}return this._decimals}async getExistentialDeposit(){let t;try{let s=await this.api.constants.Balances.ExistentialDeposit();t=typeof s=="bigint"?s:BigInt(String(s))}catch{t=0n}let e=await this.getAsset(),n=await this.getDecimals();return en.fromAsset(e,{amount:t,decimals:n})}isDryRunSupported(){return this.api.apis?.DryRunApi!==void 0}async getDecimalsForAsset(t){let e=await this.getDecimals();return this.chain.getAssetDecimals(t)??e}getExtrinsic(t){let e=U(t.module),n=Wt(t.func),s=this.api.tx[e];if(!s)throw new Error(`Pallet "${t.module}" (${e}) not found in runtime`);let a=s[n];if(!a||typeof a!="function")throw new Error(`Extrinsic "${t.func}" (${n}) not found in pallet "${e}"`);let r=t.getArgs();return this.isBatchCall(t.func)?this.buildBatchCall(a,r):a(r)}isBatchCall(t){return["batch","batchAll","forceBatch"].includes(t)}buildBatchCall(t,e){if(!e||typeof e!="object")throw new Error("Batch call requires transaction data");if(Array.isArray(e)){let n=e.map(s=>s instanceof jt?this.getExtrinsic(s):s);return t({calls:n})}if("calls"in e&&Array.isArray(e.calls)){let n=e.calls.map(s=>s instanceof jt?this.getExtrinsic(s):s);return t({...e,calls:n})}return t(e)}async buildMessageId(t,e,n,s){let a=await this.client._request("system_accountNextIndex",[t]),r=new Uint8Array(4);new DataView(r.buffer).setUint32(0,a,!0);let o=l=>new TextEncoder().encode(l),i=new Uint8Array([...o(this.chain.parachainId.toString()),...zt(t.startsWith("0x")?t.slice(2):t),...r,...zt(n.startsWith("0x")?n.slice(2):n),...o(s),...o(e.toString())]),u=nn(i);return sn(u)}async dryRun(t,e){if(!this.api.apis?.DryRunApi)throw new Error("DryRunApi not available on this chain");let n={System:{Signed:t}},s=e.decodedCall,a=await this.api.apis.DryRunApi.dry_run_call(n,s);if(!a.success)throw new Error("DryRun call failed");return a.value}async estimateNetworkFee(t,e){let n=await this.getExtrinsic(e);try{let s=await n.getPaymentInfo(t);return BigInt(s.partial_fee)}catch{console.warn("Can't estimate network fee.")}return 0n}async estimateDeliveryFee(t,e){if(this.chain.usesDeliveryFee){let n=await this.estimateDeliveryFeeWith(t,e);try{let s=this.getExtrinsic(e),a=await this.dryRun(n,s);if(a.execution_result?.success)return Nt(a.emitted_events||[]);{let r=V(a.execution_result?.value);console.warn(`Can't estimate delivery fee. Reason:
|
|
4
|
-
${r}`)}}catch{}}return 0n}async estimateDeliveryFeeWith(t,e){if(["xcmPallet","polkadotXcm"].includes(e.module)){let n=e.getArgs();if(!n||typeof n!="object")return t;let s="dest"in n?n.dest:void 0;if(!s)return t;let a=At.findNestedKey(s,"interior"),r=At.findParachain(s);if(At.findGlobalConsensus(s))return t;if(r){let i=Ze.getSovereignAccounts(r);return this.chain.parachainId===0?Qt.encodePubKey(i.relay):Qt.encodePubKey(i.generic)}if(a&&a.interior==="Here")return this.chain.treasury||t}return t}};var mt=class{#t;#e;constructor(t){this.#t=x.create(t),this.#e=on.getInstance().get(t.key)}async useSignerFee(t){let e=await this.#t,n=await e.getAsset();return e.chain.usesSignerFee&&!n.isEqual(t)}async buildCall(t,e,n,s){let a=await this.#t,o=await this.useSignerFee(n)?{asset:new an(n)}:void 0,i=await a.getExtrinsic(s),u=s.module+"."+s.func,l=await i.getEncodedData();return{from:t,data:l.asHex(),type:rn.Substrate,txOptions:o,dryRun:a.isDryRunSupported()?async()=>{try{let m=a.getExtrinsic(s),d=await a.dryRun(t,m),g=d.execution_result&&!d.execution_result.success?V(d.execution_result.value):void 0;return{call:u,error:g,events:d.emitted_events||[],xcm:d.forwarded_xcms||[]}}catch(m){return{call:u,error:m instanceof Error?m.message:"unknown"}}}:()=>{}}}async estimateFee(t,e,n,s){let a=await this.#t,r=await a.estimateNetworkFee(t,s),o=await a.estimateDeliveryFee(t,s),i=await this.exchangeFee(r+o,n),u=await Ct(i,n,a);return n.copyWith(u)}async getBalance(t,e){let n=await this.subscribeBalance(t,e);return un(n)}async subscribeBalance(t,e){let n=await this.#t,{module:s,func:a,args:r,transform:o}=e,i=U(s),u=U(a),m=n.client.getUnsafeApi().query[i];if(!m)throw new Error(`Query module "${s}" (${i}) not found in runtime`);let d=m[u];if(!d)throw new Error(`Query function "${a}" (${u}) not found in module "${i}"`);return d.watchValue(...r).pipe($t(f=>o(f)),cn((f,p)=>f===p),$t(async f=>{let p=await Ct(f,t,n);return Ht.fromAsset(t,p)}))}async exchangeFee(t,e){let n=await this.#t,s=await n.getAsset(),a=await n.getDecimals();if(s.isEqual(e))return t;if(this.#e){let r=Ht.fromAsset(s,{amount:t,decimals:a});return(await this.#e.getQuote(e,s,r,!0)).amount}return t}};import{AssetAmount as gn,CallType as fn}from"@galacticcouncil/xc-core";import{toBase64 as pn}from"@mysten/bcs";import{distinctUntilChanged as hn,finalize as yn,shareReplay as Cn,Subject as bn}from"rxjs";var lt=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 mn}from"@mysten/sui/utils";var ln=9,dt=class extends lt{async getBalance(){let{address:t}=this.config,e=await this.client.getBalance({owner:t,coinType:mn});return BigInt(e.totalBalance)}async getDecimals(){return ln}};var gt=class{static get(t,e){switch(e.module){case"Native":return new dt(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};import{fromBase64 as dn}from"@mysten/bcs";function Kt(c,t={}){let e=c.inputs??[],n=c.commands??[],s=t.numbers??"string",a=t.decode32As??"address",r=l=>s==="bigint"?l:s==="number"?Number(l):l.toString(),o=l=>{let m=dn(l),d=g=>{let f=0n;for(let p=0;p<g;p++)f|=BigInt(m[p])<<8n*BigInt(p);return f};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(f=>f.toString(16).padStart(2,"0")).join("")}:{type:"pure",valueType:"vector<u8>",value:Array.from(m)}},i=l=>{let m=e[l];if(!m)return{Input:l};if(m.Pure?.bytes)return o(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}},u=l=>l?.GasCoin?"GasCoin":Array.isArray(l?.NestedResult)?l:typeof l?.Input=="number"?i(l.Input):l;return n.map(l=>{if(l.MoveCall){let m=l.MoveCall;return{MoveCall:{...m,arguments:(m.arguments??[]).map(u)}}}if(l.SplitCoins){let m=l.SplitCoins,d=m.coin?.GasCoin?"GasCoin":u(m.coin),g=(m.amounts??[]).map(u);return{SplitCoins:[d,g]}}if(l.MergeCoins){let m=l.MergeCoins;return{MergeCoins:{...m,destination:u(m.destination),sources:(m.sources??[]).map(u)}}}if(l.TransferObjects){let m=l.TransferObjects;return{TransferObjects:{...m,objects:(m.objects??[]).map(u),address:u(m.address)}}}return l})}var ft=class{#t;constructor(t){this.#t=t.client}async buildCall(t,e,n,s){let{transaction:a}=s;a.setSender(t);let r=await a.build({client:this.#t}),o=await a.toJSON(),i=Kt(JSON.parse(o));return{from:t,commands:i,data:pn(r),type:fn.Sui,dryRun:async()=>{let u=await this.#t.dryRunTransactionBlock({transactionBlock:r});return{call:s.module+"."+s.func,error:u.executionErrorSource}}}}async estimateFee(t,e,n,s){let{transaction:a}=s;a.setSender(t);let r=await a.build({client:this.#t}),i=(await this.#t.dryRunTransactionBlock({transactionBlock:r})).effects.gasUsed,u=BigInt(i.computationCost),l=BigInt(i.storageCost),m=BigInt(i.storageRebate),d=u+l-m;return n.copyWith({amount:d})}async getBalance(t,e){let n=gt.get(this.#t,e),[s,a]=await Promise.all([n.getBalance(),n.getDecimals()]);return gn.fromAsset(t,{amount:s,decimals:a})}async subscribeBalance(t,e){let n=new bn,s=n.pipe(Cn(1)),a=async()=>{await(async()=>{let u=await this.getBalance(t,e);n.next(u)})();let i=setInterval(()=>{},3e3);return()=>clearInterval(i)},r;return a().then(o=>r=o),s.pipe(yn(()=>r?.()),hn((o,i)=>o.amount===i.amount))}};var I=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 rt(e)}registerSui(t){let e=t;this.platform.Sui=new ft(e)}registerSubstrate(t){let e=t;this.platform.Substrate=new mt(e)}async buildCall(t,e,n,s){return this.platform[s.type].buildCall(t,e,n,s)}async estimateFee(t,e,n,s){return this.platform[s.type].estimateFee(t,e,n,s)}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{acc as Pn,addr as Bn,AssetAmount as wt,Parachain as Tn}from"@galacticcouncil/xc-core";import{big as Yt}from"@galacticcouncil/common";import{big as An}from"@galacticcouncil/common";import z from"big.js";function qt(c,t,e,n){let s=c.toBig().minus(e.toBig()).minus(c.isSame(t)?t.toBig():new z(0));return n&&(s=s.minus(c.isSame(n)?n.toBig():new z(0))),c.copyWith({amount:s.lt(0)?0n:BigInt(s.toFixed())})}function Xt(c,t,e,n){let a=c.copyWith({amount:0n}).toBig().plus(c.isSame(t)?t.toBig():new z(0)).plus(c.toBig().lt(e.toBig())?e.toBig():new z(0));return n&&(a=a.plus(c.isSame(n)&&c.toBig().lt(n.toBig())?n.toBig():new z(0))),c.copyWith({amount:BigInt(a.toFixed())})}async function F(c,t){return t.isEvmParachain()?t.getDerivatedAddress(c):c}function Gt(c,t){return t?An.toBigInt(t,c):0n}import{addr as wn,AssetAmount as vn,Parachain as Jt}from"@galacticcouncil/xc-core";import{big as xn}from"@galacticcouncil/common";var{EvmAddr:Sn}=wn,O=class{adapter;config;constructor(t,e){this.adapter=t,this.config=e}async getEd(){let{chain:t}=this.config;if(t instanceof Jt)return(await x.create(t)).getExistentialDeposit()}async getBalance(t){let{chain:e,route:n}=this.config,{source:s}=n,a=s.asset,r=e.getBalanceAssetId(a),o=Sn.isValid(r.toString())?await F(t,e):t,i=n.source.balance.build({address:o,asset:a,chain:e});return this.adapter.getBalance(a,i)}async getMin(){let{chain:t,route:e}=this.config,{source:n}=e,s=n.asset,a=n.min;if(t instanceof Jt&&a){let r=t.getMinAssetId(s),o=a.build({asset:r});return this.adapter.getBalance(s,o)}return this.getAssetMin()}async getAssetMin(){let{chain:t,route:e}=this.config,{source:n}=e,s=n.asset,a=t.getAssetMin(s),r=await this.getDecimals(s),o=0n;return a&&(o=xn.toBigInt(a,r)),vn.fromAsset(s,{amount:o,decimals:r})}async getDecimals(t){let{chain:e}=this.config,n=e.getAssetDecimals(t);return n||(await e.getCurrency()).decimals}};var{EvmAddr:Zt}=Bn,Q=class extends O{constructor(t,e){super(t,e)}async getCall(t){let{amount:e,sender:n,source:s}=t,a=await this.getTransfer(t);return this.adapter.buildCall(n,e,s.feeBalance,a)}async getDestinationFee(){let{chain:t,route:e}=this.config,{source:n,destination:s,transact:a}=e,r=s.fee.amount,o=n.destinationFee.asset||s.fee.asset,i=await this.getDecimals(o);if(Number.isFinite(r))return{fee:wt.fromAsset(o,{amount:Yt.toBigInt(r,i),decimals:i}),feeBreakdown:{}};let u=r,{amount:l,breakdown:m}=await u.build({feeAsset:o,transferAsset:n.asset,source:a?a.chain:t,destination:s.chain});return{fee:wt.fromAsset(o,{amount:l,decimals:i}),feeBreakdown:m}}async getDestinationFeeBalance(t){let{chain:e,route:n}=this.config,{source:s,destination:a}=n,r=s.asset,o=s.destinationFee.asset||a.fee.asset;if(r.isEqual(o))return this.getBalance(t);let i=e.getBalanceAssetId(o),u=Zt.isValid(i.toString())?await F(t,e):t,l=s.destinationFee.balance.build({address:u,asset:o,chain:e});return this.adapter.getBalance(o,l)}async getFee(t){let{chain:e,route:n}=this.config,{amount:s,sender:a,source:r}=t,o=await this.getTransfer(t),i=n.contract?await F(a,e):a,u=await this.adapter.estimateFee(i,s,r.feeBalance,o),{fee:l}=n.source,m=l?Gt(u.decimals,l.extra):0n,d=u.amount+m;return u.copyWith({amount:d})}async getFeeBalance(t){let{chain:e,route:n}=this.config,{source:s}=n;if(!s.fee)return this.getBalance(t);let a=await this.getFeeAsset(t),r=e.getBalanceAssetId(a),o=Zt.isValid(r.toString())?await F(t,e):t,i=s.fee.balance.build({address:o,asset:a,chain:e});return this.adapter.getBalance(a,i)}async getFeeAsset(t){let{chain:e,route:n}=this.config,{source:s}=n,a=s.fee,r=s.asset;if(!a)return r;let o=a.asset;return e instanceof Tn&&"build"in o?await o.build({chain:e,address:t}):o}async getTransfer(t){let{chain:e,route:n}=this.config,{contract:s,extrinsic:a,program:r,move:o}=n;if(a){let{address:u,amount:l,asset:m,sender:d}=t,f=await(await x.create(e)).buildMessageId(d,l,m.originSymbol,u);return a.build({...t,messageId:f})}let i=s||r||o;if(i)return i.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:n}=e;if(n){let s=Object.assign({transact:{chain:n.chain}}),a={...t,...s};return{...await this.getTransactData(n,a),chain:n.chain}}}async getTransactData(t,e){let{chain:n,extrinsic:s}=t,a=s.build(e),o=await(await x.create(n)).getExtrinsic(a),i=e.source.chain,u=e.sender,l=Pn.getMultilocationDerivatedAccount(i.parachainId,u,n.parachainId===0?0:1,n.usesH160Acc),m=await o.getPaymentInfo(l),[d,g]=await Promise.all([this.getTransactFee(t),this.getTransactFeeBalance(t,e)]);return{call:o.decodedCall,chain:n,fee:d,feeBalance:g,weight:{refTime:Number(m.weight.ref_time),proofSize:String(m.weight.proof_size)}}}async getTransactFee(t){let{fee:e}=t,n=await this.getDecimals(e.asset),s=Yt.toBigInt(e.amount,n);return wt.fromAsset(e.asset,{amount:s,decimals:n})}async getTransactFeeBalance(t,e){let{chain:n}=this.config,{fee:s}=t,a=s.balance.build({address:e.sender,asset:s.asset,chain:n});return this.adapter.getBalance(s.asset,a)}};var H=class extends O{constructor(t,e){super(t,e)}};import{AssetAmount as En,DexFactory as Fn}from"@galacticcouncil/xc-core";var $=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 Fn.getInstance().get(t.chain.key)}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:n}=await this.dex.chain.getCurrency(),{amount:s}=await this.dex.getQuote(e,t,t);return{aIn:t,aOut:En.fromAsset(e,{amount:s,decimals:n}),enabled:!0}}isSwapSupported(t){let e=!!this.dex,n=t&&t.swap;return e&&!!n}async getDestinationSwap(t){let{amount:e,route:n}=await this.dex.getQuote(t,this.destFee,this.destFee),s=this.destFeeBalance.amount<this.destFee.amount,a=this.feeBalance.amount-t.amount>e*2n;return{aIn:t.copyWith({amount:e}),aOut:this.destFee,enabled:s&&a,route:n}}isDestinationSwapSupported(t){let e=!!this.dex,n=!t.isSame(this.destFee),s=this.asset.isSame(this.destFee);return e&&n&&!s}};var{EvmAddr:_n}=In,vt=class{config;validations;constructor({configService:t,transferValidations:e}){this.config=t,this.validations=e||[]}registerDex(...t){t.forEach(e=>kn.getInstance().register(e))}async transfer(t,e,n,s,a){let r=Rn(this.config).assets().asset(t).source(n).destination(a).build();return this.getTransferData(r,e,s)}async remoteXcm(t,e,n,s,a={}){let r=this.config.getChain(e),o=this.config.getChain(n);if(!(r.isSubstrate()&&o.isSubstrate()))throw Error("RemoteXcm is supported only between parachains");let[u,l]=await Promise.all([x.create(r),x.create(o)]),m=new ut(u,l),d=Dn.getMultilocationDerivatedAccount(r.parachainId,t,1,o.usesH160Acc),g=await l.getAsset(),f=await this.transfer(g,t,e,d,n);return m.remoteExec(t,d,s,p=>{let C=p.toDecimal(p.decimals);return f.buildCall(C)},a)}async getTransferData(t,e,n){let s=t.origin,a=t.reverse,r=new I(s.chain),o=new I(a.chain),i=new Q(r,s),u=new H(o,a),l=new Mn(...this.validations),[m,d,g,f,p,C,S]=await Promise.all([i.getBalance(e),i.getFeeBalance(e),i.getDestinationFee(),i.getDestinationFeeBalance(e),i.getMin(),u.getBalance(n),u.getMin()]),{source:P,destination:h}=s.route,B=g.fee.copyWith(h.fee.asset),D=g.feeBreakdown,y={address:n,amount:1n,asset:P.asset,destination:{balance:C,chain:a.chain,fee:B,feeBreakdown:D},sender:e,source:{balance:m,chain:s.chain,fee:d.copyWith({amount:0n}),feeBalance:d,destinationFee:g.fee,destinationFeeBalance:f}};y.transact=await i.getTransact(y);let A=new $(y),b=await i.getFee(y),E;A.isSwapSupported(P.fee)&&(E=await A.getSwap(b),y.source.feeSwap=E);let T;A.isDestinationSwapSupported(b)&&(T=await A.getDestinationSwap(b),y.source.destinationFeeSwap=T),(E||T)&&(b=await i.getFee(y),b=b.padByPct(5n));let w=await u.getEd(),K=Xt(C,B,S,w),ae=await i.getEd(),re=qt(m,b,p,ae);return y.amount=0n,y.source.fee=b,{source:{balance:m,destinationFee:g.fee,destinationFeeBalance:f,destinationFeeSwap:T,fee:b,feeBalance:d,feeSwap:E,max:re,min:m.copyWith({amount:K.amount})},destination:{balance:C,fee:B},async buildCall(N){let v=Object.assign({},y);return v.amount=te.toBigInt(N,m.decimals),v.transact=await i.getTransact(v),i.getCall(v)},async estimateFee(N){let v=Object.assign({},y);return v.amount=te.toBigInt(N,m.decimals),v.transact=await i.getTransact(v),i.getFee(v)},async validate(N){let v=Object.assign({},y),ie=N||b.amount;return v.source.fee=b.copyWith({amount:ie}),l.validate(v)}}}async subscribeBalance(t,e,n){let s=this.config.getChainRoutes(e),a=new I(s.chain),r=s.getUniqueRoutes().map(async({source:u})=>{let{asset:l,balance:m}=u,d=s.chain.getBalanceAssetId(l),g=_n.isValid(d.toString())?await F(t,s.chain):t,f=m.build({address:g,asset:l,chain:s.chain});return a.subscribeBalance(l,f)}),o=await Promise.all(r);return Vn(o).pipe(On(500)).subscribe(n)}};import{ConfigBuilder as Nn}from"@galacticcouncil/xc-core";function Wn(c){let t=Nn(c.config).assets();return{assets:t,withAsset(e){let n=t.asset(e);return{sources:n,withSource(s){let a=n.source(s);return{destinations:a,withDestination(r){let{routes:o,build:i}=a.destination(r);return{routes:o,build({srcAddress:u,dstAddress:l,dstAsset:m}){let d=i(m);return c.getTransferData(d,u,l)}}}}}}}}}import{Precompile as Ln}from"@galacticcouncil/xc-core";var Un="https://api.wormholescan.io",pt=class{_baseUrl;constructor(t){this._baseUrl=t||Un}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}),s=await(await fetch(e)).json();if(s.data.length>0)return s.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:n,toChain:s}=t,a="0x"+n.substring(26);return e===3&&s===16&&a===Ln.Bridge}};import{acc as jn,mrl as zn,ChainType as ne,Parachain as Qn,Precompile as Hn,Wormhole as _}from"@galacticcouncil/xc-core";import{encoding as $n}from"@wormhole-foundation/sdk-base";import{keccak256 as Kn}from"@wormhole-foundation/sdk-connect";import{deserialize as qn}from"@wormhole-foundation/sdk-definitions";var ee=(n=>(n[n.WaitingForVaa=0]="WaitingForVaa",n[n.VaaEmitted=1]="VaaEmitted",n[n.Completed=2]="Completed",n))(ee||{});var Xn=300*1e3,se=class{parachainId;config;whScan;constructor(t,e){this.config=t,this.parachainId=e,this.whScan=new pt}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 n=t.toISOString();return{page:"0",pageSize:"50",includeEndDate:"true",from:e.toISOString(),to:n}}async getWithdraws(t){let e=jn.getMultilocationDerivatedAccount(this.parachainId,t,1,!0),s=(await this.whScan.getOperations({...this.filters,address:e})).map(async a=>{let{content:r}=a,{payload:o,standarizedProperties:i}=r,u=this.getStatus(a),l=this.chains.find(p=>p instanceof Qn&&p.parachainId===this.parachainId),{toAddress:m,tokenAddress:d}=i,g=this.chains.find(p=>_.isKnown(p)&&_.fromChain(p).getWormholeId()===o.tokenChain),f;if(u===1&&a.vaa){let{timestamp:p}=this.getVaaHeader(a.vaa.raw),C=a.vaa.raw;if(this.isStuck(p))switch(g.getType()){case ne.EvmChain:let S=new q(g);f=async h=>S.redeem(h,C);break;case ne.SolanaChain:let P=new ot(g);f=async h=>P.redeem(h,C);break}}return{asset:d,assetSymbol:a.data.symbol,amount:a.data.tokenAmount,from:t,fromChain:l,to:m,toChain:g,status:u,redeem:f,operation:a}});return Promise.all(s)}async getDeposits(t,e="hydration"){let n=await this.whScan.getOperations({...this.filters,address:Hn.Bridge,pageSize:"100"}),s=this.config.chains.get(e);if(!s)return[];let a=s,o=(await zn.createPayload(a,t)).toHex(),i=n.filter(u=>{let{content:l}=u,{payload:m}=l;return m.payloadType===3&&m.toChain===16&&"0x"+m.payload===o}).map(async u=>{let{content:l,sourceChain:m}=u,{payload:d,standarizedProperties:g}=l,f=this.getStatus(u),{tokenAddress:p}=g,C=this.chains.find(h=>_.isKnown(h)&&_.fromChain(h).getWormholeId()===d.tokenChain),S=this.chains.find(h=>_.isKnown(h)&&_.fromChain(h).getWormholeId()===d.toChain),P;if(f===1&&u.vaa){let{timestamp:h}=this.getVaaHeader(u.vaa.raw),B=u.vaa.raw;if(this.isStuck(h)){let D=new ct(S);P=async y=>D.redeemMrlViaXcm(y,B)}}return{asset:p,assetSymbol:u.data.symbol,amount:u.data.tokenAmount,from:m.from,fromChain:C,to:t,toChain:s,status:f,redeem:P,operation:u}});return Promise.all(i)}isStuck(t){return Date.now()>=t*1e3+Xn}getVaaHeader(t){let e=$n.b64.decode(t),n=qn("Uint8Array",e);return{timestamp:n.timestamp,emitterChain:n.emitterChain,emitterAddress:n.emitterAddress.toString(),sequence:n.sequence,payload:n.payload,hash:n.hash,id:Kn(n.hash)}}getStatus(t){return t.vaa?t.targetChain&&t.targetChain.status==="completed"?2:1:0}};export{q as EvmClaim,Z as EvmPlatform,$ as FeeSwap,I as PlatformAdapter,ot as SolanaClaim,it as SolanaLilJit,rt as SolanaPlatform,ct as SubstrateClaim,ut as SubstrateExec,mt as SubstratePlatform,x as SubstrateService,ft as SuiPlatform,Wn as TransferBuilder,vt as Wallet,ee as WhStatus,pt as WormholeScan,se as WormholeTransfer,kt as chunkBySize,ha as deserializeV0,M as ixToHuman,at as serializeV0};
|
|
1
|
+
import{big as se}from"@galacticcouncil/common";import{acc as Rn,addr as kn,ConfigBuilder as Vn,DexFactory as Mn,TransferValidator as On}from"@galacticcouncil/xc-core";import{combineLatest as _n,debounceTime as Nn}from"rxjs";import{ChainType as j}from"@galacticcouncil/xc-core";import{Abi as oe,Wormhole as ce}from"@galacticcouncil/xc-core";import{encodeFunctionData as ue}from"viem";import{encoding as Bt}from"@wormhole-foundation/sdk-base";var K=class{#t;constructor(t){this.#t=t}redeem(t,e){let n=ce.fromChain(this.#t),s=Bt.b64.decode(e),a=Bt.hex.encode(s),r=oe.TokenBridge,i=ue({abi:r,functionName:"completeTransfer",args:["0x"+a]});return{abi:JSON.stringify(r),data:i,from:t,to:n.getTokenBridge()}}};import{Abi as pe,AssetAmount as fe,CallType as Ft,Erc20Client as he}from"@galacticcouncil/xc-core";import{distinctUntilChanged as ye,finalize as Ce,shareReplay as be,Subject as Ae}from"rxjs";var R=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 EVM client found")}validateConfig(t){if(!t.address)throw new Error("Contract address is required")}};import{Erc20Client as me}from"@galacticcouncil/xc-core";var q=class extends R{erc20;constructor(t,e){super(t,e),this.erc20=new me(t,e.address)}async getBalance(){let{args:t}=this.config,[e]=t;return this.erc20.balanceOf(e)}async getDecimals(){return this.erc20.decimals()}};var X=class extends R{async getBalance(){let t=this.client.getProvider(),{address:e}=this.config;return t.getBalance({address:e})}async getDecimals(){return this.client.chain.nativeCurrency.decimals}};var $=class{static get(t,e){switch(e.module){case"Erc20":return new q(t,e);case"Native":return new X(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};import{ContractFunctionExecutionError as le,decodeEventLog as de}from"viem";var G=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:n,value:s,func:a}=this.config;return await this.client.getProvider().estimateContractGas({address:e,abi:this.abi,functionName:a,args:n,value:s,account:t})}async estimateFee(t,e){if(e===0n)return 0n;try{let n=await this.estimateGas(t),s=await this.getGasPrice();return n*s}catch(n){return n instanceof le?console.log(`Can't estimate fees!
|
|
2
|
+
`,n.message):console.log(n),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:n,value:s,func:a}=this.config,r=this.client.getProvider(),i=await this.getNonce(t);try{let{results:o}=await r.simulateCalls({account:t,calls:[{to:e,abi:this.abi,functionName:a,args:n,value:s}],stateOverrides:[{address:t,nonce:i}]}),[u]=o;return u}catch(o){return console.log(`Can't simulate call!
|
|
3
|
+
`,o.details),{error:o}}}decodeEvents(t){let e=[];return t&&t.forEach(n=>{try{let{eventName:s,args:a}=de({abi:this.abi,data:n.data,topics:n.topics});e.push({eventName:s,args:a})}catch{}}),e}};var N=class{static get(t,e){return new G(t,e)}};import{Precompile as ge}from"@galacticcouncil/xc-core";function Tt(c){let t=c.module==="Snowbridge"&&c.func==="sendToken"&&c.args[0]==="0x0000000000000000000000000000000000000000";return c.module==="TokenBridge"&&["wrapAndTransferETHWithPayload","wrapAndTransferETH"].includes(c.func)||t}function Et(c){return Object.entries(ge).map(([e,n])=>n).includes(c.address)}var J=class{#t;constructor(t){this.#t=t.evmClient}async buildCall(t,e,n,s){let a=N.get(this.#t,s),{abi:r,asset:i,calldata:o}=a,u={abi:JSON.stringify(r),data:o,from:t,to:s.address,type:Ft.Evm,value:s.value,dryRun:async()=>{let{error:g,logs:p}=await a.simulateCall(t),f=a.decodeEvents(p);return{call:s.module+"."+s.func,error:g?.shortMessage,events:f}}};if(Et(s)||Tt(s))return u;let l=new he(this.#t,i),m=await l.allowance(t,s.address);if(m>=e)return u;let d=l.approve(s.address,e);return{abi:JSON.stringify(pe.Erc20),allowance:m,data:d,from:t,to:i,type:Ft.Evm,dryRun:()=>{}}}async estimateFee(t,e,n,s){let r=await N.get(this.#t,s).estimateFee(t,e);return n.copyWith({amount:r})}async getBalance(t,e){let n=$.get(this.#t,e),[s,a]=await Promise.all([n.getBalance(),n.getDecimals()]);return fe.fromAsset(t,{amount:s,decimals:a})}async subscribeBalance(t,e){let n=new Ae,s=n.pipe(be(1)),a=this.#t.getProvider(),r=async()=>{let o=async()=>{let l=await this.getBalance(t,e);n.next(l)};await o();let u=a.watchBlocks({onBlock:()=>o()});return()=>u()},i;return r().then(o=>i=o),s.pipe(Ce(()=>i?.()),ye((o,u)=>o.amount===u.amount))}};import{AssetAmount as Te,CallType as Ee}from"@galacticcouncil/xc-core";import{PublicKey as Fe}from"@solana/web3.js";import{Buffer as De}from"buffer";import{distinctUntilChanged as Ie,finalize as Re,shareReplay as ke,Subject as Ve}from"rxjs";var k=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 ve}from"@wormhole-foundation/sdk-solana";var we=9,Y=class extends k{async getBalance(){let{address:t}=this.config,e=new ve(t).unwrap(),n=await this.connection.getBalance(e);return BigInt(n)}async getDecimals(){return we}};import{SolanaAddress as Ct}from"@wormhole-foundation/sdk-solana";var Z=class extends k{constructor(t,e){super(t,e),this.validateToken(e)}async getBalance(){let{address:t,token:e}=this.config,n=new Ct(t).unwrap(),s=new Ct(e).unwrap();return(await this.connection.getParsedTokenAccountsByOwner(n,{mint:s})).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 Ct(t).unwrap();return(await this.connection.getTokenSupply(e)).value.decimals}validateToken(t){if(!t.token)throw new Error("Token address is required")}};var tt=class{static get(t,e){switch(e.module){case"Native":return new Y(t,e);case"Token":return new Z(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};import{ComputeBudgetProgram as Dt,PublicKey as xe,TransactionMessage as Se,VersionedTransaction as It}from"@solana/web3.js";var Rt=.5,kt=2,Vt=1,Mt=1e6,Pe=25e4,et=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,n=await this.getV0Message(t,e),s=await this.createPriorityFeeInstructions(n);return this.getV0Message(t,[...e,...s])}async estimateFee(t,e){if(e===0n)return 0n;let{instructions:n}=this.config,s=await this.getV0Message(t,n),a=await this.determineComputeBudget(s);return BigInt(a)}async getV0Message(t,e){let n=new xe(t),{blockhash:s}=await this.connection.getLatestBlockhash("finalized");return new Se({payerKey:n,recentBlockhash:s,instructions:e}).compileToV0Message()}async createPriorityFeeInstructions(t,e=Rt,n=kt,s=Vt,a=Mt){let[r,i]=await Promise.all([this.determineComputeBudget(t),this.determinePriorityFee(t,e,n,s,a)]);return[Dt.setComputeUnitLimit({units:r}),Dt.setComputeUnitPrice({microLamports:i})]}async simulateTransaction(t,e){let n=new It(e);return(await this.connection.simulateTransaction(n,{accounts:{encoding:"base64",addresses:[t]}})).value}async determineComputeBudget(t){let e=new It(t),n=await this.connection.simulateTransaction(e),{err:s,unitsConsumed:a}=n.value;return a&&!s?Math.round(a*1.2):Pe}async determinePriorityFee(t,e=Rt,n=kt,s=Vt,a=Mt){let r=s,i=await this.getTxAccounts(t),o=await this.connection.getRecentPrioritizationFees({lockedWritableAccounts:i});if(o){let u=o.map(m=>m.prioritizationFee).filter(m=>m>0).sort((m,d)=>m-d),l=Math.ceil(u.length*e);if(u.length>l){let d=u[l]*n;r=Math.max(r,d)}}return Math.min(Math.max(r,s),a)}async getTxAccounts(t){let e=(await Promise.all(t.addressTableLookups.map(s=>this.connection.getAddressLookupTable(s.accountKey)))).map(s=>s.value).filter(s=>s!==null),n=t.getAccountKeys({addressLookupTableAccounts:e??void 0});return t.compiledInstructions.flatMap(s=>s.accountKeyIndexes).map(s=>t.isAccountWritable(s)?n.get(s):null).filter(s=>s!==null)}};var W=class{static get(t,e){return new et(t,e)}};import{MessageV0 as Be}from"@solana/web3.js";function V(c){return c.map(t=>({program:t.programId.toBase58(),data:t.data.toString("hex"),keys:t.keys.map(e=>e.pubkey.toBase58())}))}function Ot(c,t=1e3){let e=[],n=[],s=0;for(let a of c){let r=a.data?.length??0;n.length&&s+r>t&&(e.push(n),n=[],s=0),n.push(a),s+=r}return n.length&&e.push(n),e}function nt(c){let t=c.serialize();return Buffer.from(t).toString("hex")}function Ca(c){let t=Buffer.from(c,"hex"),e=Uint8Array.from(t);return Be.deserialize(e)}var st=class{#t;constructor(t){this.#t=t.connection}async buildCall(t,e,n,s){let a=W.get(this.#t,s),r=await a.getPriorityMessage(t),i=r.serialize(),o=De.from(i).toString("hex");return{from:t,data:o,ix:V(s.instructions),signers:s.signers,type:Ee.Solana,dryRun:async()=>{let{err:u,logs:l}=await a.simulateTransaction(t,r);return{call:s.module+"."+s.func,error:u,events:l}}}}async estimateFee(t,e,n,s){let a=W.get(this.#t,s),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=s.module==="TokenBridge"&&s.func==="TransferNativeWithPayload";return n.copyWith({amount:n.amount-BigInt(l)-(m?e:0n)})}return n.copyWith({amount:r})}async getBalance(t,e){let n=tt.get(this.#t,e),[s,a]=await Promise.all([n.getBalance(),n.getDecimals()]);return Te.fromAsset(t,{amount:s,decimals:a})}async subscribeBalance(t,e){let n=new Ve,s=n.pipe(ke(1)),a=async()=>{let i=async()=>{let l=await this.getBalance(t,e);n.next(l)};await i();let o=new Fe(e.address),u=this.#t.onAccountChange(o,()=>i());return()=>{this.#t.removeAccountChangeListener(u)}},r;return a().then(i=>r=i),s.pipe(Re(()=>r?.()),Ie((i,o)=>i.amount===o.amount))}};import{CallType as bt,Wormhole as Me}from"@galacticcouncil/xc-core";import{Keypair as Oe,PublicKey as _t,SystemProgram as _e,TransactionMessage as Ne}from"@solana/web3.js";import{utils as We}from"@wormhole-foundation/sdk-solana";import{utils as Nt}from"@wormhole-foundation/sdk-solana-core";import{encoding as je}from"@wormhole-foundation/sdk-base";import{deserialize as Wt}from"@wormhole-foundation/sdk-definitions";import{createCompleteTransferNativeInstruction as Le,createCompleteTransferWrappedInstruction as Ue}from"@wormhole-foundation/sdk-solana-tokenbridge";var at=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){let{result:e}=await this.#t._rpcRequest("simulateBundle",[[t]]);return e}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 rt=class{#t;#e;#n;constructor(t){this.#t=t,this.#e=t.connection,this.#n=new at(t)}async redeem(t,e){let n=Me.fromChain(this.#t),s=je.b64.decode(e),a=Wt("TokenBridge:Transfer",s),r=Wt("Uint8Array",s),i=this.derivePostedVaaKey(n.getCoreBridge(),Buffer.from(a.hash)),o=new _t(t),u=[];if(!await this.#e.getAccountInfo(i)){let S=Oe.generate(),w=await Nt.createVerifySignaturesInstructions(this.#t.connection,n.getCoreBridge(),o,r,S.publicKey),y=Ot(w,1e3);for(let B=0;B<y.length;B++){let h=y[B],T=await this.getV0Message(o,h),E=nt(T);u.push({from:t,data:E,ix:V(h),signers:[S],type:bt.Solana})}let P=Nt.createPostVaaInstruction(this.#e,n.getCoreBridge(),o,r,S.publicKey),D=await this.getV0Message(o,[P]),C=nt(D);u.push({from:t,data:C,ix:V([P]),type:bt.Solana})}let d=(a.payload.token.chain==="Solana"?Le:Ue)(this.#e,n.getTokenBridge(),n.getCoreBridge(),o,a),g=await this.#n.getTipAccount(),p=_e.transfer({fromPubkey:o,toPubkey:new _t(g[0]),lamports:1e3}),f=await this.getV0Message(o,[d,p]),A=nt(f);return u.push({from:t,data:A,ix:V([d]),type:bt.Solana}),u}derivePostedVaaKey(t,e){return We.deriveAddress([Buffer.from("PostedVAA"),e],t)}async getV0Message(t,e){let{blockhash:n}=await this.#e.getLatestBlockhash("finalized");return new Ne({payerKey:t,recentBlockhash:n,instructions:e}).compileToV0Message()}};import{Abi as ze,CallType as He,Precompile as Qe,Wormhole as Ke}from"@galacticcouncil/xc-core";import{encoding as jt}from"@wormhole-foundation/sdk-base";import{encodeFunctionData as qe}from"viem";var it=class{#t;constructor(t){this.#t=t,Ke.fromChain(this.#t)}redeemMrl(t,e){let n=jt.b64.decode(e),s=jt.hex.encode(n),a=ze.Gmp,r=qe({abi:a,functionName:"wormholeTransferERC20",args:["0x"+s]});return{abi:JSON.stringify(a),data:r,from:t,to:Qe.Bridge}}async redeemMrlViaXcm(t,e){let s=this.#t.client.getUnsafeApi(),a=this.redeemMrl(t,e);return{data:s.tx.EthereumXcm.transact({V2:{gas_limit:5000000n,action:{Call:a.to},value:0n,input:a.data}}).decodedCall,from:t,type:He.Substrate,dryRun:async()=>{},txOptions:void 0}}};import{AssetAmount as Je,CallType as Ye}from"@galacticcouncil/xc-core";import{Binary as wt}from"polkadot-api";import{big as Xe}from"@galacticcouncil/common";async function At(c,t,e){let n=await e.getDecimals(),s=e.chain.getAssetDecimals(t)??n,a=e.chain.usesChainDecimals?n:s;return{amount:Xe.convertDecimals(c,a,s),decimals:s}}import{enums as $e}from"@galacticcouncil/common";var Lt=c=>{let t=[];for(let e of c)if(["PolkadotXcm"].includes(e.type)&&e.value.type==="FeesPaid"){let s=e.value.value.fees;for(let a of s)if(a.fun.type==="Fungible"){let r=BigInt(a.fun.value);t.push(r)}}return t.reduce((e,n)=>e+n,0n)},M=c=>{let t=c.value.error;return t.type==="Module"?$e.enumPath(t.value):JSON.stringify(t.value)};import{xcm as vt}from"@galacticcouncil/common";function Ge(c){return{parents:0,interior:{type:"X1",value:[c.startsWith("0x")?vt.toAccountKey20(c):vt.toAccountId32(c)]}}}function zt(c){return{type:"V4",value:{parents:1,interior:{type:"X1",value:[{type:"Parachain",value:c.parachainId}]}}}}var Ut=(c,t)=>({id:vt.transform(c),fun:{type:"Fungible",value:t}}),Ht=(c,t,e,n,s,a)=>{console.log(a);let r=Ge(c);return{type:"V4",value:[{type:"WithdrawAsset",value:Ut(t,e.amount)},{type:"BuyExecution",value:{fees:Ut(t,e.amount),weight_limit:{type:"Unlimited"}}},{type:"Transact",value:{origin_kind:{type:"SovereignAccount"},require_weight_at_most:{ref_time:n,proof_size:s},call:a}},{type:"RefundSurplus"},{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,n,s,a={}){let r=this.#t.api,i=await this.#t.getAsset(),o=this.#e.api,u=this.#e.chain,l=await u.getCurrency(),m=l.asset,d=l.decimals,g=u.getAssetXcmLocation(m),p=wt.fromHex(n.data),A=await(await o.txFromCallData(p)).getPaymentInfo(e),S=BigInt(A.partial_fee)*120n/100n,w=Je.fromAsset(m,{amount:S,decimals:d}),y=A.weight.ref_time,P=A.weight.proof_size,D=zt(u),C=Ht(e,g,w,y,P,p),B=r.tx.PolkadotXcm.send({dest:D,message:C}),h=[];try{let b=await this.#t.chain.dex.getCalldata(t,a.srcFeeAsset||i,m,w,10),v=wt.fromHex(b),yt=await r.txFromCallData(v);h.push(yt)}catch{}let T=await s(w),E=wt.fromHex(T.data),pt=await r.txFromCallData(E);h.push(pt),h.push(B);let ft=h.map(b=>b.decodedCall),Q=r.tx.Utility.batch_all({calls:ft}),ht=await Q.getEncodedData();return{from:t,data:ht.asHex(),type:Ye.Substrate,dryRun:this.#t.isDryRunSupported()?async()=>{try{let b=await this.#t.dryRun(t,Q);return{call:"polkadotXcm.send",error:b.execution_result&&b.execution_result.success?void 0:M(b.execution_result),events:b.emitted_events||[],xcm:b.forwarded_xcms||[]}}catch(b){return{call:"polkadotXcm.send",error:b instanceof Error?b.message:"unknown"}}}:()=>{}}}};import{Asset as on,AssetAmount as Xt,CallType as cn}from"@galacticcouncil/xc-core";import{concatMap as $t,catchError as un,distinctUntilChanged as mn,firstValueFrom as ln,throwError as dn}from"rxjs";import{acc as Ze,addr as tn,multiloc as xt,AssetAmount as en}from"@galacticcouncil/xc-core";import{enums as nn}from"@galacticcouncil/common";import{Blake2256 as sn,u32 as an}from"@polkadot-api/substrate-bindings";import{toHex as rn,fromHex as Qt}from"@polkadot-api/utils";import{Enum as Kt}from"polkadot-api";var{Ss58Addr:qt}=tn,x=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}async getExistentialDeposit(){let t;try{let s=await this.api.constants.Balances.ExistentialDeposit();t=typeof s=="bigint"?s:BigInt(String(s))}catch{t=0n}let{asset:e,decimals:n}=await this.getCurrency();return en.fromAsset(e,{amount:t,decimals:n})}isDryRunSupported(){return this.api.apis?.DryRunApi!==void 0}async buildMessageId(t,e,n,s){let a=await this.client._request("system_accountNextIndex",[t]),r=an.enc(a),i=l=>new TextEncoder().encode(l),o=new Uint8Array([...i(this.chain.parachainId.toString()),...Qt(t.startsWith("0x")?t.slice(2):t),...r,...Qt(n.startsWith("0x")?n.slice(2):n),...i(s),...i(e.toString())]),u=sn(o);return rn(u)}async dryRun(t,e){let n=Kt("Signed",t),s=Kt("system",n),a=await this.api.apis.DryRunApi.dry_run_call(s,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 n=e.getTx(this.client);try{let s=await n.getPaymentInfo(t);return BigInt(s.partial_fee)}catch{console.warn("Can't estimate network fee.")}return 0n}async estimateDeliveryFee(t,e){if(this.chain.usesDeliveryFee){let n=await this.estimateDeliveryFeeWith(t,e);try{let s=e.getTx(this.client),a=await this.dryRun(n,s);if(a.execution_result?.success)return Lt(a.emitted_events||[]);{let r=M(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 s=e.getTx(this.client).decodedCall.value.value,a="dest"in s?s.dest:void 0;if(!a)return t;let r=xt.findNestedKey(a,"interior"),i=xt.findParachain(a);if(xt.findGlobalConsensus(a))return t;if(i){let u=Ze.getSovereignAccounts(i);return this.chain.parachainId===0?qt.encodePubKey(u.relay):qt.encodePubKey(u.generic)}if(r&&r.interior==="Here")return this.chain.treasury||t}return t}};var ct=class{#t;constructor(t){this.#t=x.create(t)}async useSignerFee(t){let e=await this.#t,n=await e.getAsset();return e.chain.usesSignerFee&&!n.isEqual(t)}async buildCall(t,e,n,s){let a=await this.#t,i=await this.useSignerFee(n)?{asset:new on(n)}:void 0,o=s.getTx(a.client),u=s.module+"."+s.func,l=await o.getEncodedData();return{from:t,data:l.asHex(),type:cn.Substrate,txOptions:i,dryRun:a.isDryRunSupported()?async()=>{try{let m=s.getTx(a.client),d=await a.dryRun(t,m),g=d.execution_result&&d.execution_result.success?void 0:M(d.execution_result);return{call:u,error:g,events:d.emitted_events||[],xcm:d.forwarded_xcms||[]}}catch(m){return{call:u,error:m instanceof Error?m.message:"unknown"}}}:()=>{}}}async estimateFee(t,e,n,s){let a=await this.#t,r=await a.estimateNetworkFee(t,s),i=await a.estimateDeliveryFee(t,s),o=await this.exchangeFee(r+i,n),u=await At(o,n,a);return n.copyWith(u)}async getBalance(t,e){let n=await this.subscribeBalance(t,e);return ln(n)}async subscribeBalance(t,e){let n=await this.#t,{module:s,func:a,args:r,transform:i}=e;return n.client.getUnsafeApi().query[s][a].watchValue(...r).pipe($t(l=>i(l)),mn((l,m)=>l===m),$t(async l=>{let m=await At(l,t,n);return Xt.fromAsset(t,m)}),un(l=>(console.error("subscribe fails for:",t),dn(()=>l))))}async exchangeFee(t,e){let n=await this.#t,s=await n.getAsset(),a=await n.getDecimals();if(s.isEqual(e))return t;try{let r=n.chain.dex,i=Xt.fromAsset(s,{amount:t,decimals:a});return(await r.getQuote(e,s,i,!0)).amount}catch{}return t}};import{AssetAmount as hn,CallType as yn}from"@galacticcouncil/xc-core";import{toBase64 as Cn}from"@mysten/bcs";import{distinctUntilChanged as bn,finalize as An,shareReplay as vn,Subject as wn}from"rxjs";var ut=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 gn}from"@mysten/sui/utils";var pn=9,mt=class extends ut{async getBalance(){let{address:t}=this.config,e=await this.client.getBalance({owner:t,coinType:gn});return BigInt(e.totalBalance)}async getDecimals(){return pn}};var lt=class{static get(t,e){switch(e.module){case"Native":return new mt(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};import{fromBase64 as fn}from"@mysten/bcs";function Gt(c,t={}){let e=c.inputs??[],n=c.commands??[],s=t.numbers??"string",a=t.decode32As??"address",r=l=>s==="bigint"?l:s==="number"?Number(l):l.toString(),i=l=>{let m=fn(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}},u=l=>l?.GasCoin?"GasCoin":Array.isArray(l?.NestedResult)?l:typeof l?.Input=="number"?o(l.Input):l;return n.map(l=>{if(l.MoveCall){let m=l.MoveCall;return{MoveCall:{...m,arguments:(m.arguments??[]).map(u)}}}if(l.SplitCoins){let m=l.SplitCoins,d=m.coin?.GasCoin?"GasCoin":u(m.coin),g=(m.amounts??[]).map(u);return{SplitCoins:[d,g]}}if(l.MergeCoins){let m=l.MergeCoins;return{MergeCoins:{...m,destination:u(m.destination),sources:(m.sources??[]).map(u)}}}if(l.TransferObjects){let m=l.TransferObjects;return{TransferObjects:{...m,objects:(m.objects??[]).map(u),address:u(m.address)}}}return l})}var dt=class{#t;constructor(t){this.#t=t.client}async buildCall(t,e,n,s){let{transaction:a}=s;a.setSender(t);let r=await a.build({client:this.#t}),i=await a.toJSON(),o=Gt(JSON.parse(i));return{from:t,commands:o,data:Cn(r),type:yn.Sui,dryRun:async()=>{let u=await this.#t.dryRunTransactionBlock({transactionBlock:r});return{call:s.module+"."+s.func,error:u.executionErrorSource}}}}async estimateFee(t,e,n,s){let{transaction:a}=s;a.setSender(t);let r=await a.build({client:this.#t}),o=(await this.#t.dryRunTransactionBlock({transactionBlock:r})).effects.gasUsed,u=BigInt(o.computationCost),l=BigInt(o.storageCost),m=BigInt(o.storageRebate),d=u+l-m;return n.copyWith({amount:d})}async getBalance(t,e){let n=lt.get(this.#t,e),[s,a]=await Promise.all([n.getBalance(),n.getDecimals()]);return hn.fromAsset(t,{amount:s,decimals:a})}async subscribeBalance(t,e){let n=new wn,s=n.pipe(vn(1)),a=async()=>{await(async()=>{let u=await this.getBalance(t,e);n.next(u)})();let o=setInterval(()=>{},3e3);return()=>clearInterval(o)},r;return a().then(i=>r=i),s.pipe(An(()=>r?.()),bn((i,o)=>i.amount===o.amount))}};var I=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 J(e)}registerSolana(t){let e=t;this.platform.Solana=new st(e)}registerSui(t){let e=t;this.platform.Sui=new dt(e)}registerSubstrate(t){let e=t;this.platform.Substrate=new ct(e)}async buildCall(t,e,n,s){return this.platform[s.type].buildCall(t,e,n,s)}async estimateFee(t,e,n,s){return this.platform[s.type].estimateFee(t,e,n,s)}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{acc as En,addr as Fn,AssetAmount as St,Parachain as Dn}from"@galacticcouncil/xc-core";import{big as ee}from"@galacticcouncil/common";import{big as xn}from"@galacticcouncil/common";import L from"big.js";function Jt(c,t,e,n){let s=c.toBig().minus(e.toBig()).minus(c.isSame(t)?t.toBig():new L(0));return n&&(s=s.minus(c.isSame(n)?n.toBig():new L(0))),c.copyWith({amount:s.lt(0)?0n:BigInt(s.toFixed())})}function Yt(c,t,e,n){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 n&&(a=a.plus(c.isSame(n)&&c.toBig().lt(n.toBig())?n.toBig():new L(0))),c.copyWith({amount:BigInt(a.toFixed())})}async function F(c,t){return t.isEvmParachain()?t.getDerivatedAddress(c):c}function Zt(c,t){return t?xn.toBigInt(t,c):0n}import{addr as Sn,AssetAmount as Pn,Parachain as te}from"@galacticcouncil/xc-core";import{big as Bn}from"@galacticcouncil/common";var{EvmAddr:Tn}=Sn,O=class{adapter;config;constructor(t,e){this.adapter=t,this.config=e}async getEd(){let{chain:t}=this.config;if(t instanceof te)return(await x.create(t)).getExistentialDeposit()}async getBalance(t){let{chain:e,route:n}=this.config,{source:s}=n,a=s.asset,r=e.getBalanceAssetId(a),i=Tn.isValid(r.toString())?await F(t,e):t,o=n.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:n}=e,s=n.asset,a=n.min;if(t instanceof te&&a){let r=t.getMinAssetId(s),i=a.build({asset:r});return this.adapter.getBalance(s,i)}return this.getAssetMin()}async getAssetMin(){let{chain:t,route:e}=this.config,{source:n}=e,s=n.asset,a=t.getAssetMin(s),r=await this.getDecimals(s),i=0n;return a&&(i=Bn.toBigInt(a,r)),Pn.fromAsset(s,{amount:i,decimals:r})}async getDecimals(t){let{chain:e}=this.config,n=e.getAssetDecimals(t);return n||(await e.getCurrency()).decimals}};var{EvmAddr:ne}=Fn,U=class extends O{constructor(t,e){super(t,e)}async getCall(t){let{amount:e,sender:n,source:s}=t,a=await this.getTransfer(t);return this.adapter.buildCall(n,e,s.feeBalance,a)}async getDestinationFee(){let{chain:t,route:e}=this.config,{source:n,destination:s,transact:a}=e,r=s.fee.amount,i=n.destinationFee.asset||s.fee.asset,o=await this.getDecimals(i);if(Number.isFinite(r))return{fee:St.fromAsset(i,{amount:ee.toBigInt(r,o),decimals:o}),feeBreakdown:{}};let u=r,{amount:l,breakdown:m}=await u.build({feeAsset:i,transferAsset:n.asset,source:a?a.chain:t,destination:s.chain});return{fee:St.fromAsset(i,{amount:l,decimals:o}),feeBreakdown:m}}async getDestinationFeeBalance(t){let{chain:e,route:n}=this.config,{source:s,destination:a}=n,r=s.asset,i=s.destinationFee.asset||a.fee.asset;if(r.isEqual(i))return this.getBalance(t);let o=e.getBalanceAssetId(i),u=ne.isValid(o.toString())?await F(t,e):t,l=s.destinationFee.balance.build({address:u,asset:i,chain:e});return this.adapter.getBalance(i,l)}async getFee(t){let{chain:e,route:n}=this.config,{amount:s,sender:a,source:r}=t,i=await this.getTransfer(t),o=n.contract?await F(a,e):a,u=await this.adapter.estimateFee(o,s,r.feeBalance,i),{fee:l}=n.source,m=l?Zt(u.decimals,l.extra):0n,d=u.amount+m;return u.copyWith({amount:d})}async getFeeBalance(t){let{chain:e,route:n}=this.config,{source:s}=n;if(!s.fee)return this.getBalance(t);let a=await this.getFeeAsset(t),r=e.getBalanceAssetId(a),i=ne.isValid(r.toString())?await F(t,e):t,o=s.fee.balance.build({address:i,asset:a,chain:e});return this.adapter.getBalance(a,o)}async getFeeAsset(t){let{chain:e,route:n}=this.config,{source:s}=n,a=s.fee,r=s.asset;if(!a)return r;let i=a.asset;return e instanceof Dn&&"build"in i?await i.build({chain:e,address:t}):i}async getTransfer(t){let{chain:e,route:n}=this.config,{contract:s,extrinsic:a,program:r,move:i}=n;if(a){let{address:u,amount:l,asset:m,sender:d}=t,p=await(await x.create(e)).buildMessageId(d,l,m.originSymbol,u);return a.build({...t,messageId:p})}let o=s||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:n}=e;if(n){let s=Object.assign({transact:{chain:n.chain}}),a={...t,...s};return{...await this.getTransactData(n,a),chain:n.chain}}}async getTransactData(t,e){let{chain:n,extrinsic:s}=t,a=await s.build(e),r=await x.create(n),i=a.getTx(r.client),o=e.source.chain,u=e.sender,l=En.getMultilocationDerivatedAccount(o.parachainId,u,n.parachainId===0?0:1,n.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:n,fee:g,feeBalance:p,weight:{refTime:m.weight.ref_time,proofSize:m.weight.proof_size}}}async getTransactFee(t){let{fee:e}=t,n=await this.getDecimals(e.asset),s=ee.toBigInt(e.amount,n);return St.fromAsset(e.asset,{amount:s,decimals:n})}async getTransactFeeBalance(t,e){let{chain:n}=this.config,{fee:s}=t,a=s.balance.build({address:e.sender,asset:s.asset,chain:n});return this.adapter.getBalance(s.asset,a)}};var z=class extends O{constructor(t,e){super(t,e)}};import{AssetAmount as In}from"@galacticcouncil/xc-core";var H=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:n}=await this.dex.chain.getCurrency(),{amount:s}=await this.dex.getQuote(e,t,t);return{aIn:t,aOut:In.fromAsset(e,{amount:s,decimals:n}),enabled:!0}}isSwapSupported(t){try{this.dex}catch{return!1}return!!(t&&t.swap)}async getDestinationSwap(t){let{amount:e,route:n}=await this.dex.getQuote(t,this.destFee,this.destFee),s=this.destFeeBalance.amount<this.destFee.amount,a=this.feeBalance.amount-t.amount>e*2n;return{aIn:t.copyWith({amount:e}),aOut:this.destFee,enabled:s&&a,route:n}}isDestinationSwapSupported(t){try{this.dex}catch{return!1}let e=!t.isSame(this.destFee),n=this.asset.isSame(this.destFee);return e&&!n}};var{EvmAddr:Wn}=kn,Pt=class{config;validations;constructor({configService:t,transferValidations:e}){this.config=t,this.validations=e||[]}registerDex(...t){t.forEach(e=>Mn.getInstance().register(e))}async transfer(t,e,n,s,a){let r=Vn(this.config).assets().asset(t).source(n).destination(a).build();return this.getTransferData(r,e,s)}async remoteXcm(t,e,n,s,a={}){let r=this.config.getChain(e),i=this.config.getChain(n);if(!(r.isSubstrate()&&i.isSubstrate()))throw Error("RemoteXcm is supported only between parachains");let[u,l]=await Promise.all([x.create(r),x.create(i)]),m=new ot(u,l),d=Rn.getMultilocationDerivatedAccount(r.parachainId,t,1,i.usesH160Acc),g=await l.getAsset(),p=await this.transfer(g,t,e,d,n);return m.remoteExec(t,d,s,f=>{let A=f.toDecimal(f.decimals);return p.buildCall(A)},a)}async getTransferData(t,e,n){let s=t.origin,a=t.reverse,r=new I(s.chain),i=new I(a.chain),o=new U(r,s),u=new z(i,a),l=new On(...this.validations),[m,d,g,p,f,A,S]=await Promise.all([o.getBalance(e),o.getFeeBalance(e),o.getDestinationFee(),o.getDestinationFeeBalance(e),o.getMin(),u.getBalance(n),u.getMin()]),{source:w,destination:y}=s.route,P=g.fee.copyWith(y.fee.asset),D=g.feeBreakdown,C={address:n,amount:1n,asset:w.asset,destination:{balance:A,chain:a.chain,fee:P,feeBreakdown:D},sender:e,source:{balance:m,chain:s.chain,fee:d.copyWith({amount:0n}),feeBalance:d,destinationFee:g.fee,destinationFeeBalance:p}};C.transact=await o.getTransact(C);let B=new H(C),h=await o.getFee(C),T;B.isSwapSupported(w.fee)&&(T=await B.getSwap(h),C.source.feeSwap=T);let E;B.isDestinationSwapSupported(h)&&(E=await B.getDestinationSwap(h),C.source.destinationFeeSwap=E),(T||E)&&(h=await o.getFee(C),h=h.padByPct(5n));let pt=await u.getEd(),ft=Yt(A,P,S,pt),Q=await o.getEd(),ht=Jt(m,h,f,Q);return C.amount=0n,C.source.fee=h,{source:{balance:m,destinationFee:g.fee,destinationFeeBalance:p,destinationFeeSwap:E,fee:h,feeBalance:d,feeSwap:T,max:ht,min:m.copyWith({amount:ft.amount})},destination:{balance:A,fee:P},async buildCall(b){let v=Object.assign({},C);return v.amount=se.toBigInt(b,m.decimals),v.transact=await o.getTransact(v),o.getCall(v)},async estimateFee(b){let v=Object.assign({},C);return v.amount=se.toBigInt(b,m.decimals),v.transact=await o.getTransact(v),o.getFee(v)},async validate(b){let v=Object.assign({},C),yt=b||h.amount;return v.source.fee=h.copyWith({amount:yt}),l.validate(v)}}}async subscribeBalance(t,e,n){let s=this.config.getChainRoutes(e),a=new I(s.chain),r=s.getUniqueRoutes().map(async({source:u})=>{let{asset:l,balance:m}=u,d=s.chain.getBalanceAssetId(l),g=Wn.isValid(d.toString())?await F(t,s.chain):t,p=m.build({address:g,asset:l,chain:s.chain});return a.subscribeBalance(l,p)}),i=await Promise.all(r);return _n(i).pipe(Nn(500)).subscribe(n)}};import{ConfigBuilder as jn}from"@galacticcouncil/xc-core";function Ln(c){let t=jn(c.config).assets();return{assets:t,withAsset(e){let n=t.asset(e);return{sources:n,withSource(s){let a=n.source(s);return{destinations:a,withDestination(r){let{routes:i,build:o}=a.destination(r);return{routes:i,build({srcAddress:u,dstAddress:l,dstAsset:m}){let d=o(m);return c.getTransferData(d,u,l)}}}}}}}}}import{Precompile as Un}from"@galacticcouncil/xc-core";var zn="https://api.wormholescan.io",gt=class{_baseUrl;constructor(t){this._baseUrl=t||zn}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}),s=await(await fetch(e)).json();if(s.data.length>0)return s.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:n,toChain:s}=t,a="0x"+n.substring(26);return e===3&&s===16&&a===Un.Bridge}};import{acc as Hn,mrl as Qn,ChainType as re,Parachain as Kn,Precompile as qn,Wormhole as _}from"@galacticcouncil/xc-core";import{encoding as Xn}from"@wormhole-foundation/sdk-base";import{keccak256 as $n}from"@wormhole-foundation/sdk-connect";import{deserialize as Gn}from"@wormhole-foundation/sdk-definitions";var ae=(n=>(n[n.WaitingForVaa=0]="WaitingForVaa",n[n.VaaEmitted=1]="VaaEmitted",n[n.Completed=2]="Completed",n))(ae||{});var Jn=300*1e3,ie=class{parachainId;config;whScan;constructor(t,e){this.config=t,this.parachainId=e,this.whScan=new gt}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 n=t.toISOString();return{page:"0",pageSize:"50",includeEndDate:"true",from:e.toISOString(),to:n}}async getWithdraws(t){let e=Hn.getMultilocationDerivatedAccount(this.parachainId,t,1,!0),s=(await this.whScan.getOperations({...this.filters,address:e})).map(async a=>{let{content:r}=a,{payload:i,standarizedProperties:o}=r,u=this.getStatus(a),l=this.chains.find(f=>f instanceof Kn&&f.parachainId===this.parachainId),{toAddress:m,tokenAddress:d}=o,g=this.chains.find(f=>_.isKnown(f)&&_.fromChain(f).getWormholeId()===i.tokenChain),p;if(u===1&&a.vaa){let{timestamp:f}=this.getVaaHeader(a.vaa.raw),A=a.vaa.raw;if(this.isStuck(f))switch(g.getType()){case re.EvmChain:let S=new K(g);p=async y=>S.redeem(y,A);break;case re.SolanaChain:let w=new rt(g);p=async y=>w.redeem(y,A);break}}return{asset:d,assetSymbol:a.data.symbol,amount:a.data.tokenAmount,from:t,fromChain:l,to:m,toChain:g,status:u,redeem:p,operation:a}});return Promise.all(s)}async getDeposits(t,e="hydration"){let n=await this.whScan.getOperations({...this.filters,address:qn.Bridge,pageSize:"100"}),s=this.config.chains.get(e);if(!s)return[];let a=s,i=(await Qn.createPayload(a,t)).toHex(),o=n.filter(u=>{let{content:l}=u,{payload:m}=l;return m.payloadType===3&&m.toChain===16&&"0x"+m.payload===i}).map(async u=>{let{content:l,sourceChain:m}=u,{payload:d,standarizedProperties:g}=l,p=this.getStatus(u),{tokenAddress:f}=g,A=this.chains.find(y=>_.isKnown(y)&&_.fromChain(y).getWormholeId()===d.tokenChain),S=this.chains.find(y=>_.isKnown(y)&&_.fromChain(y).getWormholeId()===d.toChain),w;if(p===1&&u.vaa){let{timestamp:y}=this.getVaaHeader(u.vaa.raw),P=u.vaa.raw;if(this.isStuck(y)){let D=new it(S);w=async C=>D.redeemMrlViaXcm(C,P)}}return{asset:f,assetSymbol:u.data.symbol,amount:u.data.tokenAmount,from:m.from,fromChain:A,to:t,toChain:s,status:p,redeem:w,operation:u}});return Promise.all(o)}isStuck(t){return Date.now()>=t*1e3+Jn}getVaaHeader(t){let e=Xn.b64.decode(t),n=Gn("Uint8Array",e);return{timestamp:n.timestamp,emitterChain:n.emitterChain,emitterAddress:n.emitterAddress.toString(),sequence:n.sequence,payload:n.payload,hash:n.hash,id:$n(n.hash)}}getStatus(t){return t.vaa?t.targetChain&&t.targetChain.status==="completed"?2:1:0}};export{K as EvmClaim,J as EvmPlatform,H as FeeSwap,I as PlatformAdapter,rt as SolanaClaim,at as SolanaLilJit,st as SolanaPlatform,it as SubstrateClaim,ot as SubstrateExec,ct as SubstratePlatform,x as SubstrateService,dt as SuiPlatform,Ln as TransferBuilder,Pt as Wallet,ae as WhStatus,gt as WormholeScan,ie as WormholeTransfer,Ot as chunkBySize,Ca as deserializeV0,V as ixToHuman,nt as serializeV0};
|
package/build/types/FeeSwap.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ export declare class FeeSwap {
|
|
|
3
3
|
readonly ctx: TransferCtx;
|
|
4
4
|
constructor(ctx: TransferCtx);
|
|
5
5
|
get asset(): AssetAmount;
|
|
6
|
-
get dex(): import("@galacticcouncil/xc-core").Dex
|
|
6
|
+
get dex(): import("@galacticcouncil/xc-core").Dex;
|
|
7
7
|
get destFee(): AssetAmount;
|
|
8
8
|
get destFeeBalance(): AssetAmount;
|
|
9
9
|
get feeBalance(): AssetAmount;
|
|
@@ -1,32 +1,25 @@
|
|
|
1
|
-
import { AnyParachain, Asset, AssetAmount, ExtrinsicConfig } from '@galacticcouncil/xc-core';
|
|
2
|
-
import {
|
|
1
|
+
import { AnyParachain, Asset, AssetAmount, ChainCurrency, Extrinsic, ExtrinsicConfig } from '@galacticcouncil/xc-core';
|
|
2
|
+
import { HubApis } from '@galacticcouncil/descriptors';
|
|
3
|
+
type TRawDryRun = HubApis['DryRunApi']['dry_run_call']['Value']['value'];
|
|
4
|
+
type TDryRun = Extract<TRawDryRun, {
|
|
5
|
+
execution_result: any;
|
|
6
|
+
}>;
|
|
3
7
|
export declare class SubstrateService {
|
|
4
|
-
readonly client: PolkadotClient;
|
|
5
|
-
readonly api: ReturnType<PolkadotClient['getUnsafeApi']>;
|
|
6
8
|
readonly chain: AnyParachain;
|
|
7
|
-
private
|
|
8
|
-
|
|
9
|
-
private _decimals?;
|
|
10
|
-
constructor(client: PolkadotClient, chain: AnyParachain);
|
|
9
|
+
private _currency?;
|
|
10
|
+
constructor(chain: AnyParachain);
|
|
11
11
|
static create(chain: AnyParachain): Promise<SubstrateService>;
|
|
12
|
-
|
|
12
|
+
get client(): import("polkadot-api").PolkadotClient;
|
|
13
|
+
get api(): import("polkadot-api").UnsafeApi<unknown>;
|
|
14
|
+
getCurrency(): Promise<ChainCurrency>;
|
|
13
15
|
getAsset(): Promise<Asset>;
|
|
14
16
|
getDecimals(): Promise<number>;
|
|
15
17
|
getExistentialDeposit(): Promise<AssetAmount>;
|
|
16
18
|
isDryRunSupported(): boolean;
|
|
17
|
-
getDecimalsForAsset(asset: Asset): Promise<number>;
|
|
18
|
-
getExtrinsic(config: ExtrinsicConfig): Transaction<any, any, any, any>;
|
|
19
|
-
/**
|
|
20
|
-
* Check if extrinsic is a batch call
|
|
21
|
-
*/
|
|
22
|
-
private isBatchCall;
|
|
23
|
-
/**
|
|
24
|
-
* Build batch call with recursive ExtrinsicConfig processing
|
|
25
|
-
*/
|
|
26
|
-
private buildBatchCall;
|
|
27
19
|
buildMessageId(account: string, amount: bigint, asset: string, beneficiary: string): Promise<string>;
|
|
28
|
-
dryRun(account: string,
|
|
20
|
+
dryRun(account: string, tx: Extrinsic): Promise<TDryRun>;
|
|
29
21
|
estimateNetworkFee(account: string, config: ExtrinsicConfig): Promise<bigint>;
|
|
30
22
|
estimateDeliveryFee(account: string, config: ExtrinsicConfig): Promise<bigint>;
|
|
31
23
|
private estimateDeliveryFeeWith;
|
|
32
24
|
}
|
|
25
|
+
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const getDeliveryFeeFromDryRun: (events: any[]) => bigint;
|
|
2
|
-
export declare const getErrorFromDryRun: (
|
|
2
|
+
export declare const getErrorFromDryRun: (executionResult: any) => string | undefined;
|
|
@@ -1,110 +1,120 @@
|
|
|
1
1
|
import { AnyParachain, AssetAmount } from '@galacticcouncil/xc-core';
|
|
2
|
+
import { Binary } from 'polkadot-api';
|
|
2
3
|
export declare function buildBeneficiary(dstAccount: string): {
|
|
3
4
|
parents: number;
|
|
4
5
|
interior: {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
type: string;
|
|
7
|
+
value: ({
|
|
8
|
+
type: string;
|
|
9
|
+
value: {
|
|
10
|
+
network: undefined;
|
|
11
|
+
key: Binary;
|
|
8
12
|
};
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
X1: {
|
|
15
|
-
AccountId32: {
|
|
16
|
-
id: string;
|
|
13
|
+
} | {
|
|
14
|
+
type: string;
|
|
15
|
+
value: {
|
|
16
|
+
network: undefined;
|
|
17
|
+
id: Binary;
|
|
17
18
|
};
|
|
18
|
-
}[];
|
|
19
|
+
})[];
|
|
19
20
|
};
|
|
20
21
|
};
|
|
21
22
|
export declare function buildXcmDest(dstChain: AnyParachain): {
|
|
22
|
-
|
|
23
|
+
type: string;
|
|
24
|
+
value: {
|
|
23
25
|
parents: number;
|
|
24
26
|
interior: {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
+
type: string;
|
|
28
|
+
value: {
|
|
29
|
+
type: string;
|
|
30
|
+
value: number;
|
|
27
31
|
}[];
|
|
28
32
|
};
|
|
29
33
|
};
|
|
30
34
|
};
|
|
31
|
-
export declare
|
|
32
|
-
|
|
33
|
-
|
|
35
|
+
export declare const buildXcmMessage: (dstAccount: string, dstFeeLocation: any, dstFee: AssetAmount, dstRefTime: bigint, dstProofSize: bigint, dstCallEncoded: Binary) => {
|
|
36
|
+
type: string;
|
|
37
|
+
value: ({
|
|
38
|
+
type: string;
|
|
39
|
+
value: {
|
|
34
40
|
id: any;
|
|
35
41
|
fun: {
|
|
36
|
-
|
|
42
|
+
type: string;
|
|
43
|
+
value: any;
|
|
37
44
|
};
|
|
38
|
-
}
|
|
39
|
-
BuyExecution?: undefined;
|
|
40
|
-
Transact?: undefined;
|
|
41
|
-
RefundSurplus?: undefined;
|
|
42
|
-
DepositAsset?: undefined;
|
|
45
|
+
};
|
|
43
46
|
} | {
|
|
44
|
-
|
|
47
|
+
type: string;
|
|
48
|
+
value: {
|
|
45
49
|
fees: {
|
|
46
50
|
id: any;
|
|
47
51
|
fun: {
|
|
48
|
-
|
|
52
|
+
type: string;
|
|
53
|
+
value: any;
|
|
49
54
|
};
|
|
50
55
|
};
|
|
51
|
-
|
|
56
|
+
weight_limit: {
|
|
57
|
+
type: string;
|
|
58
|
+
};
|
|
59
|
+
origin_kind?: undefined;
|
|
60
|
+
require_weight_at_most?: undefined;
|
|
61
|
+
call?: undefined;
|
|
62
|
+
assets?: undefined;
|
|
63
|
+
beneficiary?: undefined;
|
|
52
64
|
};
|
|
53
|
-
WithdrawAsset?: undefined;
|
|
54
|
-
Transact?: undefined;
|
|
55
|
-
RefundSurplus?: undefined;
|
|
56
|
-
DepositAsset?: undefined;
|
|
57
65
|
} | {
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
proofSize: string;
|
|
66
|
+
type: string;
|
|
67
|
+
value: {
|
|
68
|
+
origin_kind: {
|
|
69
|
+
type: string;
|
|
63
70
|
};
|
|
64
|
-
|
|
65
|
-
|
|
71
|
+
require_weight_at_most: {
|
|
72
|
+
ref_time: bigint;
|
|
73
|
+
proof_size: bigint;
|
|
66
74
|
};
|
|
75
|
+
call: Binary;
|
|
76
|
+
fees?: undefined;
|
|
77
|
+
weight_limit?: undefined;
|
|
78
|
+
assets?: undefined;
|
|
79
|
+
beneficiary?: undefined;
|
|
67
80
|
};
|
|
68
|
-
WithdrawAsset?: undefined;
|
|
69
|
-
BuyExecution?: undefined;
|
|
70
|
-
RefundSurplus?: undefined;
|
|
71
|
-
DepositAsset?: undefined;
|
|
72
81
|
} | {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
BuyExecution?: undefined;
|
|
76
|
-
Transact?: undefined;
|
|
77
|
-
DepositAsset?: undefined;
|
|
82
|
+
type: string;
|
|
83
|
+
value?: undefined;
|
|
78
84
|
} | {
|
|
79
|
-
|
|
85
|
+
type: string;
|
|
86
|
+
value: {
|
|
80
87
|
assets: {
|
|
81
|
-
|
|
82
|
-
|
|
88
|
+
type: string;
|
|
89
|
+
value: {
|
|
90
|
+
type: string;
|
|
91
|
+
value: number;
|
|
83
92
|
};
|
|
84
93
|
};
|
|
85
94
|
beneficiary: {
|
|
86
95
|
parents: number;
|
|
87
96
|
interior: {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
97
|
+
type: string;
|
|
98
|
+
value: ({
|
|
99
|
+
type: string;
|
|
100
|
+
value: {
|
|
101
|
+
network: undefined;
|
|
102
|
+
key: Binary;
|
|
91
103
|
};
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
X1: {
|
|
98
|
-
AccountId32: {
|
|
99
|
-
id: string;
|
|
104
|
+
} | {
|
|
105
|
+
type: string;
|
|
106
|
+
value: {
|
|
107
|
+
network: undefined;
|
|
108
|
+
id: Binary;
|
|
100
109
|
};
|
|
101
|
-
}[];
|
|
110
|
+
})[];
|
|
102
111
|
};
|
|
103
112
|
};
|
|
113
|
+
fees?: undefined;
|
|
114
|
+
weight_limit?: undefined;
|
|
115
|
+
origin_kind?: undefined;
|
|
116
|
+
require_weight_at_most?: undefined;
|
|
117
|
+
call?: undefined;
|
|
104
118
|
};
|
|
105
|
-
WithdrawAsset?: undefined;
|
|
106
|
-
BuyExecution?: undefined;
|
|
107
|
-
Transact?: undefined;
|
|
108
|
-
RefundSurplus?: undefined;
|
|
109
119
|
})[];
|
|
110
120
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@galacticcouncil/xc-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
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": "^0.
|
|
36
|
+
"@galacticcouncil/xc-core": "^0.3.0"
|
|
37
37
|
}
|
|
38
38
|
}
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Naming conversion utilities for PAPI unsafe API
|
|
3
|
-
*
|
|
4
|
-
* These utilities convert config-style names to PAPI runtime names.
|
|
5
|
-
* Used when working with unsafe API for generic chain support.
|
|
6
|
-
*/
|
|
7
|
-
/**
|
|
8
|
-
* Convert string to PascalCase (first letter uppercase)
|
|
9
|
-
* Used for pallet names and query function names in PAPI
|
|
10
|
-
* @example
|
|
11
|
-
* toPascalCase('balances') // 'Balances'
|
|
12
|
-
* toPascalCase('polkadotXcm') // 'PolkadotXcm'
|
|
13
|
-
* toPascalCase('multiTransactionPayment') // 'MultiTransactionPayment'
|
|
14
|
-
*/
|
|
15
|
-
export declare function toPascalCase(str: string): string;
|
|
16
|
-
/**
|
|
17
|
-
* Convert camelCase string to snake_case
|
|
18
|
-
* Used for extrinsic/function names in PAPI
|
|
19
|
-
* @example
|
|
20
|
-
* toSnakeCase('transferAll') // 'transfer_all'
|
|
21
|
-
* toSnakeCase('batchAll') // 'batch_all'
|
|
22
|
-
* toSnakeCase('setSufficient') // 'set_sufficient'
|
|
23
|
-
*/
|
|
24
|
-
export declare function toSnakeCase(str: string): string;
|