@galacticcouncil/xc-sdk 0.1.0 → 0.2.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 +9 -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 He=Object.create;var Ct=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var qe=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var $e=(o,t)=>{for(var e in t)Ct(o,e,{get:t[e],enumerable:!0})},se=(o,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ke(t))!Xe.call(o,s)&&s!==e&&Ct(o,s,{get:()=>t[s],enumerable:!(n=Qe(t,s))||n.enumerable});return o};var Ge=(o,t,e)=>(e=o!=null?He(qe(o)):{},se(t||!o||!o.__esModule?Ct(e,"default",{value:o,enumerable:!0}):e,o)),Je=o=>se(Ct({},"__esModule",{value:!0}),o);var cn={};$e(cn,{EvmClaim:()=>et,EvmPlatform:()=>st,FeeSwap:()=>tt,PlatformAdapter:()=>U,SolanaClaim:()=>ct,SolanaLilJit:()=>ot,SolanaPlatform:()=>it,SubstrateClaim:()=>ut,SubstrateExec:()=>mt,SubstratePlatform:()=>dt,SubstrateService:()=>S,SuiPlatform:()=>gt,TransferBuilder:()=>We,Wallet:()=>Ut,WhStatus:()=>ee,WormholeScan:()=>ht,WormholeTransfer:()=>ne,chunkBySize:()=>qt,deserializeV0:()=>tn,ixToHuman:()=>z,serializeV0:()=>rt});module.exports=Je(cn);var te=require("@galacticcouncil/common"),D=require("@galacticcouncil/xc-core"),jt=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,c=(0,ae.encodeFunctionData)({abi:r,functionName:"completeTransfer",args:["0x"+a]});return{abi:JSON.stringify(r),data:c,from:t,to:n.getTokenBridge()}}};var R=require("@galacticcouncil/xc-core"),O=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(),c=await this.getNonce(t);try{let{results:i}=await r.simulateCalls({account:t,calls:[{to:e,abi:this.abi,functionName:a,args:n,value:s}],stateOverrides:[{address:t,nonce:c}]}),[m]=i;return m}catch(i){return console.log(`Can't simulate call!
|
|
3
|
+
`,i.details),{error:i}}}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(o){let t=o.module==="Snowbridge"&&o.func==="sendToken"&&o.args[0]==="0x0000000000000000000000000000000000000000";return o.module==="TokenBridge"&&["wrapAndTransferETHWithPayload","wrapAndTransferETH"].includes(o.func)||t}function ce(o){return Object.entries(ie.Precompile).map(([e,n])=>n).includes(o.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:c,calldata:i}=a,m={abi:JSON.stringify(r),data:i,from:t,to:s.address,type:R.CallType.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(ce(s)||oe(s))return m;let l=new R.Erc20Client(this.#t,c),u=await l.allowance(t,s.address);if(u>=e)return m;let d=l.approve(s.address,e);return{abi:JSON.stringify(R.Abi.Erc20),allowance:u,data:d,from:t,to:c,type:R.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 R.AssetAmount.fromAsset(t,{amount:s,decimals:a})}async subscribeBalance(t,e){let n=new O.Subject,s=n.pipe((0,O.shareReplay)(1)),a=this.#t.getProvider(),r=async()=>{let i=async()=>{let l=await this.getBalance(t,e);n.next(l)};await i();let m=a.watchBlocks({onBlock:()=>i()});return()=>m()},c;return r().then(i=>c=i),s.pipe((0,O.finalize)(()=>c?.()),(0,O.distinctUntilChanged)((i,m)=>i.amount===m.amount))}};var It=require("@galacticcouncil/xc-core"),pe=require("@solana/web3.js"),he=require("buffer"),_=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 Ye=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 Ye}};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:c})=>{let i=c.data.parsed.info.tokenAmount;return r+=BigInt(i.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 E=require("@solana/web3.js"),me=.5,le=2,de=1,ge=1e6,Ze=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 E.PublicKey(t),{blockhash:s}=await this.connection.getLatestBlockhash("finalized");return new E.TransactionMessage({payerKey:n,recentBlockhash:s,instructions:e}).compileToV0Message()}async createPriorityFeeInstructions(t,e=me,n=le,s=de,a=ge){let[r,c]=await Promise.all([this.determineComputeBudget(t),this.determinePriorityFee(t,e,n,s,a)]);return[E.ComputeBudgetProgram.setComputeUnitLimit({units:r}),E.ComputeBudgetProgram.setComputeUnitPrice({microLamports:c})]}async simulateTransaction(t,e){let n=new E.VersionedTransaction(e);return(await this.connection.simulateTransaction(n,{accounts:{encoding:"base64",addresses:[t]}})).value}async determineComputeBudget(t){let e=new E.VersionedTransaction(t),n=await this.connection.simulateTransaction(e),{err:s,unitsConsumed:a}=n.value;return a&&!s?Math.round(a*1.2):Ze}async determinePriorityFee(t,e=me,n=le,s=de,a=ge){let r=s,c=await this.getTxAccounts(t),i=await this.connection.getRecentPrioritizationFees({lockedWritableAccounts:c});if(i){let m=i.map(u=>u.prioritizationFee).filter(u=>u>0).sort((u,d)=>u-d),l=Math.ceil(m.length*e);if(m.length>l){let d=m[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 fe=require("@solana/web3.js");function z(o){return o.map(t=>({program:t.programId.toBase58(),data:t.data.toString("hex"),keys:t.keys.map(e=>e.pubkey.toBase58())}))}function qt(o,t=1e3){let e=[],n=[],s=0;for(let a of o){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(o){let t=o.serialize();return Buffer.from(t).toString("hex")}function tn(o){let t=Buffer.from(o,"hex"),e=Uint8Array.from(t);return fe.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),c=r.serialize(),i=he.Buffer.from(c).toString("hex");return{from:t,data:i,ix:z(s.instructions),signers:s.signers,type:It.CallType.Solana,dryRun:async()=>{let{err:m,logs:l}=await a.simulateTransaction(t,r);return{call:s.module+"."+s.func,error:m,events:l}}}}async estimateFee(t,e,n,s){let a=at.get(this.#t,s),r=await a.estimateFee(t,e),c=await a.getPriorityMessage(t),{accounts:i}=await a.simulateTransaction(t,c),l=(i&&i[0])?.lamports;if(l){let u=s.module==="TokenBridge"&&s.func==="TransferNativeWithPayload";return n.copyWith({amount:n.amount-BigInt(l)-(u?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 It.AssetAmount.fromAsset(t,{amount:s,decimals:a})}async subscribeBalance(t,e){let n=new _.Subject,s=n.pipe((0,_.shareReplay)(1)),a=async()=>{let c=async()=>{let l=await this.getBalance(t,e);n.next(l)};await c();let i=new pe.PublicKey(e.address),m=this.#t.onAccountChange(i,()=>c());return()=>{this.#t.removeAccountChangeListener(m)}},r;return a().then(c=>r=c),s.pipe((0,_.finalize)(()=>r?.()),(0,_.distinctUntilChanged)((c,i)=>c.amount===i.amount))}};var $=require("@galacticcouncil/xc-core"),k=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"),Dt=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),c=this.derivePostedVaaKey(n.getCoreBridge(),Buffer.from(a.hash)),i=new k.PublicKey(t),m=[];if(!await this.#e.getAccountInfo(c)){let P=k.Keypair.generate(),x=await Xt.utils.createVerifySignaturesInstructions(this.#t.connection,n.getCoreBridge(),i,r,P.publicKey),y=qt(x,1e3);for(let T=0;T<y.length;T++){let h=y[T],M=await this.getV0Message(i,h),V=rt(M);m.push({from:t,data:V,ix:z(h),signers:[P],type:$.CallType.Solana})}let B=Xt.utils.createPostVaaInstruction(this.#e,n.getCoreBridge(),i,r,P.publicKey),L=await this.getV0Message(i,[B]),C=rt(L);m.push({from:t,data:C,ix:z([B]),type:$.CallType.Solana})}let d=(a.payload.token.chain==="Solana"?Dt.createCompleteTransferNativeInstruction:Dt.createCompleteTransferWrappedInstruction)(this.#e,n.getTokenBridge(),n.getCoreBridge(),i,a),g=await this.#n.getTipAccount(),f=k.SystemProgram.transfer({fromPubkey:i,toPubkey:new k.PublicKey(g[0]),lamports:1e3}),p=await this.getV0Message(i,[d,f]),v=rt(p);return m.push({from:t,data:v,ix:z([d]),type:$.CallType.Solana}),m}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 k.TransactionMessage({payerKey:t,recentBlockhash:n,instructions:e}).compileToV0Message()}};var N=require("@galacticcouncil/xc-core"),Gt=require("@wormhole-foundation/sdk-base"),be=require("viem"),ut=class{#t;constructor(t){this.#t=t,N.Wormhole.fromChain(this.#t)}redeemMrl(t,e){let n=Gt.encoding.b64.decode(e),s=Gt.encoding.hex.encode(n),a=N.Abi.Gmp,r=(0,be.encodeFunctionData)({abi:a,functionName:"wormholeTransferERC20",args:["0x"+s]});return{abi:JSON.stringify(a),data:r,from:t,to:N.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:N.CallType.Substrate,dryRun:async()=>{},txOptions:void 0}}};var Mt=require("@galacticcouncil/xc-core"),kt=require("polkadot-api");var Ae=require("@galacticcouncil/common");async function Jt(o,t,e){let n=await e.getDecimals(),s=e.chain.getAssetDecimals(t)??n,a=e.chain.usesChainDecimals?n:s;return{amount:Ae.big.convertDecimals(o,a,s),decimals:s}}var ve=require("@galacticcouncil/common"),we=o=>{let t=[];for(let e of o)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)},G=o=>{let t=o.value.error;return t.type==="Module"?ve.enums.enumPath(t.value):JSON.stringify(t.value)};var Rt=require("@galacticcouncil/common");function en(o){return{parents:0,interior:{type:"X1",value:[o.startsWith("0x")?Rt.xcm.toAccountKey20(o):Rt.xcm.toAccountId32(o)]}}}function Se(o){return{type:"V4",value:{parents:1,interior:{type:"X1",value:[{type:"Parachain",value:o.parachainId}]}}}}var xe=(o,t)=>({id:Rt.xcm.transform(o),fun:{type:"Fungible",value:t}}),Pe=(o,t,e,n,s,a)=>{console.log(a);let r=en(o);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,c=await this.#t.getAsset(),i=this.#e.api,m=this.#e.chain,l=await m.getCurrency(),u=l.asset,d=l.decimals,g=m.getAssetXcmLocation(u),f=kt.Binary.fromHex(n.data),v=await(await i.txFromCallData(f)).getPaymentInfo(e),P=BigInt(v.partial_fee)*120n/100n,x=Mt.AssetAmount.fromAsset(u,{amount:P,decimals:d}),y=v.weight.ref_time,B=v.weight.proof_size,L=Se(m),C=Pe(e,g,x,y,B,f),T=r.tx.PolkadotXcm.send({dest:L,message:C}),h=[];try{let b=await this.#t.chain.dex.getCalldata(t,a.srcFeeAsset||c,u,x,10),w=kt.Binary.fromHex(b),Qt=await r.txFromCallData(w);h.push(Qt)}catch{}let M=await s(x),V=kt.Binary.fromHex(M.data),Lt=await r.txFromCallData(V);h.push(Lt),h.push(T);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:Mt.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 H=require("@galacticcouncil/xc-core"),Q=require("rxjs");var F=require("@galacticcouncil/xc-core"),Vt=require("@polkadot-api/substrate-bindings"),lt=require("@polkadot-api/utils"),Yt=require("polkadot-api");var{Ss58Addr:Be}=F.addr,S=class o{chain;_currency;constructor(t){this.chain=t}static async create(t){return new o(t)}get client(){return this.chain.client}get api(){return this.client.getUnsafeApi()}async getCurrency(){return this._currency||(this._currency=this.chain.getCurrency()),this._currency}async getAsset(){return(await this.getCurrency()).asset}async getDecimals(){return(await this.getCurrency()).decimals}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 F.AssetAmount.fromAsset(e,{amount:t,decimals:n})}isDryRunSupported(){return this.api.apis?.DryRunApi!==void 0}async getExtrinsic(t){let e=this.api.tx[t.module][t.func],n=await t.getArgs(e);if(Array.isArray(n)&&t.func==="batch_all"){let a=n.map(async({module:i,func:m,getArgs:l})=>{let u=this.api.tx[i][m],d=await l(u);return u(d)}),c=(await Promise.all(a)).map(i=>i.decodedCall);return e({calls:c})}return e(n)}async buildMessageId(t,e,n,s){let a=await this.client._request("system_accountNextIndex",[t]),r=Vt.u32.enc(a),c=l=>new TextEncoder().encode(l),i=new Uint8Array([...c(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),...c(s),...c(e.toString())]),m=(0,Vt.Blake2256)(i);return(0,lt.toHex)(m)}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");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=await this.getExtrinsic(e),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 n=await e.getArgs(),s="dest"in n?n.dest:void 0;if(!s)return t;let a=F.multiloc.findNestedKey(s,"interior"),r=F.multiloc.findParachain(s);if(F.multiloc.findGlobalConsensus(s))return t;if(r){let i=F.acc.getSovereignAccounts(r);return this.chain.parachainId===0?Be.encodePubKey(i.relay):Be.encodePubKey(i.generic)}if(a&&a.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,c=await this.useSignerFee(n)?{asset:new H.Asset(n)}:void 0,i=await a.getExtrinsic(s),m=s.module+"."+s.func,l=await i.getEncodedData();return{from:t,data:l.asHex(),type:H.CallType.Substrate,txOptions:c,dryRun:a.isDryRunSupported()?async()=>{try{let u=await a.getExtrinsic(s),d=await a.dryRun(t,u),g=d.execution_result&&d.execution_result.success?void 0:G(d.execution_result);return{call:m,error:g,events:d.emitted_events||[],xcm:d.forwarded_xcms||[]}}catch(u){return{call:m,error:u instanceof Error?u.message:"unknown"}}}:()=>{}}}async estimateFee(t,e,n,s){let a=await this.#t,r=await a.estimateNetworkFee(t,s),c=await a.estimateDeliveryFee(t,s),i=await this.exchangeFee(r+c,n),m=await Jt(i,n,a);return n.copyWith(m)}async getBalance(t,e){let n=await this.subscribeBalance(t,e);return(0,Q.firstValueFrom)(n)}async subscribeBalance(t,e){let n=await this.#t,{module:s,func:a,args:r,transform:c}=e;return n.client.getUnsafeApi().query[s][a].watchValue(...r).pipe((0,Q.concatMap)(l=>c(l)),(0,Q.distinctUntilChanged)((l,u)=>l===u),(0,Q.concatMap)(async l=>{let u=await Jt(l,t,n);return H.AssetAmount.fromAsset(t,u)}))}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,c=H.AssetAmount.fromAsset(s,{amount:t,decimals:a});return(await r.getQuote(e,s,c,!0)).amount}catch{}return t}};var Wt=require("@galacticcouncil/xc-core"),Ie=require("@mysten/bcs"),W=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 Te=require("@mysten/sui/utils");var nn=9,_t=class extends Ot{async getBalance(){let{address:t}=this.config,e=await this.client.getBalance({owner:t,coinType:Te.SUI_TYPE_ARG});return BigInt(e.totalBalance)}async getDecimals(){return nn}};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 Ee=require("@mysten/bcs");function Fe(o,t={}){let e=o.inputs??[],n=o.commands??[],s=t.numbers??"string",a=t.decode32As??"address",r=l=>s==="bigint"?l:s==="number"?Number(l):l.toString(),c=l=>{let u=(0,Ee.fromBase64)(l),d=g=>{let f=0n;for(let p=0;p<g;p++)f|=BigInt(u[p])<<8n*BigInt(p);return f};return u.length===1?{type:"pure",valueType:"u8",value:Number(u[0])}:u.length===2?{type:"pure",valueType:"u16",value:r(d(2))}:u.length===4?{type:"pure",valueType:"u32",value:Number(d(4))}:u.length===8?{type:"pure",valueType:"u64",value:r(d(8))}:u.length===32&&a==="address"?{type:"pure",valueType:"address",value:"0x"+[...u].map(f=>f.toString(16).padStart(2,"0")).join("")}:{type:"pure",valueType:"vector<u8>",value:Array.from(u)}},i=l=>{let u=e[l];if(!u)return{Input:l};if(u.Pure?.bytes)return c(u.Pure.bytes);let d=u.Object?.SharedObject;if(d)return{type:"object",objectType:"sharedObject",objectId:d.objectId,initialSharedVersion:String(d.initialSharedVersion),mutable:!!d.mutable};let g=u.Object?.ImmOrOwnedObject;return g?{type:"object",objectType:"immOrOwnedObject",objectId:g.objectId,version:String(g.version),digest:g.digest??void 0}:{Input:l}},m=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 u=l.MoveCall;return{MoveCall:{...u,arguments:(u.arguments??[]).map(m)}}}if(l.SplitCoins){let u=l.SplitCoins,d=u.coin?.GasCoin?"GasCoin":m(u.coin),g=(u.amounts??[]).map(m);return{SplitCoins:[d,g]}}if(l.MergeCoins){let u=l.MergeCoins;return{MergeCoins:{...u,destination:m(u.destination),sources:(u.sources??[]).map(m)}}}if(l.TransferObjects){let u=l.TransferObjects;return{TransferObjects:{...u,objects:(u.objects??[]).map(m),address:m(u.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}),c=await a.toJSON(),i=Fe(JSON.parse(c));return{from:t,commands:i,data:(0,Ie.toBase64)(r),type:Wt.CallType.Sui,dryRun:async()=>{let m=await this.#t.dryRunTransactionBlock({transactionBlock:r});return{call:s.module+"."+s.func,error:m.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,m=BigInt(i.computationCost),l=BigInt(i.storageCost),u=BigInt(i.storageRebate),d=m+l-u;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 W.Subject,s=n.pipe((0,W.shareReplay)(1)),a=async()=>{await(async()=>{let m=await this.getBalance(t,e);n.next(m)})();let i=setInterval(()=>{},3e3);return()=>clearInterval(i)},r;return a().then(c=>r=c),s.pipe((0,W.finalize)(()=>r?.()),(0,W.distinctUntilChanged)((c,i)=>c.amount===i.amount))}};var U=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 De=require("@galacticcouncil/common"),Y=Ge(require("big.js"),1);function Re(o,t,e,n){let s=o.toBig().minus(e.toBig()).minus(o.isSame(t)?t.toBig():new Y.default(0));return n&&(s=s.minus(o.isSame(n)?n.toBig():new Y.default(0))),o.copyWith({amount:s.lt(0)?0n:BigInt(s.toFixed())})}function ke(o,t,e,n){let a=o.copyWith({amount:0n}).toBig().plus(o.isSame(t)?t.toBig():new Y.default(0)).plus(o.toBig().lt(e.toBig())?e.toBig():new Y.default(0));return n&&(a=a.plus(o.isSame(n)&&o.toBig().lt(n.toBig())?n.toBig():new Y.default(0))),o.copyWith({amount:BigInt(a.toFixed())})}async function j(o,t){return t.isEvmParachain()?t.getDerivatedAddress(o):o}function Me(o,t){return t?De.big.toBigInt(t,o):0n}var K=require("@galacticcouncil/xc-core"),Ve=require("@galacticcouncil/common");var{EvmAddr:sn}=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),c=sn.isValid(r.toString())?await j(t,e):t,i=n.source.balance.build({address:c,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 K.Parachain&&a){let r=t.getMinAssetId(s),c=a.build({asset:r});return this.adapter.getBalance(s,c)}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),c=0n;return a&&(c=Ve.big.toBigInt(a,r)),K.AssetAmount.fromAsset(s,{amount:c,decimals:r})}async getDecimals(t){let{chain:e}=this.config,n=e.getAssetDecimals(t);return n||(await e.getCurrency()).decimals}};var{EvmAddr:Oe}=I.addr,ft=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,c=n.destinationFee.asset||s.fee.asset,i=await this.getDecimals(c);if(Number.isFinite(r))return{fee:I.AssetAmount.fromAsset(c,{amount:Zt.big.toBigInt(r,i),decimals:i}),feeBreakdown:{}};let m=r,{amount:l,breakdown:u}=await m.build({feeAsset:c,transferAsset:n.asset,source:a?a.chain:t,destination:s.chain});return{fee:I.AssetAmount.fromAsset(c,{amount:l,decimals:i}),feeBreakdown:u}}async getDestinationFeeBalance(t){let{chain:e,route:n}=this.config,{source:s,destination:a}=n,r=s.asset,c=s.destinationFee.asset||a.fee.asset;if(r.isEqual(c))return this.getBalance(t);let i=e.getBalanceAssetId(c),m=Oe.isValid(i.toString())?await j(t,e):t,l=s.destinationFee.balance.build({address:m,asset:c,chain:e});return this.adapter.getBalance(c,l)}async getFee(t){let{chain:e,route:n}=this.config,{amount:s,sender:a,source:r}=t,c=await this.getTransfer(t),i=n.contract?await j(a,e):a,m=await this.adapter.estimateFee(i,s,r.feeBalance,c),{fee:l}=n.source,u=l?Me(m.decimals,l.extra):0n,d=m.amount+u;return m.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),c=Oe.isValid(r.toString())?await j(t,e):t,i=s.fee.balance.build({address:c,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 c=a.asset;return e instanceof I.Parachain&&"build"in c?await c.build({chain:e,address:t}):c}async getTransfer(t){let{chain:e,route:n}=this.config,{contract:s,extrinsic:a,program:r,move:c}=n;if(a){let{address:m,amount:l,asset:u,sender:d}=t,f=await(await S.create(e)).buildMessageId(d,l,u.originSymbol,m);return a.build({...t,messageId:f})}let i=s||r||c;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),c=await(await S.create(n)).getExtrinsic(a),i=e.source.chain,m=e.sender,l=I.acc.getMultilocationDerivatedAccount(i.parachainId,m,n.parachainId===0?0:1,n.usesH160Acc),u=await c.getPaymentInfo(l),d=await c.getEncodedData(),[g,f]=await Promise.all([this.getTransactFee(t),this.getTransactFeeBalance(t,e)]);return{call:d,chain:n,fee:g,feeBalance:f,weight:{refTime:u.weight.ref_time,proofSize:u.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 pt=class extends Z{constructor(t,e){super(t,e)}};var _e=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:_e.AssetAmount.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:an}=D.addr,Ut=class{config;validations;constructor({configService:t,transferValidations:e}){this.config=t,this.validations=e||[]}registerDex(...t){t.forEach(e=>D.DexFactory.getInstance().register(e))}async transfer(t,e,n,s,a){let r=(0,D.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),c=this.config.getChain(n);if(!(r.isSubstrate()&&c.isSubstrate()))throw Error("RemoteXcm is supported only between parachains");let[m,l]=await Promise.all([S.create(r),S.create(c)]),u=new mt(m,l),d=D.acc.getMultilocationDerivatedAccount(r.parachainId,t,1,c.usesH160Acc),g=await l.getAsset(),f=await this.transfer(g,t,e,d,n);return u.remoteExec(t,d,s,p=>{let v=p.toDecimal(p.decimals);return f.buildCall(v)},a)}async getTransferData(t,e,n){let s=t.origin,a=t.reverse,r=new U(s.chain),c=new U(a.chain),i=new ft(r,s),m=new pt(c,a),l=new D.TransferValidator(...this.validations),[u,d,g,f,p,v,P]=await Promise.all([i.getBalance(e),i.getFeeBalance(e),i.getDestinationFee(),i.getDestinationFeeBalance(e),i.getMin(),m.getBalance(n),m.getMin()]),{source:x,destination:y}=s.route,B=g.fee.copyWith(y.fee.asset),L=g.feeBreakdown,C={address:n,amount:1n,asset:x.asset,destination:{balance:v,chain:a.chain,fee:B,feeBreakdown:L},sender:e,source:{balance:u,chain:s.chain,fee:d.copyWith({amount:0n}),feeBalance:d,destinationFee:g.fee,destinationFeeBalance:f}};C.transact=await i.getTransact(C);let T=new tt(C),h=await i.getFee(C),M;T.isSwapSupported(x.fee)&&(M=await T.getSwap(h),C.source.feeSwap=M);let V;T.isDestinationSwapSupported(h)&&(V=await T.getDestinationSwap(h),C.source.destinationFeeSwap=V),(M||V)&&(h=await i.getFee(C),h=h.padByPct(5n));let Lt=await m.getEd(),zt=ke(v,B,P,Lt),yt=await i.getEd(),Ht=Re(u,h,p,yt);return C.amount=0n,C.source.fee=h,{source:{balance:u,destinationFee:g.fee,destinationFeeBalance:f,destinationFeeSwap:V,fee:h,feeBalance:d,feeSwap:M,max:Ht,min:u.copyWith({amount:zt.amount})},destination:{balance:v,fee:B},async buildCall(b){let w=Object.assign({},C);return w.amount=te.big.toBigInt(b,u.decimals),w.transact=await i.getTransact(w),i.getCall(w)},async estimateFee(b){let w=Object.assign({},C);return w.amount=te.big.toBigInt(b,u.decimals),w.transact=await i.getTransact(w),i.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 U(s.chain),r=s.getUniqueRoutes().map(async({source:m})=>{let{asset:l,balance:u}=m,d=s.chain.getBalanceAssetId(l),g=an.isValid(d.toString())?await j(t,s.chain):t,f=u.build({address:g,asset:l,chain:s.chain});return a.subscribeBalance(l,f)}),c=await Promise.all(r);return(0,jt.combineLatest)(c).pipe((0,jt.debounceTime)(500)).subscribe(n)}};var Ne=require("@galacticcouncil/xc-core");function We(o){let t=(0,Ne.ConfigBuilder)(o.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:c,build:i}=a.destination(r);return{routes:c,build({srcAddress:m,dstAddress:l,dstAsset:u}){let d=i(u);return o.getTransferData(d,m,l)}}}}}}}}}var Ue=require("@galacticcouncil/xc-core"),rn="https://api.wormholescan.io",ht=class{_baseUrl;constructor(t){this._baseUrl=t||rn}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===Ue.Precompile.Bridge}};var A=require("@galacticcouncil/xc-core"),je=require("@wormhole-foundation/sdk-base"),Le=require("@wormhole-foundation/sdk-connect"),ze=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 on=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:c,standarizedProperties:i}=r,m=this.getStatus(a),l=this.chains.find(p=>p instanceof A.Parachain&&p.parachainId===this.parachainId),{toAddress:u,tokenAddress:d}=i,g=this.chains.find(p=>A.Wormhole.isKnown(p)&&A.Wormhole.fromChain(p).getWormholeId()===c.tokenChain),f;if(m===1&&a.vaa){let{timestamp:p}=this.getVaaHeader(a.vaa.raw),v=a.vaa.raw;if(this.isStuck(p))switch(g.getType()){case A.ChainType.EvmChain:let P=new et(g);f=async y=>P.redeem(y,v);break;case A.ChainType.SolanaChain:let x=new ct(g);f=async y=>x.redeem(y,v);break}}return{asset:d,assetSymbol:a.data.symbol,amount:a.data.tokenAmount,from:t,fromChain:l,to:u,toChain:g,status:m,redeem:f,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,c=(await A.mrl.createPayload(a,t)).toHex(),i=n.filter(m=>{let{content:l}=m,{payload:u}=l;return u.payloadType===3&&u.toChain===16&&"0x"+u.payload===c}).map(async m=>{let{content:l,sourceChain:u}=m,{payload:d,standarizedProperties:g}=l,f=this.getStatus(m),{tokenAddress:p}=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(f===1&&m.vaa){let{timestamp:y}=this.getVaaHeader(m.vaa.raw),B=m.vaa.raw;if(this.isStuck(y)){let L=new ut(P);x=async C=>L.redeemMrlViaXcm(C,B)}}return{asset:p,assetSymbol:m.data.symbol,amount:m.data.tokenAmount,from:u.from,fromChain:v,to:t,toChain:s,status:f,redeem:x,operation:m}});return Promise.all(i)}isStuck(t){return Date.now()>=t*1e3+on}getVaaHeader(t){let e=je.encoding.b64.decode(t),n=(0,ze.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,Le.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(),o=await this.getNonce(t);try{let{results:i}=await r.simulateCalls({account:t,calls:[{to:e,abi:this.abi,functionName:a,args:n,value:s}],stateOverrides:[{address:t,nonce:o}]}),[
|
|
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 Fn,addr as In,ConfigBuilder as Dn,DexFactory as Rn,TransferValidator as kn}from"@galacticcouncil/xc-core";import{combineLatest as Mn,debounceTime as Vn}from"rxjs";import{ChainType as U}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,o=ue({abi:r,functionName:"completeTransfer",args:["0x"+a]});return{abi:JSON.stringify(r),data:o,from:t,to:n.getTokenBridge()}}};import{Abi as fe,AssetAmount as pe,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(),o=await this.getNonce(t);try{let{results:i}=await r.simulateCalls({account:t,calls:[{to:e,abi:this.abi,functionName:a,args:n,value:s}],stateOverrides:[{address:t,nonce:o}]}),[m]=i;return m}catch(i){return console.log(`Can't simulate call!
|
|
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 N=class{static get(t,e){return new G(t,e)}};import{Precompile as ge}from"@galacticcouncil/xc-core";function Tt(u){let t=u.module==="Snowbridge"&&u.func==="sendToken"&&u.args[0]==="0x0000000000000000000000000000000000000000";return u.module==="TokenBridge"&&["wrapAndTransferETHWithPayload","wrapAndTransferETH"].includes(u.func)||t}function Et(u){return Object.entries(ge).map(([e,n])=>n).includes(u.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:o,calldata:i}=a,m={abi:JSON.stringify(r),data:i,from:t,to:s.address,type:Ft.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(Et(s)||Tt(s))return m;let l=new he(this.#t,o),c=await l.allowance(t,s.address);if(c>=e)return m;let d=l.approve(s.address,e);return{abi:JSON.stringify(fe.Erc20),allowance:c,data:d,from:t,to:o,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 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 m=a.watchBlocks({onBlock:()=>i()});return()=>m()},o;return r().then(i=>o=i),s.pipe(Ce(()=>o?.()),ye((i,m)=>i.amount===m.amount))}};import{AssetAmount as Te,CallType as Ee}from"@galacticcouncil/xc-core";import{PublicKey as Fe}from"@solana/web3.js";import{Buffer as Ie}from"buffer";import{distinctUntilChanged as De,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 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:o})=>{let i=o.data.parsed.info.tokenAmount;return r+=BigInt(i.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 It,PublicKey as xe,TransactionMessage as Se,VersionedTransaction as Dt}from"@solana/web3.js";var Rt=.5,kt=2,Mt=1,Vt=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=Mt,a=Vt){let[r,o]=await Promise.all([this.determineComputeBudget(t),this.determinePriorityFee(t,e,n,s,a)]);return[It.setComputeUnitLimit({units:r}),It.setComputeUnitPrice({microLamports:o})]}async simulateTransaction(t,e){let n=new Dt(e);return(await this.connection.simulateTransaction(n,{accounts:{encoding:"base64",addresses:[t]}})).value}async determineComputeBudget(t){let e=new Dt(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=Mt,a=Vt){let r=s,o=await this.getTxAccounts(t),i=await this.connection.getRecentPrioritizationFees({lockedWritableAccounts:o});if(i){let m=i.map(c=>c.prioritizationFee).filter(c=>c>0).sort((c,d)=>c-d),l=Math.ceil(m.length*e);if(m.length>l){let d=m[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 M(u){return u.map(t=>({program:t.programId.toBase58(),data:t.data.toString("hex"),keys:t.keys.map(e=>e.pubkey.toBase58())}))}function Ot(u,t=1e3){let e=[],n=[],s=0;for(let a of u){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(u){let t=u.serialize();return Buffer.from(t).toString("hex")}function pa(u){let t=Buffer.from(u,"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),o=r.serialize(),i=Ie.from(o).toString("hex");return{from:t,data:i,ix:M(s.instructions),signers:s.signers,type:Ee.Solana,dryRun:async()=>{let{err:m,logs:l}=await a.simulateTransaction(t,r);return{call:s.module+"."+s.func,error:m,events:l}}}}async estimateFee(t,e,n,s){let a=W.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 c=s.module==="TokenBridge"&&s.func==="TransferNativeWithPayload";return n.copyWith({amount:n.amount-BigInt(l)-(c?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 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),m=this.#t.onAccountChange(i,()=>o());return()=>{this.#t.removeAccountChangeListener(m)}},r;return a().then(o=>r=o),s.pipe(Re(()=>r?.()),De((o,i)=>o.amount===i.amount))}};import{CallType as bt,Wormhole as Ve}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 Ue}from"@wormhole-foundation/sdk-base";import{deserialize as Wt}from"@wormhole-foundation/sdk-definitions";import{createCompleteTransferNativeInstruction as je,createCompleteTransferWrappedInstruction as Le}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=Ve.fromChain(this.#t),s=Ue.b64.decode(e),a=Wt("TokenBridge:Transfer",s),r=Wt("Uint8Array",s),o=this.derivePostedVaaKey(n.getCoreBridge(),Buffer.from(a.hash)),i=new _t(t),m=[];if(!await this.#e.getAccountInfo(o)){let S=Oe.generate(),w=await Nt.createVerifySignaturesInstructions(this.#t.connection,n.getCoreBridge(),i,r,S.publicKey),y=Ot(w,1e3);for(let B=0;B<y.length;B++){let h=y[B],T=await this.getV0Message(i,h),E=nt(T);m.push({from:t,data:E,ix:M(h),signers:[S],type:bt.Solana})}let P=Nt.createPostVaaInstruction(this.#e,n.getCoreBridge(),i,r,S.publicKey),I=await this.getV0Message(i,[P]),C=nt(I);m.push({from:t,data:C,ix:M([P]),type:bt.Solana})}let d=(a.payload.token.chain==="Solana"?je:Le)(this.#e,n.getTokenBridge(),n.getCoreBridge(),i,a),g=await this.#n.getTipAccount(),f=_e.transfer({fromPubkey:i,toPubkey:new _t(g[0]),lamports:1e3}),p=await this.getV0Message(i,[d,f]),A=nt(p);return m.push({from:t,data:A,ix:M([d]),type:bt.Solana}),m}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 Ut}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=Ut.b64.decode(e),s=Ut.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(u,t,e){let n=await e.getDecimals(),s=e.chain.getAssetDecimals(t)??n,a=e.chain.usesChainDecimals?n:s;return{amount:Xe.convertDecimals(u,a,s),decimals:s}}import{enums as $e}from"@galacticcouncil/common";var jt=u=>{let t=[];for(let e of u)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=u=>{let t=u.value.error;return t.type==="Module"?$e.enumPath(t.value):JSON.stringify(t.value)};import{xcm as vt}from"@galacticcouncil/common";function Ge(u){return{parents:0,interior:{type:"X1",value:[u.startsWith("0x")?vt.toAccountKey20(u):vt.toAccountId32(u)]}}}function zt(u){return{type:"V4",value:{parents:1,interior:{type:"X1",value:[{type:"Parachain",value:u.parachainId}]}}}}var Lt=(u,t)=>({id:vt.transform(u),fun:{type:"Fungible",value:t}}),Ht=(u,t,e,n,s,a)=>{console.log(a);let r=Ge(u);return{type:"V4",value:[{type:"WithdrawAsset",value:Lt(t,e.amount)},{type:"BuyExecution",value:{fees:Lt(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,o=await this.#t.getAsset(),i=this.#e.api,m=this.#e.chain,l=await m.getCurrency(),c=l.asset,d=l.decimals,g=m.getAssetXcmLocation(c),f=wt.fromHex(n.data),A=await(await i.txFromCallData(f)).getPaymentInfo(e),S=BigInt(A.partial_fee)*120n/100n,w=Je.fromAsset(c,{amount:S,decimals:d}),y=A.weight.ref_time,P=A.weight.proof_size,I=zt(m),C=Ht(e,g,w,y,P,f),B=r.tx.PolkadotXcm.send({dest:I,message:C}),h=[];try{let b=await this.#t.chain.dex.getCalldata(t,a.srcFeeAsset||o,c,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),ft=await r.txFromCallData(E);h.push(ft),h.push(B);let pt=h.map(b=>b.decodedCall),Q=r.tx.Utility.batch_all({calls:pt}),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:V(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 rn,AssetAmount as Xt,CallType 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 xt,AssetAmount as en}from"@galacticcouncil/xc-core";import{Blake2256 as nn,u32 as sn}from"@polkadot-api/substrate-bindings";import{toHex as an,fromHex as Qt}from"@polkadot-api/utils";import{Enum as Kt}from"polkadot-api";var{Ss58Addr:qt}=tn,x=class u{chain;_currency;constructor(t){this.chain=t}static async create(t){return new u(t)}get client(){return this.chain.client}get api(){return this.client.getUnsafeApi()}async getCurrency(){return this._currency||(this._currency=this.chain.getCurrency()),this._currency}async getAsset(){return(await this.getCurrency()).asset}async getDecimals(){return(await this.getCurrency()).decimals}async getExistentialDeposit(){let t;try{let 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 getExtrinsic(t){let e=this.api.tx[t.module][t.func],n=await t.getArgs(e);if(Array.isArray(n)&&t.func==="batch_all"){let a=n.map(async({module:i,func:m,getArgs:l})=>{let c=this.api.tx[i][m],d=await l(c);return c(d)}),o=(await Promise.all(a)).map(i=>i.decodedCall);return e({calls:o})}return e(n)}async buildMessageId(t,e,n,s){let a=await this.client._request("system_accountNextIndex",[t]),r=sn.enc(a),o=l=>new TextEncoder().encode(l),i=new Uint8Array([...o(this.chain.parachainId.toString()),...Qt(t.startsWith("0x")?t.slice(2):t),...r,...Qt(n.startsWith("0x")?n.slice(2):n),...o(s),...o(e.toString())]),m=nn(i);return an(m)}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");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=await this.getExtrinsic(e),a=await this.dryRun(n,s);if(a.execution_result?.success)return jt(a.emitted_events||[]);{let r=V(a.execution_result);console.warn(`Can't estimate delivery fee. Reason:
|
|
4
|
+
${r}`)}}catch{}}return 0n}async estimateDeliveryFeeWith(t,e){if(["PolkadotXcm"].includes(e.module)){let n=await e.getArgs(),s="dest"in n?n.dest:void 0;if(!s)return t;let a=xt.findNestedKey(s,"interior"),r=xt.findParachain(s);if(xt.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 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,o=await this.useSignerFee(n)?{asset:new rn(n)}:void 0,i=await a.getExtrinsic(s),m=s.module+"."+s.func,l=await i.getEncodedData();return{from:t,data:l.asHex(),type:on.Substrate,txOptions:o,dryRun:a.isDryRunSupported()?async()=>{try{let c=await a.getExtrinsic(s),d=await a.dryRun(t,c),g=d.execution_result&&d.execution_result.success?void 0:V(d.execution_result);return{call:m,error:g,events:d.emitted_events||[],xcm:d.forwarded_xcms||[]}}catch(c){return{call:m,error:c instanceof Error?c.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),m=await At(i,n,a);return n.copyWith(m)}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;return n.client.getUnsafeApi().query[s][a].watchValue(...r).pipe($t(l=>o(l)),cn((l,c)=>l===c),$t(async l=>{let c=await At(l,t,n);return Xt.fromAsset(t,c)}))}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=Xt.fromAsset(s,{amount:t,decimals:a});return(await r.getQuote(e,s,o,!0)).amount}catch{}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 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 mn}from"@mysten/sui/utils";var ln=9,mt=class extends ut{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 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 dn}from"@mysten/bcs";function Gt(u,t={}){let e=u.inputs??[],n=u.commands??[],s=t.numbers??"string",a=t.decode32As??"address",r=l=>s==="bigint"?l:s==="number"?Number(l):l.toString(),o=l=>{let c=dn(l),d=g=>{let f=0n;for(let p=0;p<g;p++)f|=BigInt(c[p])<<8n*BigInt(p);return f};return c.length===1?{type:"pure",valueType:"u8",value:Number(c[0])}:c.length===2?{type:"pure",valueType:"u16",value:r(d(2))}:c.length===4?{type:"pure",valueType:"u32",value:Number(d(4))}:c.length===8?{type:"pure",valueType:"u64",value:r(d(8))}:c.length===32&&a==="address"?{type:"pure",valueType:"address",value:"0x"+[...c].map(f=>f.toString(16).padStart(2,"0")).join("")}:{type:"pure",valueType:"vector<u8>",value:Array.from(c)}},i=l=>{let c=e[l];if(!c)return{Input:l};if(c.Pure?.bytes)return o(c.Pure.bytes);let d=c.Object?.SharedObject;if(d)return{type:"object",objectType:"sharedObject",objectId:d.objectId,initialSharedVersion:String(d.initialSharedVersion),mutable:!!d.mutable};let g=c.Object?.ImmOrOwnedObject;return g?{type:"object",objectType:"immOrOwnedObject",objectId:g.objectId,version:String(g.version),digest:g.digest??void 0}:{Input:l}},m=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 c=l.MoveCall;return{MoveCall:{...c,arguments:(c.arguments??[]).map(m)}}}if(l.SplitCoins){let c=l.SplitCoins,d=c.coin?.GasCoin?"GasCoin":m(c.coin),g=(c.amounts??[]).map(m);return{SplitCoins:[d,g]}}if(l.MergeCoins){let c=l.MergeCoins;return{MergeCoins:{...c,destination:m(c.destination),sources:(c.sources??[]).map(m)}}}if(l.TransferObjects){let c=l.TransferObjects;return{TransferObjects:{...c,objects:(c.objects??[]).map(m),address:m(c.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}),o=await a.toJSON(),i=Gt(JSON.parse(o));return{from:t,commands:i,data:pn(r),type:fn.Sui,dryRun:async()=>{let m=await this.#t.dryRunTransactionBlock({transactionBlock:r});return{call:s.module+"."+s.func,error:m.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,m=BigInt(i.computationCost),l=BigInt(i.storageCost),c=BigInt(i.storageRebate),d=m+l-c;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 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 m=await this.getBalance(t,e);n.next(m)})();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 D=class{platform={};constructor(t){switch(t.getType()){case U.EvmChain:this.registerEvm(t);break;case U.EvmParachain:this.registerEvm(t),this.registerSubstrate(t);break;case U.Parachain:this.registerSubstrate(t);break;case U.SolanaChain:this.registerSolana(t);break;case U.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 Pn,addr as Bn,AssetAmount as St,Parachain as Tn}from"@galacticcouncil/xc-core";import{big as ee}from"@galacticcouncil/common";import{big as An}from"@galacticcouncil/common";import j from"big.js";function Jt(u,t,e,n){let s=u.toBig().minus(e.toBig()).minus(u.isSame(t)?t.toBig():new j(0));return n&&(s=s.minus(u.isSame(n)?n.toBig():new j(0))),u.copyWith({amount:s.lt(0)?0n:BigInt(s.toFixed())})}function Yt(u,t,e,n){let a=u.copyWith({amount:0n}).toBig().plus(u.isSame(t)?t.toBig():new j(0)).plus(u.toBig().lt(e.toBig())?e.toBig():new j(0));return n&&(a=a.plus(u.isSame(n)&&u.toBig().lt(n.toBig())?n.toBig():new j(0))),u.copyWith({amount:BigInt(a.toFixed())})}async function F(u,t){return t.isEvmParachain()?t.getDerivatedAddress(u):u}function Zt(u,t){return t?An.toBigInt(t,u):0n}import{addr as vn,AssetAmount as wn,Parachain as te}from"@galacticcouncil/xc-core";import{big as xn}from"@galacticcouncil/common";var{EvmAddr:Sn}=vn,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),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 te&&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)),wn.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:ne}=Bn,L=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:St.fromAsset(o,{amount:ee.toBigInt(r,i),decimals:i}),feeBreakdown:{}};let m=r,{amount:l,breakdown:c}=await m.build({feeAsset:o,transferAsset:n.asset,source:a?a.chain:t,destination:s.chain});return{fee:St.fromAsset(o,{amount:l,decimals:i}),feeBreakdown:c}}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),m=ne.isValid(i.toString())?await F(t,e):t,l=s.destinationFee.balance.build({address:m,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,m=await this.adapter.estimateFee(i,s,r.feeBalance,o),{fee:l}=n.source,c=l?Zt(m.decimals,l.extra):0n,d=m.amount+c;return m.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=ne.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:m,amount:l,asset:c,sender:d}=t,f=await(await x.create(e)).buildMessageId(d,l,c.originSymbol,m);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,m=e.sender,l=Pn.getMultilocationDerivatedAccount(i.parachainId,m,n.parachainId===0?0:1,n.usesH160Acc),c=await o.getPaymentInfo(l),d=await o.getEncodedData(),[g,f]=await Promise.all([this.getTransactFee(t),this.getTransactFeeBalance(t,e)]);return{call:d,chain:n,fee:g,feeBalance:f,weight:{refTime:c.weight.ref_time,proofSize:c.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 En}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: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:On}=In,Pt=class{config;validations;constructor({configService:t,transferValidations:e}){this.config=t,this.validations=e||[]}registerDex(...t){t.forEach(e=>Rn.getInstance().register(e))}async transfer(t,e,n,s,a){let r=Dn(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[m,l]=await Promise.all([x.create(r),x.create(o)]),c=new ot(m,l),d=Fn.getMultilocationDerivatedAccount(r.parachainId,t,1,o.usesH160Acc),g=await l.getAsset(),f=await this.transfer(g,t,e,d,n);return c.remoteExec(t,d,s,p=>{let A=p.toDecimal(p.decimals);return f.buildCall(A)},a)}async getTransferData(t,e,n){let s=t.origin,a=t.reverse,r=new D(s.chain),o=new D(a.chain),i=new L(r,s),m=new z(o,a),l=new kn(...this.validations),[c,d,g,f,p,A,S]=await Promise.all([i.getBalance(e),i.getFeeBalance(e),i.getDestinationFee(),i.getDestinationFeeBalance(e),i.getMin(),m.getBalance(n),m.getMin()]),{source:w,destination:y}=s.route,P=g.fee.copyWith(y.fee.asset),I=g.feeBreakdown,C={address:n,amount:1n,asset:w.asset,destination:{balance:A,chain:a.chain,fee:P,feeBreakdown:I},sender:e,source:{balance:c,chain:s.chain,fee:d.copyWith({amount:0n}),feeBalance:d,destinationFee:g.fee,destinationFeeBalance:f}};C.transact=await i.getTransact(C);let B=new H(C),h=await i.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 i.getFee(C),h=h.padByPct(5n));let ft=await m.getEd(),pt=Yt(A,P,S,ft),Q=await i.getEd(),ht=Jt(c,h,p,Q);return C.amount=0n,C.source.fee=h,{source:{balance:c,destinationFee:g.fee,destinationFeeBalance:f,destinationFeeSwap:E,fee:h,feeBalance:d,feeSwap:T,max:ht,min:c.copyWith({amount:pt.amount})},destination:{balance:A,fee:P},async buildCall(b){let v=Object.assign({},C);return v.amount=se.toBigInt(b,c.decimals),v.transact=await i.getTransact(v),i.getCall(v)},async estimateFee(b){let v=Object.assign({},C);return v.amount=se.toBigInt(b,c.decimals),v.transact=await i.getTransact(v),i.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 D(s.chain),r=s.getUniqueRoutes().map(async({source:m})=>{let{asset:l,balance:c}=m,d=s.chain.getBalanceAssetId(l),g=On.isValid(d.toString())?await F(t,s.chain):t,f=c.build({address:g,asset:l,chain:s.chain});return a.subscribeBalance(l,f)}),o=await Promise.all(r);return Mn(o).pipe(Vn(500)).subscribe(n)}};import{ConfigBuilder as _n}from"@galacticcouncil/xc-core";function Nn(u){let t=_n(u.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:m,dstAddress:l,dstAsset:c}){let d=i(c);return u.getTransferData(d,m,l)}}}}}}}}}import{Precompile as Wn}from"@galacticcouncil/xc-core";var Un="https://api.wormholescan.io",gt=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===Wn.Bridge}};import{acc as jn,mrl as Ln,ChainType as re,Parachain as zn,Precompile as Hn,Wormhole as _}from"@galacticcouncil/xc-core";import{encoding as Qn}from"@wormhole-foundation/sdk-base";import{keccak256 as Kn}from"@wormhole-foundation/sdk-connect";import{deserialize as qn}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 Xn=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=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,m=this.getStatus(a),l=this.chains.find(p=>p instanceof zn&&p.parachainId===this.parachainId),{toAddress:c,tokenAddress:d}=i,g=this.chains.find(p=>_.isKnown(p)&&_.fromChain(p).getWormholeId()===o.tokenChain),f;if(m===1&&a.vaa){let{timestamp:p}=this.getVaaHeader(a.vaa.raw),A=a.vaa.raw;if(this.isStuck(p))switch(g.getType()){case re.EvmChain:let S=new K(g);f=async y=>S.redeem(y,A);break;case re.SolanaChain:let w=new rt(g);f=async y=>w.redeem(y,A);break}}return{asset:d,assetSymbol:a.data.symbol,amount:a.data.tokenAmount,from:t,fromChain:l,to:c,toChain:g,status:m,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 Ln.createPayload(a,t)).toHex(),i=n.filter(m=>{let{content:l}=m,{payload:c}=l;return c.payloadType===3&&c.toChain===16&&"0x"+c.payload===o}).map(async m=>{let{content:l,sourceChain:c}=m,{payload:d,standarizedProperties:g}=l,f=this.getStatus(m),{tokenAddress:p}=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(f===1&&m.vaa){let{timestamp:y}=this.getVaaHeader(m.vaa.raw),P=m.vaa.raw;if(this.isStuck(y)){let I=new it(S);w=async C=>I.redeemMrlViaXcm(C,P)}}return{asset:p,assetSymbol:m.data.symbol,amount:m.data.tokenAmount,from:c.from,fromChain:A,to:t,toChain:s,status:f,redeem:w,operation:m}});return Promise.all(i)}isStuck(t){return Date.now()>=t*1e3+Xn}getVaaHeader(t){let e=Qn.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{K as EvmClaim,J as EvmPlatform,H as FeeSwap,D 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,Nn as TransferBuilder,Pt as Wallet,ae as WhStatus,gt as WormholeScan,ie as WormholeTransfer,Ot as chunkBySize,pa as deserializeV0,M 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,31 +1,20 @@
|
|
|
1
|
-
import { AnyParachain, Asset, AssetAmount, ExtrinsicConfig } from '@galacticcouncil/xc-core';
|
|
2
|
-
import {
|
|
1
|
+
import { AnyParachain, Asset, AssetAmount, ExtrinsicConfig, ChainCurrency } from '@galacticcouncil/xc-core';
|
|
2
|
+
import { UnsafeTransaction } from 'polkadot-api';
|
|
3
3
|
export declare class SubstrateService {
|
|
4
|
-
readonly client: PolkadotClient;
|
|
5
|
-
readonly api: ReturnType<PolkadotClient['getUnsafeApi']>;
|
|
6
4
|
readonly chain: AnyParachain;
|
|
7
|
-
private
|
|
8
|
-
|
|
9
|
-
private _decimals?;
|
|
10
|
-
constructor(client: PolkadotClient, chain: AnyParachain);
|
|
5
|
+
private _currency?;
|
|
6
|
+
constructor(chain: AnyParachain);
|
|
11
7
|
static create(chain: AnyParachain): Promise<SubstrateService>;
|
|
12
|
-
|
|
8
|
+
get client(): import("polkadot-api").PolkadotClient;
|
|
9
|
+
get api(): import("polkadot-api").UnsafeApi<unknown>;
|
|
10
|
+
getCurrency(): Promise<ChainCurrency>;
|
|
13
11
|
getAsset(): Promise<Asset>;
|
|
14
12
|
getDecimals(): Promise<number>;
|
|
15
13
|
getExistentialDeposit(): Promise<AssetAmount>;
|
|
16
14
|
isDryRunSupported(): boolean;
|
|
17
|
-
|
|
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;
|
|
15
|
+
getExtrinsic(config: ExtrinsicConfig): Promise<UnsafeTransaction<any, any, any, any>>;
|
|
27
16
|
buildMessageId(account: string, amount: bigint, asset: string, beneficiary: string): Promise<string>;
|
|
28
|
-
dryRun(account: string,
|
|
17
|
+
dryRun(account: string, tx: UnsafeTransaction<any, any, any, any>): Promise<any>;
|
|
29
18
|
estimateNetworkFee(account: string, config: ExtrinsicConfig): Promise<bigint>;
|
|
30
19
|
estimateDeliveryFee(account: string, config: ExtrinsicConfig): Promise<bigint>;
|
|
31
20
|
private estimateDeliveryFeeWith;
|
|
@@ -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.2.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.2.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;
|