@moonbeam-network/xcm-utils 1.0.0-dev.28 → 1.0.0-dev.280

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/LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright 2022 PureStake
1
+ Copyright 2024 Moonbeam Foundation
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
4
 
package/README.md CHANGED
@@ -1,9 +1,20 @@
1
- ![Moonbeam](https://docs.moonbeam.network/images/builders/interoperability/xcm/sdk/xcm-sdk-banner.png)
1
+ The Utils package contains the utility functions for the Moonbeam XCM SDK and MRL SDK.
2
2
 
3
- The Moonbeam XCM SDK enables developers to easily deposit and withdraw assets to Moonbeam/Moonriver from the relay chain and other parachains in the Polkadot/Kusama ecosystem. With the SDK, you don't need to worry about determining the multilocation of the origin or destination assets or which extrinsics are used on which networks to send XCM transfers. To deposit or withdraw assets, you simply define the asset and origin chain you want to deposit from or withdraw back to, along with the sending account's signer, and the amount to send.
3
+ # Documentation for the Moonbeam XCM SDK
4
4
 
5
- # Documentation
5
+ ## v3 (current)
6
6
 
7
- ## v1 (current)
7
+ ### Usage
8
8
 
9
- - TODO: (coming soon)
9
+ - [XCM SDK](https://moonbeam-foundation.github.io/xcm-sdk/latest/example-usage/xcm)
10
+ - [MRL SDK](https://moonbeam-foundation.github.io/xcm-sdk/latest/example-usage/mrl)
11
+
12
+ ### References
13
+
14
+ - [XCM SDK](https://moonbeam-foundation.github.io/xcm-sdk/latest/reference/xcm)
15
+ - [MRL SDK](https://moonbeam-foundation.github.io/xcm-sdk/latest/reference/mrl)
16
+
17
+ ## v2 (previous)
18
+
19
+ - [usage](https://moonbeam-foundation.github.io/xcm-sdk/v2/example-usage)
20
+ - [references](https://moonbeam-foundation.github.io/xcm-sdk/v2/reference/interfaces)
package/build/index.d.ts CHANGED
@@ -1,35 +1,45 @@
1
1
  import { RoundingMode } from 'big.js';
2
2
  import { ApiPromise } from '@polkadot/api';
3
3
 
4
- declare function formatAssetIdToERC20(id: string): string;
4
+ declare function isHexString(asset: unknown): boolean;
5
+ declare function isEthAddress(address: string): boolean;
5
6
 
6
- declare function toDecimal(
7
- number: bigint | number | string,
8
- decimals: number,
9
- maxDecimal?: number,
10
- roundType?: RoundingMode,
11
- ): string;
12
- declare function toBigInt(
13
- amount: bigint | string | number,
14
- decimals: number,
15
- ): bigint;
16
- declare function convertDecimals(
17
- number: string | bigint,
18
- decimals: number,
19
- targetDecimals: number,
20
- ): bigint;
21
- declare function hasDecimalOverflow(
22
- fl: number | string,
23
- maxDecimal: number,
24
- ): boolean;
7
+ declare function formatAssetIdToERC20(id: string): string;
8
+ declare function convertAddressTo32Bytes(address: string): string;
25
9
 
26
- declare function getPolkadotApi(ws: string): Promise<ApiPromise>;
10
+ declare function toDecimal(number: bigint | number | string, decimals: number, maxDecimal?: number, roundType?: RoundingMode): string;
11
+ declare function toBigInt(amount: bigint | string | number, decimals: number): bigint;
12
+ declare function convertDecimals(number: string | bigint, decimals: number, targetDecimals: number): bigint;
13
+ declare function hasDecimalOverflow(fl: number | string, maxDecimal: number): boolean;
27
14
 
28
- export {
29
- convertDecimals,
30
- formatAssetIdToERC20,
31
- getPolkadotApi,
32
- hasDecimalOverflow,
33
- toBigInt,
34
- toDecimal,
15
+ /**
16
+ * reference: https://github.com/Moonsong-Labs/xcm-tools/blob/main/scripts/calculate-sovereign-account.ts
17
+ */
18
+ declare function getSovereignAccountAddresses(paraId: number): {
19
+ generic: string;
20
+ moonbeam: string;
21
+ relay: string;
22
+ };
23
+ /**
24
+ * reference: https://github.com/Moonsong-Labs/xcm-tools/blob/main/scripts/calculate-multilocation-derivative-account.ts
25
+ */
26
+ declare function getMultilocationDerivedAddresses({ paraId, address, isParents, }: {
27
+ paraId?: number;
28
+ address: string;
29
+ isParents?: boolean;
30
+ }): {
31
+ address20: `0x${string}`;
32
+ address32: `0x${string}`;
35
33
  };
34
+
35
+ declare enum MRLTypes {
36
+ XcmVersionedMultiLocation = "XcmVersionedMultiLocation",
37
+ XcmVersionedLocation = "XcmVersionedLocation",
38
+ XcmRoutingUserAction = "XcmRoutingUserAction",
39
+ VersionedUserAction = "VersionedUserAction"
40
+ }
41
+ declare function getPolkadotApi(ws: string | string[]): Promise<ApiPromise>;
42
+
43
+ declare function getPolkadotAppsUrl(ws: string): string;
44
+
45
+ export { MRLTypes, convertAddressTo32Bytes, convertDecimals, formatAssetIdToERC20, getMultilocationDerivedAddresses, getPolkadotApi, getPolkadotAppsUrl, getSovereignAccountAddresses, hasDecimalOverflow, isEthAddress, isHexString, toBigInt, toDecimal };
package/build/index.mjs CHANGED
@@ -1,2 +1,162 @@
1
- function b(t){if(t.startsWith("0x"))return t;if(!/^\d{38,39}$/.test(t))throw new Error(`Asset id: ${t} must be a string and have 38-39 digits`);return`0xffffffff${BigInt(t).toString(16).padStart(32,"0")}`}import i from"big.js";i.NE=-18;function p(t,r,n=6,o){let s=i(t.toString().replace(/[^0-9]/g,"")),m=i(10).pow(r);return s.div(m).round(n,o).toString()}function u(t,r){if(typeof t=="bigint")return t;let n=i(10).pow(r),o=i(t).mul(n);return BigInt(o.toFixed(0,i.roundDown))}function h(t,r,n){let o=p(t,r,r);return u(o.toString(),n)}function A(t,r){let n=t.toString().split(".");return n.length>1&&n[1].length>r}import{ApiPromise as g,WsProvider as f}from"@polkadot/api";import{typesBundle as c}from"@polkadot/apps-config";import a from"lru-cache";var e=new a({max:20,dispose:async t=>{let r=await t;r.isConnected&&r.disconnect()}});async function E(t){let r=e.get(t)||g.create({noInitWarn:!0,provider:new f(t),typesBundle:c});e.set(t,r);let n=await r;return await n.isReady,n}export{h as convertDecimals,b as formatAssetIdToERC20,E as getPolkadotApi,A as hasDecimalOverflow,u as toBigInt,p as toDecimal};
1
+ // src/format/address.ts
2
+ function isHexString(asset) {
3
+ return typeof asset === "string" && asset.startsWith("0x");
4
+ }
5
+ function isEthAddress(address) {
6
+ return address.length === 42 && address.startsWith("0x");
7
+ }
8
+
9
+ // src/format/asset.ts
10
+ function formatAssetIdToERC20(id) {
11
+ if (id.startsWith("0x")) {
12
+ return id;
13
+ }
14
+ if (!/^\d{38,39}$/.test(id)) {
15
+ throw new Error(`Asset id: ${id} must be a string and have 38-39 digits`);
16
+ }
17
+ return `0xffffffff${BigInt(id).toString(16).padStart(32, "0")}`;
18
+ }
19
+ function convertAddressTo32Bytes(address) {
20
+ if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {
21
+ throw new Error(`Invalid address: ${address}`);
22
+ }
23
+ return `0x000000000000000000000000${address.substring(2)}`;
24
+ }
25
+
26
+ // src/numbers/decimals.ts
27
+ import Big from "big.js";
28
+ Big.NE = -18;
29
+ function toDecimal(number, decimals, maxDecimal = 6, roundType) {
30
+ const dividend = Big(number.toString().replace(/[^0-9]/g, ""));
31
+ const divisor = Big(10).pow(decimals);
32
+ const result = dividend.div(divisor).round(maxDecimal, roundType);
33
+ return result.toString();
34
+ }
35
+ function toBigInt(amount, decimals) {
36
+ if (typeof amount === "bigint") {
37
+ return amount;
38
+ }
39
+ const multiplier = Big(10).pow(decimals);
40
+ const result = Big(amount).mul(multiplier);
41
+ return BigInt(result.toFixed(0, Big.roundDown));
42
+ }
43
+ function convertDecimals(number, decimals, targetDecimals) {
44
+ const decimalNumber = toDecimal(number, decimals, decimals);
45
+ return toBigInt(decimalNumber.toString(), targetDecimals);
46
+ }
47
+ function hasDecimalOverflow(fl, maxDecimal) {
48
+ const parts = fl.toString().split(".");
49
+ return parts.length > 1 && parts[1].length > maxDecimal;
50
+ }
51
+
52
+ // src/polkadot/polkadot.address.ts
53
+ import {
54
+ bnToU8a,
55
+ compactToU8a,
56
+ hexToU8a,
57
+ stringToU8a,
58
+ u8aToHex
59
+ } from "@polkadot/util";
60
+ import { blake2AsU8a, decodeAddress } from "@polkadot/util-crypto";
61
+ function getSovereignAccountAddresses(paraId) {
62
+ const paraIdU8a = bnToU8a(paraId, { bitLength: 32 });
63
+ const relay = u8aToHex(
64
+ new Uint8Array([...stringToU8a("para"), ...paraIdU8a])
65
+ ).padEnd(66, "0");
66
+ const generic = u8aToHex(
67
+ new Uint8Array([...stringToU8a("sibl"), ...paraIdU8a])
68
+ ).padEnd(66, "0");
69
+ const moonbeam = generic.slice(0, 42);
70
+ return {
71
+ generic,
72
+ moonbeam,
73
+ relay
74
+ };
75
+ }
76
+ function getMultilocationDerivedAddresses({
77
+ paraId,
78
+ address,
79
+ isParents = false
80
+ }) {
81
+ const parents = isParents ? 1 : 0;
82
+ const accType = isEthAddress(address) ? "AccountKey20" : "AccountId32";
83
+ const decodedAddress = isEthAddress(address) ? hexToU8a(address) : decodeAddress(address);
84
+ const family = parents === 0 && paraId ? "ChildChain" : parents === 1 && !paraId ? "ParentChain" : "SiblingChain";
85
+ const blake = blake2AsU8a(
86
+ new Uint8Array([
87
+ ...stringToU8a(family),
88
+ ...paraId ? compactToU8a(paraId) : [],
89
+ ...compactToU8a(accType.length + (isEthAddress(address) ? 20 : 32)),
90
+ ...stringToU8a(accType),
91
+ ...decodedAddress
92
+ ])
93
+ );
94
+ const address20 = u8aToHex(blake.slice(0, 20));
95
+ const address32 = u8aToHex(blake.slice(0, 32));
96
+ return {
97
+ address20,
98
+ address32
99
+ };
100
+ }
101
+
102
+ // src/polkadot/polkadot.api.ts
103
+ import { ApiPromise, WsProvider } from "@polkadot/api";
104
+ import { typesBundle } from "@polkadot/apps-config";
105
+ import { LRUCache } from "lru-cache";
106
+ var MRLTypes = /* @__PURE__ */ ((MRLTypes2) => {
107
+ MRLTypes2["XcmVersionedMultiLocation"] = "XcmVersionedMultiLocation";
108
+ MRLTypes2["XcmVersionedLocation"] = "XcmVersionedLocation";
109
+ MRLTypes2["XcmRoutingUserAction"] = "XcmRoutingUserAction";
110
+ MRLTypes2["VersionedUserAction"] = "VersionedUserAction";
111
+ return MRLTypes2;
112
+ })(MRLTypes || {});
113
+ var cache = new LRUCache({
114
+ max: 20,
115
+ dispose: async (promise) => {
116
+ const api = await promise;
117
+ if (api.isConnected) {
118
+ api.disconnect();
119
+ }
120
+ }
121
+ });
122
+ async function getPolkadotApi(ws) {
123
+ const key = Array.isArray(ws) ? ws.join(";") : ws;
124
+ const promise = cache.get(key) || ApiPromise.create({
125
+ noInitWarn: true,
126
+ provider: new WsProvider(ws),
127
+ types: {
128
+ ["XcmRoutingUserAction" /* XcmRoutingUserAction */]: {
129
+ destination: "XcmVersionedLocation" /* XcmVersionedLocation */
130
+ },
131
+ ["VersionedUserAction" /* VersionedUserAction */]: {
132
+ _enum: { V1: "XcmRoutingUserAction" /* XcmRoutingUserAction */ }
133
+ }
134
+ },
135
+ typesBundle
136
+ });
137
+ cache.set(key, promise);
138
+ const api = await promise;
139
+ await api.isReady;
140
+ return api;
141
+ }
142
+
143
+ // src/polkadot/polkadot.apps.ts
144
+ function getPolkadotAppsUrl(ws) {
145
+ return `https://polkadot.js.org/apps/?rpc=${encodeURIComponent(ws)}#/explorer/query`;
146
+ }
147
+ export {
148
+ MRLTypes,
149
+ convertAddressTo32Bytes,
150
+ convertDecimals,
151
+ formatAssetIdToERC20,
152
+ getMultilocationDerivedAddresses,
153
+ getPolkadotApi,
154
+ getPolkadotAppsUrl,
155
+ getSovereignAccountAddresses,
156
+ hasDecimalOverflow,
157
+ isEthAddress,
158
+ isHexString,
159
+ toBigInt,
160
+ toDecimal
161
+ };
2
162
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/format/asset.ts","../src/numbers/decimals.ts","../src/polkadot/polkadot.api.ts"],"sourcesContent":["export function formatAssetIdToERC20(id: string) {\n if (id.startsWith('0x')) {\n return id;\n }\n\n if (!/^\\d{38,39}$/.test(id)) {\n throw new Error(`Asset id: ${id} must be a string and have 38-39 digits`);\n }\n\n return `0xffffffff${BigInt(id).toString(16).padStart(32, '0')}`;\n}\n","import Big, { RoundingMode } from 'big.js';\n\nBig.NE = -18;\n\nexport function toDecimal(\n number: bigint | number | string,\n decimals: number,\n maxDecimal = 6,\n roundType?: RoundingMode,\n): string {\n const dividend = Big(number.toString().replace(/[^0-9]/g, ''));\n const divisor = Big(10).pow(decimals);\n const result = dividend.div(divisor).round(maxDecimal, roundType);\n\n return result.toString();\n}\n\nexport function toBigInt(\n amount: bigint | string | number,\n decimals: number,\n): bigint {\n if (typeof amount === 'bigint') {\n return amount;\n }\n\n const multiplier = Big(10).pow(decimals);\n const result = Big(amount).mul(multiplier);\n\n return BigInt(result.toFixed(0, Big.roundDown));\n}\n\nexport function convertDecimals(\n number: string | bigint,\n decimals: number,\n targetDecimals: number,\n): bigint {\n const decimalNumber = toDecimal(number, decimals, decimals);\n\n return toBigInt(decimalNumber.toString(), targetDecimals);\n}\n\nexport function hasDecimalOverflow(fl: number | string, maxDecimal: number) {\n const parts = fl.toString().split('.');\n return parts.length > 1 && parts[1].length > maxDecimal;\n}\n","import { ApiPromise, WsProvider } from '@polkadot/api';\nimport { typesBundle } from '@polkadot/apps-config';\nimport LRU from 'lru-cache';\n\nconst cache = new LRU<string, Promise<ApiPromise>>({\n max: 20,\n // eslint-disable-next-line sort-keys\n dispose: async (promise: Promise<ApiPromise>) => {\n const api = await promise;\n\n if (api.isConnected) {\n api.disconnect();\n }\n },\n});\n\nexport async function getPolkadotApi(ws: string): Promise<ApiPromise> {\n const promise =\n cache.get(ws) ||\n ApiPromise.create({\n noInitWarn: true,\n provider: new WsProvider(ws),\n typesBundle,\n });\n\n cache.set(ws, promise);\n\n const api = await promise;\n\n await api.isReady;\n\n return api;\n}\n"],"mappings":"AAAO,SAASA,EAAqBC,EAAY,CAC/C,GAAIA,EAAG,WAAW,IAAI,EACpB,OAAOA,EAGT,GAAI,CAAC,cAAc,KAAKA,CAAE,EACxB,MAAM,IAAI,MAAM,aAAaA,0CAA2C,EAG1E,MAAO,aAAa,OA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E,EAC3B,YAAAN,CACF,CAAC,EAEHE,EAAM,IAAII,EAAIH,CAAO,EAErB,IAAMC,EAAM,MAAMD,EAElB,aAAMC,EAAI,QAEHA,CACT","names":["formatAssetIdToERC20","id","Big","toDecimal","number","decimals","maxDecimal","roundType","dividend","divisor","toBigInt","amount","multiplier","result","convertDecimals","targetDecimals","decimalNumber","hasDecimalOverflow","fl","parts","ApiPromise","WsProvider","typesBundle","LRU","cache","promise","api","getPolkadotApi","ws"]}
1
+ {"version":3,"sources":["../src/format/address.ts","../src/format/asset.ts","../src/numbers/decimals.ts","../src/polkadot/polkadot.address.ts","../src/polkadot/polkadot.api.ts","../src/polkadot/polkadot.apps.ts"],"sourcesContent":["export function isHexString(asset: unknown): boolean {\n return typeof asset === 'string' && asset.startsWith('0x');\n}\n\nexport function isEthAddress(address: string): boolean {\n return address.length === 42 && address.startsWith('0x');\n}\n","export function formatAssetIdToERC20(id: string) {\n if (id.startsWith('0x')) {\n return id;\n }\n\n if (!/^\\d{38,39}$/.test(id)) {\n throw new Error(`Asset id: ${id} must be a string and have 38-39 digits`);\n }\n\n return `0xffffffff${BigInt(id).toString(16).padStart(32, '0')}`;\n}\n\nexport function convertAddressTo32Bytes(address: string): string {\n if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {\n throw new Error(`Invalid address: ${address}`);\n }\n\n return `0x000000000000000000000000${address.substring(2)}`;\n}\n","import Big, { type RoundingMode } from 'big.js';\n\nBig.NE = -18;\n\nexport function toDecimal(\n number: bigint | number | string,\n decimals: number,\n maxDecimal = 6,\n roundType?: RoundingMode,\n): string {\n const dividend = Big(number.toString().replace(/[^0-9]/g, ''));\n const divisor = Big(10).pow(decimals);\n const result = dividend.div(divisor).round(maxDecimal, roundType);\n\n return result.toString();\n}\n\nexport function toBigInt(\n amount: bigint | string | number,\n decimals: number,\n): bigint {\n if (typeof amount === 'bigint') {\n return amount;\n }\n\n const multiplier = Big(10).pow(decimals);\n const result = Big(amount).mul(multiplier);\n\n return BigInt(result.toFixed(0, Big.roundDown));\n}\n\nexport function convertDecimals(\n number: string | bigint,\n decimals: number,\n targetDecimals: number,\n): bigint {\n const decimalNumber = toDecimal(number, decimals, decimals);\n\n return toBigInt(decimalNumber.toString(), targetDecimals);\n}\n\nexport function hasDecimalOverflow(fl: number | string, maxDecimal: number) {\n const parts = fl.toString().split('.');\n return parts.length > 1 && parts[1].length > maxDecimal;\n}\n","import {\n bnToU8a,\n compactToU8a,\n hexToU8a,\n stringToU8a,\n u8aToHex,\n} from '@polkadot/util';\nimport { blake2AsU8a, decodeAddress } from '@polkadot/util-crypto';\nimport { isEthAddress } from '../format';\n\n/**\n * reference: https://github.com/Moonsong-Labs/xcm-tools/blob/main/scripts/calculate-sovereign-account.ts\n */\n\nexport function getSovereignAccountAddresses(paraId: number) {\n const paraIdU8a = bnToU8a(paraId, { bitLength: 32 });\n const relay = u8aToHex(\n new Uint8Array([...stringToU8a('para'), ...paraIdU8a]),\n ).padEnd(66, '0');\n const generic = u8aToHex(\n new Uint8Array([...stringToU8a('sibl'), ...paraIdU8a]),\n ).padEnd(66, '0');\n const moonbeam = generic.slice(0, 42);\n\n return {\n generic,\n moonbeam,\n relay,\n };\n}\n\n/**\n * reference: https://github.com/Moonsong-Labs/xcm-tools/blob/main/scripts/calculate-multilocation-derivative-account.ts\n */\n\nexport function getMultilocationDerivedAddresses({\n paraId,\n address,\n isParents = false,\n}: {\n paraId?: number;\n address: string;\n isParents?: boolean;\n}) {\n const parents = isParents ? 1 : 0;\n const accType = isEthAddress(address) ? 'AccountKey20' : 'AccountId32';\n const decodedAddress = isEthAddress(address)\n ? hexToU8a(address)\n : decodeAddress(address);\n\n // Describe Family\n // https://github.com/paritytech/polkadot/blob/master/xcm/xcm-builder/src/location_conversion.rs#L96-L118\n const family =\n parents === 0 && paraId\n ? 'ChildChain'\n : parents === 1 && !paraId\n ? 'ParentChain'\n : 'SiblingChain';\n\n const blake = blake2AsU8a(\n new Uint8Array([\n ...stringToU8a(family),\n ...(paraId ? compactToU8a(paraId) : []),\n ...compactToU8a(accType.length + (isEthAddress(address) ? 20 : 32)),\n ...stringToU8a(accType),\n ...decodedAddress,\n ]),\n );\n\n const address20 = u8aToHex(blake.slice(0, 20));\n const address32 = u8aToHex(blake.slice(0, 32));\n\n return {\n address20,\n address32,\n };\n}\n","import { ApiPromise, WsProvider } from '@polkadot/api';\nimport { typesBundle } from '@polkadot/apps-config';\nimport { LRUCache } from 'lru-cache';\n\nexport enum MRLTypes {\n // TODO handle both types according to RT version\n XcmVersionedMultiLocation = 'XcmVersionedMultiLocation',\n XcmVersionedLocation = 'XcmVersionedLocation',\n XcmRoutingUserAction = 'XcmRoutingUserAction',\n VersionedUserAction = 'VersionedUserAction',\n}\n\nconst cache = new LRUCache<string, Promise<ApiPromise>>({\n max: 20,\n dispose: async (promise: Promise<ApiPromise>) => {\n const api = await promise;\n\n if (api.isConnected) {\n api.disconnect();\n }\n },\n});\n\nexport async function getPolkadotApi(\n ws: string | string[],\n): Promise<ApiPromise> {\n const key = Array.isArray(ws) ? ws.join(';') : ws;\n const promise =\n cache.get(key) ||\n ApiPromise.create({\n noInitWarn: true,\n provider: new WsProvider(ws),\n types: {\n [MRLTypes.XcmRoutingUserAction]: {\n destination: MRLTypes.XcmVersionedLocation,\n },\n [MRLTypes.VersionedUserAction]: {\n _enum: { V1: MRLTypes.XcmRoutingUserAction },\n },\n },\n typesBundle,\n });\n\n cache.set(key, promise);\n\n const api = await promise;\n\n await api.isReady;\n\n return api;\n}\n","export function getPolkadotAppsUrl(ws: string) {\n return `https://polkadot.js.org/apps/?rpc=${encodeURIComponent(ws)}#/explorer/query`;\n}\n"],"mappings":";AAAO,SAAS,YAAY,OAAyB;AACnD,SAAO,OAAO,UAAU,YAAY,MAAM,WAAW,IAAI;AAC3D;AAEO,SAAS,aAAa,SAA0B;AACrD,SAAO,QAAQ,WAAW,MAAM,QAAQ,WAAW,IAAI;AACzD;;;ACNO,SAAS,qBAAqB,IAAY;AAC/C,MAAI,G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AAA,EACF;AACF;;;AC5EA,SAAS,YAAY,kBAAkB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AAElB,IAAK,WAAL,kBAAKA,cAAL;AAEL,EAAAA,UAAA,+BAA4B;AAC5B,EAAAA,UAAA,0BAAuB;AACvB,EAAAA,UAAA,0BAAuB;AACvB,EAAAA,UAAA,yBAAsB;AALZ,SAAAA;AAAA,GAAA;AAQZ,IAAM,QAAQ,IAAI,SAAsC;AAAA,EACtD,KAAK;AAAA,EACL,SAAS,OAAO,YAAiC;AAC/C,UAAM,MAAM,MAAM;AAElB,QAAI,IAAI,aAAa;AACnB,UAAI,WAAW;AAAA,IACjB;AAAA,EACF;AACF,CAAC;AAED,eAAsB,eACpB,IACqB;AACrB,QAAM,MAAM,MAAM,QAAQ,EAAE,IAAI,GAAG,KAAK,GAAG,IAAI;AAC/C,QAAM,UACJ,MAAM,IAAI,GAAG,KACb,WAAW,OAAO;AAAA,IAChB,YAAY;AAAA,IACZ,UAAU,IAAI,WAAW,EAAE;AAAA,IAC3B,OAAO;AAAA,MACL,CAAC,iDAA6B,GAAG;AAAA,QAC/B,aAAa;AAAA,MACf;AAAA,MACA,CAAC,+CAA4B,GAAG;AAAA,QAC9B,OAAO,EAAE,IAAI,kDAA8B;AAAA,MAC7C;AAAA,IACF;AAAA,IACA;AAAA,EACF,CAAC;AAEH,QAAM,IAAI,KAAK,OAAO;AAEtB,QAAM,MAAM,MAAM;AAElB,QAAM,IAAI;AAEV,SAAO;AACT;;;AClDO,SAAS,mBAAmB,IAAY;AAC7C,SAAO,qCAAqC,mBAAmB,EAAE,CAAC;AACpE;","names":["MRLTypes"]}
package/package.json CHANGED
@@ -1,26 +1,13 @@
1
1
  {
2
2
  "name": "@moonbeam-network/xcm-utils",
3
- "version": "1.0.0-dev.28",
3
+ "version": "1.0.0-dev.280",
4
4
  "description": "Moonbeam XCM utilities",
5
- "scripts": {
6
- "build": "tsup",
7
- "dev": "npm run build -- --watch",
8
- "link": "npm ln",
9
- "lint": "eslint . --ext .js,.ts",
10
- "lint:fix": "npm run lint -- --fix",
11
- "typecheck": "tsc --noEmit",
12
- "test": "jest /src",
13
- "test:watch": "npm test -- --watch",
14
- "test:update": "npm test -- -u",
15
- "test:ci": "npm test -- --ci",
16
- "prepack": "prettier --write build/index.d.ts"
17
- },
18
- "author": "PureStake",
5
+ "author": "moonbeam-foundation",
19
6
  "license": "MIT",
20
7
  "repository": {
21
8
  "directory": "packages/utils",
22
9
  "type": "git",
23
- "url": "git+https://github.com/PureStake/xcm-sdk.git"
10
+ "url": "git+https://github.com/moonbeam-foundation/xcm-sdk.git"
24
11
  },
25
12
  "keywords": [
26
13
  "moonbeam",
@@ -29,36 +16,42 @@
29
16
  "utils"
30
17
  ],
31
18
  "bugs": {
32
- "url": "https://github.com/PureStake/xcm-sdk/issues"
19
+ "url": "https://github.com/moonbeam-foundation/xcm-sdk/issues"
33
20
  },
34
- "homepage": "https://docs.moonbeam.network/builders/xcm/xcm-sdk/xcm-sdk/",
21
+ "homepage": "https://moonbeam-foundation.github.io/xcm-sdk/latest",
35
22
  "files": [
36
23
  "build"
37
24
  ],
38
25
  "type": "module",
39
26
  "exports": {
40
27
  ".": {
41
- "import": {
42
- "types": "./build/index.d.ts",
43
- "default": "./build/index.mjs"
44
- },
45
- "require": {
46
- "types": "./build/index.d.ts",
47
- "default": "./build/index.cjs"
48
- }
28
+ "import": "./build/index.mjs",
29
+ "types": "./build/index.d.ts",
30
+ "default": "./build/index.mjs"
49
31
  }
50
32
  },
51
33
  "types": "./build/index.d.ts",
52
- "main": "./build/index.cjs",
34
+ "main": "./build/index.mjs",
53
35
  "dependencies": {
54
- "big.js": "^6.2.1",
55
- "lru-cache": "^7.17.0"
36
+ "big.js": "^7.0.1",
37
+ "lru-cache": "^11.1.0"
56
38
  },
57
39
  "devDependencies": {
58
- "@types/big.js": "^6.1.6"
40
+ "@types/big.js": "^6.2.2"
59
41
  },
60
42
  "peerDependencies": {
61
- "@polkadot/apps-config": "^0.132.1",
62
- "@polkadot/api": "^10.10.1"
43
+ "@polkadot/api": "16.5.4",
44
+ "@polkadot/apps-config": "0.169.1",
45
+ "@polkadot/util": "14.0.1",
46
+ "@polkadot/util-crypto": "14.0.1"
47
+ },
48
+ "scripts": {
49
+ "build": "tsup",
50
+ "dev": "tsup --watch",
51
+ "link": "pnpm ln --global",
52
+ "typecheck": "tsc --noEmit",
53
+ "test": "vitest --run",
54
+ "test:watch": "vitest",
55
+ "test:update": "vitest -u"
63
56
  }
64
57
  }
package/build/index.cjs DELETED
@@ -1,2 +0,0 @@
1
- "use strict";var l=Object.create;var s=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var P=Object.getPrototypeOf,v=Object.prototype.hasOwnProperty;var h=(t,r)=>{for(var n in r)s(t,n,{get:r[n],enumerable:!0})},p=(t,r,n,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of w(r))!v.call(t,o)&&o!==n&&s(t,o,{get:()=>r[o],enumerable:!(i=x(r,o))||i.enumerable});return t};var u=(t,r,n)=>(n=t!=null?l(P(t)):{},p(r||!t||!t.__esModule?s(n,"default",{value:t,enumerable:!0}):n,t)),A=t=>p(s({},"__esModule",{value:!0}),t);var R={};h(R,{convertDecimals:()=>y,formatAssetIdToERC20:()=>S,getPolkadotApi:()=>I,hasDecimalOverflow:()=>B,toBigInt:()=>f,toDecimal:()=>g});module.exports=A(R);function S(t){if(t.startsWith("0x"))return t;if(!/^\d{38,39}$/.test(t))throw new Error(`Asset id: ${t} must be a string and have 38-39 digits`);return`0xffffffff${BigInt(t).toString(16).padStart(32,"0")}`}var e=u(require("big.js"),1);e.default.NE=-18;function g(t,r,n=6,i){let o=(0,e.default)(t.toString().replace(/[^0-9]/g,"")),b=(0,e.default)(10).pow(r);return o.div(b).round(n,i).toString()}function f(t,r){if(typeof t=="bigint")return t;let n=(0,e.default)(10).pow(r),i=(0,e.default)(t).mul(n);return BigInt(i.toFixed(0,e.default.roundDown))}function y(t,r,n){let i=g(t,r,r);return f(i.toString(),n)}function B(t,r){let n=t.toString().split(".");return n.length>1&&n[1].length>r}var m=require("@polkadot/api"),a=require("@polkadot/apps-config"),d=u(require("lru-cache"),1),c=new d.default({max:20,dispose:async t=>{let r=await t;r.isConnected&&r.disconnect()}});async function I(t){let r=c.get(t)||m.ApiPromise.create({noInitWarn:!0,provider:new m.WsProvider(t),typesBundle:a.typesBundle});c.set(t,r);let n=await r;return await n.isReady,n}0&&(module.exports={convertDecimals,formatAssetIdToERC20,getPolkadotApi,hasDecimalOverflow,toBigInt,toDecimal});
2
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts","../src/format/asset.ts","../src/numbers/decimals.ts","../src/polkadot/polkadot.api.ts"],"sourcesContent":["export * from './format';\nexport * from './numbers';\nexport * from './polkadot';\n","export function formatAssetIdToERC20(id: string) {\n if (id.startsWith('0x')) {\n return id;\n }\n\n if (!/^\\d{38,39}$/.test(id)) {\n throw new Error(`Asset id: ${id} must be a string and have 38-39 digits`);\n }\n\n return `0xffffffff${BigInt(id).toString(16).padStart(32, '0')}`;\n}\n","import Big, { RoundingMode } from 'big.js';\n\nBig.NE = -18;\n\nexport function toDecimal(\n number: bigint | number | string,\n decimals: number,\n maxDecimal = 6,\n roundType?: RoundingMode,\n): string {\n const dividend = Big(number.toString().replace(/[^0-9]/g, ''));\n const divisor = Big(10).pow(decimals);\n const result = dividend.div(divisor).round(maxDecimal, roundType);\n\n return result.toString();\n}\n\nexport function toBigInt(\n amount: bigint | string | number,\n decimals: number,\n): bigint {\n if (typeof amount === 'bigint') {\n return amount;\n }\n\n const multiplier = Big(10).pow(decimals);\n const result = Big(amount).mul(multiplier);\n\n return BigInt(result.toFixed(0, Big.roundDown));\n}\n\nexport function convertDecimals(\n number: string | bigint,\n decimals: number,\n targetDecimals: number,\n): bigint {\n const decimalNumber = toDecimal(number, decimals, decimals);\n\n return toBigInt(decimalNumber.toString(), targetDecimals);\n}\n\nexport function hasDecimalOverflow(fl: number | string, maxDecimal: number) {\n const parts = fl.toString().split('.');\n return parts.length > 1 && parts[1].length > maxDecimal;\n}\n","import { ApiPromise, WsProvider } from '@polkadot/api';\nimport { typesBundle } from '@polkadot/apps-config';\nimport LRU from 'lru-cache';\n\nconst cache = new LRU<string, Promise<ApiPromise>>({\n max: 20,\n // eslint-disable-next-line sort-keys\n dispose: async (promise: Promise<ApiPromise>) => {\n const api = await promise;\n\n if (api.isConnected) {\n api.disconnect();\n }\n },\n});\n\nexport async function getPolkadotApi(ws: string): Promise<ApiPromise> {\n const promise =\n cache.get(ws) ||\n ApiPromise.create({\n noInitWarn: true,\n provider: new WsProvider(ws),\n typesBundle,\n });\n\n cache.set(ws, promise);\n\n const api = await promise;\n\n await api.isReady;\n\n return api;\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,yBAAAC,EAAA,mBAAAC,EAAA,uBAAAC,EAAA,aAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAAR,GCAO,SAASS,EAAqBC,EAAY,CAC/C,GAAIA,EAAG,WAAW,IAAI,EACpB,OAAOA,EAGT,GAAI,CAAC,cAAc,KAAKA,CAAE,EACxB,MAAM,IAAI,MAAM,aAAaA,0CAA2C,EAG1E,MAAO,aAAa,OAAOA,CAAE,EAAE,SAAS,EAAE,EAAE,SAAS,GAAI,GAAG,GAC9D,CCVA,IAAAC,EAAkC,uBAElC,EAAAC,QAAI,GAAK,IAEF,SAASC,EACdC,EACAC,EACAC,EAAa,EACbC,EACQ,CACR,IAAMC,KAAW,EAAAN,SAAIE,EAAO,SAAS,EAAE,QAAQ,UAAW,EAAE,CAAC,EACvDK,KAAU,EAAAP,SAAI,EAAE,EAAE,IAAIG,CAAQ,EAGpC,OAFeG,EAAS,IAAIC,CAAO,EAAE,MAAMH,EAAYC,CAAS,EAElD,SAAS,CACzB,CAEO,SAASG,EACdC,EACAN,EACQ,CACR,GAAI,OAAOM,GAAW,SACpB,OAAOA,EAGT,IAAMC,KAAa,EAAAV,SAAI,EAAE,EAAE,IAAIG,CAAQ,EACjCQ,KAAS,EAAAX,SAAIS,CAAM,EAAE,IAAIC,CAAU,EAEzC,OAAO,OAAOC,EAAO,QAAQ,EAAG,EAAAX,QAAI,SAAS,CAAC,CAChD,CAEO,SAASY,EACdV,EACAC,EACAU,EACQ,CACR,IAAMC,EAAgBb,EAAUC,EAAQC,EAAUA,CAAQ,EAE1D,OAAOK,EAASM,EAAc,SAAS,EAAGD,CAAc,CAC1D,CAEO,SAASE,EAAmBC,EAAqBZ,EAAoB,CAC1E,IAAMa,EAAQD,EAAG,SAAS,EAAE,MAAM,GAAG,EACrC,OAAOC,EAAM,OAAS,GAAKA,EAAM,CAAC,EAAE,OAASb,CAC/C,CC5CA,IAAAc,EAAuC,yBACvCC,EAA4B,iCAC5BC,EAAgB,0BAEVC,EAAQ,IAAI,EAAAC,QAAiC,CACjD,IAAK,GAEL,QAAS,MAAOC,GAAiC,CAC/C,IAAMC,EAAM,MAAMD,EAEdC,EAAI,aACNA,EAAI,WAAW,CAEnB,CACF,CAAC,EAED,eAAsBC,EAAeC,EAAiC,CACpE,IAAMH,EACJF,EAAM,IAAIK,CAAE,GACZ,aAAW,OAAO,CAChB,WAAY,GACZ,SAAU,IAAI,aAAWA,CAAE,EAC3B,yBACF,CAAC,EAEHL,EAAM,IAAIK,EAAIH,CAAO,EAErB,IAAMC,EAAM,MAAMD,EAElB,aAAMC,EAAI,QAEHA,CACT","names":["src_exports","__export","convertDecimals","formatAssetIdToERC20","getPolkadotApi","hasDecimalOverflow","toBigInt","toDecimal","__toCommonJS","formatAssetIdToERC20","id","import_big","Big","toDecimal","number","decimals","maxDecimal","roundType","dividend","divisor","toBigInt","amount","multiplier","result","convertDecimals","targetDecimals","decimalNumber","hasDecimalOverflow","fl","parts","import_api","import_apps_config","import_lru_cache","cache","LRU","promise","api","getPolkadotApi","ws"]}