@layerzerolabs/lz-utilities 3.0.12 → 3.0.14-aptos.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/CHANGELOG.md +16 -0
- package/dist/index.cjs +69 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +12 -5
- package/dist/index.d.ts +12 -5
- package/dist/index.mjs +68 -7
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# @layerzerolabs/lz-utilities
|
|
2
2
|
|
|
3
|
+
## 3.0.14-aptos.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Fix Aptos,Movement counter config, build new snapshots
|
|
8
|
+
- Updated dependencies
|
|
9
|
+
- @layerzerolabs/lz-definitions@3.0.14-aptos.0
|
|
10
|
+
|
|
11
|
+
## 3.0.13
|
|
12
|
+
|
|
13
|
+
### Patch Changes
|
|
14
|
+
|
|
15
|
+
- 066ceca: unichain, read on 4 new chains: bsc,ava,poly,ape
|
|
16
|
+
- Updated dependencies [066ceca]
|
|
17
|
+
- @layerzerolabs/lz-definitions@3.0.13
|
|
18
|
+
|
|
3
19
|
## 3.0.12
|
|
4
20
|
|
|
5
21
|
### Patch Changes
|
package/dist/index.cjs
CHANGED
|
@@ -2,8 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
var http = require('http');
|
|
4
4
|
var path2 = require('path');
|
|
5
|
-
var web3_js = require('@solana/web3.js');
|
|
6
5
|
var initia_js = require('@initia/initia.js');
|
|
6
|
+
var web3_js = require('@solana/web3.js');
|
|
7
|
+
var crypto = require('@ton/crypto');
|
|
8
|
+
var ton = require('@ton/ton');
|
|
7
9
|
var aptos = require('aptos');
|
|
8
10
|
var bip39 = require('bip39');
|
|
9
11
|
var ed25519HdKey = require('ed25519-hd-key');
|
|
@@ -175,6 +177,8 @@ function getBIP044Path(chainType, account, change, index) {
|
|
|
175
177
|
return `m/44'/637'/${account}'/${change}'/${index}'`;
|
|
176
178
|
case lzDefinitions.ChainType.SOLANA:
|
|
177
179
|
return `m/44'/501'/${account}'/${change}'`;
|
|
180
|
+
case lzDefinitions.ChainType.TON:
|
|
181
|
+
return `m/44'/607'/${account}'/${change}/${index}`;
|
|
178
182
|
default:
|
|
179
183
|
throw new Error(`Unsupported chain: ${chainType}`);
|
|
180
184
|
}
|
|
@@ -232,7 +236,16 @@ function getSolanaAccountFromMnemonic(mnemonic, path3 = "m/44'/501'/0'/0'") {
|
|
|
232
236
|
address: keyPair.publicKey.toBase58()
|
|
233
237
|
};
|
|
234
238
|
}
|
|
235
|
-
function
|
|
239
|
+
async function getTonAccountFromMnemonic(mnemonic, path3 = "m/44'/607'/0'/0'/0'", workchain = 0) {
|
|
240
|
+
const { wallet, keyPair } = await getTonWalletFromMnemonic(mnemonic, path3, workchain);
|
|
241
|
+
return {
|
|
242
|
+
mnemonic,
|
|
243
|
+
path: path3,
|
|
244
|
+
privateKey: ethers.ethers.utils.hexlify(keyPair.secretKey),
|
|
245
|
+
address: wallet.address.toString({ bounceable: false, urlSafe: true })
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
async function getKeypairFromMnemonic(chainType, mnemonic, path3) {
|
|
236
249
|
switch (chainType) {
|
|
237
250
|
case lzDefinitions.ChainType.EVM:
|
|
238
251
|
return getEvmAccountFromMnemonic(mnemonic, path3);
|
|
@@ -242,10 +255,40 @@ function getKeypairFromMnemonic(chainType, mnemonic, path3) {
|
|
|
242
255
|
return getInitiaAccountFromMnemonic(mnemonic, path3);
|
|
243
256
|
case lzDefinitions.ChainType.SOLANA:
|
|
244
257
|
return getSolanaAccountFromMnemonic(mnemonic, path3);
|
|
258
|
+
case lzDefinitions.ChainType.TON:
|
|
259
|
+
return getTonAccountFromMnemonic(mnemonic, path3);
|
|
245
260
|
default:
|
|
246
261
|
throw new Error(`Unsupported chain: ${chainType}`);
|
|
247
262
|
}
|
|
248
263
|
}
|
|
264
|
+
async function getTonWalletFromMnemonic(mnemonic, path3 = "m/44'/607'/0'/0'/0'", workchain = 0) {
|
|
265
|
+
const seed = await crypto.mnemonicToHDSeed(mnemonic.split(" "));
|
|
266
|
+
const indices = toPathArray(path3);
|
|
267
|
+
const derivedSeed = await crypto.deriveEd25519Path(seed, indices);
|
|
268
|
+
const keyPair = crypto.keyPairFromSeed(derivedSeed);
|
|
269
|
+
return {
|
|
270
|
+
wallet: ton.WalletContractV4.create({ publicKey: keyPair.publicKey, workchain }),
|
|
271
|
+
keyPair
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
function toPathArray(path3) {
|
|
275
|
+
if (!/^[mM]'?/.test(path3)) {
|
|
276
|
+
throw new Error('Path must start with "m" or "M"');
|
|
277
|
+
}
|
|
278
|
+
const parts = path3.replace(/^[mM]'?\//, "").split("/");
|
|
279
|
+
const ret = Array(parts.length);
|
|
280
|
+
for (let i = 0; i < parts.length; i++) {
|
|
281
|
+
const tmp = /(\d+)[hH']/.exec(parts[i]);
|
|
282
|
+
if (tmp === null) {
|
|
283
|
+
throw new Error("Invalid input");
|
|
284
|
+
}
|
|
285
|
+
ret[i] = parseInt(tmp[1], 10);
|
|
286
|
+
if (ret[i] >= 2147483648) {
|
|
287
|
+
throw new Error("Invalid child index");
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return ret;
|
|
291
|
+
}
|
|
249
292
|
var logger = void 0;
|
|
250
293
|
function getStackTrace() {
|
|
251
294
|
const oldLimit = Error.stackTraceLimit;
|
|
@@ -531,13 +574,31 @@ function enableTS(relativeToPath) {
|
|
|
531
574
|
typeCheck: false
|
|
532
575
|
});
|
|
533
576
|
}
|
|
534
|
-
function loadJSorTS(fileName, relativeToPath) {
|
|
577
|
+
async function loadJSorTS(fileName, relativeToPath) {
|
|
578
|
+
const require2 = module$1.createRequire(relativeToPath);
|
|
579
|
+
const modulePath = require2.resolve(fileName);
|
|
535
580
|
if (fileName.endsWith(".ts")) {
|
|
536
581
|
enableTS(relativeToPath);
|
|
582
|
+
return import(modulePath);
|
|
583
|
+
} else if (fileName.endsWith(".mjs")) {
|
|
584
|
+
return import(modulePath);
|
|
585
|
+
} else if (fileName.endsWith(".cjs")) {
|
|
586
|
+
return Promise.resolve(require2(modulePath));
|
|
587
|
+
} else if (fileName.endsWith(".js")) {
|
|
588
|
+
try {
|
|
589
|
+
return await Promise.resolve(require2(modulePath));
|
|
590
|
+
} catch (requireError) {
|
|
591
|
+
try {
|
|
592
|
+
return await import(modulePath);
|
|
593
|
+
} catch (importError) {
|
|
594
|
+
throw new Error(
|
|
595
|
+
`Failed to load module: ${fileName}. Require error: ${requireError}. Import error: ${importError}`
|
|
596
|
+
);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
} else {
|
|
600
|
+
throw new Error(`Unsupported file extension: ${fileName}`);
|
|
537
601
|
}
|
|
538
|
-
const require2 = module$1.createRequire(relativeToPath);
|
|
539
|
-
const modulePath = require2.resolve(fileName);
|
|
540
|
-
return require2(modulePath);
|
|
541
602
|
}
|
|
542
603
|
var logger2 = getLogger();
|
|
543
604
|
async function sleep(timeout) {
|
|
@@ -631,6 +692,8 @@ exports.getLogger = getLogger;
|
|
|
631
692
|
exports.getProjectPackageManager = getProjectPackageManager;
|
|
632
693
|
exports.getProjectRootDir = getProjectRootDir;
|
|
633
694
|
exports.getSolanaAccountFromMnemonic = getSolanaAccountFromMnemonic;
|
|
695
|
+
exports.getTonAccountFromMnemonic = getTonAccountFromMnemonic;
|
|
696
|
+
exports.getTonWalletFromMnemonic = getTonWalletFromMnemonic;
|
|
634
697
|
exports.hasRequiredProperties = hasRequiredProperties;
|
|
635
698
|
exports.hexToBytes = hexToBytes;
|
|
636
699
|
exports.hexlify = hexlify;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/account.ts","../src/pad.ts","../src/types.ts","../src/format.ts","../src/logger.ts","../src/deployment.ts","../src/path.ts","../src/assert.ts","../src/promise.ts","../src/array.ts","../src/enum.ts","../src/generic.ts","../src/findup.ts","../src/loader.ts"],"names":["path","format","createLogger","logger","ethers","dirname","getStackTrace","createRequire","require"],"mappings":";AAAA,OAAO,UAA8B;AACrC,OAAOA,WAAU;;;ACDjB,SAAS,eAAe;AACxB,SAAS,mBAAmB;AAC5B,YAAY,WAAW;AACvB,YAAY,WAAW;AACvB,YAAY,kBAAkB;AAC9B,SAAS,cAAc;AAEvB,SAAS,iBAAiB;;;ACKnB,IAAM,8BAAN,cAA0C,MAAM;AAAA,EAEnD,YAAY,EAAE,MAAM,YAAY,KAAK,GAAgE;AACjG;AAAA,MACI,GAAG,KAAK,OAAO,CAAC,EAAE,YAAY,CAAC,GAAG,KAC7B,MAAM,CAAC,EACP,YAAY,CAAC,UAAU,IAAI,2BAA2B,UAAU;AAAA,IACzE;AANJ,SAAS,OAAO;AAAA,EAOhB;AACJ;AAWO,SAAS,OACZ,YACA,EAAE,KAAK,OAAO,GAAG,IAAgB,CAAC,GACd;AACpB,MAAI,OAAO,eAAe,UAAU;AAChC,WAAO,OAAO,YAAY,EAAE,KAAK,KAAK,CAAC;AAAA,EAC3C;AACA,SAAO,SAAS,YAAY,EAAE,KAAK,KAAK,CAAC;AAC7C;AAEA,SAAS,OAAO,KAAU,EAAE,KAAK,OAAO,GAAG,IAAgB,CAAC,GAAQ;AAChE,MAAI,SAAS;AAAM,WAAO;AAC1B,QAAM,QAAQ,IAAI,QAAQ,MAAM,EAAE;AAClC,MAAI,MAAM,SAAS,OAAO;AACtB,UAAM,IAAI,4BAA4B;AAAA,MAClC,MAAM,KAAK,KAAK,MAAM,SAAS,CAAC;AAAA,MAChC,YAAY;AAAA,MACZ,MAAM;AAAA,IACV,CAAC;AAEL,SAAO,KAAK,MAAM,QAAQ,UAAU,WAAW,UAAU,EAAE,OAAO,GAAG,GAAG,CAAC;AAC7E;AAEA,SAAS,SAAS,OAAc,EAAE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,MACA,MAAAA;AAAA,MACA,QAAQ;AAAA,IACZ;AAEA,UAAM,UAAU,KAAK,QAAQ,SAAS,CAAC,cAAc;AACjD,cAAQ,IAAI;AAAA,IAChB,CAAC;AAED,YAAQ,GAAG,SAAS,CAAC,SAAS;AAC1B,cAAQ,KAAK;AAAA,IACjB,CAAC;AAED,YAAQ,IAAI;AAAA,EAChB,CAAC;AACL;AAEO,SAAS,eAAe,KAI7B;AAEE,QAAM,IAAI,IAAI,MAAM,oDAAoD;AACxE,MAAI,GAAG,QAAQ,SAAS,QAAW;AAC/B,UAAM,IAAI,MAAM,eAAe,GAAG,EAAE;AAAA,EACxC;AAEA,SAAO;AAAA,IACH,QAAQ,EAAE,OAAO;AAAA,IACjB,MAAM,EAAE,OAAO;AAAA,IACf,MAAM,EAAE,OAAO;AAAA,EACnB;AACJ","sourcesContent":["import http, { RequestOptions } from 'http'\nimport path from 'path'\n\nexport * from './account'\nexport * from './logger'\nexport * from './deployment'\nexport * from './path'\nexport * from './promise'\nexport * from './types'\nexport * from './assert'\nexport * from './array'\nexport * from './enum'\nexport * from './pad'\nexport * from './format'\nexport * from './generic'\nexport * from './findup'\nexport * from './loader'\n\nimport { sync as findUpSync } from 'find-up'\n\nimport { getLogger } from './logger'\n\nexport const logger = getLogger()\n\nexport async function sleep(timeout: number): Promise<void> {\n await new Promise((resolve) => setTimeout(resolve, timeout))\n}\n\nexport function getProjectPackageManager(cwd?: string): 'yarn' | 'npm' | 'pnpm' {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn !== undefined) return 'yarn'\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm !== undefined) return 'npm'\n\n // pnpm\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm !== undefined) return 'pnpm'\n\n throw new Error('Cannot find package.json or yarn.lock')\n}\n\nexport function getProjectRootDir(cwd?: string): string {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn !== undefined) return path.dirname(yarn)\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm !== undefined) return path.dirname(npm)\n\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm !== undefined) return path.dirname(pnpm)\n\n throw new Error('Cannot find yarn.lock or package-lock.json or pnpm-lock.yaml')\n}\n\nexport async function isHttpServiceReachable(\n host: string,\n port: number,\n timeout: number,\n path?: string\n): Promise<boolean> {\n return new Promise((resolve, _reject) => {\n const options: RequestOptions = {\n host,\n port,\n timeout,\n path,\n method: 'HEAD',\n }\n\n const request = http.request(options, (_response) => {\n resolve(true)\n })\n\n request.on('error', (_err) => {\n resolve(false)\n })\n\n request.end()\n })\n}\n\nexport function extractUrlInfo(url: string): {\n schema: 'http' | 'https'\n host: string\n port: string\n} {\n //TODO: handle the default port for http and https(443, 80)\n const m = url.match(/(?<schema>http|https):\\/\\/(?<host>.*):(?<port>\\d+)/)\n if (m?.groups?.host === undefined) {\n throw new Error(`Invalid url ${url}`)\n }\n\n return {\n schema: m.groups.schema as 'http' | 'https',\n host: m.groups.host,\n port: m.groups.port,\n }\n}\n","import { Keypair } from '@solana/web3.js'\nimport { MnemonicKey } from '@initia/initia.js'\nimport * as aptos from 'aptos'\nimport * as bip39 from 'bip39'\nimport * as ed25519HdKey from 'ed25519-hd-key'\nimport { ethers } from 'ethers'\n\nimport { ChainType } from '@layerzerolabs/lz-definitions'\n\nimport { hexlify, trim0x } from './format'\n\nexport interface AccountMnemonic {\n mnemonic: string\n path: string\n privateKey?: string\n address?: string\n}\n\nexport function getBIP044Path(chainType: ChainType, account: number, change: number, index: number): string {\n // CAUTION: the path format is different for each chain\n // https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki\n //\n // The \"m/44'/637'/0'/0'/0'\" path is known as a hardened derivation path, while the \"m/44'/637'/0'/0/0\" path is a non-hardened derivation path.\n // The technical benefit of using a hardened derivation path is enhanced security.\n // In BIP32, a hardened derivation is denoted by an apostrophe ('), which indicates that the child private key should be derived in a way\n // that makes it computationally infeasible to derive the parent private key from it. This additional level of security\n // protects the mnemonic phrase and its derived private keys even if one of the derived private keys is compromised.\n // By using a hardened derivation path, like \"m/44'/637'/0'/0'/0'\", each level of the path requires a unique private key derivation,\n // making it more difficult to infer the parent private key from the child private key. This is particularly important when dealing with\n // hierarchical deterministic wallets, as it helps protect funds across multiple accounts or purposes.\n\n switch (chainType) {\n case ChainType.EVM:\n // https://github.com/ethers-io/ethers.js/blob/main/src.ts/wallet/hdwallet.ts\n return `m/44'/60'/${account}'/${change}/${index}`\n case ChainType.APTOS:\n // https://github.com/aptos-labs/aptos-core/blob/main/ecosystem/typescript/sdk/src/aptos_account.ts\n return `m/44'/637'/${account}'/${change}'/${index}'`\n case ChainType.SOLANA:\n // https://github.com/solana-labs/solana/blob/master/sdk/src/derivation_path.rs\n return `m/44'/501'/${account}'/${change}'`\n default:\n throw new Error(`Unsupported chain: ${chainType}`)\n }\n}\n\nexport function getEvmAccountFromMnemonic(mnemonic: string, path = \"m/44'/60'/0'/0/0\"): AccountMnemonic {\n const wallet = ethers.Wallet.fromMnemonic(mnemonic, path)\n return {\n mnemonic,\n path,\n privateKey: wallet.privateKey,\n address: wallet.address,\n }\n}\n\nexport function getAptosAccountFromMnemonic(mnemonic: string, path = \"m/44'/637'/0'/0'/0'\"): AccountMnemonic {\n //https://aptos.dev/guides/building-your-own-wallet/#creating-an-aptos-account\n if (!aptos.AptosAccount.isValidPath(path)) {\n throw new Error(`Invalid derivation path: ${path}`)\n }\n const normalizeMnemonics = mnemonic\n .trim()\n .split(/\\s+/)\n .map((part) => part.toLowerCase())\n .join(' ')\n {\n const { key } = aptos.derivePath(path, trim0x(hexlify(bip39.mnemonicToSeedSync(normalizeMnemonics))))\n const account = new aptos.AptosAccount(new Uint8Array(key)).toPrivateKeyObject()\n return {\n mnemonic,\n path,\n privateKey: account.privateKeyHex,\n address: account.address,\n }\n }\n}\n\nexport function getInitiaAccountFromMnemonic(mnemonic: string, path = \"m/44'/118'/0'/0/0\"): AccountMnemonic {\n const [_, coinType, account, __, index] = path.match(/\\d+/g)?.map(Number) ?? [44, 118, 0, 0, 0]\n const normalizeMnemonics = mnemonic\n .trim()\n .split(/\\s+/)\n .map((part) => part.toLowerCase())\n .join(' ')\n const key = new MnemonicKey({\n mnemonic: normalizeMnemonics,\n coinType,\n account,\n index,\n })\n {\n return {\n mnemonic,\n path,\n privateKey: key.privateKey.toString('hex'),\n address: key.accAddress,\n }\n }\n}\n\nexport function getSolanaAccountFromMnemonic(mnemonic: string, path = \"m/44'/501'/0'/0'\"): AccountMnemonic {\n const seed = bip39.mnemonicToSeedSync(mnemonic, '') // (mnemonic, password)\n const keyPair = Keypair.fromSeed(ed25519HdKey.derivePath(path, seed.toString('hex')).key)\n return {\n mnemonic,\n path,\n privateKey: ethers.utils.hexlify(keyPair.secretKey),\n address: keyPair.publicKey.toBase58(),\n }\n}\n\nexport function getKeypairFromMnemonic(chainType: ChainType, mnemonic: string, path?: string): AccountMnemonic {\n switch (chainType) {\n case ChainType.EVM:\n return getEvmAccountFromMnemonic(mnemonic, path)\n case ChainType.APTOS:\n return getAptosAccountFromMnemonic(mnemonic, path)\n case ChainType.INITIA:\n return getInitiaAccountFromMnemonic(mnemonic, path)\n case ChainType.SOLANA:\n return getSolanaAccountFromMnemonic(mnemonic, path)\n default:\n throw new Error(`Unsupported chain: ${chainType}`)\n }\n}\n","import { Bytes, Hex } from './types'\n\ninterface PadOptions {\n dir?: 'left' | 'right' | undefined\n size?: number | null | undefined\n}\nexport type PadReturnType<value extends Bytes | Hex> = value extends Hex ? Hex : Bytes\n\nexport type SizeExceedsPaddingSizeErrorType = SizeExceedsPaddingSizeError & {\n name: 'SizeExceedsPaddingSizeError'\n}\n\nexport class SizeExceedsPaddingSizeError extends Error {\n override name = 'SizeExceedsPaddingSizeError'\n constructor({ size, targetSize, type }: { size: number; targetSize: number; type: 'hex' | 'bytes' }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (${size}) exceeds padding size (${targetSize})`\n )\n }\n}\n\n/**\n * Pads a hexadecimal string or byte array to a specified size.\n *\n * @param hexOrBytes - The hexadecimal string or byte array to pad.\n * @param options - The padding options.\n * @param options.dir - The direction of the padding. Defaults to undefined.\n * @param options.size - The size to pad to. Defaults to 32.\n * @returns The padded hexadecimal string or byte array.\n */\nexport function padify<value extends Bytes | Hex>(\n hexOrBytes: value,\n { dir, size = 32 }: PadOptions = {}\n): PadReturnType<value> {\n if (typeof hexOrBytes === 'string') {\n return padHex(hexOrBytes, { dir, size }) as PadReturnType<value>\n }\n return padBytes(hexOrBytes, { dir, size }) as PadReturnType<value>\n}\n\nfunction padHex(hex: Hex, { dir, size = 32 }: PadOptions = {}): Hex {\n if (size === null) return hex\n const value = hex.replace('0x', '')\n if (value.length > size * 2)\n throw new SizeExceedsPaddingSizeError({\n size: Math.ceil(value.length / 2),\n targetSize: size,\n type: 'hex',\n })\n\n return `0x${value[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`\n}\n\nfunction padBytes(bytes: Bytes, { dir, size = 32 }: PadOptions = {}): Bytes {\n if (size === null) return bytes\n if (bytes.length > size)\n throw new SizeExceedsPaddingSizeError({\n size: bytes.length,\n targetSize: size,\n type: 'bytes',\n })\n const paddedBytes = new Uint8Array(size)\n for (let i = 0; i < size; i++) {\n const padEnd = dir === 'right'\n paddedBytes[padEnd ? i : size - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]\n }\n return paddedBytes\n}\n","/**\n * Type representing a hexadecimal string prefixed with '0x'.\n */\nexport type Hex = `0x${string}`\n\n/**\n * Type representing a hash string prefixed with '0x'.\n */\nexport type Hash = `0x${string}`\n\n/**\n * Checks if a given string is a valid hexadecimal string.\n * @param value - The string to check.\n * @returns True if the string is a valid hexadecimal string, false otherwise.\n */\nexport function isHex(value: string): value is Hex {\n return /^(0x)?[0-9A-F]+/i.test(value)\n}\n\n/**\n * Checks if a given string is a valid hash string.\n * @param value - The string to check.\n * @returns True if the string is a valid hash string, false otherwise.\n */\nexport function isHash(value: string): value is Hash {\n return /^(0x)?[0-9A-F]+/i.test(value)\n}\n\n/**\n * Represents a byte array.\n */\nexport type Bytes = Uint8Array\n","import { padify } from './pad'\nimport { Hex, isHex } from './types'\n\n/**\n * A function to convert Uint8Array to hex string\n * @deprecated use `hexlify` instead\n * @param bytes Uint8Array\n * @returns hex string without 0x prefix, e.g., '0102030405'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return trim0x(hexlify(bytes)).replace(/^0x/i, '')\n}\n\n/**\n * A function to convert hex string to Uint8Array\n * @deprecated use `arrayify` instead\n * @param hex hex string, e.g., '0x0102030405' or '0102030405'\n * @returns Uint8Array\n */\nexport function hexToBytes(hex: string): Uint8Array {\n return arrayify(hex)\n}\n\n/**\n * A function to trim the prefix 0x from a hex string\n * @param hex hex string\n * @returns hex string without 0x prefix\n */\nexport function trim0x(hex: string): string {\n return hex.replace(/^0x/i, '')\n}\n\n/**\n * A function to ensure the prefix 0x from a hex string\n * @param hex hex string\n * @returns hex string with 0x prefix\n */\nexport function ensure0x(hex: string): Hex {\n if (!isHex(hex)) {\n throw new Error('invalid hex string')\n }\n const value = trim0x(hex)\n const retval = `0x${value}`\n return retval as Hex\n}\n\n/**\n * A function to check if a string is a hex string\n * @deprecated use `isHex` instead\n * @param value\n * @returns\n */\nexport function isHexString(value: string): boolean {\n return isHex(value)\n}\n\nfunction _arrayify(value: string | number | Uint8Array | Buffer | bigint): Uint8Array {\n if (value instanceof Uint8Array) {\n return value\n }\n\n if (typeof value === 'string') {\n if (value.match(/^(0x)?[0-9A-F]*$/i)) {\n const hex = value.replace(/^0x/i, '')\n const len = hex.length + 1 - ((hex.length + 1) % 2)\n return Uint8Array.from(Buffer.from(hex.padStart(len, '0'), 'hex'))\n }\n throw new Error('Invalid hex string')\n }\n\n if (typeof value === 'number') {\n if (value < 0) {\n throw new Error('Number must be non-negative')\n }\n const byteArray = []\n while (value > 0) {\n byteArray.push(value & 0xff)\n value >>= 8\n }\n return new Uint8Array(byteArray.reverse())\n }\n\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {\n return new Uint8Array(value)\n }\n\n if (typeof value === 'bigint') {\n const hex = value.toString(16)\n return _arrayify(hex)\n }\n\n throw new Error('unsupported type')\n}\n\n/**\n * A function to convert a string|number|Uint8Array|Buffer|BigInt to Uint8Array\n * @param value - the value to convert\n * @param size - the size of the Uint8Array to return, if not specified, the size of the input will be returned\n */\nexport function arrayify(value: string | number | Uint8Array | Buffer | bigint, size?: number): Uint8Array {\n const bytes = _arrayify(value)\n if (size === undefined) {\n return bytes\n }\n return padify(bytes, { size })\n}\n\n/**\n * A function to convert a string|number|Uint8Array|Buffer|BigInt to hex string\n */\nexport function hexlify(value: string | number | Uint8Array | Buffer | bigint): Hex {\n if (typeof value === 'string' && /^(0x)?[0-9A-F]*$/i.test(value)) {\n const retval = '0x' + trim0x(value)\n return retval as Hex\n }\n\n const bytes = arrayify(value)\n const hex = Buffer.from(bytes).toString('hex')\n return ensure0x(hex)\n}\n","import * as winston from 'winston'\nimport { Logger, format } from 'winston'\n\nlet logger: Logger | undefined = undefined\n\nexport { Logger }\n\nfunction getStackTrace(): string | undefined {\n const oldLimit = Error.stackTraceLimit\n Error.stackTraceLimit = Infinity\n const retval = new Error().stack\n Error.stackTraceLimit = oldLimit\n return retval\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value\nexport function getCircularReplacer(): (key: string, value: unknown) => unknown {\n const ancestors: unknown[] = []\n return function (this: unknown, _key: string, value: unknown) {\n if (typeof value !== 'object' || value === null) {\n return value\n }\n // `this` is the object that value is contained in,\n // i.e., its direct parent.\n while (ancestors.length > 0 && ancestors.at(-1) !== this) {\n ancestors.pop()\n }\n if (ancestors.includes(value)) {\n return '[Circular]'\n }\n ancestors.push(value)\n return value\n }\n}\n\nfunction extractCallerInfo(line: string): string {\n for (const pattern of [/\\((.*?:\\d+:\\d+)\\)$/, /at (.*?:\\d+:\\d+)$/]) {\n const m = line.match(pattern)\n if (m === null) {\n continue\n }\n const [, fileInfoLine] = m\n return fileInfoLine\n }\n return '<unknown>'\n}\n\nconst logFormat = format.printf(\n (info: {\n level: string\n message: string\n timestamp?: string\n metadata?: {\n pretty?: boolean\n format?: string\n }\n }) => {\n if (info.level.toUpperCase() !== 'ERROR' && info.level.toUpperCase() !== 'WARN') {\n return `${info.timestamp} ${info.level.toUpperCase()}: ${info.message}`\n }\n const stack = getStackTrace() ?? ''\n\n const stackLines = stack.split('\\n')\n const index =\n stackLines.findIndex((line) => {\n return line.match(/create-logger.js/)\n }) + 1\n\n let fileInfo = '<unknown>'\n if (stackLines.length > index) {\n const line = stackLines[index]\n fileInfo = extractCallerInfo(line)\n }\n\n const formats: string[] = []\n if (fileInfo !== '<unknown>') {\n formats.push(fileInfo)\n }\n\n const { pretty, format } = info.metadata ?? {}\n const spaces = pretty === true ? 2 : undefined\n const value =\n typeof info.message === 'string'\n ? info.message\n : JSON.stringify(info.message, getCircularReplacer(), spaces)\n const message = format !== undefined ? format.replace(/%s/g, value) : value\n\n return [...formats, message].map((x) => `${info.timestamp} ${info.level.toUpperCase()}: ${x}`).join('\\n')\n }\n)\n\nconst loggerFormat = format.combine(\n format.timestamp({ format: 'YY-MM-DD HH:mm:ss' }),\n format.splat(),\n format.metadata({ fillExcept: ['level', 'timestamp', 'message'] }),\n logFormat,\n format.colorize({\n all: true,\n })\n)\n\nexport function initLogger(level: string): void {\n if (!logger) {\n logger = createLogger(level)\n }\n}\n\nexport function createLogger(level: string): Logger {\n const logger = winston.createLogger({\n level,\n format: loggerFormat,\n transports: [new winston.transports.Console()],\n })\n return logger\n}\n\nexport function getLogger(): Logger {\n initLogger(process.env.LZ_LOG ?? 'info')\n if (!logger) {\n throw new Error('Logger is not initialized')\n }\n return logger\n}\n\nconst exportsObject: {\n getCircularReplacer?: (key: unknown, value: unknown) => unknown\n} = {}\n\nif (process.env.NODE_ENV === 'test') {\n exportsObject.getCircularReplacer = getCircularReplacer\n}\nexport default exportsObject\n","import { ethers } from 'ethers'\n\nimport {\n Chain,\n EndpointId,\n EndpointVersion,\n Network,\n isNetworkEndpointIdSupported,\n networkToChain,\n networkToEndpointId,\n} from '@layerzerolabs/lz-definitions'\n\nexport interface Deployment {\n /** Name of the contract deployment. */\n name: string\n\n /** Optional endpoint identifier. */\n compatibleVersions: EndpointVersion[]\n\n /** Network of deployment. */\n network: Network\n\n /** Optional contract source. */\n source?: string\n\n /** Address of deployed contract. */\n address: string\n\n /** Optional contract ABI. */\n abi?: string\n\n /** Optional contract bytecode. */\n bytecode?: string\n}\n\n/**\n * Find the matching deployments based on the given options\n * @todo Use Partial<EndpointSpec> instead of options\n * @param deployments list of deployments\n * @param nameOrAddress contract name\n * @param options options to match against\n * @returns Deployment\n */\nexport function findDeployment(\n deployments: Deployment[],\n nameOrAddress: string,\n options: { chain?: Chain; source?: string; network?: Network; endpointId?: EndpointId }\n): Deployment {\n const retval = tryFindDeployment(deployments, nameOrAddress, options)\n if (retval === undefined) {\n throw new Error(`Deployment not found: ${nameOrAddress} options:${JSON.stringify(options)}`)\n }\n return retval\n}\n\nexport function tryFindDeployment(\n deployments: Deployment[],\n nameOrAddress: string,\n options: { chain?: Chain; source?: string; network?: Network; endpointId?: EndpointId }\n): Deployment | undefined {\n return deployments.find((deployment) => {\n let hasMatchingNameOrAddress = deployment.name === nameOrAddress\n if (!hasMatchingNameOrAddress && ethers.utils.isAddress(nameOrAddress)) {\n hasMatchingNameOrAddress =\n ethers.utils.getAddress(deployment.address) === ethers.utils.getAddress(nameOrAddress)\n }\n const hasMatchingChain = options.chain == null || options.chain === networkToChain(deployment.network)\n const hasMatchingNetwork = options.network === undefined || options.network === deployment.network\n const hasMatchingSource = options.source === undefined || options.source === deployment.source\n let hasMatchingEndpoint = true\n if (options.endpointId != null) {\n const compatibleEndpoints = deployment.compatibleVersions.map((v) => {\n if (isNetworkEndpointIdSupported(deployment.network, v)) {\n return networkToEndpointId(deployment.network, v)\n }\n return undefined\n })\n hasMatchingEndpoint = compatibleEndpoints.includes(options.endpointId)\n }\n return (\n hasMatchingNameOrAddress &&\n hasMatchingChain &&\n hasMatchingNetwork &&\n hasMatchingEndpoint &&\n hasMatchingSource\n )\n })\n}\n\ntype ContractType = { [key in string]: ethers.Contract }\nconst contractCache: ContractType = {}\nexport function deploymentToEvmContract<T extends ethers.Contract>(\n deployment: Deployment,\n provider?: ethers.providers.Provider\n): T {\n const key = `${deployment.network}-${deployment.address}`\n if (!(key in contractCache)) {\n if (deployment.abi === undefined || deployment.bytecode === undefined) {\n throw new Error('Deployment does not have ABI or bytecode')\n }\n const Contract = new ethers.ContractFactory(deployment.abi, deployment.bytecode)\n contractCache[key] = Contract.attach(deployment.address)\n }\n if (!provider) {\n return contractCache[key] as T\n }\n return contractCache[key].connect(provider) as T\n}\n\nexport function findContract<T extends ethers.Contract>(\n provider: ethers.providers.Provider | undefined,\n deployments: Deployment[],\n nameOrAddress: string,\n options: { chain?: Chain; source?: string; network?: Network; endpointId?: EndpointId }\n): T {\n const deployment = findDeployment(deployments, nameOrAddress, options)\n const retval = deploymentToEvmContract<T>(deployment, provider)\n return retval\n}\n","import { createRequire } from 'module'\n/**\n * A function to return dirname of a path\n * @param path\n * @returns\n */\nexport function dirname(path: string): string {\n const match = path.match(/(.*)([\\\\/][^\\\\/]+)[/\\\\]?$/)\n const [, basePath] = match ?? []\n const dirname = typeof basePath !== 'undefined' ? basePath : path\n return dirname\n}\n\nfunction getStackTrace(stackTraceLimit = Infinity): string | undefined {\n const oldLimit = Error.stackTraceLimit\n Error.stackTraceLimit = stackTraceLimit\n const retval = new Error().stack\n Error.stackTraceLimit = oldLimit\n return retval\n}\n\nfunction getCaller(): string | undefined {\n const lines = (getStackTrace(10) ?? '').split('\\n')\n // Error:\n // at getStackTrace\n // at getCaller\n // at <caller of getCaller>\n // at <expected caller>\n if (lines.length > 1 + 1 + 1 + 1) {\n const line = lines[4]\n const m = line.match(/^.*\\(([^:]*)[^)]*\\)/)\n if (m) {\n return m[1]\n }\n }\n return undefined\n}\n\n/**\n * return the root path of a package\n * @param packageName\n * @param relativeToPath\n * @returns\n */\nexport function pkgroot(packageName: string, relativeToPath?: string): string {\n if (relativeToPath === undefined) {\n relativeToPath = getCaller()\n if (relativeToPath === undefined) {\n relativeToPath = __filename\n }\n }\n\n const filepath = createRequire(relativeToPath).resolve(`${packageName}/package.json`)\n const packagePath = dirname(filepath)\n // https://github.com/yarnpkg/berry/blob/f67dda88fe9d0a892c44af923cbbc50bfe454e0e/packages/docusaurus/docs/advanced/03-pnp/pnp-spec.md\n // In order to properly represent packages listing peer dependencies, Yarn relies on a concept\n // called Virtual Packages. Their most notable property is that they all have different paths\n // (so that Node.js instantiates them as many times as needed), while still being baked by the\n // same concrete folder on disk.\n return packagePath.replace(/.yarn\\/([^/]*\\/)?(__virtual__|\\$\\$virtual)\\/[^/]*\\/\\d*\\//, '')\n}\n","export function assert(condition: boolean, message?: string): asserts condition {\n if (!condition) {\n throw new Error(`Assertion Error: ${message ?? 'condition is false'}`)\n }\n}\n\n/**\n * assertType\n * assertType can be used to assert that a value is of a certain type, and without naming a new variable explicitly.\n * @param value\n * @param fn\n * @param message\n */\nexport function assertType<T, M>(value: T, fn: (v: unknown) => v is M, message?: string): asserts value is T & M {\n if (!fn(value)) {\n throw new Error(`Expected value to be ${message ?? 'of correct type'}`)\n }\n}\n\nexport function assertDefined<T>(value?: T, message?: string): asserts value is NonNullable<T> {\n if (value === undefined || value === null) {\n throw new Error(message ?? 'Value is undefined or null')\n }\n}\n\nexport function asType<T, M>(value: T, fn: (v: unknown) => v is M, message?: string): M {\n if (!fn(value)) {\n throw new Error(`Expected value to be ${message ?? 'of correct type'}`)\n }\n return value\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nexport function assumeType<T>(value: unknown): asserts value is T {}\n","// This file copy from repo:devtools and is located in packages/devtools/src/common/promise.ts\n\nimport { assert } from './assert'\n\n/**\n * Generic type for a hybrid (sync / async) factory\n * that generates an instance of `TOutput` based on arguments of type `TInput`\n *\n * `TInput` represents the list of all function arguments that need to be passed to the factory:\n *\n * ```typescript\n * const mySyncFactory: Factory<[number, boolean], string> = (num: number, bool: boolean): string => \"hello\"\n *\n * const mySyncFactory: Factory<[], string> = async () => \"hello\"\n * ```\n *\n * The hybrid aspect just makes it easier for implementers - if the logic is synchronous,\n * this type will not force any extra `async`.\n */\nexport type Factory<TInput extends unknown[], TOutput> = (...input: TInput) => TOutput | Promise<TOutput>\n\n/**\n * Helper type for argumentless factories a.k.a. tasks\n */\ntype Task<T> = Factory<[], T>\n\n/**\n * Executes tasks in sequence, waiting for each one to finish before starting the next one\n *\n * Will resolve with the output of all tasks or reject with the first rejection.\n *\n * @param {Task<T>[]} tasks\n * @returns {Promise<T[]>}\n */\nexport const sequence = async <T>(tasks: Task<T>[]): Promise<T[]> => {\n const collector: T[] = []\n\n for (const task of tasks) {\n collector.push(await task())\n }\n\n return collector\n}\n\n/**\n * Executes tasks in parallel\n *\n * Will resolve with the output of all tasks or reject with the any rejection.\n *\n * @param {Task<T>[]} tasks\n * @returns {Promise<T[]>}\n */\nexport const parallel = async <T>(tasks: Task<T>[]): Promise<T[]> => Promise.all(tasks.map(async (task) => task()))\n\n/**\n * Executes tasks in a sequence until one resolves.\n *\n * Will resolve with the output of the first task that resolves\n * or reject with the last rejection.\n *\n * Will reject immediatelly if no tasks have been passed\n *\n * @param {Task<T>[]} tasks\n * @returns {Promise<T>}\n */\nexport const first = async <T>(tasks: Task<T>[]): Promise<T> => {\n assert(tasks.length !== 0, `Must have at least one task for first()`)\n\n let lastError: unknown\n\n for (const task of tasks) {\n try {\n return await task()\n } catch (error) {\n lastError = error\n }\n }\n\n throw lastError\n}\n\n/**\n * Helper utility for currying first() - creating a function\n * that behaves like first() but accepts arguments that will be passed to the factory functions\n *\n * @param {Factory<TInput, TOutput>[]} factories\n * @returns {Factory<TInput, TOutput>}\n */\nexport const firstFactory =\n <TInput extends unknown[], TOutput>(...factories: Factory<TInput, TOutput>[]): Factory<TInput, TOutput> =>\n async (...input) =>\n first(factories.map((factory) => async () => factory(...input)))\n\n/**\n * Represents a type that excludes promises.\n * If the input type is a promise, the resulting type is `never`.\n * Otherwise, it is the same as the input type.\n */\nexport type NonPromise<T> = T extends Promise<unknown> ? never : T\n","/**\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\n * @returns\n */\nexport function safeMap<T, R>(elements: T[], callbackfn: (item: T, index: number) => R): [R[], Error | undefined] {\n const result: R[] = []\n try {\n for (let i = 0; i < elements.length; i++) {\n const rv = callbackfn(elements[i], i)\n result.push(rv)\n }\n return [result, undefined]\n } catch (e) {\n return [result, e as Error]\n }\n}\n","/**\n * Converts a string or number value to a corresponding enum value.\n * @param enumType - The enum object.\n * @param value - The value to convert.\n * @returns The converted enum value.\n * @throws Error if the value is not a valid enum value.\n * @example\n * // Usage\n * enum Color {\n * Red = 'red',\n * Green = 'green',\n * Blue = 'blue'\n * }\n *\n * const color: Color = asEnum(Color, 'red');\n * expect(color).toBe(Color.Red);\n *\n * enum Direction {\n * Up = 1,\n * Down,\n * }\n *\n * const direction: Direction = asEnum(Direction, 1);\n * expect(direction).toBe(Direction.Up);\n */\nexport function asEnum<T extends object>(enumType: T, value: string | number): T[keyof T] {\n const enumValues = Object.values(enumType)\n\n if (enumValues.includes(value)) {\n return value as T[keyof T]\n } else {\n throw new Error(`Invalid enum value: ${value}`)\n }\n}\n","/**\n * Represents a type that allows partial modification of all properties in a given object type.\n * This type is similar to the built-in `Partial` type in TypeScript.\n * However, it supports deep partial modification, allowing partial modification of nested object properties.\n *\n * @typeparam T - The object type to be partially modified.\n */\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]\n}\n\n/**\n * Represents a type that makes all properties of the given type required deeply.\n *\n * This utility type recursively makes all properties of the given type required, including nested properties.\n * If a property is already required, it remains unchanged.\n *\n * @typeParam T - The type to make all properties required.\n * @returns A new type with all properties required.\n *\n * @example\n * ```typescript\n * type Person = {\n * name?: string;\n * age?: number;\n * address?: {\n * street?: string;\n * city?: string;\n * };\n * };\n *\n * type RequiredPerson = DeepRequired<Person>;\n * // Result: {\n * // name: string;\n * // age: number;\n * // address: {\n * // street: string;\n * // city: string;\n * // };\n * // }\n * ```\n */\nexport type DeepRequired<T> = {\n [P in keyof T]-?: T[P] extends object ? DeepRequired<T[P]> : T[P]\n}\n\n/**\n * Checks if an object has all the required properties specified by the given paths.\n *\n * @template T - The type of the object.\n * @param {DeepPartial<T>} obj - The object to check.\n * @param {string[]} paths - The paths of the required properties.\n * @returns {boolean} - Returns true if the object has all the required properties, otherwise returns false.\n */\nexport function hasRequiredProperties<T>(obj: DeepPartial<T>, paths: string[]): boolean {\n /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */\n return paths.every((path) => {\n const keys = path.split('.')\n let current: any = obj\n\n for (const key of keys) {\n if (current !== undefined && key in current) {\n current = current[key]\n } else {\n return false\n }\n }\n\n return true\n })\n /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */\n}\n\n/**\n * Retrieves the nested keys of an object type.\n *\n * @typeParam T - The object type.\n * @returns The union of all nested keys in the object type.\n *\n * @example\n * // Given the following object type:\n * type Person = {\n * name: string;\n * age: number;\n * address: {\n * street: string;\n * city: string;\n * };\n * };\n *\n * // The `NestedKeys` type will return the following union type:\n * // \"name\" | \"age\" | \"address\" | \"address.street\" | \"address.city\"\n * type AllKeys = NestedKeys<Person>;\n */\nexport type NestedKeys<T> = {\n [K in keyof T]: T[K] extends object ? K | `${K & string}.${NestedKeys<T[K]> & string}` : K\n}[keyof T]\n\n/**\n * Creates a new type that includes only the properties from the input type `T` that are required and not nullable.\n *\n * @typeParam T - The input type.\n * @returns A new type that includes only the required and non-nullable properties from `T`.\n *\n * @example\n * // Define a type with optional and nullable properties\n * type Person = {\n * name?: string;\n * age?: number | null;\n * email: string;\n * };\n *\n * // Create a new type with only the required and non-nullable properties from `Person`\n * type RequiredPerson = RequiredOnly<Person>;\n *\n * // `RequiredPerson` will be:\n * // {\n * // email: string;\n * // }\n */\nexport type RequiredOnly<T> = {\n [K in keyof T as Required<T>[K] extends NonNullable<Required<T>[K]> ? K : never]: T[K]\n}\n\n/**\n * `AtLeast` ensures that at least the specified keys `K` of the type `T` are required,\n * while the rest of the properties are optional.\n *\n * @template T - The original type.\n * @template K - The keys of `T` that should be required.\n *\n * @example\n * interface User {\n * id: string;\n * name: string;\n * email?: string;\n * age?: number;\n * }\n *\n * // At least 'id' and 'name' are required, the rest are optional\n * const user: AtLeast<User, 'email'> = {\n * id: '123',\n * name: 'Alice',\n * email: 'alice@example.com'\n * // age are optional\n * };\n */\nexport type AtLeast<T, K extends keyof T> = Partial<T> & RequiredOnly<T> & Required<Pick<T, K>>\n\n/**\n * RequireAtLeastOne helps create a type where at least one of the properties of an interface (can be any property) is required to exist.\n * https://learn.microsoft.com/en-us/javascript/api/@azure/keyvault-certificates/requireatleastone?view=azure-node-latest\n */\nexport type RequireAtLeastOne<T> = {\n [K in keyof T]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<keyof T, K>>>\n}[keyof T]\n","import * as fs from 'fs'\nimport * as path from 'path'\n\n/**\n * Finds files in the current directory and its parent directories.\n * @param cwd The current working directory.\n * @param expectations The expected file names.\n * @returns An array of file paths that match the expectations.\n */\nexport function findUp(cwd: string, expectations: string[]): string[] {\n let currentDir = cwd\n while (currentDir !== '/') {\n const dirFiles = fs.readdirSync(currentDir)\n const foundFiles = dirFiles.filter((file) => expectations.includes(file))\n if (foundFiles.length > 0) {\n return foundFiles.map((file) => path.join(currentDir, file))\n }\n currentDir = path.dirname(currentDir)\n }\n return []\n}\n","import { createRequire } from 'module'\n\n/**\n * Enables TypeScript support for the specified file or module.\n *\n * @param relativeToPath - The path relative to which the TypeScript module should be resolved.\n * @returns void\n *\n * @remarks\n * This function enables TypeScript support by registering the 'ts-node' module and configuring it with the provided options.\n * The 'ts-node' module allows for on-the-fly TypeScript transpilation without the need for a separate build step.\n *\n * @example\n * enableTS(process.cwd());\n */\nexport function enableTS(relativeToPath: string): void {\n // WARNING: require('ts-node') will cause '[ERROR] Unterminated template (867:31) [plugin commonjs]' in some cases\n // this error can be eliminated by assigning the name to a variable and require that variable\n const moduleName = 'ts-node'\n const require = createRequire(relativeToPath)\n const modulePath = require.resolve(moduleName)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const tsnode = require(modulePath)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access\n tsnode.register({\n transpileOnly: true,\n typeCheck: false,\n })\n}\n\n/**\n * Loads a JavaScript or TypeScript module.\n *\n * @param fileName - The name of the file to load.\n * @param relativeToPath - The path relative to which the file should be resolved.\n * @returns The loaded module.\n *\n * @example\n * // Load a JavaScript module\n * const myModule = loadJSorTS('myModule.js', '/path/to/file.js');\n *\n * // Load a TypeScript module\n * const myModule = loadJSorTS('myModule.ts', '/path/to/file.js');\n */\nexport function loadJSorTS(fileName: string, relativeToPath: string): any {\n if (fileName.endsWith('.ts')) {\n enableTS(relativeToPath)\n }\n\n const require = createRequire(relativeToPath)\n const modulePath = require.resolve(fileName)\n return require(modulePath)\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/account.ts","../src/pad.ts","../src/types.ts","../src/format.ts","../src/logger.ts","../src/deployment.ts","../src/path.ts","../src/assert.ts","../src/promise.ts","../src/array.ts","../src/enum.ts","../src/generic.ts","../src/findup.ts","../src/loader.ts"],"names":["path","format","createLogger","logger","ethers","dirname","getStackTrace","createRequire","require"],"mappings":";AAAA,OAAO,UAA8B;AACrC,OAAOA,WAAU;;;ACDjB,SAAS,mBAAmB;AAC5B,SAAS,eAAe;AACxB,SAAkB,mBAAmB,iBAAiB,wBAAwB;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AI,CAAC;AACnD,MAAI,QAAQ;AAAW,WAAOA,MAAK,QAAQ,GAAG;AAE9C,QAAM,OAAO,WAAW,kBAAkB,EAAE,IAAI,CAAC;AACjD,MAAI,SAAS;AAAW,WAAOA,MAAK,QAAQ,IAAI;AAEhD,QAAM,IAAI,MAAM,8DAA8D;AAClF;AAEA,eAAsB,uBAClB,MACA,MACA,SACAA,OACgB;AAChB,SAAO,IAAI,QAAQ,CAAC,SAAS,YAAY;AACrC,UAAM,UAA0B;AAAA,MAC5B;AAAA,MACA;AAAA,MACA;AAAA,MACA,MAAAA;AAAA,MACA,QAAQ;AAAA,IACZ;AAEA,UAAM,UAAU,KAAK,QAAQ,SAAS,CAAC,cAAc;AACjD,cAAQ,IAAI;AAAA,IAChB,CAAC;AAED,YAAQ,GAAG,SAAS,CAAC,SAAS;AAC1B,cAAQ,KAAK;AAAA,IACjB,CAAC;AAED,YAAQ,IAAI;AAAA,EAChB,CAAC;AACL;AAEO,SAAS,eAAe,KAI7B;AAEE,QAAM,IAAI,IAAI,MAAM,oDAAoD;AACxE,MAAI,GAAG,QAAQ,SAAS,QAAW;AAC/B,UAAM,IAAI,MAAM,eAAe,GAAG,EAAE;AAAA,EACxC;AAEA,SAAO;AAAA,IACH,QAAQ,EAAE,OAAO;AAAA,IACjB,MAAM,EAAE,OAAO;AAAA,IACf,MAAM,EAAE,OAAO;AAAA,EACnB;AACJ","sourcesContent":["import http, { RequestOptions } from 'http'\nimport path from 'path'\n\nexport * from './account'\nexport * from './logger'\nexport * from './deployment'\nexport * from './path'\nexport * from './promise'\nexport * from './types'\nexport * from './assert'\nexport * from './array'\nexport * from './enum'\nexport * from './pad'\nexport * from './format'\nexport * from './generic'\nexport * from './findup'\nexport * from './loader'\n\nimport { sync as findUpSync } from 'find-up'\n\nimport { getLogger } from './logger'\n\nexport const logger = getLogger()\n\nexport async function sleep(timeout: number): Promise<void> {\n await new Promise((resolve) => setTimeout(resolve, timeout))\n}\n\nexport function getProjectPackageManager(cwd?: string): 'yarn' | 'npm' | 'pnpm' {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn !== undefined) return 'yarn'\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm !== undefined) return 'npm'\n\n // pnpm\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm !== undefined) return 'pnpm'\n\n throw new Error('Cannot find package.json or yarn.lock')\n}\n\nexport function getProjectRootDir(cwd?: string): string {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn !== undefined) return path.dirname(yarn)\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm !== undefined) return path.dirname(npm)\n\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm !== undefined) return path.dirname(pnpm)\n\n throw new Error('Cannot find yarn.lock or package-lock.json or pnpm-lock.yaml')\n}\n\nexport async function isHttpServiceReachable(\n host: string,\n port: number,\n timeout: number,\n path?: string\n): Promise<boolean> {\n return new Promise((resolve, _reject) => {\n const options: RequestOptions = {\n host,\n port,\n timeout,\n path,\n method: 'HEAD',\n }\n\n const request = http.request(options, (_response) => {\n resolve(true)\n })\n\n request.on('error', (_err) => {\n resolve(false)\n })\n\n request.end()\n })\n}\n\nexport function extractUrlInfo(url: string): {\n schema: 'http' | 'https'\n host: string\n port: string\n} {\n //TODO: handle the default port for http and https(443, 80)\n const m = url.match(/(?<schema>http|https):\\/\\/(?<host>.*):(?<port>\\d+)/)\n if (m?.groups?.host === undefined) {\n throw new Error(`Invalid url ${url}`)\n }\n\n return {\n schema: m.groups.schema as 'http' | 'https',\n host: m.groups.host,\n port: m.groups.port,\n }\n}\n","import { MnemonicKey } from '@initia/initia.js'\nimport { Keypair } from '@solana/web3.js'\nimport { KeyPair, deriveEd25519Path, keyPairFromSeed, mnemonicToHDSeed } from '@ton/crypto'\nimport { WalletContractV4 } from '@ton/ton'\nimport * as aptos from 'aptos'\nimport * as bip39 from 'bip39'\nimport * as ed25519HdKey from 'ed25519-hd-key'\nimport { ethers } from 'ethers'\n\nimport { ChainType } from '@layerzerolabs/lz-definitions'\n\nimport { hexlify, trim0x } from './format'\n\nexport interface AccountMnemonic {\n mnemonic: string\n path: string\n privateKey?: string\n address?: string\n}\n\nexport function getBIP044Path(chainType: ChainType, account: number, change: number, index: number): string {\n // CAUTION: the path format is different for each chain\n // https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki\n //\n // The \"m/44'/637'/0'/0'/0'\" path is known as a hardened derivation path, while the \"m/44'/637'/0'/0/0\" path is a non-hardened derivation path.\n // The technical benefit of using a hardened derivation path is enhanced security.\n // In BIP32, a hardened derivation is denoted by an apostrophe ('), which indicates that the child private key should be derived in a way\n // that makes it computationally infeasible to derive the parent private key from it. This additional level of security\n // protects the mnemonic phrase and its derived private keys even if one of the derived private keys is compromised.\n // By using a hardened derivation path, like \"m/44'/637'/0'/0'/0'\", each level of the path requires a unique private key derivation,\n // making it more difficult to infer the parent private key from the child private key. This is particularly important when dealing with\n // hierarchical deterministic wallets, as it helps protect funds across multiple accounts or purposes.\n\n switch (chainType) {\n case ChainType.EVM:\n // https://github.com/ethers-io/ethers.js/blob/main/src.ts/wallet/hdwallet.ts\n return `m/44'/60'/${account}'/${change}/${index}`\n case ChainType.APTOS:\n // https://github.com/aptos-labs/aptos-core/blob/main/ecosystem/typescript/sdk/src/aptos_account.ts\n return `m/44'/637'/${account}'/${change}'/${index}'`\n case ChainType.SOLANA:\n // https://github.com/solana-labs/solana/blob/master/sdk/src/derivation_path.rs\n return `m/44'/501'/${account}'/${change}'`\n case ChainType.TON:\n // https://github.com/satoshilabs/slips/blob/master/slip-0044.md#registered-coin-types\n return `m/44'/607'/${account}'/${change}/${index}`\n default:\n throw new Error(`Unsupported chain: ${chainType}`)\n }\n}\n\nexport function getEvmAccountFromMnemonic(mnemonic: string, path = \"m/44'/60'/0'/0/0\"): AccountMnemonic {\n const wallet = ethers.Wallet.fromMnemonic(mnemonic, path)\n return {\n mnemonic,\n path,\n privateKey: wallet.privateKey,\n address: wallet.address,\n }\n}\n\nexport function getAptosAccountFromMnemonic(mnemonic: string, path = \"m/44'/637'/0'/0'/0'\"): AccountMnemonic {\n //https://aptos.dev/guides/building-your-own-wallet/#creating-an-aptos-account\n if (!aptos.AptosAccount.isValidPath(path)) {\n throw new Error(`Invalid derivation path: ${path}`)\n }\n const normalizeMnemonics = mnemonic\n .trim()\n .split(/\\s+/)\n .map((part) => part.toLowerCase())\n .join(' ')\n {\n const { key } = aptos.derivePath(path, trim0x(hexlify(bip39.mnemonicToSeedSync(normalizeMnemonics))))\n const account = new aptos.AptosAccount(new Uint8Array(key)).toPrivateKeyObject()\n return {\n mnemonic,\n path,\n privateKey: account.privateKeyHex,\n address: account.address,\n }\n }\n}\n\nexport function getInitiaAccountFromMnemonic(mnemonic: string, path = \"m/44'/118'/0'/0/0\"): AccountMnemonic {\n const [_, coinType, account, __, index] = path.match(/\\d+/g)?.map(Number) ?? [44, 118, 0, 0, 0]\n const normalizeMnemonics = mnemonic\n .trim()\n .split(/\\s+/)\n .map((part) => part.toLowerCase())\n .join(' ')\n const key = new MnemonicKey({\n mnemonic: normalizeMnemonics,\n coinType,\n account,\n index,\n })\n {\n return {\n mnemonic,\n path,\n privateKey: key.privateKey.toString('hex'),\n address: key.accAddress,\n }\n }\n}\n\nexport function getSolanaAccountFromMnemonic(mnemonic: string, path = \"m/44'/501'/0'/0'\"): AccountMnemonic {\n const seed = bip39.mnemonicToSeedSync(mnemonic, '') // (mnemonic, password)\n const keyPair = Keypair.fromSeed(ed25519HdKey.derivePath(path, seed.toString('hex')).key)\n return {\n mnemonic,\n path,\n privateKey: ethers.utils.hexlify(keyPair.secretKey),\n address: keyPair.publicKey.toBase58(),\n }\n}\n\nexport async function getTonAccountFromMnemonic(\n mnemonic: string,\n path = \"m/44'/607'/0'/0'/0'\",\n workchain = 0\n): Promise<AccountMnemonic> {\n const { wallet, keyPair } = await getTonWalletFromMnemonic(mnemonic, path, workchain)\n return {\n mnemonic,\n path,\n privateKey: ethers.utils.hexlify(keyPair.secretKey),\n address: wallet.address.toString({ bounceable: false, urlSafe: true }),\n }\n}\n\nexport async function getKeypairFromMnemonic(\n chainType: ChainType,\n mnemonic: string,\n path?: string\n): Promise<AccountMnemonic> {\n switch (chainType) {\n case ChainType.EVM:\n return getEvmAccountFromMnemonic(mnemonic, path)\n case ChainType.APTOS:\n return getAptosAccountFromMnemonic(mnemonic, path)\n case ChainType.INITIA:\n return getInitiaAccountFromMnemonic(mnemonic, path)\n case ChainType.SOLANA:\n return getSolanaAccountFromMnemonic(mnemonic, path)\n case ChainType.TON:\n return getTonAccountFromMnemonic(mnemonic, path)\n default:\n throw new Error(`Unsupported chain: ${chainType}`)\n }\n}\n\nexport async function getTonWalletFromMnemonic(\n mnemonic: string,\n path = \"m/44'/607'/0'/0'/0'\",\n workchain = 0\n): Promise<{ wallet: WalletContractV4; keyPair: KeyPair }> {\n const seed: Buffer = await mnemonicToHDSeed(mnemonic.split(' '))\n const indices: number[] = toPathArray(path)\n const derivedSeed: Buffer = await deriveEd25519Path(seed, indices)\n const keyPair: KeyPair = keyPairFromSeed(derivedSeed)\n return {\n wallet: WalletContractV4.create({ publicKey: keyPair.publicKey, workchain }),\n keyPair,\n }\n}\n\n/**\n * Convert a path string to an array of numbers\n *\n * TON currently supports hardened paths only: https://github.com/ton-org/ton-crypto/blob/master/src/hd/ed25519.ts#L32\n *\n * @param path - The path string to convert\n * @returns An array of numbers representing the path\n */\nfunction toPathArray(path: string): number[] {\n if (!/^[mM]'?/.test(path)) {\n throw new Error('Path must start with \"m\" or \"M\"')\n }\n const parts = path.replace(/^[mM]'?\\//, '').split('/')\n const ret: number[] = Array<number>(parts.length)\n for (let i = 0; i < parts.length; i++) {\n const tmp = /(\\d+)[hH']/.exec(parts[i])\n if (tmp === null) {\n throw new Error('Invalid input')\n }\n ret[i] = parseInt(tmp[1], 10)\n\n if (ret[i] >= 0x80000000) {\n throw new Error('Invalid child index')\n }\n }\n return ret\n}\n","import { Bytes, Hex } from './types'\n\ninterface PadOptions {\n dir?: 'left' | 'right' | undefined\n size?: number | null | undefined\n}\nexport type PadReturnType<value extends Bytes | Hex> = value extends Hex ? Hex : Bytes\n\nexport type SizeExceedsPaddingSizeErrorType = SizeExceedsPaddingSizeError & {\n name: 'SizeExceedsPaddingSizeError'\n}\n\nexport class SizeExceedsPaddingSizeError extends Error {\n override name = 'SizeExceedsPaddingSizeError'\n constructor({ size, targetSize, type }: { size: number; targetSize: number; type: 'hex' | 'bytes' }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (${size}) exceeds padding size (${targetSize})`\n )\n }\n}\n\n/**\n * Pads a hexadecimal string or byte array to a specified size.\n *\n * @param hexOrBytes - The hexadecimal string or byte array to pad.\n * @param options - The padding options.\n * @param options.dir - The direction of the padding. Defaults to undefined.\n * @param options.size - The size to pad to. Defaults to 32.\n * @returns The padded hexadecimal string or byte array.\n */\nexport function padify<value extends Bytes | Hex>(\n hexOrBytes: value,\n { dir, size = 32 }: PadOptions = {}\n): PadReturnType<value> {\n if (typeof hexOrBytes === 'string') {\n return padHex(hexOrBytes, { dir, size }) as PadReturnType<value>\n }\n return padBytes(hexOrBytes, { dir, size }) as PadReturnType<value>\n}\n\nfunction padHex(hex: Hex, { dir, size = 32 }: PadOptions = {}): Hex {\n if (size === null) return hex\n const value = hex.replace('0x', '')\n if (value.length > size * 2)\n throw new SizeExceedsPaddingSizeError({\n size: Math.ceil(value.length / 2),\n targetSize: size,\n type: 'hex',\n })\n\n return `0x${value[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`\n}\n\nfunction padBytes(bytes: Bytes, { dir, size = 32 }: PadOptions = {}): Bytes {\n if (size === null) return bytes\n if (bytes.length > size)\n throw new SizeExceedsPaddingSizeError({\n size: bytes.length,\n targetSize: size,\n type: 'bytes',\n })\n const paddedBytes = new Uint8Array(size)\n for (let i = 0; i < size; i++) {\n const padEnd = dir === 'right'\n paddedBytes[padEnd ? i : size - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]\n }\n return paddedBytes\n}\n","/**\n * Type representing a hexadecimal string prefixed with '0x'.\n */\nexport type Hex = `0x${string}`\n\n/**\n * Type representing a hash string prefixed with '0x'.\n */\nexport type Hash = `0x${string}`\n\n/**\n * Checks if a given string is a valid hexadecimal string.\n * @param value - The string to check.\n * @returns True if the string is a valid hexadecimal string, false otherwise.\n */\nexport function isHex(value: string): value is Hex {\n return /^(0x)?[0-9A-F]+/i.test(value)\n}\n\n/**\n * Checks if a given string is a valid hash string.\n * @param value - The string to check.\n * @returns True if the string is a valid hash string, false otherwise.\n */\nexport function isHash(value: string): value is Hash {\n return /^(0x)?[0-9A-F]+/i.test(value)\n}\n\n/**\n * Represents a byte array.\n */\nexport type Bytes = Uint8Array\n","import { padify } from './pad'\nimport { Hex, isHex } from './types'\n\n/**\n * A function to convert Uint8Array to hex string\n * @deprecated use `hexlify` instead\n * @param bytes Uint8Array\n * @returns hex string without 0x prefix, e.g., '0102030405'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return trim0x(hexlify(bytes)).replace(/^0x/i, '')\n}\n\n/**\n * A function to convert hex string to Uint8Array\n * @deprecated use `arrayify` instead\n * @param hex hex string, e.g., '0x0102030405' or '0102030405'\n * @returns Uint8Array\n */\nexport function hexToBytes(hex: string): Uint8Array {\n return arrayify(hex)\n}\n\n/**\n * A function to trim the prefix 0x from a hex string\n * @param hex hex string\n * @returns hex string without 0x prefix\n */\nexport function trim0x(hex: string): string {\n return hex.replace(/^0x/i, '')\n}\n\n/**\n * A function to ensure the prefix 0x from a hex string\n * @param hex hex string\n * @returns hex string with 0x prefix\n */\nexport function ensure0x(hex: string): Hex {\n if (!isHex(hex)) {\n throw new Error('invalid hex string')\n }\n const value = trim0x(hex)\n const retval = `0x${value}`\n return retval as Hex\n}\n\n/**\n * A function to check if a string is a hex string\n * @deprecated use `isHex` instead\n * @param value\n * @returns\n */\nexport function isHexString(value: string): boolean {\n return isHex(value)\n}\n\nfunction _arrayify(value: string | number | Uint8Array | Buffer | bigint): Uint8Array {\n if (value instanceof Uint8Array) {\n return value\n }\n\n if (typeof value === 'string') {\n if (value.match(/^(0x)?[0-9A-F]*$/i)) {\n const hex = value.replace(/^0x/i, '')\n const len = hex.length + 1 - ((hex.length + 1) % 2)\n return Uint8Array.from(Buffer.from(hex.padStart(len, '0'), 'hex'))\n }\n throw new Error('Invalid hex string')\n }\n\n if (typeof value === 'number') {\n if (value < 0) {\n throw new Error('Number must be non-negative')\n }\n const byteArray = []\n while (value > 0) {\n byteArray.push(value & 0xff)\n value >>= 8\n }\n return new Uint8Array(byteArray.reverse())\n }\n\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {\n return new Uint8Array(value)\n }\n\n if (typeof value === 'bigint') {\n const hex = value.toString(16)\n return _arrayify(hex)\n }\n\n throw new Error('unsupported type')\n}\n\n/**\n * A function to convert a string|number|Uint8Array|Buffer|BigInt to Uint8Array\n * @param value - the value to convert\n * @param size - the size of the Uint8Array to return, if not specified, the size of the input will be returned\n */\nexport function arrayify(value: string | number | Uint8Array | Buffer | bigint, size?: number): Uint8Array {\n const bytes = _arrayify(value)\n if (size === undefined) {\n return bytes\n }\n return padify(bytes, { size })\n}\n\n/**\n * A function to convert a string|number|Uint8Array|Buffer|BigInt to hex string\n */\nexport function hexlify(value: string | number | Uint8Array | Buffer | bigint): Hex {\n if (typeof value === 'string' && /^(0x)?[0-9A-F]*$/i.test(value)) {\n const retval = '0x' + trim0x(value)\n return retval as Hex\n }\n\n const bytes = arrayify(value)\n const hex = Buffer.from(bytes).toString('hex')\n return ensure0x(hex)\n}\n","import * as winston from 'winston'\nimport { Logger, format } from 'winston'\n\nlet logger: Logger | undefined = undefined\n\nexport { Logger }\n\nfunction getStackTrace(): string | undefined {\n const oldLimit = Error.stackTraceLimit\n Error.stackTraceLimit = Infinity\n const retval = new Error().stack\n Error.stackTraceLimit = oldLimit\n return retval\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value\nexport function getCircularReplacer(): (key: string, value: unknown) => unknown {\n const ancestors: unknown[] = []\n return function (this: unknown, _key: string, value: unknown) {\n if (typeof value !== 'object' || value === null) {\n return value\n }\n // `this` is the object that value is contained in,\n // i.e., its direct parent.\n while (ancestors.length > 0 && ancestors.at(-1) !== this) {\n ancestors.pop()\n }\n if (ancestors.includes(value)) {\n return '[Circular]'\n }\n ancestors.push(value)\n return value\n }\n}\n\nfunction extractCallerInfo(line: string): string {\n for (const pattern of [/\\((.*?:\\d+:\\d+)\\)$/, /at (.*?:\\d+:\\d+)$/]) {\n const m = line.match(pattern)\n if (m === null) {\n continue\n }\n const [, fileInfoLine] = m\n return fileInfoLine\n }\n return '<unknown>'\n}\n\nconst logFormat = format.printf(\n (info: {\n level: string\n message: string\n timestamp?: string\n metadata?: {\n pretty?: boolean\n format?: string\n }\n }) => {\n if (info.level.toUpperCase() !== 'ERROR' && info.level.toUpperCase() !== 'WARN') {\n return `${info.timestamp} ${info.level.toUpperCase()}: ${info.message}`\n }\n const stack = getStackTrace() ?? ''\n\n const stackLines = stack.split('\\n')\n const index =\n stackLines.findIndex((line) => {\n return line.match(/create-logger.js/)\n }) + 1\n\n let fileInfo = '<unknown>'\n if (stackLines.length > index) {\n const line = stackLines[index]\n fileInfo = extractCallerInfo(line)\n }\n\n const formats: string[] = []\n if (fileInfo !== '<unknown>') {\n formats.push(fileInfo)\n }\n\n const { pretty, format } = info.metadata ?? {}\n const spaces = pretty === true ? 2 : undefined\n const value =\n typeof info.message === 'string'\n ? info.message\n : JSON.stringify(info.message, getCircularReplacer(), spaces)\n const message = format !== undefined ? format.replace(/%s/g, value) : value\n\n return [...formats, message].map((x) => `${info.timestamp} ${info.level.toUpperCase()}: ${x}`).join('\\n')\n }\n)\n\nconst loggerFormat = format.combine(\n format.timestamp({ format: 'YY-MM-DD HH:mm:ss' }),\n format.splat(),\n format.metadata({ fillExcept: ['level', 'timestamp', 'message'] }),\n logFormat,\n format.colorize({\n all: true,\n })\n)\n\nexport function initLogger(level: string): void {\n if (!logger) {\n logger = createLogger(level)\n }\n}\n\nexport function createLogger(level: string): Logger {\n const logger = winston.createLogger({\n level,\n format: loggerFormat,\n transports: [new winston.transports.Console()],\n })\n return logger\n}\n\nexport function getLogger(): Logger {\n initLogger(process.env.LZ_LOG ?? 'info')\n if (!logger) {\n throw new Error('Logger is not initialized')\n }\n return logger\n}\n\nconst exportsObject: {\n getCircularReplacer?: (key: unknown, value: unknown) => unknown\n} = {}\n\nif (process.env.NODE_ENV === 'test') {\n exportsObject.getCircularReplacer = getCircularReplacer\n}\nexport default exportsObject\n","import { ethers } from 'ethers'\n\nimport {\n Chain,\n EndpointId,\n EndpointVersion,\n Network,\n isNetworkEndpointIdSupported,\n networkToChain,\n networkToEndpointId,\n} from '@layerzerolabs/lz-definitions'\n\nexport interface Deployment {\n /** Name of the contract deployment. */\n name: string\n\n /** Optional endpoint identifier. */\n compatibleVersions: EndpointVersion[]\n\n /** Network of deployment. */\n network: Network\n\n /** Optional contract source. */\n source?: string\n\n /** Address of deployed contract. */\n address: string\n\n /** Optional contract ABI. */\n abi?: string\n\n /** Optional contract bytecode. */\n bytecode?: string\n}\n\n/**\n * Find the matching deployments based on the given options\n * @todo Use Partial<EndpointSpec> instead of options\n * @param deployments list of deployments\n * @param nameOrAddress contract name\n * @param options options to match against\n * @returns Deployment\n */\nexport function findDeployment(\n deployments: Deployment[],\n nameOrAddress: string,\n options: { chain?: Chain; source?: string; network?: Network; endpointId?: EndpointId }\n): Deployment {\n const retval = tryFindDeployment(deployments, nameOrAddress, options)\n if (retval === undefined) {\n throw new Error(`Deployment not found: ${nameOrAddress} options:${JSON.stringify(options)}`)\n }\n return retval\n}\n\nexport function tryFindDeployment(\n deployments: Deployment[],\n nameOrAddress: string,\n options: { chain?: Chain; source?: string; network?: Network; endpointId?: EndpointId }\n): Deployment | undefined {\n return deployments.find((deployment) => {\n let hasMatchingNameOrAddress = deployment.name === nameOrAddress\n if (!hasMatchingNameOrAddress && ethers.utils.isAddress(nameOrAddress)) {\n hasMatchingNameOrAddress =\n ethers.utils.getAddress(deployment.address) === ethers.utils.getAddress(nameOrAddress)\n }\n const hasMatchingChain = options.chain == null || options.chain === networkToChain(deployment.network)\n const hasMatchingNetwork = options.network === undefined || options.network === deployment.network\n const hasMatchingSource = options.source === undefined || options.source === deployment.source\n let hasMatchingEndpoint = true\n if (options.endpointId != null) {\n const compatibleEndpoints = deployment.compatibleVersions.map((v) => {\n if (isNetworkEndpointIdSupported(deployment.network, v)) {\n return networkToEndpointId(deployment.network, v)\n }\n return undefined\n })\n hasMatchingEndpoint = compatibleEndpoints.includes(options.endpointId)\n }\n return (\n hasMatchingNameOrAddress &&\n hasMatchingChain &&\n hasMatchingNetwork &&\n hasMatchingEndpoint &&\n hasMatchingSource\n )\n })\n}\n\ntype ContractType = { [key in string]: ethers.Contract }\nconst contractCache: ContractType = {}\nexport function deploymentToEvmContract<T extends ethers.Contract>(\n deployment: Deployment,\n provider?: ethers.providers.Provider\n): T {\n const key = `${deployment.network}-${deployment.address}`\n if (!(key in contractCache)) {\n if (deployment.abi === undefined || deployment.bytecode === undefined) {\n throw new Error('Deployment does not have ABI or bytecode')\n }\n const Contract = new ethers.ContractFactory(deployment.abi, deployment.bytecode)\n contractCache[key] = Contract.attach(deployment.address)\n }\n if (!provider) {\n return contractCache[key] as T\n }\n return contractCache[key].connect(provider) as T\n}\n\nexport function findContract<T extends ethers.Contract>(\n provider: ethers.providers.Provider | undefined,\n deployments: Deployment[],\n nameOrAddress: string,\n options: { chain?: Chain; source?: string; network?: Network; endpointId?: EndpointId }\n): T {\n const deployment = findDeployment(deployments, nameOrAddress, options)\n const retval = deploymentToEvmContract<T>(deployment, provider)\n return retval\n}\n","import { createRequire } from 'module'\n/**\n * A function to return dirname of a path\n * @param path\n * @returns\n */\nexport function dirname(path: string): string {\n const match = path.match(/(.*)([\\\\/][^\\\\/]+)[/\\\\]?$/)\n const [, basePath] = match ?? []\n const dirname = typeof basePath !== 'undefined' ? basePath : path\n return dirname\n}\n\nfunction getStackTrace(stackTraceLimit = Infinity): string | undefined {\n const oldLimit = Error.stackTraceLimit\n Error.stackTraceLimit = stackTraceLimit\n const retval = new Error().stack\n Error.stackTraceLimit = oldLimit\n return retval\n}\n\nfunction getCaller(): string | undefined {\n const lines = (getStackTrace(10) ?? '').split('\\n')\n // Error:\n // at getStackTrace\n // at getCaller\n // at <caller of getCaller>\n // at <expected caller>\n if (lines.length > 1 + 1 + 1 + 1) {\n const line = lines[4]\n const m = line.match(/^.*\\(([^:]*)[^)]*\\)/)\n if (m) {\n return m[1]\n }\n }\n return undefined\n}\n\n/**\n * return the root path of a package\n * @param packageName\n * @param relativeToPath\n * @returns\n */\nexport function pkgroot(packageName: string, relativeToPath?: string): string {\n if (relativeToPath === undefined) {\n relativeToPath = getCaller()\n if (relativeToPath === undefined) {\n relativeToPath = __filename\n }\n }\n\n const filepath = createRequire(relativeToPath).resolve(`${packageName}/package.json`)\n const packagePath = dirname(filepath)\n // https://github.com/yarnpkg/berry/blob/f67dda88fe9d0a892c44af923cbbc50bfe454e0e/packages/docusaurus/docs/advanced/03-pnp/pnp-spec.md\n // In order to properly represent packages listing peer dependencies, Yarn relies on a concept\n // called Virtual Packages. Their most notable property is that they all have different paths\n // (so that Node.js instantiates them as many times as needed), while still being baked by the\n // same concrete folder on disk.\n return packagePath.replace(/.yarn\\/([^/]*\\/)?(__virtual__|\\$\\$virtual)\\/[^/]*\\/\\d*\\//, '')\n}\n","export function assert(condition: boolean, message?: string): asserts condition {\n if (!condition) {\n throw new Error(`Assertion Error: ${message ?? 'condition is false'}`)\n }\n}\n\n/**\n * assertType\n * assertType can be used to assert that a value is of a certain type, and without naming a new variable explicitly.\n * @param value\n * @param fn\n * @param message\n */\nexport function assertType<T, M>(value: T, fn: (v: unknown) => v is M, message?: string): asserts value is T & M {\n if (!fn(value)) {\n throw new Error(`Expected value to be ${message ?? 'of correct type'}`)\n }\n}\n\nexport function assertDefined<T>(value?: T, message?: string): asserts value is NonNullable<T> {\n if (value === undefined || value === null) {\n throw new Error(message ?? 'Value is undefined or null')\n }\n}\n\nexport function asType<T, M>(value: T, fn: (v: unknown) => v is M, message?: string): M {\n if (!fn(value)) {\n throw new Error(`Expected value to be ${message ?? 'of correct type'}`)\n }\n return value\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nexport function assumeType<T>(value: unknown): asserts value is T {}\n","// This file copy from repo:devtools and is located in packages/devtools/src/common/promise.ts\n\nimport { assert } from './assert'\n\n/**\n * Generic type for a hybrid (sync / async) factory\n * that generates an instance of `TOutput` based on arguments of type `TInput`\n *\n * `TInput` represents the list of all function arguments that need to be passed to the factory:\n *\n * ```typescript\n * const mySyncFactory: Factory<[number, boolean], string> = (num: number, bool: boolean): string => \"hello\"\n *\n * const mySyncFactory: Factory<[], string> = async () => \"hello\"\n * ```\n *\n * The hybrid aspect just makes it easier for implementers - if the logic is synchronous,\n * this type will not force any extra `async`.\n */\nexport type Factory<TInput extends unknown[], TOutput> = (...input: TInput) => TOutput | Promise<TOutput>\n\n/**\n * Helper type for argumentless factories a.k.a. tasks\n */\ntype Task<T> = Factory<[], T>\n\n/**\n * Executes tasks in sequence, waiting for each one to finish before starting the next one\n *\n * Will resolve with the output of all tasks or reject with the first rejection.\n *\n * @param {Task<T>[]} tasks\n * @returns {Promise<T[]>}\n */\nexport const sequence = async <T>(tasks: Task<T>[]): Promise<T[]> => {\n const collector: T[] = []\n\n for (const task of tasks) {\n collector.push(await task())\n }\n\n return collector\n}\n\n/**\n * Executes tasks in parallel\n *\n * Will resolve with the output of all tasks or reject with the any rejection.\n *\n * @param {Task<T>[]} tasks\n * @returns {Promise<T[]>}\n */\nexport const parallel = async <T>(tasks: Task<T>[]): Promise<T[]> => Promise.all(tasks.map(async (task) => task()))\n\n/**\n * Executes tasks in a sequence until one resolves.\n *\n * Will resolve with the output of the first task that resolves\n * or reject with the last rejection.\n *\n * Will reject immediatelly if no tasks have been passed\n *\n * @param {Task<T>[]} tasks\n * @returns {Promise<T>}\n */\nexport const first = async <T>(tasks: Task<T>[]): Promise<T> => {\n assert(tasks.length !== 0, `Must have at least one task for first()`)\n\n let lastError: unknown\n\n for (const task of tasks) {\n try {\n return await task()\n } catch (error) {\n lastError = error\n }\n }\n\n throw lastError\n}\n\n/**\n * Helper utility for currying first() - creating a function\n * that behaves like first() but accepts arguments that will be passed to the factory functions\n *\n * @param {Factory<TInput, TOutput>[]} factories\n * @returns {Factory<TInput, TOutput>}\n */\nexport const firstFactory =\n <TInput extends unknown[], TOutput>(...factories: Factory<TInput, TOutput>[]): Factory<TInput, TOutput> =>\n async (...input) =>\n first(factories.map((factory) => async () => factory(...input)))\n\n/**\n * Represents a type that excludes promises.\n * If the input type is a promise, the resulting type is `never`.\n * Otherwise, it is the same as the input type.\n */\nexport type NonPromise<T> = T extends Promise<unknown> ? never : T\n","/**\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\n * @returns\n */\nexport function safeMap<T, R>(elements: T[], callbackfn: (item: T, index: number) => R): [R[], Error | undefined] {\n const result: R[] = []\n try {\n for (let i = 0; i < elements.length; i++) {\n const rv = callbackfn(elements[i], i)\n result.push(rv)\n }\n return [result, undefined]\n } catch (e) {\n return [result, e as Error]\n }\n}\n","/**\n * Converts a string or number value to a corresponding enum value.\n * @param enumType - The enum object.\n * @param value - The value to convert.\n * @returns The converted enum value.\n * @throws Error if the value is not a valid enum value.\n * @example\n * // Usage\n * enum Color {\n * Red = 'red',\n * Green = 'green',\n * Blue = 'blue'\n * }\n *\n * const color: Color = asEnum(Color, 'red');\n * expect(color).toBe(Color.Red);\n *\n * enum Direction {\n * Up = 1,\n * Down,\n * }\n *\n * const direction: Direction = asEnum(Direction, 1);\n * expect(direction).toBe(Direction.Up);\n */\nexport function asEnum<T extends object>(enumType: T, value: string | number): T[keyof T] {\n const enumValues = Object.values(enumType)\n\n if (enumValues.includes(value)) {\n return value as T[keyof T]\n } else {\n throw new Error(`Invalid enum value: ${value}`)\n }\n}\n","/**\n * Represents a type that allows partial modification of all properties in a given object type.\n * This type is similar to the built-in `Partial` type in TypeScript.\n * However, it supports deep partial modification, allowing partial modification of nested object properties.\n *\n * @typeparam T - The object type to be partially modified.\n */\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]\n}\n\n/**\n * Represents a type that makes all properties of the given type required deeply.\n *\n * This utility type recursively makes all properties of the given type required, including nested properties.\n * If a property is already required, it remains unchanged.\n *\n * @typeParam T - The type to make all properties required.\n * @returns A new type with all properties required.\n *\n * @example\n * ```typescript\n * type Person = {\n * name?: string;\n * age?: number;\n * address?: {\n * street?: string;\n * city?: string;\n * };\n * };\n *\n * type RequiredPerson = DeepRequired<Person>;\n * // Result: {\n * // name: string;\n * // age: number;\n * // address: {\n * // street: string;\n * // city: string;\n * // };\n * // }\n * ```\n */\nexport type DeepRequired<T> = {\n [P in keyof T]-?: T[P] extends object ? DeepRequired<T[P]> : T[P]\n}\n\n/**\n * Checks if an object has all the required properties specified by the given paths.\n *\n * @template T - The type of the object.\n * @param {DeepPartial<T>} obj - The object to check.\n * @param {string[]} paths - The paths of the required properties.\n * @returns {boolean} - Returns true if the object has all the required properties, otherwise returns false.\n */\nexport function hasRequiredProperties<T>(obj: DeepPartial<T>, paths: string[]): boolean {\n /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */\n return paths.every((path) => {\n const keys = path.split('.')\n let current: any = obj\n\n for (const key of keys) {\n if (current !== undefined && key in current) {\n current = current[key]\n } else {\n return false\n }\n }\n\n return true\n })\n /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */\n}\n\n/**\n * Retrieves the nested keys of an object type.\n *\n * @typeParam T - The object type.\n * @returns The union of all nested keys in the object type.\n *\n * @example\n * // Given the following object type:\n * type Person = {\n * name: string;\n * age: number;\n * address: {\n * street: string;\n * city: string;\n * };\n * };\n *\n * // The `NestedKeys` type will return the following union type:\n * // \"name\" | \"age\" | \"address\" | \"address.street\" | \"address.city\"\n * type AllKeys = NestedKeys<Person>;\n */\nexport type NestedKeys<T> = {\n [K in keyof T]: T[K] extends object ? K | `${K & string}.${NestedKeys<T[K]> & string}` : K\n}[keyof T]\n\n/**\n * Creates a new type that includes only the properties from the input type `T` that are required and not nullable.\n *\n * @typeParam T - The input type.\n * @returns A new type that includes only the required and non-nullable properties from `T`.\n *\n * @example\n * // Define a type with optional and nullable properties\n * type Person = {\n * name?: string;\n * age?: number | null;\n * email: string;\n * };\n *\n * // Create a new type with only the required and non-nullable properties from `Person`\n * type RequiredPerson = RequiredOnly<Person>;\n *\n * // `RequiredPerson` will be:\n * // {\n * // email: string;\n * // }\n */\nexport type RequiredOnly<T> = {\n [K in keyof T as Required<T>[K] extends NonNullable<Required<T>[K]> ? K : never]: T[K]\n}\n\n/**\n * `AtLeast` ensures that at least the specified keys `K` of the type `T` are required,\n * while the rest of the properties are optional.\n *\n * @template T - The original type.\n * @template K - The keys of `T` that should be required.\n *\n * @example\n * interface User {\n * id: string;\n * name: string;\n * email?: string;\n * age?: number;\n * }\n *\n * // At least 'id' and 'name' are required, the rest are optional\n * const user: AtLeast<User, 'email'> = {\n * id: '123',\n * name: 'Alice',\n * email: 'alice@example.com'\n * // age are optional\n * };\n */\nexport type AtLeast<T, K extends keyof T> = Partial<T> & RequiredOnly<T> & Required<Pick<T, K>>\n\n/**\n * RequireAtLeastOne helps create a type where at least one of the properties of an interface (can be any property) is required to exist.\n * https://learn.microsoft.com/en-us/javascript/api/@azure/keyvault-certificates/requireatleastone?view=azure-node-latest\n */\nexport type RequireAtLeastOne<T> = {\n [K in keyof T]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<keyof T, K>>>\n}[keyof T]\n","import * as fs from 'fs'\nimport * as path from 'path'\n\n/**\n * Finds files in the current directory and its parent directories.\n * @param cwd The current working directory.\n * @param expectations The expected file names.\n * @returns An array of file paths that match the expectations.\n */\nexport function findUp(cwd: string, expectations: string[]): string[] {\n let currentDir = cwd\n while (currentDir !== '/') {\n const dirFiles = fs.readdirSync(currentDir)\n const foundFiles = dirFiles.filter((file) => expectations.includes(file))\n if (foundFiles.length > 0) {\n return foundFiles.map((file) => path.join(currentDir, file))\n }\n currentDir = path.dirname(currentDir)\n }\n return []\n}\n","import { createRequire } from 'module'\n\n/**\n * Enables TypeScript support for the specified file or module.\n *\n * @param relativeToPath - The path relative to which the TypeScript module should be resolved.\n * @returns void\n *\n * @remarks\n * This function enables TypeScript support by registering the 'ts-node' module and configuring it with the provided options.\n * The 'ts-node' module allows for on-the-fly TypeScript transpilation without the need for a separate build step.\n *\n * @example\n * enableTS(process.cwd());\n */\nexport function enableTS(relativeToPath: string): void {\n // WARNING: require('ts-node') will cause '[ERROR] Unterminated template (867:31) [plugin commonjs]' in some cases\n // this error can be eliminated by assigning the name to a variable and require that variable\n const moduleName = 'ts-node'\n const require = createRequire(relativeToPath)\n const modulePath = require.resolve(moduleName)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const tsnode = require(modulePath)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access\n tsnode.register({\n transpileOnly: true,\n typeCheck: false,\n })\n}\n\n/**\n * Loads a JavaScript or TypeScript module.\n *\n * @param fileName - The name of the file to load.\n * @param relativeToPath - The path relative to which the file should be resolved.\n * @returns The loaded module.\n *\n * @example\n * // Load a JavaScript module\n * const myModule = await loadJSorTS('myModule.js', '/path/to/file.js');\n *\n * // Load a TypeScript module\n * const myModule = await loadJSorTS('myModule.ts', '/path/to/file.js');\n */\nexport async function loadJSorTS(fileName: string, relativeToPath: string): Promise<any> {\n /* eslint-disable @typescript-eslint/no-unsafe-return, @typescript-eslint/restrict-template-expressions */\n const require = createRequire(relativeToPath)\n const modulePath = require.resolve(fileName)\n\n if (fileName.endsWith('.ts')) {\n enableTS(relativeToPath)\n return import(modulePath)\n } else if (fileName.endsWith('.mjs')) {\n return import(modulePath)\n } else if (fileName.endsWith('.cjs')) {\n return Promise.resolve(require(modulePath))\n } else if (fileName.endsWith('.js')) {\n try {\n return await Promise.resolve(require(modulePath))\n } catch (requireError) {\n try {\n return await import(modulePath)\n } catch (importError) {\n throw new Error(\n `Failed to load module: ${fileName}. Require error: ${requireError}. Import error: ${importError}`\n )\n }\n }\n } else {\n throw new Error(`Unsupported file extension: ${fileName}`)\n }\n /* eslint-enable @typescript-eslint/no-unsafe-return, @typescript-eslint/restrict-template-expressions */\n}\n"]}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import * as winston from 'winston';
|
|
2
2
|
import { Logger } from 'winston';
|
|
3
3
|
export { Logger } from 'winston';
|
|
4
|
+
import { KeyPair } from '@ton/crypto';
|
|
5
|
+
import { WalletContractV4 } from '@ton/ton';
|
|
4
6
|
import { ChainType, EndpointVersion, Network, Chain, EndpointId } from '@layerzerolabs/lz-definitions';
|
|
5
7
|
import { ethers } from 'ethers';
|
|
6
8
|
|
|
@@ -15,7 +17,12 @@ declare function getEvmAccountFromMnemonic(mnemonic: string, path?: string): Acc
|
|
|
15
17
|
declare function getAptosAccountFromMnemonic(mnemonic: string, path?: string): AccountMnemonic;
|
|
16
18
|
declare function getInitiaAccountFromMnemonic(mnemonic: string, path?: string): AccountMnemonic;
|
|
17
19
|
declare function getSolanaAccountFromMnemonic(mnemonic: string, path?: string): AccountMnemonic;
|
|
18
|
-
declare function
|
|
20
|
+
declare function getTonAccountFromMnemonic(mnemonic: string, path?: string, workchain?: number): Promise<AccountMnemonic>;
|
|
21
|
+
declare function getKeypairFromMnemonic(chainType: ChainType, mnemonic: string, path?: string): Promise<AccountMnemonic>;
|
|
22
|
+
declare function getTonWalletFromMnemonic(mnemonic: string, path?: string, workchain?: number): Promise<{
|
|
23
|
+
wallet: WalletContractV4;
|
|
24
|
+
keyPair: KeyPair;
|
|
25
|
+
}>;
|
|
19
26
|
|
|
20
27
|
declare function getCircularReplacer(): (key: string, value: unknown) => unknown;
|
|
21
28
|
declare function initLogger(level: string): void;
|
|
@@ -453,12 +460,12 @@ declare function enableTS(relativeToPath: string): void;
|
|
|
453
460
|
*
|
|
454
461
|
* @example
|
|
455
462
|
* // Load a JavaScript module
|
|
456
|
-
* const myModule = loadJSorTS('myModule.js', '/path/to/file.js');
|
|
463
|
+
* const myModule = await loadJSorTS('myModule.js', '/path/to/file.js');
|
|
457
464
|
*
|
|
458
465
|
* // Load a TypeScript module
|
|
459
|
-
* const myModule = loadJSorTS('myModule.ts', '/path/to/file.js');
|
|
466
|
+
* const myModule = await loadJSorTS('myModule.ts', '/path/to/file.js');
|
|
460
467
|
*/
|
|
461
|
-
declare function loadJSorTS(fileName: string, relativeToPath: string): any
|
|
468
|
+
declare function loadJSorTS(fileName: string, relativeToPath: string): Promise<any>;
|
|
462
469
|
|
|
463
470
|
declare const logger: winston.Logger;
|
|
464
471
|
declare function sleep(timeout: number): Promise<void>;
|
|
@@ -471,4 +478,4 @@ declare function extractUrlInfo(url: string): {
|
|
|
471
478
|
port: string;
|
|
472
479
|
};
|
|
473
480
|
|
|
474
|
-
export { type AccountMnemonic, type AtLeast, type Bytes, type DeepPartial, type DeepRequired, type Deployment, type Factory, type Hash, type Hex, type NestedKeys, type NonPromise, type PadReturnType, type RequireAtLeastOne, type RequiredOnly, SizeExceedsPaddingSizeError, type SizeExceedsPaddingSizeErrorType, arrayify, asEnum, asType, assert, assertDefined, assertType, assumeType, bytesToHex, createLogger, deploymentToEvmContract, dirname, enableTS, ensure0x, extractUrlInfo, findContract, findDeployment, findUp, first, firstFactory, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getInitiaAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, hasRequiredProperties, hexToBytes, hexlify, initLogger, isHash, isHex, isHexString, isHttpServiceReachable, loadJSorTS, logger, padify, parallel, pkgroot, safeMap, sequence, sleep, trim0x, tryFindDeployment };
|
|
481
|
+
export { type AccountMnemonic, type AtLeast, type Bytes, type DeepPartial, type DeepRequired, type Deployment, type Factory, type Hash, type Hex, type NestedKeys, type NonPromise, type PadReturnType, type RequireAtLeastOne, type RequiredOnly, SizeExceedsPaddingSizeError, type SizeExceedsPaddingSizeErrorType, arrayify, asEnum, asType, assert, assertDefined, assertType, assumeType, bytesToHex, createLogger, deploymentToEvmContract, dirname, enableTS, ensure0x, extractUrlInfo, findContract, findDeployment, findUp, first, firstFactory, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getInitiaAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, getTonAccountFromMnemonic, getTonWalletFromMnemonic, hasRequiredProperties, hexToBytes, hexlify, initLogger, isHash, isHex, isHexString, isHttpServiceReachable, loadJSorTS, logger, padify, parallel, pkgroot, safeMap, sequence, sleep, trim0x, tryFindDeployment };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import * as winston from 'winston';
|
|
2
2
|
import { Logger } from 'winston';
|
|
3
3
|
export { Logger } from 'winston';
|
|
4
|
+
import { KeyPair } from '@ton/crypto';
|
|
5
|
+
import { WalletContractV4 } from '@ton/ton';
|
|
4
6
|
import { ChainType, EndpointVersion, Network, Chain, EndpointId } from '@layerzerolabs/lz-definitions';
|
|
5
7
|
import { ethers } from 'ethers';
|
|
6
8
|
|
|
@@ -15,7 +17,12 @@ declare function getEvmAccountFromMnemonic(mnemonic: string, path?: string): Acc
|
|
|
15
17
|
declare function getAptosAccountFromMnemonic(mnemonic: string, path?: string): AccountMnemonic;
|
|
16
18
|
declare function getInitiaAccountFromMnemonic(mnemonic: string, path?: string): AccountMnemonic;
|
|
17
19
|
declare function getSolanaAccountFromMnemonic(mnemonic: string, path?: string): AccountMnemonic;
|
|
18
|
-
declare function
|
|
20
|
+
declare function getTonAccountFromMnemonic(mnemonic: string, path?: string, workchain?: number): Promise<AccountMnemonic>;
|
|
21
|
+
declare function getKeypairFromMnemonic(chainType: ChainType, mnemonic: string, path?: string): Promise<AccountMnemonic>;
|
|
22
|
+
declare function getTonWalletFromMnemonic(mnemonic: string, path?: string, workchain?: number): Promise<{
|
|
23
|
+
wallet: WalletContractV4;
|
|
24
|
+
keyPair: KeyPair;
|
|
25
|
+
}>;
|
|
19
26
|
|
|
20
27
|
declare function getCircularReplacer(): (key: string, value: unknown) => unknown;
|
|
21
28
|
declare function initLogger(level: string): void;
|
|
@@ -453,12 +460,12 @@ declare function enableTS(relativeToPath: string): void;
|
|
|
453
460
|
*
|
|
454
461
|
* @example
|
|
455
462
|
* // Load a JavaScript module
|
|
456
|
-
* const myModule = loadJSorTS('myModule.js', '/path/to/file.js');
|
|
463
|
+
* const myModule = await loadJSorTS('myModule.js', '/path/to/file.js');
|
|
457
464
|
*
|
|
458
465
|
* // Load a TypeScript module
|
|
459
|
-
* const myModule = loadJSorTS('myModule.ts', '/path/to/file.js');
|
|
466
|
+
* const myModule = await loadJSorTS('myModule.ts', '/path/to/file.js');
|
|
460
467
|
*/
|
|
461
|
-
declare function loadJSorTS(fileName: string, relativeToPath: string): any
|
|
468
|
+
declare function loadJSorTS(fileName: string, relativeToPath: string): Promise<any>;
|
|
462
469
|
|
|
463
470
|
declare const logger: winston.Logger;
|
|
464
471
|
declare function sleep(timeout: number): Promise<void>;
|
|
@@ -471,4 +478,4 @@ declare function extractUrlInfo(url: string): {
|
|
|
471
478
|
port: string;
|
|
472
479
|
};
|
|
473
480
|
|
|
474
|
-
export { type AccountMnemonic, type AtLeast, type Bytes, type DeepPartial, type DeepRequired, type Deployment, type Factory, type Hash, type Hex, type NestedKeys, type NonPromise, type PadReturnType, type RequireAtLeastOne, type RequiredOnly, SizeExceedsPaddingSizeError, type SizeExceedsPaddingSizeErrorType, arrayify, asEnum, asType, assert, assertDefined, assertType, assumeType, bytesToHex, createLogger, deploymentToEvmContract, dirname, enableTS, ensure0x, extractUrlInfo, findContract, findDeployment, findUp, first, firstFactory, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getInitiaAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, hasRequiredProperties, hexToBytes, hexlify, initLogger, isHash, isHex, isHexString, isHttpServiceReachable, loadJSorTS, logger, padify, parallel, pkgroot, safeMap, sequence, sleep, trim0x, tryFindDeployment };
|
|
481
|
+
export { type AccountMnemonic, type AtLeast, type Bytes, type DeepPartial, type DeepRequired, type Deployment, type Factory, type Hash, type Hex, type NestedKeys, type NonPromise, type PadReturnType, type RequireAtLeastOne, type RequiredOnly, SizeExceedsPaddingSizeError, type SizeExceedsPaddingSizeErrorType, arrayify, asEnum, asType, assert, assertDefined, assertType, assumeType, bytesToHex, createLogger, deploymentToEvmContract, dirname, enableTS, ensure0x, extractUrlInfo, findContract, findDeployment, findUp, first, firstFactory, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getInitiaAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, getTonAccountFromMnemonic, getTonWalletFromMnemonic, hasRequiredProperties, hexToBytes, hexlify, initLogger, isHash, isHex, isHexString, isHttpServiceReachable, loadJSorTS, logger, padify, parallel, pkgroot, safeMap, sequence, sleep, trim0x, tryFindDeployment };
|
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import http from 'http';
|
|
2
2
|
import * as path2 from 'path';
|
|
3
3
|
import path2__default from 'path';
|
|
4
|
-
import { Keypair } from '@solana/web3.js';
|
|
5
4
|
import { MnemonicKey } from '@initia/initia.js';
|
|
5
|
+
import { Keypair } from '@solana/web3.js';
|
|
6
|
+
import { mnemonicToHDSeed, deriveEd25519Path, keyPairFromSeed } from '@ton/crypto';
|
|
7
|
+
import { WalletContractV4 } from '@ton/ton';
|
|
6
8
|
import * as aptos from 'aptos';
|
|
7
9
|
import * as bip39 from 'bip39';
|
|
8
10
|
import * as ed25519HdKey from 'ed25519-hd-key';
|
|
@@ -148,6 +150,8 @@ function getBIP044Path(chainType, account, change, index) {
|
|
|
148
150
|
return `m/44'/637'/${account}'/${change}'/${index}'`;
|
|
149
151
|
case ChainType.SOLANA:
|
|
150
152
|
return `m/44'/501'/${account}'/${change}'`;
|
|
153
|
+
case ChainType.TON:
|
|
154
|
+
return `m/44'/607'/${account}'/${change}/${index}`;
|
|
151
155
|
default:
|
|
152
156
|
throw new Error(`Unsupported chain: ${chainType}`);
|
|
153
157
|
}
|
|
@@ -205,7 +209,16 @@ function getSolanaAccountFromMnemonic(mnemonic, path3 = "m/44'/501'/0'/0'") {
|
|
|
205
209
|
address: keyPair.publicKey.toBase58()
|
|
206
210
|
};
|
|
207
211
|
}
|
|
208
|
-
function
|
|
212
|
+
async function getTonAccountFromMnemonic(mnemonic, path3 = "m/44'/607'/0'/0'/0'", workchain = 0) {
|
|
213
|
+
const { wallet, keyPair } = await getTonWalletFromMnemonic(mnemonic, path3, workchain);
|
|
214
|
+
return {
|
|
215
|
+
mnemonic,
|
|
216
|
+
path: path3,
|
|
217
|
+
privateKey: ethers.utils.hexlify(keyPair.secretKey),
|
|
218
|
+
address: wallet.address.toString({ bounceable: false, urlSafe: true })
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
async function getKeypairFromMnemonic(chainType, mnemonic, path3) {
|
|
209
222
|
switch (chainType) {
|
|
210
223
|
case ChainType.EVM:
|
|
211
224
|
return getEvmAccountFromMnemonic(mnemonic, path3);
|
|
@@ -215,10 +228,40 @@ function getKeypairFromMnemonic(chainType, mnemonic, path3) {
|
|
|
215
228
|
return getInitiaAccountFromMnemonic(mnemonic, path3);
|
|
216
229
|
case ChainType.SOLANA:
|
|
217
230
|
return getSolanaAccountFromMnemonic(mnemonic, path3);
|
|
231
|
+
case ChainType.TON:
|
|
232
|
+
return getTonAccountFromMnemonic(mnemonic, path3);
|
|
218
233
|
default:
|
|
219
234
|
throw new Error(`Unsupported chain: ${chainType}`);
|
|
220
235
|
}
|
|
221
236
|
}
|
|
237
|
+
async function getTonWalletFromMnemonic(mnemonic, path3 = "m/44'/607'/0'/0'/0'", workchain = 0) {
|
|
238
|
+
const seed = await mnemonicToHDSeed(mnemonic.split(" "));
|
|
239
|
+
const indices = toPathArray(path3);
|
|
240
|
+
const derivedSeed = await deriveEd25519Path(seed, indices);
|
|
241
|
+
const keyPair = keyPairFromSeed(derivedSeed);
|
|
242
|
+
return {
|
|
243
|
+
wallet: WalletContractV4.create({ publicKey: keyPair.publicKey, workchain }),
|
|
244
|
+
keyPair
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
function toPathArray(path3) {
|
|
248
|
+
if (!/^[mM]'?/.test(path3)) {
|
|
249
|
+
throw new Error('Path must start with "m" or "M"');
|
|
250
|
+
}
|
|
251
|
+
const parts = path3.replace(/^[mM]'?\//, "").split("/");
|
|
252
|
+
const ret = Array(parts.length);
|
|
253
|
+
for (let i = 0; i < parts.length; i++) {
|
|
254
|
+
const tmp = /(\d+)[hH']/.exec(parts[i]);
|
|
255
|
+
if (tmp === null) {
|
|
256
|
+
throw new Error("Invalid input");
|
|
257
|
+
}
|
|
258
|
+
ret[i] = parseInt(tmp[1], 10);
|
|
259
|
+
if (ret[i] >= 2147483648) {
|
|
260
|
+
throw new Error("Invalid child index");
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return ret;
|
|
264
|
+
}
|
|
222
265
|
var logger = void 0;
|
|
223
266
|
function getStackTrace() {
|
|
224
267
|
const oldLimit = Error.stackTraceLimit;
|
|
@@ -504,13 +547,31 @@ function enableTS(relativeToPath) {
|
|
|
504
547
|
typeCheck: false
|
|
505
548
|
});
|
|
506
549
|
}
|
|
507
|
-
function loadJSorTS(fileName, relativeToPath) {
|
|
550
|
+
async function loadJSorTS(fileName, relativeToPath) {
|
|
551
|
+
const require2 = createRequire(relativeToPath);
|
|
552
|
+
const modulePath = require2.resolve(fileName);
|
|
508
553
|
if (fileName.endsWith(".ts")) {
|
|
509
554
|
enableTS(relativeToPath);
|
|
555
|
+
return import(modulePath);
|
|
556
|
+
} else if (fileName.endsWith(".mjs")) {
|
|
557
|
+
return import(modulePath);
|
|
558
|
+
} else if (fileName.endsWith(".cjs")) {
|
|
559
|
+
return Promise.resolve(require2(modulePath));
|
|
560
|
+
} else if (fileName.endsWith(".js")) {
|
|
561
|
+
try {
|
|
562
|
+
return await Promise.resolve(require2(modulePath));
|
|
563
|
+
} catch (requireError) {
|
|
564
|
+
try {
|
|
565
|
+
return await import(modulePath);
|
|
566
|
+
} catch (importError) {
|
|
567
|
+
throw new Error(
|
|
568
|
+
`Failed to load module: ${fileName}. Require error: ${requireError}. Import error: ${importError}`
|
|
569
|
+
);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
} else {
|
|
573
|
+
throw new Error(`Unsupported file extension: ${fileName}`);
|
|
510
574
|
}
|
|
511
|
-
const require2 = createRequire(relativeToPath);
|
|
512
|
-
const modulePath = require2.resolve(fileName);
|
|
513
|
-
return require2(modulePath);
|
|
514
575
|
}
|
|
515
576
|
var logger2 = getLogger();
|
|
516
577
|
async function sleep(timeout) {
|
|
@@ -570,6 +631,6 @@ function extractUrlInfo(url) {
|
|
|
570
631
|
};
|
|
571
632
|
}
|
|
572
633
|
|
|
573
|
-
export { SizeExceedsPaddingSizeError, arrayify, asEnum, asType, assert, assertDefined, assertType, assumeType, bytesToHex, createLogger2 as createLogger, deploymentToEvmContract, dirname, enableTS, ensure0x, extractUrlInfo, findContract, findDeployment, findUp, first, firstFactory, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getInitiaAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, hasRequiredProperties, hexToBytes, hexlify, initLogger, isHash, isHex, isHexString, isHttpServiceReachable, loadJSorTS, logger2 as logger, padify, parallel, pkgroot, safeMap, sequence, sleep, trim0x, tryFindDeployment };
|
|
634
|
+
export { SizeExceedsPaddingSizeError, arrayify, asEnum, asType, assert, assertDefined, assertType, assumeType, bytesToHex, createLogger2 as createLogger, deploymentToEvmContract, dirname, enableTS, ensure0x, extractUrlInfo, findContract, findDeployment, findUp, first, firstFactory, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getInitiaAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, getTonAccountFromMnemonic, getTonWalletFromMnemonic, hasRequiredProperties, hexToBytes, hexlify, initLogger, isHash, isHex, isHexString, isHttpServiceReachable, loadJSorTS, logger2 as logger, padify, parallel, pkgroot, safeMap, sequence, sleep, trim0x, tryFindDeployment };
|
|
574
635
|
//# sourceMappingURL=out.js.map
|
|
575
636
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/account.ts","../src/pad.ts","../src/types.ts","../src/format.ts","../src/logger.ts","../src/deployment.ts","../src/path.ts","../src/assert.ts","../src/promise.ts","../src/array.ts","../src/enum.ts","../src/generic.ts","../src/findup.ts","../src/loader.ts"],"names":["path","format","createLogger","logger","ethers","dirname","getStackTrace","createRequire","require"],"mappings":";AAAA,OAAO,UAA8B;AACrC,OAAOA,WAAU;;;ACDjB,SAAS,eAAe;AACxB,SAAS,mBAAmB;AAC5B,YAAY,WAAW;AACvB,YAAY,WAAW;AACvB,YAAY,kBAAkB;AAC9B,SAAS,cAAc;AAEvB,SAAS,iBAAiB;;;ACKnB,IAAM,8BAAN,cAA0C,MAAM;A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GAAG,EAAE;AAAA,EACxC;AAEA,SAAO;AAAA,IACH,QAAQ,EAAE,OAAO;AAAA,IACjB,MAAM,EAAE,OAAO;AAAA,IACf,MAAM,EAAE,OAAO;AAAA,EACnB;AACJ","sourcesContent":["import http, { RequestOptions } from 'http'\nimport path from 'path'\n\nexport * from './account'\nexport * from './logger'\nexport * from './deployment'\nexport * from './path'\nexport * from './promise'\nexport * from './types'\nexport * from './assert'\nexport * from './array'\nexport * from './enum'\nexport * from './pad'\nexport * from './format'\nexport * from './generic'\nexport * from './findup'\nexport * from './loader'\n\nimport { sync as findUpSync } from 'find-up'\n\nimport { getLogger } from './logger'\n\nexport const logger = getLogger()\n\nexport async function sleep(timeout: number): Promise<void> {\n await new Promise((resolve) => setTimeout(resolve, timeout))\n}\n\nexport function getProjectPackageManager(cwd?: string): 'yarn' | 'npm' | 'pnpm' {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn !== undefined) return 'yarn'\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm !== undefined) return 'npm'\n\n // pnpm\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm !== undefined) return 'pnpm'\n\n throw new Error('Cannot find package.json or yarn.lock')\n}\n\nexport function getProjectRootDir(cwd?: string): string {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn !== undefined) return path.dirname(yarn)\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm !== undefined) return path.dirname(npm)\n\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm !== undefined) return path.dirname(pnpm)\n\n throw new Error('Cannot find yarn.lock or package-lock.json or pnpm-lock.yaml')\n}\n\nexport async function isHttpServiceReachable(\n host: string,\n port: number,\n timeout: number,\n path?: string\n): Promise<boolean> {\n return new Promise((resolve, _reject) => {\n const options: RequestOptions = {\n host,\n port,\n timeout,\n path,\n method: 'HEAD',\n }\n\n const request = http.request(options, (_response) => {\n resolve(true)\n })\n\n request.on('error', (_err) => {\n resolve(false)\n })\n\n request.end()\n })\n}\n\nexport function extractUrlInfo(url: string): {\n schema: 'http' | 'https'\n host: string\n port: string\n} {\n //TODO: handle the default port for http and https(443, 80)\n const m = url.match(/(?<schema>http|https):\\/\\/(?<host>.*):(?<port>\\d+)/)\n if (m?.groups?.host === undefined) {\n throw new Error(`Invalid url ${url}`)\n }\n\n return {\n schema: m.groups.schema as 'http' | 'https',\n host: m.groups.host,\n port: m.groups.port,\n }\n}\n","import { Keypair } from '@solana/web3.js'\nimport { MnemonicKey } from '@initia/initia.js'\nimport * as aptos from 'aptos'\nimport * as bip39 from 'bip39'\nimport * as ed25519HdKey from 'ed25519-hd-key'\nimport { ethers } from 'ethers'\n\nimport { ChainType } from '@layerzerolabs/lz-definitions'\n\nimport { hexlify, trim0x } from './format'\n\nexport interface AccountMnemonic {\n mnemonic: string\n path: string\n privateKey?: string\n address?: string\n}\n\nexport function getBIP044Path(chainType: ChainType, account: number, change: number, index: number): string {\n // CAUTION: the path format is different for each chain\n // https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki\n //\n // The \"m/44'/637'/0'/0'/0'\" path is known as a hardened derivation path, while the \"m/44'/637'/0'/0/0\" path is a non-hardened derivation path.\n // The technical benefit of using a hardened derivation path is enhanced security.\n // In BIP32, a hardened derivation is denoted by an apostrophe ('), which indicates that the child private key should be derived in a way\n // that makes it computationally infeasible to derive the parent private key from it. This additional level of security\n // protects the mnemonic phrase and its derived private keys even if one of the derived private keys is compromised.\n // By using a hardened derivation path, like \"m/44'/637'/0'/0'/0'\", each level of the path requires a unique private key derivation,\n // making it more difficult to infer the parent private key from the child private key. This is particularly important when dealing with\n // hierarchical deterministic wallets, as it helps protect funds across multiple accounts or purposes.\n\n switch (chainType) {\n case ChainType.EVM:\n // https://github.com/ethers-io/ethers.js/blob/main/src.ts/wallet/hdwallet.ts\n return `m/44'/60'/${account}'/${change}/${index}`\n case ChainType.APTOS:\n // https://github.com/aptos-labs/aptos-core/blob/main/ecosystem/typescript/sdk/src/aptos_account.ts\n return `m/44'/637'/${account}'/${change}'/${index}'`\n case ChainType.SOLANA:\n // https://github.com/solana-labs/solana/blob/master/sdk/src/derivation_path.rs\n return `m/44'/501'/${account}'/${change}'`\n default:\n throw new Error(`Unsupported chain: ${chainType}`)\n }\n}\n\nexport function getEvmAccountFromMnemonic(mnemonic: string, path = \"m/44'/60'/0'/0/0\"): AccountMnemonic {\n const wallet = ethers.Wallet.fromMnemonic(mnemonic, path)\n return {\n mnemonic,\n path,\n privateKey: wallet.privateKey,\n address: wallet.address,\n }\n}\n\nexport function getAptosAccountFromMnemonic(mnemonic: string, path = \"m/44'/637'/0'/0'/0'\"): AccountMnemonic {\n //https://aptos.dev/guides/building-your-own-wallet/#creating-an-aptos-account\n if (!aptos.AptosAccount.isValidPath(path)) {\n throw new Error(`Invalid derivation path: ${path}`)\n }\n const normalizeMnemonics = mnemonic\n .trim()\n .split(/\\s+/)\n .map((part) => part.toLowerCase())\n .join(' ')\n {\n const { key } = aptos.derivePath(path, trim0x(hexlify(bip39.mnemonicToSeedSync(normalizeMnemonics))))\n const account = new aptos.AptosAccount(new Uint8Array(key)).toPrivateKeyObject()\n return {\n mnemonic,\n path,\n privateKey: account.privateKeyHex,\n address: account.address,\n }\n }\n}\n\nexport function getInitiaAccountFromMnemonic(mnemonic: string, path = \"m/44'/118'/0'/0/0\"): AccountMnemonic {\n const [_, coinType, account, __, index] = path.match(/\\d+/g)?.map(Number) ?? [44, 118, 0, 0, 0]\n const normalizeMnemonics = mnemonic\n .trim()\n .split(/\\s+/)\n .map((part) => part.toLowerCase())\n .join(' ')\n const key = new MnemonicKey({\n mnemonic: normalizeMnemonics,\n coinType,\n account,\n index,\n })\n {\n return {\n mnemonic,\n path,\n privateKey: key.privateKey.toString('hex'),\n address: key.accAddress,\n }\n }\n}\n\nexport function getSolanaAccountFromMnemonic(mnemonic: string, path = \"m/44'/501'/0'/0'\"): AccountMnemonic {\n const seed = bip39.mnemonicToSeedSync(mnemonic, '') // (mnemonic, password)\n const keyPair = Keypair.fromSeed(ed25519HdKey.derivePath(path, seed.toString('hex')).key)\n return {\n mnemonic,\n path,\n privateKey: ethers.utils.hexlify(keyPair.secretKey),\n address: keyPair.publicKey.toBase58(),\n }\n}\n\nexport function getKeypairFromMnemonic(chainType: ChainType, mnemonic: string, path?: string): AccountMnemonic {\n switch (chainType) {\n case ChainType.EVM:\n return getEvmAccountFromMnemonic(mnemonic, path)\n case ChainType.APTOS:\n return getAptosAccountFromMnemonic(mnemonic, path)\n case ChainType.INITIA:\n return getInitiaAccountFromMnemonic(mnemonic, path)\n case ChainType.SOLANA:\n return getSolanaAccountFromMnemonic(mnemonic, path)\n default:\n throw new Error(`Unsupported chain: ${chainType}`)\n }\n}\n","import { Bytes, Hex } from './types'\n\ninterface PadOptions {\n dir?: 'left' | 'right' | undefined\n size?: number | null | undefined\n}\nexport type PadReturnType<value extends Bytes | Hex> = value extends Hex ? Hex : Bytes\n\nexport type SizeExceedsPaddingSizeErrorType = SizeExceedsPaddingSizeError & {\n name: 'SizeExceedsPaddingSizeError'\n}\n\nexport class SizeExceedsPaddingSizeError extends Error {\n override name = 'SizeExceedsPaddingSizeError'\n constructor({ size, targetSize, type }: { size: number; targetSize: number; type: 'hex' | 'bytes' }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (${size}) exceeds padding size (${targetSize})`\n )\n }\n}\n\n/**\n * Pads a hexadecimal string or byte array to a specified size.\n *\n * @param hexOrBytes - The hexadecimal string or byte array to pad.\n * @param options - The padding options.\n * @param options.dir - The direction of the padding. Defaults to undefined.\n * @param options.size - The size to pad to. Defaults to 32.\n * @returns The padded hexadecimal string or byte array.\n */\nexport function padify<value extends Bytes | Hex>(\n hexOrBytes: value,\n { dir, size = 32 }: PadOptions = {}\n): PadReturnType<value> {\n if (typeof hexOrBytes === 'string') {\n return padHex(hexOrBytes, { dir, size }) as PadReturnType<value>\n }\n return padBytes(hexOrBytes, { dir, size }) as PadReturnType<value>\n}\n\nfunction padHex(hex: Hex, { dir, size = 32 }: PadOptions = {}): Hex {\n if (size === null) return hex\n const value = hex.replace('0x', '')\n if (value.length > size * 2)\n throw new SizeExceedsPaddingSizeError({\n size: Math.ceil(value.length / 2),\n targetSize: size,\n type: 'hex',\n })\n\n return `0x${value[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`\n}\n\nfunction padBytes(bytes: Bytes, { dir, size = 32 }: PadOptions = {}): Bytes {\n if (size === null) return bytes\n if (bytes.length > size)\n throw new SizeExceedsPaddingSizeError({\n size: bytes.length,\n targetSize: size,\n type: 'bytes',\n })\n const paddedBytes = new Uint8Array(size)\n for (let i = 0; i < size; i++) {\n const padEnd = dir === 'right'\n paddedBytes[padEnd ? i : size - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]\n }\n return paddedBytes\n}\n","/**\n * Type representing a hexadecimal string prefixed with '0x'.\n */\nexport type Hex = `0x${string}`\n\n/**\n * Type representing a hash string prefixed with '0x'.\n */\nexport type Hash = `0x${string}`\n\n/**\n * Checks if a given string is a valid hexadecimal string.\n * @param value - The string to check.\n * @returns True if the string is a valid hexadecimal string, false otherwise.\n */\nexport function isHex(value: string): value is Hex {\n return /^(0x)?[0-9A-F]+/i.test(value)\n}\n\n/**\n * Checks if a given string is a valid hash string.\n * @param value - The string to check.\n * @returns True if the string is a valid hash string, false otherwise.\n */\nexport function isHash(value: string): value is Hash {\n return /^(0x)?[0-9A-F]+/i.test(value)\n}\n\n/**\n * Represents a byte array.\n */\nexport type Bytes = Uint8Array\n","import { padify } from './pad'\nimport { Hex, isHex } from './types'\n\n/**\n * A function to convert Uint8Array to hex string\n * @deprecated use `hexlify` instead\n * @param bytes Uint8Array\n * @returns hex string without 0x prefix, e.g., '0102030405'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return trim0x(hexlify(bytes)).replace(/^0x/i, '')\n}\n\n/**\n * A function to convert hex string to Uint8Array\n * @deprecated use `arrayify` instead\n * @param hex hex string, e.g., '0x0102030405' or '0102030405'\n * @returns Uint8Array\n */\nexport function hexToBytes(hex: string): Uint8Array {\n return arrayify(hex)\n}\n\n/**\n * A function to trim the prefix 0x from a hex string\n * @param hex hex string\n * @returns hex string without 0x prefix\n */\nexport function trim0x(hex: string): string {\n return hex.replace(/^0x/i, '')\n}\n\n/**\n * A function to ensure the prefix 0x from a hex string\n * @param hex hex string\n * @returns hex string with 0x prefix\n */\nexport function ensure0x(hex: string): Hex {\n if (!isHex(hex)) {\n throw new Error('invalid hex string')\n }\n const value = trim0x(hex)\n const retval = `0x${value}`\n return retval as Hex\n}\n\n/**\n * A function to check if a string is a hex string\n * @deprecated use `isHex` instead\n * @param value\n * @returns\n */\nexport function isHexString(value: string): boolean {\n return isHex(value)\n}\n\nfunction _arrayify(value: string | number | Uint8Array | Buffer | bigint): Uint8Array {\n if (value instanceof Uint8Array) {\n return value\n }\n\n if (typeof value === 'string') {\n if (value.match(/^(0x)?[0-9A-F]*$/i)) {\n const hex = value.replace(/^0x/i, '')\n const len = hex.length + 1 - ((hex.length + 1) % 2)\n return Uint8Array.from(Buffer.from(hex.padStart(len, '0'), 'hex'))\n }\n throw new Error('Invalid hex string')\n }\n\n if (typeof value === 'number') {\n if (value < 0) {\n throw new Error('Number must be non-negative')\n }\n const byteArray = []\n while (value > 0) {\n byteArray.push(value & 0xff)\n value >>= 8\n }\n return new Uint8Array(byteArray.reverse())\n }\n\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {\n return new Uint8Array(value)\n }\n\n if (typeof value === 'bigint') {\n const hex = value.toString(16)\n return _arrayify(hex)\n }\n\n throw new Error('unsupported type')\n}\n\n/**\n * A function to convert a string|number|Uint8Array|Buffer|BigInt to Uint8Array\n * @param value - the value to convert\n * @param size - the size of the Uint8Array to return, if not specified, the size of the input will be returned\n */\nexport function arrayify(value: string | number | Uint8Array | Buffer | bigint, size?: number): Uint8Array {\n const bytes = _arrayify(value)\n if (size === undefined) {\n return bytes\n }\n return padify(bytes, { size })\n}\n\n/**\n * A function to convert a string|number|Uint8Array|Buffer|BigInt to hex string\n */\nexport function hexlify(value: string | number | Uint8Array | Buffer | bigint): Hex {\n if (typeof value === 'string' && /^(0x)?[0-9A-F]*$/i.test(value)) {\n const retval = '0x' + trim0x(value)\n return retval as Hex\n }\n\n const bytes = arrayify(value)\n const hex = Buffer.from(bytes).toString('hex')\n return ensure0x(hex)\n}\n","import * as winston from 'winston'\nimport { Logger, format } from 'winston'\n\nlet logger: Logger | undefined = undefined\n\nexport { Logger }\n\nfunction getStackTrace(): string | undefined {\n const oldLimit = Error.stackTraceLimit\n Error.stackTraceLimit = Infinity\n const retval = new Error().stack\n Error.stackTraceLimit = oldLimit\n return retval\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value\nexport function getCircularReplacer(): (key: string, value: unknown) => unknown {\n const ancestors: unknown[] = []\n return function (this: unknown, _key: string, value: unknown) {\n if (typeof value !== 'object' || value === null) {\n return value\n }\n // `this` is the object that value is contained in,\n // i.e., its direct parent.\n while (ancestors.length > 0 && ancestors.at(-1) !== this) {\n ancestors.pop()\n }\n if (ancestors.includes(value)) {\n return '[Circular]'\n }\n ancestors.push(value)\n return value\n }\n}\n\nfunction extractCallerInfo(line: string): string {\n for (const pattern of [/\\((.*?:\\d+:\\d+)\\)$/, /at (.*?:\\d+:\\d+)$/]) {\n const m = line.match(pattern)\n if (m === null) {\n continue\n }\n const [, fileInfoLine] = m\n return fileInfoLine\n }\n return '<unknown>'\n}\n\nconst logFormat = format.printf(\n (info: {\n level: string\n message: string\n timestamp?: string\n metadata?: {\n pretty?: boolean\n format?: string\n }\n }) => {\n if (info.level.toUpperCase() !== 'ERROR' && info.level.toUpperCase() !== 'WARN') {\n return `${info.timestamp} ${info.level.toUpperCase()}: ${info.message}`\n }\n const stack = getStackTrace() ?? ''\n\n const stackLines = stack.split('\\n')\n const index =\n stackLines.findIndex((line) => {\n return line.match(/create-logger.js/)\n }) + 1\n\n let fileInfo = '<unknown>'\n if (stackLines.length > index) {\n const line = stackLines[index]\n fileInfo = extractCallerInfo(line)\n }\n\n const formats: string[] = []\n if (fileInfo !== '<unknown>') {\n formats.push(fileInfo)\n }\n\n const { pretty, format } = info.metadata ?? {}\n const spaces = pretty === true ? 2 : undefined\n const value =\n typeof info.message === 'string'\n ? info.message\n : JSON.stringify(info.message, getCircularReplacer(), spaces)\n const message = format !== undefined ? format.replace(/%s/g, value) : value\n\n return [...formats, message].map((x) => `${info.timestamp} ${info.level.toUpperCase()}: ${x}`).join('\\n')\n }\n)\n\nconst loggerFormat = format.combine(\n format.timestamp({ format: 'YY-MM-DD HH:mm:ss' }),\n format.splat(),\n format.metadata({ fillExcept: ['level', 'timestamp', 'message'] }),\n logFormat,\n format.colorize({\n all: true,\n })\n)\n\nexport function initLogger(level: string): void {\n if (!logger) {\n logger = createLogger(level)\n }\n}\n\nexport function createLogger(level: string): Logger {\n const logger = winston.createLogger({\n level,\n format: loggerFormat,\n transports: [new winston.transports.Console()],\n })\n return logger\n}\n\nexport function getLogger(): Logger {\n initLogger(process.env.LZ_LOG ?? 'info')\n if (!logger) {\n throw new Error('Logger is not initialized')\n }\n return logger\n}\n\nconst exportsObject: {\n getCircularReplacer?: (key: unknown, value: unknown) => unknown\n} = {}\n\nif (process.env.NODE_ENV === 'test') {\n exportsObject.getCircularReplacer = getCircularReplacer\n}\nexport default exportsObject\n","import { ethers } from 'ethers'\n\nimport {\n Chain,\n EndpointId,\n EndpointVersion,\n Network,\n isNetworkEndpointIdSupported,\n networkToChain,\n networkToEndpointId,\n} from '@layerzerolabs/lz-definitions'\n\nexport interface Deployment {\n /** Name of the contract deployment. */\n name: string\n\n /** Optional endpoint identifier. */\n compatibleVersions: EndpointVersion[]\n\n /** Network of deployment. */\n network: Network\n\n /** Optional contract source. */\n source?: string\n\n /** Address of deployed contract. */\n address: string\n\n /** Optional contract ABI. */\n abi?: string\n\n /** Optional contract bytecode. */\n bytecode?: string\n}\n\n/**\n * Find the matching deployments based on the given options\n * @todo Use Partial<EndpointSpec> instead of options\n * @param deployments list of deployments\n * @param nameOrAddress contract name\n * @param options options to match against\n * @returns Deployment\n */\nexport function findDeployment(\n deployments: Deployment[],\n nameOrAddress: string,\n options: { chain?: Chain; source?: string; network?: Network; endpointId?: EndpointId }\n): Deployment {\n const retval = tryFindDeployment(deployments, nameOrAddress, options)\n if (retval === undefined) {\n throw new Error(`Deployment not found: ${nameOrAddress} options:${JSON.stringify(options)}`)\n }\n return retval\n}\n\nexport function tryFindDeployment(\n deployments: Deployment[],\n nameOrAddress: string,\n options: { chain?: Chain; source?: string; network?: Network; endpointId?: EndpointId }\n): Deployment | undefined {\n return deployments.find((deployment) => {\n let hasMatchingNameOrAddress = deployment.name === nameOrAddress\n if (!hasMatchingNameOrAddress && ethers.utils.isAddress(nameOrAddress)) {\n hasMatchingNameOrAddress =\n ethers.utils.getAddress(deployment.address) === ethers.utils.getAddress(nameOrAddress)\n }\n const hasMatchingChain = options.chain == null || options.chain === networkToChain(deployment.network)\n const hasMatchingNetwork = options.network === undefined || options.network === deployment.network\n const hasMatchingSource = options.source === undefined || options.source === deployment.source\n let hasMatchingEndpoint = true\n if (options.endpointId != null) {\n const compatibleEndpoints = deployment.compatibleVersions.map((v) => {\n if (isNetworkEndpointIdSupported(deployment.network, v)) {\n return networkToEndpointId(deployment.network, v)\n }\n return undefined\n })\n hasMatchingEndpoint = compatibleEndpoints.includes(options.endpointId)\n }\n return (\n hasMatchingNameOrAddress &&\n hasMatchingChain &&\n hasMatchingNetwork &&\n hasMatchingEndpoint &&\n hasMatchingSource\n )\n })\n}\n\ntype ContractType = { [key in string]: ethers.Contract }\nconst contractCache: ContractType = {}\nexport function deploymentToEvmContract<T extends ethers.Contract>(\n deployment: Deployment,\n provider?: ethers.providers.Provider\n): T {\n const key = `${deployment.network}-${deployment.address}`\n if (!(key in contractCache)) {\n if (deployment.abi === undefined || deployment.bytecode === undefined) {\n throw new Error('Deployment does not have ABI or bytecode')\n }\n const Contract = new ethers.ContractFactory(deployment.abi, deployment.bytecode)\n contractCache[key] = Contract.attach(deployment.address)\n }\n if (!provider) {\n return contractCache[key] as T\n }\n return contractCache[key].connect(provider) as T\n}\n\nexport function findContract<T extends ethers.Contract>(\n provider: ethers.providers.Provider | undefined,\n deployments: Deployment[],\n nameOrAddress: string,\n options: { chain?: Chain; source?: string; network?: Network; endpointId?: EndpointId }\n): T {\n const deployment = findDeployment(deployments, nameOrAddress, options)\n const retval = deploymentToEvmContract<T>(deployment, provider)\n return retval\n}\n","import { createRequire } from 'module'\n/**\n * A function to return dirname of a path\n * @param path\n * @returns\n */\nexport function dirname(path: string): string {\n const match = path.match(/(.*)([\\\\/][^\\\\/]+)[/\\\\]?$/)\n const [, basePath] = match ?? []\n const dirname = typeof basePath !== 'undefined' ? basePath : path\n return dirname\n}\n\nfunction getStackTrace(stackTraceLimit = Infinity): string | undefined {\n const oldLimit = Error.stackTraceLimit\n Error.stackTraceLimit = stackTraceLimit\n const retval = new Error().stack\n Error.stackTraceLimit = oldLimit\n return retval\n}\n\nfunction getCaller(): string | undefined {\n const lines = (getStackTrace(10) ?? '').split('\\n')\n // Error:\n // at getStackTrace\n // at getCaller\n // at <caller of getCaller>\n // at <expected caller>\n if (lines.length > 1 + 1 + 1 + 1) {\n const line = lines[4]\n const m = line.match(/^.*\\(([^:]*)[^)]*\\)/)\n if (m) {\n return m[1]\n }\n }\n return undefined\n}\n\n/**\n * return the root path of a package\n * @param packageName\n * @param relativeToPath\n * @returns\n */\nexport function pkgroot(packageName: string, relativeToPath?: string): string {\n if (relativeToPath === undefined) {\n relativeToPath = getCaller()\n if (relativeToPath === undefined) {\n relativeToPath = __filename\n }\n }\n\n const filepath = createRequire(relativeToPath).resolve(`${packageName}/package.json`)\n const packagePath = dirname(filepath)\n // https://github.com/yarnpkg/berry/blob/f67dda88fe9d0a892c44af923cbbc50bfe454e0e/packages/docusaurus/docs/advanced/03-pnp/pnp-spec.md\n // In order to properly represent packages listing peer dependencies, Yarn relies on a concept\n // called Virtual Packages. Their most notable property is that they all have different paths\n // (so that Node.js instantiates them as many times as needed), while still being baked by the\n // same concrete folder on disk.\n return packagePath.replace(/.yarn\\/([^/]*\\/)?(__virtual__|\\$\\$virtual)\\/[^/]*\\/\\d*\\//, '')\n}\n","export function assert(condition: boolean, message?: string): asserts condition {\n if (!condition) {\n throw new Error(`Assertion Error: ${message ?? 'condition is false'}`)\n }\n}\n\n/**\n * assertType\n * assertType can be used to assert that a value is of a certain type, and without naming a new variable explicitly.\n * @param value\n * @param fn\n * @param message\n */\nexport function assertType<T, M>(value: T, fn: (v: unknown) => v is M, message?: string): asserts value is T & M {\n if (!fn(value)) {\n throw new Error(`Expected value to be ${message ?? 'of correct type'}`)\n }\n}\n\nexport function assertDefined<T>(value?: T, message?: string): asserts value is NonNullable<T> {\n if (value === undefined || value === null) {\n throw new Error(message ?? 'Value is undefined or null')\n }\n}\n\nexport function asType<T, M>(value: T, fn: (v: unknown) => v is M, message?: string): M {\n if (!fn(value)) {\n throw new Error(`Expected value to be ${message ?? 'of correct type'}`)\n }\n return value\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nexport function assumeType<T>(value: unknown): asserts value is T {}\n","// This file copy from repo:devtools and is located in packages/devtools/src/common/promise.ts\n\nimport { assert } from './assert'\n\n/**\n * Generic type for a hybrid (sync / async) factory\n * that generates an instance of `TOutput` based on arguments of type `TInput`\n *\n * `TInput` represents the list of all function arguments that need to be passed to the factory:\n *\n * ```typescript\n * const mySyncFactory: Factory<[number, boolean], string> = (num: number, bool: boolean): string => \"hello\"\n *\n * const mySyncFactory: Factory<[], string> = async () => \"hello\"\n * ```\n *\n * The hybrid aspect just makes it easier for implementers - if the logic is synchronous,\n * this type will not force any extra `async`.\n */\nexport type Factory<TInput extends unknown[], TOutput> = (...input: TInput) => TOutput | Promise<TOutput>\n\n/**\n * Helper type for argumentless factories a.k.a. tasks\n */\ntype Task<T> = Factory<[], T>\n\n/**\n * Executes tasks in sequence, waiting for each one to finish before starting the next one\n *\n * Will resolve with the output of all tasks or reject with the first rejection.\n *\n * @param {Task<T>[]} tasks\n * @returns {Promise<T[]>}\n */\nexport const sequence = async <T>(tasks: Task<T>[]): Promise<T[]> => {\n const collector: T[] = []\n\n for (const task of tasks) {\n collector.push(await task())\n }\n\n return collector\n}\n\n/**\n * Executes tasks in parallel\n *\n * Will resolve with the output of all tasks or reject with the any rejection.\n *\n * @param {Task<T>[]} tasks\n * @returns {Promise<T[]>}\n */\nexport const parallel = async <T>(tasks: Task<T>[]): Promise<T[]> => Promise.all(tasks.map(async (task) => task()))\n\n/**\n * Executes tasks in a sequence until one resolves.\n *\n * Will resolve with the output of the first task that resolves\n * or reject with the last rejection.\n *\n * Will reject immediatelly if no tasks have been passed\n *\n * @param {Task<T>[]} tasks\n * @returns {Promise<T>}\n */\nexport const first = async <T>(tasks: Task<T>[]): Promise<T> => {\n assert(tasks.length !== 0, `Must have at least one task for first()`)\n\n let lastError: unknown\n\n for (const task of tasks) {\n try {\n return await task()\n } catch (error) {\n lastError = error\n }\n }\n\n throw lastError\n}\n\n/**\n * Helper utility for currying first() - creating a function\n * that behaves like first() but accepts arguments that will be passed to the factory functions\n *\n * @param {Factory<TInput, TOutput>[]} factories\n * @returns {Factory<TInput, TOutput>}\n */\nexport const firstFactory =\n <TInput extends unknown[], TOutput>(...factories: Factory<TInput, TOutput>[]): Factory<TInput, TOutput> =>\n async (...input) =>\n first(factories.map((factory) => async () => factory(...input)))\n\n/**\n * Represents a type that excludes promises.\n * If the input type is a promise, the resulting type is `never`.\n * Otherwise, it is the same as the input type.\n */\nexport type NonPromise<T> = T extends Promise<unknown> ? never : T\n","/**\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\n * @returns\n */\nexport function safeMap<T, R>(elements: T[], callbackfn: (item: T, index: number) => R): [R[], Error | undefined] {\n const result: R[] = []\n try {\n for (let i = 0; i < elements.length; i++) {\n const rv = callbackfn(elements[i], i)\n result.push(rv)\n }\n return [result, undefined]\n } catch (e) {\n return [result, e as Error]\n }\n}\n","/**\n * Converts a string or number value to a corresponding enum value.\n * @param enumType - The enum object.\n * @param value - The value to convert.\n * @returns The converted enum value.\n * @throws Error if the value is not a valid enum value.\n * @example\n * // Usage\n * enum Color {\n * Red = 'red',\n * Green = 'green',\n * Blue = 'blue'\n * }\n *\n * const color: Color = asEnum(Color, 'red');\n * expect(color).toBe(Color.Red);\n *\n * enum Direction {\n * Up = 1,\n * Down,\n * }\n *\n * const direction: Direction = asEnum(Direction, 1);\n * expect(direction).toBe(Direction.Up);\n */\nexport function asEnum<T extends object>(enumType: T, value: string | number): T[keyof T] {\n const enumValues = Object.values(enumType)\n\n if (enumValues.includes(value)) {\n return value as T[keyof T]\n } else {\n throw new Error(`Invalid enum value: ${value}`)\n }\n}\n","/**\n * Represents a type that allows partial modification of all properties in a given object type.\n * This type is similar to the built-in `Partial` type in TypeScript.\n * However, it supports deep partial modification, allowing partial modification of nested object properties.\n *\n * @typeparam T - The object type to be partially modified.\n */\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]\n}\n\n/**\n * Represents a type that makes all properties of the given type required deeply.\n *\n * This utility type recursively makes all properties of the given type required, including nested properties.\n * If a property is already required, it remains unchanged.\n *\n * @typeParam T - The type to make all properties required.\n * @returns A new type with all properties required.\n *\n * @example\n * ```typescript\n * type Person = {\n * name?: string;\n * age?: number;\n * address?: {\n * street?: string;\n * city?: string;\n * };\n * };\n *\n * type RequiredPerson = DeepRequired<Person>;\n * // Result: {\n * // name: string;\n * // age: number;\n * // address: {\n * // street: string;\n * // city: string;\n * // };\n * // }\n * ```\n */\nexport type DeepRequired<T> = {\n [P in keyof T]-?: T[P] extends object ? DeepRequired<T[P]> : T[P]\n}\n\n/**\n * Checks if an object has all the required properties specified by the given paths.\n *\n * @template T - The type of the object.\n * @param {DeepPartial<T>} obj - The object to check.\n * @param {string[]} paths - The paths of the required properties.\n * @returns {boolean} - Returns true if the object has all the required properties, otherwise returns false.\n */\nexport function hasRequiredProperties<T>(obj: DeepPartial<T>, paths: string[]): boolean {\n /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */\n return paths.every((path) => {\n const keys = path.split('.')\n let current: any = obj\n\n for (const key of keys) {\n if (current !== undefined && key in current) {\n current = current[key]\n } else {\n return false\n }\n }\n\n return true\n })\n /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */\n}\n\n/**\n * Retrieves the nested keys of an object type.\n *\n * @typeParam T - The object type.\n * @returns The union of all nested keys in the object type.\n *\n * @example\n * // Given the following object type:\n * type Person = {\n * name: string;\n * age: number;\n * address: {\n * street: string;\n * city: string;\n * };\n * };\n *\n * // The `NestedKeys` type will return the following union type:\n * // \"name\" | \"age\" | \"address\" | \"address.street\" | \"address.city\"\n * type AllKeys = NestedKeys<Person>;\n */\nexport type NestedKeys<T> = {\n [K in keyof T]: T[K] extends object ? K | `${K & string}.${NestedKeys<T[K]> & string}` : K\n}[keyof T]\n\n/**\n * Creates a new type that includes only the properties from the input type `T` that are required and not nullable.\n *\n * @typeParam T - The input type.\n * @returns A new type that includes only the required and non-nullable properties from `T`.\n *\n * @example\n * // Define a type with optional and nullable properties\n * type Person = {\n * name?: string;\n * age?: number | null;\n * email: string;\n * };\n *\n * // Create a new type with only the required and non-nullable properties from `Person`\n * type RequiredPerson = RequiredOnly<Person>;\n *\n * // `RequiredPerson` will be:\n * // {\n * // email: string;\n * // }\n */\nexport type RequiredOnly<T> = {\n [K in keyof T as Required<T>[K] extends NonNullable<Required<T>[K]> ? K : never]: T[K]\n}\n\n/**\n * `AtLeast` ensures that at least the specified keys `K` of the type `T` are required,\n * while the rest of the properties are optional.\n *\n * @template T - The original type.\n * @template K - The keys of `T` that should be required.\n *\n * @example\n * interface User {\n * id: string;\n * name: string;\n * email?: string;\n * age?: number;\n * }\n *\n * // At least 'id' and 'name' are required, the rest are optional\n * const user: AtLeast<User, 'email'> = {\n * id: '123',\n * name: 'Alice',\n * email: 'alice@example.com'\n * // age are optional\n * };\n */\nexport type AtLeast<T, K extends keyof T> = Partial<T> & RequiredOnly<T> & Required<Pick<T, K>>\n\n/**\n * RequireAtLeastOne helps create a type where at least one of the properties of an interface (can be any property) is required to exist.\n * https://learn.microsoft.com/en-us/javascript/api/@azure/keyvault-certificates/requireatleastone?view=azure-node-latest\n */\nexport type RequireAtLeastOne<T> = {\n [K in keyof T]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<keyof T, K>>>\n}[keyof T]\n","import * as fs from 'fs'\nimport * as path from 'path'\n\n/**\n * Finds files in the current directory and its parent directories.\n * @param cwd The current working directory.\n * @param expectations The expected file names.\n * @returns An array of file paths that match the expectations.\n */\nexport function findUp(cwd: string, expectations: string[]): string[] {\n let currentDir = cwd\n while (currentDir !== '/') {\n const dirFiles = fs.readdirSync(currentDir)\n const foundFiles = dirFiles.filter((file) => expectations.includes(file))\n if (foundFiles.length > 0) {\n return foundFiles.map((file) => path.join(currentDir, file))\n }\n currentDir = path.dirname(currentDir)\n }\n return []\n}\n","import { createRequire } from 'module'\n\n/**\n * Enables TypeScript support for the specified file or module.\n *\n * @param relativeToPath - The path relative to which the TypeScript module should be resolved.\n * @returns void\n *\n * @remarks\n * This function enables TypeScript support by registering the 'ts-node' module and configuring it with the provided options.\n * The 'ts-node' module allows for on-the-fly TypeScript transpilation without the need for a separate build step.\n *\n * @example\n * enableTS(process.cwd());\n */\nexport function enableTS(relativeToPath: string): void {\n // WARNING: require('ts-node') will cause '[ERROR] Unterminated template (867:31) [plugin commonjs]' in some cases\n // this error can be eliminated by assigning the name to a variable and require that variable\n const moduleName = 'ts-node'\n const require = createRequire(relativeToPath)\n const modulePath = require.resolve(moduleName)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const tsnode = require(modulePath)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access\n tsnode.register({\n transpileOnly: true,\n typeCheck: false,\n })\n}\n\n/**\n * Loads a JavaScript or TypeScript module.\n *\n * @param fileName - The name of the file to load.\n * @param relativeToPath - The path relative to which the file should be resolved.\n * @returns The loaded module.\n *\n * @example\n * // Load a JavaScript module\n * const myModule = loadJSorTS('myModule.js', '/path/to/file.js');\n *\n * // Load a TypeScript module\n * const myModule = loadJSorTS('myModule.ts', '/path/to/file.js');\n */\nexport function loadJSorTS(fileName: string, relativeToPath: string): any {\n if (fileName.endsWith('.ts')) {\n enableTS(relativeToPath)\n }\n\n const require = createRequire(relativeToPath)\n const modulePath = require.resolve(fileName)\n return require(modulePath)\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/account.ts","../src/pad.ts","../src/types.ts","../src/format.ts","../src/logger.ts","../src/deployment.ts","../src/path.ts","../src/assert.ts","../src/promise.ts","../src/array.ts","../src/enum.ts","../src/generic.ts","../src/findup.ts","../src/loader.ts"],"names":["path","format","createLogger","logger","ethers","dirname","getStackTrace","createRequire","require"],"mappings":";AAAA,OAAO,UAA8B;AACrC,OAAOA,WAAU;;;ACDjB,SAAS,mBAAmB;AAC5B,SAAS,eAAe;AACxB,SAAkB,mBAAmB,iBAAiB,wBAAwB;AAC9E,SAAS,wBAAwB;AACjC,YAAY,WAAW;AACvB,YAAY,WAAW;AACvB,YAAY,kBAAkB;AAC9B,SAAS,cAAc;AAEvB,SAAS,iBAAiB;;;ACGnB,IAAM,8BAAN,cAA0C,MAAM;AAAA,EAEnD,YAAY,EAAE,MAAM,YAAY,KAAK,GAAgE;AACjG;AAAA,MACI,GAAG,KAAK,OAAO,CAAC,EAAE,YAAY,CAAC,GAAG,KAC7B,MAAM,CAAC,EACP,YAAY,CAAC,UAAU,IAAI,2BAA2B,UAAU;AAAA,IACzE;AANJ,SAAS,OAAO;AAAA,EAOhB;A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;AAAA,IACZ;AAEA,UAAM,UAAU,KAAK,QAAQ,SAAS,CAAC,cAAc;AACjD,cAAQ,IAAI;AAAA,IAChB,CAAC;AAED,YAAQ,GAAG,SAAS,CAAC,SAAS;AAC1B,cAAQ,KAAK;AAAA,IACjB,CAAC;AAED,YAAQ,IAAI;AAAA,EAChB,CAAC;AACL;AAEO,SAAS,eAAe,KAI7B;AAEE,QAAM,IAAI,IAAI,MAAM,oDAAoD;AACxE,MAAI,GAAG,QAAQ,SAAS,QAAW;AAC/B,UAAM,IAAI,MAAM,eAAe,GAAG,EAAE;AAAA,EACxC;AAEA,SAAO;AAAA,IACH,QAAQ,EAAE,OAAO;AAAA,IACjB,MAAM,EAAE,OAAO;AAAA,IACf,MAAM,EAAE,OAAO;AAAA,EACnB;AACJ","sourcesContent":["import http, { RequestOptions } from 'http'\nimport path from 'path'\n\nexport * from './account'\nexport * from './logger'\nexport * from './deployment'\nexport * from './path'\nexport * from './promise'\nexport * from './types'\nexport * from './assert'\nexport * from './array'\nexport * from './enum'\nexport * from './pad'\nexport * from './format'\nexport * from './generic'\nexport * from './findup'\nexport * from './loader'\n\nimport { sync as findUpSync } from 'find-up'\n\nimport { getLogger } from './logger'\n\nexport const logger = getLogger()\n\nexport async function sleep(timeout: number): Promise<void> {\n await new Promise((resolve) => setTimeout(resolve, timeout))\n}\n\nexport function getProjectPackageManager(cwd?: string): 'yarn' | 'npm' | 'pnpm' {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn !== undefined) return 'yarn'\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm !== undefined) return 'npm'\n\n // pnpm\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm !== undefined) return 'pnpm'\n\n throw new Error('Cannot find package.json or yarn.lock')\n}\n\nexport function getProjectRootDir(cwd?: string): string {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn !== undefined) return path.dirname(yarn)\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm !== undefined) return path.dirname(npm)\n\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm !== undefined) return path.dirname(pnpm)\n\n throw new Error('Cannot find yarn.lock or package-lock.json or pnpm-lock.yaml')\n}\n\nexport async function isHttpServiceReachable(\n host: string,\n port: number,\n timeout: number,\n path?: string\n): Promise<boolean> {\n return new Promise((resolve, _reject) => {\n const options: RequestOptions = {\n host,\n port,\n timeout,\n path,\n method: 'HEAD',\n }\n\n const request = http.request(options, (_response) => {\n resolve(true)\n })\n\n request.on('error', (_err) => {\n resolve(false)\n })\n\n request.end()\n })\n}\n\nexport function extractUrlInfo(url: string): {\n schema: 'http' | 'https'\n host: string\n port: string\n} {\n //TODO: handle the default port for http and https(443, 80)\n const m = url.match(/(?<schema>http|https):\\/\\/(?<host>.*):(?<port>\\d+)/)\n if (m?.groups?.host === undefined) {\n throw new Error(`Invalid url ${url}`)\n }\n\n return {\n schema: m.groups.schema as 'http' | 'https',\n host: m.groups.host,\n port: m.groups.port,\n }\n}\n","import { MnemonicKey } from '@initia/initia.js'\nimport { Keypair } from '@solana/web3.js'\nimport { KeyPair, deriveEd25519Path, keyPairFromSeed, mnemonicToHDSeed } from '@ton/crypto'\nimport { WalletContractV4 } from '@ton/ton'\nimport * as aptos from 'aptos'\nimport * as bip39 from 'bip39'\nimport * as ed25519HdKey from 'ed25519-hd-key'\nimport { ethers } from 'ethers'\n\nimport { ChainType } from '@layerzerolabs/lz-definitions'\n\nimport { hexlify, trim0x } from './format'\n\nexport interface AccountMnemonic {\n mnemonic: string\n path: string\n privateKey?: string\n address?: string\n}\n\nexport function getBIP044Path(chainType: ChainType, account: number, change: number, index: number): string {\n // CAUTION: the path format is different for each chain\n // https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki\n //\n // The \"m/44'/637'/0'/0'/0'\" path is known as a hardened derivation path, while the \"m/44'/637'/0'/0/0\" path is a non-hardened derivation path.\n // The technical benefit of using a hardened derivation path is enhanced security.\n // In BIP32, a hardened derivation is denoted by an apostrophe ('), which indicates that the child private key should be derived in a way\n // that makes it computationally infeasible to derive the parent private key from it. This additional level of security\n // protects the mnemonic phrase and its derived private keys even if one of the derived private keys is compromised.\n // By using a hardened derivation path, like \"m/44'/637'/0'/0'/0'\", each level of the path requires a unique private key derivation,\n // making it more difficult to infer the parent private key from the child private key. This is particularly important when dealing with\n // hierarchical deterministic wallets, as it helps protect funds across multiple accounts or purposes.\n\n switch (chainType) {\n case ChainType.EVM:\n // https://github.com/ethers-io/ethers.js/blob/main/src.ts/wallet/hdwallet.ts\n return `m/44'/60'/${account}'/${change}/${index}`\n case ChainType.APTOS:\n // https://github.com/aptos-labs/aptos-core/blob/main/ecosystem/typescript/sdk/src/aptos_account.ts\n return `m/44'/637'/${account}'/${change}'/${index}'`\n case ChainType.SOLANA:\n // https://github.com/solana-labs/solana/blob/master/sdk/src/derivation_path.rs\n return `m/44'/501'/${account}'/${change}'`\n case ChainType.TON:\n // https://github.com/satoshilabs/slips/blob/master/slip-0044.md#registered-coin-types\n return `m/44'/607'/${account}'/${change}/${index}`\n default:\n throw new Error(`Unsupported chain: ${chainType}`)\n }\n}\n\nexport function getEvmAccountFromMnemonic(mnemonic: string, path = \"m/44'/60'/0'/0/0\"): AccountMnemonic {\n const wallet = ethers.Wallet.fromMnemonic(mnemonic, path)\n return {\n mnemonic,\n path,\n privateKey: wallet.privateKey,\n address: wallet.address,\n }\n}\n\nexport function getAptosAccountFromMnemonic(mnemonic: string, path = \"m/44'/637'/0'/0'/0'\"): AccountMnemonic {\n //https://aptos.dev/guides/building-your-own-wallet/#creating-an-aptos-account\n if (!aptos.AptosAccount.isValidPath(path)) {\n throw new Error(`Invalid derivation path: ${path}`)\n }\n const normalizeMnemonics = mnemonic\n .trim()\n .split(/\\s+/)\n .map((part) => part.toLowerCase())\n .join(' ')\n {\n const { key } = aptos.derivePath(path, trim0x(hexlify(bip39.mnemonicToSeedSync(normalizeMnemonics))))\n const account = new aptos.AptosAccount(new Uint8Array(key)).toPrivateKeyObject()\n return {\n mnemonic,\n path,\n privateKey: account.privateKeyHex,\n address: account.address,\n }\n }\n}\n\nexport function getInitiaAccountFromMnemonic(mnemonic: string, path = \"m/44'/118'/0'/0/0\"): AccountMnemonic {\n const [_, coinType, account, __, index] = path.match(/\\d+/g)?.map(Number) ?? [44, 118, 0, 0, 0]\n const normalizeMnemonics = mnemonic\n .trim()\n .split(/\\s+/)\n .map((part) => part.toLowerCase())\n .join(' ')\n const key = new MnemonicKey({\n mnemonic: normalizeMnemonics,\n coinType,\n account,\n index,\n })\n {\n return {\n mnemonic,\n path,\n privateKey: key.privateKey.toString('hex'),\n address: key.accAddress,\n }\n }\n}\n\nexport function getSolanaAccountFromMnemonic(mnemonic: string, path = \"m/44'/501'/0'/0'\"): AccountMnemonic {\n const seed = bip39.mnemonicToSeedSync(mnemonic, '') // (mnemonic, password)\n const keyPair = Keypair.fromSeed(ed25519HdKey.derivePath(path, seed.toString('hex')).key)\n return {\n mnemonic,\n path,\n privateKey: ethers.utils.hexlify(keyPair.secretKey),\n address: keyPair.publicKey.toBase58(),\n }\n}\n\nexport async function getTonAccountFromMnemonic(\n mnemonic: string,\n path = \"m/44'/607'/0'/0'/0'\",\n workchain = 0\n): Promise<AccountMnemonic> {\n const { wallet, keyPair } = await getTonWalletFromMnemonic(mnemonic, path, workchain)\n return {\n mnemonic,\n path,\n privateKey: ethers.utils.hexlify(keyPair.secretKey),\n address: wallet.address.toString({ bounceable: false, urlSafe: true }),\n }\n}\n\nexport async function getKeypairFromMnemonic(\n chainType: ChainType,\n mnemonic: string,\n path?: string\n): Promise<AccountMnemonic> {\n switch (chainType) {\n case ChainType.EVM:\n return getEvmAccountFromMnemonic(mnemonic, path)\n case ChainType.APTOS:\n return getAptosAccountFromMnemonic(mnemonic, path)\n case ChainType.INITIA:\n return getInitiaAccountFromMnemonic(mnemonic, path)\n case ChainType.SOLANA:\n return getSolanaAccountFromMnemonic(mnemonic, path)\n case ChainType.TON:\n return getTonAccountFromMnemonic(mnemonic, path)\n default:\n throw new Error(`Unsupported chain: ${chainType}`)\n }\n}\n\nexport async function getTonWalletFromMnemonic(\n mnemonic: string,\n path = \"m/44'/607'/0'/0'/0'\",\n workchain = 0\n): Promise<{ wallet: WalletContractV4; keyPair: KeyPair }> {\n const seed: Buffer = await mnemonicToHDSeed(mnemonic.split(' '))\n const indices: number[] = toPathArray(path)\n const derivedSeed: Buffer = await deriveEd25519Path(seed, indices)\n const keyPair: KeyPair = keyPairFromSeed(derivedSeed)\n return {\n wallet: WalletContractV4.create({ publicKey: keyPair.publicKey, workchain }),\n keyPair,\n }\n}\n\n/**\n * Convert a path string to an array of numbers\n *\n * TON currently supports hardened paths only: https://github.com/ton-org/ton-crypto/blob/master/src/hd/ed25519.ts#L32\n *\n * @param path - The path string to convert\n * @returns An array of numbers representing the path\n */\nfunction toPathArray(path: string): number[] {\n if (!/^[mM]'?/.test(path)) {\n throw new Error('Path must start with \"m\" or \"M\"')\n }\n const parts = path.replace(/^[mM]'?\\//, '').split('/')\n const ret: number[] = Array<number>(parts.length)\n for (let i = 0; i < parts.length; i++) {\n const tmp = /(\\d+)[hH']/.exec(parts[i])\n if (tmp === null) {\n throw new Error('Invalid input')\n }\n ret[i] = parseInt(tmp[1], 10)\n\n if (ret[i] >= 0x80000000) {\n throw new Error('Invalid child index')\n }\n }\n return ret\n}\n","import { Bytes, Hex } from './types'\n\ninterface PadOptions {\n dir?: 'left' | 'right' | undefined\n size?: number | null | undefined\n}\nexport type PadReturnType<value extends Bytes | Hex> = value extends Hex ? Hex : Bytes\n\nexport type SizeExceedsPaddingSizeErrorType = SizeExceedsPaddingSizeError & {\n name: 'SizeExceedsPaddingSizeError'\n}\n\nexport class SizeExceedsPaddingSizeError extends Error {\n override name = 'SizeExceedsPaddingSizeError'\n constructor({ size, targetSize, type }: { size: number; targetSize: number; type: 'hex' | 'bytes' }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (${size}) exceeds padding size (${targetSize})`\n )\n }\n}\n\n/**\n * Pads a hexadecimal string or byte array to a specified size.\n *\n * @param hexOrBytes - The hexadecimal string or byte array to pad.\n * @param options - The padding options.\n * @param options.dir - The direction of the padding. Defaults to undefined.\n * @param options.size - The size to pad to. Defaults to 32.\n * @returns The padded hexadecimal string or byte array.\n */\nexport function padify<value extends Bytes | Hex>(\n hexOrBytes: value,\n { dir, size = 32 }: PadOptions = {}\n): PadReturnType<value> {\n if (typeof hexOrBytes === 'string') {\n return padHex(hexOrBytes, { dir, size }) as PadReturnType<value>\n }\n return padBytes(hexOrBytes, { dir, size }) as PadReturnType<value>\n}\n\nfunction padHex(hex: Hex, { dir, size = 32 }: PadOptions = {}): Hex {\n if (size === null) return hex\n const value = hex.replace('0x', '')\n if (value.length > size * 2)\n throw new SizeExceedsPaddingSizeError({\n size: Math.ceil(value.length / 2),\n targetSize: size,\n type: 'hex',\n })\n\n return `0x${value[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`\n}\n\nfunction padBytes(bytes: Bytes, { dir, size = 32 }: PadOptions = {}): Bytes {\n if (size === null) return bytes\n if (bytes.length > size)\n throw new SizeExceedsPaddingSizeError({\n size: bytes.length,\n targetSize: size,\n type: 'bytes',\n })\n const paddedBytes = new Uint8Array(size)\n for (let i = 0; i < size; i++) {\n const padEnd = dir === 'right'\n paddedBytes[padEnd ? i : size - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]\n }\n return paddedBytes\n}\n","/**\n * Type representing a hexadecimal string prefixed with '0x'.\n */\nexport type Hex = `0x${string}`\n\n/**\n * Type representing a hash string prefixed with '0x'.\n */\nexport type Hash = `0x${string}`\n\n/**\n * Checks if a given string is a valid hexadecimal string.\n * @param value - The string to check.\n * @returns True if the string is a valid hexadecimal string, false otherwise.\n */\nexport function isHex(value: string): value is Hex {\n return /^(0x)?[0-9A-F]+/i.test(value)\n}\n\n/**\n * Checks if a given string is a valid hash string.\n * @param value - The string to check.\n * @returns True if the string is a valid hash string, false otherwise.\n */\nexport function isHash(value: string): value is Hash {\n return /^(0x)?[0-9A-F]+/i.test(value)\n}\n\n/**\n * Represents a byte array.\n */\nexport type Bytes = Uint8Array\n","import { padify } from './pad'\nimport { Hex, isHex } from './types'\n\n/**\n * A function to convert Uint8Array to hex string\n * @deprecated use `hexlify` instead\n * @param bytes Uint8Array\n * @returns hex string without 0x prefix, e.g., '0102030405'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return trim0x(hexlify(bytes)).replace(/^0x/i, '')\n}\n\n/**\n * A function to convert hex string to Uint8Array\n * @deprecated use `arrayify` instead\n * @param hex hex string, e.g., '0x0102030405' or '0102030405'\n * @returns Uint8Array\n */\nexport function hexToBytes(hex: string): Uint8Array {\n return arrayify(hex)\n}\n\n/**\n * A function to trim the prefix 0x from a hex string\n * @param hex hex string\n * @returns hex string without 0x prefix\n */\nexport function trim0x(hex: string): string {\n return hex.replace(/^0x/i, '')\n}\n\n/**\n * A function to ensure the prefix 0x from a hex string\n * @param hex hex string\n * @returns hex string with 0x prefix\n */\nexport function ensure0x(hex: string): Hex {\n if (!isHex(hex)) {\n throw new Error('invalid hex string')\n }\n const value = trim0x(hex)\n const retval = `0x${value}`\n return retval as Hex\n}\n\n/**\n * A function to check if a string is a hex string\n * @deprecated use `isHex` instead\n * @param value\n * @returns\n */\nexport function isHexString(value: string): boolean {\n return isHex(value)\n}\n\nfunction _arrayify(value: string | number | Uint8Array | Buffer | bigint): Uint8Array {\n if (value instanceof Uint8Array) {\n return value\n }\n\n if (typeof value === 'string') {\n if (value.match(/^(0x)?[0-9A-F]*$/i)) {\n const hex = value.replace(/^0x/i, '')\n const len = hex.length + 1 - ((hex.length + 1) % 2)\n return Uint8Array.from(Buffer.from(hex.padStart(len, '0'), 'hex'))\n }\n throw new Error('Invalid hex string')\n }\n\n if (typeof value === 'number') {\n if (value < 0) {\n throw new Error('Number must be non-negative')\n }\n const byteArray = []\n while (value > 0) {\n byteArray.push(value & 0xff)\n value >>= 8\n }\n return new Uint8Array(byteArray.reverse())\n }\n\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {\n return new Uint8Array(value)\n }\n\n if (typeof value === 'bigint') {\n const hex = value.toString(16)\n return _arrayify(hex)\n }\n\n throw new Error('unsupported type')\n}\n\n/**\n * A function to convert a string|number|Uint8Array|Buffer|BigInt to Uint8Array\n * @param value - the value to convert\n * @param size - the size of the Uint8Array to return, if not specified, the size of the input will be returned\n */\nexport function arrayify(value: string | number | Uint8Array | Buffer | bigint, size?: number): Uint8Array {\n const bytes = _arrayify(value)\n if (size === undefined) {\n return bytes\n }\n return padify(bytes, { size })\n}\n\n/**\n * A function to convert a string|number|Uint8Array|Buffer|BigInt to hex string\n */\nexport function hexlify(value: string | number | Uint8Array | Buffer | bigint): Hex {\n if (typeof value === 'string' && /^(0x)?[0-9A-F]*$/i.test(value)) {\n const retval = '0x' + trim0x(value)\n return retval as Hex\n }\n\n const bytes = arrayify(value)\n const hex = Buffer.from(bytes).toString('hex')\n return ensure0x(hex)\n}\n","import * as winston from 'winston'\nimport { Logger, format } from 'winston'\n\nlet logger: Logger | undefined = undefined\n\nexport { Logger }\n\nfunction getStackTrace(): string | undefined {\n const oldLimit = Error.stackTraceLimit\n Error.stackTraceLimit = Infinity\n const retval = new Error().stack\n Error.stackTraceLimit = oldLimit\n return retval\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value\nexport function getCircularReplacer(): (key: string, value: unknown) => unknown {\n const ancestors: unknown[] = []\n return function (this: unknown, _key: string, value: unknown) {\n if (typeof value !== 'object' || value === null) {\n return value\n }\n // `this` is the object that value is contained in,\n // i.e., its direct parent.\n while (ancestors.length > 0 && ancestors.at(-1) !== this) {\n ancestors.pop()\n }\n if (ancestors.includes(value)) {\n return '[Circular]'\n }\n ancestors.push(value)\n return value\n }\n}\n\nfunction extractCallerInfo(line: string): string {\n for (const pattern of [/\\((.*?:\\d+:\\d+)\\)$/, /at (.*?:\\d+:\\d+)$/]) {\n const m = line.match(pattern)\n if (m === null) {\n continue\n }\n const [, fileInfoLine] = m\n return fileInfoLine\n }\n return '<unknown>'\n}\n\nconst logFormat = format.printf(\n (info: {\n level: string\n message: string\n timestamp?: string\n metadata?: {\n pretty?: boolean\n format?: string\n }\n }) => {\n if (info.level.toUpperCase() !== 'ERROR' && info.level.toUpperCase() !== 'WARN') {\n return `${info.timestamp} ${info.level.toUpperCase()}: ${info.message}`\n }\n const stack = getStackTrace() ?? ''\n\n const stackLines = stack.split('\\n')\n const index =\n stackLines.findIndex((line) => {\n return line.match(/create-logger.js/)\n }) + 1\n\n let fileInfo = '<unknown>'\n if (stackLines.length > index) {\n const line = stackLines[index]\n fileInfo = extractCallerInfo(line)\n }\n\n const formats: string[] = []\n if (fileInfo !== '<unknown>') {\n formats.push(fileInfo)\n }\n\n const { pretty, format } = info.metadata ?? {}\n const spaces = pretty === true ? 2 : undefined\n const value =\n typeof info.message === 'string'\n ? info.message\n : JSON.stringify(info.message, getCircularReplacer(), spaces)\n const message = format !== undefined ? format.replace(/%s/g, value) : value\n\n return [...formats, message].map((x) => `${info.timestamp} ${info.level.toUpperCase()}: ${x}`).join('\\n')\n }\n)\n\nconst loggerFormat = format.combine(\n format.timestamp({ format: 'YY-MM-DD HH:mm:ss' }),\n format.splat(),\n format.metadata({ fillExcept: ['level', 'timestamp', 'message'] }),\n logFormat,\n format.colorize({\n all: true,\n })\n)\n\nexport function initLogger(level: string): void {\n if (!logger) {\n logger = createLogger(level)\n }\n}\n\nexport function createLogger(level: string): Logger {\n const logger = winston.createLogger({\n level,\n format: loggerFormat,\n transports: [new winston.transports.Console()],\n })\n return logger\n}\n\nexport function getLogger(): Logger {\n initLogger(process.env.LZ_LOG ?? 'info')\n if (!logger) {\n throw new Error('Logger is not initialized')\n }\n return logger\n}\n\nconst exportsObject: {\n getCircularReplacer?: (key: unknown, value: unknown) => unknown\n} = {}\n\nif (process.env.NODE_ENV === 'test') {\n exportsObject.getCircularReplacer = getCircularReplacer\n}\nexport default exportsObject\n","import { ethers } from 'ethers'\n\nimport {\n Chain,\n EndpointId,\n EndpointVersion,\n Network,\n isNetworkEndpointIdSupported,\n networkToChain,\n networkToEndpointId,\n} from '@layerzerolabs/lz-definitions'\n\nexport interface Deployment {\n /** Name of the contract deployment. */\n name: string\n\n /** Optional endpoint identifier. */\n compatibleVersions: EndpointVersion[]\n\n /** Network of deployment. */\n network: Network\n\n /** Optional contract source. */\n source?: string\n\n /** Address of deployed contract. */\n address: string\n\n /** Optional contract ABI. */\n abi?: string\n\n /** Optional contract bytecode. */\n bytecode?: string\n}\n\n/**\n * Find the matching deployments based on the given options\n * @todo Use Partial<EndpointSpec> instead of options\n * @param deployments list of deployments\n * @param nameOrAddress contract name\n * @param options options to match against\n * @returns Deployment\n */\nexport function findDeployment(\n deployments: Deployment[],\n nameOrAddress: string,\n options: { chain?: Chain; source?: string; network?: Network; endpointId?: EndpointId }\n): Deployment {\n const retval = tryFindDeployment(deployments, nameOrAddress, options)\n if (retval === undefined) {\n throw new Error(`Deployment not found: ${nameOrAddress} options:${JSON.stringify(options)}`)\n }\n return retval\n}\n\nexport function tryFindDeployment(\n deployments: Deployment[],\n nameOrAddress: string,\n options: { chain?: Chain; source?: string; network?: Network; endpointId?: EndpointId }\n): Deployment | undefined {\n return deployments.find((deployment) => {\n let hasMatchingNameOrAddress = deployment.name === nameOrAddress\n if (!hasMatchingNameOrAddress && ethers.utils.isAddress(nameOrAddress)) {\n hasMatchingNameOrAddress =\n ethers.utils.getAddress(deployment.address) === ethers.utils.getAddress(nameOrAddress)\n }\n const hasMatchingChain = options.chain == null || options.chain === networkToChain(deployment.network)\n const hasMatchingNetwork = options.network === undefined || options.network === deployment.network\n const hasMatchingSource = options.source === undefined || options.source === deployment.source\n let hasMatchingEndpoint = true\n if (options.endpointId != null) {\n const compatibleEndpoints = deployment.compatibleVersions.map((v) => {\n if (isNetworkEndpointIdSupported(deployment.network, v)) {\n return networkToEndpointId(deployment.network, v)\n }\n return undefined\n })\n hasMatchingEndpoint = compatibleEndpoints.includes(options.endpointId)\n }\n return (\n hasMatchingNameOrAddress &&\n hasMatchingChain &&\n hasMatchingNetwork &&\n hasMatchingEndpoint &&\n hasMatchingSource\n )\n })\n}\n\ntype ContractType = { [key in string]: ethers.Contract }\nconst contractCache: ContractType = {}\nexport function deploymentToEvmContract<T extends ethers.Contract>(\n deployment: Deployment,\n provider?: ethers.providers.Provider\n): T {\n const key = `${deployment.network}-${deployment.address}`\n if (!(key in contractCache)) {\n if (deployment.abi === undefined || deployment.bytecode === undefined) {\n throw new Error('Deployment does not have ABI or bytecode')\n }\n const Contract = new ethers.ContractFactory(deployment.abi, deployment.bytecode)\n contractCache[key] = Contract.attach(deployment.address)\n }\n if (!provider) {\n return contractCache[key] as T\n }\n return contractCache[key].connect(provider) as T\n}\n\nexport function findContract<T extends ethers.Contract>(\n provider: ethers.providers.Provider | undefined,\n deployments: Deployment[],\n nameOrAddress: string,\n options: { chain?: Chain; source?: string; network?: Network; endpointId?: EndpointId }\n): T {\n const deployment = findDeployment(deployments, nameOrAddress, options)\n const retval = deploymentToEvmContract<T>(deployment, provider)\n return retval\n}\n","import { createRequire } from 'module'\n/**\n * A function to return dirname of a path\n * @param path\n * @returns\n */\nexport function dirname(path: string): string {\n const match = path.match(/(.*)([\\\\/][^\\\\/]+)[/\\\\]?$/)\n const [, basePath] = match ?? []\n const dirname = typeof basePath !== 'undefined' ? basePath : path\n return dirname\n}\n\nfunction getStackTrace(stackTraceLimit = Infinity): string | undefined {\n const oldLimit = Error.stackTraceLimit\n Error.stackTraceLimit = stackTraceLimit\n const retval = new Error().stack\n Error.stackTraceLimit = oldLimit\n return retval\n}\n\nfunction getCaller(): string | undefined {\n const lines = (getStackTrace(10) ?? '').split('\\n')\n // Error:\n // at getStackTrace\n // at getCaller\n // at <caller of getCaller>\n // at <expected caller>\n if (lines.length > 1 + 1 + 1 + 1) {\n const line = lines[4]\n const m = line.match(/^.*\\(([^:]*)[^)]*\\)/)\n if (m) {\n return m[1]\n }\n }\n return undefined\n}\n\n/**\n * return the root path of a package\n * @param packageName\n * @param relativeToPath\n * @returns\n */\nexport function pkgroot(packageName: string, relativeToPath?: string): string {\n if (relativeToPath === undefined) {\n relativeToPath = getCaller()\n if (relativeToPath === undefined) {\n relativeToPath = __filename\n }\n }\n\n const filepath = createRequire(relativeToPath).resolve(`${packageName}/package.json`)\n const packagePath = dirname(filepath)\n // https://github.com/yarnpkg/berry/blob/f67dda88fe9d0a892c44af923cbbc50bfe454e0e/packages/docusaurus/docs/advanced/03-pnp/pnp-spec.md\n // In order to properly represent packages listing peer dependencies, Yarn relies on a concept\n // called Virtual Packages. Their most notable property is that they all have different paths\n // (so that Node.js instantiates them as many times as needed), while still being baked by the\n // same concrete folder on disk.\n return packagePath.replace(/.yarn\\/([^/]*\\/)?(__virtual__|\\$\\$virtual)\\/[^/]*\\/\\d*\\//, '')\n}\n","export function assert(condition: boolean, message?: string): asserts condition {\n if (!condition) {\n throw new Error(`Assertion Error: ${message ?? 'condition is false'}`)\n }\n}\n\n/**\n * assertType\n * assertType can be used to assert that a value is of a certain type, and without naming a new variable explicitly.\n * @param value\n * @param fn\n * @param message\n */\nexport function assertType<T, M>(value: T, fn: (v: unknown) => v is M, message?: string): asserts value is T & M {\n if (!fn(value)) {\n throw new Error(`Expected value to be ${message ?? 'of correct type'}`)\n }\n}\n\nexport function assertDefined<T>(value?: T, message?: string): asserts value is NonNullable<T> {\n if (value === undefined || value === null) {\n throw new Error(message ?? 'Value is undefined or null')\n }\n}\n\nexport function asType<T, M>(value: T, fn: (v: unknown) => v is M, message?: string): M {\n if (!fn(value)) {\n throw new Error(`Expected value to be ${message ?? 'of correct type'}`)\n }\n return value\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nexport function assumeType<T>(value: unknown): asserts value is T {}\n","// This file copy from repo:devtools and is located in packages/devtools/src/common/promise.ts\n\nimport { assert } from './assert'\n\n/**\n * Generic type for a hybrid (sync / async) factory\n * that generates an instance of `TOutput` based on arguments of type `TInput`\n *\n * `TInput` represents the list of all function arguments that need to be passed to the factory:\n *\n * ```typescript\n * const mySyncFactory: Factory<[number, boolean], string> = (num: number, bool: boolean): string => \"hello\"\n *\n * const mySyncFactory: Factory<[], string> = async () => \"hello\"\n * ```\n *\n * The hybrid aspect just makes it easier for implementers - if the logic is synchronous,\n * this type will not force any extra `async`.\n */\nexport type Factory<TInput extends unknown[], TOutput> = (...input: TInput) => TOutput | Promise<TOutput>\n\n/**\n * Helper type for argumentless factories a.k.a. tasks\n */\ntype Task<T> = Factory<[], T>\n\n/**\n * Executes tasks in sequence, waiting for each one to finish before starting the next one\n *\n * Will resolve with the output of all tasks or reject with the first rejection.\n *\n * @param {Task<T>[]} tasks\n * @returns {Promise<T[]>}\n */\nexport const sequence = async <T>(tasks: Task<T>[]): Promise<T[]> => {\n const collector: T[] = []\n\n for (const task of tasks) {\n collector.push(await task())\n }\n\n return collector\n}\n\n/**\n * Executes tasks in parallel\n *\n * Will resolve with the output of all tasks or reject with the any rejection.\n *\n * @param {Task<T>[]} tasks\n * @returns {Promise<T[]>}\n */\nexport const parallel = async <T>(tasks: Task<T>[]): Promise<T[]> => Promise.all(tasks.map(async (task) => task()))\n\n/**\n * Executes tasks in a sequence until one resolves.\n *\n * Will resolve with the output of the first task that resolves\n * or reject with the last rejection.\n *\n * Will reject immediatelly if no tasks have been passed\n *\n * @param {Task<T>[]} tasks\n * @returns {Promise<T>}\n */\nexport const first = async <T>(tasks: Task<T>[]): Promise<T> => {\n assert(tasks.length !== 0, `Must have at least one task for first()`)\n\n let lastError: unknown\n\n for (const task of tasks) {\n try {\n return await task()\n } catch (error) {\n lastError = error\n }\n }\n\n throw lastError\n}\n\n/**\n * Helper utility for currying first() - creating a function\n * that behaves like first() but accepts arguments that will be passed to the factory functions\n *\n * @param {Factory<TInput, TOutput>[]} factories\n * @returns {Factory<TInput, TOutput>}\n */\nexport const firstFactory =\n <TInput extends unknown[], TOutput>(...factories: Factory<TInput, TOutput>[]): Factory<TInput, TOutput> =>\n async (...input) =>\n first(factories.map((factory) => async () => factory(...input)))\n\n/**\n * Represents a type that excludes promises.\n * If the input type is a promise, the resulting type is `never`.\n * Otherwise, it is the same as the input type.\n */\nexport type NonPromise<T> = T extends Promise<unknown> ? never : T\n","/**\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\n * @returns\n */\nexport function safeMap<T, R>(elements: T[], callbackfn: (item: T, index: number) => R): [R[], Error | undefined] {\n const result: R[] = []\n try {\n for (let i = 0; i < elements.length; i++) {\n const rv = callbackfn(elements[i], i)\n result.push(rv)\n }\n return [result, undefined]\n } catch (e) {\n return [result, e as Error]\n }\n}\n","/**\n * Converts a string or number value to a corresponding enum value.\n * @param enumType - The enum object.\n * @param value - The value to convert.\n * @returns The converted enum value.\n * @throws Error if the value is not a valid enum value.\n * @example\n * // Usage\n * enum Color {\n * Red = 'red',\n * Green = 'green',\n * Blue = 'blue'\n * }\n *\n * const color: Color = asEnum(Color, 'red');\n * expect(color).toBe(Color.Red);\n *\n * enum Direction {\n * Up = 1,\n * Down,\n * }\n *\n * const direction: Direction = asEnum(Direction, 1);\n * expect(direction).toBe(Direction.Up);\n */\nexport function asEnum<T extends object>(enumType: T, value: string | number): T[keyof T] {\n const enumValues = Object.values(enumType)\n\n if (enumValues.includes(value)) {\n return value as T[keyof T]\n } else {\n throw new Error(`Invalid enum value: ${value}`)\n }\n}\n","/**\n * Represents a type that allows partial modification of all properties in a given object type.\n * This type is similar to the built-in `Partial` type in TypeScript.\n * However, it supports deep partial modification, allowing partial modification of nested object properties.\n *\n * @typeparam T - The object type to be partially modified.\n */\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]\n}\n\n/**\n * Represents a type that makes all properties of the given type required deeply.\n *\n * This utility type recursively makes all properties of the given type required, including nested properties.\n * If a property is already required, it remains unchanged.\n *\n * @typeParam T - The type to make all properties required.\n * @returns A new type with all properties required.\n *\n * @example\n * ```typescript\n * type Person = {\n * name?: string;\n * age?: number;\n * address?: {\n * street?: string;\n * city?: string;\n * };\n * };\n *\n * type RequiredPerson = DeepRequired<Person>;\n * // Result: {\n * // name: string;\n * // age: number;\n * // address: {\n * // street: string;\n * // city: string;\n * // };\n * // }\n * ```\n */\nexport type DeepRequired<T> = {\n [P in keyof T]-?: T[P] extends object ? DeepRequired<T[P]> : T[P]\n}\n\n/**\n * Checks if an object has all the required properties specified by the given paths.\n *\n * @template T - The type of the object.\n * @param {DeepPartial<T>} obj - The object to check.\n * @param {string[]} paths - The paths of the required properties.\n * @returns {boolean} - Returns true if the object has all the required properties, otherwise returns false.\n */\nexport function hasRequiredProperties<T>(obj: DeepPartial<T>, paths: string[]): boolean {\n /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */\n return paths.every((path) => {\n const keys = path.split('.')\n let current: any = obj\n\n for (const key of keys) {\n if (current !== undefined && key in current) {\n current = current[key]\n } else {\n return false\n }\n }\n\n return true\n })\n /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */\n}\n\n/**\n * Retrieves the nested keys of an object type.\n *\n * @typeParam T - The object type.\n * @returns The union of all nested keys in the object type.\n *\n * @example\n * // Given the following object type:\n * type Person = {\n * name: string;\n * age: number;\n * address: {\n * street: string;\n * city: string;\n * };\n * };\n *\n * // The `NestedKeys` type will return the following union type:\n * // \"name\" | \"age\" | \"address\" | \"address.street\" | \"address.city\"\n * type AllKeys = NestedKeys<Person>;\n */\nexport type NestedKeys<T> = {\n [K in keyof T]: T[K] extends object ? K | `${K & string}.${NestedKeys<T[K]> & string}` : K\n}[keyof T]\n\n/**\n * Creates a new type that includes only the properties from the input type `T` that are required and not nullable.\n *\n * @typeParam T - The input type.\n * @returns A new type that includes only the required and non-nullable properties from `T`.\n *\n * @example\n * // Define a type with optional and nullable properties\n * type Person = {\n * name?: string;\n * age?: number | null;\n * email: string;\n * };\n *\n * // Create a new type with only the required and non-nullable properties from `Person`\n * type RequiredPerson = RequiredOnly<Person>;\n *\n * // `RequiredPerson` will be:\n * // {\n * // email: string;\n * // }\n */\nexport type RequiredOnly<T> = {\n [K in keyof T as Required<T>[K] extends NonNullable<Required<T>[K]> ? K : never]: T[K]\n}\n\n/**\n * `AtLeast` ensures that at least the specified keys `K` of the type `T` are required,\n * while the rest of the properties are optional.\n *\n * @template T - The original type.\n * @template K - The keys of `T` that should be required.\n *\n * @example\n * interface User {\n * id: string;\n * name: string;\n * email?: string;\n * age?: number;\n * }\n *\n * // At least 'id' and 'name' are required, the rest are optional\n * const user: AtLeast<User, 'email'> = {\n * id: '123',\n * name: 'Alice',\n * email: 'alice@example.com'\n * // age are optional\n * };\n */\nexport type AtLeast<T, K extends keyof T> = Partial<T> & RequiredOnly<T> & Required<Pick<T, K>>\n\n/**\n * RequireAtLeastOne helps create a type where at least one of the properties of an interface (can be any property) is required to exist.\n * https://learn.microsoft.com/en-us/javascript/api/@azure/keyvault-certificates/requireatleastone?view=azure-node-latest\n */\nexport type RequireAtLeastOne<T> = {\n [K in keyof T]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<keyof T, K>>>\n}[keyof T]\n","import * as fs from 'fs'\nimport * as path from 'path'\n\n/**\n * Finds files in the current directory and its parent directories.\n * @param cwd The current working directory.\n * @param expectations The expected file names.\n * @returns An array of file paths that match the expectations.\n */\nexport function findUp(cwd: string, expectations: string[]): string[] {\n let currentDir = cwd\n while (currentDir !== '/') {\n const dirFiles = fs.readdirSync(currentDir)\n const foundFiles = dirFiles.filter((file) => expectations.includes(file))\n if (foundFiles.length > 0) {\n return foundFiles.map((file) => path.join(currentDir, file))\n }\n currentDir = path.dirname(currentDir)\n }\n return []\n}\n","import { createRequire } from 'module'\n\n/**\n * Enables TypeScript support for the specified file or module.\n *\n * @param relativeToPath - The path relative to which the TypeScript module should be resolved.\n * @returns void\n *\n * @remarks\n * This function enables TypeScript support by registering the 'ts-node' module and configuring it with the provided options.\n * The 'ts-node' module allows for on-the-fly TypeScript transpilation without the need for a separate build step.\n *\n * @example\n * enableTS(process.cwd());\n */\nexport function enableTS(relativeToPath: string): void {\n // WARNING: require('ts-node') will cause '[ERROR] Unterminated template (867:31) [plugin commonjs]' in some cases\n // this error can be eliminated by assigning the name to a variable and require that variable\n const moduleName = 'ts-node'\n const require = createRequire(relativeToPath)\n const modulePath = require.resolve(moduleName)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const tsnode = require(modulePath)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access\n tsnode.register({\n transpileOnly: true,\n typeCheck: false,\n })\n}\n\n/**\n * Loads a JavaScript or TypeScript module.\n *\n * @param fileName - The name of the file to load.\n * @param relativeToPath - The path relative to which the file should be resolved.\n * @returns The loaded module.\n *\n * @example\n * // Load a JavaScript module\n * const myModule = await loadJSorTS('myModule.js', '/path/to/file.js');\n *\n * // Load a TypeScript module\n * const myModule = await loadJSorTS('myModule.ts', '/path/to/file.js');\n */\nexport async function loadJSorTS(fileName: string, relativeToPath: string): Promise<any> {\n /* eslint-disable @typescript-eslint/no-unsafe-return, @typescript-eslint/restrict-template-expressions */\n const require = createRequire(relativeToPath)\n const modulePath = require.resolve(fileName)\n\n if (fileName.endsWith('.ts')) {\n enableTS(relativeToPath)\n return import(modulePath)\n } else if (fileName.endsWith('.mjs')) {\n return import(modulePath)\n } else if (fileName.endsWith('.cjs')) {\n return Promise.resolve(require(modulePath))\n } else if (fileName.endsWith('.js')) {\n try {\n return await Promise.resolve(require(modulePath))\n } catch (requireError) {\n try {\n return await import(modulePath)\n } catch (importError) {\n throw new Error(\n `Failed to load module: ${fileName}. Require error: ${requireError}. Import error: ${importError}`\n )\n }\n }\n } else {\n throw new Error(`Unsupported file extension: ${fileName}`)\n }\n /* eslint-enable @typescript-eslint/no-unsafe-return, @typescript-eslint/restrict-template-expressions */\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@layerzerolabs/lz-utilities",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.14-aptos.0",
|
|
4
4
|
"license": "BUSL-1.1",
|
|
5
5
|
"exports": {
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -22,10 +22,13 @@
|
|
|
22
22
|
"@ethersproject/bytes": "^5.7.0",
|
|
23
23
|
"@ethersproject/providers": "^5.7.0",
|
|
24
24
|
"@initia/initia.js": "^0.2.11",
|
|
25
|
-
"@layerzerolabs/lz-definitions": "^3.0.
|
|
25
|
+
"@layerzerolabs/lz-definitions": "^3.0.14-aptos.0",
|
|
26
26
|
"@noble/hashes": "^1.3.2",
|
|
27
27
|
"@noble/secp256k1": "^1.7.1",
|
|
28
28
|
"@solana/web3.js": "^1.92.1",
|
|
29
|
+
"@ton/core": "^0.59.0",
|
|
30
|
+
"@ton/crypto": "^3.3.0",
|
|
31
|
+
"@ton/ton": "^15.1.0",
|
|
29
32
|
"aptos": "^1.20.0",
|
|
30
33
|
"bip39": "^3.1.0",
|
|
31
34
|
"ed25519-hd-key": "^1.3.0",
|
|
@@ -38,8 +41,8 @@
|
|
|
38
41
|
},
|
|
39
42
|
"devDependencies": {
|
|
40
43
|
"@jest/globals": "^29.7.0",
|
|
41
|
-
"@layerzerolabs/tsup-config-next": "^3.0.
|
|
42
|
-
"@layerzerolabs/typescript-config-next": "^3.0.
|
|
44
|
+
"@layerzerolabs/tsup-config-next": "^3.0.14-aptos.0",
|
|
45
|
+
"@layerzerolabs/typescript-config-next": "^3.0.14-aptos.0",
|
|
43
46
|
"@types/glob": "^8.1.0",
|
|
44
47
|
"@types/jest": "^29.5.10",
|
|
45
48
|
"@types/node": "^20.10.5",
|