@moonbeam-network/xcm-sdk 0.4.2 → 1.0.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.d.ts CHANGED
@@ -1,316 +1,200 @@
1
- import { ExtrinsicEventsCallback, Hash } from '@moonbeam-network/xcm-utils';
2
- export {
3
- ExtrinsicEvent,
4
- ExtrinsicEventsCallback,
5
- ExtrinsicFailedEvent,
6
- ExtrinsicSentEvent,
7
- ExtrinsicStatus,
8
- ExtrinsicSuccessEvent,
9
- } from '@moonbeam-network/xcm-utils';
10
- import { TransactionResponse } from '@ethersproject/abstract-provider';
11
1
  import {
12
- AssetSymbol,
13
- Asset,
14
- WithdrawXTokensConfig,
15
- MoonbaseAssets,
16
- MoonbaseChains,
17
- MoonbeamAssets,
18
- MoonbeamChains,
19
- MoonriverAssets,
20
- MoonriverChains,
21
- ChainKey,
22
- AssetsMap,
23
- MoonChain,
24
- Chain,
25
- BalanceConfig,
26
- MinBalanceConfig,
2
+ SubstrateQueryConfig,
27
3
  ExtrinsicConfig,
28
- XcmConfigBuilder,
29
- } from '@moonbeam-network/xcm-config';
30
- import { Signer } from 'ethers';
31
- import { ApiPromise } from '@polkadot/api';
4
+ ContractConfig,
5
+ } from '@moonbeam-network/xcm-builder';
6
+ import { TransferConfig, AssetConfig } from '@moonbeam-network/xcm-config';
32
7
  import {
33
- UnsubscribePromise,
34
- Signer as Signer$1,
35
- SubmittableExtrinsic,
36
- } from '@polkadot/api/types';
37
- import { AccountInfo } from '@polkadot/types/interfaces';
38
- import {
39
- PalletAssetsAssetMetadata,
40
- PalletAssetsAssetAccount,
41
- } from '@polkadot/types/lookup';
8
+ AnyParachain,
9
+ Asset,
10
+ AssetAmount,
11
+ ChainAssetId,
12
+ AnyChain,
13
+ Ecosystem,
14
+ } from '@moonbeam-network/xcm-types';
15
+ import { Signer as Signer$1 } from 'ethers';
16
+ import { ApiPromise } from '@polkadot/api';
17
+ import { Signer } from '@polkadot/api/types';
42
18
  import { IKeyringPair } from '@polkadot/types/types';
43
19
 
44
- declare class XTokensContract<Symbols extends AssetSymbol = AssetSymbol> {
20
+ declare class PolkadotService {
45
21
  #private;
46
- readonly address: string;
47
- constructor(signer: Signer);
22
+ readonly api: ApiPromise;
23
+ readonly chain: AnyParachain;
24
+ constructor(api: ApiPromise, chain: AnyParachain);
25
+ static create(chain: AnyParachain): Promise<PolkadotService>;
26
+ static createMulti(chains: AnyParachain[]): Promise<PolkadotService[]>;
27
+ get decimals(): number;
28
+ get asset(): Asset;
29
+ get existentialDeposit(): AssetAmount;
30
+ getAssetMeta(asset: ChainAssetId): Promise<
31
+ | {
32
+ symbol: string;
33
+ decimals: number;
34
+ }
35
+ | undefined
36
+ >;
37
+ getAssetDecimals(asset: Asset): Promise<number>;
38
+ query(config: SubstrateQueryConfig): Promise<bigint>;
39
+ getFee(account: string, config: ExtrinsicConfig): Promise<bigint>;
48
40
  transfer(
49
41
  account: string,
50
- amount: bigint,
51
- asset: Asset<Symbols>,
52
- config: WithdrawXTokensConfig<Symbols>,
53
- minAmount: bigint,
54
- ): Promise<TransactionResponse>;
55
- getTransferFees(
56
- account: string,
57
- amount: bigint,
58
- asset: Asset<Symbols>,
59
- config: WithdrawXTokensConfig<Symbols>,
60
- ): Promise<bigint>;
61
- private getGasPrice;
42
+ config: ExtrinsicConfig,
43
+ signer: Signer | IKeyringPair,
44
+ ): Promise<string>;
62
45
  }
63
46
 
