@moonbeam-network/xcm-sdk 1.0.0-dev.30 → 1.0.0-dev.300

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.mjs CHANGED
@@ -1,2 +1,1002 @@
1
- import{AssetAmount as G}from"@moonbeam-network/xcm-types";import{convertDecimals as ut}from"@moonbeam-network/xcm-utils";import V from"big.js";import{Contract as nt}from"ethers";import{createPublicClient as at,getContract as rt,http as st}from"viem";function w(a){return"provider"in a}function C(a){return"signer"in a}var k=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}];var I=class{address;#t;#e;constructor(t,e){if(!t.address)throw new Error("Contract address is required");this.address=t.address,this.#t=t,this.#e=w(e)?new nt(this.address,k,e):rt({abi:k,address:this.address,publicClient:at({chain:e.chain,transport:st()}),walletClient:e})}async getBalance(){return C(this.#e)?(await this.#e.balanceOf(...this.#t.args)).toBigInt():this.#e.read.balanceOf(this.#t.args)}async getDecimals(){return C(this.#e)?await this.#e.decimals():this.#e.read.decimals()}};import{Contract as ot}from"ethers";import{createPublicClient as z,getContract as ct,http as K}from"viem";var F=[{inputs:[{internalType:"address",name:"currencyAddress",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{components:[{internalType:"uint8",name:"parents",type:"uint8"},{internalType:"bytes[]",name:"interior",type:"bytes[]"}],internalType:"struct Xtokens.Multilocation",name:"destination",type:"tuple"},{internalType:"uint64",name:"weight",type:"uint64"}],name:"transfer",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"currencyAddress",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],internalType:"struct Xtokens.Currency[]",name:"currencies",type:"tuple[]"},{internalType:"uint32",name:"feeItem",type:"uint32"},{components:[{internalType:"uint8",name:"parents",type:"uint8"},{internalType:"bytes[]",name:"interior",type:"bytes[]"}],internalType:"struct Xtokens.Multilocation",name:"destination",type:"tuple"},{internalType:"uint64",name:"weight",type:"uint64"}],name:"transferMultiCurrencies",outputs:[],stateMutability:"nonpayable",type:"function"}];var T=class{address="0x0000000000000000000000000000000000000804";#t;#e;#n;constructor(t,e){this.#t=t,this.#n=e,this.#e=w(e)?new ot(this.address,F,e):ct({abi:F,address:this.address,publicClient:z({chain:e.chain,transport:K()}),walletClient:e})}async transfer(){return C(this.#e)?this.#e[this.#t.func](...this.#t.args):this.#e.write[this.#t.func](this.#t.args)}async getEthersContractEstimatedGas(t){return(await t.estimateGas[this.#t.func](...this.#t.args)).toBigInt()}async getViemContractEstimatedGas(t){return t?t.estimateGas[this.#t.func](this.#t.args):0n}async getFee(t){if(t===0n)return 0n;try{let e=C(this.#e)?await this.getEthersContractEstimatedGas(this.#e):await this.getViemContractEstimatedGas(this.#e),n=await this.getGasPrice();return e*n}catch(e){throw console.error(e),new Error("Can't get a fee. Make sure that you have enough balance!")}}async getGasPrice(){if(w(this.#n)){let{gasPrice:e,maxPriorityFeePerGas:n}=await this.#n.getFeeData();return((e==null?void 0:e.toBigInt())||0n)+((n==null?void 0:n.toBigInt())||0n)}return z({chain:this.#n.chain,transport:K()}).getGasPrice()}};function g(a,t){if(a.module==="Erc20")return new I(a,t);if(a.module==="Xtokens")return new T(a,t);throw new Error(`Contract ${a.module} not found`)}import{CallType as N}from"@moonbeam-network/xcm-builder";import{toBigInt as mt}from"@moonbeam-network/xcm-utils";async function B({address:a,config:t,evmSigner:e,polkadot:n}){let r=t.balance.build({address:a,asset:n.chain.getBalanceAssetId(t.asset)});if(r.type===N.Substrate)return n.query(r);if(!e)throw new Error("Evm signer must be provided");return g(r,e).getBalance()}async function b({address:a,asset:t,config:e,evmSigner:n,polkadot:r}){let s=e.balance.build({address:a,asset:r.chain.getBalanceAssetId(t||e.asset)});if(s.type===N.Substrate)return r.getAssetDecimals(t||e.asset);if(!n)throw new Error("Evm signer must be provided");return g(s,n).getDecimals()}async function D(a,t){if(a.min)return t.query(a.min.build({asset:t.chain.getMinAssetId(a.asset)}));let e=t.chain.getAssetMin(a.asset);if(e){let n=await t.getAssetDecimals(a.asset);return mt(e,n)}return 0n}async function j({transferConfig:a,destinationAddress:t,destinationFee:e,evmSigner:n,polkadot:r,sourceAddress:s}){var O,Q,_,X;let{asset:o,destination:f,source:{chain:c,config:i}}=a,p=G.fromAsset(o,{amount:0n,decimals:await b({address:t,config:i,evmSigner:n,polkadot:r})}),l=(O=i.fee)!=null&&O.asset?G.fromAsset(i.fee.asset,{amount:0n,decimals:await b({address:t,asset:i.fee.asset,config:i,evmSigner:n,polkadot:r})}):p,d=(Q=i.destinationFee)!=null&&Q.asset?G.fromAsset(i.destinationFee.asset,{amount:0n,decimals:await b({address:t,asset:i.destinationFee.asset,config:i,evmSigner:n,polkadot:r})}):p,m=await B({address:s,config:i,evmSigner:n,polkadot:r}),u=await $({address:s,balance:m,feeConfig:i.fee,polkadot:r}),S=i.asset.isEqual(i.destinationFee.asset)?m:await $({address:s,balance:m,feeConfig:i.destinationFee,polkadot:r}),P=await D(i,r),x=(_=i.extrinsic)==null?void 0:_.build({address:t,amount:m,asset:c.getAssetId(o),destination:f.chain,fee:e.amount,feeAsset:c.getAssetId(e),palletInstance:c.getAssetPalletInstance(o),source:c}),v=(X=i.contract)==null?void 0:X.build({address:t,amount:m,asset:c.getAssetId(o),destination:f.chain,fee:e.amount,feeAsset:c.getAssetId(e)}),E=await ft({balance:m,contract:v,decimals:l.decimals,evmSigner:n,extrinsic:x,polkadot:r,sourceAddress:s}),h=p.copyWith({amount:m}),{existentialDeposit:W}=r,R=l.copyWith({amount:E}),Y=l.copyWith({amount:u}),Z=d.copyWith({amount:S}),q=p.copyWith({amount:P}),tt=dt({balanceAmount:h,existentialDeposit:W,feeAmount:R,minAmount:q});return{balance:h,chain:c,destinationFeeBalance:Z,existentialDeposit:W,fee:R,feeBalance:Y,max:tt,min:q}}async function $({address:a,balance:t,feeConfig:e,polkadot:n}){return e?n.query(e.balance.build({address:a,asset:n.chain.getBalanceAssetId(e.asset)})):t}async function ft({balance:a,contract:t,decimals:e,evmSigner:n,extrinsic:r,polkadot:s,sourceAddress:o}){if(t){if(!n)throw new Error("EVM Signer must be provided");return pt(a,t,e,n)}if(r)return lt(a,r,s,o);throw new Error("Either contract or extrinsic must be provided")}async function pt(a,t,e,n){let s=await g(t,n).getFee(a);return ut(s,18,e)}async function lt(a,t,e,n){try{return await e.getFee(n,t)}catch(r){if(a)throw r;return 0n}}function dt({balanceAmount:a,existentialDeposit:t,feeAmount:e,minAmount:n}){let r=a.toBig().minus(n.toBig()).minus(a.isSame(t)?t.toBig():V(0)).minus(a.isSame(e)?e.toBig():V(0));return a.copyWith({amount:r.lt(0)?0n:BigInt(r.toFixed())})}import{ConfigBuilder as U,ConfigService as It}from"@moonbeam-network/xcm-config";import{convertDecimals as xt,toBigInt as J}from"@moonbeam-network/xcm-utils";import A from"big.js";import"@polkadot/api-augment";import{darwiniaPangoro as gt,eq as yt,equilibrium as ht,equilibriumAlphanet as Ct,paring as bt}from"@moonbeam-network/xcm-config";import{AssetAmount as At}from"@moonbeam-network/xcm-types";import{getPolkadotApi as wt}from"@moonbeam-network/xcm-utils";var y=class{api;chain;configService;constructor(t,e,n){this.api=t,this.chain=e,this.configService=n}static async create(t,e){return new y(await wt(t.ws),t,e)}static async createMulti(t,e){return Promise.all(t.map(n=>y.create(n,e)))}get decimals(){return this.api.registry.chainDecimals.at(0)||12}get asset(){let t=this.api.registry.chainTokens.at(0),e=t==null?void 0:t.toString().toLowerCase();if(e==="token"&&[Ct.key,ht.key].includes(this.chain.key))return yt;if(e==="oring"&&this.chain.key===gt.key)return bt;if(!e)throw new Error("No native symbol key found");let n=this.configService.getAsset(e);if(!n)throw new Error(`No asset found for key "${e}" and symbol "${t}"`);return n}get existentialDeposit(){var r,s;let t=(r=this.api.consts.balances)==null?void 0:r.existentialDeposit,e=(s=this.api.consts.eqBalances)==null?void 0:s.existentialDeposit,n=(t==null?void 0:t.toBigInt())||(e==null?void 0:e.toBigInt())||0n;return At.fromAsset(this.asset,{amount:n,decimals:this.decimals})}async getAssetMeta(t){var s,o,f,c,i;let e=((s=this.api.query.assets)==null?void 0:s.metadata)||((o=this.api.query.assetRegistry)==null?void 0:o.metadata)||((f=this.api.query.assetRegistry)==null?void 0:f.currencyMetadatas)||((c=this.api.query.assetRegistry)==null?void 0:c.assetMetadatas)||((i=this.api.query.assetRegistry)==null?void 0:i.assetMetadataMap);if(!e)return;let n=await e(t),r="unwrapOrDefault"in n?n.unwrapOrDefault():n;return{decimals:r.decimals.toNumber(),symbol:r.symbol.toString()}}async getAssetDecimalsFromQuery(t){var r;let e=(r=this.api.query.assetsRegistry)==null?void 0:r.assetDecimals;return e?(await e(t)).unwrapOrDefault().toNumber():void 0}async getAssetDecimals(t){var n;let e=this.chain.getMetadataAssetId(t);return await this.getAssetDecimalsFromQuery(e)||((n=await this.getAssetMeta(e))==null?void 0:n.decimals)||this.chain.getAssetDecimals(t)||this.decimals}async query(t){let e=await this.api.query[t.module][t.func](...t.args);return t.transform(e)}async getFee(t,e){let n=this.api.tx[e.module][e.func],r=e.getArgs(n);return(await n(...r).paymentInfo(t,{nonce:-1})).partialFee.toBigInt()}async transfer(t,e,n){let r=this.api.tx[e.module][e.func],s=e.getArgs(r);return(await r(...s).signAndSend(this.#t(n)?t:n,{nonce:-1,signer:this.#t(n)?n:void 0})).toString()}#t(t){return"signPayload"in t}};import{AssetAmount as L}from"@moonbeam-network/xcm-types";import{toBigInt as St}from"@moonbeam-network/xcm-utils";async function H({transferConfig:a,destinationAddress:t,evmSigner:e,polkadot:n}){let{asset:r,destination:{chain:s,config:o}}=a,f=L.fromAsset(r,{amount:0n,decimals:await b({address:t,config:o,evmSigner:e,polkadot:n})}),c=await B({address:t,config:o,evmSigner:e,polkadot:n}),i=await D(o,n),p=f.copyWith({amount:c}),{existentialDeposit:l}=n,d=await Pt({address:t,config:a,evmSigner:e,polkadot:n}),m=f.copyWith({amount:i});return{balance:p,chain:s,existentialDeposit:l,fee:d,min:m}}async function Pt({config:a,polkadot:t}){let{amount:e,asset:n}=a.source.config.destinationFee,r=await t.getAssetDecimals(n),s=L.fromAsset(n,{amount:0n,decimals:r});if(Number.isFinite(e))return s.copyWith({amount:St(e,r)});let o=e.build({api:t.api,asset:t.chain.getAssetId(n)});return s.copyWith({amount:await o.call()})}async function M({configService:a,destinationAddress:t,evmSigner:e,polkadotSigner:n,sourceAddress:r,transferConfig:s}){let[o,f]=await y.createMulti([s.destination.chain,s.source.chain],a),c=await H({destinationAddress:t,evmSigner:e,polkadot:o,transferConfig:s}),i=await Et(f,c.fee),p=await j({destinationAddress:t,destinationFee:i,evmSigner:e,polkadot:f,sourceAddress:r,transferConfig:s});return{destination:c,getEstimate(l){let m=A(J(l,p.balance.decimals).toString()).minus(p.balance.isSame(i)?i.toBig():A(0));return p.balance.copyWith({amount:m.lt(0)?0n:BigInt(m.toFixed())})},isSwapPossible:!0,max:p.max,min:vt(c),source:p,async swap(){return M({configService:a,destinationAddress:r,evmSigner:e,polkadotSigner:n,sourceAddress:t,transferConfig:{...s,destination:s.source,source:s.destination}})},async transfer(l){var v,E;let d=J(l,p.balance.decimals),{asset:m,source:{chain:u,config:S}}=s,P=(v=S.contract)==null?void 0:v.build({address:t,amount:d,asset:u.getAssetId(m),destination:c.chain,fee:i.amount,feeAsset:u.getAssetId(i)}),x=(E=S.extrinsic)==null?void 0:E.build({address:t,amount:d,asset:u.getAssetId(m),destination:c.chain,fee:i.amount,feeAsset:u.getAssetId(i),palletInstance:u.getAssetPalletInstance(m),source:u});if(P){if(!e)throw new Error("EVM Signer must be provided");return g(P,e).transfer().then(h=>typeof h=="object"?h.hash:h)}if(x){if(!n)throw new Error("Polkadot signer must be provided");return f.transfer(r,x,n)}throw new Error("Either contract or extrinsic must be provided")}}}function vt({balance:a,existentialDeposit:t,fee:e,min:n}){let r=A(0).plus(a.isSame(e)?e.toBig():A(0)).plus(a.isSame(t)&&a.toBig().lt(t.toBig())?t.toBig():A(0)).plus(a.toBig().lt(n.toBig())?n.toBig():A(0));return a.copyWith({amount:BigInt(r.toFixed())})}async function Et(a,t){let e=await a.getAssetDecimals(t);return t.decimals===e?t:t.copyWith({amount:xt(t.amount,t.decimals,e),decimals:e})}function $e(a){let t=(a==null?void 0:a.configService)??new It;return{assets(e){let{assets:n,asset:r}=U(t).assets(e);return{assets:n,asset(s){let{sourceChains:o,source:f}=r(s);return{sourceChains:o,source(c){let{destinationChains:i,destination:p}=f(c);return{destinationChains:i,destination(l){return{async accounts(d,m,u){return M({...a,configService:t,destinationAddress:m,evmSigner:(u==null?void 0:u.evmSigner)??(u==null?void 0:u.ethersSigner),sourceAddress:d,transferConfig:p(l).build(),polkadotSigner:u==null?void 0:u.polkadotSigner})}}}}}}}}},async getTransferData({destinationAddress:e,destinationKeyOrChain:n,ethersSigner:r,evmSigner:s,keyOrAsset:o,polkadotSigner:f,sourceAddress:c,sourceKeyOrChain:i}){return M({configService:t,destinationAddress:e,evmSigner:s??r,polkadotSigner:f,sourceAddress:c,transferConfig:U(t).assets().asset(o).source(i).destination(n).build()})}}}export{$e as Sdk,pt as getContractFee,lt as getExtrinsicFee,ft as getFee,$ as getFeeBalances,dt as getMax,j as getSourceData};
1
+ // src/getTransferData/getDestinationData.ts
2
+ import { Parachain as Parachain2 } from "@moonbeam-network/xcm-types";
3
+ import { getSovereignAccountAddresses } from "@moonbeam-network/xcm-utils";
4
+
5
+ // src/getTransferData/getTransferData.utils.ts
6
+ import {
7
+ ContractConfig,
8
+ EvmQueryConfig,
9
+ SubstrateCallConfig,
10
+ SubstrateQueryConfig
11
+ } from "@moonbeam-network/xcm-builder";
12
+ import {
13
+ AssetAmount as AssetAmount2,
14
+ EvmChain,
15
+ EvmParachain,
16
+ Parachain
17
+ } from "@moonbeam-network/xcm-types";
18
+ import { convertDecimals, toBigInt } from "@moonbeam-network/xcm-utils";
19
+ import Big from "big.js";
20
+
21
+ // src/services/evm/EvmService.ts
22
+ import {
23
+ createPublicClient,
24
+ http
25
+ } from "viem";
26
+ var EvmService = class _EvmService {
27
+ chain;
28
+ client;
29
+ static create(chain) {
30
+ return new _EvmService(chain);
31
+ }
32
+ constructor(chain) {
33
+ this.chain = chain;
34
+ this.client = createPublicClient({
35
+ chain: chain.getViemChain(),
36
+ transport: http()
37
+ });
38
+ }
39
+ async query(query) {
40
+ return this.client[query.func](...query.args);
41
+ }
42
+ async read(config) {
43
+ return this.client.readContract({
44
+ abi: config.abi,
45
+ address: config.address,
46
+ args: config.args,
47
+ functionName: config.func
48
+ });
49
+ }
50
+ async getFee(address, contract, stateOverride) {
51
+ const gas = await this.client.estimateContractGas({
52
+ abi: contract.abi,
53
+ account: address,
54
+ address: contract.address,
55
+ args: contract.args,
56
+ functionName: contract.func,
57
+ value: contract.value,
58
+ stateOverride
59
+ });
60
+ const gasPrice = await this.client.getGasPrice();
61
+ return gas * gasPrice;
62
+ }
63
+ async getBalance(address, contract) {
64
+ const balance = await this.client.readContract({
65
+ abi: contract.abi,
66
+ address: contract.address,
67
+ args: [address],
68
+ functionName: "balanceOf"
69
+ });
70
+ if (typeof balance !== "bigint") {
71
+ throw new Error(
72
+ `Could not get balance on ${this.chain.name} for ${address} from contract ${contract.address}`
73
+ );
74
+ }
75
+ return balance;
76
+ }
77
+ async transfer(signer, contract) {
78
+ const { request } = await this.client.simulateContract({
79
+ abi: contract.abi,
80
+ account: signer.account,
81
+ address: contract.address,
82
+ args: contract.args,
83
+ functionName: contract.func,
84
+ value: contract.value
85
+ });
86
+ const hash = await signer.writeContract(request);
87
+ return hash;
88
+ }
89
+ };
90
+
91
+ // src/services/polkadot/PolkadotService.ts
92
+ import "@polkadot/api-augment";
93
+ import { AssetAmount } from "@moonbeam-network/xcm-types";
94
+ import { getPolkadotApi } from "@moonbeam-network/xcm-utils";
95
+ var PolkadotService = class _PolkadotService {
96
+ api;
97
+ chain;
98
+ constructor(api, chain) {
99
+ this.api = api;
100
+ this.chain = chain;
101
+ }
102
+ static async create(chain) {
103
+ return new _PolkadotService(await getPolkadotApi(chain.ws), chain);
104
+ }
105
+ static async createMulti(chains) {
106
+ return Promise.all(
107
+ chains.map((chain) => _PolkadotService.create(chain))
108
+ );
109
+ }
110
+ get decimals() {
111
+ return this.api.registry.chainDecimals.at(0) || 12;
112
+ }
113
+ get existentialDeposit() {
114
+ const existentialDeposit = this.api.consts.balances?.existentialDeposit;
115
+ const eqExistentialDeposit = this.api.consts.eqBalances?.existentialDeposit;
116
+ const amount = existentialDeposit?.toBigInt() || eqExistentialDeposit?.toBigInt() || 0n;
117
+ return AssetAmount.fromChainAsset(this.chain.nativeAsset, { amount });
118
+ }
119
+ async query(config) {
120
+ const queryFn = this.api[config.queryType][config.module][config.func];
121
+ const response = await queryFn(...config.args);
122
+ return config.transform(response);
123
+ }
124
+ getExtrinsic(config) {
125
+ const fn = this.api.tx[config.module][config.func];
126
+ const args = config.getArgs(fn);
127
+ return fn(...args);
128
+ }
129
+ getExtrinsicCallHash(config) {
130
+ return this.getExtrinsic(config).method.toHex();
131
+ }
132
+ async getPaymentInfo(account, config) {
133
+ const extrinsic = this.getExtrinsic(config);
134
+ return extrinsic.paymentInfo(account, { nonce: -1 });
135
+ }
136
+ async getFee(account, config) {
137
+ const info = await this.getPaymentInfo(account, config);
138
+ return info.partialFee.toBigInt();
139
+ }
140
+ async transfer(account, config, signer, statusCallback) {
141
+ const extrinsic = this.getExtrinsic(config);
142
+ const isSigner = this.#isSigner(signer);
143
+ const signOptions = {
144
+ nonce: -1,
145
+ signer: isSigner ? signer : void 0,
146
+ withSignedTransaction: true
147
+ };
148
+ const hash = await new Promise((resolve, reject) => {
149
+ extrinsic.signAndSend(isSigner ? account : signer, signOptions, (result) => {
150
+ if (result.isError || result.dispatchError) {
151
+ reject(
152
+ new Error(
153
+ result.dispatchError?.toString() || "Transaction failed"
154
+ )
155
+ );
156
+ }
157
+ if (result.txHash) {
158
+ resolve(result.txHash.toString());
159
+ }
160
+ statusCallback?.(result);
161
+ }).catch(reject);
162
+ });
163
+ return hash;
164
+ }
165
+ #isSigner(signer) {
166
+ return "signPayload" in signer;
167
+ }
168
+ };
169
+
170
+ // src/getTransferData/getTransferData.utils.ts
171
+ async function getBalance({
172
+ address,
173
+ asset,
174
+ builder,
175
+ chain
176
+ }) {
177
+ const config = builder.build({
178
+ address,
179
+ asset
180
+ });
181
+ const amount = AssetAmount2.fromChainAsset(asset, { amount: 0n });
182
+ if (SubstrateQueryConfig.is(config) && EvmParachain.isAnyParachain(chain)) {
183
+ const polkadot = await PolkadotService.create(chain);
184
+ const balance = await polkadot.query(config);
185
+ const converted = chain.usesChainDecimals ? convertDecimals(balance, polkadot.decimals, asset.decimals) : balance;
186
+ return amount.copyWith({ amount: converted });
187
+ }
188
+ if (EvmChain.is(chain) || EvmParachain.is(chain)) {
189
+ const evm = EvmService.create(chain);
190
+ if (ContractConfig.is(config)) {
191
+ const balance = await evm.getBalance(address, config);
192
+ return amount.copyWith({ amount: balance });
193
+ }
194
+ if (EvmQueryConfig.is(config)) {
195
+ const balance = await evm.query(config);
196
+ return amount.copyWith({ amount: balance });
197
+ }
198
+ }
199
+ throw new Error(
200
+ `Can't get balance for ${address} on chain ${chain.name} and asset ${asset.symbol}`
201
+ );
202
+ }
203
+ async function getAssetMin({
204
+ asset,
205
+ builder,
206
+ chain
207
+ }) {
208
+ const zero = AssetAmount2.fromChainAsset(chain.getChainAsset(asset), {
209
+ amount: 0n
210
+ });
211
+ if (builder && EvmParachain.isAnyParachain(chain)) {
212
+ const polkadot = await PolkadotService.create(chain);
213
+ const min = await polkadot.query(
214
+ builder.build({ asset: zero.getMinAssetId(), address: zero.address })
215
+ );
216
+ return zero.copyWith({ amount: min });
217
+ }
218
+ if (zero.min) {
219
+ return zero.copyWith({ amount: zero.min });
220
+ }
221
+ return zero;
222
+ }
223
+ function getMin({
224
+ balance,
225
+ existentialDeposit,
226
+ fee,
227
+ min
228
+ }) {
229
+ const result = Big(0).plus(balance.isSame(fee) ? fee.toBig() : Big(0)).plus(
230
+ existentialDeposit && balance.isSame(existentialDeposit) && balance.toBig().lt(existentialDeposit.toBig()) ? existentialDeposit.toBig() : Big(0)
231
+ ).plus(balance.toBig().lt(min.toBig()) ? min.toBig() : Big(0));
232
+ return balance.copyWith({
233
+ amount: BigInt(result.toFixed())
234
+ });
235
+ }
236
+ function getMax({
237
+ balance,
238
+ existentialDeposit,
239
+ fee,
240
+ min
241
+ }) {
242
+ const result = balance.toBig().minus(min.toBig()).minus(
243
+ existentialDeposit && balance.isSame(existentialDeposit) ? existentialDeposit.toBig() : Big(0)
244
+ ).minus(balance.isSame(fee) ? fee.toBig() : Big(0));
245
+ return balance.copyWith({
246
+ amount: result.lt(0) ? 0n : BigInt(result.toFixed())
247
+ });
248
+ }
249
+ async function getDestinationFee({
250
+ address,
251
+ asset,
252
+ destination,
253
+ fee,
254
+ feeAsset,
255
+ source
256
+ }) {
257
+ const zero = AssetAmount2.fromChainAsset(destination.getChainAsset(feeAsset), {
258
+ amount: 0n
259
+ });
260
+ if (typeof fee === "number") {
261
+ return zero.copyWith({
262
+ amount: fee
263
+ });
264
+ }
265
+ if (EvmParachain.isAnyParachain(destination)) {
266
+ const polkadot = await PolkadotService.create(destination);
267
+ const cfg = fee.build({
268
+ address,
269
+ api: polkadot.api,
270
+ asset: destination.getChainAsset(asset),
271
+ destination,
272
+ feeAsset: destination.getChainAsset(feeAsset),
273
+ source
274
+ });
275
+ if (SubstrateCallConfig.is(cfg)) {
276
+ return zero.copyWith({
277
+ amount: await cfg.call()
278
+ });
279
+ }
280
+ }
281
+ return zero;
282
+ }
283
+ function convertToChainDecimals({
284
+ asset,
285
+ target
286
+ }) {
287
+ return AssetAmount2.fromChainAsset(target, {
288
+ amount: asset.convertDecimals(target.decimals).amount
289
+ });
290
+ }
291
+ async function getExistentialDeposit(chain) {
292
+ if (EvmParachain.isAnyParachain(chain)) {
293
+ const polkadot = await PolkadotService.create(chain);
294
+ return polkadot.existentialDeposit;
295
+ }
296
+ return void 0;
297
+ }
298
+ async function getDestinationFeeBalance({
299
+ balance,
300
+ feeBalance,
301
+ route,
302
+ sourceAddress
303
+ }) {
304
+ if (route.destination.fee.asset.isEqual(balance)) {
305
+ return balance;
306
+ }
307
+ if (route.destination.fee.asset.isEqual(feeBalance)) {
308
+ return feeBalance;
309
+ }
310
+ if (!route.source.destinationFee?.balance) {
311
+ throw new Error(
312
+ "BalanceBuilder must be defined for source.destinationFee.balance for AssetRoute"
313
+ );
314
+ }
315
+ return getBalance({
316
+ address: sourceAddress,
317
+ asset: route.getDestinationFeeAssetOnSource(),
318
+ builder: route.source.destinationFee?.balance,
319
+ chain: route.source.chain
320
+ });
321
+ }
322
+ async function getExtrinsicFee({
323
+ address,
324
+ balance,
325
+ chain,
326
+ extrinsic,
327
+ feeBalance,
328
+ feeConfig
329
+ }) {
330
+ try {
331
+ const polkadot = await PolkadotService.create(chain);
332
+ const fee = await polkadot.getFee(address, extrinsic);
333
+ const extra = feeConfig?.extra ? toBigInt(feeConfig.extra, feeBalance.decimals) : 0n;
334
+ const totalFee = fee + extra;
335
+ const converted = chain.usesChainDecimals ? convertDecimals(totalFee, polkadot.decimals, feeBalance.decimals) : totalFee;
336
+ return feeBalance.copyWith({ amount: converted });
337
+ } catch (error) {
338
+ if (balance.amount) {
339
+ throw error;
340
+ }
341
+ return feeBalance.copyWith({ amount: 0n });
342
+ }
343
+ }
344
+ async function getContractFee({
345
+ address,
346
+ balance,
347
+ chain,
348
+ contract,
349
+ destinationFee,
350
+ feeBalance,
351
+ feeConfig
352
+ }) {
353
+ try {
354
+ if (balance.amount === 0n) {
355
+ return feeBalance.copyWith({ amount: 0n });
356
+ }
357
+ const evm = EvmService.create(chain);
358
+ const fee = await evm.getFee(address, contract);
359
+ const extra = feeConfig?.extra ? toBigInt(feeConfig.extra, feeBalance.decimals) : 0n;
360
+ return feeBalance.copyWith({ amount: fee + extra });
361
+ } catch (error) {
362
+ throw new Error(
363
+ `Can't get a fee, make sure you have ${destinationFee.toDecimal()} ${destinationFee.getSymbol()} in your source balance, needed for destination fees`,
364
+ { cause: error }
365
+ );
366
+ }
367
+ }
368
+ function validateSovereignAccountBalances({
369
+ amount,
370
+ sourceData,
371
+ destinationData
372
+ }) {
373
+ if (!Parachain.is(destinationData.chain) || !destinationData.chain.checkSovereignAccountBalances || !destinationData.sovereignAccountBalances) {
374
+ return;
375
+ }
376
+ const { feeAssetBalance, transferAssetBalance } = destinationData.sovereignAccountBalances;
377
+ if (amount > transferAssetBalance) {
378
+ throw new Error(
379
+ `${sourceData.chain.name} Sovereign account in ${destinationData.chain.name} does not have enough balance for this transaction`
380
+ );
381
+ }
382
+ if (feeAssetBalance && sourceData.destinationFee.amount > feeAssetBalance) {
383
+ throw new Error(
384
+ `${sourceData.chain.name} Sovereign account in ${destinationData.chain.name} does not have enough balance to pay for fees for this transaction`
385
+ );
386
+ }
387
+ }
388
+
389
+ // src/getTransferData/getDestinationData.ts
390
+ async function getDestinationData({
391
+ route,
392
+ destinationAddress
393
+ }) {
394
+ const destination = route.destination.chain;
395
+ const asset = destination.getChainAsset(route.destination.asset);
396
+ const balance = await getBalance({
397
+ address: destinationAddress,
398
+ asset,
399
+ builder: route.destination.balance,
400
+ chain: destination
401
+ });
402
+ const min = await getAssetMin({
403
+ asset,
404
+ builder: route.destination.min,
405
+ chain: destination
406
+ });
407
+ const fee = await getDestinationFee({
408
+ address: destinationAddress,
409
+ feeAsset: route.destination.fee.asset,
410
+ destination,
411
+ fee: route.destination.fee.amount,
412
+ source: route.source.chain,
413
+ asset: route.source.asset
414
+ });
415
+ const existentialDeposit = await getExistentialDeposit(destination);
416
+ return {
417
+ chain: destination,
418
+ balance,
419
+ existentialDeposit,
420
+ fee,
421
+ min,
422
+ sovereignAccountBalances: await getSovereignAccountBalances({
423
+ source: route.source,
424
+ destination: route.destination
425
+ })
426
+ };
427
+ }
428
+ async function getSovereignAccountBalances({
429
+ destination,
430
+ source
431
+ }) {
432
+ if (!Parachain2.is(source.chain) || !Parachain2.is(destination.chain) || !destination.chain.checkSovereignAccountBalances) {
433
+ return void 0;
434
+ }
435
+ const sovereignAccountAddresses = getSovereignAccountAddresses(
436
+ source.chain.parachainId
437
+ );
438
+ const destinationFeeAssetBalance = destination.fee.balance;
439
+ const sovereignAccountAddress = destination.chain.isRelay ? sovereignAccountAddresses.relay : sovereignAccountAddresses.generic;
440
+ const sovereignAccountBalance = await getBalance({
441
+ address: sovereignAccountAddress,
442
+ asset: destination.chain.getChainAsset(destination.asset),
443
+ builder: destination.balance,
444
+ chain: destination.chain
445
+ });
446
+ const sovereignAccountFeeAssetBalance = destinationFeeAssetBalance ? await getBalance({
447
+ address: sovereignAccountAddress,
448
+ asset: destination.chain.getChainAsset(destination.fee.asset),
449
+ builder: destinationFeeAssetBalance,
450
+ chain: destination.chain
451
+ }) : void 0;
452
+ return {
453
+ feeAssetBalance: sovereignAccountFeeAssetBalance?.amount,
454
+ transferAssetBalance: sovereignAccountBalance.amount
455
+ };
456
+ }
457
+
458
+ // src/getTransferData/getSourceData.ts
459
+ async function getSourceData({
460
+ route,
461
+ destinationAddress,
462
+ destinationFee,
463
+ sourceAddress
464
+ }) {
465
+ const source = route.source.chain;
466
+ const destination = route.destination.chain;
467
+ const [sourcePolkadot, destinationPolkadot] = await PolkadotService.createMulti([source, destination]);
468
+ const asset = source.getChainAsset(route.source.asset);
469
+ const feeAsset = route.source.fee ? source.getChainAsset(route.source.fee.asset) : asset;
470
+ const balance = await getBalance({
471
+ address: sourceAddress,
472
+ asset,
473
+ builder: route.source.balance,
474
+ chain: source
475
+ });
476
+ const feeBalance = await getBalance({
477
+ address: sourceAddress,
478
+ asset: feeAsset,
479
+ builder: route.source.fee.balance,
480
+ chain: source
481
+ });
482
+ const destinationFeeBalance = await getDestinationFeeBalance({
483
+ balance,
484
+ feeBalance,
485
+ route,
486
+ sourceAddress
487
+ });
488
+ const existentialDeposit = await getExistentialDeposit(source);
489
+ const min = await getAssetMin({
490
+ asset,
491
+ builder: route.source.min,
492
+ chain: source
493
+ });
494
+ const extrinsic = route.extrinsic?.build({
495
+ asset: balance,
496
+ destination: route.destination.chain,
497
+ destinationAddress,
498
+ destinationApi: destinationPolkadot.api,
499
+ fee: destinationFee,
500
+ source,
501
+ sourceAddress,
502
+ sourceApi: sourcePolkadot.api
503
+ });
504
+ const contract = route.contract?.build({
505
+ asset: balance,
506
+ destination: route.destination.chain,
507
+ destinationAddress,
508
+ destinationApi: destinationPolkadot.api,
509
+ fee: destinationFee,
510
+ source,
511
+ sourceAddress,
512
+ sourceApi: sourcePolkadot.api
513
+ });
514
+ const fee = await getFee({
515
+ balance,
516
+ chain: source,
517
+ contract,
518
+ destinationFee,
519
+ extrinsic,
520
+ feeBalance,
521
+ feeConfig: route.source.fee,
522
+ sourceAddress
523
+ });
524
+ const max = getMax({
525
+ balance,
526
+ existentialDeposit,
527
+ fee,
528
+ min
529
+ });
530
+ return {
531
+ balance,
532
+ chain: source,
533
+ destinationFee,
534
+ destinationFeeBalance,
535
+ existentialDeposit,
536
+ fee,
537
+ feeBalance,
538
+ max,
539
+ min
540
+ };
541
+ }
542
+ async function getFee({
543
+ balance,
544
+ feeBalance,
545
+ chain,
546
+ contract,
547
+ destinationFee,
548
+ extrinsic,
549
+ feeConfig,
550
+ sourceAddress
551
+ }) {
552
+ if (!contract && !extrinsic) {
553
+ throw new Error("Either contract or extrinsic must be provided");
554
+ }
555
+ if (contract) {
556
+ return getContractFee({
557
+ address: sourceAddress,
558
+ balance,
559
+ chain,
560
+ contract,
561
+ destinationFee,
562
+ feeBalance,
563
+ feeConfig
564
+ });
565
+ }
566
+ return getExtrinsicFee({
567
+ address: sourceAddress,
568
+ balance,
569
+ chain,
570
+ extrinsic,
571
+ feeBalance,
572
+ feeConfig
573
+ });
574
+ }
575
+ async function getAssetsBalances({
576
+ address,
577
+ chain,
578
+ routes
579
+ }) {
580
+ const uniqueRoutes = routes.reduce((acc, route) => {
581
+ if (!acc.some((a) => a.source.asset.isEqual(route.source.asset))) {
582
+ return [route, ...acc];
583
+ }
584
+ return acc;
585
+ }, []);
586
+ const balances = await Promise.all(
587
+ uniqueRoutes.map(
588
+ async (route) => getBalance({
589
+ address,
590
+ asset: chain.getChainAsset(route.source.asset),
591
+ builder: route.source.balance,
592
+ chain
593
+ })
594
+ )
595
+ );
596
+ return balances;
597
+ }
598
+
599
+ // src/sdk.ts
600
+ import { ConfigService, xcmRoutesMap } from "@moonbeam-network/xcm-config";
601
+ import {
602
+ EvmParachain as EvmParachain2
603
+ } from "@moonbeam-network/xcm-types";
604
+
605
+ // src/getTransferData/getTransferData.ts
606
+ import {
607
+ AssetAmount as AssetAmount3
608
+ } from "@moonbeam-network/xcm-types";
609
+ import { toBigInt as toBigInt2 } from "@moonbeam-network/xcm-utils";
610
+ import Big2 from "big.js";
611
+
612
+ // src/utils/monitoring.ts
613
+ import { getPolkadotApi as getPolkadotApi2 } from "@moonbeam-network/xcm-utils";
614
+ var ENABLE_LOGGING = process.env.ENABLE_LOGGING === "true";
615
+ function log(label, message) {
616
+ if (ENABLE_LOGGING) {
617
+ console.log(`[${label}]`, message ?? "");
618
+ }
619
+ }
620
+ async function listenToDestinationEvents({
621
+ route,
622
+ monitoringConfig,
623
+ messageId,
624
+ onDestinationFinalized,
625
+ onDestinationError
626
+ }) {
627
+ if (!route?.destination?.chain || !("ws" in route.destination.chain)) {
628
+ log("No destination WS endpoint available");
629
+ return;
630
+ }
631
+ try {
632
+ const api = await getPolkadotApi2(route.destination.chain.ws);
633
+ log("Subscribing to destination events...");
634
+ const unsubscribe = await api.query.system.events((events) => {
635
+ log("Destination events", events.toHuman());
636
+ const destinationResult = monitoringConfig.checkDestination(
637
+ events,
638
+ messageId
639
+ );
640
+ if (destinationResult.matched) {
641
+ log("Destination event matched:", destinationResult.event?.toHuman());
642
+ unsubscribe();
643
+ if (destinationResult.success) {
644
+ onDestinationFinalized?.();
645
+ } else {
646
+ const error = new Error(
647
+ `Message processing failed on destination chain: ${route.destination.chain.name}`
648
+ );
649
+ console.error(
650
+ "Destination message processing failed:",
651
+ destinationResult.event?.toHuman()
652
+ );
653
+ onDestinationError?.(error);
654
+ }
655
+ }
656
+ });
657
+ } catch (error) {
658
+ console.error("Error listening to destination events:", error);
659
+ onDestinationError?.(error);
660
+ }
661
+ }
662
+ function processSourceEvents({
663
+ events,
664
+ sourceAddress,
665
+ route,
666
+ onSourceFinalized,
667
+ onSourceError,
668
+ onDestinationFinalized,
669
+ onDestinationError,
670
+ unsubscribe
671
+ }) {
672
+ const monitoringConfig = route.monitoring;
673
+ if (!monitoringConfig) {
674
+ log("No monitoring config found");
675
+ unsubscribe?.();
676
+ return;
677
+ }
678
+ const extrinsicFailedEvent = events.find((event) => {
679
+ return event.event.section === "system" && event.event.method === "ExtrinsicFailed";
680
+ });
681
+ if (extrinsicFailedEvent) {
682
+ onSourceError?.(new Error("Extrinsic failed"));
683
+ unsubscribe?.();
684
+ return;
685
+ }
686
+ try {
687
+ const sourceResult = monitoringConfig.checkSource(events, sourceAddress);
688
+ if (sourceResult.matched) {
689
+ log("Source event matched:", sourceResult.event?.toHuman());
690
+ onSourceFinalized?.();
691
+ log("Message ID:", sourceResult.messageId);
692
+ if (unsubscribe) {
693
+ log("Unsubscribing from source events...");
694
+ unsubscribe();
695
+ }
696
+ listenToDestinationEvents({
697
+ route,
698
+ monitoringConfig,
699
+ messageId: sourceResult.messageId,
700
+ onDestinationFinalized,
701
+ onDestinationError
702
+ });
703
+ return;
704
+ }
705
+ } catch (error) {
706
+ console.error("Error in MonitoringBuilder config:", error);
707
+ return;
708
+ }
709
+ }
710
+ function createMonitoringCallback({
711
+ sourceAddress,
712
+ route,
713
+ statusCallback,
714
+ onSourceFinalized,
715
+ onSourceError,
716
+ onDestinationFinalized,
717
+ onDestinationError
718
+ }) {
719
+ return (status) => {
720
+ statusCallback?.(status);
721
+ processSourceEvents({
722
+ events: status.events,
723
+ sourceAddress,
724
+ route,
725
+ onSourceFinalized,
726
+ onSourceError,
727
+ onDestinationFinalized,
728
+ onDestinationError
729
+ });
730
+ };
731
+ }
732
+ async function listenToSourceEvents({
733
+ route,
734
+ sourceAddress,
735
+ onSourceFinalized,
736
+ onSourceError,
737
+ onDestinationFinalized,
738
+ onDestinationError
739
+ }) {
740
+ if (!route?.source?.chain || !("ws" in route.source.chain)) {
741
+ log("No source WS endpoint available");
742
+ return;
743
+ }
744
+ try {
745
+ const api = await getPolkadotApi2(route.source.chain.ws);
746
+ log("Subscribing to source events...");
747
+ const unsubscribe = await api.query.system.events((events) => {
748
+ log("Source events:", events.toHuman());
749
+ processSourceEvents({
750
+ events,
751
+ sourceAddress,
752
+ route,
753
+ onSourceFinalized,
754
+ onSourceError,
755
+ onDestinationFinalized,
756
+ onDestinationError,
757
+ unsubscribe
758
+ });
759
+ });
760
+ } catch (error) {
761
+ console.error("Error listening to source events:", error);
762
+ }
763
+ }
764
+
765
+ // src/getTransferData/getTransferData.ts
766
+ async function getTransferData({
767
+ route,
768
+ sourceAddress,
769
+ destinationAddress
770
+ }) {
771
+ const destinationData = await getDestinationData({
772
+ route,
773
+ destinationAddress
774
+ });
775
+ const destinationFee = convertToChainDecimals({
776
+ asset: destinationData.fee,
777
+ target: route.getDestinationFeeAssetOnSource()
778
+ });
779
+ const sourceData = await getSourceData({
780
+ route,
781
+ destinationAddress,
782
+ destinationFee,
783
+ sourceAddress
784
+ });
785
+ return {
786
+ destination: destinationData,
787
+ getEstimate(amount) {
788
+ const bigAmount = Big2(
789
+ toBigInt2(amount, sourceData.balance.decimals).toString()
790
+ );
791
+ const result = bigAmount.minus(
792
+ sourceData.balance.isSame(destinationFee) ? destinationFee.toBig() : Big2(0)
793
+ );
794
+ return sourceData.balance.copyWith({
795
+ amount: result.lt(0) ? 0n : BigInt(result.toFixed())
796
+ });
797
+ },
798
+ max: sourceData.max,
799
+ min: getMin(destinationData),
800
+ source: sourceData,
801
+ async transfer({
802
+ amount,
803
+ signers: { evmSigner, polkadotSigner },
804
+ statusCallback,
805
+ onSourceFinalized,
806
+ onSourceError,
807
+ onDestinationFinalized,
808
+ onDestinationError
809
+ }) {
810
+ const source = route.source.chain;
811
+ const destination = route.destination.chain;
812
+ const bigintAmount = toBigInt2(amount, sourceData.balance.decimals);
813
+ validateSovereignAccountBalances({
814
+ amount: bigintAmount,
815
+ destinationData,
816
+ sourceData
817
+ });
818
+ const asset = AssetAmount3.fromChainAsset(
819
+ route.source.chain.getChainAsset(route.source.asset),
820
+ { amount: bigintAmount }
821
+ );
822
+ const [sourcePolkadot, destinationPolkadot] = await PolkadotService.createMulti([source, destination]);
823
+ const contract = route.contract?.build({
824
+ asset,
825
+ destination,
826
+ destinationAddress,
827
+ destinationApi: destinationPolkadot.api,
828
+ fee: destinationFee,
829
+ source,
830
+ sourceAddress,
831
+ sourceApi: sourcePolkadot.api
832
+ });
833
+ const extrinsic = route.extrinsic?.build({
834
+ asset,
835
+ destination,
836
+ destinationAddress,
837
+ destinationApi: destinationPolkadot.api,
838
+ fee: destinationFee,
839
+ source,
840
+ sourceAddress,
841
+ sourceApi: sourcePolkadot.api
842
+ });
843
+ const shouldListenToEvents = !!onSourceFinalized || !!onSourceError || !!onDestinationFinalized || !!onDestinationError;
844
+ if (contract) {
845
+ if (!evmSigner) {
846
+ throw new Error("EVM Signer must be provided");
847
+ }
848
+ const evm = EvmService.create(source);
849
+ const hash = await evm.transfer(evmSigner, contract);
850
+ if (shouldListenToEvents) {
851
+ listenToSourceEvents({
852
+ route,
853
+ sourceAddress,
854
+ onSourceFinalized,
855
+ onSourceError,
856
+ onDestinationFinalized,
857
+ onDestinationError
858
+ });
859
+ }
860
+ return hash;
861
+ }
862
+ if (extrinsic) {
863
+ if (!polkadotSigner) {
864
+ throw new Error("Polkadot signer must be provided");
865
+ }
866
+ const monitoringCallback = shouldListenToEvents ? createMonitoringCallback({
867
+ sourceAddress,
868
+ route,
869
+ statusCallback,
870
+ onSourceFinalized,
871
+ onSourceError,
872
+ onDestinationFinalized,
873
+ onDestinationError
874
+ }) : void 0;
875
+ return sourcePolkadot.transfer(
876
+ sourceAddress,
877
+ extrinsic,
878
+ polkadotSigner,
879
+ monitoringCallback || statusCallback
880
+ );
881
+ }
882
+ throw new Error("Either contract or extrinsic must be provided");
883
+ }
884
+ };
885
+ }
886
+
887
+ // src/sdk.ts
888
+ var DEFAULT_SERVICE = new ConfigService({ routes: xcmRoutesMap });
889
+ function Sdk({ configService, ecosystem } = {}) {
890
+ const service = configService ?? DEFAULT_SERVICE;
891
+ const assets = service.getEcosystemAssets(ecosystem);
892
+ return {
893
+ assets,
894
+ setAsset(asset) {
895
+ const sources = service.getSourceChains({ asset, ecosystem });
896
+ return {
897
+ sources,
898
+ setSource(source) {
899
+ const destinations = service.getDestinationChains({
900
+ asset,
901
+ source
902
+ });
903
+ return {
904
+ destinations,
905
+ setDestination(destination) {
906
+ const route = service.getAssetRoute({
907
+ asset,
908
+ source,
909
+ destination
910
+ });
911
+ return {
912
+ setAddresses({
913
+ sourceAddress,
914
+ destinationAddress
915
+ }) {
916
+ const sourceChain = service.getChain(source);
917
+ if (!EvmParachain2.isAnyParachain(sourceChain)) {
918
+ throw new Error(
919
+ "Source chain should be a Parachain or EvmParachain"
920
+ );
921
+ }
922
+ if (!EvmParachain2.isAnyParachain(route.destination.chain)) {
923
+ throw new Error(
924
+ "Destination chain should be a Parachain or EvmParachain"
925
+ );
926
+ }
927
+ return getTransferData({
928
+ route,
929
+ sourceAddress,
930
+ destinationAddress
931
+ });
932
+ }
933
+ };
934
+ }
935
+ };
936
+ }
937
+ };
938
+ }
939
+ };
940
+ }
941
+ async function getParachainBalances(chain, address, service = DEFAULT_SERVICE) {
942
+ const routes = service.getChainRoutes(chain).getRoutes();
943
+ const balances = await getAssetsBalances({
944
+ chain,
945
+ routes,
946
+ address
947
+ });
948
+ return balances;
949
+ }
950
+
951
+ // src/utils/evm.ts
952
+ import {
953
+ encodeAbiParameters,
954
+ keccak256,
955
+ maxUint256,
956
+ numberToHex,
957
+ parseAbiParameters
958
+ } from "viem";
959
+ function getAllowanceSlot(owner, spender, allowanceSlot) {
960
+ const mappingSlot = allowanceSlot;
961
+ const outer = keccak256(
962
+ encodeAbiParameters(parseAbiParameters("address, uint256"), [
963
+ owner,
964
+ BigInt(mappingSlot)
965
+ ])
966
+ );
967
+ return keccak256(
968
+ encodeAbiParameters(parseAbiParameters("address, bytes32"), [
969
+ spender,
970
+ outer
971
+ ])
972
+ );
973
+ }
974
+ var MAX_ALLOWANCE_HEX = numberToHex(maxUint256);
975
+ export {
976
+ EvmService,
977
+ MAX_ALLOWANCE_HEX,
978
+ PolkadotService,
979
+ Sdk,
980
+ convertToChainDecimals,
981
+ createMonitoringCallback,
982
+ getAllowanceSlot,
983
+ getAssetMin,
984
+ getAssetsBalances,
985
+ getBalance,
986
+ getContractFee,
987
+ getDestinationData,
988
+ getDestinationFee,
989
+ getDestinationFeeBalance,
990
+ getExistentialDeposit,
991
+ getExtrinsicFee,
992
+ getFee,
993
+ getMax,
994
+ getMin,
995
+ getParachainBalances,
996
+ getSourceData,
997
+ listenToDestinationEvents,
998
+ listenToSourceEvents,
999
+ processSourceEvents,
1000
+ validateSovereignAccountBalances
1001
+ };
2
1002
  //# sourceMappingURL=index.mjs.map