@layerzerolabs/lz-utilities 2.3.6 → 2.3.8

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 CHANGED
@@ -1,5 +1,21 @@
1
1
  # @layerzerolabs/lz-utilities
2
2
 
3
+ ## 2.3.8
4
+
5
+ ### Patch Changes
6
+
7
+ - e0f5d04: deploy contracts to Ebi mainnet
8
+ - Updated dependencies [e0f5d04]
9
+ - @layerzerolabs/lz-definitions@2.3.8
10
+
11
+ ## 2.3.7
12
+
13
+ ### Patch Changes
14
+
15
+ - 5fa1b78: fix some solana bugs
16
+ - Updated dependencies [5fa1b78]
17
+ - @layerzerolabs/lz-definitions@2.3.7
18
+
3
19
  ## 2.3.6
4
20
 
5
21
  ### Patch Changes
package/dist/index.cjs CHANGED
@@ -107,7 +107,7 @@ function getKeypairFromMnemonic(chainType, mnemonic, path2) {
107
107
  throw new Error(`Unsupported chain: ${chainType}`);
108
108
  }
109
109
  }
110
- var logger;
110
+ var logger = void 0;
111
111
  function getStackTrace() {
112
112
  const oldLimit = Error.stackTraceLimit;
113
113
  Error.stackTraceLimit = Infinity;
@@ -117,7 +117,7 @@ function getStackTrace() {
117
117
  }
118
118
  function getCircularReplacer() {
119
119
  const ancestors = [];
120
- return function(key, value) {
120
+ return function(_key, value) {
121
121
  if (typeof value !== "object" || value === null) {
122
122
  return value;
123
123
  }
@@ -134,7 +134,7 @@ function getCircularReplacer() {
134
134
  function extractCallerInfo(line) {
135
135
  for (const pattern of [/\((.*?:\d+:\d+)\)$/, /at (.*?:\d+:\d+)$/]) {
136
136
  const m = line.match(pattern);
137
- if (m === void 0 || m === null) {
137
+ if (m === null) {
138
138
  continue;
139
139
  }
140
140
  const [, fileInfoLine] = m;
@@ -142,30 +142,32 @@ function extractCallerInfo(line) {
142
142
  }
143
143
  return "<unknown>";
144
144
  }
145
- var logFormat = winston.format.printf((info) => {
146
- if (info.level.toUpperCase() !== "ERROR" && info.level.toUpperCase() !== "WARN") {
147
- return `${info.timestamp} ${info.level.toUpperCase()}: ${info.message}`;
148
- }
149
- const stack = getStackTrace() || "";
150
- const stackLines = stack.split("\n");
151
- const index = stackLines.findIndex((line) => {
152
- return line.match(/create-logger.js/);
153
- }) + 1;
154
- let fileInfo = "<unknown>";
155
- if (stackLines.length > index) {
156
- const line = stackLines[index];
157
- fileInfo = extractCallerInfo(line);
158
- }
159
- const formats = [];
160
- if (fileInfo !== "<unknown>") {
161
- formats.push(fileInfo);
145
+ var logFormat = winston.format.printf(
146
+ (info) => {
147
+ if (info.level.toUpperCase() !== "ERROR" && info.level.toUpperCase() !== "WARN") {
148
+ return `${info.timestamp} ${info.level.toUpperCase()}: ${info.message}`;
149
+ }
150
+ const stack = getStackTrace() ?? "";
151
+ const stackLines = stack.split("\n");
152
+ const index = stackLines.findIndex((line) => {
153
+ return line.match(/create-logger.js/);
154
+ }) + 1;
155
+ let fileInfo = "<unknown>";
156
+ if (stackLines.length > index) {
157
+ const line = stackLines[index];
158
+ fileInfo = extractCallerInfo(line);
159
+ }
160
+ const formats = [];
161
+ if (fileInfo !== "<unknown>") {
162
+ formats.push(fileInfo);
163
+ }
164
+ const { pretty, format: format2 } = info.metadata ?? {};
165
+ const spaces = pretty === true ? 2 : void 0;
166
+ const value = typeof info.message === "string" ? info.message : JSON.stringify(info.message, getCircularReplacer(), spaces);
167
+ const message = format2 !== void 0 ? format2.replace(/%s/g, value) : value;
168
+ return [...formats, message].map((x) => `${info.timestamp} ${info.level.toUpperCase()}: ${x}`).join("\n");
162
169
  }
163
- const spaces = info.metadata?.pretty === true ? 2 : void 0;
164
- const value = typeof info.message === "string" ? info.message : JSON.stringify(info.message, getCircularReplacer(), spaces);
165
- const format2 = info.metadata?.format;
166
- const message = format2 ? format2.replace(/%s/g, value) : value;
167
- return [...formats, message].map((x) => `${info.timestamp} ${info.level.toUpperCase()}: ${x}`).join("\n");
168
- });
170
+ );
169
171
  var loggerFormat = winston.format.combine(
170
172
  winston.format.timestamp({ format: "YY-MM-DD HH:mm:ss" }),
171
173
  winston.format.splat(),
@@ -190,24 +192,28 @@ function createLogger2(level) {
190
192
  }
191
193
  function getLogger() {
192
194
  initLogger(process.env.LZ_LOG ?? "info");
195
+ if (!logger) {
196
+ throw new Error("Logger is not initialized");
197
+ }
193
198
  return logger;
194
199
  }
195
- if (process.env["NODE_ENV"] === "test") ;
200
+ if (process.env.NODE_ENV === "test") ;
196
201
  function findDeployment(deployments, nameOrAddress, options) {
197
202
  return deployments.find((deployment) => {
198
203
  let hasMatchingNameOrAddress = deployment.name === nameOrAddress;
199
204
  if (!hasMatchingNameOrAddress && ethers.ethers.utils.isAddress(nameOrAddress)) {
200
205
  hasMatchingNameOrAddress = ethers.ethers.utils.getAddress(deployment.address) === ethers.ethers.utils.getAddress(nameOrAddress);
201
206
  }
202
- const hasMatchingChain = !options.chain || options.chain === lzDefinitions.networkToChain(deployment.network);
203
- const hasMatchingNetwork = !options.network || options.network === deployment.network;
204
- const hasMatchingSource = !options.source || options.source === deployment.source;
207
+ const hasMatchingChain = options.chain == null || options.chain === lzDefinitions.networkToChain(deployment.network);
208
+ const hasMatchingNetwork = options.network === void 0 || options.network === deployment.network;
209
+ const hasMatchingSource = options.source === void 0 || options.source === deployment.source;
205
210
  let hasMatchingEndpoint = true;
206
- if (options.endpointId) {
211
+ if (options.endpointId != null) {
207
212
  const compatibleEndpoints = deployment.compatibleVersions.map((v) => {
208
213
  if (lzDefinitions.isNetworkEndpointIdSupported(deployment.network, v)) {
209
214
  return lzDefinitions.networkToEndpointId(deployment.network, v);
210
215
  }
216
+ return void 0;
211
217
  });
212
218
  hasMatchingEndpoint = compatibleEndpoints.includes(options.endpointId);
213
219
  }
@@ -217,7 +223,10 @@ function findDeployment(deployments, nameOrAddress, options) {
217
223
  var contractCache = {};
218
224
  function deploymentToEvmContract(deployment, provider) {
219
225
  const key = `${deployment.network}-${deployment.address}`;
220
- if (!contractCache[key]) {
226
+ if (!(key in contractCache)) {
227
+ if (deployment.abi === void 0 || deployment.bytecode === void 0) {
228
+ throw new Error("Deployment does not have ABI or bytecode");
229
+ }
221
230
  const Contract = new ethers.ethers.ContractFactory(deployment.abi, deployment.bytecode);
222
231
  contractCache[key] = Contract.attach(deployment.address);
223
232
  }
@@ -228,8 +237,8 @@ function deploymentToEvmContract(deployment, provider) {
228
237
  }
229
238
  function dirname(path2) {
230
239
  const match = path2.match(/(.*)([\\/][^\\/]+)[/\\]?$/);
231
- const [, basePath] = match || [];
232
- const dirname2 = basePath || path2;
240
+ const [, basePath] = match ?? [];
241
+ const dirname2 = typeof basePath !== "undefined" ? basePath : path2;
233
242
  return dirname2;
234
243
  }
235
244
  function getStackTrace2(stackTraceLimit = Infinity) {
@@ -241,13 +250,14 @@ function getStackTrace2(stackTraceLimit = Infinity) {
241
250
  }
242
251
  function getCaller() {
243
252
  const lines = (getStackTrace2(10) ?? "").split("\n");
244
- if (lines && lines.length > 1 + 1 + 1 + 1) {
253
+ if (lines.length > 1 + 1 + 1 + 1) {
245
254
  const line = lines[4];
246
255
  const m = line.match(/^.*\(([^:]*)[^)]*\)/);
247
256
  if (m) {
248
257
  return m[1];
249
258
  }
250
259
  }
260
+ return void 0;
251
261
  }
252
262
  function pkgroot(packageName, relativeToPath) {
253
263
  if (relativeToPath === void 0) {
@@ -267,7 +277,7 @@ var sequence = async (tasks) => {
267
277
  }
268
278
  return collector;
269
279
  };
270
- var parallel = async (tasks) => await Promise.all(tasks.map(async (task) => task()));
280
+ var parallel = async (tasks) => Promise.all(tasks.map(async (task) => task()));
271
281
  var first = async (tasks) => {
272
282
  assert__default.default(tasks.length !== 0, `Must have at least one task for first()`);
273
283
  let lastError;
@@ -280,7 +290,7 @@ var first = async (tasks) => {
280
290
  }
281
291
  throw lastError;
282
292
  };
283
- var firstFactory = (...factories) => async (...input) => await first(factories.map((factory) => async () => factory(...input)));
293
+ var firstFactory = (...factories) => async (...input) => first(factories.map((factory) => async () => factory(...input)));
284
294
 
285
295
  // src/array.ts
286
296
  function safeMap(elements, callbackfn) {
@@ -315,7 +325,7 @@ function isHexString(value) {
315
325
  return /^(0x)?[0-9a-fA-F]+$/.test(value);
316
326
  }
317
327
  async function signWithECDSA(data, privateKey) {
318
- const [signature, recoveryId] = await secp256k1.sign(data, privateKey, {
328
+ const [signature, recoveryId] = await secp256k1.sign(data, privateKey.replace("0x", ""), {
319
329
  canonical: true,
320
330
  recovered: true,
321
331
  der: false
@@ -326,7 +336,7 @@ async function signWithECDSA(data, privateKey) {
326
336
  };
327
337
  }
328
338
  function getECDSAPublicKey(privateKey) {
329
- return bytes.hexlify(secp256k1.getPublicKey(privateKey).subarray(1));
339
+ return bytes.hexlify(secp256k1.getPublicKey(privateKey.replace("0x", "")).subarray(1));
330
340
  }
331
341
  var logger2 = getLogger();
332
342
  async function sleep(timeout) {
@@ -334,30 +344,30 @@ async function sleep(timeout) {
334
344
  }
335
345
  function getProjectPackageManager(cwd) {
336
346
  const yarn = findUp.sync("yarn.lock", { cwd });
337
- if (yarn)
347
+ if (yarn !== void 0)
338
348
  return "yarn";
339
349
  const npm = findUp.sync("package-lock.json", { cwd });
340
- if (npm)
350
+ if (npm !== void 0)
341
351
  return "npm";
342
352
  const pnpm = findUp.sync("pnpm-lock.yaml", { cwd });
343
- if (pnpm)
353
+ if (pnpm !== void 0)
344
354
  return "pnpm";
345
355
  throw new Error("Cannot find package.json or yarn.lock");
346
356
  }
347
357
  function getProjectRootDir(cwd) {
348
358
  const yarn = findUp.sync("yarn.lock", { cwd });
349
- if (yarn)
359
+ if (yarn !== void 0)
350
360
  return path__default.default.dirname(yarn);
351
361
  const npm = findUp.sync("package-lock.json", { cwd });
352
- if (npm)
362
+ if (npm !== void 0)
353
363
  return path__default.default.dirname(npm);
354
364
  const pnpm = findUp.sync("pnpm-lock.yaml", { cwd });
355
- if (pnpm)
365
+ if (pnpm !== void 0)
356
366
  return path__default.default.dirname(pnpm);
357
367
  throw new Error("Cannot find yarn.lock or package-lock.json or pnpm-lock.yaml");
358
368
  }
359
369
  async function isHttpServiceReachable(host, port, timeout, path2) {
360
- return new Promise((resolve, reject) => {
370
+ return new Promise((resolve, _reject) => {
361
371
  const options = {
362
372
  host,
363
373
  port,
@@ -365,10 +375,10 @@ async function isHttpServiceReachable(host, port, timeout, path2) {
365
375
  path: path2,
366
376
  method: "HEAD"
367
377
  };
368
- const request = http__default.default.request(options, (response) => {
378
+ const request = http__default.default.request(options, (_response) => {
369
379
  resolve(true);
370
380
  });
371
- request.on("error", (err) => {
381
+ request.on("error", (_err) => {
372
382
  resolve(false);
373
383
  });
374
384
  request.end();
@@ -376,7 +386,7 @@ async function isHttpServiceReachable(host, port, timeout, path2) {
376
386
  }
377
387
  function extractUrlInfo(url) {
378
388
  const m = url.match(/(?<schema>http|https):\/\/(?<host>.*):(?<port>\d+)/);
379
- if (!m || !m.groups || !m.groups.host || !m.groups.schema || !m.groups.port) {
389
+ if (m?.groups?.host === void 0) {
380
390
  throw new Error(`Invalid url ${url}`);
381
391
  }
382
392
  return {
@@ -392,16 +402,16 @@ var CmdExecutor = class {
392
402
  }
393
403
  async executeCmd(command, args, options, verbose = false, runningCheck, logger3) {
394
404
  if (logger3) {
395
- logger3.info(`Running command: ${command} ${args?.join(" ") ?? ""}`);
405
+ logger3.info(`Running command: ${command} ${args.join(" ")}`);
396
406
  } else {
397
- console.log(`Running command: ${command} ${args?.join(" ") ?? ""}`);
407
+ console.log(`Running command: ${command} ${args.join(" ")}`);
398
408
  }
399
409
  return new Promise((resolve, reject) => {
400
410
  let notified = false;
401
411
  this.currentProcess = child_process.spawn(command, args, options);
402
- if (!this.currentProcess) {
403
- throw new Error(`Failed to spawn command: ${command} ${args?.join(" ") ?? ""}`);
404
- }
412
+ this.currentProcess.on("error", (error) => {
413
+ throw new Error(`Failed to execute command: ${command} ${args.join(" ")} - ${error.message}`);
414
+ });
405
415
  this.currentProcess.stdout?.on("data", (data) => {
406
416
  if (runningCheck && !notified && data.toString().includes(runningCheck.key)) {
407
417
  runningCheck.runningNotify(true);
@@ -421,25 +431,27 @@ var CmdExecutor = class {
421
431
  }
422
432
  });
423
433
  this.currentProcess.on("exit", (code) => {
424
- if (code && code !== 0) {
434
+ if (code !== 0) {
425
435
  if (logger3) {
426
436
  logger3.info(`Command ${command} exited with code ${code}.`);
427
437
  } else {
428
438
  console.info(`Command ${command} exited with code ${code}.`);
429
439
  }
430
- reject({ command: `${command} ${args.join(" ")}` });
440
+ reject(new Error(`${command} ${args.join(" ")}`));
431
441
  return;
432
442
  }
433
443
  resolve();
434
444
  });
435
445
  });
436
446
  }
437
- async interrupt(killDescendents = true) {
447
+ async interrupt(killDescendants = true) {
438
448
  if (this.currentProcess) {
439
449
  logger2.info("Killing process: %s", this.currentProcess.pid);
440
- if (killDescendents) {
441
- kill__default.default(this.currentProcess.pid);
442
- await sleep(2e3);
450
+ if (killDescendants) {
451
+ if (this.currentProcess.pid !== void 0) {
452
+ kill__default.default(this.currentProcess.pid);
453
+ await sleep(2e3);
454
+ }
443
455
  } else {
444
456
  this.currentProcess.kill();
445
457
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/account.ts","../src/logger.ts","../src/deployment.ts","../src/path.ts","../src/promise.ts","../src/array.ts","../src/format.ts","../src/ecdsa.ts"],"names":["path","format","createLogger","logger","ethers","dirname","getStackTrace","bytesToHex"],"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,M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,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'\nexport * from './promise'\nexport * from './types'\nexport * from './array'\nexport * from './format'\nexport * from './ecdsa'\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): 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) 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): 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 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 || !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 async 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): Promise<void> {\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(): 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: any, value: any) => any {\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): 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 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): string {\n const match = path.match(/(.*)([\\\\/][^\\\\/]+)[/\\\\]?$/)\n const [, basePath] = match || []\n const dirname = 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 && 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): 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","// 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[]> =>\n await 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 await 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 * A function to convert Uint8Array to hex string\n * @param bytes Uint8Array\n * @returns hex string\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('hex')\n}\n\n/**\n * A function to convert hex string to Uint8Array\n * @param hex hex string\n * @returns Uint8Array\n */\nexport function hexToBytes(hex: string): Uint8Array {\n const value = hex.replace(/^0x/i, '')\n const len = value.length + 1 - ((value.length + 1) % 2)\n return Uint8Array.from(Buffer.from(value.padStart(len, '0'), '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(/^0[xX]/, '')\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): string {\n return hex.startsWith('0x') || hex.startsWith('0X') ? hex : `0x${hex}`\n}\n\n/**\n * A function to check if a string is a hex string\n * @param value\n * @returns\n */\nexport function isHexString(value: string): boolean {\n return /^(0x)?[0-9a-fA-F]+$/.test(value)\n}\n","import { hexlify } from '@ethersproject/bytes'\nimport { getPublicKey, sign } from '@noble/secp256k1'\n\nexport { recoverPublicKey } from '@noble/secp256k1'\n\nexport async function signWithECDSA(\n data: Buffer,\n privateKey: string\n): Promise<{ signature: Uint8Array; recoveryId: number }> {\n const [signature, recoveryId] = await sign(data, privateKey, {\n canonical: true,\n recovered: true,\n der: false,\n })\n return {\n signature,\n recoveryId,\n }\n}\n\nexport function getECDSAPublicKey(privateKey: string): string {\n // remove the compression byte\n return hexlify(getPublicKey(privateKey).subarray(1))\n}\n"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/account.ts","../src/logger.ts","../src/deployment.ts","../src/path.ts","../src/promise.ts","../src/array.ts","../src/format.ts","../src/ecdsa.ts"],"names":["path","format","createLogger","logger","ethers","dirname","getStackTrace","bytesToHex"],"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,K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I,GAAG;AAAA,UAC/D;AACA,iBAAO,IAAI,MAAM,GAAG,OAAO,IAAI,KAAK,KAAK,GAAG,CAAC,EAAE,CAAC;AAChD;AAAA,QACJ;AACA,gBAAQ;AAAA,MACZ,CAAC;AAAA,IACL,CAAC;AAAA,EACL;AAAA,EAEA,MAAa,UAAU,kBAAkB,MAAqB;AAC1D,QAAI,KAAK,gBAAgB;AACrB,MAAAA,QAAO,KAAK,uBAAuB,KAAK,eAAe,GAAG;AAC1D,UAAI,iBAAiB;AACjB,YAAI,KAAK,eAAe,QAAQ,QAAW;AACvC,eAAK,KAAK,eAAe,GAAG;AAE5B,gBAAM,MAAM,GAAI;AAAA,QACpB;AAAA,MACJ,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'\nexport * from './promise'\nexport * from './types'\nexport * from './array'\nexport * from './format'\nexport * from './ecdsa'\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): 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\nexport class CmdExecutor {\n private currentProcess: ChildProcess | null = null\n\n private onFinish: Promise<void> | null = null\n\n public async 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\n this.currentProcess.on('error', (error) => {\n throw new Error(`Failed to execute command: ${command} ${args.join(' ')} - ${error.message}`)\n })\n\n // Listen for standard output from the child process and print it to the console\n this.currentProcess.stdout?.on('data', (data: Buffer | string) => {\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: Buffer | string) => {\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: number) => {\n if (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(new Error(`${command} ${args.join(' ')}`))\n return\n }\n resolve()\n })\n })\n }\n\n public async interrupt(killDescendants = true): Promise<void> {\n if (this.currentProcess) {\n logger.info('Killing process: %s', this.currentProcess.pid)\n if (killDescendants) {\n if (this.currentProcess.pid !== undefined) {\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 }\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 | 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 * @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 == 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","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","// 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 * A function to convert Uint8Array to hex string\n * @param bytes Uint8Array\n * @returns hex string\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('hex')\n}\n\n/**\n * A function to convert hex string to Uint8Array\n * @param hex hex string\n * @returns Uint8Array\n */\nexport function hexToBytes(hex: string): Uint8Array {\n const value = hex.replace(/^0x/i, '')\n const len = value.length + 1 - ((value.length + 1) % 2)\n return Uint8Array.from(Buffer.from(value.padStart(len, '0'), '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(/^0[xX]/, '')\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): string {\n return hex.startsWith('0x') || hex.startsWith('0X') ? hex : `0x${hex}`\n}\n\n/**\n * A function to check if a string is a hex string\n * @param value\n * @returns\n */\nexport function isHexString(value: string): boolean {\n return /^(0x)?[0-9a-fA-F]+$/.test(value)\n}\n","import { hexlify } from '@ethersproject/bytes'\nimport { getPublicKey, sign } from '@noble/secp256k1'\n\nexport { recoverPublicKey } from '@noble/secp256k1'\n\nexport async function signWithECDSA(\n data: Buffer,\n privateKey: string\n): Promise<{ signature: Uint8Array; recoveryId: number }> {\n const [signature, recoveryId] = await sign(data, privateKey.replace('0x', ''), {\n canonical: true,\n recovered: true,\n der: false,\n })\n return {\n signature,\n recoveryId,\n }\n}\n\nexport function getECDSAPublicKey(privateKey: string): string {\n // remove the compression byte\n return hexlify(getPublicKey(privateKey.replace('0x', '')).subarray(1))\n}\n"]}
package/dist/index.d.mts CHANGED
@@ -17,7 +17,7 @@ declare function getAptosAccountFromMnemonic(mnemonic: string, path?: string): A
17
17
  declare function getSolanaAccountFromMnemonic(mnemonic: string, path?: string): AccountMnemonic;
18
18
  declare function getKeypairFromMnemonic(chainType: ChainType, mnemonic: string, path?: string): AccountMnemonic;
19
19
 
20
- declare function getCircularReplacer(): (key: any, value: any) => any;
20
+ declare function getCircularReplacer(): (key: string, value: unknown) => unknown;
21
21
  declare function initLogger(level: string): void;
22
22
  declare function createLogger(level: string): Logger;
23
23
  declare function getLogger(): Logger;
@@ -208,7 +208,7 @@ declare class CmdExecutor {
208
208
  key: string;
209
209
  runningNotify: (running: boolean) => void;
210
210
  }, logger?: Logger): Promise<void>;
211
- interrupt(killDescendents?: boolean): Promise<void>;
211
+ interrupt(killDescendants?: boolean): Promise<void>;
212
212
  }
213
213
 
214
214
  export { type AccountMnemonic, type AtLeast, CmdExecutor, type Deployment, type Factory, type NonPromise, type RequireAtLeastOne, type RequiredOnly, bytesToHex, createLogger, deploymentToEvmContract, dirname, ensure0x, extractUrlInfo, findDeployment, first, firstFactory, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getECDSAPublicKey, getEvmAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, hexToBytes, initLogger, isHexString, isHttpServiceReachable, logger, parallel, pkgroot, safeMap, sequence, signWithECDSA, sleep, trim0x };
package/dist/index.d.ts CHANGED
@@ -17,7 +17,7 @@ declare function getAptosAccountFromMnemonic(mnemonic: string, path?: string): A
17
17
  declare function getSolanaAccountFromMnemonic(mnemonic: string, path?: string): AccountMnemonic;
18
18
  declare function getKeypairFromMnemonic(chainType: ChainType, mnemonic: string, path?: string): AccountMnemonic;
19
19
 
20
- declare function getCircularReplacer(): (key: any, value: any) => any;
20
+ declare function getCircularReplacer(): (key: string, value: unknown) => unknown;
21
21
  declare function initLogger(level: string): void;
22
22
  declare function createLogger(level: string): Logger;
23
23
  declare function getLogger(): Logger;
@@ -208,7 +208,7 @@ declare class CmdExecutor {
208
208
  key: string;
209
209
  runningNotify: (running: boolean) => void;
210
210
  }, logger?: Logger): Promise<void>;
211
- interrupt(killDescendents?: boolean): Promise<void>;
211
+ interrupt(killDescendants?: boolean): Promise<void>;
212
212
  }
213
213
 
214
214
  export { type AccountMnemonic, type AtLeast, CmdExecutor, type Deployment, type Factory, type NonPromise, type RequireAtLeastOne, type RequiredOnly, bytesToHex, createLogger, deploymentToEvmContract, dirname, ensure0x, extractUrlInfo, findDeployment, first, firstFactory, getAptosAccountFromMnemonic, getBIP044Path, getCircularReplacer, getECDSAPublicKey, getEvmAccountFromMnemonic, getKeypairFromMnemonic, getLogger, getProjectPackageManager, getProjectRootDir, getSolanaAccountFromMnemonic, hexToBytes, initLogger, isHexString, isHttpServiceReachable, logger, parallel, pkgroot, safeMap, sequence, signWithECDSA, sleep, trim0x };
package/dist/index.mjs CHANGED
@@ -79,7 +79,7 @@ function getKeypairFromMnemonic(chainType, mnemonic, path2) {
79
79
  throw new Error(`Unsupported chain: ${chainType}`);
80
80
  }
81
81
  }
82
- var logger;
82
+ var logger = void 0;
83
83
  function getStackTrace() {
84
84
  const oldLimit = Error.stackTraceLimit;
85
85
  Error.stackTraceLimit = Infinity;
@@ -89,7 +89,7 @@ function getStackTrace() {
89
89
  }
90
90
  function getCircularReplacer() {
91
91
  const ancestors = [];
92
- return function(key, value) {
92
+ return function(_key, value) {
93
93
  if (typeof value !== "object" || value === null) {
94
94
  return value;
95
95
  }
@@ -106,7 +106,7 @@ function getCircularReplacer() {
106
106
  function extractCallerInfo(line) {
107
107
  for (const pattern of [/\((.*?:\d+:\d+)\)$/, /at (.*?:\d+:\d+)$/]) {
108
108
  const m = line.match(pattern);
109
- if (m === void 0 || m === null) {
109
+ if (m === null) {
110
110
  continue;
111
111
  }
112
112
  const [, fileInfoLine] = m;
@@ -114,30 +114,32 @@ function extractCallerInfo(line) {
114
114
  }
115
115
  return "<unknown>";
116
116
  }
117
- var logFormat = format.printf((info) => {
118
- if (info.level.toUpperCase() !== "ERROR" && info.level.toUpperCase() !== "WARN") {
119
- return `${info.timestamp} ${info.level.toUpperCase()}: ${info.message}`;
120
- }
121
- const stack = getStackTrace() || "";
122
- const stackLines = stack.split("\n");
123
- const index = stackLines.findIndex((line) => {
124
- return line.match(/create-logger.js/);
125
- }) + 1;
126
- let fileInfo = "<unknown>";
127
- if (stackLines.length > index) {
128
- const line = stackLines[index];
129
- fileInfo = extractCallerInfo(line);
130
- }
131
- const formats = [];
132
- if (fileInfo !== "<unknown>") {
133
- formats.push(fileInfo);
117
+ var logFormat = format.printf(
118
+ (info) => {
119
+ if (info.level.toUpperCase() !== "ERROR" && info.level.toUpperCase() !== "WARN") {
120
+ return `${info.timestamp} ${info.level.toUpperCase()}: ${info.message}`;
121
+ }
122
+ const stack = getStackTrace() ?? "";
123
+ const stackLines = stack.split("\n");
124
+ const index = stackLines.findIndex((line) => {
125
+ return line.match(/create-logger.js/);
126
+ }) + 1;
127
+ let fileInfo = "<unknown>";
128
+ if (stackLines.length > index) {
129
+ const line = stackLines[index];
130
+ fileInfo = extractCallerInfo(line);
131
+ }
132
+ const formats = [];
133
+ if (fileInfo !== "<unknown>") {
134
+ formats.push(fileInfo);
135
+ }
136
+ const { pretty, format: format2 } = info.metadata ?? {};
137
+ const spaces = pretty === true ? 2 : void 0;
138
+ const value = typeof info.message === "string" ? info.message : JSON.stringify(info.message, getCircularReplacer(), spaces);
139
+ const message = format2 !== void 0 ? format2.replace(/%s/g, value) : value;
140
+ return [...formats, message].map((x) => `${info.timestamp} ${info.level.toUpperCase()}: ${x}`).join("\n");
134
141
  }
135
- const spaces = info.metadata?.pretty === true ? 2 : void 0;
136
- const value = typeof info.message === "string" ? info.message : JSON.stringify(info.message, getCircularReplacer(), spaces);
137
- const format2 = info.metadata?.format;
138
- const message = format2 ? format2.replace(/%s/g, value) : value;
139
- return [...formats, message].map((x) => `${info.timestamp} ${info.level.toUpperCase()}: ${x}`).join("\n");
140
- });
142
+ );
141
143
  var loggerFormat = format.combine(
142
144
  format.timestamp({ format: "YY-MM-DD HH:mm:ss" }),
143
145
  format.splat(),
@@ -162,24 +164,28 @@ function createLogger2(level) {
162
164
  }
163
165
  function getLogger() {
164
166
  initLogger(process.env.LZ_LOG ?? "info");
167
+ if (!logger) {
168
+ throw new Error("Logger is not initialized");
169
+ }
165
170
  return logger;
166
171
  }
167
- if (process.env["NODE_ENV"] === "test") ;
172
+ if (process.env.NODE_ENV === "test") ;
168
173
  function findDeployment(deployments, nameOrAddress, options) {
169
174
  return deployments.find((deployment) => {
170
175
  let hasMatchingNameOrAddress = deployment.name === nameOrAddress;
171
176
  if (!hasMatchingNameOrAddress && ethers.utils.isAddress(nameOrAddress)) {
172
177
  hasMatchingNameOrAddress = ethers.utils.getAddress(deployment.address) === ethers.utils.getAddress(nameOrAddress);
173
178
  }
174
- const hasMatchingChain = !options.chain || options.chain === networkToChain(deployment.network);
175
- const hasMatchingNetwork = !options.network || options.network === deployment.network;
176
- const hasMatchingSource = !options.source || options.source === deployment.source;
179
+ const hasMatchingChain = options.chain == null || options.chain === networkToChain(deployment.network);
180
+ const hasMatchingNetwork = options.network === void 0 || options.network === deployment.network;
181
+ const hasMatchingSource = options.source === void 0 || options.source === deployment.source;
177
182
  let hasMatchingEndpoint = true;
178
- if (options.endpointId) {
183
+ if (options.endpointId != null) {
179
184
  const compatibleEndpoints = deployment.compatibleVersions.map((v) => {
180
185
  if (isNetworkEndpointIdSupported(deployment.network, v)) {
181
186
  return networkToEndpointId(deployment.network, v);
182
187
  }
188
+ return void 0;
183
189
  });
184
190
  hasMatchingEndpoint = compatibleEndpoints.includes(options.endpointId);
185
191
  }
@@ -189,7 +195,10 @@ function findDeployment(deployments, nameOrAddress, options) {
189
195
  var contractCache = {};
190
196
  function deploymentToEvmContract(deployment, provider) {
191
197
  const key = `${deployment.network}-${deployment.address}`;
192
- if (!contractCache[key]) {
198
+ if (!(key in contractCache)) {
199
+ if (deployment.abi === void 0 || deployment.bytecode === void 0) {
200
+ throw new Error("Deployment does not have ABI or bytecode");
201
+ }
193
202
  const Contract = new ethers.ContractFactory(deployment.abi, deployment.bytecode);
194
203
  contractCache[key] = Contract.attach(deployment.address);
195
204
  }
@@ -200,8 +209,8 @@ function deploymentToEvmContract(deployment, provider) {
200
209
  }
201
210
  function dirname(path2) {
202
211
  const match = path2.match(/(.*)([\\/][^\\/]+)[/\\]?$/);
203
- const [, basePath] = match || [];
204
- const dirname2 = basePath || path2;
212
+ const [, basePath] = match ?? [];
213
+ const dirname2 = typeof basePath !== "undefined" ? basePath : path2;
205
214
  return dirname2;
206
215
  }
207
216
  function getStackTrace2(stackTraceLimit = Infinity) {
@@ -213,13 +222,14 @@ function getStackTrace2(stackTraceLimit = Infinity) {
213
222
  }
214
223
  function getCaller() {
215
224
  const lines = (getStackTrace2(10) ?? "").split("\n");
216
- if (lines && lines.length > 1 + 1 + 1 + 1) {
225
+ if (lines.length > 1 + 1 + 1 + 1) {
217
226
  const line = lines[4];
218
227
  const m = line.match(/^.*\(([^:]*)[^)]*\)/);
219
228
  if (m) {
220
229
  return m[1];
221
230
  }
222
231
  }
232
+ return void 0;
223
233
  }
224
234
  function pkgroot(packageName, relativeToPath) {
225
235
  if (relativeToPath === void 0) {
@@ -239,7 +249,7 @@ var sequence = async (tasks) => {
239
249
  }
240
250
  return collector;
241
251
  };
242
- var parallel = async (tasks) => await Promise.all(tasks.map(async (task) => task()));
252
+ var parallel = async (tasks) => Promise.all(tasks.map(async (task) => task()));
243
253
  var first = async (tasks) => {
244
254
  assert(tasks.length !== 0, `Must have at least one task for first()`);
245
255
  let lastError;
@@ -252,7 +262,7 @@ var first = async (tasks) => {
252
262
  }
253
263
  throw lastError;
254
264
  };
255
- var firstFactory = (...factories) => async (...input) => await first(factories.map((factory) => async () => factory(...input)));
265
+ var firstFactory = (...factories) => async (...input) => first(factories.map((factory) => async () => factory(...input)));
256
266
 
257
267
  // src/array.ts
258
268
  function safeMap(elements, callbackfn) {
@@ -287,7 +297,7 @@ function isHexString(value) {
287
297
  return /^(0x)?[0-9a-fA-F]+$/.test(value);
288
298
  }
289
299
  async function signWithECDSA(data, privateKey) {
290
- const [signature, recoveryId] = await sign(data, privateKey, {
300
+ const [signature, recoveryId] = await sign(data, privateKey.replace("0x", ""), {
291
301
  canonical: true,
292
302
  recovered: true,
293
303
  der: false
@@ -298,7 +308,7 @@ async function signWithECDSA(data, privateKey) {
298
308
  };
299
309
  }
300
310
  function getECDSAPublicKey(privateKey) {
301
- return hexlify(getPublicKey(privateKey).subarray(1));
311
+ return hexlify(getPublicKey(privateKey.replace("0x", "")).subarray(1));
302
312
  }
303
313
  var logger2 = getLogger();
304
314
  async function sleep(timeout) {
@@ -306,30 +316,30 @@ async function sleep(timeout) {
306
316
  }
307
317
  function getProjectPackageManager(cwd) {
308
318
  const yarn = sync("yarn.lock", { cwd });
309
- if (yarn)
319
+ if (yarn !== void 0)
310
320
  return "yarn";
311
321
  const npm = sync("package-lock.json", { cwd });
312
- if (npm)
322
+ if (npm !== void 0)
313
323
  return "npm";
314
324
  const pnpm = sync("pnpm-lock.yaml", { cwd });
315
- if (pnpm)
325
+ if (pnpm !== void 0)
316
326
  return "pnpm";
317
327
  throw new Error("Cannot find package.json or yarn.lock");
318
328
  }
319
329
  function getProjectRootDir(cwd) {
320
330
  const yarn = sync("yarn.lock", { cwd });
321
- if (yarn)
331
+ if (yarn !== void 0)
322
332
  return path.dirname(yarn);
323
333
  const npm = sync("package-lock.json", { cwd });
324
- if (npm)
334
+ if (npm !== void 0)
325
335
  return path.dirname(npm);
326
336
  const pnpm = sync("pnpm-lock.yaml", { cwd });
327
- if (pnpm)
337
+ if (pnpm !== void 0)
328
338
  return path.dirname(pnpm);
329
339
  throw new Error("Cannot find yarn.lock or package-lock.json or pnpm-lock.yaml");
330
340
  }
331
341
  async function isHttpServiceReachable(host, port, timeout, path2) {
332
- return new Promise((resolve, reject) => {
342
+ return new Promise((resolve, _reject) => {
333
343
  const options = {
334
344
  host,
335
345
  port,
@@ -337,10 +347,10 @@ async function isHttpServiceReachable(host, port, timeout, path2) {
337
347
  path: path2,
338
348
  method: "HEAD"
339
349
  };
340
- const request = http.request(options, (response) => {
350
+ const request = http.request(options, (_response) => {
341
351
  resolve(true);
342
352
  });
343
- request.on("error", (err) => {
353
+ request.on("error", (_err) => {
344
354
  resolve(false);
345
355
  });
346
356
  request.end();
@@ -348,7 +358,7 @@ async function isHttpServiceReachable(host, port, timeout, path2) {
348
358
  }
349
359
  function extractUrlInfo(url) {
350
360
  const m = url.match(/(?<schema>http|https):\/\/(?<host>.*):(?<port>\d+)/);
351
- if (!m || !m.groups || !m.groups.host || !m.groups.schema || !m.groups.port) {
361
+ if (m?.groups?.host === void 0) {
352
362
  throw new Error(`Invalid url ${url}`);
353
363
  }
354
364
  return {
@@ -364,16 +374,16 @@ var CmdExecutor = class {
364
374
  }
365
375
  async executeCmd(command, args, options, verbose = false, runningCheck, logger3) {
366
376
  if (logger3) {
367
- logger3.info(`Running command: ${command} ${args?.join(" ") ?? ""}`);
377
+ logger3.info(`Running command: ${command} ${args.join(" ")}`);
368
378
  } else {
369
- console.log(`Running command: ${command} ${args?.join(" ") ?? ""}`);
379
+ console.log(`Running command: ${command} ${args.join(" ")}`);
370
380
  }
371
381
  return new Promise((resolve, reject) => {
372
382
  let notified = false;
373
383
  this.currentProcess = spawn(command, args, options);
374
- if (!this.currentProcess) {
375
- throw new Error(`Failed to spawn command: ${command} ${args?.join(" ") ?? ""}`);
376
- }
384
+ this.currentProcess.on("error", (error) => {
385
+ throw new Error(`Failed to execute command: ${command} ${args.join(" ")} - ${error.message}`);
386
+ });
377
387
  this.currentProcess.stdout?.on("data", (data) => {
378
388
  if (runningCheck && !notified && data.toString().includes(runningCheck.key)) {
379
389
  runningCheck.runningNotify(true);
@@ -393,25 +403,27 @@ var CmdExecutor = class {
393
403
  }
394
404
  });
395
405
  this.currentProcess.on("exit", (code) => {
396
- if (code && code !== 0) {
406
+ if (code !== 0) {
397
407
  if (logger3) {
398
408
  logger3.info(`Command ${command} exited with code ${code}.`);
399
409
  } else {
400
410
  console.info(`Command ${command} exited with code ${code}.`);
401
411
  }
402
- reject({ command: `${command} ${args.join(" ")}` });
412
+ reject(new Error(`${command} ${args.join(" ")}`));
403
413
  return;
404
414
  }
405
415
  resolve();
406
416
  });
407
417
  });
408
418
  }
409
- async interrupt(killDescendents = true) {
419
+ async interrupt(killDescendants = true) {
410
420
  if (this.currentProcess) {
411
421
  logger2.info("Killing process: %s", this.currentProcess.pid);
412
- if (killDescendents) {
413
- kill(this.currentProcess.pid);
414
- await sleep(2e3);
422
+ if (killDescendants) {
423
+ if (this.currentProcess.pid !== void 0) {
424
+ kill(this.currentProcess.pid);
425
+ await sleep(2e3);
426
+ }
415
427
  } else {
416
428
  this.currentProcess.kill();
417
429
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/account.ts","../src/logger.ts","../src/deployment.ts","../src/path.ts","../src/promise.ts","../src/array.ts","../src/format.ts","../src/ecdsa.ts"],"names":["path","format","createLogger","logger","ethers","dirname","getStackTrace","bytesToHex"],"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;AA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AkB,MAAqB;AAC1D,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'\nexport * from './promise'\nexport * from './types'\nexport * from './array'\nexport * from './format'\nexport * from './ecdsa'\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): 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) 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): 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 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 || !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 async 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): Promise<void> {\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(): 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: any, value: any) => any {\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): 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 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): string {\n const match = path.match(/(.*)([\\\\/][^\\\\/]+)[/\\\\]?$/)\n const [, basePath] = match || []\n const dirname = 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 && 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): 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","// 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[]> =>\n await 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 await 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 * A function to convert Uint8Array to hex string\n * @param bytes Uint8Array\n * @returns hex string\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('hex')\n}\n\n/**\n * A function to convert hex string to Uint8Array\n * @param hex hex string\n * @returns Uint8Array\n */\nexport function hexToBytes(hex: string): Uint8Array {\n const value = hex.replace(/^0x/i, '')\n const len = value.length + 1 - ((value.length + 1) % 2)\n return Uint8Array.from(Buffer.from(value.padStart(len, '0'), '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(/^0[xX]/, '')\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): string {\n return hex.startsWith('0x') || hex.startsWith('0X') ? hex : `0x${hex}`\n}\n\n/**\n * A function to check if a string is a hex string\n * @param value\n * @returns\n */\nexport function isHexString(value: string): boolean {\n return /^(0x)?[0-9a-fA-F]+$/.test(value)\n}\n","import { hexlify } from '@ethersproject/bytes'\nimport { getPublicKey, sign } from '@noble/secp256k1'\n\nexport { recoverPublicKey } from '@noble/secp256k1'\n\nexport async function signWithECDSA(\n data: Buffer,\n privateKey: string\n): Promise<{ signature: Uint8Array; recoveryId: number }> {\n const [signature, recoveryId] = await sign(data, privateKey, {\n canonical: true,\n recovered: true,\n der: false,\n })\n return {\n signature,\n recoveryId,\n }\n}\n\nexport function getECDSAPublicKey(privateKey: string): string {\n // remove the compression byte\n return hexlify(getPublicKey(privateKey).subarray(1))\n}\n"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/account.ts","../src/logger.ts","../src/deployment.ts","../src/path.ts","../src/promise.ts","../src/array.ts","../src/format.ts","../src/ecdsa.ts"],"names":["path","format","createLogger","logger","ethers","dirname","getStackTrace","bytesToHex"],"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,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AQ;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,IAAI,MAAM,GAAG,OAAO,IAAI,KAAK,KAAK,GAAG,CAAC,EAAE,CAAC;AAChD;AAAA,QACJ;AACA,gBAAQ;AAAA,MACZ,CAAC;AAAA,IACL,CAAC;AAAA,EACL;AAAA,EAEA,MAAa,UAAU,kBAAkB,MAAqB;AAC1D,QAAI,KAAK,gBAAgB;AACrB,MAAAA,QAAO,KAAK,uBAAuB,KAAK,eAAe,GAAG;AAC1D,UAAI,iBAAiB;AACjB,YAAI,KAAK,eAAe,QAAQ,QAAW;AACvC,eAAK,KAAK,eAAe,GAAG;AAE5B,gBAAM,MAAM,GAAI;AAAA,QACpB;AAAA,MACJ,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'\nexport * from './promise'\nexport * from './types'\nexport * from './array'\nexport * from './format'\nexport * from './ecdsa'\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): 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\nexport class CmdExecutor {\n private currentProcess: ChildProcess | null = null\n\n private onFinish: Promise<void> | null = null\n\n public async 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\n this.currentProcess.on('error', (error) => {\n throw new Error(`Failed to execute command: ${command} ${args.join(' ')} - ${error.message}`)\n })\n\n // Listen for standard output from the child process and print it to the console\n this.currentProcess.stdout?.on('data', (data: Buffer | string) => {\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: Buffer | string) => {\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: number) => {\n if (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(new Error(`${command} ${args.join(' ')}`))\n return\n }\n resolve()\n })\n })\n }\n\n public async interrupt(killDescendants = true): Promise<void> {\n if (this.currentProcess) {\n logger.info('Killing process: %s', this.currentProcess.pid)\n if (killDescendants) {\n if (this.currentProcess.pid !== undefined) {\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 }\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 | 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 * @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 == 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","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","// 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 * A function to convert Uint8Array to hex string\n * @param bytes Uint8Array\n * @returns hex string\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('hex')\n}\n\n/**\n * A function to convert hex string to Uint8Array\n * @param hex hex string\n * @returns Uint8Array\n */\nexport function hexToBytes(hex: string): Uint8Array {\n const value = hex.replace(/^0x/i, '')\n const len = value.length + 1 - ((value.length + 1) % 2)\n return Uint8Array.from(Buffer.from(value.padStart(len, '0'), '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(/^0[xX]/, '')\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): string {\n return hex.startsWith('0x') || hex.startsWith('0X') ? hex : `0x${hex}`\n}\n\n/**\n * A function to check if a string is a hex string\n * @param value\n * @returns\n */\nexport function isHexString(value: string): boolean {\n return /^(0x)?[0-9a-fA-F]+$/.test(value)\n}\n","import { hexlify } from '@ethersproject/bytes'\nimport { getPublicKey, sign } from '@noble/secp256k1'\n\nexport { recoverPublicKey } from '@noble/secp256k1'\n\nexport async function signWithECDSA(\n data: Buffer,\n privateKey: string\n): Promise<{ signature: Uint8Array; recoveryId: number }> {\n const [signature, recoveryId] = await sign(data, privateKey.replace('0x', ''), {\n canonical: true,\n recovered: true,\n der: false,\n })\n return {\n signature,\n recoveryId,\n }\n}\n\nexport function getECDSAPublicKey(privateKey: string): string {\n // remove the compression byte\n return hexlify(getPublicKey(privateKey.replace('0x', '')).subarray(1))\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@layerzerolabs/lz-utilities",
3
- "version": "2.3.6",
3
+ "version": "2.3.8",
4
4
  "license": "BUSL-1.1",
5
5
  "exports": {
6
6
  "types": "./dist/index.d.ts",
@@ -21,7 +21,7 @@
21
21
  "dependencies": {
22
22
  "@ethersproject/bytes": "^5.7.0",
23
23
  "@ethersproject/providers": "^5.7.0",
24
- "@layerzerolabs/lz-definitions": "^2.3.6",
24
+ "@layerzerolabs/lz-definitions": "^2.3.8",
25
25
  "@noble/hashes": "^1.3.2",
26
26
  "@noble/secp256k1": "^1.7.1",
27
27
  "@solana/web3.js": "^1.91.8",
@@ -36,8 +36,8 @@
36
36
  },
37
37
  "devDependencies": {
38
38
  "@jest/globals": "^29.7.0",
39
- "@layerzerolabs/tsup-config-next": "^2.3.6",
40
- "@layerzerolabs/typescript-config-next": "^2.3.6",
39
+ "@layerzerolabs/tsup-config-next": "^2.3.8",
40
+ "@layerzerolabs/typescript-config-next": "^2.3.8",
41
41
  "@types/glob": "^8.1.0",
42
42
  "@types/jest": "^29.5.10",
43
43
  "@types/node": "^20.10.5",