64
- interface XcmSdkByChain {
65
- moonbase: MoonbaseXcmSdk;
66
- moonbeam: MoonbeamXcmSdk;
67
- moonriver: MoonriverXcmSdk;
68
- }
69
- type MoonXcmSdk = MoonbaseXcmSdk | MoonbeamXcmSdk | MoonriverXcmSdk;
70
- type MoonbaseXcmSdk = XcmSdk<MoonbaseAssets, MoonbaseChains>;
71
- type MoonbeamXcmSdk = XcmSdk<MoonbeamAssets, MoonbeamChains>;
72
- type MoonriverXcmSdk = XcmSdk<MoonriverAssets, MoonriverChains>;
73
- interface XcmSdk<
74
- Symbols extends AssetSymbol = AssetSymbol,
75
- ChainKeys extends ChainKey = ChainKey,
76
- > {
77
- symbols: Symbols[];
78
- assets: AssetsMap<Symbols>;
79
- moonAsset: Asset<Symbols>;
80
- moonChain: MoonChain;
81
- subscribeToAssetsBalanceInfo: (
82
- account: string,
83
- cb: (data: AssetBalanceInfo<Symbols>[]) => void,
84
- ) => UnsubscribePromise;
85
- deposit: (
86
- symbolOrAsset: Symbols | Asset<Symbols>,
87
- ) => XcmSdkDeposit<Symbols, ChainKeys>;
88
- withdraw: (
89
- symbolOrAsset: Symbols | Asset<Symbols>,
90
- ) => XcmSdkWithdraw<Symbols, ChainKeys>;
91
- }
92
- interface XcmSdkDeposit<
93
- Symbols extends AssetSymbol = AssetSymbol,
94
- ChainKeys extends ChainKey = ChainKey,
95
- > {
96
- chains: Chain<ChainKeys>[];
97
- from: (
98
- keyOrChain: ChainKeys | Chain<ChainKeys>,
99
- ) => XcmSdkDepositFrom<Symbols>;
100
- }
101
- interface XcmSdkWithdraw<
102
- Symbols extends AssetSymbol = AssetSymbol,
103
- ChainKeys extends ChainKey = ChainKey,
104
- > {
105
- chains: Chain<ChainKeys>[];
106
- to: (keyOrChain: ChainKeys | Chain<ChainKeys>) => XcmSdkWithdrawTo<Symbols>;
47
+ interface Signers {
48
+ ethersSigner: Signer$1;
49
+ polkadotSigner: Signer | IKeyringPair;
50
+ }
51
+ interface TransferData {
52
+ destination: DestinationChainTransferData;
53
+ getEstimate(amount: number | string): AssetAmount;
54
+ isSwapPossible: boolean;
55
+ max: AssetAmount;
56
+ min: AssetAmount;
57
+ source: SourceChainTransferData;
58
+ swap(): Promise<TransferData | undefined>;
59
+ transfer(amount: bigint | number | string): Promise<string>;
60
+ }
61
+ interface SourceChainTransferData extends ChainTransferData {
62
+ feeBalance: AssetAmount;
63
+ max: AssetAmount;
64
+ }
65
+ interface DestinationChainTransferData extends ChainTransferData {}
66
+ interface ChainTransferData {
67
+ balance: AssetAmount;
68
+ chain: AnyChain;
69
+ existentialDeposit: AssetAmount;
70
+ fee: AssetAmount;
71
+ min: AssetAmount;
107
72
  }
108
- interface XcmSdkDepositFrom<Symbols extends AssetSymbol = AssetSymbol> {
109
- get: (
110
- account: string,
111
- sourceAccount: string | IKeyringPair,
112
- params?: DepositGetParams,
113
- ) => Promise<DepositTransferData<Symbols>>;
114
- }
115
- interface DepositGetParams {
116
- polkadotSigner?: Signer$1;
117
- primaryAccount?: string;
118
- }
119
- interface XcmSdkWithdrawTo<Symbols extends AssetSymbol = AssetSymbol> {
120
- get: (
121
- destinationAccount: string,
122
- params?: WithdrawGetParams,
123
- ) => Promise<WithdrawTransferData<Symbols>>;
124
- }
125
- interface WithdrawGetParams {
126
- ethersSigner?: Signer;
127
- }
128
- interface DepositTransferData<
129
- Symbols extends AssetSymbol = AssetSymbol,
130
- ChainKeys extends ChainKey = ChainKey,
131
- > {
132
- asset: AssetWithDecimals<Symbols>;
133
- existentialDeposit: bigint;
134
- min: bigint;
135
- moonChainFee: XcmFeeWithDecimals<Symbols>;
136
- native: AssetWithDecimals<Symbols>;
137
- origin: MoonChain | Chain<ChainKeys>;
138
- source: Chain<ChainKeys>;
139
- sourceBalance: bigint;
140
- sourceAssetDecimals: number;
141
- sourceFeeBalance?: Balance<Symbols>;
142
- sourceMinBalance: bigint;
143
- getFee: (amount?: bigint) => Promise<bigint>;
144
- send: (amount: bigint, cb?: ExtrinsicEventsCallback) => Promise<Hash>;
145
- }
146
- interface WithdrawTransferData<
147
- Symbols extends AssetSymbol = AssetSymbol,
148
- ChainKeys extends ChainKey = ChainKey,
149
- > {
150
- asset: AssetWithDecimals<Symbols>;
151
- destination: Chain<ChainKeys>;
152
- destinationBalance: bigint;
153
- destinationAssetDecimals: number;
154
- destinationFee: bigint;
155
- existentialDeposit: bigint;
156
- min: bigint;
157
- minXcmFeeAsset: XcmFeeWithDecimals<Symbols>;
158
- native: AssetWithDecimals<Symbols>;
159
- origin: MoonChain | Chain<ChainKeys>;
160
- originXcmFeeAssetBalance?: bigint;
161
- getFee: (amount: bigint) => Promise<bigint>;
162
- send: (amount: bigint, cb?: ExtrinsicEventsCallback) => Promise<Hash>;
163
- }
164
- interface AssetWithDecimals<Symbols extends AssetSymbol = AssetSymbol>
165
- extends Asset<Symbols> {
166
- decimals: number;
167
- }
168
- interface XcmFeeWithDecimals<Symbols extends AssetSymbol = AssetSymbol> {
169
- amount: bigint;
170
- decimals: number;
171
- symbol: Symbols;
172
- }
173
- interface Balance<Symbols extends string | AssetSymbol = AssetSymbol> {
73
+
74
+ interface GetSourceDataParams {
75
+ transferConfig: TransferConfig;
76
+ destinationAddress: string;
77
+ destinationFee: AssetAmount;
78
+ ethersSigner: Signer$1;
79
+ polkadot: PolkadotService;
80
+ sourceAddress: string;
81
+ }
82
+ declare function getSourceData({
83
+ transferConfig,
84
+ destinationAddress,
85
+ destinationFee,
86
+ ethersSigner,
87
+ polkadot,
88
+ sourceAddress,
89
+ }: GetSourceDataParams): Promise<SourceChainTransferData>;
90
+ interface GetBalancesParams {
91
+ address: string;
92
+ balance: bigint;
93
+ config: AssetConfig;
94
+ polkadot: PolkadotService;
95
+ }
96
+ declare function getFeeBalances({
97
+ address,
98
+ balance,
99
+ config,
100
+ polkadot,
101
+ }: GetBalancesParams): Promise<bigint>;
102
+ interface GetFeeParams {
174
103
  balance: bigint;
104
+ contract?: ContractConfig;
175
105
  decimals: number;
176
- symbol: Symbols;
177
- }
178
- interface SdkOptions {
179
- ethersSigner?: Signer;
180
- polkadotSigner?: Signer$1;
181
- }
182
-
183
- declare function init(options?: SdkOptions): XcmSdkByChain;
184
-
185
- declare function isXcmSdkDeposit(
186
- config: XcmSdkDeposit | XcmSdkWithdraw,
187
- ): config is XcmSdkDeposit;
188
- declare function isXcmSdkWithdraw(
189
- config: XcmSdkDeposit | XcmSdkWithdraw,
190
- ): config is XcmSdkWithdraw;
191
- declare function isWithdrawTransferData(
192
- data?: WithdrawTransferData | DepositTransferData,
193
- ): data is WithdrawTransferData;
194
- declare function isDepositTransferData(
195
- data?: WithdrawTransferData | DepositTransferData,
196
- ): data is DepositTransferData;
197
-
198
- interface AssetBalanceInfo<
199
- Symbols extends AssetSymbol = AssetSymbol,
200
- ChainKeys extends ChainKey = ChainKey,
201
- > {
202
- asset: Asset<Symbols>;
203
- balance: Balance<string>;
204
- origin: Chain<ChainKeys> | MoonChain;
205
- }
206
- interface XCMType {
207
- Xcm: {
208
- parents: number;
209
- interior: unknown;
210
- };
211
- }
106
+ ethersSigner?: Signer$1;
107
+ extrinsic?: ExtrinsicConfig;
108
+ polkadot: PolkadotService;
109
+ sourceAddress: string;
110
+ }
111
+ declare function getFee({
112
+ balance,
113
+ contract,
114
+ decimals,
115
+ ethersSigner,
116
+ extrinsic,
117
+ polkadot,
118
+ sourceAddress,
119
+ }: GetFeeParams): Promise<bigint>;
120
+ declare function getContractFee(
121
+ balance: bigint,
122
+ config: ContractConfig,
123
+ decimals: number,
124
+ ethersSigner: Signer$1,
125
+ ): Promise<bigint>;
126
+ declare function getExtrinsicFee(
127
+ balance: bigint,
128
+ extrinsic: ExtrinsicConfig,
129
+ polkadot: PolkadotService,
130
+ sourceAddress: string,
131
+ ): Promise<bigint>;
132
+ interface GetMaxParams {
133
+ balanceAmount: AssetAmount;
134
+ existentialDeposit: AssetAmount;
135
+ feeAmount: AssetAmount;
136
+ minAmount: AssetAmount;
137
+ }
138
+ declare function getMax({
139
+ balanceAmount,
140
+ existentialDeposit,
141
+ feeAmount,
142
+ minAmount,
143
+ }: GetMaxParams): AssetAmount;
212
144
 
213
- declare class PolkadotService<
214
- Symbols extends AssetSymbol = AssetSymbol,
215
- ChainKeys extends ChainKey = ChainKey,
216
- > {
217
- #private;
218
- constructor(api: ApiPromise);
219
- static create<
220
- Symbols extends AssetSymbol = AssetSymbol,
221
- ChainKeys extends ChainKey = ChainKey,
222
- >(ws: string): Promise<PolkadotService<Symbols, ChainKeys>>;
223
- getMetadata(): {
224
- decimals: number;
225
- symbol: Symbols;
226
- ss58Format: number;
227
- genesisHash: `0x${string}`;
145
+ interface SdkOptions extends Partial<Signers> {}
146
+ declare function Sdk(options?: SdkOptions): {
147
+ assets(ecosystem?: Ecosystem): {
148
+ assets: Asset[];
149
+ asset(keyOrAsset: string | Asset): {
150
+ sourceChains: AnyChain[];
151
+ source(keyOrChain: string | AnyChain): {
152
+ destinationChains: AnyChain[];
153
+ destination(destKeyOrChain: string | AnyChain): {
154
+ accounts(
155
+ sourceAddress: string,
156
+ destinationAddress: string,
157
+ signers?: Partial<Signers>,
158
+ ): Promise<TransferData>;
159
+ };
160
+ };
161
+ };
228
162
  };
229
- getExistentialDeposit(): bigint;
230
- getAssetDecimals(asset: Asset<Symbols>): Promise<number>;
231
- getAssetMeta(asset: Asset<Symbols>): Promise<PalletAssetsAssetMetadata>;
232
- subscribeToAccountInfo(
233
- account: string,
234
- callback: (info: AccountInfo) => void,
235
- ): UnsubscribePromise;
236
- subscribeToBalance(
237
- account: string,
238
- callback: (balance: bigint) => void,
239
- ): UnsubscribePromise;
240
- getGenericBalance(
241
- account: string,
242
- { pallet, function: fn, getParams, path, calc }: BalanceConfig<Symbols>,
243
- ): Promise<bigint>;
244
- getAssetMinBalance({
245
- pallet,
246
- function: fn,
247
- params,
248
- path,
249
- }: MinBalanceConfig): Promise<bigint>;
250
- getXcmExtrinsic(
251
- account: string,
252
- amount: bigint,
253
- { pallet, extrinsic, getParams }: ExtrinsicConfig<Symbols>,
254
- fee?: bigint,
255
- primaryAccount?: string,
256
- ): SubmittableExtrinsic<'promise'>;
257
- getAssetFee(
258
- asset: Asset,
259
- weight: number,
260
- moonChain: MoonChain,
261
- ): Promise<bigint>;
262
- getUnitsPerSecond(asset: Asset, moonChain: MoonChain): Promise<bigint>;
263
- /**
264
- * this is only for Moon* chains
265
- */
266
- getAssetType(id: string): Promise<XCMType | undefined>;
267
- subscribeToAssetsBalanceInfo(
268
- account: string,
269
- config: XcmConfigBuilder<Symbols, ChainKeys>,
270
- callback: (data: AssetBalanceInfo<Symbols>[]) => void,
271
- ): UnsubscribePromise;
272
- getAssetsMetadata(
273
- assetsArray: Asset<Symbols>[],
274
- ): Promise<PalletAssetsAssetMetadata[]>;
275
- subscribeToAccountBalances(
276
- account: string,
277
- assetsArray: Asset<Symbols>[],
278
- callback: (balances: PalletAssetsAssetAccount[]) => void,
279
- ): UnsubscribePromise;
163
+ getTransferData({
164
+ destinationAddress,
165
+ destinationKeyOrChain,
166
+ ethersSigner,
167
+ keyOrAsset,
168
+ polkadotSigner,
169
+ sourceAddress,
170
+ sourceKeyOrChain,
171
+ }: SdkTransferParams): Promise<TransferData>;
172
+ };
173
+ interface SdkTransferParams extends Partial<Signers> {
174
+ destinationAddress: string;
175
+ destinationKeyOrChain: string | AnyChain;
176
+ keyOrAsset: string | Asset;
177
+ sourceAddress: string;
178
+ sourceKeyOrChain: string | AnyChain;
280
179
  }
281
180
 
282
- declare function createPolkadotServices<
283
- Symbols extends AssetSymbol,
284
- ChainKeys extends ChainKey,
285
- >(ws: string[]): Promise<PolkadotService<Symbols, ChainKeys>[]>;
286
-
287
181
  export {
288
- AssetBalanceInfo,
289
- AssetWithDecimals,
290
- Balance,
291
- DepositGetParams,
292
- DepositTransferData,
293
- MoonXcmSdk,
294
- MoonbaseXcmSdk,
295
- MoonbeamXcmSdk,
296
- MoonriverXcmSdk,
297
- PolkadotService,
182
+ ChainTransferData,
183
+ DestinationChainTransferData,
184
+ GetBalancesParams,
185
+ GetFeeParams,
186
+ GetMaxParams,
187
+ GetSourceDataParams,
188
+ Sdk,
298
189
  SdkOptions,
299
- WithdrawGetParams,
300
- WithdrawTransferData,
301
- XCMType,
302
- XTokensContract,
303
- XcmFeeWithDecimals,
304
- XcmSdk,
305
- XcmSdkByChain,
306
- XcmSdkDeposit,
307
- XcmSdkDepositFrom,
308
- XcmSdkWithdraw,
309
- XcmSdkWithdrawTo,
310
- createPolkadotServices,
311
- init,
312
- isDepositTransferData,
313
- isWithdrawTransferData,
314
- isXcmSdkDeposit,
315
- isXcmSdkWithdraw,
190
+ SdkTransferParams,
191
+ Signers,
192
+ SourceChainTransferData,
193
+ TransferData,
194
+ getContractFee,
195
+ getExtrinsicFee,
196
+ getFee,
197
+ getFeeBalances,
198
+ getMax,
199
+ getSourceData,
316
200
  };
package/build/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{ExtrinsicStatus as ls}from"@moonbeam-network/xcm-utils";import{Contract as Q}from"ethers";var X=[{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 K=class{constructor(e){this.address="0x0000000000000000000000000000000000000804";this.#s=e,this.#e=new Q(this.address,X,e)}#e;#s;async transfer(e,s,n,a,i){let{usesEthereumAccounts:o}=a.destination,r=a.getParams(e,o);return a.xcmFeeAsset?this.#e.transferMultiCurrencies([[a.xcmFeeAsset.asset.erc20Id,i],[n.erc20Id,s]],0,r,a.weight):this.#e.transfer(n.erc20Id,s,r,a.weight)}async getTransferFees(e,s,n,a){let i=(await this.#e.estimateGas.transfer(n.erc20Id,s,a.getParams(e,a.destination.usesEthereumAccounts),a.weight)).toBigInt(),o=await this.getGasPrice();return i*o}async getGasPrice(){let{gasPrice:e,maxPriorityFeePerGas:s}=await this.#s.getFeeData();return((e==null?void 0:e.toBigInt())||0n)+((s==null?void 0:s.toBigInt())||0n)}};import"@polkadot/api-augment";import{getPolkadotApi as j}from"@moonbeam-network/xcm-utils";import W from"lodash";function F(t,e){return BigInt(t)*e/BigInt(10**12)}var D=class{#e;constructor(e){this.#e=e}static async create(e){return new D(await j(e))}getMetadata(){return{decimals:this.#e.registry.chainDecimals.at(0)||12,symbol:this.#e.registry.chainTokens.at(0),ss58Format:this.#e.registry.chainSS58||42,genesisHash:this.#e.genesisHash.toHex()}}getExistentialDeposit(){var n,a;let e=(n=this.#e.consts.balances)==null?void 0:n.existentialDeposit,s=(a=this.#e.consts.eqBalances)==null?void 0:a.existentialDeposit;return(e==null?void 0:e.toBigInt())||(s==null?void 0:s.toBigInt())||0n}async getAssetDecimals(e){return(await this.getAssetMeta(e)).decimals.toNumber()}async getAssetMeta(e){return await(e.isLocalAsset?this.#e.query.localAssets.metadata:this.#e.query.assets.metadata)(e.id)}async subscribeToAccountInfo(e,s){return this.#e.query.system.account(e,s)}async subscribeToBalance(e,s){return this.subscribeToAccountInfo(e,({data:n})=>s(n.free.toBigInt()-n.miscFrozen.toBigInt()))}async getGenericBalance(e,{pallet:s,function:n,getParams:a,path:i,calc:o}){var m;let r=await this.#e.query[s][n](...a(e));if(r.isEmpty)return 0n;let l=((m=r.unwrap)==null?void 0:m.call(r))||r;return o(i.length?W.get(l,i):l)}async getAssetMinBalance({pallet:e,function:s,params:n,path:a}){let i=await this.#e.query[e][s](...n);return i.isEmpty?0n:W.get(i.value,a).toBigInt()}getXcmExtrinsic(e,s,{pallet:n,extrinsic:a,getParams:i},o,r){let l=this.#e.tx[n][a],m=i({account:e,amount:s,extrinsicCall:l,fee:o}),c=l(...m);return r&&(c=this.#e.tx.proxy.proxy(r,null,c)),c}async getAssetFee(e,s,n){return F(s,await this.getUnitsPerSecond(e,n))}async getUnitsPerSecond(e,s){if(e.isNative)return s.unitsPerSecond;let n=await this.getAssetType(e.id);return n?(await this.#e.query.assetManager.assetTypeUnitsPerSecond(n)).unwrapOrDefault().toBigInt():0n}async getAssetType(e){return(await this.#e.query.assetManager.assetIdType(e)).unwrapOr(void 0)}async subscribeToAssetsBalanceInfo(e,s,n){let a=Object.values(s.assets),i=await this.getAssetsMetadata(a);return this.subscribeToAccountBalances(e,a,o=>{n(o.map((r,l)=>{var u;let m=a[l],c=i[l],{chains:[y],from:d}=s.deposit(m.originSymbol),{origin:b}=d(y.key);return{asset:m,balance:{balance:r.balance.toBigInt(),decimals:m.isNative?b.decimals:c.decimals.toNumber(),symbol:m.isNative?m.originSymbol:((u=c.symbol.toHuman())==null?void 0:u.toString())||""},origin:b}}))})}async getAssetsMetadata(e){let s=e.map(n=>[n.isLocalAsset?this.#e.query.localAssets.metadata:this.#e.query.assets.metadata,[n.id]]);return this.#e.queryMulti(s)}async subscribeToAccountBalances(e,s,n){let a=s.map(i=>[i.isLocalAsset?this.#e.query.localAssets.account:this.#e.query.assets.account,[i.id,e]]);return this.#e.queryMulti(a,i=>{let o=i.map(r=>r.unwrapOrDefault());n(o)})}};async function v(t){return Promise.all(t.map(e=>D.create(e)))}import{moonbase as ne,moonbeam as ae,moonriver as ie}from"@moonbeam-network/xcm-config";import re from"lodash";import{convertDecimals as R,createExtrinsicEventHandler as z}from"@moonbeam-network/xcm-utils";import{isUndefined as _}from"@polkadot/util";function J({account:t,config:e,foreignPolkadot:s,primaryAccount:n,fee:a}){return i=>s.getXcmExtrinsic(t,i,e.extrinsic,a,n)}async function q({account:t,asset:e,config:s,foreignPolkadot:n,moonChain:a,nativeAsset:i,origin:o,polkadot:r,polkadotSigner:l,primaryAccount:m,sourceAccount:c}){var B,x,k;let y=typeof c=="string"?c:c.address,d=n.getMetadata(),b={asset:((B=s.xcmFeeAsset)==null?void 0:B.asset)??e,balance:((x=s.xcmFeeAsset)==null?void 0:x.balance)??s.balance},[u,h,f,S,A=0n,p,g]=await Promise.all([e.isNative?a.decimals:r.getAssetDecimals(e),n.getExistentialDeposit(),n.getGenericBalance(m||y,s.balance),s.sourceFeeBalance?n.getGenericBalance(y,s.sourceFeeBalance):void 0,s.sourceMinBalance?n.getAssetMinBalance(s.sourceMinBalance):void 0,r.getAssetFee(b.asset,s.source.weight,a),r.getAssetDecimals(b.asset)]),C=((k=s.source.assetsDecimals)==null?void 0:k[e.originSymbol])||u,T=s.xcmFeeAsset?0n:p,M=u!==C?R(p,u,C):p,P=J({account:t,config:s,foreignPolkadot:n,primaryAccount:m,fee:M});return{asset:{...e,decimals:u},existentialDeposit:h,min:T,moonChainFee:{amount:p,decimals:b.asset.isNative?a.decimals:g,symbol:b.asset.originSymbol},native:{...i,decimals:d.decimals},origin:o,source:{...s.source},sourceBalance:f,sourceAssetDecimals:C,sourceFeeBalance:_(S)?void 0:{...d,balance:S},sourceMinBalance:A,getFee:async(w=f)=>(await P(w).paymentInfo(c,{nonce:-1})).partialFee.toBigInt(),send:async(w,I)=>(await P(w).signAndSend(c,{signer:l,nonce:-1},I&&z(s.extrinsic.pallet,s.extrinsic.successEvent,I))).toString()}}function V(t){return!!t.from}function Y(t){return!!t.to}function Z(t){return!!(t!=null&&t.destination)}function $(t){return!!(t!=null&&t.moonChainFee)}function ee(t,e){if(t.asset.isNative)return-1;if(e.asset.isNative)return 1;if(t.balance.balance||e.balance.balance)return Number(e.balance.balance-t.balance.balance);let s=(t.origin.name+t.asset.originSymbol).toLowerCase(),n=(e.origin.name+e.asset.originSymbol).toLowerCase();return s<n?-1:s>n?1:0}async function G({account:t,polkadot:e,configBuilder:s,cb:n}){let a=0n,i=[],o=m=>{let c=typeof m=="bigint";a=c?m:a,i=(c?i:m).map(y=>(y.asset.isNative&&(y.balance.balance=a),y)).sort(ee),i.length&&n(i)},r=await e.subscribeToBalance(t,o),l=await e.subscribeToAssetsBalanceInfo(t,s,o);return()=>{r(),l()}}function N(t){return{id:"",erc20Id:"",originSymbol:t}}import{createTxEventHandler as se}from"@moonbeam-network/xcm-utils";async function U({asset:t,config:e,contract:s,originAccount:n,destinationAccount:a,destinationPolkadot:i,ethersSigner:o,moonChain:r,nativeAsset:l,origin:m,polkadot:c}){var M,P,B;let y=i.getMetadata(),d=((M=e.xcmFeeAsset)==null?void 0:M.asset)??t,[b,u,h,f,S,A,p]=await Promise.all([t.isNative?r.decimals:c.getAssetDecimals(t),e.xcmFeeAsset?await c.getGenericBalance(n,(P=e.xcmFeeAsset)==null?void 0:P.balance.origin):void 0,i.getGenericBalance(a,e.balance),e.xcmFeeAsset?i.getGenericBalance(a,e.xcmFeeAsset.balance.destination):void 0,t.isNative?0n:i.getExistentialDeposit(),e.sourceMinBalance?i.getAssetMinBalance(e.sourceMinBalance):0n,c.getAssetDecimals(d)]),g=te(A,e),C=e.xcmFeeAsset?0n:O(A||S,h,g),T=e.xcmFeeAsset&&f!==void 0?O(A||S,f,g):0n;return{asset:{...t,decimals:b},destination:{...e.destination},destinationBalance:h,destinationAssetDecimals:((B=e.destination.assetsDecimals)==null?void 0:B[t.originSymbol])||b,destinationFee:g,existentialDeposit:S,min:C,minXcmFeeAsset:{amount:T,decimals:p,symbol:d.originSymbol},native:{...l,decimals:y.decimals},origin:m,originXcmFeeAssetBalance:u,getFee:async x=>s.getTransferFees(a,x,t,e),send:async(x,k)=>{let w=await s.transfer(a,x,t,e,T);return k&&se(o,w.hash,k),w.hash}}}function te(t,e){let s=BigInt(e.weight*e.feePerWeight);return t>s?t:s}function O(t,e,s){let n=e>=t?0n:t-e;return s+n}function ts(t){return{moonbase:E(ne,t),moonbeam:E(ae,t),moonriver:E(ie,t)}}function E(t,e){let{symbols:s,assets:n,moonAsset:a,moonChain:i}=t;return{symbols:s,assets:n,moonAsset:a,moonChain:i,subscribeToAssetsBalanceInfo:async(o,r)=>{let[l]=await v([t.moonChain.ws]);return G({account:o,polkadot:l,configBuilder:t,cb:r})},deposit:o=>{let{chains:r,from:l}=t.deposit(o);return{chains:r,from:m=>{let{asset:c,origin:y,config:d}=l(m);return{get:async(b,u,{primaryAccount:h,polkadotSigner:f}={})=>{let S=f||(e==null?void 0:e.polkadotSigner);if(re.isString(u)&&!S)throw new Error("Polkadot Signer/KeyringPair are not provided to XCM-SDK");let[A,p]=await v([t.moonChain.ws,d.source.ws]),g=p.getMetadata(),C=t.assets[g.symbol]||N(g.symbol);return q({account:b,asset:c,config:d,foreignPolkadot:p,moonChain:i,nativeAsset:C,origin:y,polkadot:A,polkadotSigner:S,primaryAccount:h,sourceAccount:u})}}}}},withdraw:o=>{let{chains:r,to:l}=t.withdraw(o);return{chains:r,to:m=>{let{asset:c,origin:y,config:d}=l(m);return{get:async(b,{ethersSigner:u}={})=>{let h=u||(e==null?void 0:e.ethersSigner);if(!h)throw new Error("Ethers signer is not provided to XCM-SDK");let f=await h.getAddress(),S=new K(h),[A,p]=await v([t.moonChain.ws,d.destination.ws]),g=p.getMetadata(),C=t.assets[g.symbol];return U({asset:c,config:d,contract:S,originAccount:f,destinationAccount:b,destinationPolkadot:p,ethersSigner:h,moonChain:i,nativeAsset:C,origin:y,polkadot:A})}}}}}}}export{ls as ExtrinsicStatus,D as PolkadotService,K as XTokensContract,v as createPolkadotServices,ts as init,$ as isDepositTransferData,Z as isWithdrawTransferData,V as isXcmSdkDeposit,Y as isXcmSdkWithdraw};
1
+ import{AssetAmount as q}from"@moonbeam-network/xcm-types";import{convertDecimals as U}from"@moonbeam-network/xcm-utils";import W from"big.js";import{Contract as $}from"ethers";var F=[{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 x=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=new $(this.address,F,e)}async getBalance(){return(await this.#e.balanceOf(...this.#t.args)).toBigInt()}};import{Contract as L}from"ethers";var G=[{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 S=class{address="0x0000000000000000000000000000000000000804";#t;#e;#n;constructor(t,e){this.#t=t,this.#n=e,this.#e=new L(this.address,G,e)}async transfer(){return this.#e[this.#t.func](...this.#t.args)}async getFee(t){if(t===0n)return 0n;try{let e=(await this.#e.estimateGas[this.#t.func](...this.#t.args)).toBigInt(),n=await this.getGasPrice();return e*n}catch(e){return console.error(e),0n}}async getGasPrice(){let{gasPrice:t,maxPriorityFeePerGas:e}=await this.#n.getFeeData();return((t==null?void 0:t.toBigInt())||0n)+((e==null?void 0:e.toBigInt())||0n)}};function g(a,t){if(a.module==="Erc20")return new x(a,t);if(a.module==="Xtokens")return new S(a,t);throw new Error(`Contract ${a.module} not found`)}import{CallType as H}from"@moonbeam-network/xcm-builder";import{toBigInt as J}from"@moonbeam-network/xcm-utils";async function B({address:a,config:t,ethersSigner:e,polkadot:n}){let r=t.balance.build({address:a,asset:n.chain.getBalanceAssetId(t.asset)});return r.type===H.Substrate?n.query(r):g(r,e).getBalance()}async function T(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 J(e,n)}return 0n}async function O({transferConfig:a,destinationAddress:t,destinationFee:e,ethersSigner:n,polkadot:r,sourceAddress:s}){var M,E,k;let{asset:i,destination:m,source:{chain:o,config:c}}=a,f=q.fromAsset(i,{amount:0n,decimals:await r.getAssetDecimals(i)}),l=(M=c.fee)!=null&&M.asset?q.fromAsset(c.fee.asset,{amount:0n,decimals:await r.getAssetDecimals(c.fee.asset)}):f,u=await B({address:s,config:c,ethersSigner:n,polkadot:r}),p=await V({address:s,balance:u,config:c,polkadot:r}),A=await T(c,r),b=(E=c.extrinsic)==null?void 0:E.build({address:t,amount:u,asset:o.getAssetId(i),destination:m.chain,fee:e.amount,feeAsset:o.getAssetId(e),palletInstance:o.getAssetPalletInstance(i),source:o}),C=(k=c.contract)==null?void 0:k.build({address:t,amount:u,asset:o.getAssetId(i),destination:m.chain,fee:e.amount,feeAsset:o.getAssetId(e)}),P=await Y({balance:u,contract:C,decimals:l.decimals,ethersSigner:n,extrinsic:b,polkadot:r,sourceAddress:s}),h=f.copyWith({amount:u}),{existentialDeposit:w}=r,D=l.copyWith({amount:P}),z=l.copyWith({amount:p}),v=f.copyWith({amount:A}),N=et({balanceAmount:h,existentialDeposit:w,feeAmount:D,minAmount:v});return{balance:h,chain:o,existentialDeposit:w,fee:D,feeBalance:z,max:N,min:v}}async function V({address:a,balance:t,config:e,polkadot:n}){return e.fee?n.query(e.fee.balance.build({address:a,asset:n.chain.getBalanceAssetId(e.fee.asset)})):t}async function Y({balance:a,contract:t,decimals:e,ethersSigner:n,extrinsic:r,polkadot:s,sourceAddress:i}){if(t){if(!n)throw new Error("Ethers signer must be provided");return Z(a,t,e,n)}if(r)return tt(a,r,s,i);throw new Error("Either contract or extrinsic must be provided")}async function Z(a,t,e,n){let s=await g(t,n).getFee(a);return U(s,18,e)}async function tt(a,t,e,n){try{return await e.getFee(n,t)}catch(r){if(a)throw r;return 0n}}function et({balanceAmount:a,existentialDeposit:t,feeAmount:e,minAmount:n}){let r=a.toBig().minus(n.toBig()).minus(a.isSame(t)?t.toBig():W(0)).minus(a.isSame(e)?e.toBig():W(0));return a.copyWith({amount:r.lt(0)?0n:BigInt(r.toFixed())})}import{ConfigBuilder as K}from"@moonbeam-network/xcm-config";import{convertDecimals as pt,toBigInt as R}from"@moonbeam-network/xcm-utils";import y from"big.js";import"@polkadot/api-augment";import{assetsMap as nt,darwiniaPangoro as at,eq as rt,equilibriumAlphanet as st,paring as it}from"@moonbeam-network/xcm-config";import{AssetAmount as ot}from"@moonbeam-network/xcm-types";import{getPolkadotApi as ct}from"@moonbeam-network/xcm-utils";var d=class{api;chain;constructor(t,e){this.api=t,this.chain=e}static async create(t){return new d(await ct(t.ws),t)}static async createMulti(t){return Promise.all(t.map(d.create))}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"&&this.chain.key===st.key)return rt;if(e==="oring"&&this.chain.key===at.key)return it;if(!e)throw new Error("No native symbol key found");let n=nt.get(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 ot.fromAsset(this.asset,{amount:n,decimals:this.decimals})}async getAssetMeta(t){var s,i,m,o,c;let e=((s=this.api.query.assets)==null?void 0:s.metadata)||((i=this.api.query.assetRegistry)==null?void 0:i.metadata)||((m=this.api.query.assetRegistry)==null?void 0:m.currencyMetadatas)||((o=this.api.query.assetRegistry)==null?void 0:o.assetMetadatas)||((c=this.api.query.assetRegistry)==null?void 0:c.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 getAssetDecimals(t){var e;return((e=await this.getAssetMeta(this.chain.getMetadataAssetId(t)))==null?void 0:e.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 _}from"@moonbeam-network/xcm-types";import{toBigInt as mt}from"@moonbeam-network/xcm-utils";async function Q({transferConfig:a,destinationAddress:t,ethersSigner:e,polkadot:n}){let{asset:r,destination:{chain:s,config:i}}=a,m=_.fromAsset(r,{amount:0n,decimals:await n.getAssetDecimals(r)}),o=await B({address:t,config:i,ethersSigner:e,polkadot:n}),c=await T(i,n),f=m.copyWith({amount:o}),{existentialDeposit:l}=n,u=await ut({config:a,polkadot:n}),p=m.copyWith({amount:c});return{balance:f,chain:s,existentialDeposit:l,fee:u,min:p}}async function ut({config:a,polkadot:t}){let{amount:e,asset:n}=a.source.config.destinationFee,r=await t.getAssetDecimals(n),s=_.fromAsset(n,{amount:0n,decimals:r});if(Number.isFinite(e))return s.copyWith({amount:mt(e,r)});let i=e.build({api:t.api,asset:t.chain.getAssetId(n)});return s.copyWith({amount:await i.call()})}async function I({destinationAddress:a,ethersSigner:t,polkadotSigner:e,sourceAddress:n,transferConfig:r}){if(!t)throw new Error("Ethers signer must be provided");let[s,i]=await d.createMulti([r.destination.chain,r.source.chain]),m=await Q({destinationAddress:a,ethersSigner:t,polkadot:s,transferConfig:r}),o=await lt(i,m.fee),c=await O({destinationAddress:a,destinationFee:o,ethersSigner:t,polkadot:i,sourceAddress:n,transferConfig:r});return{destination:m,getEstimate(f){let u=y(R(f,c.balance.decimals).toString()).minus(c.balance.isSame(o)?o.toBig():y(0));return c.balance.copyWith({amount:u.lt(0)?0n:BigInt(u.toFixed())})},isSwapPossible:!0,max:c.max,min:ft(m),source:c,async swap(){return I({destinationAddress:n,ethersSigner:t,polkadotSigner:e,sourceAddress:a,transferConfig:{...r,destination:r.source,source:r.destination}})},async transfer(f){var P,h;let l=R(f,c.balance.decimals),{asset:u,source:{chain:p,config:A}}=r,b=(P=A.contract)==null?void 0:P.build({address:a,amount:l,asset:p.getAssetId(u),destination:m.chain,fee:o.amount,feeAsset:p.getAssetId(o)}),C=(h=A.extrinsic)==null?void 0:h.build({address:a,amount:l,asset:p.getAssetId(u),destination:m.chain,fee:o.amount,feeAsset:p.getAssetId(o),palletInstance:p.getAssetPalletInstance(u),source:p});if(b){if(!t)throw new Error("Ethers signer must be provided");return g(b,t).transfer().then(w=>w.hash)}if(C){if(!e)throw new Error("Polkadot signer must be provided");return i.transfer(n,C,e)}throw new Error("Either contract or extrinsic must be provided")}}}function ft({balance:a,existentialDeposit:t,fee:e,min:n}){let r=y(0).plus(a.isSame(e)?e.toBig():y(0)).plus(a.isSame(t)&&a.toBig().lt(t.toBig())?t.toBig():y(0)).plus(a.toBig().lt(n.toBig())?n.toBig():y(0));return a.copyWith({amount:BigInt(r.toFixed())})}async function lt(a,t){let e=await a.getAssetDecimals(t);return t.decimals===e?t:t.copyWith({amount:pt(t.amount,t.decimals,e),decimals:e})}function Ce(a){return{assets(t){let{assets:e,asset:n}=K().assets(t);return{assets:e,asset(r){let{sourceChains:s,source:i}=n(r);return{sourceChains:s,source(m){let{destinationChains:o,destination:c}=i(m);return{destinationChains:o,destination(f){return{async accounts(l,u,p){return I({...a,...p,destinationAddress:u,sourceAddress:l,transferConfig:c(f).build()})}}}}}}}}},async getTransferData({destinationAddress:t,destinationKeyOrChain:e,ethersSigner:n,keyOrAsset:r,polkadotSigner:s,sourceAddress:i,sourceKeyOrChain:m}){return I({destinationAddress:t,ethersSigner:n,polkadotSigner:s,sourceAddress:i,transferConfig:K().assets().asset(r).source(m).destination(e).build()})}}}export{Ce as Sdk,Z as getContractFee,tt as getExtrinsicFee,Y as getFee,V as getFeeBalances,et as getMax,O as getSourceData};
2
2
  //# sourceMappingURL=index.mjs.map