@layerzerolabs/lz-utilities 2.3.41 → 2.3.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,8 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var http = require('http');
4
- var path = require('path');
5
- var utils = require('@noble/hashes/utils');
4
+ var path2 = require('path');
6
5
  var web3_js = require('@solana/web3.js');
7
6
  var aptos = require('aptos');
8
7
  var bip39 = require('bip39');
@@ -11,8 +10,8 @@ var ethers = require('ethers');
11
10
  var lzDefinitions = require('@layerzerolabs/lz-definitions');
12
11
  var winston = require('winston');
13
12
  var module$1 = require('module');
14
- var assert = require('assert');
15
- var findUp = require('find-up');
13
+ var fs = require('fs');
14
+ var findUp$1 = require('find-up');
16
15
 
17
16
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
18
17
 
@@ -35,14 +34,138 @@ function _interopNamespace(e) {
35
34
  }
36
35
 
37
36
  var http__default = /*#__PURE__*/_interopDefault(http);
38
- var path__default = /*#__PURE__*/_interopDefault(path);
37
+ var path2__namespace = /*#__PURE__*/_interopNamespace(path2);
39
38
  var aptos__namespace = /*#__PURE__*/_interopNamespace(aptos);
40
39
  var bip39__namespace = /*#__PURE__*/_interopNamespace(bip39);
41
40
  var ed25519HdKey__namespace = /*#__PURE__*/_interopNamespace(ed25519HdKey);
42
41
  var winston__namespace = /*#__PURE__*/_interopNamespace(winston);
43
- var assert__default = /*#__PURE__*/_interopDefault(assert);
42
+ var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
44
43
 
45
44
  // src/index.ts
