@layerzerolabs/lz-utilities 2.1.11 → 2.1.13

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/dist/index.cjs CHANGED
@@ -177,12 +177,12 @@ function initLogger(level) {
177
177
  }
178
178
  }
179
179
  function createLogger2(level) {
180
- const logger2 = winston__namespace.createLogger({
180
+ const logger3 = winston__namespace.createLogger({
181
181
  level,
182
182
  format: loggerFormat,
183
183
  transports: [new winston__namespace.transports.Console()]
184
184
  });
185
- return logger2;
185
+ return logger3;
186
186
  }
187
187
  function getLogger() {
188
188
  initLogger(process.env.LZ_LOG ?? "info");
@@ -256,6 +256,7 @@ function pkgroot(packageName, relativeToPath) {
256
256
  const packagePath = dirname(filepath);
257
257
  return packagePath.replace(/.yarn\/([^/]*\/)?(__virtual__|\$\$virtual)\/[^/]*\/\d*\//, "");
258
258
  }
259
+ var logger2 = getLogger();
259
260
  async function sleep(timeout) {
260
261
  await new Promise((resolve) => setTimeout(resolve, timeout));
261
262
  }
@@ -317,9 +318,9 @@ var CmdExecutor = class {
317
318
  this.currentProcess = null;
318
319
  this.onFinish = null;
319
320
  }
320
- executeCmd(command, args, options, verbose = false, runningCheck, logger2) {
321
- if (logger2) {
322
- logger2.info(`Running command: ${command} ${args?.join(" ") ?? ""}`);
321
+ executeCmd(command, args, options, verbose = false, runningCheck, logger3) {
322
+ if (logger3) {
323
+ logger3.info(`Running command: ${command} ${args?.join(" ") ?? ""}`);
323
324
  } else {
324
325
  console.log(`Running command: ${command} ${args?.join(" ") ?? ""}`);
325
326
  }
@@ -334,23 +335,23 @@ var CmdExecutor = class {
334
335
  runningCheck.runningNotify(true);
335
336
  notified = true;
336
337
  }
337
- if (verbose && logger2) {
338
- logger2.info(data.toString());
338
+ if (verbose && logger3) {
339
+ logger3.info(data.toString());
339
340
  } else if (verbose) {
340
341
  process.stdout.write(data);
341
342
  }
342
343
  });
343
344
  this.currentProcess.stderr?.on("data", (data) => {
344
- if (logger2) {
345
- logger2.error(data.toString());
345
+ if (logger3) {
346
+ logger3.error(data.toString());
346
347
  } else {
347
348
  process.stderr.write(data);
348
349
  }
349
350
  });
350
351
  this.currentProcess.on("exit", (code) => {
351
352
  if (code && code !== 0) {
352
- if (logger2) {
353
- logger2.info(`Command ${command} exited with code ${code}.`);
353
+ if (logger3) {
354
+ logger3.info(`Command ${command} exited with code ${code}.`);
354
355
  } else {
355
356
  console.info(`Command ${command} exited with code ${code}.`);
356
357
  }
@@ -363,7 +364,7 @@ var CmdExecutor = class {
363
364
  }
364
365
  async interrupt(killDescendents = true) {
365
366
  if (this.currentProcess) {
366
- console.log("Killing process:", this.currentProcess.pid);
367
+ logger2.info("Killing process: %s", this.currentProcess.pid);
367
368
  if (killDescendents) {
368
369
  kill__default.default(this.currentProcess.pid);
369
370
  await sleep(2e3);
@@ -396,6 +397,7 @@ exports.getProjectRootDir = getProjectRootDir;
396
397
  exports.getSolanaAccountFromMnemonic = getSolanaAccountFromMnemonic;
397
398
  exports.initLogger = initLogger;
398
399
  exports.isHttpServiceReachable = isHttpServiceReachable;
400
+ exports.logger = logger2;
399
401
  exports.pkgroot = pkgroot;
400
402
  exports.sleep = sleep;
401
403
  //# sourceMappingURL=out.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/account.ts","../src/logger.ts","../src/deployment.ts","../src/path.ts"],"names":["path","format","createLogger","logger","ethers","dirname","getStackTrace"],"mappings":";AAAA,SAAqC,aAAa;AAClD,OAAO,UAA8B;AACrC,OAAO,UAAU;;;ACFjB,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,YAAY,WAAW;AACvB,YAAY,WAAW;AACvB,YAAY,kBAAkB;AAC9B,SAAS,cAAc;AAEvB,SAAS,iBAAiB;AASnB,SAAS,cAAc,WAAsB,SAAiB,QAAgB,OAAuB;AAaxG,UAAQ,WAAW;AAAA,IACf,KAAK,UAAU;AAEX,aAAO,aAAa,OAAO,KAAK,MAAM,IAAI,KA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AAQ;AACR,UAAAA,QAAO,MAAM,KAAK,SAAS,CAAC;AAAA,QAChC,OAAO;AACH,kBAAQ,OAAO,MAAM,IAAI;AAAA,QAC7B;AAAA,MACJ,CAAC;AAID,WAAK,eAAe,GAAG,QAAQ,CAAC,SAAS;AACrC,YAAI,QAAQ,SAAS,GAAG;AACpB,cAAIA,SAAQ;AACR,YAAAA,QAAO,KAAK,WAAW,OAAO,qBAAqB,IAAI,GAAG;AAAA,UAC9D,OAAO;AACH,oBAAQ,KAAK,WAAW,OAAO,qBAAqB,IAAI,GAAG;AAAA,UAC/D;AACA,iBAAO,EAAE,SAAS,GAAG,OAAO,IAAI,KAAK,KAAK,GAAG,CAAC,GAAG,CAAC;AAClD;AAAA,QACJ;AACA,gBAAQ;AAAA,MACZ,CAAC;AAAA,IACL,CAAC;AAAA,EACL;AAAA,EAEA,MAAa,UAAU,kBAAkB,MAAM;AAC3C,QAAI,KAAK,gBAAgB;AACrB,cAAQ,IAAI,oBAAoB,KAAK,eAAe,GAAG;AACvD,UAAI,iBAAiB;AACjB,aAAK,KAAK,eAAe,GAAI;AAE7B,cAAM,MAAM,GAAI;AAAA,MACpB,OAAO;AACH,aAAK,eAAe,KAAK;AAAA,MAC7B;AACA,WAAK,iBAAiB;AAAA,IAC1B;AAAA,EACJ;AACJ","sourcesContent":["import { ChildProcess, SpawnOptions, spawn } from 'child_process'\nimport http, { RequestOptions } from 'http'\nimport path from 'path'\n\nexport * from './account'\nexport * from './logger'\nexport * from './deployment'\nexport * from './path'\n\nimport { sync as findUpSync } from 'find-up'\nimport kill from 'tree-kill'\nimport { Logger } from 'winston'\n\nexport async function sleep(timeout: number) {\n await new Promise((resolve) => setTimeout(resolve, timeout))\n}\n\nexport function getProjectPackageManager(cwd?: string) {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn) return 'yarn'\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm) return 'npm'\n\n // pnpm\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm) return 'pnpm'\n\n throw new Error('Cannot find package.json or yarn.lock')\n}\n\nexport function getProjectRootDir(cwd?: string) {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn) return path.dirname(yarn)\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm) return path.dirname(npm)\n\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm) return path.dirname(pnpm)\n\n throw new Error('Cannot find yarn.lock or package-lock.json or pnpm-lock.yaml')\n}\n\nexport function isHttpServiceReachable(host: string, port: number, timeout: number, path?: string): 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 || !m.groups || !m.groups.host || !m.groups.schema || !m.groups.port) {\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\nexport class CmdExecutor {\n private currentProcess: ChildProcess | null = null\n\n private onFinish: Promise<void> | null = null\n\n public executeCmd(\n command: string,\n args: string[],\n options: SpawnOptions,\n verbose = false,\n runningCheck?: { key: string; runningNotify: (running: boolean) => void },\n logger?: Logger\n ): Promise<void> {\n if (logger) {\n logger.info(`Running command: ${command} ${args?.join(' ') ?? ''}`)\n } else {\n console.log(`Running command: ${command} ${args?.join(' ') ?? ''}`)\n }\n return new Promise<void>((resolve, reject) => {\n let notified = false\n this.currentProcess = spawn(command, args, options)\n if (!this.currentProcess) {\n throw new Error(`Failed to spawn command: ${command} ${args?.join(' ') ?? ''}`)\n }\n\n // Listen for standard output from the child process and print it to the console\n this.currentProcess.stdout?.on('data', (data) => {\n if (runningCheck && !notified && data.toString().includes(runningCheck.key)) {\n runningCheck.runningNotify(true)\n notified = true\n }\n if (verbose && logger) {\n logger.info(data.toString())\n } else if (verbose) {\n process.stdout.write(data)\n }\n })\n\n // Listen for errors from the child process and print them to the console\n this.currentProcess.stderr?.on('data', (data) => {\n if (logger) {\n logger.error(data.toString())\n } else {\n process.stderr.write(data)\n }\n })\n\n // Listen for the exit event of the child process and resolve the promise\n // if the child process exits normally (with code 0)\n this.currentProcess.on('exit', (code) => {\n if (code && code !== 0) {\n if (logger) {\n logger.info(`Command ${command} exited with code ${code}.`)\n } else {\n console.info(`Command ${command} exited with code ${code}.`)\n }\n reject({ command: `${command} ${args.join(' ')}` })\n return\n }\n resolve()\n })\n })\n }\n\n public async interrupt(killDescendents = true) {\n if (this.currentProcess) {\n console.log('Killing process:', this.currentProcess.pid)\n if (killDescendents) {\n kill(this.currentProcess.pid!)\n // the implementation of tree-kill is using spawn, which is async. So we need to wait for a while\n await sleep(2000)\n } else {\n this.currentProcess.kill()\n }\n this.currentProcess = null\n }\n }\n}\n","import { bytesToHex } from '@noble/hashes/utils'\nimport { Keypair } from '@solana/web3.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\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, bytesToHex(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 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.SOLANA:\n return getSolanaAccountFromMnemonic(mnemonic, path)\n default:\n throw new Error(`Unsupported chain: ${chainType}`)\n }\n}\n","import * as winston from 'winston'\nimport { Logger, format } from 'winston'\n\nlet logger: Logger\n\nexport { Logger }\n\nfunction getStackTrace() {\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() {\n const ancestors: any[] = []\n return function (key: any, value: any) {\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 // @ts-ignore\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 === undefined || m === null) {\n continue\n }\n const [, fileInfoLine] = m\n return fileInfoLine\n }\n return '<unknown>'\n}\n\nconst logFormat = format.printf((info) => {\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 spaces = info.metadata?.pretty === true ? 2 : undefined\n const value =\n typeof info.message === 'string' ? info.message : JSON.stringify(info.message, getCircularReplacer(), spaces)\n const format = info.metadata?.format\n const message = format ? format.replace(/%s/g, value) : value\n\n return [...formats, message].map((x) => `${info.timestamp} ${info.level.toUpperCase()}: ${x}`).join('\\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) {\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 return logger\n}\n\nconst exportsObject = {}\nif (process.env['NODE_ENV'] === 'test') {\n // @ts-ignore\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 * @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 | 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 || options.chain === networkToChain(deployment.network)\n const hasMatchingNetwork = !options.network || options.network === deployment.network\n const hasMatchingSource = !options.source || options.source === deployment.source\n let hasMatchingEndpoint = true\n if (options.endpointId) {\n const compatibleEndpoints = deployment.compatibleVersions.map((v) => {\n if (isNetworkEndpointIdSupported(deployment.network, v)) {\n return networkToEndpointId(deployment.network, v)\n }\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 (!contractCache[key]) {\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","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) {\n const match = path.match(/(.*)([\\\\/][^\\\\/]+)[/\\\\]?$/)\n const [, basePath] = match || []\n const dirname = basePath || path\n return dirname\n}\n\nfunction getStackTrace(stackTraceLimit = Infinity) {\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 && 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}\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) {\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"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/account.ts","../src/logger.ts","../src/deployment.ts","../src/path.ts"],"names":["path","format","createLogger","logger","ethers","dirname","getStackTrace"],"mappings":";AAAA,SAAqC,aAAa;AAClD,OAAO,UAA8B;AACrC,OAAO,UAAU;;;ACFjB,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,YAAY,WAAW;AACvB,YAAY,WAAW;AACvB,YAAY,kBAAkB;AAC9B,SAAS,cAAc;AAEvB,SAAS,iBAAiB;AASnB,SAAS,cAAc,WAAsB,SAAiB,QAAgB,O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Q,OAAO,MAAM,IAAI;AAAA,QAC7B;AAAA,MACJ,CAAC;AAGD,WAAK,eAAe,QAAQ,GAAG,QAAQ,CAAC,SAAS;AAC7C,YAAIA,SAAQ;AACR,UAAAA,QAAO,MAAM,KAAK,SAAS,CAAC;AAAA,QAChC,OAAO;AACH,kBAAQ,OAAO,MAAM,IAAI;AAAA,QAC7B;AAAA,MACJ,CAAC;AAID,WAAK,eAAe,GAAG,QAAQ,CAAC,SAAS;AACrC,YAAI,QAAQ,SAAS,GAAG;AACpB,cAAIA,SAAQ;AACR,YAAAA,QAAO,KAAK,WAAW,OAAO,qBAAqB,IAAI,GAAG;AAAA,UAC9D,OAAO;AACH,oBAAQ,KAAK,WAAW,OAAO,qBAAqB,IAAI,GAAG;AAAA,UAC/D;AACA,iBAAO,EAAE,SAAS,GAAG,OAAO,IAAI,KAAK,KAAK,GAAG,CAAC,GAAG,CAAC;AAClD;AAAA,QACJ;AACA,gBAAQ;AAAA,MACZ,CAAC;AAAA,IACL,CAAC;AAAA,EACL;AAAA,EAEA,MAAa,UAAU,kBAAkB,MAAM;AAC3C,QAAI,KAAK,gBAAgB;AACrB,MAAAA,QAAO,KAAK,uBAAuB,KAAK,eAAe,GAAG;AAC1D,UAAI,iBAAiB;AACjB,aAAK,KAAK,eAAe,GAAI;AAE7B,cAAM,MAAM,GAAI;AAAA,MACpB,OAAO;AACH,aAAK,eAAe,KAAK;AAAA,MAC7B;AACA,WAAK,iBAAiB;AAAA,IAC1B;AAAA,EACJ;AACJ","sourcesContent":["import { ChildProcess, SpawnOptions, spawn } from 'child_process'\nimport http, { RequestOptions } from 'http'\nimport path from 'path'\n\nexport * from './account'\nexport * from './logger'\nexport * from './deployment'\nexport * from './path'\n\nimport { sync as findUpSync } from 'find-up'\nimport kill from 'tree-kill'\nimport { Logger } from 'winston'\n\nimport { getLogger } from './logger'\n\nexport const logger = getLogger()\n\nexport async function sleep(timeout: number) {\n await new Promise((resolve) => setTimeout(resolve, timeout))\n}\n\nexport function getProjectPackageManager(cwd?: string) {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn) return 'yarn'\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm) return 'npm'\n\n // pnpm\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm) return 'pnpm'\n\n throw new Error('Cannot find package.json or yarn.lock')\n}\n\nexport function getProjectRootDir(cwd?: string) {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn) return path.dirname(yarn)\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm) return path.dirname(npm)\n\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm) return path.dirname(pnpm)\n\n throw new Error('Cannot find yarn.lock or package-lock.json or pnpm-lock.yaml')\n}\n\nexport function isHttpServiceReachable(host: string, port: number, timeout: number, path?: string): 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 || !m.groups || !m.groups.host || !m.groups.schema || !m.groups.port) {\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\nexport class CmdExecutor {\n private currentProcess: ChildProcess | null = null\n\n private onFinish: Promise<void> | null = null\n\n public executeCmd(\n command: string,\n args: string[],\n options: SpawnOptions,\n verbose = false,\n runningCheck?: { key: string; runningNotify: (running: boolean) => void },\n logger?: Logger\n ): Promise<void> {\n if (logger) {\n logger.info(`Running command: ${command} ${args?.join(' ') ?? ''}`)\n } else {\n console.log(`Running command: ${command} ${args?.join(' ') ?? ''}`)\n }\n return new Promise<void>((resolve, reject) => {\n let notified = false\n this.currentProcess = spawn(command, args, options)\n if (!this.currentProcess) {\n throw new Error(`Failed to spawn command: ${command} ${args?.join(' ') ?? ''}`)\n }\n\n // Listen for standard output from the child process and print it to the console\n this.currentProcess.stdout?.on('data', (data) => {\n if (runningCheck && !notified && data.toString().includes(runningCheck.key)) {\n runningCheck.runningNotify(true)\n notified = true\n }\n if (verbose && logger) {\n logger.info(data.toString())\n } else if (verbose) {\n process.stdout.write(data)\n }\n })\n\n // Listen for errors from the child process and print them to the console\n this.currentProcess.stderr?.on('data', (data) => {\n if (logger) {\n logger.error(data.toString())\n } else {\n process.stderr.write(data)\n }\n })\n\n // Listen for the exit event of the child process and resolve the promise\n // if the child process exits normally (with code 0)\n this.currentProcess.on('exit', (code) => {\n if (code && code !== 0) {\n if (logger) {\n logger.info(`Command ${command} exited with code ${code}.`)\n } else {\n console.info(`Command ${command} exited with code ${code}.`)\n }\n reject({ command: `${command} ${args.join(' ')}` })\n return\n }\n resolve()\n })\n })\n }\n\n public async interrupt(killDescendents = true) {\n if (this.currentProcess) {\n logger.info('Killing process: %s', this.currentProcess.pid)\n if (killDescendents) {\n kill(this.currentProcess.pid!)\n // the implementation of tree-kill is using spawn, which is async. So we need to wait for a while\n await sleep(2000)\n } else {\n this.currentProcess.kill()\n }\n this.currentProcess = null\n }\n }\n}\n","import { bytesToHex } from '@noble/hashes/utils'\nimport { Keypair } from '@solana/web3.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\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, bytesToHex(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 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.SOLANA:\n return getSolanaAccountFromMnemonic(mnemonic, path)\n default:\n throw new Error(`Unsupported chain: ${chainType}`)\n }\n}\n","import * as winston from 'winston'\nimport { Logger, format } from 'winston'\n\nlet logger: Logger\n\nexport { Logger }\n\nfunction getStackTrace() {\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() {\n const ancestors: any[] = []\n return function (key: any, value: any) {\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 // @ts-ignore\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 === undefined || m === null) {\n continue\n }\n const [, fileInfoLine] = m\n return fileInfoLine\n }\n return '<unknown>'\n}\n\nconst logFormat = format.printf((info) => {\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 spaces = info.metadata?.pretty === true ? 2 : undefined\n const value =\n typeof info.message === 'string' ? info.message : JSON.stringify(info.message, getCircularReplacer(), spaces)\n const format = info.metadata?.format\n const message = format ? format.replace(/%s/g, value) : value\n\n return [...formats, message].map((x) => `${info.timestamp} ${info.level.toUpperCase()}: ${x}`).join('\\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) {\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 return logger\n}\n\nconst exportsObject = {}\nif (process.env['NODE_ENV'] === 'test') {\n // @ts-ignore\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 * @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 | 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 || options.chain === networkToChain(deployment.network)\n const hasMatchingNetwork = !options.network || options.network === deployment.network\n const hasMatchingSource = !options.source || options.source === deployment.source\n let hasMatchingEndpoint = true\n if (options.endpointId) {\n const compatibleEndpoints = deployment.compatibleVersions.map((v) => {\n if (isNetworkEndpointIdSupported(deployment.network, v)) {\n return networkToEndpointId(deployment.network, v)\n }\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 (!contractCache[key]) {\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","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) {\n const match = path.match(/(.*)([\\\\/][^\\\\/]+)[/\\\\]?$/)\n const [, basePath] = match || []\n const dirname = basePath || path\n return dirname\n}\n\nfunction getStackTrace(stackTraceLimit = Infinity) {\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 && 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}\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) {\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"]}
package/dist/index.d.mts CHANGED
@@ -66,6 +66,7 @@ declare function dirname(path: string): string;
66
66
  */
67
67
  declare function pkgroot(packageName: string, relativeToPath?: string): string;
68
68
 
69
+ declare const logger: Logger;
69
70
  declare function sleep(timeout: number): Promise<void>;
70
71
  declare function getProjectPackageManager(cwd?: string): "yarn" | "npm" | "pnpm";
71
72
  declare function getProjectRootDir(cwd?: string): string;
@@ -85,4 +86,4 @@ declare class CmdExecutor {
85
86
  interrupt(killDescendents?: boolean): Promise<void>;
86
87
  }
87
88
 
88
- export { type AccountMnemonic, CmdExecutor, type Deployment, createLogger, deploymentToEvmContract, dirname, extractUrlInfo, findDeployment, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, initLogger, isHttpServiceReachable, pkgroot, sleep };
89
+ export { type AccountMnemonic, CmdExecutor, type Deployment, createLogger, deploymentToEvmContract, dirname, extractUrlInfo, findDeployment, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, initLogger, isHttpServiceReachable, logger, pkgroot, sleep };
package/dist/index.d.ts CHANGED
@@ -66,6 +66,7 @@ declare function dirname(path: string): string;
66
66
  */
67
67
  declare function pkgroot(packageName: string, relativeToPath?: string): string;
68
68
 
69
+ declare const logger: Logger;
69
70
  declare function sleep(timeout: number): Promise<void>;
70
71
  declare function getProjectPackageManager(cwd?: string): "yarn" | "npm" | "pnpm";
71
72
  declare function getProjectRootDir(cwd?: string): string;
@@ -85,4 +86,4 @@ declare class CmdExecutor {
85
86
  interrupt(killDescendents?: boolean): Promise<void>;
86
87
  }
87
88
 
88
- export { type AccountMnemonic, CmdExecutor, type Deployment, createLogger, deploymentToEvmContract, dirname, extractUrlInfo, findDeployment, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, initLogger, isHttpServiceReachable, pkgroot, sleep };
89
+ export { type AccountMnemonic, CmdExecutor, type Deployment, createLogger, deploymentToEvmContract, dirname, extractUrlInfo, findDeployment, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, initLogger, isHttpServiceReachable, logger, pkgroot, sleep };
package/dist/index.mjs CHANGED
@@ -149,12 +149,12 @@ function initLogger(level) {
149
149
  }
150
150
  }
151
151
  function createLogger2(level) {
152
- const logger2 = winston.createLogger({
152
+ const logger3 = winston.createLogger({
153
153
  level,
154
154
  format: loggerFormat,
155
155
  transports: [new winston.transports.Console()]
156
156
  });
157
- return logger2;
157
+ return logger3;
158
158
  }
159
159
  function getLogger() {
160
160
  initLogger(process.env.LZ_LOG ?? "info");
@@ -228,6 +228,7 @@ function pkgroot(packageName, relativeToPath) {
228
228
  const packagePath = dirname(filepath);
229
229
  return packagePath.replace(/.yarn\/([^/]*\/)?(__virtual__|\$\$virtual)\/[^/]*\/\d*\//, "");
230
230
  }
231
+ var logger2 = getLogger();
231
232
  async function sleep(timeout) {
232
233
  await new Promise((resolve) => setTimeout(resolve, timeout));
233
234
  }
@@ -289,9 +290,9 @@ var CmdExecutor = class {
289
290
  this.currentProcess = null;
290
291
  this.onFinish = null;
291
292
  }
292
- executeCmd(command, args, options, verbose = false, runningCheck, logger2) {
293
- if (logger2) {
294
- logger2.info(`Running command: ${command} ${args?.join(" ") ?? ""}`);
293
+ executeCmd(command, args, options, verbose = false, runningCheck, logger3) {
294
+ if (logger3) {
295
+ logger3.info(`Running command: ${command} ${args?.join(" ") ?? ""}`);
295
296
  } else {
296
297
  console.log(`Running command: ${command} ${args?.join(" ") ?? ""}`);
297
298
  }
@@ -306,23 +307,23 @@ var CmdExecutor = class {
306
307
  runningCheck.runningNotify(true);
307
308
  notified = true;
308
309
  }
309
- if (verbose && logger2) {
310
- logger2.info(data.toString());
310
+ if (verbose && logger3) {
311
+ logger3.info(data.toString());
311
312
  } else if (verbose) {
312
313
  process.stdout.write(data);
313
314
  }
314
315
  });
315
316
  this.currentProcess.stderr?.on("data", (data) => {
316
- if (logger2) {
317
- logger2.error(data.toString());
317
+ if (logger3) {
318
+ logger3.error(data.toString());
318
319
  } else {
319
320
  process.stderr.write(data);
320
321
  }
321
322
  });
322
323
  this.currentProcess.on("exit", (code) => {
323
324
  if (code && code !== 0) {
324
- if (logger2) {
325
- logger2.info(`Command ${command} exited with code ${code}.`);
325
+ if (logger3) {
326
+ logger3.info(`Command ${command} exited with code ${code}.`);
326
327
  } else {
327
328
  console.info(`Command ${command} exited with code ${code}.`);
328
329
  }
@@ -335,7 +336,7 @@ var CmdExecutor = class {
335
336
  }
336
337
  async interrupt(killDescendents = true) {
337
338
  if (this.currentProcess) {
338
- console.log("Killing process:", this.currentProcess.pid);
339
+ logger2.info("Killing process: %s", this.currentProcess.pid);
339
340
  if (killDescendents) {
340
341
  kill(this.currentProcess.pid);
341
342
  await sleep(2e3);
@@ -347,6 +348,6 @@ var CmdExecutor = class {
347
348
  }
348
349
  };
349
350
 
350
- export { CmdExecutor, createLogger2 as createLogger, deploymentToEvmContract, dirname, extractUrlInfo, findDeployment, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, initLogger, isHttpServiceReachable, pkgroot, sleep };
351
+ export { CmdExecutor, createLogger2 as createLogger, deploymentToEvmContract, dirname, extractUrlInfo, findDeployment, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getEvmAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, initLogger, isHttpServiceReachable, logger2 as logger, pkgroot, sleep };
351
352
  //# sourceMappingURL=out.js.map
352
353
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/account.ts","../src/logger.ts","../src/deployment.ts","../src/path.ts"],"names":["path","format","createLogger","logger","ethers","dirname","get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 'path'\n\nexport * from './account'\nexport * from './logger'\nexport * from './deployment'\nexport * from './path'\n\nimport { sync as findUpSync } from 'find-up'\nimport kill from 'tree-kill'\nimport { Logger } from 'winston'\n\nexport async function sleep(timeout: number) {\n await new Promise((resolve) => setTimeout(resolve, timeout))\n}\n\nexport function getProjectPackageManager(cwd?: string) {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn) return 'yarn'\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm) return 'npm'\n\n // pnpm\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm) return 'pnpm'\n\n throw new Error('Cannot find package.json or yarn.lock')\n}\n\nexport function getProjectRootDir(cwd?: string) {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn) return path.dirname(yarn)\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm) return path.dirname(npm)\n\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm) return path.dirname(pnpm)\n\n throw new Error('Cannot find yarn.lock or package-lock.json or pnpm-lock.yaml')\n}\n\nexport function isHttpServiceReachable(host: string, port: number, timeout: number, path?: string): 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 || !m.groups || !m.groups.host || !m.groups.schema || !m.groups.port) {\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\nexport class CmdExecutor {\n private currentProcess: ChildProcess | null = null\n\n private onFinish: Promise<void> | null = null\n\n public executeCmd(\n command: string,\n args: string[],\n options: SpawnOptions,\n verbose = false,\n runningCheck?: { key: string; runningNotify: (running: boolean) => void },\n logger?: Logger\n ): Promise<void> {\n if (logger) {\n logger.info(`Running command: ${command} ${args?.join(' ') ?? ''}`)\n } else {\n console.log(`Running command: ${command} ${args?.join(' ') ?? ''}`)\n }\n return new Promise<void>((resolve, reject) => {\n let notified = false\n this.currentProcess = spawn(command, args, options)\n if (!this.currentProcess) {\n throw new Error(`Failed to spawn command: ${command} ${args?.join(' ') ?? ''}`)\n }\n\n // Listen for standard output from the child process and print it to the console\n this.currentProcess.stdout?.on('data', (data) => {\n if (runningCheck && !notified && data.toString().includes(runningCheck.key)) {\n runningCheck.runningNotify(true)\n notified = true\n }\n if (verbose && logger) {\n logger.info(data.toString())\n } else if (verbose) {\n process.stdout.write(data)\n }\n })\n\n // Listen for errors from the child process and print them to the console\n this.currentProcess.stderr?.on('data', (data) => {\n if (logger) {\n logger.error(data.toString())\n } else {\n process.stderr.write(data)\n }\n })\n\n // Listen for the exit event of the child process and resolve the promise\n // if the child process exits normally (with code 0)\n this.currentProcess.on('exit', (code) => {\n if (code && code !== 0) {\n if (logger) {\n logger.info(`Command ${command} exited with code ${code}.`)\n } else {\n console.info(`Command ${command} exited with code ${code}.`)\n }\n reject({ command: `${command} ${args.join(' ')}` })\n return\n }\n resolve()\n })\n })\n }\n\n public async interrupt(killDescendents = true) {\n if (this.currentProcess) {\n console.log('Killing process:', this.currentProcess.pid)\n if (killDescendents) {\n kill(this.currentProcess.pid!)\n // the implementation of tree-kill is using spawn, which is async. So we need to wait for a while\n await sleep(2000)\n } else {\n this.currentProcess.kill()\n }\n this.currentProcess = null\n }\n }\n}\n","import { bytesToHex } from '@noble/hashes/utils'\nimport { Keypair } from '@solana/web3.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\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, bytesToHex(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 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.SOLANA:\n return getSolanaAccountFromMnemonic(mnemonic, path)\n default:\n throw new Error(`Unsupported chain: ${chainType}`)\n }\n}\n","import * as winston from 'winston'\nimport { Logger, format } from 'winston'\n\nlet logger: Logger\n\nexport { Logger }\n\nfunction getStackTrace() {\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() {\n const ancestors: any[] = []\n return function (key: any, value: any) {\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 // @ts-ignore\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 === undefined || m === null) {\n continue\n }\n const [, fileInfoLine] = m\n return fileInfoLine\n }\n return '<unknown>'\n}\n\nconst logFormat = format.printf((info) => {\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 spaces = info.metadata?.pretty === true ? 2 : undefined\n const value =\n typeof info.message === 'string' ? info.message : JSON.stringify(info.message, getCircularReplacer(), spaces)\n const format = info.metadata?.format\n const message = format ? format.replace(/%s/g, value) : value\n\n return [...formats, message].map((x) => `${info.timestamp} ${info.level.toUpperCase()}: ${x}`).join('\\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) {\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 return logger\n}\n\nconst exportsObject = {}\nif (process.env['NODE_ENV'] === 'test') {\n // @ts-ignore\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 * @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 | 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 || options.chain === networkToChain(deployment.network)\n const hasMatchingNetwork = !options.network || options.network === deployment.network\n const hasMatchingSource = !options.source || options.source === deployment.source\n let hasMatchingEndpoint = true\n if (options.endpointId) {\n const compatibleEndpoints = deployment.compatibleVersions.map((v) => {\n if (isNetworkEndpointIdSupported(deployment.network, v)) {\n return networkToEndpointId(deployment.network, v)\n }\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 (!contractCache[key]) {\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","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) {\n const match = path.match(/(.*)([\\\\/][^\\\\/]+)[/\\\\]?$/)\n const [, basePath] = match || []\n const dirname = basePath || path\n return dirname\n}\n\nfunction getStackTrace(stackTraceLimit = Infinity) {\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 && 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}\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) {\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"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/account.ts","../src/logger.ts","../src/deployment.ts","../src/path.ts"],"names":["path","format","createLogger","logger","ethers","dirname","getStackTrace"],"mappings":";AAAA,SAAqC,aAAa;AAClD,OAAO,UAA8B;AACrC,OAAO,UAAU;;;ACFjB,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,YAAY,WAAW;AACvB,YAAY,WAAW;AACvB,YAAY,kBAAkB;AAC9B,SAAS,cAAc;AAEvB,SAAS,iBAAiB;AASnB,SAAS,cAAc,WAAsB,SAAiB,QAAgB,OAAuB;AAaxG,UAAQ,WAAW;AAAA,IACf,KAAK,UAAU;AAEX,aAAO,aAAa,OAAO,KAAK,MAAM,IAAI,KAAK;AAAA,IACnD,KAAK,UAAU;AAEX,aAAO,cAAc,OAAO,KAAK,MAAM,KAAK,KAAK;AAAA,IACrD,KAAK,UAAU;AAEX,aAAO,cAAc,OAAO,KAAK,MAAM;AAAA,IAC3C;AACI,YAAM,IAAI,MAAM,sBAAsB,SAAS,EAAE;AAAA,EACzD;AACJ;AAEO,SAAS,0BAA0B,UAAkBA,QAAO,oBAAqC;AACpG,QAAM,SAAS,OAAO,OAAO,aAAa,UAAUA,KAAI;AACxD,SAAO;AAAA,IACH;AAAA,IACA,MAAAA;AAAA,IACA,YAAY,OAAO;AAAA,IACnB,SAAS,OAAO;AAAA,EACpB;AACJ;AAEO,SAAS,4BAA4B,UAAkBA,QAAO,uBAAwC;AAEzG,MAAI,CAAO,mBAAa,YAAYA,KAAI,GAAG;AACvC,UAAM,IAAI,MAAM,4BAA4BA,KAAI,EAAE;AAAA,EACtD;AACA,QAAM,qBAAqB,SACtB,KAAK,EACL,MAAM,KAAK,EACX,IAAI,CAAC,SAAS,KAAK,YAAY,CAAC,EAChC,KAAK,GAAG;AACb;AACI,UAAM,EAAE,IAAI,IAAU,iBAAWA,OAAM,WAAiB,yBAAmB,kBAAkB,CAAC,CAAC;AAC/F,UAAM,UAAU,IAAU,mBAAa,IAAI,WAAW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B;AACA,WAAK,iBAAiB;AAAA,IAC1B;AAAA,EACJ;AACJ","sourcesContent":["import { ChildProcess, SpawnOptions, spawn } from 'child_process'\nimport http, { RequestOptions } from 'http'\nimport path from 'path'\n\nexport * from './account'\nexport * from './logger'\nexport * from './deployment'\nexport * from './path'\n\nimport { sync as findUpSync } from 'find-up'\nimport kill from 'tree-kill'\nimport { Logger } from 'winston'\n\nimport { getLogger } from './logger'\n\nexport const logger = getLogger()\n\nexport async function sleep(timeout: number) {\n await new Promise((resolve) => setTimeout(resolve, timeout))\n}\n\nexport function getProjectPackageManager(cwd?: string) {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn) return 'yarn'\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm) return 'npm'\n\n // pnpm\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm) return 'pnpm'\n\n throw new Error('Cannot find package.json or yarn.lock')\n}\n\nexport function getProjectRootDir(cwd?: string) {\n const yarn = findUpSync('yarn.lock', { cwd })\n if (yarn) return path.dirname(yarn)\n\n const npm = findUpSync('package-lock.json', { cwd })\n if (npm) return path.dirname(npm)\n\n const pnpm = findUpSync('pnpm-lock.yaml', { cwd })\n if (pnpm) return path.dirname(pnpm)\n\n throw new Error('Cannot find yarn.lock or package-lock.json or pnpm-lock.yaml')\n}\n\nexport function isHttpServiceReachable(host: string, port: number, timeout: number, path?: string): 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 || !m.groups || !m.groups.host || !m.groups.schema || !m.groups.port) {\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\nexport class CmdExecutor {\n private currentProcess: ChildProcess | null = null\n\n private onFinish: Promise<void> | null = null\n\n public executeCmd(\n command: string,\n args: string[],\n options: SpawnOptions,\n verbose = false,\n runningCheck?: { key: string; runningNotify: (running: boolean) => void },\n logger?: Logger\n ): Promise<void> {\n if (logger) {\n logger.info(`Running command: ${command} ${args?.join(' ') ?? ''}`)\n } else {\n console.log(`Running command: ${command} ${args?.join(' ') ?? ''}`)\n }\n return new Promise<void>((resolve, reject) => {\n let notified = false\n this.currentProcess = spawn(command, args, options)\n if (!this.currentProcess) {\n throw new Error(`Failed to spawn command: ${command} ${args?.join(' ') ?? ''}`)\n }\n\n // Listen for standard output from the child process and print it to the console\n this.currentProcess.stdout?.on('data', (data) => {\n if (runningCheck && !notified && data.toString().includes(runningCheck.key)) {\n runningCheck.runningNotify(true)\n notified = true\n }\n if (verbose && logger) {\n logger.info(data.toString())\n } else if (verbose) {\n process.stdout.write(data)\n }\n })\n\n // Listen for errors from the child process and print them to the console\n this.currentProcess.stderr?.on('data', (data) => {\n if (logger) {\n logger.error(data.toString())\n } else {\n process.stderr.write(data)\n }\n })\n\n // Listen for the exit event of the child process and resolve the promise\n // if the child process exits normally (with code 0)\n this.currentProcess.on('exit', (code) => {\n if (code && code !== 0) {\n if (logger) {\n logger.info(`Command ${command} exited with code ${code}.`)\n } else {\n console.info(`Command ${command} exited with code ${code}.`)\n }\n reject({ command: `${command} ${args.join(' ')}` })\n return\n }\n resolve()\n })\n })\n }\n\n public async interrupt(killDescendents = true) {\n if (this.currentProcess) {\n logger.info('Killing process: %s', this.currentProcess.pid)\n if (killDescendents) {\n kill(this.currentProcess.pid!)\n // the implementation of tree-kill is using spawn, which is async. So we need to wait for a while\n await sleep(2000)\n } else {\n this.currentProcess.kill()\n }\n this.currentProcess = null\n }\n }\n}\n","import { bytesToHex } from '@noble/hashes/utils'\nimport { Keypair } from '@solana/web3.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\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, bytesToHex(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 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.SOLANA:\n return getSolanaAccountFromMnemonic(mnemonic, path)\n default:\n throw new Error(`Unsupported chain: ${chainType}`)\n }\n}\n","import * as winston from 'winston'\nimport { Logger, format } from 'winston'\n\nlet logger: Logger\n\nexport { Logger }\n\nfunction getStackTrace() {\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() {\n const ancestors: any[] = []\n return function (key: any, value: any) {\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 // @ts-ignore\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 === undefined || m === null) {\n continue\n }\n const [, fileInfoLine] = m\n return fileInfoLine\n }\n return '<unknown>'\n}\n\nconst logFormat = format.printf((info) => {\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 spaces = info.metadata?.pretty === true ? 2 : undefined\n const value =\n typeof info.message === 'string' ? info.message : JSON.stringify(info.message, getCircularReplacer(), spaces)\n const format = info.metadata?.format\n const message = format ? format.replace(/%s/g, value) : value\n\n return [...formats, message].map((x) => `${info.timestamp} ${info.level.toUpperCase()}: ${x}`).join('\\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) {\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 return logger\n}\n\nconst exportsObject = {}\nif (process.env['NODE_ENV'] === 'test') {\n // @ts-ignore\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 * @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 | 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 || options.chain === networkToChain(deployment.network)\n const hasMatchingNetwork = !options.network || options.network === deployment.network\n const hasMatchingSource = !options.source || options.source === deployment.source\n let hasMatchingEndpoint = true\n if (options.endpointId) {\n const compatibleEndpoints = deployment.compatibleVersions.map((v) => {\n if (isNetworkEndpointIdSupported(deployment.network, v)) {\n return networkToEndpointId(deployment.network, v)\n }\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 (!contractCache[key]) {\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","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) {\n const match = path.match(/(.*)([\\\\/][^\\\\/]+)[/\\\\]?$/)\n const [, basePath] = match || []\n const dirname = basePath || path\n return dirname\n}\n\nfunction getStackTrace(stackTraceLimit = Infinity) {\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 && 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}\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) {\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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@layerzerolabs/lz-utilities",
3
- "version": "2.1.11",
3
+ "version": "2.1.13",
4
4
  "license": "BUSL-1.1",
5
5
  "exports": {
6
6
  "types": "./dist/index.d.ts",
@@ -20,7 +20,7 @@
20
20
  },
21
21
  "dependencies": {
22
22
  "@ethersproject/providers": "^5.7.0",
23
- "@layerzerolabs/lz-definitions": "^2.1.11",
23
+ "@layerzerolabs/lz-definitions": "^2.1.13",
24
24
  "@noble/hashes": "^1.3.2",
25
25
  "@solana/web3.js": "^1.87.6",
26
26
  "aptos": "^1.20.0",
@@ -34,8 +34,8 @@
34
34
  },
35
35
  "devDependencies": {
36
36
  "@jest/globals": "^29.7.0",
37
- "@layerzerolabs/tsup-config-next": "^2.1.11",
38
- "@layerzerolabs/typescript-config-next": "^2.1.11",
37
+ "@layerzerolabs/tsup-config-next": "^2.1.13",
38
+ "@layerzerolabs/typescript-config-next": "^2.1.13",
39
39
  "@types/glob": "^8.1.0",
40
40
  "@types/jest": "^29.5.10",
41
41
  "@types/node": "^20.10.5",