@galacticcouncil/xc-sdk 0.1.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/README.md +114 -0
- package/build/index.cjs +4 -0
- package/build/index.mjs +4 -0
- package/build/types/FeeSwap.d.ts +47 -0
- package/build/types/Wallet.d.ts +20 -0
- package/build/types/Wallet.utils.d.ts +47 -0
- package/build/types/clients/WormholeScan.d.ts +87 -0
- package/build/types/clients/WormholeTransfer.d.ts +16 -0
- package/build/types/clients/index.d.ts +3 -0
- package/build/types/clients/types.d.ts +20 -0
- package/build/types/index.d.ts +6 -0
- package/build/types/platforms/adapter.d.ts +15 -0
- package/build/types/platforms/evm/EvmClaim.d.ts +7 -0
- package/build/types/platforms/evm/EvmPlatform.d.ts +12 -0
- package/build/types/platforms/evm/balance/Erc20.d.ts +8 -0
- package/build/types/platforms/evm/balance/EvmBalance.d.ts +10 -0
- package/build/types/platforms/evm/balance/EvmBalanceFactory.d.ts +5 -0
- package/build/types/platforms/evm/balance/Native.d.ts +5 -0
- package/build/types/platforms/evm/balance/index.d.ts +2 -0
- package/build/types/platforms/evm/index.d.ts +3 -0
- package/build/types/platforms/evm/transfer/EvmTransfer.d.ts +23 -0
- package/build/types/platforms/evm/transfer/EvmTransferFactory.d.ts +5 -0
- package/build/types/platforms/evm/transfer/index.d.ts +2 -0
- package/build/types/platforms/evm/transfer/utils.d.ts +3 -0
- package/build/types/platforms/evm/types.d.ts +19 -0
- package/build/types/platforms/index.d.ts +6 -0
- package/build/types/platforms/solana/SolanaClaim.d.ts +9 -0
- package/build/types/platforms/solana/SolanaLilJit.d.ts +54 -0
- package/build/types/platforms/solana/SolanaPlatform.d.ts +12 -0
- package/build/types/platforms/solana/balance/Native.d.ts +5 -0
- package/build/types/platforms/solana/balance/SolanaBalance.d.ts +11 -0
- package/build/types/platforms/solana/balance/SolanaBalanceFactory.d.ts +6 -0
- package/build/types/platforms/solana/balance/Token.d.ts +9 -0
- package/build/types/platforms/solana/balance/index.d.ts +2 -0
- package/build/types/platforms/solana/index.d.ts +5 -0
- package/build/types/platforms/solana/transfer/SolanaTransfer.d.ts +33 -0
- package/build/types/platforms/solana/transfer/SolanaTransferFactory.d.ts +6 -0
- package/build/types/platforms/solana/transfer/index.d.ts +2 -0
- package/build/types/platforms/solana/types.d.ts +15 -0
- package/build/types/platforms/solana/utils.d.ts +6 -0
- package/build/types/platforms/substrate/SubstrateClaim.d.ts +9 -0
- package/build/types/platforms/substrate/SubstrateExec.d.ts +11 -0
- package/build/types/platforms/substrate/SubstratePlatform.d.ts +23 -0
- package/build/types/platforms/substrate/SubstrateService.d.ts +32 -0
- package/build/types/platforms/substrate/index.d.ts +5 -0
- package/build/types/platforms/substrate/types.d.ts +12 -0
- package/build/types/platforms/substrate/utils/amount.d.ts +12 -0
- package/build/types/platforms/substrate/utils/dryRun.d.ts +2 -0
- package/build/types/platforms/substrate/utils/index.d.ts +4 -0
- package/build/types/platforms/substrate/utils/naming.d.ts +24 -0
- package/build/types/platforms/substrate/utils/xcm.d.ts +110 -0
- package/build/types/platforms/sui/SuiPlatform.d.ts +12 -0
- package/build/types/platforms/sui/balance/Native.d.ts +5 -0
- package/build/types/platforms/sui/balance/SuiBalance.d.ts +11 -0
- package/build/types/platforms/sui/balance/SuiBalanceFactory.d.ts +6 -0
- package/build/types/platforms/sui/balance/index.d.ts +2 -0
- package/build/types/platforms/sui/index.d.ts +2 -0
- package/build/types/platforms/sui/types.d.ts +4 -0
- package/build/types/platforms/sui/utils.d.ts +10 -0
- package/build/types/platforms/types.d.ts +25 -0
- package/build/types/transfer/DataOriginProcessor.d.ts +42 -0
- package/build/types/transfer/DataProcessor.d.ts +12 -0
- package/build/types/transfer/DataReverseProcessor.d.ts +6 -0
- package/build/types/transfer/index.d.ts +3 -0
- package/build/types/transfer/utils.d.ts +41 -0
- package/build/types/types.d.ts +51 -0
- package/package.json +38 -0
package/README.md
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# Galactic XC SDK
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@galacticcouncil/xc-sdk)
|
|
4
|
+
|
|
5
|
+
Wallet interface for asset multi-platform transfer supporting fee swaps & bridging.
|
|
6
|
+
|
|
7
|
+
Wallet does not perform any signing rather provide transfer data to maintain loose coupling & interoperability with 3rd party code.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
Install with [npm](https://www.npmjs.com/):
|
|
12
|
+
|
|
13
|
+
`npm install @galacticcouncil/xc-sdk`
|
|
14
|
+
|
|
15
|
+
## API
|
|
16
|
+
|
|
17
|
+
```typescript
|
|
18
|
+
transfer(
|
|
19
|
+
asset: string | Asset,
|
|
20
|
+
srcAddr: string,
|
|
21
|
+
srcChain: string | AnyChain,
|
|
22
|
+
dstAddr: string,
|
|
23
|
+
dstChain: string | AnyChain
|
|
24
|
+
): Promise<Transfer>
|
|
25
|
+
subscribeBalance(
|
|
26
|
+
address: string,
|
|
27
|
+
chain: string | AnyChain,
|
|
28
|
+
observer: (balances: AssetAmount[]) => void
|
|
29
|
+
)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Usage
|
|
33
|
+
|
|
34
|
+
```typescript
|
|
35
|
+
// Import
|
|
36
|
+
import {
|
|
37
|
+
assetsMap,
|
|
38
|
+
chainsMap,
|
|
39
|
+
routesMap,
|
|
40
|
+
dex,
|
|
41
|
+
validations,
|
|
42
|
+
} from '@galacticcouncil/xc-cfg';
|
|
43
|
+
import { ConfigService, EvmParachain } from '@galacticcouncil/xc-core';
|
|
44
|
+
import { Wallet, Call } from '@galacticcouncil/xc-sdk';
|
|
45
|
+
|
|
46
|
+
// Initialize config service
|
|
47
|
+
const configService = new ConfigService({
|
|
48
|
+
assets: assetsMap,
|
|
49
|
+
chains: chainsMap,
|
|
50
|
+
routes: routesMap,
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// Initialize wallet
|
|
54
|
+
const wallet = new Wallet({
|
|
55
|
+
configService: configService,
|
|
56
|
+
transferValidations: validations,
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
// Register dex-es
|
|
60
|
+
const hydration = configService.getChain('hydration');
|
|
61
|
+
const assethub = configService.getChain('assethub');
|
|
62
|
+
|
|
63
|
+
wallet.registerDex(
|
|
64
|
+
new dex.HydrationDex(hydration),
|
|
65
|
+
new dex.AssethubDex(assethub)
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
// Define transfer
|
|
69
|
+
const srcChain = configService.getChain('ethereum');
|
|
70
|
+
const destChain = configService.getChain('hydration');
|
|
71
|
+
const asset = configService.getAsset('eth');
|
|
72
|
+
|
|
73
|
+
// Define source & dest accounts
|
|
74
|
+
const srcAddr = 'INSERT_ADDRESS';
|
|
75
|
+
const destAddr = 'INSERT_ADDRESS';
|
|
76
|
+
|
|
77
|
+
// Subscribe source chain token balance
|
|
78
|
+
const balanceObserver = (balances: AssetAmount[]) => console.log(balances);
|
|
79
|
+
const balanceSubscription = await wallet.subscribeBalance(
|
|
80
|
+
srcAddr,
|
|
81
|
+
srcChain,
|
|
82
|
+
balanceObserver
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
// Get transfer data
|
|
86
|
+
const transfer = await wallet.transfer(
|
|
87
|
+
asset,
|
|
88
|
+
srcAddr,
|
|
89
|
+
srcChain,
|
|
90
|
+
destAddr,
|
|
91
|
+
destChain
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
// Validate transfer
|
|
95
|
+
const status = await transfer.validate();
|
|
96
|
+
|
|
97
|
+
// Estimate fee & construct calldata with transfer amount (1 ETH)
|
|
98
|
+
const fee: AssetAmount = await transfer.estimateFee('1');
|
|
99
|
+
const feeInfo = [
|
|
100
|
+
'Estimated fee:',
|
|
101
|
+
fee.toDecimal(fee.decimals),
|
|
102
|
+
fee.originSymbol,
|
|
103
|
+
].join(' ');
|
|
104
|
+
const call: Call = await transfer.buildCall('1');
|
|
105
|
+
|
|
106
|
+
// Dump transfer info
|
|
107
|
+
console.log(transfer);
|
|
108
|
+
console.log(status);
|
|
109
|
+
console.log(feeInfo);
|
|
110
|
+
console.log(call);
|
|
111
|
+
|
|
112
|
+
// Unsubscribe source chain balance
|
|
113
|
+
balanceSubscription.unsubscribe();
|
|
114
|
+
```
|
package/build/index.cjs
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"use strict";var je=Object.create;var wt=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var He=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Ke=(i,t)=>{for(var e in t)wt(i,e,{get:t[e],enumerable:!0})},Zt=(i,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Qe(t))!$e.call(i,n)&&n!==e&&wt(i,n,{get:()=>t[n],enumerable:!(s=ze(t,n))||s.enumerable});return i};var qe=(i,t,e)=>(e=i!=null?je(He(i)):{},Zt(t||!i||!i.__esModule?wt(e,"default",{value:i,enumerable:!0}):e,i)),Xe=i=>Zt(wt({},"__esModule",{value:!0}),i);var rn={};Ke(rn,{EvmClaim:()=>st,EvmPlatform:()=>rt,FeeSwap:()=>et,PlatformAdapter:()=>U,SolanaClaim:()=>mt,SolanaLilJit:()=>ut,SolanaPlatform:()=>ct,SubstrateClaim:()=>lt,SubstrateExec:()=>gt,SubstratePlatform:()=>pt,SubstrateService:()=>S,SuiPlatform:()=>ht,TransferBuilder:()=>Me,Wallet:()=>Ut,WhStatus:()=>Jt,WormholeScan:()=>bt,WormholeTransfer:()=>Yt,chunkBySize:()=>Qt,deserializeV0:()=>Ye,ixToHuman:()=>Q,serializeV0:()=>ot});module.exports=Xe(rn);var I=require("@galacticcouncil/xc-core"),Gt=require("@galacticcouncil/common"),jt=require("rxjs");var Y=require("@galacticcouncil/xc-core");var vt=require("@galacticcouncil/xc-core"),te=require("viem"),zt=require("@wormhole-foundation/sdk-base"),st=class{#t;constructor(t){this.#t=t}redeem(t,e){let s=vt.Wormhole.fromChain(this.#t),n=zt.encoding.b64.decode(e),a=zt.encoding.hex.encode(n),r=vt.Abi.TokenBridge,c=(0,te.encodeFunctionData)({abi:r,functionName:"completeTransfer",args:["0x"+a]});return{abi:JSON.stringify(r),data:c,from:t,to:s.getTokenBridge()}}};var k=require("@galacticcouncil/xc-core"),_=require("rxjs");var K=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 ee=require("@galacticcouncil/xc-core");var xt=class extends K{erc20;constructor(t,e){super(t,e),this.erc20=new ee.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 St=class extends K{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 Pt=class{static get(t,e){switch(e.module){case"Erc20":return new xt(t,e);case"Native":return new St(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};var Tt=require("viem"),Bt=class{client;config;constructor(t,e){this.validateClient(t),this.client=t,this.config=e}validateClient(t){if(!t)throw new Error("No EVM client found")}get abi(){return this.config.abi}get asset(){let t=this.config.args,[e]=t;return e}get calldata(){return this.config.encodeFunctionData()}async estimateGas(t){let{address:e,args:s,value:n,func:a}=this.config;return await this.client.getProvider().estimateContractGas({address:e,abi:this.abi,functionName:a,args:s,value:n,account:t})}async estimateFee(t,e){if(e===0n)return 0n;try{let s=await this.estimateGas(t),n=await this.getGasPrice();return s*n}catch(s){return s instanceof Tt.ContractFunctionExecutionError?console.log(`Can't estimate fees!
|
|
2
|
+
`,s.message):console.log(s),0n}}async getGasPrice(){return this.client.getProvider().getGasPrice()}async getNonce(t){return this.client.getProvider().getTransactionCount({address:t})}async simulateCall(t){let{address:e,args:s,value:n,func:a}=this.config,r=this.client.getProvider(),c=await this.getNonce(t);try{let{results:o}=await r.simulateCalls({account:t,calls:[{to:e,abi:this.abi,functionName:a,args:s,value:n}],stateOverrides:[{address:t,nonce:c}]}),[u]=o;return u}catch(o){return console.log(`Can't simulate call!
|
|
3
|
+
`,o.details),{error:o}}}decodeEvents(t){let e=[];return t&&t.forEach(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});
|
package/build/index.mjs
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{acc as Dn,addr as In,ConfigBuilder as Rn,DexFactory as kn,TransferValidator as Mn}from"@galacticcouncil/xc-core";import{big as te}from"@galacticcouncil/common";import{combineLatest as Vn,debounceTime as On}from"rxjs";import{ChainType as j}from"@galacticcouncil/xc-core";import{Abi as oe,Wormhole as ce}from"@galacticcouncil/xc-core";import{encodeFunctionData as ue}from"viem";import{encoding as xt}from"@wormhole-foundation/sdk-base";var q=class{#t;constructor(t){this.#t=t}redeem(t,e){let n=ce.fromChain(this.#t),s=xt.b64.decode(e),a=xt.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 Bt,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 X=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 G=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 J=class{static get(t,e){switch(e.module){case"Erc20":return new X(t,e);case"Native":return new G(t,e);default:throw new Error("Module "+e.module+" is not supported")}}};import{ContractFunctionExecutionError as le,decodeEventLog as de}from"viem";var Y=class{client;config;constructor(t,e){this.validateClient(t),this.client=t,this.config=e}validateClient(t){if(!t)throw new Error("No EVM client found")}get abi(){return this.config.abi}get asset(){let t=this.config.args,[e]=t;return e}get calldata(){return this.config.encodeFunctionData()}async estimateGas(t){let{address:e,args: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}]}),[u]=i;return u}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 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};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { AssetAmount, FeeConfig, SwapCtx, TransferCtx } from '@galacticcouncil/xc-core';
|
|
2
|
+
export declare class FeeSwap {
|
|
3
|
+
readonly ctx: TransferCtx;
|
|
4
|
+
constructor(ctx: TransferCtx);
|
|
5
|
+
get asset(): AssetAmount;
|
|
6
|
+
get dex(): import("@galacticcouncil/xc-core").Dex | undefined;
|
|
7
|
+
get destFee(): AssetAmount;
|
|
8
|
+
get destFeeBalance(): AssetAmount;
|
|
9
|
+
get feeBalance(): AssetAmount;
|
|
10
|
+
/**
|
|
11
|
+
* Fee swap context
|
|
12
|
+
*
|
|
13
|
+
* @param fee - source chain fee
|
|
14
|
+
* @returns source fee swap context
|
|
15
|
+
*/
|
|
16
|
+
getSwap(fee: AssetAmount): Promise<SwapCtx | undefined>;
|
|
17
|
+
/**
|
|
18
|
+
* Swap source fee only if explicitly enabled in route
|
|
19
|
+
* fee config
|
|
20
|
+
*
|
|
21
|
+
* @param fee - source chain fee config
|
|
22
|
+
* @returns true if supported, otherwise false
|
|
23
|
+
*/
|
|
24
|
+
isSwapSupported(cfg?: FeeConfig): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Destination fee swap context
|
|
27
|
+
*
|
|
28
|
+
* Swap is enabled if following applies:
|
|
29
|
+
* - account has not enough destination fee balance
|
|
30
|
+
* - account has enough source fee reserves (double the fee) to buy required asset
|
|
31
|
+
*
|
|
32
|
+
* Note: Slippage can be set up to 100% in builder config (see maxAmountIn)
|
|
33
|
+
*
|
|
34
|
+
* @param fee - source chain fee
|
|
35
|
+
* @returns destination fee swap context
|
|
36
|
+
*/
|
|
37
|
+
getDestinationSwap(fee: AssetAmount): Promise<SwapCtx | undefined>;
|
|
38
|
+
/**
|
|
39
|
+
* Swap destination fee only if:
|
|
40
|
+
* - transfer asset insufficient
|
|
41
|
+
* - destination fee asset is different than fee asset
|
|
42
|
+
*
|
|
43
|
+
* @param fee - source chain fee
|
|
44
|
+
* @returns true if supported, otherwise false
|
|
45
|
+
*/
|
|
46
|
+
isDestinationSwapSupported(fee: AssetAmount): boolean;
|
|
47
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Asset, AnyChain, AnyParachain, AssetAmount, ConfigService, Dex, TransferConfigs, TransferValidation } from '@galacticcouncil/xc-core';
|
|
2
|
+
import { Subscription } from 'rxjs';
|
|
3
|
+
import { SubstrateCall } from './platforms';
|
|
4
|
+
import { Transfer } from './types';
|
|
5
|
+
export interface WalletOptions {
|
|
6
|
+
configService: ConfigService;
|
|
7
|
+
transferValidations?: TransferValidation[];
|
|
8
|
+
}
|
|
9
|
+
export declare class Wallet {
|
|
10
|
+
readonly config: ConfigService;
|
|
11
|
+
readonly validations: TransferValidation[];
|
|
12
|
+
constructor({ configService, transferValidations }: WalletOptions);
|
|
13
|
+
registerDex(...dex: Dex[]): void;
|
|
14
|
+
transfer(asset: string | Asset, srcAddress: string, srcChain: string | AnyChain, dstAddress: string, dstChain: string | AnyChain): Promise<Transfer>;
|
|
15
|
+
remoteXcm(srcAddress: string, srcChain: string | AnyParachain, dstChain: string | AnyParachain, dstCall: SubstrateCall, opts?: {
|
|
16
|
+
srcFeeAsset?: Asset;
|
|
17
|
+
}): Promise<SubstrateCall>;
|
|
18
|
+
getTransferData(configs: TransferConfigs, srcAddress: string, dstAddress: string): Promise<Transfer>;
|
|
19
|
+
subscribeBalance(address: string, chain: string | AnyChain, observer: (balances: AssetAmount[]) => void): Promise<Subscription>;
|
|
20
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { AnyChain, Asset, TransferConfigs } from '@galacticcouncil/xc-core';
|
|
2
|
+
import { Wallet } from './Wallet';
|
|
3
|
+
import { Transfer } from './types';
|
|
4
|
+
export declare function TransferBuilder(wallet: Wallet): {
|
|
5
|
+
assets: {
|
|
6
|
+
assets: Asset[];
|
|
7
|
+
asset: (keyOrAsset: string | Asset) => {
|
|
8
|
+
sourceChains: AnyChain[];
|
|
9
|
+
source: (keyOrChain: string | AnyChain) => {
|
|
10
|
+
destinationChains: AnyChain[];
|
|
11
|
+
destination: (keyOrChain: string | AnyChain) => {
|
|
12
|
+
routes: import("@galacticcouncil/xc-core").AssetRoute[];
|
|
13
|
+
build: (assetOnDest?: string | Asset) => TransferConfigs;
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
withAsset(asset: string | Asset): {
|
|
19
|
+
sources: {
|
|
20
|
+
sourceChains: AnyChain[];
|
|
21
|
+
source: (keyOrChain: string | AnyChain) => {
|
|
22
|
+
destinationChains: AnyChain[];
|
|
23
|
+
destination: (keyOrChain: string | AnyChain) => {
|
|
24
|
+
routes: import("@galacticcouncil/xc-core").AssetRoute[];
|
|
25
|
+
build: (assetOnDest?: string | Asset) => TransferConfigs;
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
withSource(srcChain: string | AnyChain): {
|
|
30
|
+
destinations: {
|
|
31
|
+
destinationChains: AnyChain[];
|
|
32
|
+
destination: (keyOrChain: string | AnyChain) => {
|
|
33
|
+
routes: import("@galacticcouncil/xc-core").AssetRoute[];
|
|
34
|
+
build: (assetOnDest?: string | Asset) => TransferConfigs;
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
withDestination(dstChain: string | AnyChain): {
|
|
38
|
+
routes: import("@galacticcouncil/xc-core").AssetRoute[];
|
|
39
|
+
build({ srcAddress, dstAddress, dstAsset, }: {
|
|
40
|
+
srcAddress: string;
|
|
41
|
+
dstAddress: string;
|
|
42
|
+
dstAsset?: string | Asset;
|
|
43
|
+
}): Promise<Transfer>;
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
};
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
export interface Vaa {
|
|
2
|
+
sequence: number;
|
|
3
|
+
id: string;
|
|
4
|
+
version: number;
|
|
5
|
+
emitterChain: number;
|
|
6
|
+
emitterAddr: string;
|
|
7
|
+
emitterNativeAddr: string;
|
|
8
|
+
guardianSetIndex: number;
|
|
9
|
+
vaa: string;
|
|
10
|
+
timestamp: string;
|
|
11
|
+
updatedAt: string;
|
|
12
|
+
indexedAt: string;
|
|
13
|
+
txHash: string;
|
|
14
|
+
}
|
|
15
|
+
export interface VaaBytes {
|
|
16
|
+
vaaBytes: string;
|
|
17
|
+
}
|
|
18
|
+
export interface Operation {
|
|
19
|
+
id: string;
|
|
20
|
+
content: {
|
|
21
|
+
payload: OperationPayload;
|
|
22
|
+
standarizedProperties: OperationProperties;
|
|
23
|
+
};
|
|
24
|
+
data: {
|
|
25
|
+
symbol: string;
|
|
26
|
+
tokenAmount: string;
|
|
27
|
+
};
|
|
28
|
+
emitterChain: number;
|
|
29
|
+
emitterAddress: {
|
|
30
|
+
hex: string;
|
|
31
|
+
native: string;
|
|
32
|
+
};
|
|
33
|
+
sequence: string;
|
|
34
|
+
sourceChain: {
|
|
35
|
+
chainId: number;
|
|
36
|
+
from: string;
|
|
37
|
+
status: string;
|
|
38
|
+
timestamp: string;
|
|
39
|
+
transaction: {
|
|
40
|
+
txHash: string;
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
targetChain?: {
|
|
44
|
+
status: string;
|
|
45
|
+
};
|
|
46
|
+
vaa?: {
|
|
47
|
+
guardianSetIndex: number;
|
|
48
|
+
isDuplicated: boolean;
|
|
49
|
+
raw: string;
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
export interface OperationParsedPayload {
|
|
53
|
+
targetRecipient: string;
|
|
54
|
+
targetRelayerFee: bigint;
|
|
55
|
+
toNativeTokenAmount: bigint;
|
|
56
|
+
}
|
|
57
|
+
export interface OperationPayload {
|
|
58
|
+
amount: string;
|
|
59
|
+
fee: string;
|
|
60
|
+
fromAddress: string;
|
|
61
|
+
parsedPayload: OperationParsedPayload;
|
|
62
|
+
payload: string;
|
|
63
|
+
payloadType: number;
|
|
64
|
+
toAddress: string;
|
|
65
|
+
toChain: number;
|
|
66
|
+
tokenAddress: string;
|
|
67
|
+
tokenChain: number;
|
|
68
|
+
}
|
|
69
|
+
export interface OperationProperties {
|
|
70
|
+
fromChain: number;
|
|
71
|
+
fromAddress: string;
|
|
72
|
+
toChain: number;
|
|
73
|
+
toAddress: string;
|
|
74
|
+
tokenChain: number;
|
|
75
|
+
tokenAddress: string;
|
|
76
|
+
}
|
|
77
|
+
export declare class WormholeScan {
|
|
78
|
+
private _baseUrl;
|
|
79
|
+
constructor(baseUrl?: string);
|
|
80
|
+
private buildApi;
|
|
81
|
+
getVaaBytes(wormholeId: string): Promise<VaaBytes>;
|
|
82
|
+
getVaa(wormholeId: string): Promise<Vaa>;
|
|
83
|
+
getVaaByTxHash(txHash: string): Promise<Vaa>;
|
|
84
|
+
getOperations(params: Record<string, string>): Promise<Operation[]>;
|
|
85
|
+
getOperation(wormholeId: string): Promise<Operation>;
|
|
86
|
+
isMrlTransfer(payload: OperationPayload): boolean;
|
|
87
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { AnyChain, ConfigService } from '@galacticcouncil/xc-core';
|
|
2
|
+
import { WormholeScan } from './WormholeScan';
|
|
3
|
+
import { WhTransfer } from './types';
|
|
4
|
+
export declare class WormholeTransfer {
|
|
5
|
+
private parachainId;
|
|
6
|
+
private config;
|
|
7
|
+
readonly whScan: WormholeScan;
|
|
8
|
+
constructor(config: ConfigService, parachainId: number);
|
|
9
|
+
get chains(): AnyChain[];
|
|
10
|
+
get filters(): Record<string, string>;
|
|
11
|
+
getWithdraws(address: string): Promise<WhTransfer[]>;
|
|
12
|
+
getDeposits(address: string, to?: string): Promise<WhTransfer[]>;
|
|
13
|
+
private isStuck;
|
|
14
|
+
private getVaaHeader;
|
|
15
|
+
private getStatus;
|
|
16
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { AnyChain } from '@galacticcouncil/xc-core';
|
|
2
|
+
import { Operation } from './WormholeScan';
|
|
3
|
+
import { Call } from '../platforms';
|
|
4
|
+
export interface WhTransfer {
|
|
5
|
+
asset: string;
|
|
6
|
+
assetSymbol: string;
|
|
7
|
+
amount: string;
|
|
8
|
+
from: string;
|
|
9
|
+
fromChain: AnyChain;
|
|
10
|
+
to: string;
|
|
11
|
+
toChain: AnyChain;
|
|
12
|
+
status: WhStatus;
|
|
13
|
+
redeem?: (from: string) => Promise<Call | Call[]>;
|
|
14
|
+
operation: Operation;
|
|
15
|
+
}
|
|
16
|
+
export declare enum WhStatus {
|
|
17
|
+
WaitingForVaa = 0,
|
|
18
|
+
VaaEmitted = 1,
|
|
19
|
+
Completed = 2
|
|
20
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { AnyChain, Asset, AssetAmount, BaseConfig } from '@galacticcouncil/xc-core';
|
|
2
|
+
import { Observable } from 'rxjs';
|
|
3
|
+
import { Call, Platform } from './types';
|
|
4
|
+
export declare class PlatformAdapter {
|
|
5
|
+
readonly platform: Record<string, Platform<BaseConfig, BaseConfig>>;
|
|
6
|
+
constructor(chain: AnyChain);
|
|
7
|
+
private registerEvm;
|
|
8
|
+
private registerSolana;
|
|
9
|
+
private registerSui;
|
|
10
|
+
private registerSubstrate;
|
|
11
|
+
buildCall(account: string, amount: bigint, feeBalance: AssetAmount, config: BaseConfig): Promise<Call>;
|
|
12
|
+
estimateFee(account: string, amount: bigint, feeBalance: AssetAmount, config: BaseConfig): Promise<AssetAmount>;
|
|
13
|
+
getBalance(asset: Asset, config: BaseConfig): Promise<AssetAmount>;
|
|
14
|
+
subscribeBalance(asset: Asset, config: BaseConfig): Promise<Observable<AssetAmount>>;
|
|
15
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { AnyEvmChain, Asset, AssetAmount, ContractConfig } from '@galacticcouncil/xc-core';
|
|
2
|
+
import { Observable } from 'rxjs';
|
|
3
|
+
import { EvmCall } from './types';
|
|
4
|
+
import { Platform } from '../types';
|
|
5
|
+
export declare class EvmPlatform implements Platform<ContractConfig, ContractConfig> {
|
|
6
|
+
#private;
|
|
7
|
+
constructor(chain: AnyEvmChain);
|
|
8
|
+
buildCall(account: string, amount: bigint, _feeBalance: AssetAmount, config: ContractConfig): Promise<EvmCall>;
|
|
9
|
+
estimateFee(account: string, amount: bigint, feeBalance: AssetAmount, config: ContractConfig): Promise<AssetAmount>;
|
|
10
|
+
getBalance(asset: Asset, config: ContractConfig): Promise<AssetAmount>;
|
|
11
|
+
subscribeBalance(asset: Asset, config: ContractConfig): Promise<Observable<AssetAmount>>;
|
|
12
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { ContractConfig, Erc20Client, EvmClient } from '@galacticcouncil/xc-core';
|
|
2
|
+
import { EvmBalance } from './EvmBalance';
|
|
3
|
+
export declare class Erc20 extends EvmBalance {
|
|
4
|
+
readonly erc20: Erc20Client;
|
|
5
|
+
constructor(client: EvmClient, config: ContractConfig);
|
|
6
|
+
getBalance(): Promise<bigint>;
|
|
7
|
+
getDecimals(): Promise<number>;
|
|
8
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { ContractConfig, EvmClient } from '@galacticcouncil/xc-core';
|
|
2
|
+
export declare abstract class EvmBalance {
|
|
3
|
+
readonly client: EvmClient;
|
|
4
|
+
readonly config: ContractConfig;
|
|
5
|
+
constructor(client: EvmClient, config: ContractConfig);
|
|
6
|
+
private validateClient;
|
|
7
|
+
private validateConfig;
|
|
8
|
+
abstract getBalance(): Promise<bigint>;
|
|
9
|
+
abstract getDecimals(): Promise<number>;
|
|
10
|
+
}
|