45
+
46
+ // src/pad.ts
47
+ var SizeExceedsPaddingSizeError = class extends Error {
48
+ constructor({ size, targetSize, type }) {
49
+ super(
50
+ `${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size}) exceeds padding size (${targetSize})`
51
+ );
52
+ this.name = "SizeExceedsPaddingSizeError";
53
+ }
54
+ };
55
+ function padify(hexOrBytes, { dir, size = 32 } = {}) {
56
+ if (typeof hexOrBytes === "string") {
57
+ return padHex(hexOrBytes, { dir, size });
58
+ }
59
+ return padBytes(hexOrBytes, { dir, size });
60
+ }
61
+ function padHex(hex, { dir, size = 32 } = {}) {
62
+ if (size === null)
63
+ return hex;
64
+ const value = hex.replace("0x", "");
65
+ if (value.length > size * 2)
66
+ throw new SizeExceedsPaddingSizeError({
67
+ size: Math.ceil(value.length / 2),
68
+ targetSize: size,
69
+ type: "hex"
70
+ });
71
+ return `0x${value[dir === "right" ? "padEnd" : "padStart"](size * 2, "0")}`;
72
+ }
73
+ function padBytes(bytes, { dir, size = 32 } = {}) {
74
+ if (size === null)
75
+ return bytes;
76
+ if (bytes.length > size)
77
+ throw new SizeExceedsPaddingSizeError({
78
+ size: bytes.length,
79
+ targetSize: size,
80
+ type: "bytes"
81
+ });
82
+ const paddedBytes = new Uint8Array(size);
83
+ for (let i = 0; i < size; i++) {
84
+ const padEnd = dir === "right";
85
+ paddedBytes[padEnd ? i : size - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
86
+ }
87
+ return paddedBytes;
88
+ }
89
+
90
+ // src/types.ts
91
+ function isHex(value) {
92
+ return /^(0x)?[0-9A-F]+/i.test(value);
93
+ }
94
+ function isHash(value) {
95
+ return /^(0x)?[0-9A-F]+/i.test(value);
96
+ }
97
+
98
+ // src/format.ts
99
+ function bytesToHex(bytes) {
100
+ return trim0x(hexlify(bytes)).replace(/^0x/i, "");
101
+ }
102
+ function hexToBytes(hex) {
103
+ return arrayify(hex);
104
+ }
105
+ function trim0x(hex) {
106
+ return hex.replace(/^0x/i, "");
107
+ }
108
+ function ensure0x(hex) {
109
+ if (!isHex(hex)) {
110
+ throw new Error("invalid hex string");
111
+ }
112
+ const value = trim0x(hex);
113
+ const retval = `0x${value}`;
114
+ return retval;
115
+ }
116
+ function isHexString(value) {
117
+ return isHex(value);
118
+ }
119
+ function _arrayify(value) {
120
+ if (value instanceof Uint8Array) {
121
+ return value;
122
+ }
123
+ if (typeof value === "string") {
124
+ if (value.match(/^(0x)?[0-9A-F]*$/i)) {
125
+ const hex = value.replace(/^0x/i, "");
126
+ const len = hex.length + 1 - (hex.length + 1) % 2;
127
+ return Uint8Array.from(Buffer.from(hex.padStart(len, "0"), "hex"));
128
+ }
129
+ throw new Error("Invalid hex string");
130
+ }
131
+ if (typeof value === "number") {
132
+ if (value < 0) {
133
+ throw new Error("Number must be non-negative");
134
+ }
135
+ const byteArray = [];
136
+ while (value > 0) {
137
+ byteArray.push(value & 255);
138
+ value >>= 8;
139
+ }
140
+ return new Uint8Array(byteArray.reverse());
141
+ }
142
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(value)) {
143
+ return new Uint8Array(value);
144
+ }
145
+ if (typeof value === "bigint") {
146
+ const hex = value.toString(16);
147
+ return _arrayify(hex);
148
+ }
149
+ throw new Error("unsupported type");
150
+ }
151
+ function arrayify(value, size) {
152
+ const bytes = _arrayify(value);
153
+ if (size === void 0) {
154
+ return bytes;
155
+ }
156
+ return padify(bytes, { size });
157
+ }
158
+ function hexlify(value) {
159
+ if (typeof value === "string" && /^(0x)?[0-9A-F]*$/i.test(value)) {
160
+ const retval = "0x" + trim0x(value);
161
+ return retval;
162
+ }
163
+ const bytes = arrayify(value);
164
+ const hex = Buffer.from(bytes).toString("hex");
165
+ return ensure0x(hex);
166
+ }
167
+
168
+ // src/account.ts
46
169
  function getBIP044Path(chainType, account, change, index) {
47
170
  switch (chainType) {
48
171
  case lzDefinitions.ChainType.EVM:
@@ -55,49 +178,49 @@ function getBIP044Path(chainType, account, change, index) {
55
178
  throw new Error(`Unsupported chain: ${chainType}`);
56
179
  }
57
180
  }
58
- function getEvmAccountFromMnemonic(mnemonic, path2 = "m/44'/60'/0'/0/0") {
59
- const wallet = ethers.ethers.Wallet.fromMnemonic(mnemonic, path2);
181
+ function getEvmAccountFromMnemonic(mnemonic, path3 = "m/44'/60'/0'/0/0") {
182
+ const wallet = ethers.ethers.Wallet.fromMnemonic(mnemonic, path3);
60
183
  return {
61
184
  mnemonic,
62
- path: path2,
185
+ path: path3,
63
186
  privateKey: wallet.privateKey,
64
187
  address: wallet.address
65
188
  };
66
189
  }
67
- function getAptosAccountFromMnemonic(mnemonic, path2 = "m/44'/637'/0'/0'/0'") {
68
- if (!aptos__namespace.AptosAccount.isValidPath(path2)) {
69
- throw new Error(`Invalid derivation path: ${path2}`);
190
+ function getAptosAccountFromMnemonic(mnemonic, path3 = "m/44'/637'/0'/0'/0'") {
191
+ if (!aptos__namespace.AptosAccount.isValidPath(path3)) {
192
+ throw new Error(`Invalid derivation path: ${path3}`);
70
193
  }
71
194
  const normalizeMnemonics = mnemonic.trim().split(/\s+/).map((part) => part.toLowerCase()).join(" ");
72
195
  {
73
- const { key } = aptos__namespace.derivePath(path2, utils.bytesToHex(bip39__namespace.mnemonicToSeedSync(normalizeMnemonics)));
196
+ const { key } = aptos__namespace.derivePath(path3, trim0x(hexlify(bip39__namespace.mnemonicToSeedSync(normalizeMnemonics))));
74
197
  const account = new aptos__namespace.AptosAccount(new Uint8Array(key)).toPrivateKeyObject();
75
198
  return {
76
199
  mnemonic,
77
- path: path2,
200
+ path: path3,
78
201
  privateKey: account.privateKeyHex,
79
202
  address: account.address
80
203
  };
81
204
  }
82
205
  }
83
- function getSolanaAccountFromMnemonic(mnemonic, path2 = "m/44'/501'/0'/0'") {
206
+ function getSolanaAccountFromMnemonic(mnemonic, path3 = "m/44'/501'/0'/0'") {
84
207
  const seed = bip39__namespace.mnemonicToSeedSync(mnemonic, "");
85
- const keyPair = web3_js.Keypair.fromSeed(ed25519HdKey__namespace.derivePath(path2, seed.toString("hex")).key);
208
+ const keyPair = web3_js.Keypair.fromSeed(ed25519HdKey__namespace.derivePath(path3, seed.toString("hex")).key);
86
209
  return {
87
210
  mnemonic,
88
- path: path2,
211
+ path: path3,
89
212
  privateKey: ethers.ethers.utils.hexlify(keyPair.secretKey),
90
213
  address: keyPair.publicKey.toBase58()
91
214
  };
92
215
  }
93
- function getKeypairFromMnemonic(chainType, mnemonic, path2) {
216
+ function getKeypairFromMnemonic(chainType, mnemonic, path3) {
94
217
  switch (chainType) {
95
218
  case lzDefinitions.ChainType.EVM:
96
- return getEvmAccountFromMnemonic(mnemonic, path2);
219
+ return getEvmAccountFromMnemonic(mnemonic, path3);
97
220
  case lzDefinitions.ChainType.APTOS:
98
- return getAptosAccountFromMnemonic(mnemonic, path2);
221
+ return getAptosAccountFromMnemonic(mnemonic, path3);
99
222
  case lzDefinitions.ChainType.SOLANA:
100
- return getSolanaAccountFromMnemonic(mnemonic, path2);
223
+ return getSolanaAccountFromMnemonic(mnemonic, path3);
101
224
  default:
102
225
  throw new Error(`Unsupported chain: ${chainType}`);
103
226
  }
@@ -194,7 +317,7 @@ function getLogger() {
194
317
  }
195
318
  if (process.env.NODE_ENV === "test") ;
196
319
  function findDeployment(deployments, nameOrAddress, options) {
197
- return deployments.find((deployment) => {
320
+ const retval = deployments.find((deployment) => {
198
321
  let hasMatchingNameOrAddress = deployment.name === nameOrAddress;
199
322
  if (!hasMatchingNameOrAddress && ethers.ethers.utils.isAddress(nameOrAddress)) {
200
323
  hasMatchingNameOrAddress = ethers.ethers.utils.getAddress(deployment.address) === ethers.ethers.utils.getAddress(nameOrAddress);
@@ -214,6 +337,10 @@ function findDeployment(deployments, nameOrAddress, options) {
214
337
  }
215
338
  return hasMatchingNameOrAddress && hasMatchingChain && hasMatchingNetwork && hasMatchingEndpoint && hasMatchingSource;
216
339
  });
340
+ if (retval === void 0) {
341
+ throw new Error(`Deployment not found: ${nameOrAddress}`);
342
+ }
343
+ return retval;
217
344
  }
218
345
  var contractCache = {};
219
346
  function deploymentToEvmContract(deployment, provider) {
@@ -230,11 +357,16 @@ function deploymentToEvmContract(deployment, provider) {
230
357
  }
231
358
  return contractCache[key].connect(provider);
232
359
  }
233
- function dirname(path2) {
234
- const match = path2.match(/(.*)([\\/][^\\/]+)[/\\]?$/);
360
+ function findContract(provider, deployments, nameOrAddress, options) {
361
+ const deployment = findDeployment(deployments, nameOrAddress, options);
362
+ const retval = deploymentToEvmContract(deployment, provider);
363
+ return retval;
364
+ }
365
+ function dirname(path3) {
366
+ const match = path3.match(/(.*)([\\/][^\\/]+)[/\\]?$/);
235
367
  const [, basePath] = match ?? [];
236
- const dirname2 = typeof basePath !== "undefined" ? basePath : path2;
237
- return dirname2;
368
+ const dirname3 = typeof basePath !== "undefined" ? basePath : path3;
369
+ return dirname3;
238
370
  }
239
371
  function getStackTrace2(stackTraceLimit = Infinity) {
240
372
  const oldLimit = Error.stackTraceLimit;
@@ -265,6 +397,33 @@ function pkgroot(packageName, relativeToPath) {
265
397
  const packagePath = dirname(filepath);
266
398
  return packagePath.replace(/.yarn\/([^/]*\/)?(__virtual__|\$\$virtual)\/[^/]*\/\d*\//, "");
267
399
  }
400
+
401
+ // src/assert.ts
402
+ function assert(condition, message) {
403
+ if (!condition) {
404
+ throw new Error(`Assertion Error: ${message ?? "condition is false"}`);
405
+ }
406
+ }
407
+ function assertType(value, fn, message) {
408
+ if (!fn(value)) {
409
+ throw new Error(`Expected value to be ${message ?? "of correct type"}`);
410
+ }
411
+ }
412
+ function assertDefined(value, message) {
413
+ if (value === void 0 || value === null) {
414
+ throw new Error(message ?? "Value is undefined or null");
415
+ }
416
+ }
417
+ function asType(value, fn, message) {
418
+ if (!fn(value)) {
419
+ throw new Error(`Expected value to be ${message ?? "of correct type"}`);
420
+ }
421
+ return value;
422
+ }
423
+ function assumeType(value) {
424
+ }
425
+
426
+ // src/promise.ts
268
427
  var sequence = async (tasks) => {
269
428
  const collector = [];
270
429
  for (const task of tasks) {
@@ -274,7 +433,7 @@ var sequence = async (tasks) => {
274
433
  };
275
434
  var parallel = async (tasks) => Promise.all(tasks.map(async (task) => task()));
276
435
  var first = async (tasks) => {
277
- assert__default.default(tasks.length !== 0, `Must have at least one task for first()`);
436
+ assert(tasks.length !== 0, `Must have at least one task for first()`);
278
437
  let lastError;
279
438
  for (const task of tasks) {
280
439
  try {
@@ -301,59 +460,96 @@ function safeMap(elements, callbackfn) {
301
460
  }
302
461
  }
303
462
 
304
- // src/format.ts
305
- function bytesToHex2(bytes) {
306
- return Buffer.from(bytes).toString("hex");
463
+ // src/enum.ts
464
+ function asEnum(enumType, value) {
465
+ const enumValues = Object.values(enumType);
466
+ if (enumValues.includes(value)) {
467
+ return value;
468
+ } else {
469
+ throw new Error(`Invalid enum value: ${value}`);
470
+ }
307
471
  }
308
- function hexToBytes(hex) {
309
- const value = hex.replace(/^0x/i, "");
310
- const len = value.length + 1 - (value.length + 1) % 2;
311
- return Uint8Array.from(Buffer.from(value.padStart(len, "0"), "hex"));
472
+
473
+ // src/generic.ts
474
+ function hasRequiredProperties(obj, paths) {
475
+ return paths.every((path3) => {
476
+ const keys = path3.split(".");
477
+ let current = obj;
478
+ for (const key of keys) {
479
+ if (current !== void 0 && key in current) {
480
+ current = current[key];
481
+ } else {
482
+ return false;
483
+ }
484
+ }
485
+ return true;
486
+ });
312
487
  }
313
- function trim0x(hex) {
314
- return hex.replace(/^0[xX]/, "");
488
+ function findUp(cwd, expectations) {
489
+ let currentDir = cwd;
490
+ while (currentDir !== "/") {
491
+ const dirFiles = fs__namespace.readdirSync(currentDir);
492
+ const foundFiles = dirFiles.filter((file) => expectations.includes(file));
493
+ if (foundFiles.length > 0) {
494
+ return foundFiles.map((file) => path2__namespace.join(currentDir, file));
495
+ }
496
+ currentDir = path2__namespace.dirname(currentDir);
497
+ }
498
+ return [];
315
499
  }
316
- function ensure0x(hex) {
317
- return hex.startsWith("0x") || hex.startsWith("0X") ? hex : `0x${hex}`;
500
+ function enableTS(relativeToPath) {
501
+ const moduleName = "ts-node";
502
+ const require2 = module$1.createRequire(relativeToPath);
503
+ const modulePath = require2.resolve(moduleName);
504
+ const tsnode = require2(modulePath);
505
+ tsnode.register({
506
+ transpileOnly: true,
507
+ typeCheck: false
508
+ });
318
509
  }
319
- function isHexString(value) {
320
- return /^(0x)?[0-9a-fA-F]+$/.test(value);
510
+ function loadJSorTS(fileName, relativeToPath) {
511
+ if (fileName.endsWith(".ts")) {
512
+ enableTS(relativeToPath);
513
+ }
514
+ const require2 = module$1.createRequire(relativeToPath);
515
+ const modulePath = require2.resolve(fileName);
516
+ return require2(modulePath);
321
517
  }
322
518
  var logger2 = getLogger();
323
519
  async function sleep(timeout) {
324
520
  await new Promise((resolve) => setTimeout(resolve, timeout));
325
521
  }
326
522
  function getProjectPackageManager(cwd) {
327
- const yarn = findUp.sync("yarn.lock", { cwd });
523
+ const yarn = findUp$1.sync("yarn.lock", { cwd });
328
524
  if (yarn !== void 0)
329
525
  return "yarn";
330
- const npm = findUp.sync("package-lock.json", { cwd });
526
+ const npm = findUp$1.sync("package-lock.json", { cwd });
331
527
  if (npm !== void 0)
332
528
  return "npm";
333
- const pnpm = findUp.sync("pnpm-lock.yaml", { cwd });
529
+ const pnpm = findUp$1.sync("pnpm-lock.yaml", { cwd });
334
530
  if (pnpm !== void 0)
335
531
  return "pnpm";
336
532
  throw new Error("Cannot find package.json or yarn.lock");
337
533
  }
338
534
  function getProjectRootDir(cwd) {
339
- const yarn = findUp.sync("yarn.lock", { cwd });
535
+ const yarn = findUp$1.sync("yarn.lock", { cwd });
340
536
  if (yarn !== void 0)
341
- return path__default.default.dirname(yarn);
342
- const npm = findUp.sync("package-lock.json", { cwd });
537
+ return path2__namespace.default.dirname(yarn);
538
+ const npm = findUp$1.sync("package-lock.json", { cwd });
343
539
  if (npm !== void 0)
344
- return path__default.default.dirname(npm);
345
- const pnpm = findUp.sync("pnpm-lock.yaml", { cwd });
540
+ return path2__namespace.default.dirname(npm);
541
+ const pnpm = findUp$1.sync("pnpm-lock.yaml", { cwd });
346
542
  if (pnpm !== void 0)
347
- return path__default.default.dirname(pnpm);
543
+ return path2__namespace.default.dirname(pnpm);
348
544
  throw new Error("Cannot find yarn.lock or package-lock.json or pnpm-lock.yaml");
349
545
  }
350
- async function isHttpServiceReachable(host, port, timeout, path2) {
546
+ async function isHttpServiceReachable(host, port, timeout, path3) {
351
547
  return new Promise((resolve, _reject) => {
352
548
  const options = {
353
549
  host,
354
550
  port,
355
551
  timeout,
356
- path: path2,
552
+ path: path3,
357
553
  method: "HEAD"
358
554
  };
359
555
  const request = http__default.default.request(options, (_response) => {
@@ -381,13 +577,24 @@ Object.defineProperty(exports, "Logger", {
381
577
  enumerable: true,
382
578
  get: function () { return winston.Logger; }
383
579
  });
384
- exports.bytesToHex = bytesToHex2;
580
+ exports.SizeExceedsPaddingSizeError = SizeExceedsPaddingSizeError;
581
+ exports.arrayify = arrayify;
582
+ exports.asEnum = asEnum;
583
+ exports.asType = asType;
584
+ exports.assert = assert;
585
+ exports.assertDefined = assertDefined;
586
+ exports.assertType = assertType;
587
+ exports.assumeType = assumeType;
588
+ exports.bytesToHex = bytesToHex;
385
589
  exports.createLogger = createLogger2;
386
590
  exports.deploymentToEvmContract = deploymentToEvmContract;
387
591
  exports.dirname = dirname;
592
+ exports.enableTS = enableTS;
388
593
  exports.ensure0x = ensure0x;
389
594
  exports.extractUrlInfo = extractUrlInfo;
595
+ exports.findContract = findContract;
390
596
  exports.findDeployment = findDeployment;
597
+ exports.findUp = findUp;
391
598
  exports.first = first;
392
599
  exports.firstFactory = firstFactory;
393
600
  exports.getAptosAccountFromMnemonic = getAptosAccountFromMnemonic;
@@ -399,11 +606,17 @@ exports.getLogger = getLogger;
399
606
  exports.getProjectPackageManager = getProjectPackageManager;
400
607
  exports.getProjectRootDir = getProjectRootDir;
401
608
  exports.getSolanaAccountFromMnemonic = getSolanaAccountFromMnemonic;
609
+ exports.hasRequiredProperties = hasRequiredProperties;
402
610
  exports.hexToBytes = hexToBytes;
611
+ exports.hexlify = hexlify;
403
612
  exports.initLogger = initLogger;
613
+ exports.isHash = isHash;
614
+ exports.isHex = isHex;
404
615
  exports.isHexString = isHexString;
405
616
  exports.isHttpServiceReachable = isHttpServiceReachable;
617
+ exports.loadJSorTS = loadJSorTS;
406
618
  exports.logger = logger2;
619
+ exports.padify = padify;
407
620
  exports.parallel = parallel;
408
621
  exports.pkgroot = pkgroot;
409
622
  exports.safeMap = safeMap;